/* * blebus.hpp — BLEBus v1.1.0 * Pure C++17 BLE L2CAP IPC library. * Dual-listener broker: local unix socket + BLE L2CAP CoC. * Length-prefixed framing (wire-compatible with sockbus). * Bytes in, bytes out, broadcast to all readers including sender. * * Copyright (c) 2026 Are Bjørby * SPDX-License-Identifier: MIT */ #pragma once #include #include #include #include namespace blebus { // ── Constants ──────────────────────────────────────────────────────── inline constexpr size_t DEFAULT_SIZE = 64 * 1024; inline constexpr size_t MAX_NAME = 256; inline constexpr size_t MAX_READERS = 8; inline constexpr size_t READER_NAME_LEN = 32; inline constexpr size_t MAX_MSG_SIZE = DEFAULT_SIZE - 4; inline constexpr uint16_t PSM = 0x0080; // ── Bus lifecycle (no handle) ──────────────────────────────────────── /** * Create a new BLE bus. * Starts BLE advertising, L2CAP listener (PSM 0x0080), and local * unix socket listener. Spawns broker thread. * @throws std::system_error on failure */ void create(std::string_view name, size_t size = 0); /** * Destroy bus (stop advertising, disconnect all clients). * @throws std::system_error(ENOENT) if no broker for name */ void destroy(std::string_view name); // ── Bus handle (RAII) ──────────────────────────────────────────────── class Bus { public: /** * Connect to an existing blebus via local unix socket. * @throws std::system_error on connection failure */ explicit Bus(std::string_view name); ~Bus(); Bus(const Bus&) = delete; Bus& operator=(const Bus&) = delete; Bus(Bus&&) noexcept; Bus& operator=(Bus&&) noexcept; // ── Write ──────────────────────────────────────────────────────── /** * Write data to bus (broadcast to all connected peers). * @return Payload bytes written * @throws std::system_error(EMSGSIZE) if len > MAX_MSG_SIZE * @throws std::system_error on send failure */ size_t write(const uint8_t* data, size_t len); size_t write(std::string_view sv); // ── Read ───────────────────────────────────────────────────────── /** * Non-blocking read. Returns one complete message per call. * @return Bytes read, 0 if no message available */ size_t read(uint8_t* buf, size_t len); /** * Blocking read with timeout. * @param timeout_ms -1 = block forever, 0 = poll, >0 = ms * @return Bytes read, 0 on timeout */ size_t read_wait(uint8_t* buf, size_t len, int timeout_ms = -1); // ── Metadata ───────────────────────────────────────────────────── void set_reader_name(std::string_view label); std::string_view name() const; private: struct Impl; std::unique_ptr impl_; }; } // namespace blebus