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