MayaFlux 1.0.0
Digital-First Multimedia Processing Framework
Loading...
Searching...
No Matches
SerialDevice.hpp
Go to the documentation of this file.
1#pragma once
2
3#include "SerialLink.hpp"
4#include "SerialReader.hpp"
5#include "SerialSpec.hpp"
6
8
9namespace MayaFlux::Core {
10
11/**
12 * @enum SerialReply
13 * @brief How a request ended.
14 */
15enum class SerialReply : uint8_t {
16 REPLIED, ///< A message the matcher accepted arrived
17 TIMED_OUT, ///< Nothing matched within the timeout
18 LINK_LOST ///< The port left OPEN, or the device was closed, before a reply
19};
20
22
23/**
24 * @class SerialDevice
25 * @brief A serial port with a protocol on it: framing, parsing, commands and replies.
26 *
27 * The device knows only an ISerialLink and a SerialSpec. Chunks from the link are cut
28 * into messages by the spec's framing and each message becomes an InputValue through
29 * its parser, delivered to the value callback with the device id and InputType::SERIAL.
30 * Any number of further readers can be added, each with a spec of its own, and every
31 * reader sees the same bytes and reads them independently. A message over a spec's limit
32 * is dropped and counted, never queued.
33 *
34 * A request sends a command and waits for a message its matcher accepts. One request
35 * is outstanding at a time, a matched message goes to the request and not to the value
36 * callback, and every other message flows on as usual. When the port leaves OPEN the
37 * partial message and the running MIDI status are dropped and a pending request ends
38 * with LINK_LOST, so the stream resynchronises when the port returns. Destroying the
39 * device drops a pending request without calling it.
40 *
41 * The device's own callbacks run on the link's thread and must be set before open(). A
42 * reader's callback runs there too. send(), request(), add_reader() and remove_reader()
43 * may be called from any thread.
44 *
45 * @code
46 * SerialDevice device(1, SerialSpec::lines().baud(115200).settle_ms(1500),
47 * std::make_unique<NetworkSerialLink>(service));
48 * device.set_value_callback([](const InputValue& value) { });
49 * device.open("/dev/ttyACM0");
50 *
51 * device.request(bytes_of("?\n"),
52 * [](Transitive::Protocol::Message m) { return Transitive::Protocol::as_text(m).starts_with("ok"); },
53 * std::chrono::milliseconds(200),
54 * [](SerialReply how, Transitive::Protocol::Message reply) { });
55 * @endcode
56 */
57class MAYAFLUX_API SerialDevice {
58public:
59 using ValueCallback = std::function<void(const InputValue&)>;
60 using ReaderToken = uint64_t;
62 using ReplyMatcher = std::function<bool(Transitive::Protocol::Message message)>;
63 using ReplyCallback = std::function<void(SerialReply how, Transitive::Protocol::Message reply)>;
64
65 /**
66 * @param device_id Id stamped on every value.
67 * @param spec The line setup, framing and parsing.
68 * @param link The transport. Owned.
69 */
70 SerialDevice(uint32_t device_id, SerialSpec spec, std::unique_ptr<ISerialLink> link);
72
73 SerialDevice(const SerialDevice&) = delete;
77
78 void set_value_callback(ValueCallback callback);
79
80 /**
81 * @brief Read the same bytes a second way.
82 * @param spec Framing and parsing of this reader. Its line setup is not used.
83 * @param id Id stamped on the values it produces.
84 * @param callback Receives each value, on the link's thread.
85 * @return A token for remove_reader(), never 0.
86 *
87 * The reader does not take part in requests, and it starts from a clean stream.
88 */
89 ReaderToken add_reader(SerialSpec spec, uint32_t id, ValueCallback callback);
90
91 /** @brief Stop a reader. No-op for an unknown token. */
92 void remove_reader(ReaderToken token);
93
94 void set_state_callback(StateCallback callback);
95
96 /** @brief Open the port at @p path with the spec's line setup. */
97 bool open(const std::string& path);
98
99 /** @brief Close the port. A pending request ends with LINK_LOST. */
100 void close();
101
102 [[nodiscard]] EndpointState state() const;
103
104 /** @brief Send bytes as they are. */
105 bool send(std::span<const uint8_t> bytes);
106
107 /**
108 * @brief Send one message framed the way the spec reads them.
109 * @return false when the port is not open or the message cannot be framed, such as an
110 * LF inside a line.
111 */
112 bool send_framed(std::span<const uint8_t> message);
113
114 /**
115 * @brief Send a command and wait for its reply.
116 * @param command Sent as it is.
117 * @param matcher True for the message that answers the command.
118 * @param timeout How long to wait.
119 * @param done Called exactly once for a request that returns true, on the link's thread,
120 * with the reply when there is one. Never called for a request that returns false.
121 * @return false when a request is already pending, the port is not open or the send
122 * failed. A request whose reply or timeout beat a failed send is already complete,
123 * its callback has run, and this returns true.
124 */
125 bool request(std::span<const uint8_t> command, ReplyMatcher matcher,
126 std::chrono::milliseconds timeout, ReplyCallback done);
127
128 bool set_control_lines(std::optional<bool> dtr, std::optional<bool> rts);
129 bool send_break();
130
131 /** @brief Bytes accepted for sending and not yet sent. */
132 [[nodiscard]] size_t write_backlog() const;
133
134 [[nodiscard]] SerialDeviceStats stats() const;
135 [[nodiscard]] uint32_t device_id() const { return m_device_id; }
136 [[nodiscard]] const SerialSpec& spec() const { return m_spec; }
137
138private:
139 struct Pending {
142 std::atomic<ISerialLink::TimerToken> timer { 0 };
143 };
144
145 using ReaderList = std::vector<std::pair<ReaderToken, std::shared_ptr<SerialReader>>>;
146
147 void handle_chunk(std::span<const uint8_t> chunk);
148 void handle_state(EndpointState previous, EndpointState current);
150 std::shared_ptr<Pending> take_pending(const std::shared_ptr<Pending>& only = {});
151 [[nodiscard]] bool is_pending(const std::shared_ptr<Pending>& request) const;
152 void end_request(const std::shared_ptr<Pending>& request, SerialReply how, Transitive::Protocol::Message reply);
153
154 uint32_t m_device_id;
156 std::unique_ptr<ISerialLink> m_link;
157
158 std::unique_ptr<SerialReader> m_reader;
160 std::atomic<ReaderToken> m_next_token { 1 };
162
164};
165
166} // namespace MayaFlux::Core
Memory::SnapshotCell< ReaderList > m_readers
std::vector< std::pair< ReaderToken, std::shared_ptr< SerialReader > > > ReaderList
SerialDevice(SerialDevice &&)=delete
Memory::SnapshotCell< std::shared_ptr< Pending > > m_pending
std::unique_ptr< SerialReader > m_reader
bool send_framed(std::span< const uint8_t > message)
Send one message framed the way the spec reads them.
std::function< bool(Transitive::Protocol::Message message)> ReplyMatcher
SerialDevice & operator=(SerialDevice &&)=delete
ISerialLink::StateCallback StateCallback
SerialDeviceStats stats() const
std::function< void(SerialReply how, Transitive::Protocol::Message reply)> ReplyCallback
size_t write_backlog() const
Bytes accepted for sending and not yet sent.
std::shared_ptr< Pending > take_pending(const std::shared_ptr< Pending > &only={})
std::unique_ptr< ISerialLink > m_link
std::atomic< ReaderToken > m_next_token
void handle_chunk(std::span< const uint8_t > chunk)
SerialDevice(uint32_t device_id, SerialSpec spec, std::unique_ptr< ISerialLink > link)
void handle_state(EndpointState previous, EndpointState current)
bool set_control_lines(std::optional< bool > dtr, std::optional< bool > rts)
void set_value_callback(ValueCallback callback)
bool open(const std::string &path)
Open the port at path with the spec's line setup.
SerialDevice & operator=(const SerialDevice &)=delete
std::function< void(const InputValue &)> ValueCallback
SerialDevice(const SerialDevice &)=delete
bool complete_request(Transitive::Protocol::Message frame)
const SerialSpec & spec() const
bool send(std::span< const uint8_t > bytes)
Send bytes as they are.
void set_state_callback(StateCallback callback)
EndpointState state() const
ReaderToken add_reader(SerialSpec spec, uint32_t id, ValueCallback callback)
Read the same bytes a second way.
bool request(std::span< const uint8_t > command, ReplyMatcher matcher, std::chrono::milliseconds timeout, ReplyCallback done)
Send a command and wait for its reply.
void close()
Close the port.
void remove_reader(ReaderToken token)
Stop a reader.
Lock-free cell holding one immutable snapshot of a value, read without blocking.
EndpointState
Observable connection state for an endpoint.
SerialReaderStats SerialDeviceStats
SerialReply
How a request ended.
@ REPLIED
A message the matcher accepted arrived.
@ LINK_LOST
The port left OPEN, or the device was closed, before a reply.
@ TIMED_OUT
Nothing matched within the timeout.
std::span< const uint8_t > Message
One complete message.
Definition Framing.hpp:8
Generic input value container.
std::atomic< ISerialLink::TimerToken > timer
What a reader has seen since it was made.
What a serial device is: its line setup, framing and parsing, as a plain value.