-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathBoostSerial.cpp
462 lines (406 loc) · 12.6 KB
/
BoostSerial.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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
#include "BoostSerial.h"
#include <iostream>
using namespace std;
void BoostSerial::asyncReadHandler(const boost::system::error_code &error, std::size_t bytes_transferred)
{
std::unique_lock<std::mutex> elk(errMtx);
if (error)
{
err = error.value();
}
elk.unlock();
if(error.value() == 995)
return;//operation aborted
//place the content of buffer array into usableReadBuffer vector
//usableReadBuffer is necessary because using handler buffer directly in read() or available() functions
//fuck ups entire class for some reason
//probably due to manipulating buffer in async_read_some
std::unique_lock<std::mutex> lk(readBufferMtx); //for readBufferSize and usableReadBuffer
for (auto i = 0; i < bytes_transferred; i++)
{
usableReadBuffer.push_back(buf[i]);
}
//overflow
if (usableReadBuffer.size() > readBufferSize)
{
//remove overflow
//and lose data
unsigned int overflow = usableReadBuffer.size() - readBufferSize;
usableReadBuffer.erase(usableReadBuffer.begin(), usableReadBuffer.begin() + overflow);
}
lk.unlock();
//read async again
serial.async_read_some(
boost::asio::buffer(buf, buf.size()),
[this](const boost::system::error_code &error, std::size_t bytes_transferred) {
asyncReadHandler(error, bytes_transferred);
});
}
void BoostSerial::asyncWriteHandler(const boost::system::error_code &error, std::size_t bytes_transferred)
{
std::unique_lock<std::mutex> elk(errMtx);
if (error)
{
err = error.value();
}
elk.unlock();
std::unique_lock<std::mutex> lk(writeMtx);
writeLocked = false;
lk.unlock(); //next write is possible
writeCv.notify_one(); //if there is next write() waiting, notify it so it can continue
}
void BoostSerial::printString(const std::string &s)
{
std::unique_lock<std::mutex> lk(writeMtx); //lock variable
if (writeLocked) //if previous async is still writting
writeCv.wait(lk); //pause this thread and wait until write is finished then lock variable again
writeLocked = true; //then set locked and begin writting
lk.unlock();
boost::asio::async_write(
serial,
boost::asio::buffer(s, s.size()),
[this](const boost::system::error_code &error, std::size_t bytes_transferred) {
asyncWriteHandler(error, bytes_transferred);
});
}
BoostSerial::~BoostSerial()
{
if (serial.is_open())
close();
}
unsigned int BoostSerial::write(uint8_t c)
{
std::vector<uint8_t> v({c});
return write(v);
}
unsigned int BoostSerial::write(const std::vector<uint8_t> &v)
{
std::unique_lock<std::mutex> lk(writeMtx); //lock variable
if (writeLocked) //if previous async is still writting
writeCv.wait(lk); //pause this thread and wait until write is finished then lock variable again
writeLocked = true; //then set locked and begin writting
lk.unlock(); //asyncWriteHandler can access writeLocked now
boost::asio::async_write(
serial,
boost::asio::buffer(v, v.size()),
[this](const boost::system::error_code &error, std::size_t bytes_transferred) {
asyncWriteHandler(error, bytes_transferred);
});
return v.size();
}
template <class T>
unsigned int BoostSerial::print(T const &a, unsigned int option)
{
//write unknown data to stringstream
std::stringstream ss;
//for float treat option as precision
if (std::is_floating_point<T>::value)
{
ss << std::setprecision(option) << std::fixed << a;
}
//for int treat it as print format
else if (std::is_integral<T>::value)
{
//only for BIN
bool trim = true;
std::string str;
switch (option)
{
case BIN:
ss << std::bitset<sizeof(T) * 8>(a);
str = ss.str();
//remove leading zeroes
while (trim)
{
if (!str.length())
trim = false;
else if (str[0] == '1')
trim = false;
else
str.erase(str.begin());
}
ss.str(std::string());
ss.clear();
ss << str;
break;
case HEX:
ss << std::hex << a;
break;
case OCT:
ss << std::oct << a;
break;
case DEC:
default:
ss << a;
break;
}
}
//do not use option value for non int nor float
else
{
ss << a;
}
std::string res = ss.str();
printString(res);
return res.length();
}
template <class T>
unsigned int BoostSerial::println(T const &t, unsigned int option)
{
unsigned int r = print(t, option);
write('\n');
return r + 1;
}
int16_t BoostSerial::read()
{
std::unique_lock<std::mutex> lk(readBufferMtx); //for readBufferSize;
//return -1 if there is no data available
if (!usableReadBuffer.size())
return -1;
//return first element and remove it from the buffer
int res = usableReadBuffer[0];
usableReadBuffer.erase(usableReadBuffer.begin());
return res;
}
std::vector<uint8_t> BoostSerial::readBuffer()
{
std::vector<uint8_t> v;
//move content of buffer to user's variable
std::unique_lock<std::mutex> lk(readBufferMtx); //for readBufferSize;
v = std::move(usableReadBuffer);
usableReadBuffer.clear();
return v;
}
std::vector<uint8_t> BoostSerial::readBytes(uint16_t len)
{
auto start = std::chrono::system_clock::now();
bool timeout = false;
std::vector<uint8_t> res;
//check whether given number of bytes has been read
//or whether timeout happened
while (res.size() < len && !timeout)
{
//check whether timeout happened
//and if so, set timeout flag
auto now = std::chrono::system_clock::now();
auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(now - start);
if (elapsed.count() >= timeoutVal)
{
timeout = true;
}
//else check if there is data in the buffer
//and if so, push it to res
else
{
int16_t b = read();
if (b > -1)
{
res.push_back(b);
start = std::chrono::system_clock::now();
}
}
}
return res;
}
std::vector<uint8_t> BoostSerial::readBytesUntil(uint8_t givenByte, uint16_t len)
{
auto start = std::chrono::system_clock::now();
bool endFlag = false;
std::vector<uint8_t> res;
//check whether given number of bytes has been read
//or whether timeout happened
while (res.size() < len && !endFlag)
{
//check whether timeout happened
//and if so, set timeout flag
auto now = std::chrono::system_clock::now();
auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(now - start);
if (elapsed.count() >= timeoutVal)
{
endFlag = true;
}
//else check if there is data in the buffer
//and if so, push it to res
else
{
int16_t readByte = read();
if (readByte == givenByte)
{
endFlag = true;
}
else if (readByte > -1)
{
res.push_back(readByte);
start = std::chrono::system_clock::now();
}
}
}
return res;
}
std::string BoostSerial::readStringUntil(char givenChar)
{
auto start = std::chrono::system_clock::now();
bool endFlag = false;
std::string res;
//check whether given number of characters has been read
//or whether timeout happened
while (!endFlag)
{
//check whether timeout happened
//and if so, set endFlag
auto now = std::chrono::system_clock::now();
auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(now - start);
if (elapsed.count() >= timeoutVal)
{
endFlag = true;
}
else
{
int16_t readChar = read();
//check if read character is given character
//or string terminator
//and if so, set endFlag flag
if (readChar == givenChar || readChar == '\0')
{
endFlag = true;
}
//else check if there is data in the buffer
//and if so, push it to res
else if (readChar > -1)
{
res += readChar;
}
}
}
return res;
}
int16_t BoostSerial::peek() const
{
//std::unique_lock<std::mutex> lk(readBufferMtx); //for readBufferSize;
std::unique_lock<std::mutex> lk(readBufferMtx);
//return -1 if there is no data available
if (!usableReadBuffer.size())
return -1;
return usableReadBuffer[0];
}
void BoostSerial::open(std::string dname,
unsigned int baud_,
flowControlType flowControl_,
unsigned int characterSize_,
parityType parity_,
stopBitsType stopBits_)
{
//cleanup if port was already opened
if(serial.is_open())
close();
try{
serial.open(dname);
}
catch(...){}
if (!serial.is_open())
return;
baud = baud_;
flowControl = flowControl_;
characterSize = characterSize_;
parity = parity_;
stopBits = stopBits_;
//set options for serial port
serial.set_option(boost::asio::serial_port_base::baud_rate(baud));
serial.set_option(boost::asio::serial_port_base::flow_control(flowControl));
serial.set_option(boost::asio::serial_port_base::character_size(characterSize));
serial.set_option(boost::asio::serial_port_base::parity(parity));
serial.set_option(boost::asio::serial_port_base::stop_bits(stopBits));
serial_work.reset(new boost::asio::io_service::work(serial_service));
//create thread that will read incoming data asynchronously
asyncReadThread.reset(new std::thread([this] { serial_service.run(); }));
//push the first read request
serial.async_read_some(
boost::asio::buffer(buf, buf.size()),
[this](const boost::system::error_code &error, std::size_t bytes_transferred) {
asyncReadHandler(error, bytes_transferred);
});
}
void BoostSerial::close()
{
if (!serial.is_open())
return;
clear();//clear read buffer
//cancel pending async processes
serial.cancel();
//finish async read thread and delete it
serial_service.stop();
if(asyncReadThread.get() != nullptr)
{
asyncReadThread->join();
asyncReadThread.reset(nullptr);
}
//reset io service for reopening
serial_service.reset();
serial.close();
}
bool BoostSerial::good() const
{
std::unique_lock<std::mutex> lk(errMtx);
return !err;
}
int BoostSerial::getErr() const
{
std::unique_lock<std::mutex> lk(errMtx);
return err;
}
void BoostSerial::clear()
{
std::unique_lock<std::mutex> lk(errMtx);
err = errorCode::success;
}
unsigned int BoostSerial::available() const
{
//returns true if there are some bytes in the buffer
std::unique_lock<std::mutex> lk(readBufferMtx); //for readBufferSize;
return usableReadBuffer.size();
}
bool BoostSerial::idle() const
{
std::unique_lock<std::mutex> lx(writeMtx);
return !writeLocked;
}
void BoostSerial::setBaud(unsigned int b)
{
baud = b;
if (serial.is_open())
serial.set_option(boost::asio::serial_port_base::baud_rate(b));
}
void BoostSerial::setFlowControl(flowControlType t)
{
flowControl = t;
if (serial.is_open())
serial.set_option(boost::asio::serial_port_base::flow_control(t));
}
void BoostSerial::setCharacterSize(unsigned int s)
{
characterSize = s;
if (serial.is_open())
serial.set_option(boost::asio::serial_port_base::character_size(s));
}
void BoostSerial::setParity(parityType t)
{
parity = t;
if (serial.is_open())
serial.set_option(boost::asio::serial_port_base::parity(t));
}
void BoostSerial::setStopBits(stopBitsType t)
{
stopBits = t;
if (serial.is_open())
serial.set_option(boost::asio::serial_port_base::stop_bits(t));
}
void BoostSerial::setBufferSize(unsigned int b)
{
std::unique_lock<std::mutex> lk(readBufferMtx); //for readBufferSize;
readBufferSize = b;
}
unsigned int BoostSerial::getBufferSize() const
{
std::unique_lock<std::mutex> lk(readBufferMtx); //for readBufferSize;
return readBufferSize;
}