TinyRobotics
Loading...
Searching...
No Matches
MessageDispatcher.h
1#pragma once
2#include "Message.h"
5#include "Stream.h"
6#include "TinyRobotics/utils/LoggerClass.h"
7#include "TinyRobotics/vehicles/Vehicle.h"
8
9namespace tinyrobotics {
10
11/**
12 * @class MessageDispatcher
13 * @ingroup communication
14 * @brief Reads stream and forwards messages to handler.
15 *
16 * The MessageDispatcher class reads messages from a communication stream
17 * (such as Serial, UDP, etc.) and dispatches them to the MessageHandler
18 * instance for processing. It handles message framing, validation, and error
19 * logging, providing a unified interface for remote control and telemetry.
20 *
21 * Usage Example:
22 * @code
23 * MessageDispatcher commMgr(handler, Serial);
24 * while (true) {
25 * commMgr.run();
26 * }
27 * @endcode
28 */
29
31 public:
32 MessageDispatcher() = default;
33 MessageDispatcher(MessageHandler& handler) { p_handler = &handler; }
34 MessageDispatcher(MessageHandler& handler, Stream& io) {
35 p_handler = &handler;
36 p_stream = &io;
37 };
38
39 bool begin() {
40 if (p_stream == nullptr || p_handler == nullptr) {
41 TRLogger.error("CommMgr: Invalid stream or handler");
42 return false;
43 }
44 is_active = true;
45 return true;
46 }
47
48 void end() { is_active = false; }
49
50 /// Read messages from the stream and dispatch them to the vehicle for
51 /// processing.
52 virtual bool run() {
53 if (!is_active) return false;
54 if (!p_stream || !p_handler) return false;
55 MessageParser parser;
56 // Try to parse and dispatch a message from the stream
57 if (!parser.parse(*p_stream, *p_handler)) {
58 // Optionally log error or warning here
59 TRLogger.error("CommMgr: Failed to parse message");
60 return false;
61 }
62 return true;
63 }
64
65 void setStream(Stream& io) { p_stream = &io; }
66 void setHandler(MessageHandler& handler) { p_handler = &handler; }
67
68 protected:
69 Stream* p_stream = nullptr;
70 bool is_active = false;
71 MessageHandler* p_handler = nullptr;
72};
73
74} // namespace tinyrobotics
Reads stream and forwards messages to handler.
Definition: MessageDispatcher.h:30
virtual bool run()
Definition: MessageDispatcher.h:52
Interface for handling messages in the TinyRobotics framework.
Definition: MessageHandler.h:18
Parses binary TinyRobotics messages from a Stream and dispatches them by type.
Definition: MessageParser.h:79