• 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 
17 #include "pw_hdlc/rpc_channel.h"
18 #include "pw_hdlc/rpc_packets.h"
19 #include "pw_log/log.h"
20 #include "pw_rpc_system_server/rpc_server.h"
21 #include "pw_stream/sys_io_stream.h"
22 
23 namespace pw::rpc::system_server {
24 namespace {
25 
26 constexpr size_t kMaxTransmissionUnit = 256;
27 
28 // Used to write HDLC data to pw::sys_io.
29 stream::SysIoWriter writer;
30 stream::SysIoReader reader;
31 
32 // Set up the output channel for the pw_rpc server to use.
33 hdlc::RpcChannelOutput hdlc_channel_output(writer,
34                                            pw::hdlc::kDefaultRpcAddress,
35                                            "HDLC channel");
36 Channel channels[] = {pw::rpc::Channel::Create<1>(&hdlc_channel_output)};
37 rpc::Server server(channels);
38 
39 }  // namespace
40 
Init()41 void Init() {
42   // Send log messages to HDLC address 1. This prevents logs from interfering
43   // with pw_rpc communications.
44   pw::log_basic::SetOutput([](std::string_view log) {
45     pw::hdlc::WriteUIFrame(1, std::as_bytes(std::span(log)), writer);
46   });
47 }
48 
Server()49 rpc::Server& Server() { return server; }
50 
Start()51 Status Start() {
52   // Declare a buffer for decoding incoming HDLC frames.
53   std::array<std::byte, kMaxTransmissionUnit> input_buffer;
54   hdlc::Decoder decoder(input_buffer);
55 
56   while (true) {
57     std::byte byte;
58     Status ret_val = pw::sys_io::ReadByte(&byte);
59     if (!ret_val.ok()) {
60       return ret_val;
61     }
62     if (auto result = decoder.Process(byte); result.ok()) {
63       hdlc::Frame& frame = result.value();
64       if (frame.address() == hdlc::kDefaultRpcAddress) {
65         server.ProcessPacket(frame.data(), hdlc_channel_output);
66       }
67     }
68   }
69 }
70 
71 }  // namespace pw::rpc::system_server
72