319ee1bca180ac30ffec6e7d49308e782a30c29f
[platform/upstream/connectedhomeip.git] / third_party / pigweed / repo / pw_hdlc_lite / rpc_example / hdlc_rpc_server.cc
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 <array>
16 #include <span>
17 #include <string_view>
18
19 #include "pw_hdlc_lite/encoder.h"
20 #include "pw_hdlc_lite/rpc_channel.h"
21 #include "pw_hdlc_lite/rpc_packets.h"
22 #include "pw_hdlc_lite/sys_io_stream.h"
23 #include "pw_log/log.h"
24 #include "pw_rpc/echo_service_nanopb.h"
25 #include "pw_rpc/server.h"
26
27 namespace hdlc_example {
28 namespace {
29
30 using std::byte;
31
32 constexpr size_t kMaxTransmissionUnit = 256;
33
34 // Used to write HDLC data to pw::sys_io.
35 pw::stream::SysIoWriter writer;
36
37 // Set up the output channel for the pw_rpc server to use to use.
38 pw::hdlc_lite::RpcChannelOutputBuffer<kMaxTransmissionUnit> hdlc_channel_output(
39     writer, pw::hdlc_lite::kDefaultRpcAddress, "HDLC channel");
40
41 pw::rpc::Channel channels[] = {
42     pw::rpc::Channel::Create<1>(&hdlc_channel_output)};
43
44 // Declare the pw_rpc server with the HDLC channel.
45 pw::rpc::Server server(channels);
46
47 pw::rpc::EchoService echo_service;
48
49 void RegisterServices() { server.RegisterService(echo_service); }
50
51 }  // namespace
52
53 void Start() {
54   // Send log messages to HDLC address 1. This prevents logs from interfering
55   // with pw_rpc communications.
56   pw::log_basic::SetOutput([](std::string_view log) {
57     pw::hdlc_lite::WriteInformationFrame(
58         1, std::as_bytes(std::span(log)), writer);
59   });
60
61   // Set up the server and start processing data.
62   RegisterServices();
63
64   // Declare a buffer for decoding incoming HDLC frames.
65   std::array<std::byte, kMaxTransmissionUnit> input_buffer;
66
67   PW_LOG_INFO("Starting pw_rpc server");
68   pw::hdlc_lite::ReadAndProcessPackets(
69       server, hdlc_channel_output, input_buffer);
70 }
71
72 }  // namespace hdlc_example