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