1 // Copyright 2022 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 <cstdint> 17 18 #include "pw_rpc/internal/packet.h" 19 #include "pw_rpc/internal/packet.pwpb.h" 20 #include "pw_rpc/method_id.h" 21 #include "pw_rpc/service_id.h" 22 #include "pw_span/span.h" 23 #include "pw_status/status_with_size.h" 24 25 namespace pw::rpc { 26 27 // Metadata about a `pw_rpc` packet. 28 // 29 // For now, this metadata structure only includes a limited set of information 30 // about the contents of a packet, but it may be extended in the future. 31 class PacketMeta { 32 public: 33 // Parses the metadata from a serialized packet. 34 static Result<PacketMeta> FromBuffer(ConstByteSpan data); channel_id()35 constexpr uint32_t channel_id() const { return channel_id_; } service_id()36 constexpr ServiceId service_id() const { return service_id_; } method_id()37 constexpr MethodId method_id() const { return method_id_; } destination_is_client()38 constexpr bool destination_is_client() const { 39 return destination_ == internal::Packet::kClient; 40 } destination_is_server()41 constexpr bool destination_is_server() const { 42 return destination_ == internal::Packet::kServer; 43 } type_is_client_error()44 constexpr bool type_is_client_error() const { 45 return type_ == internal::pwpb::PacketType::CLIENT_ERROR; 46 } type_is_server_error()47 constexpr bool type_is_server_error() const { 48 return type_ == internal::pwpb::PacketType::SERVER_ERROR; 49 } 50 // Note: this `payload` is only valid so long as the original `data` buffer 51 // passed to `PacketMeta::FromBuffer` remains valid. payload()52 constexpr ConstByteSpan payload() const { return payload_; } 53 54 private: PacketMeta(const internal::Packet packet)55 constexpr explicit PacketMeta(const internal::Packet packet) 56 : channel_id_(packet.channel_id()), 57 service_id_(internal::WrapServiceId(packet.service_id())), 58 method_id_(internal::WrapMethodId(packet.method_id())), 59 destination_(packet.destination()), 60 type_(packet.type()), 61 payload_(packet.payload()) {} 62 uint32_t channel_id_; 63 ServiceId service_id_; 64 MethodId method_id_; 65 internal::Packet::Destination destination_; 66 internal::pwpb::PacketType type_; 67 ConstByteSpan payload_; 68 }; 69 70 } // namespace pw::rpc 71