1 // Copyright 2021 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 #include "pw_assert/assert.h"
16 #include "pw_bloat/bloat_this_binary.h"
17 #include "pw_log/log.h"
18 #include "pw_router/egress_function.h"
19 #include "pw_router/static_router.h"
20 #include "pw_sys_io/sys_io.h"
21
22 namespace {
23
24 struct BasicPacket {
25 static constexpr uint32_t kMagic = 0x8badf00d;
26
BasicPacket__anon3bab10e60111::BasicPacket27 constexpr BasicPacket(uint32_t addr, uint64_t data)
28 : magic(kMagic), address(addr), payload(data) {}
29
30 uint32_t magic;
31 uint32_t address;
32 uint64_t payload;
33 };
34
35 } // namespace
36
37 // All the new router-specific stuff.
38 namespace {
39
40 class BasicPacketParser : public pw::router::PacketParser {
41 public:
BasicPacketParser()42 constexpr BasicPacketParser() : packet_(nullptr) {}
43
Parse(pw::ConstByteSpan packet)44 bool Parse(pw::ConstByteSpan packet) final {
45 packet_ = reinterpret_cast<const BasicPacket*>(packet.data());
46 return packet_->magic == BasicPacket::kMagic;
47 }
48
GetDestinationAddress() const49 std::optional<uint32_t> GetDestinationAddress() const final {
50 return packet_->address;
51 }
52
53 private:
54 const BasicPacket* packet_;
55 };
56
57 BasicPacketParser parser;
__anon3bab10e60302(pw::ConstByteSpan packet) 58 pw::router::EgressFunction sys_io_egress(+[](pw::ConstByteSpan packet) {
59 return pw::sys_io::WriteBytes(packet).status();
60 });
61 constexpr pw::router::StaticRouter::Route routes[] = {{1, sys_io_egress}};
62 pw::router::StaticRouter router(parser, routes);
63
64 } // namespace
65
main()66 int main() {
67 pw::bloat::BloatThisBinary();
68
69 // Ensure we are paying the cost for log and assert.
70 BasicPacket packet(0x1, 0x2);
71 PW_CHECK_UINT_EQ(packet.magic, BasicPacket::kMagic, "Some CHECK logic");
72 PW_LOG_INFO("Packet has address %u", static_cast<unsigned>(packet.address));
73 PW_LOG_INFO("pw_StatusString %s", pw::OkStatus().str());
74
75 std::array<std::byte, sizeof(BasicPacket)> packet_buffer;
76 pw::sys_io::ReadBytes(packet_buffer);
77 pw::sys_io::WriteBytes(packet_buffer);
78
79 while (true) {
80 pw::sys_io::ReadBytes(packet_buffer);
81 router.RoutePacket(packet_buffer);
82 }
83
84 return static_cast<int>(packet.payload);
85 }
86