MayaFlux 1.0.0
Digital-First Multimedia Processing Framework
Loading...
Searching...
No Matches
SerialInputBackend.hpp
Go to the documentation of this file.
1#pragma once
2
3#include "InputBackend.hpp"
6
9
11struct NetworkService;
12}
13
14namespace MayaFlux::Core {
15
16/**
17 * @class SerialInputBackend
18 * @brief The serial devices of the input system, one SerialDevice per open port.
19 *
20 * Devices come from the configured ports and, with enumerate_ports, from the ports the
21 * system exposes. A device keeps its id for as long as the backend lives, found again by
22 * the path it was configured with or the path the enumerator gave it, which is the stable
23 * /dev/serial/by-id link where the system has one, so a replug does not change it. Every value a device parses is delivered to the input callback, from
24 * the network io thread, once the backend is started.
25 *
26 * Ports are opened through the NetworkService, which must have the serial transport
27 * enabled in GlobalNetworkConfig, and that endpoint does the reconnecting. The device
28 * callback reports a device as connected while its port is open and as disconnected when
29 * it leaves OPEN. A device uses the default spec, one line per message read as numbers,
30 * unless set_device_spec gave it another before it was opened.
31 *
32 * write() sends the bytes as they are. A caller that wants requests and replies takes the
33 * device from get_device().
34 */
35class MAYAFLUX_API SerialInputBackend : public IInputBackend {
36public:
37 struct Config {
38 std::vector<SerialPortConfig> ports; ///< Ports to list, with the line setup of each
39 bool enumerate_ports { false }; ///< Also list the ports the system exposes
40 SerialLineSettings detected_line; ///< Line setup of enumerated ports
41 SerialProtocolSettings detected_protocol; ///< Framing and parsing of enumerated ports
42 Registry::Service::NetworkService* network { nullptr }; ///< Not owned, must outlive the backend
43 std::function<std::vector<Platform::SerialPortEntry>()> enumerator; ///< Lists the system's ports, Platform::list_serial_ports when empty
44 };
45
46 explicit SerialInputBackend(Config config);
47 ~SerialInputBackend() override;
48
53
54 bool initialize() override;
55 void start() override;
56 void stop() override;
57 void shutdown() override;
58
59 [[nodiscard]] bool is_initialized() const override { return m_initialized.load(); }
60 [[nodiscard]] bool is_running() const override { return m_running.load(); }
61
62 [[nodiscard]] std::vector<InputDeviceInfo> get_devices() const override;
63 size_t refresh_devices() override;
64
65 bool open_device(uint32_t device_id) override;
66 void close_device(uint32_t device_id) override;
67 [[nodiscard]] bool is_device_open(uint32_t device_id) const override;
68 [[nodiscard]] std::vector<uint32_t> get_open_devices() const override;
69
70 int write(uint32_t device_id, std::span<const uint8_t> data) override;
71
72 void set_input_callback(InputCallback callback) override;
73 void set_device_callback(DeviceCallback callback) override;
74
75 [[nodiscard]] InputType get_type() const override { return InputType::SERIAL; }
76 [[nodiscard]] std::string get_name() const override { return "Serial"; }
77 [[nodiscard]] std::string get_version() const override { return "1.0"; }
78
79 /**
80 * @brief List a port that was not configured, or update one that was while it is closed.
81 * @return The device id, or 0 before initialize().
82 *
83 * A port already listed under the same path keeps its id and takes the new line setup
84 * and protocol unless it is open.
85 */
86 uint32_t add_port(const SerialPortConfig& port);
87
88 /**
89 * @brief Give a device its spec, before it is opened.
90 * @return false for an unknown device or one that is open.
91 */
92 bool set_device_spec(uint32_t device_id, SerialSpec spec);
93
94 /**
95 * @brief List a second way of reading a device, as a device of its own.
96 * @param device_id The device to read, never a reading itself.
97 * @param spec Framing and parsing of this reading. Its line setup is not used.
98 * @return The id of the reading, or 0 for an unknown device or a reading. Bind nodes to it.
99 *
100 * The reading sees the bytes of the device it reads and cuts and parses them on its own,
101 * so one port can be read as lines by one node and as raw bytes by another. Opening it
102 * opens the device, closing it only stops this reading, and its values carry its own
103 * id. Writes to its id go to the device.
104 */
105 uint32_t add_view(uint32_t device_id, SerialSpec spec);
106
107 using ReaderCallback = std::function<void(const InputValue&)>;
108
109 /**
110 * @brief Read a device's bytes a second way and hand the values to @p callback.
111 * @return A token for remove_reader(), or 0 for an unknown device or a reading.
112 *
113 * Unlike a view, it is not listed as a device and does not go to the input callback. It
114 * stays attached when the device is closed and opened again, and runs on the link's
115 * thread. Values carry the id of the device.
116 */
117 uint64_t add_reader(uint32_t device_id, SerialSpec spec, ReaderCallback callback);
118
119 /** @brief Stop a reader. No-op for an unknown token. */
120 void remove_reader(uint64_t token);
121
122 /** @brief The open device, or null. A reading resolves to the device it reads. For requests and replies. */
123 [[nodiscard]] std::shared_ptr<SerialDevice> get_device(uint32_t device_id) const;
124
125private:
126 struct Entry {
129 std::shared_ptr<SerialDevice> device;
130 bool configured {};
131 uint32_t parent {};
132 uint64_t view_reader {};
133 };
134
136 uint64_t token {};
137 uint32_t device_id {};
138 uint32_t stamp {};
141 std::weak_ptr<SerialDevice> attached_to;
143 };
144
145 struct Roster {
147 std::map<std::string, uint32_t> ids;
148 uint32_t next_id { 1 };
149 };
150
151 using DeviceEvent = std::pair<InputDeviceInfo, bool>;
152
153 static uint32_t id_for(Roster& roster, const std::string& key);
154 static Entry make_entry(uint32_t id, const std::string& path, const std::string& name,
155 const SerialLineSettings& line, const SerialProtocolSettings& protocol, bool configured);
156
157 uint64_t add_record(uint32_t device_id, uint32_t stamp, SerialSpec spec, ReaderCallback callback);
158 void attach_readers(uint32_t device_id, const std::shared_ptr<SerialDevice>& device);
159 void detach_view(uint32_t view_id);
160
161 void on_link_state(uint32_t device_id, EndpointState previous, EndpointState current);
162 void notify_input(const InputValue& value) const;
163 void notify_device(const InputDeviceInfo& info, bool connected) const;
164
166 std::atomic<bool> m_initialized { false };
167 std::atomic<bool> m_running { false };
168
170 std::mutex m_reader_mutex;
171 std::vector<ReaderRecord> m_records;
172 std::atomic<uint64_t> m_next_reader { 1 };
175};
176
177} // namespace MayaFlux::Core
Abstract interface for input device backends.
uint64_t add_record(uint32_t device_id, uint32_t stamp, SerialSpec spec, ReaderCallback callback)
void remove_reader(uint64_t token)
Stop a reader.
SerialInputBackend & operator=(const SerialInputBackend &)=delete
static uint32_t id_for(Roster &roster, const std::string &key)
bool is_initialized() const override
Check if backend is initialized.
SerialInputBackend & operator=(SerialInputBackend &&)=delete
std::string get_version() const override
Get backend version string.
std::shared_ptr< SerialDevice > get_device(uint32_t device_id) const
The open device, or null.
std::string get_name() const override
Get backend name/identifier string.
SerialInputBackend(SerialInputBackend &&)=delete
std::vector< ReaderRecord > m_records
InputType get_type() const override
Get backend type.
bool is_running() const override
Check if backend is actively listening.
void on_link_state(uint32_t device_id, EndpointState previous, EndpointState current)
std::pair< InputDeviceInfo, bool > DeviceEvent
static Entry make_entry(uint32_t id, const std::string &path, const std::string &name, const SerialLineSettings &line, const SerialProtocolSettings &protocol, bool configured)
Memory::SnapshotCell< InputCallback > m_input_callback
Memory::SnapshotCell< DeviceCallback > m_device_callback
void attach_readers(uint32_t device_id, const std::shared_ptr< SerialDevice > &device)
Memory::SnapshotCell< Roster > m_roster
void start() override
Start listening for input events.
void stop() override
Stop listening for input events.
std::function< void(const InputValue &)> ReaderCallback
void shutdown() override
Shutdown and release all resources.
void notify_device(const InputDeviceInfo &info, bool connected) const
SerialInputBackend(const SerialInputBackend &)=delete
uint64_t add_reader(uint32_t device_id, SerialSpec spec, ReaderCallback callback)
Read a device's bytes a second way and hand the values to callback.
void notify_input(const InputValue &value) const
Map kept as one sorted vector, cheap to copy.
Definition FlatMap.hpp:21
Lock-free cell holding one immutable snapshot of a value, read without blocking.
void initialize()
Definition main.cpp:10
InputType
Input backend type enumeration.
@ SERIAL
Serial port communication (Arduino, etc.).
EndpointState
Observable connection state for an endpoint.
std::function< void(const InputDeviceInfo &, bool connected)> DeviceCallback
Callback signature for device connection/disconnection events.
std::function< void(const InputValue &)> InputCallback
Callback signature for input events.
Information about a connected input device.
Generic input value container.
bool enumerate_ports
Also list the ports the system exposes.
std::function< std::vector< Platform::SerialPortEntry >()> enumerator
Lists the system's ports, Platform::list_serial_ports when empty.
SerialLineSettings detected_line
Line setup of enumerated ports.
SerialProtocolSettings detected_protocol
Framing and parsing of enumerated ports.
std::vector< SerialPortConfig > ports
Ports to list, with the line setup of each.
Registry::Service::NetworkService * network
Not owned, must outlive the backend.
Memory::FlatMap< uint32_t, Entry > entries
Line setup applied when a serial endpoint opens.
One serial port, the line setup it opens with and how it is read.
How a port is read, as plain data a config can hold.
What a serial device is: its line setup, framing and parsing, as a plain value.
Backend network transport service interface.