4f0e401a6c2ea0868c977b5f44002445783f3db8
[platform/upstream/connectedhomeip.git] / third_party / pigweed / repo / pw_hdlc_lite / public / pw_hdlc_lite / rpc_channel.h
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 #pragma once
15
16 #include <array>
17 #include <span>
18
19 #include "pw_hdlc_lite/encoder.h"
20 #include "pw_rpc/channel.h"
21 #include "pw_stream/stream.h"
22
23 namespace pw::hdlc_lite {
24
25 // Custom HDLC ChannelOutput class to write and read data through serial using
26 // the HDLC-Lite protocol.
27 class RpcChannelOutput : public rpc::ChannelOutput {
28  public:
29   // The RpcChannelOutput class does not own the buffer it uses to store the
30   // protobuf bytes. This buffer is specified at the time of creation along with
31   // a writer object to which will be used to write and send the bytes.
32   constexpr RpcChannelOutput(stream::Writer& writer,
33                              std::span<std::byte> buffer,
34                              uint8_t address,
35                              const char* channel_name)
36       : ChannelOutput(channel_name),
37         writer_(writer),
38         buffer_(buffer),
39         address_(address) {}
40
41   std::span<std::byte> AcquireBuffer() override { return buffer_; }
42
43   Status SendAndReleaseBuffer(size_t size) override {
44     return hdlc_lite::WriteInformationFrame(
45         address_, buffer_.first(size), writer_);
46   }
47
48  private:
49   stream::Writer& writer_;
50   const std::span<std::byte> buffer_;
51   const uint8_t address_;
52 };
53
54 // RpcChannelOutput with its own buffer.
55 template <size_t buffer_size>
56 class RpcChannelOutputBuffer : public rpc::ChannelOutput {
57  public:
58   constexpr RpcChannelOutputBuffer(stream::Writer& writer,
59                                    uint8_t address,
60                                    const char* channel_name)
61       : ChannelOutput(channel_name), writer_(writer), address_(address) {}
62
63   std::span<std::byte> AcquireBuffer() override { return buffer_; }
64
65   Status SendAndReleaseBuffer(size_t size) override {
66     return hdlc_lite::WriteInformationFrame(
67         address_, std::span(buffer_.data(), size), writer_);
68   }
69
70  private:
71   stream::Writer& writer_;
72   std::array<std::byte, buffer_size> buffer_;
73   const uint8_t address_;
74 };
75
76 }  // namespace pw::hdlc_lite