• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2020 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 <cstddef>
16 #include <cstdint>
17 #include <cstdio>
18 
19 #include "pw_assert/check.h"
20 #include "pw_hdlc/rpc_channel.h"
21 #include "pw_hdlc/rpc_packets.h"
22 #include "pw_log/log.h"
23 #include "pw_rpc_system_server/rpc_server.h"
24 #include "pw_stream/socket_stream.h"
25 
26 namespace pw::rpc::system_server {
27 namespace {
28 
29 constexpr size_t kMaxTransmissionUnit = 512;
30 uint16_t socket_port = 33000;
31 
32 stream::SocketStream socket_stream;
33 
34 hdlc::RpcChannelOutput hdlc_channel_output(socket_stream,
35                                            hdlc::kDefaultRpcAddress,
36                                            "HDLC channel");
37 Channel channels[] = {rpc::Channel::Create<1>(&hdlc_channel_output)};
38 rpc::Server server(channels);
39 
40 }  // namespace
41 
set_socket_port(uint16_t new_socket_port)42 void set_socket_port(uint16_t new_socket_port) {
43   socket_port = new_socket_port;
44 }
45 
Init()46 void Init() {
47   log_basic::SetOutput([](std::string_view log) {
48     std::fprintf(stderr, "%.*s\n", static_cast<int>(log.size()), log.data());
49     hdlc::WriteUIFrame(1, std::as_bytes(std::span(log)), socket_stream)
50         .IgnoreError();  // TODO(pwbug/387): Handle Status properly
51   });
52 
53   PW_LOG_INFO("Starting pw_rpc server on port %d", socket_port);
54   PW_CHECK_OK(socket_stream.Serve(socket_port));
55 }
56 
Server()57 rpc::Server& Server() { return server; }
58 
Start()59 Status Start() {
60   // Declare a buffer for decoding incoming HDLC frames.
61   std::array<std::byte, kMaxTransmissionUnit> input_buffer;
62   hdlc::Decoder decoder(input_buffer);
63 
64   while (true) {
65     std::array<std::byte, kMaxTransmissionUnit> data;
66     auto ret_val = socket_stream.Read(data);
67     if (ret_val.ok()) {
68       for (std::byte byte : ret_val.value()) {
69         if (auto result = decoder.Process(byte); result.ok()) {
70           hdlc::Frame& frame = result.value();
71           if (frame.address() == hdlc::kDefaultRpcAddress) {
72             server.ProcessPacket(frame.data(), hdlc_channel_output)
73                 .IgnoreError();  // TODO(pwbug/387): Handle Status properly
74           }
75         }
76       }
77     }
78   }
79 }
80 
81 }  // namespace pw::rpc::system_server
82