aboutsummaryrefslogtreecommitdiff
path: root/pw_rpc/channel.cc
blob: ea74168ccf64f3241122801acf6d94b3770b3f32 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
// Copyright 2020 The Pigweed Authors
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.

// clang-format off
#include "pw_rpc/internal/log_config.h"  // PW_LOG_* macros must be first.

#include "pw_rpc/internal/channel.h"
// clang-format on

#include "pw_bytes/span.h"
#include "pw_log/log.h"
#include "pw_protobuf/decoder.h"
#include "pw_rpc/internal/config.h"

namespace pw::rpc {
namespace {

// TODO(pwbug/615): Dynamically allocate this buffer if
//     PW_RPC_DYNAMIC_ALLOCATION is enabled.
std::array<std::byte, cfg::kEncodingBufferSizeBytes> encoding_buffer
    PW_GUARDED_BY(internal::rpc_lock());

}  // namespace

Result<uint32_t> ExtractChannelId(ConstByteSpan packet) {
  protobuf::Decoder decoder(packet);

  while (decoder.Next().ok()) {
    switch (static_cast<internal::RpcPacket::Fields>(decoder.FieldNumber())) {
      case internal::RpcPacket::Fields::CHANNEL_ID: {
        uint32_t channel_id;
        PW_TRY(decoder.ReadUint32(&channel_id));
        return channel_id;
      }

      default:
        continue;
    }
  }

  return Status::DataLoss();
}

namespace internal {

ByteSpan GetPayloadBuffer() PW_EXCLUSIVE_LOCKS_REQUIRED(rpc_lock()) {
  return ByteSpan(encoding_buffer)
      .subspan(Packet::kMinEncodedSizeWithoutPayload);
}

Status Channel::Send(const Packet& packet) {
  Result encoded = packet.Encode(encoding_buffer);

  if (!encoded.ok()) {
    PW_LOG_ERROR(
        "Failed to encode RPC packet type %u to channel %u buffer, status %u",
        static_cast<unsigned>(packet.type()),
        static_cast<unsigned>(id()),
        encoded.status().code());
    return Status::Internal();
  }

  Status sent = output().Send(encoded.value());

  if (!sent.ok()) {
    PW_LOG_DEBUG("Channel %u failed to send packet with status %u",
                 static_cast<unsigned>(id()),
                 sent.code());

    return Status::Unknown();
  }
  return OkStatus();
}

}  // namespace internal
}  // namespace pw::rpc