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