1 // Copyright 2020 The Pigweed Authors
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
7 // https://www.apache.org/licenses/LICENSE-2.0
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
15 #include "pw_rpc/internal/nanopb_method.h"
17 #include "pb_decode.h"
18 #include "pb_encode.h"
19 #include "pw_log/log.h"
20 #include "pw_rpc/internal/packet.h"
22 namespace pw::rpc::internal {
26 void NanopbMethod::CallUnary(ServerCall& call,
27 const Packet& request,
29 void* response_struct) const {
30 if (!DecodeRequest(call.channel(), request, request_struct)) {
34 const Status status = function_.unary(call, request_struct, response_struct);
35 SendResponse(call.channel(), request, response_struct, status);
38 void NanopbMethod::CallServerStreaming(ServerCall& call,
39 const Packet& request,
40 void* request_struct) const {
41 if (!DecodeRequest(call.channel(), request, request_struct)) {
45 internal::BaseServerWriter server_writer(call);
46 function_.server_streaming(call, request_struct, server_writer);
49 bool NanopbMethod::DecodeRequest(Channel& channel,
50 const Packet& request,
51 void* proto_struct) const {
52 if (serde_.DecodeRequest(proto_struct, request.payload())) {
56 PW_LOG_WARN("Failed to decode request payload from channel %u",
57 unsigned(channel.id()));
58 channel.Send(Packet::ServerError(request, Status::DataLoss()));
62 void NanopbMethod::SendResponse(Channel& channel,
63 const Packet& request,
64 const void* response_struct,
65 Status status) const {
66 Channel::OutputBuffer response_buffer = channel.AcquireBuffer();
67 std::span payload_buffer = response_buffer.payload(request);
69 StatusWithSize encoded = EncodeResponse(response_struct, payload_buffer);
72 Packet response = Packet::Response(request);
74 response.set_payload(payload_buffer.first(encoded.size()));
75 response.set_status(status);
76 if (channel.Send(response_buffer, response).ok()) {
80 // Re-acquire the buffer to encode an error packet.
81 response_buffer = channel.AcquireBuffer();
84 PW_LOG_WARN("Failed to encode response packet for channel %u",
85 unsigned(channel.id()));
86 channel.Send(response_buffer,
87 Packet::ServerError(request, Status::Internal()));
90 } // namespace pw::rpc::internal