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