-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathasyncSerial.cpp
576 lines (476 loc) · 15.5 KB
/
asyncSerial.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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
/*
* File: AsyncSerial.cpp
* Author: Terraneo Federico
* Distributed under the Boost Software License, Version 1.0.
* Created on September 7, 2009, 10:46 AM
*
* v1.02: Fixed a bug in BufferedAsyncSerial: Using the default constructor
* the callback was not set up and reading didn't work.
*
* v1.01: Fixed a bug that did not allow to reopen a closed serial port.
*
* v1.00: First release.
*
* IMPORTANT:
* On Mac OS X boost asio's serial ports have bugs, and the usual implementation
* of this class does not work. So a workaround class was written temporarily,
* until asio (hopefully) will fix Mac compatibility for serial ports.
*
* Please note that unlike said in the documentation on OS X until asio will
* be fixed serial port *writes* are *not* asynchronous, but at least
* asynchronous *read* works.
* In addition the serial port open ignores the following options: parity,
* character size, flow, stop bits, and defaults to 8N1 format.
* I know it is bad but at least it's better than nothing.
*
*/
#include "asyncSerial.h"
#include <string>
#include <algorithm>
#include <iostream>
#include <boost/bind.hpp>
using namespace std;
using namespace boost;
//
//Class AsyncSerial
//
#ifndef __APPLE__
class AsyncSerialImpl: private boost::noncopyable
{
public:
AsyncSerialImpl(): io(), port(io), backgroundThread(), open(false),
error(false) {}
boost::asio::io_service io; ///< Io service object
boost::asio::serial_port port; ///< Serial port object
boost::thread backgroundThread; ///< Thread that runs read/write operations
bool open; ///< True if port open
bool error; ///< Error flag
mutable boost::mutex errorMutex; ///< Mutex for access to error
/// Data are queued here before they go in writeBuffer
std::vector<char> writeQueue;
boost::shared_array<char> writeBuffer; ///< Data being written
size_t writeBufferSize; ///< Size of writeBuffer
boost::mutex writeQueueMutex; ///< Mutex for access to writeQueue
char readBuffer[AsyncSerial::readBufferSize]; ///< data being read
/// Read complete callback
boost::function<void (const char*, size_t)> callback;
};
AsyncSerial::AsyncSerial(): pimpl(new AsyncSerialImpl)
{
}
AsyncSerial::AsyncSerial(const std::string& devname, unsigned int baud_rate,
asio::serial_port_base::parity opt_parity,
asio::serial_port_base::character_size opt_csize,
asio::serial_port_base::flow_control opt_flow,
asio::serial_port_base::stop_bits opt_stop)
: pimpl(new AsyncSerialImpl)
{
open(devname,baud_rate,opt_parity,opt_csize,opt_flow,opt_stop);
}
void AsyncSerial::open(const std::string& devname, unsigned int baud_rate,
asio::serial_port_base::parity opt_parity,
asio::serial_port_base::character_size opt_csize,
asio::serial_port_base::flow_control opt_flow,
asio::serial_port_base::stop_bits opt_stop)
{
if(isOpen()) close();
setErrorStatus(true);//If an exception is thrown, error_ remains true
pimpl->port.open(devname);
pimpl->port.set_option(asio::serial_port_base::baud_rate(baud_rate));
pimpl->port.set_option(opt_parity);
pimpl->port.set_option(opt_csize);
pimpl->port.set_option(opt_flow);
pimpl->port.set_option(opt_stop);
//This gives some work to the io_service before it is started
pimpl->io.post(boost::bind(&AsyncSerial::doRead, this));
thread t(boost::bind(&asio::io_service::run, &pimpl->io));
pimpl->backgroundThread.swap(t);
setErrorStatus(false);//If we get here, no error
pimpl->open=true; //Port is now open
}
bool AsyncSerial::isOpen() const
{
return pimpl->open;
}
bool AsyncSerial::errorStatus() const
{
boost::lock_guard<boost::mutex> l(pimpl->errorMutex);
return pimpl->error;
}
void AsyncSerial::close()
{
if(!isOpen()) return;
pimpl->open=false;
pimpl->io.post(boost::bind(&AsyncSerial::doClose, this));
pimpl->backgroundThread.join();
pimpl->io.reset();
if(errorStatus())
{
throw(boost::system::system_error(boost::system::error_code(),
"Error while closing the device"));
}
}
void AsyncSerial::write(const char *data, size_t size)
{
{
boost::lock_guard<boost::mutex> l(pimpl->writeQueueMutex);
pimpl->writeQueue.insert(pimpl->writeQueue.end(),data,data+size);
}
pimpl->io.post(boost::bind(&AsyncSerial::doWrite, this));
}
void AsyncSerial::write(const std::vector<char>& data)
{
{
boost::lock_guard<boost::mutex> l(pimpl->writeQueueMutex);
pimpl->writeQueue.insert(pimpl->writeQueue.end(),data.begin(),
data.end());
}
pimpl->io.post(boost::bind(&AsyncSerial::doWrite, this));
}
void AsyncSerial::writeString(const std::string& s)
{
{
boost::lock_guard<boost::mutex> l(pimpl->writeQueueMutex);
pimpl->writeQueue.insert(pimpl->writeQueue.end(),s.begin(),s.end());
}
pimpl->io.post(boost::bind(&AsyncSerial::doWrite, this));
}
AsyncSerial::~AsyncSerial()
{
if(isOpen())
{
try {
close();
} catch(...)
{
//Don't throw from a destructor
}
}
}
void AsyncSerial::doRead()
{
pimpl->port.async_read_some(asio::buffer(pimpl->readBuffer,readBufferSize),
boost::bind(&AsyncSerial::readEnd,
this,
asio::placeholders::error,
asio::placeholders::bytes_transferred));
}
void AsyncSerial::readEnd(const boost::system::error_code& error,
size_t bytes_transferred)
{
if(error)
{
#ifdef __APPLE__
if(error.value()==45)
{
//Bug on OS X, it might be necessary to repeat the setup
//http://osdir.com/ml/lib.boost.asio.user/2008-08/msg00004.html
doRead();
return;
}
#endif //__APPLE__
//error can be true even because the serial port was closed.
//In this case it is not a real error, so ignore
if(isOpen())
{
doClose();
setErrorStatus(true);
}
} else {
if(pimpl->callback) pimpl->callback(pimpl->readBuffer,
bytes_transferred);
doRead();
}
}
void AsyncSerial::doWrite()
{
//If a write operation is already in progress, do nothing
if(pimpl->writeBuffer==0)
{
boost::lock_guard<boost::mutex> l(pimpl->writeQueueMutex);
pimpl->writeBufferSize=pimpl->writeQueue.size();
pimpl->writeBuffer.reset(new char[pimpl->writeQueue.size()]);
copy(pimpl->writeQueue.begin(),pimpl->writeQueue.end(),
pimpl->writeBuffer.get());
pimpl->writeQueue.clear();
async_write(pimpl->port,asio::buffer(pimpl->writeBuffer.get(),
pimpl->writeBufferSize),
boost::bind(&AsyncSerial::writeEnd, this, asio::placeholders::error));
}
}
void AsyncSerial::writeEnd(const boost::system::error_code& error)
{
if(!error)
{
boost::lock_guard<boost::mutex> l(pimpl->writeQueueMutex);
if(pimpl->writeQueue.empty())
{
pimpl->writeBuffer.reset();
pimpl->writeBufferSize=0;
return;
}
pimpl->writeBufferSize=pimpl->writeQueue.size();
pimpl->writeBuffer.reset(new char[pimpl->writeQueue.size()]);
copy(pimpl->writeQueue.begin(),pimpl->writeQueue.end(),
pimpl->writeBuffer.get());
pimpl->writeQueue.clear();
async_write(pimpl->port,asio::buffer(pimpl->writeBuffer.get(),
pimpl->writeBufferSize),
boost::bind(&AsyncSerial::writeEnd, this, asio::placeholders::error));
} else {
setErrorStatus(true);
doClose();
}
}
void AsyncSerial::doClose()
{
boost::system::error_code ec;
pimpl->port.cancel(ec);
if(ec) setErrorStatus(true);
pimpl->port.close(ec);
if(ec) setErrorStatus(true);
}
void AsyncSerial::setErrorStatus(bool e)
{
boost::lock_guard<boost::mutex> l(pimpl->errorMutex);
pimpl->error=e;
}
void AsyncSerial::setReadCallback(const boost::function<void (const char*, size_t)>& callback)
{
pimpl->callback=callback;
}
void AsyncSerial::clearReadCallback()
{
pimpl->callback.clear();
}
#else //__APPLE__
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <termios.h>
#include <unistd.h>
class AsyncSerialImpl: private boost::noncopyable
{
public:
AsyncSerialImpl(): backgroundThread(), open(false), error(false) {}
boost::thread backgroundThread; ///< Thread that runs read operations
bool open; ///< True if port open
bool error; ///< Error flag
mutable boost::mutex errorMutex; ///< Mutex for access to error
int fd; ///< File descriptor for serial port
char readBuffer[AsyncSerial::readBufferSize]; ///< data being read
/// Read complete callback
boost::function<void (const char*, size_t)> callback;
};
AsyncSerial::AsyncSerial(): pimpl(new AsyncSerialImpl)
{
}
AsyncSerial::AsyncSerial(const std::string& devname, unsigned int baud_rate,
asio::serial_port_base::parity opt_parity,
asio::serial_port_base::character_size opt_csize,
asio::serial_port_base::flow_control opt_flow,
asio::serial_port_base::stop_bits opt_stop)
: pimpl(new AsyncSerialImpl)
{
open(devname,baud_rate,opt_parity,opt_csize,opt_flow,opt_stop);
}
void AsyncSerial::open(const std::string& devname, unsigned int baud_rate,
asio::serial_port_base::parity opt_parity,
asio::serial_port_base::character_size opt_csize,
asio::serial_port_base::flow_control opt_flow,
asio::serial_port_base::stop_bits opt_stop)
{
if(isOpen()) close();
setErrorStatus(true);//If an exception is thrown, error remains true
struct termios new_attributes;
speed_t speed;
int status;
// Open port
pimpl->fd=::open(devname.c_str(), O_RDWR | O_NOCTTY | O_NONBLOCK);
if (pimpl->fd<0) throw(boost::system::system_error(
boost::system::error_code(),"Failed to open port"));
// Set Port parameters.
status=tcgetattr(pimpl->fd,&new_attributes);
if(status<0 || !isatty(pimpl->fd))
{
::close(pimpl->fd);
throw(boost::system::system_error(
boost::system::error_code(),"Device is not a tty"));
}
new_attributes.c_iflag = IGNBRK;
new_attributes.c_oflag = 0;
new_attributes.c_lflag = 0;
new_attributes.c_cflag = (CS8 | CREAD | CLOCAL);//8 data bit,Enable receiver,Ignore modem
/* In non canonical mode (Ctrl-C and other disabled, no echo,...) VMIN and VTIME work this way:
if the function read() has'nt read at least VMIN chars it waits until has read at least VMIN
chars (even if VTIME timeout expires); once it has read at least vmin chars, if subsequent
chars do not arrive before VTIME expires, it returns error; if a char arrives, it resets the
timeout, so the internal timer will again start from zero (for the nex char,if any)*/
new_attributes.c_cc[VMIN]=1;// Minimum number of characters to read before returning error
new_attributes.c_cc[VTIME]=1;// Set timeouts in tenths of second
// Set baud rate
switch(baud_rate)
{
case 50:speed= B50; break;
case 75:speed= B75; break;
case 110:speed= B110; break;
case 134:speed= B134; break;
case 150:speed= B150; break;
case 200:speed= B200; break;
case 300:speed= B300; break;
case 600:speed= B600; break;
case 1200:speed= B1200; break;
case 1800:speed= B1800; break;
case 2400:speed= B2400; break;
case 4800:speed= B4800; break;
case 9600:speed= B9600; break;
case 19200:speed= B19200; break;
case 38400:speed= B38400; break;
case 57600:speed= B57600; break;
case 115200:speed= B115200; break;
case 230400:speed= B230400; break;
default:
{
::close(pimpl->fd);
throw(boost::system::system_error(
boost::system::error_code(),"Unsupported baud rate"));
}
}
cfsetospeed(&new_attributes,speed);
cfsetispeed(&new_attributes,speed);
//Make changes effective
status=tcsetattr(pimpl->fd, TCSANOW, &new_attributes);
if(status<0)
{
::close(pimpl->fd);
throw(boost::system::system_error(
boost::system::error_code(),"Can't set port attributes"));
}
//These 3 lines clear the O_NONBLOCK flag
status=fcntl(pimpl->fd, F_GETFL, 0);
if(status!=-1) fcntl(pimpl->fd, F_SETFL, status & ~O_NONBLOCK);
setErrorStatus(false);//If we get here, no error
pimpl->open=true; //Port is now open
thread t(bind(&AsyncSerial::doRead, this));
pimpl->backgroundThread.swap(t);
}
bool AsyncSerial::isOpen() const
{
return pimpl->open;
}
bool AsyncSerial::errorStatus() const
{
boost::lock_guard<boost::mutex> l(pimpl->errorMutex);
return pimpl->error;
}
void AsyncSerial::close()
{
if(!isOpen()) return;
pimpl->open=false;
::close(pimpl->fd); //The thread waiting on I/O should return
pimpl->backgroundThread.join();
if(errorStatus())
{
throw(boost::system::system_error(boost::system::error_code(),
"Error while closing the device"));
}
}
void AsyncSerial::write(const char *data, size_t size)
{
if(::write(pimpl->fd,data,size)!=size) setErrorStatus(true);
}
void AsyncSerial::write(const std::vector<char>& data)
{
if(::write(pimpl->fd,&data[0],data.size())!=data.size())
setErrorStatus(true);
}
void AsyncSerial::writeString(const std::string& s)
{
if(::write(pimpl->fd,&s[0],s.size())!=s.size()) setErrorStatus(true);
}
AsyncSerial::~AsyncSerial()
{
if(isOpen())
{
try {
close();
} catch(...)
{
//Don't throw from a destructor
}
}
}
void AsyncSerial::doRead()
{
//Read loop in spawned thread
for(;;)
{
int received=::read(pimpl->fd,pimpl->readBuffer,readBufferSize);
if(received<0)
{
if(isOpen()==false) return; //Thread interrupted because port closed
else {
setErrorStatus(true);
continue;
}
}
if(pimpl->callback) pimpl->callback(pimpl->readBuffer, received);
}
}
void AsyncSerial::readEnd(const boost::system::error_code& error,
size_t bytes_transferred)
{
//Not used
}
void AsyncSerial::doWrite()
{
//Not used
}
void AsyncSerial::writeEnd(const boost::system::error_code& error)
{
//Not used
}
void AsyncSerial::doClose()
{
//Not used
}
void AsyncSerial::setErrorStatus(bool e)
{
boost::lock_guard<boost::mutex> l(pimpl->errorMutex);
pimpl->error=e;
}
void AsyncSerial::setReadCallback(const boost::function<void (const char*, size_t)>& callback) {
pimpl->callback=callback;
}
void AsyncSerial::clearReadCallback()
{
pimpl->callback.clear();
}
#endif //__APPLE__
//
//Class CallbackAsyncSerial
//
CallbackAsyncSerial::CallbackAsyncSerial(): AsyncSerial()
{
}
CallbackAsyncSerial::CallbackAsyncSerial(const std::string& devname,
unsigned int baud_rate,
asio::serial_port_base::parity opt_parity,
asio::serial_port_base::character_size opt_csize,
asio::serial_port_base::flow_control opt_flow,
asio::serial_port_base::stop_bits opt_stop)
:AsyncSerial(devname,baud_rate,opt_parity,opt_csize,opt_flow,opt_stop)
{
}
void CallbackAsyncSerial::setCallback(const boost::function<void (const char*, size_t)>& callback)
{
setReadCallback(callback);
}
void CallbackAsyncSerial::clearCallback()
{
clearReadCallback();
}
CallbackAsyncSerial::~CallbackAsyncSerial()
{
clearReadCallback();
}