#pragma once #include #include #include #include #include "CommandEnvelope.hpp" #include "CommandResult.hpp" #include "../Handlers/ICommandHandler.hpp" #include "../Transport/ITransport.hpp" // --------------------------------------------------------------------------- // CommandBus // // Registry + dispatcher. Replaces the 700-line if/else chain in CommandHandler. // // Usage: // // Registration (once, in CommunicationRouter::registerHandlers()) // _bus.registerHandler(std::make_unique(_player)); // _bus.addTransport(&_mqtt); // // // Dispatch (called from each transport's message callback) // _bus.dispatch(envelope); // // // Broadcast event to all transports // _bus.broadcast(CommandResult::info("bell.strike", "Bell 2 fired")); // --------------------------------------------------------------------------- class CommandBus { public: // Register a handler. All command names reported by handler->commands() // are mapped to this handler instance. Duplicate command names log a // warning and the later registration wins. void registerHandler(std::unique_ptr handler); // Add a transport that receives broadcasts and participates in health checks. void addTransport(ITransport* transport); // Dispatch an envelope to the registered handler (O(1) hash-map lookup). // Calls envelope.reply() exactly once — with an error result if no handler // is registered for envelope.command. void dispatch(CommandEnvelope& envelope); // Broadcast a serialised result to all registered transports. // Each transport's broadcast() implementation decides how to fan it out // (e.g. WebSocket sends to all connected clients; HTTP is a no-op). void broadcast(const CommandResult& result); private: // Owned storage for handler instances std::vector> _handlers; // Command name → handler pointer (non-owning, points into _handlers) // std::map used instead of unordered_map — Arduino String has no std::hash specialisation std::map _registry; // Non-owning references to transports (owned by CommunicationRouter) std::vector _transports; };