#pragma once // Splits a link message body into fragments (station-link "Fragmented messages": the link header with // flags 1 first / 2 middle / 3 last and the same opcode and sequence on every fragment, then // u16 total body size, u16 body offset, data). Header-only and free of ESP-IDF, so the host tests compile it // unmodified and check it against the app's reassembly. LinkService::send_fragmented is the only caller. #include "link_protocol.hpp" namespace microbu::link { /// One fragment: the flags for the link header and the body (u16 total, u16 offset, data). struct Fragment { std::uint8_t flags; Bytes body; }; /// Largest body that goes out as one unfragmented message on a transport whose messages are at most `limit` octets. constexpr std::size_t unfragmented_capacity(std::size_t limit) { return limit > header_size ? limit - header_size : 0; } /// Data octets one fragment carries on a transport whose messages are at most `limit` octets. constexpr std::size_t fragment_capacity(std::size_t limit) { return limit > header_size + fragment_header_size ? limit - header_size - fragment_header_size : 0; } /// @brief Fragments `body`, which must not fit one message of `limit` octets (the caller sends those as they are). /// @param body Message body to split. /// @param limit Largest message the transport carries, header included (512, or the BLE ATT MTU - 3). /// @param out Receives the fragments in order; empty when false is returned. /// @param max_fragments Refuse when more fragments would be needed (a V2X_RX on a transport with a tiny MTU). /// @return false when the body fits one message, exceeds 65535 octets, the limit leaves no room for data, or /// more than max_fragments are needed. inline bool split_fragments(const Bytes& body, std::size_t limit, std::vector& out, std::size_t max_fragments = 65535) { out.clear(); const std::size_t capacity = fragment_capacity(limit); if (body.size() <= unfragmented_capacity(limit) || body.size() > 65535 || capacity == 0) return false; if ((body.size() + capacity - 1) / capacity > max_fragments) return false; for (std::size_t offset = 0; offset < body.size(); offset += capacity) { const std::size_t n = body.size() - offset < capacity ? body.size() - offset : capacity; Fragment fragment; fragment.flags = offset == 0 ? flag_fragment_first : offset + n == body.size() ? flag_fragment_last : flag_fragment_middle; fragment.body = {static_cast(body.size()), static_cast(body.size() >> 8), static_cast(offset), static_cast(offset >> 8)}; fragment.body.insert(fragment.body.end(), body.begin() + static_cast(offset), body.begin() + static_cast(offset + n)); out.push_back(std::move(fragment)); } return true; } } // namespace microbu::link