-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathSerialDispatcher.cpp
334 lines (284 loc) · 11 KB
/
SerialDispatcher.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
/*
* This file is part of the Arduino_ThreadsafeIO library.
* Copyright (c) 2021 Arduino SA.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**************************************************************************************
* INCLUDE
**************************************************************************************/
#include "SerialDispatcher.h"
/**************************************************************************************
* CTOR/DTOR
**************************************************************************************/
SerialDispatcher::SerialDispatcher(arduino::HardwareSerial & serial)
: _is_initialized{false}
, _mutex{}
, _cond{_mutex}
, _serial{serial}
, _thread(osPriorityRealtime, 4096, nullptr, "SerialDispatcher")
, _has_tread_started{false}
, _terminate_thread{false}
, _global_prefix_callback{nullptr}
, _global_suffix_callback{nullptr}
{
}
/**************************************************************************************
* PUBLIC MEMBER FUNCTIONS
**************************************************************************************/
void SerialDispatcher::begin(unsigned long baudrate)
{
begin(baudrate, SERIAL_8N1);
}
void SerialDispatcher::begin(unsigned long baudrate, uint16_t config)
{
mbed::ScopedLock<rtos::Mutex> lock(_mutex);
if (!_is_initialized)
{
_serial.begin(baudrate, config);
_is_initialized = true;
_thread.start(mbed::callback(this, &SerialDispatcher::threadFunc)); /* TODO: Check return code */
while (!_has_tread_started) { }
}
/* Check if the thread calling begin is already in the list. */
osThreadId_t const current_thread_id = rtos::ThisThread::get_id();
if (findThreadCustomerDataById(rtos::ThisThread::get_id()) == std::end(_thread_customer_list))
{
/* Since the thread is not in the list yet we are
* going to create a new entry to the list.
*/
ThreadCustomerData data;
data.thread_id = current_thread_id;
data.block_tx_buffer = false;
data.prefix_func = nullptr;
data.suffix_func = nullptr;
_thread_customer_list.push_back(data);
}
}
void SerialDispatcher::end()
{
mbed::ScopedLock<rtos::Mutex> lock(_mutex);
/* Retrieve the current thread id and remove
* the thread data from the thread data list.
*/
osThreadId_t const current_thread_id = rtos::ThisThread::get_id();
std::remove_if(std::begin(_thread_customer_list),
std::end (_thread_customer_list),
[current_thread_id](ThreadCustomerData const d) -> bool { return (d.thread_id == current_thread_id); });
/* If no thread consumers are left also end
* the serial device altogether.
*/
if (_thread_customer_list.size() == 0)
{
_terminate_thread = true;
_thread.join();
_serial.end();
}
}
int SerialDispatcher::available()
{
mbed::ScopedLock<rtos::Mutex> lock(_mutex);
auto iter = findThreadCustomerDataById(rtos::ThisThread::get_id());
if (iter == std::end(_thread_customer_list)) return 0;
prepareSerialReader(iter);
handleSerialReader();
return iter->rx_buffer->available();
}
int SerialDispatcher::peek()
{
mbed::ScopedLock<rtos::Mutex> lock(_mutex);
auto iter = findThreadCustomerDataById(rtos::ThisThread::get_id());
if (iter == std::end(_thread_customer_list)) return 0;
prepareSerialReader(iter);
handleSerialReader();
return iter->rx_buffer->peek();
}
int SerialDispatcher::read()
{
mbed::ScopedLock<rtos::Mutex> lock(_mutex);
auto iter = findThreadCustomerDataById(rtos::ThisThread::get_id());
if (iter == std::end(_thread_customer_list)) return 0;
prepareSerialReader(iter);
handleSerialReader();
return iter->rx_buffer->read_char();
}
void SerialDispatcher::flush()
{
mbed::ScopedLock<rtos::Mutex> lock(_mutex);
_serial.flush();
}
size_t SerialDispatcher::write(uint8_t const b)
{
return write(&b, 1);
}
size_t SerialDispatcher::write(const uint8_t * data, size_t len)
{
mbed::ScopedLock<rtos::Mutex> lock(_mutex);
auto iter = findThreadCustomerDataById(rtos::ThisThread::get_id());
/* If this thread hasn't registered yet
* with the SerialDispatcher via 'begin'.
*/
if (iter == std::end(_thread_customer_list))
return 0;
size_t bytes_written = 0;
for (; (bytes_written < len) && iter->tx_buffer.availableForStore(); bytes_written++)
iter->tx_buffer.store_char(data[bytes_written]);
/* Inform the worker thread that new data has
* been written to a Serial transmit buffer.
*/
_cond.notify_one();
return bytes_written;
}
void SerialDispatcher::block()
{
mbed::ScopedLock<rtos::Mutex> lock(_mutex);
auto iter = findThreadCustomerDataById(rtos::ThisThread::get_id());
if (iter == std::end(_thread_customer_list)) return;
iter->block_tx_buffer = true;
}
void SerialDispatcher::unblock()
{
mbed::ScopedLock<rtos::Mutex> lock(_mutex);
auto iter = findThreadCustomerDataById(rtos::ThisThread::get_id());
if (iter == std::end(_thread_customer_list)) return;
iter->block_tx_buffer = false;
_cond.notify_one();
}
void SerialDispatcher::prefix(PrefixInjectorCallbackFunc func)
{
mbed::ScopedLock<rtos::Mutex> lock(_mutex);
auto iter = findThreadCustomerDataById(rtos::ThisThread::get_id());
if (iter == std::end(_thread_customer_list)) return;
iter->prefix_func = func;
}
void SerialDispatcher::suffix(SuffixInjectorCallbackFunc func)
{
mbed::ScopedLock<rtos::Mutex> lock(_mutex);
auto iter = findThreadCustomerDataById(rtos::ThisThread::get_id());
if (iter == std::end(_thread_customer_list)) return;
iter->suffix_func = func;
}
void SerialDispatcher::global_prefix(PrefixInjectorCallbackFunc func)
{
mbed::ScopedLock<rtos::Mutex> lock(_mutex);
_global_prefix_callback = func;
}
void SerialDispatcher::global_suffix(SuffixInjectorCallbackFunc func)
{
mbed::ScopedLock<rtos::Mutex> lock(_mutex);
_global_suffix_callback = func;
}
/**************************************************************************************
* PRIVATE MEMBER FUNCTIONS
**************************************************************************************/
void SerialDispatcher::threadFunc()
{
_has_tread_started = true;
while(!_terminate_thread)
{
/* Prevent race conditions by multi-threaded
* access to shared data.
*/
mbed::ScopedLock<rtos::Mutex> lock(_mutex);
/* Wait for new data to be available */
_cond.wait();
/* Iterate over all list entries. */
std::for_each(std::begin(_thread_customer_list),
std::end (_thread_customer_list),
[this](ThreadCustomerData & d)
{
if (d.block_tx_buffer)
return;
/* Return if there's no data to be written to the
* serial interface. This statement is necessary
* because otherwise the prefix/suffix functions
* will be invoked and will be printing something,
* even though no data is actually to be printed for
* most threads.
*/
if (!d.tx_buffer.available())
return;
/* Retrieve all data stored in the transmit ringbuffer
* and store it into a String for usage by both suffix
* prefix callback functions.
*/
String msg;
while(d.tx_buffer.available())
msg += static_cast<char>(d.tx_buffer.read_char());
/* The prefix callback function allows the
* user to insert a custom message before
* a new message is written to the serial
* driver. This is useful e.g. for wrapping
* protocol (e.g. the 'AT' protocol) or providing
* a timestamp, a log level, ...
*/
String prefix;
if (d.prefix_func)
prefix = d.prefix_func(msg);
/* A prefix callback function defined per thread
* takes precedence over a globally defined prefix
* callback function.
*/
else if (_global_prefix_callback)
prefix = _global_prefix_callback(msg);
/* Similar to the prefix function this callback
* allows the user to specify a specific message
* to be appended to each message, e.g. '\r\n'.
*/
String suffix;
if (d.suffix_func)
suffix = d.suffix_func(prefix, msg);
/* A suffix callback function defined per thread
* takes precedence over a globally defined suffix
* callback function.
*/
else if (_global_suffix_callback)
suffix = _global_suffix_callback(prefix, msg);
/* Now it's time to actually write the message
* conveyed by the user via Serial.print/println.
*/
_serial.write(prefix.c_str());
_serial.write(msg.c_str());
_serial.write(suffix.c_str());
});
}
}
std::list<SerialDispatcher::ThreadCustomerData>::iterator SerialDispatcher::findThreadCustomerDataById(osThreadId_t const thread_id)
{
return std::find_if(std::begin(_thread_customer_list),
std::end (_thread_customer_list),
[thread_id](ThreadCustomerData const d) -> bool { return (d.thread_id == thread_id); });
}
void SerialDispatcher::prepareSerialReader(std::list<ThreadCustomerData>::iterator & iter)
{
if (!iter->rx_buffer)
iter->rx_buffer.reset(new arduino::RingBuffer());
}
void SerialDispatcher::handleSerialReader()
{
while (_serial.available())
{
int const c = _serial.read();
std::for_each(std::begin(_thread_customer_list),
std::end (_thread_customer_list),
[c](ThreadCustomerData & d)
{
if (!d.rx_buffer)
return;
if (!d.rx_buffer->availableForStore())
return;
d.rx_buffer->store_char(c);
});
}
}