• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 // clang-format off
16 #include "pw_rpc/internal/log_config.h"  // PW_LOG_* macros must be first.
17 
18 #include "pw_rpc/internal/channel.h"
19 // clang-format on
20 
21 #include "pw_bytes/span.h"
22 #include "pw_log/log.h"
23 #include "pw_protobuf/decoder.h"
24 #include "pw_rpc/internal/config.h"
25 
26 namespace pw::rpc {
27 namespace {
28 
29 // TODO(pwbug/615): Dynamically allocate this buffer if
30 //     PW_RPC_DYNAMIC_ALLOCATION is enabled.
31 std::array<std::byte, cfg::kEncodingBufferSizeBytes> encoding_buffer
32     PW_GUARDED_BY(internal::rpc_lock());
33 
34 }  // namespace
35 
ExtractChannelId(ConstByteSpan packet)36 Result<uint32_t> ExtractChannelId(ConstByteSpan packet) {
37   protobuf::Decoder decoder(packet);
38 
39   while (decoder.Next().ok()) {
40     switch (static_cast<internal::RpcPacket::Fields>(decoder.FieldNumber())) {
41       case internal::RpcPacket::Fields::CHANNEL_ID: {
42         uint32_t channel_id;
43         PW_TRY(decoder.ReadUint32(&channel_id));
44         return channel_id;
45       }
46 
47       default:
48         continue;
49     }
50   }
51 
52   return Status::DataLoss();
53 }
54 
55 namespace internal {
56 
GetPayloadBuffer()57 ByteSpan GetPayloadBuffer() PW_EXCLUSIVE_LOCKS_REQUIRED(rpc_lock()) {
58   return ByteSpan(encoding_buffer)
59       .subspan(Packet::kMinEncodedSizeWithoutPayload);
60 }
61 
Send(const Packet & packet)62 Status Channel::Send(const Packet& packet) {
63   Result encoded = packet.Encode(encoding_buffer);
64 
65   if (!encoded.ok()) {
66     PW_LOG_ERROR(
67         "Failed to encode RPC packet type %u to channel %u buffer, status %u",
68         static_cast<unsigned>(packet.type()),
69         static_cast<unsigned>(id()),
70         encoded.status().code());
71     return Status::Internal();
72   }
73 
74   Status sent = output().Send(encoded.value());
75 
76   if (!sent.ok()) {
77     PW_LOG_DEBUG("Channel %u failed to send packet with status %u",
78                  static_cast<unsigned>(id()),
79                  sent.code());
80 
81     return Status::Unknown();
82   }
83   return OkStatus();
84 }
85 
86 }  // namespace internal
87 }  // namespace pw::rpc
88