• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 listening = false;
31   static bool client_connected = false;
32   static std::mutex socket_open_lock;
33   static stream::ServerSocket server_socket;
34   static stream::SocketStream socket_stream;
35   std::lock_guard guard(socket_open_lock);
36   if (!listening) {
37     std::printf("Awaiting connection on port %d\n", static_cast<int>(kPort));
38     PW_CHECK_OK(server_socket.Listen(kPort));
39     listening = true;
40   }
41   if (client_connected && !socket_stream.IsReady()) {
42     client_connected = false;
43     std::printf("Client disconnected\n");
44   }
45   if (!client_connected) {
46     auto accept_result = server_socket.Accept();
47     PW_CHECK_OK(accept_result.status());
48     socket_stream = *std::move(accept_result);
49     client_connected = true;
50     std::printf("Client connected\n");
51   }
52   return socket_stream;
53 }
54 
55 }  // namespace
56 
GetReader()57 stream::Reader& GetReader() { return GetStream(); }
GetWriter()58 stream::Writer& GetWriter() { return GetStream(); }
59 
60 }  // namespace pw::system
61