xref: /aosp_15_r20/external/pigweed/pw_system/socket_target_io.cc (revision 61c4878ac05f98d0ceed94b57d316916de578985)
1 // Copyright 2022 The Pigweed Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
5 // the License at
6 //
7 //     https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
13 // the License.
14 
15 #include <cstdio>
16 #include <mutex>
17 
18 #include "pw_assert/check.h"
19 #include "pw_stream/socket_stream.h"
20 #include "pw_stream/stream.h"
21 #include "pw_system/config.h"
22 #include "pw_system/io.h"
23 
24 namespace pw::system {
25 namespace {
26 
27 constexpr uint16_t kPort = PW_SYSTEM_SOCKET_IO_PORT;
28 
GetStream()29 stream::SocketStream& GetStream() {
30   static bool running = false;
31   static std::mutex socket_open_lock;
32   static stream::ServerSocket server_socket;
33   static stream::SocketStream socket_stream;
34   std::lock_guard guard(socket_open_lock);
35   if (!running) {
36     printf("Awaiting connection on port %d\n", static_cast<int>(kPort));
37     PW_CHECK_OK(server_socket.Listen(kPort));
38     auto accept_result = server_socket.Accept();
39     PW_CHECK_OK(accept_result.status());
40     socket_stream = *std::move(accept_result);
41     printf("Client connected\n");
42     running = true;
43   }
44   return socket_stream;
45 }
46 
47 }  // namespace
48 
GetReader()49 stream::Reader& GetReader() { return GetStream(); }
GetWriter()50 stream::Writer& GetWriter() { return GetStream(); }
51 
52 }  // namespace pw::system
53