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 "pb_decode.h"
16 #include "pb_encode.h"
17 #include "pw_assert/assert.h"
18 #include "pw_bloat/bloat_this_binary.h"
19 #include "pw_log/log.h"
20 #include "pw_rpc/echo_service_nanopb.h"
21 #include "pw_rpc/server.h"
22 #include "pw_sys_io/sys_io.h"
24 int volatile* unoptimizable;
26 class Output : public pw::rpc::ChannelOutput {
28 Output() : ChannelOutput("output") {}
30 std::span<std::byte> AcquireBuffer() override { return buffer_; }
32 pw::Status SendAndReleaseBuffer(std::span<const std::byte> buffer) override {
33 PW_DCHECK_PTR_EQ(buffer.data(), buffer_);
34 return pw::sys_io::WriteBytes(buffer).status();
38 std::byte buffer_[128];
41 namespace my_product {
43 template <typename DecodeFunction>
46 template <typename FieldsType>
47 struct NanopbTraits<bool(pb_istream_t*, FieldsType, void*)> {
48 using Fields = FieldsType;
51 using Fields = typename NanopbTraits<decltype(pb_decode)>::Fields;
53 // Performs the core nanopb encode and decode operations so that those functions
54 // are included in the binary.
55 void DoNanopbStuff() {
56 std::byte buffer[128];
57 void* fields = &buffer;
59 auto output = pb_ostream_from_buffer(reinterpret_cast<pb_byte_t*>(buffer),
61 pb_encode(&output, static_cast<Fields>(fields), buffer);
63 auto input = pb_istream_from_buffer(
64 reinterpret_cast<const pb_byte_t*>(buffer), sizeof(buffer));
65 pb_decode(&input, static_cast<Fields>(fields), buffer);
69 pw::rpc::Channel channels[] = {pw::rpc::Channel::Create<1>(&output)};
70 pw::rpc::Server server(channels);
71 pw::rpc::EchoService echo_service;
73 } // namespace my_product
76 pw::bloat::BloatThisBinary();
77 my_product::DoNanopbStuff();
79 // Ensure we are paying the cost for log and assert.
80 PW_CHECK_INT_GE(*unoptimizable, 0, "Ensure this CHECK logic stays");
81 PW_LOG_INFO("We care about optimizing: %d", *unoptimizable);
83 std::byte packet_buffer[128];
84 pw::sys_io::ReadBytes(packet_buffer);
85 pw::sys_io::WriteBytes(packet_buffer);
87 my_product::server.RegisterService(my_product::echo_service);
88 my_product::server.ProcessPacket(packet_buffer, my_product::output);
90 return static_cast<int>(packet_buffer[92]);