MayaFlux 1.0.0
Digital-First Multimedia Processing Framework
Loading...
Searching...
No Matches
SerialInputBackend.cpp
Go to the documentation of this file.
2
4
7
8namespace MayaFlux::Core {
9
10namespace {
11
12 bool same_port(const std::string& first, const std::string& second)
13 {
14 if (first == second) {
15 return true;
16 }
17 std::error_code ec;
18 return std::filesystem::equivalent(first, second, ec) && !ec;
19 }
20
21}
22
24 : m_config(std::move(config))
25{
26}
27
34
35uint32_t SerialInputBackend::id_for(Roster& roster, const std::string& key)
36{
37 const auto [it, inserted] = roster.ids.try_emplace(key, roster.next_id);
38 if (inserted) {
39 ++roster.next_id;
40 }
41 return it->second;
42}
43
44auto SerialInputBackend::make_entry(uint32_t id, const std::string& path, const std::string& name,
45 const SerialLineSettings& line, const SerialProtocolSettings& protocol, bool configured) -> Entry
46{
47 Entry entry;
48 entry.info = InputDeviceInfo {
49 .id = id,
50 .name = name,
51 .manufacturer = {},
52 .backend_type = InputType::SERIAL,
53 .is_connected = true,
54 .port_name = path,
55 .baud_rate = line.baud_rate,
56 };
57 entry.spec = SerialSpec::from(line, protocol);
58 entry.configured = configured;
59 return entry;
60}
61
63{
64 if (m_initialized.load()) {
65 return true;
66 }
67
68 if (!m_config.network) {
70 "SerialInputBackend needs a NetworkService");
71 return false;
72 }
73
74 m_roster.update([&](Roster& roster) {
75 roster = Roster {};
76 for (const auto& port : m_config.ports) {
77 const uint32_t id = id_for(roster, "c:" + port.port_name);
78 roster.entries.insert_or_assign(id,
79 make_entry(id, port.port_name, port.port_name, port.line, port.protocol, true));
80 }
81 return true;
82 });
83
84 m_initialized.store(true);
85
86 if (m_config.enumerate_ports) {
88 }
89
91 "SerialInputBackend initialized with {} port(s)", get_devices().size());
92
93 return true;
94}
95
97{
98 m_running.store(true);
99}
100
102{
103 m_running.store(false);
104}
105
107{
108 if (!m_initialized.load()) {
109 return;
110 }
111
112 stop();
113
114 std::vector<std::shared_ptr<SerialDevice>> open;
115 if (const auto roster = m_roster.read()) {
116 for (const auto& [id, entry] : roster->entries) {
117 if (entry.device) {
118 open.push_back(entry.device);
119 }
120 }
121 }
122 m_roster.reset();
123 {
124 std::lock_guard lock(m_reader_mutex);
125 m_records.clear();
126 }
127
128 for (const auto& device : open) {
129 device->close();
130 }
131
132 m_initialized.store(false);
133}
134
135std::vector<InputDeviceInfo> SerialInputBackend::get_devices() const
136{
137 std::vector<InputDeviceInfo> devices;
138 if (const auto roster = m_roster.read()) {
139 devices.reserve(roster->entries.size());
140 for (const auto& [id, entry] : roster->entries) {
141 devices.push_back(entry.info);
142 }
143 }
144 return devices;
145}
146
148{
149 if (!m_initialized.load() || !m_config.enumerate_ports) {
150 return get_devices().size();
151 }
152
153 const auto found = m_config.enumerator ? m_config.enumerator() : Platform::list_serial_ports();
154 std::vector<DeviceEvent> events;
155 size_t count = 0;
156
157 m_roster.update([&](Roster& roster) {
158 events.clear();
159 bool changed = false;
160 std::set<uint32_t> seen;
161
162 for (const auto& port : found) {
163 const std::string path = port.path.string();
164 const bool configured_port = std::ranges::any_of(roster.entries, [&](const auto& item) {
165 return item.second.configured && item.second.parent == 0 && same_port(item.second.info.port_name, path);
166 });
167 if (configured_port) {
168 continue;
169 }
170
171 const uint32_t id = id_for(roster, "e:" + path);
172 seen.insert(id);
173 if (roster.entries.find(id) == roster.entries.end()) {
174 Entry entry = make_entry(id, path, port.name, m_config.detected_line,
175 m_config.detected_protocol, false);
176 events.emplace_back(entry.info, true);
177 roster.entries.insert_or_assign(id, std::move(entry));
178 changed = true;
179 }
180 }
181
182 std::vector<uint32_t> gone;
183 for (const auto& [id, entry] : roster.entries) {
184 if (!entry.configured && entry.parent == 0 && !entry.device && !seen.contains(id)) {
185 gone.push_back(id);
186 }
187 }
188 for (const uint32_t id : gone) {
189 events.emplace_back(roster.entries.find(id)->second.info, false);
190 roster.entries.erase(id);
191 changed = true;
192 }
193
194 std::vector<uint32_t> orphans;
195 for (const auto& [id, entry] : roster.entries) {
196 if (entry.parent != 0 && roster.entries.find(entry.parent) == roster.entries.end()) {
197 orphans.push_back(id);
198 }
199 }
200 for (const uint32_t id : orphans) {
201 events.emplace_back(roster.entries.find(id)->second.info, false);
202 roster.entries.erase(id);
203 changed = true;
204 }
205
206 count = roster.entries.size();
207 return changed;
208 });
209
210 for (const auto& [info, connected] : events) {
211 notify_device(info, connected);
212 }
213
214 return count;
215}
216
217bool SerialInputBackend::open_device(uint32_t device_id)
218{
219 Entry entry;
220 if (const auto roster = m_roster.read()) {
221 const auto it = roster->entries.find(device_id);
222 if (it == roster->entries.end()) {
224 "Serial device {} not found", device_id);
225 return false;
226 }
227 entry = it->second;
228 } else {
229 return false;
230 }
231
232 if (entry.parent != 0) {
233 if (!open_device(entry.parent)) {
234 return false;
235 }
236 if (entry.view_reader != 0) {
237 return true;
238 }
239 const uint64_t token = add_record(entry.parent, device_id, entry.spec,
240 [this](const InputValue& value) {
241 if (m_running.load()) {
242 notify_input(value);
243 }
244 });
245 m_roster.update([&](Roster& roster) {
246 const auto it = roster.entries.find(device_id);
247 if (it == roster.entries.end()) {
248 return false;
249 }
250 Entry changed = it->second;
251 changed.view_reader = token;
252 roster.entries.insert_or_assign(device_id, std::move(changed));
253 return true;
254 });
255 attach_readers(entry.parent, get_device(entry.parent));
256 return true;
257 }
258
259 if (entry.device) {
260 return true;
261 }
262
263 auto device = std::make_shared<SerialDevice>(device_id, entry.spec,
264 std::make_unique<NetworkSerialLink>(m_config.network));
265 device->set_value_callback([this](const InputValue& value) {
266 if (m_running.load()) {
267 notify_input(value);
268 }
269 });
270 device->set_state_callback([this, device_id](EndpointState previous, EndpointState current) {
271 on_link_state(device_id, previous, current);
272 });
273
274 if (!device->open(entry.info.port_name)) {
276 "Failed to open serial device {}: {}", device_id, entry.info.port_name);
277 return false;
278 }
279
280 enum class Outcome : uint8_t { Registered, AlreadyOpen, Gone };
281 Outcome outcome = Outcome::Gone;
282 m_roster.update([&](Roster& roster) {
283 const auto it = roster.entries.find(device_id);
284 if (it == roster.entries.end()) {
285 outcome = Outcome::Gone;
286 return false;
287 }
288 if (it->second.device) {
289 outcome = Outcome::AlreadyOpen;
290 return false;
291 }
292 Entry changed = it->second;
293 changed.device = device;
294 roster.entries.insert_or_assign(device_id, std::move(changed));
295 outcome = Outcome::Registered;
296 return true;
297 });
298
299 if (outcome != Outcome::Registered) {
300 device->close();
301 }
302
303 if (outcome == Outcome::Gone) {
305 "Serial device {} left the list while it was opening", device_id);
306 return false;
307 }
308
309 if (outcome == Outcome::Registered) {
310 attach_readers(device_id, device);
311 }
312
314 "Opened serial device {}: {}", device_id, entry.info.port_name);
315
316 return true;
317}
318
320{
321 uint64_t token = 0;
322 m_roster.update([&](Roster& roster) {
323 token = 0;
324 const auto it = roster.entries.find(view_id);
325 if (it == roster.entries.end() || it->second.view_reader == 0) {
326 return false;
327 }
328 Entry changed = it->second;
329 token = std::exchange(changed.view_reader, 0);
330 roster.entries.insert_or_assign(view_id, std::move(changed));
331 return true;
332 });
333 if (token != 0) {
334 remove_reader(token);
335 }
336}
337
338void SerialInputBackend::close_device(uint32_t device_id)
339{
340 bool is_view = false;
341 if (const auto roster = m_roster.read()) {
342 const auto it = roster->entries.find(device_id);
343 is_view = it != roster->entries.end() && it->second.parent != 0;
344 }
345 if (is_view) {
346 detach_view(device_id);
347 return;
348 }
349
350 std::shared_ptr<SerialDevice> device;
351 m_roster.update([&](Roster& roster) {
352 device.reset();
353 const auto it = roster.entries.find(device_id);
354 if (it == roster.entries.end() || !it->second.device) {
355 return false;
356 }
357 Entry changed = it->second;
358 device = std::move(changed.device);
359 changed.device.reset();
360 roster.entries.insert_or_assign(device_id, std::move(changed));
361 return true;
362 });
363
364 if (device) {
365 device->close();
366 }
367}
368
369bool SerialInputBackend::is_device_open(uint32_t device_id) const
370{
371 if (const auto roster = m_roster.read()) {
372 const auto it = roster->entries.find(device_id);
373 if (it != roster->entries.end() && it->second.parent != 0) {
374 return it->second.view_reader != 0 && get_device(it->second.parent) != nullptr;
375 }
376 }
377 return get_device(device_id) != nullptr;
378}
379
380std::vector<uint32_t> SerialInputBackend::get_open_devices() const
381{
382 std::vector<uint32_t> open;
383 if (const auto roster = m_roster.read()) {
384 for (const auto& [id, entry] : roster->entries) {
385 if (entry.device) {
386 open.push_back(id);
387 }
388 }
389 }
390 return open;
391}
392
393int SerialInputBackend::write(uint32_t device_id, std::span<const uint8_t> data)
394{
395 const auto device = get_device(device_id);
396 if (!device || !device->send(data)) {
397 return -1;
398 }
399 return static_cast<int>(data.size());
400}
401
403{
404 m_input_callback.publish(std::move(callback));
405}
406
408{
409 m_device_callback.publish(std::move(callback));
410}
411
413{
414 if (!m_initialized.load()) {
415 return 0;
416 }
417
418 uint32_t id = 0;
419 m_roster.update([&](Roster& roster) {
420 id = id_for(roster, "c:" + port.port_name);
421 const auto it = roster.entries.find(id);
422 if (it == roster.entries.end()) {
423 roster.entries.insert_or_assign(id,
424 make_entry(id, port.port_name, port.port_name, port.line, port.protocol, true));
425 return true;
426 }
427 if (it->second.device) {
428 return false;
429 }
430 Entry changed = make_entry(id, port.port_name, port.port_name, port.line, port.protocol, true);
431 changed.info.is_connected = it->second.info.is_connected;
432 roster.entries.insert_or_assign(id, std::move(changed));
433 return true;
434 });
435 return id;
436}
437
439{
440 return m_roster.update([&](Roster& roster) {
441 const auto it = roster.entries.find(device_id);
442 if (it == roster.entries.end() || it->second.device) {
443 return false;
444 }
445 Entry changed = it->second;
446 changed.spec = spec;
447 roster.entries.insert_or_assign(device_id, std::move(changed));
448 return true;
449 });
450}
451
452std::shared_ptr<SerialDevice> SerialInputBackend::get_device(uint32_t device_id) const
453{
454 if (const auto roster = m_roster.read()) {
455 const auto it = roster->entries.find(device_id);
456 if (it != roster->entries.end()) {
457 if (it->second.parent != 0) {
458 const auto parent = roster->entries.find(it->second.parent);
459 return parent != roster->entries.end() ? parent->second.device : nullptr;
460 }
461 return it->second.device;
462 }
463 }
464 return nullptr;
465}
466
467uint32_t SerialInputBackend::add_view(uint32_t device_id, SerialSpec spec)
468{
469 if (!m_initialized.load()) {
470 return 0;
471 }
472
473 uint32_t id = 0;
474 InputDeviceInfo info {};
475 m_roster.update([&](Roster& roster) {
476 id = 0;
477 const auto parent = roster.entries.find(device_id);
478 if (parent == roster.entries.end() || parent->second.parent != 0) {
479 return false;
480 }
481 id = id_for(roster, "v:" + std::to_string(roster.next_id));
482 Entry entry = parent->second;
483 entry.device.reset();
484 entry.parent = device_id;
485 entry.view_reader = 0;
486 entry.configured = false;
487 entry.spec = spec;
488 entry.info.id = id;
489 entry.info.name = parent->second.info.name + " (reading " + std::to_string(id) + ")";
490 info = entry.info;
491 roster.entries.insert_or_assign(id, std::move(entry));
492 return true;
493 });
494
495 if (id != 0) {
496 notify_device(info, info.is_connected);
497 }
498 return id;
499}
500
501uint64_t SerialInputBackend::add_record(uint32_t device_id, uint32_t stamp, SerialSpec spec, ReaderCallback callback)
502{
503 const uint64_t token = m_next_reader.fetch_add(1);
504 std::lock_guard lock(m_reader_mutex);
505 m_records.push_back({ .token = token, .device_id = device_id, .stamp = stamp,
506 .spec = std::move(spec), .callback = std::move(callback), .attached_to = {}, .device_token = 0 });
507 return token;
508}
509
510void SerialInputBackend::attach_readers(uint32_t device_id, const std::shared_ptr<SerialDevice>& device)
511{
512 if (!device) {
513 return;
514 }
515 std::lock_guard lock(m_reader_mutex);
516 for (auto& record : m_records) {
517 if (record.device_id != device_id || record.attached_to.lock() == device) {
518 continue;
519 }
520 record.device_token = device->add_reader(record.spec, record.stamp, record.callback);
521 record.attached_to = device;
522 }
523}
524
525uint64_t SerialInputBackend::add_reader(uint32_t device_id, SerialSpec spec, ReaderCallback callback)
526{
527 if (!m_initialized.load() || !callback) {
528 return 0;
529 }
530
531 bool known = false;
532 if (const auto roster = m_roster.read()) {
533 const auto it = roster->entries.find(device_id);
534 known = it != roster->entries.end() && it->second.parent == 0;
535 }
536 if (!known) {
537 return 0;
538 }
539
540 const uint64_t token = add_record(device_id, device_id, std::move(spec), std::move(callback));
541 attach_readers(device_id, get_device(device_id));
542 return token;
543}
544
546{
547 std::lock_guard lock(m_reader_mutex);
548 const auto it = std::ranges::find(m_records, token, &ReaderRecord::token);
549 if (it == m_records.end()) {
550 return;
551 }
552 if (const auto device = it->attached_to.lock()) {
553 device->remove_reader(it->device_token);
554 }
555 m_records.erase(it);
556}
557
558void SerialInputBackend::on_link_state(uint32_t device_id, EndpointState previous, EndpointState current)
559{
560 const bool was_open = previous == EndpointState::OPEN;
561 const bool is_open = current == EndpointState::OPEN;
562 if (was_open == is_open) {
563 return;
564 }
565
566 InputDeviceInfo info {};
567 bool found = false;
568 m_roster.update([&](Roster& roster) {
569 found = false;
570 const auto it = roster.entries.find(device_id);
571 if (it == roster.entries.end()) {
572 return false;
573 }
574 Entry changed = it->second;
575 changed.info.is_connected = is_open;
576 info = changed.info;
577 found = true;
578 roster.entries.insert_or_assign(device_id, std::move(changed));
579 return true;
580 });
581
582 if (found) {
583 notify_device(info, is_open);
584 }
585}
586
588{
589 if (const auto callback = m_input_callback.read(); callback && *callback) {
590 (*callback)(value);
591 }
592}
593
594void SerialInputBackend::notify_device(const InputDeviceInfo& info, bool connected) const
595{
596 if (const auto callback = m_device_callback.read(); callback && *callback) {
597 (*callback)(info, connected);
598 }
599}
600
601} // namespace MayaFlux::Core
#define MF_INFO(comp, ctx,...)
#define MF_ERROR(comp, ctx,...)
#define MF_WARN(comp, ctx,...)
uint64_t add_record(uint32_t device_id, uint32_t stamp, SerialSpec spec, ReaderCallback callback)
void remove_reader(uint64_t token)
Stop a reader.
uint32_t add_port(const SerialPortConfig &port)
List a port that was not configured, or update one that was while it is closed.
std::vector< InputDeviceInfo > get_devices() const override
Get list of available devices.
static uint32_t id_for(Roster &roster, const std::string &key)
int write(uint32_t device_id, std::span< const uint8_t > data) override
Send an output report to an open device, for rumble, LEDs or commands.
uint32_t add_view(uint32_t device_id, SerialSpec spec)
List a second way of reading a device, as a device of its own.
bool initialize() override
Initialize the input backend.
std::shared_ptr< SerialDevice > get_device(uint32_t device_id) const
The open device, or null.
size_t refresh_devices() override
Refresh the device list.
void set_device_callback(DeviceCallback callback) override
Register callback for device connect/disconnect events.
std::vector< ReaderRecord > m_records
void close_device(uint32_t device_id) override
Close a previously opened device.
void on_link_state(uint32_t device_id, EndpointState previous, EndpointState current)
std::vector< uint32_t > get_open_devices() const override
Get list of currently open device IDs.
static Entry make_entry(uint32_t id, const std::string &path, const std::string &name, const SerialLineSettings &line, const SerialProtocolSettings &protocol, bool configured)
bool open_device(uint32_t device_id) override
Open a device for input.
Memory::SnapshotCell< InputCallback > m_input_callback
Memory::SnapshotCell< DeviceCallback > m_device_callback
bool set_device_spec(uint32_t device_id, SerialSpec spec)
Give a device its spec, before it is opened.
bool is_device_open(uint32_t device_id) const override
Check if a device is currently open.
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
void set_input_callback(InputCallback callback) override
Register callback for input values.
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
@ 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.
@ InputBackend
Input device backend (HID, MIDI, OSC).
@ Core
Core engine, backend, subsystems.
std::vector< SerialPortEntry > list_serial_ports()
The serial ports the system exposes, sorted by name.
std::pair< std::shared_ptr< Kriya::BufferPipeline >, std::shared_ptr< Buffers::AudioBuffer > > record(const std::shared_ptr< Kakshya::DynamicSoundStream > &stream, uint32_t input_channel, double seconds, std::optional< uint32_t > monitor, uint32_t channel)
Record a live input channel into a stream for a number of seconds.
Definition Rigs.cpp:262
bool is_connected
Current connection state.
std::string name
Human-readable device name.
uint32_t id
Unique device identifier within backend.
Information about a connected input device.
Generic input value container.
Memory::FlatMap< uint32_t, Entry > entries
Line setup applied when a serial endpoint opens.
SerialLineSettings line
Baud, framing bits, flow control, control lines at open.
SerialProtocolSettings protocol
Framing and parsing of what the port sends.
std::string port_name
e.g., "/dev/ttyUSB0" or "COM3"
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.
static SerialSpec from(const SerialLineSettings &line, const SerialProtocolSettings &protocol)
The spec a configured port describes.
What a serial device is: its line setup, framing and parsing, as a plain value.