-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathserialport.cpp
705 lines (592 loc) · 17.5 KB
/
serialport.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
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
/*
Copyright 2012-2014 Benjamin Vedder benjamin@vedder.se
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <time.h>
#include <signal.h>
#include <errno.h>
#include <QtDebug>
#include <cstdio> /* Standard input/output definitions */
#include <unistd.h> /* UNIX standard function definitions */
#include <fcntl.h> /* File control definitions */
#include <errno.h> /* Error number definitions */
#include <termios.h> /* POSIX terminal control definitions */
#include <linux/serial.h>
#include <sys/ioctl.h>
#include <iostream>
#include "serialport.h"
SerialPort::SerialPort(QObject *parent) :
QThread(parent)
{
mIsOpen = false;
mSettings.dataBits = DATA_8;
mSettings.parity = PARITY_NONE;
mSettings.stopBits = STOP_1;
mSettings.baudrate = 115200;
mBufferSize = 32768;
mReadBuffer = new char[mBufferSize];
mBufferRead = 0;
mBufferWrite = 0;
mCaptureBytes = 0;
mCaptureBuffer = 0;
mCaptureWrite = 0;
}
SerialPort::~SerialPort()
{
closePort();
delete mReadBuffer;
//std::cout << "SerialPort destructor called";
}
int SerialPort::openPort(
const QString& port,
int baudrate,
SerialDataBits dataBits,
SerialStopBits stopBits,
SerialParity parity)
{
if (mIsOpen) {
closePort();
}
mFd = open(port.toLocal8Bit().data(), O_RDWR | O_NOCTTY | O_NDELAY);
if (mFd == -1) {
qCritical() << "Opening serial port failed.";
return -1;
}
mIsOpen = true;
// No-blocking reads
fcntl(mFd, F_SETFL, FNDELAY);
struct termios options;
if (0 != tcgetattr(mFd, &options)) {
qCritical() << "Reading serial port options failed.";
return -2;
}
// Enable the receiver and set local mode...
options.c_cflag |= CLOCAL | CREAD;
// Raw input
options.c_lflag &= ~(ICANON|ECHO|ECHOE|ECHOK|ECHONL|ISIG);
// Disable flow control
options.c_cflag &= ~CRTSCTS;
options.c_iflag &= ~(IXON|IXOFF|IXANY);
// ???
/*set up other port settings*/
options.c_cflag |= CREAD|CLOCAL;
options.c_lflag &= (~(ICANON|ECHO|ECHOE|ECHOK|ECHONL|ISIG));
options.c_iflag &= (~(INPCK|IGNPAR|PARMRK|ISTRIP|ICRNL|IXANY));
options.c_oflag &= (~OPOST);
options.c_cc[VMIN] = 0;
#ifdef _POSIX_VDISABLE // Is a disable character available on this system?
// Some systems allow for per-device disable-characters, so get the
// proper value for the configured device
const long vdisable = ::fpathconf(mFd, _PC_VDISABLE);
options.c_cc[VINTR] = vdisable;
options.c_cc[VQUIT] = vdisable;
options.c_cc[VSTART] = vdisable;
options.c_cc[VSTOP] = vdisable;
options.c_cc[VSUSP] = vdisable;
#endif //_POSIX_VDISABLE
//Set the new options for the port...
if (0 != tcsetattr(mFd, TCSANOW, &options)) {
qCritical() << "Writing serial port options failed.";
closePort();
return -3;
}
if (false == setDataBits(dataBits)) {
qCritical() << "Setting data bits failed.";
closePort();
return -4;
}
if (false == setStopBits(stopBits)) {
qCritical() << "Setting stopbits failed.";
closePort();
return -5;
}
if (false == setParity(parity)) {
qCritical() << "Setting parity faield.";
closePort();
return -6;
}
if (false == setBaudrate(baudrate)) {
qCritical() << "Setting baudrate failed.";
closePort();
return -7;
}
mAbort = false;
start(LowPriority);
return 0;
}
bool SerialPort::isOpen()
{
return mIsOpen;
}
void SerialPort::closePort()
{
struct termios options;
tcgetattr(mFd, &options);
options.c_cc[VTIME] = 1;
options.c_cc[VMIN] = 0;
tcsetattr(mFd, TCSANOW, &options);
mMutex.lock();
mAbort = true;
mCondition.wakeOne();
mMutex.unlock();
wait();
mMutex.lock();
if (mIsOpen) {
close(mFd);
mIsOpen = false;
}
mMutex.unlock();
}
bool SerialPort::setBaudrate(int baudrate)
{
if (!mIsOpen) {
qCritical() << "Serial port not open.";
return false;
}
speed_t baud = 0;
switch (baudrate) {
case 50: baud = B50; break;
case 75: baud = B75; break;
case 110: baud = B110; break;
case 134: baud = B134; break;
case 150: baud = B150; break;
case 200: baud = B200; break;
case 300: baud = B300; break;
case 600: baud = B600; break;
case 1200: baud = B1200; break;
case 1800: baud = B1800; break;
case 2400: baud = B2400; break;
case 4800: baud = B4800; break;
case 9600: baud = B9600; break;
case 19200: baud = B19200; break;
case 38400: baud = B38400; break;
case 57600: baud = B57600; break;
case 115200: baud = B115200; break;
case 230400: baud = B230400; break;
case 460800: baud = B460800; break;
case 500000: baud = B500000; break;
case 576000: baud = B576000; break;
case 921600: baud = B921600; break;
case 1000000: baud = B1000000; break;
case 1152000: baud = B1152000; break;
case 1500000: baud = B1500000; break;
case 2000000: baud = B2000000; break;
case 2500000: baud = B2500000; break;
case 3000000: baud = B3000000; break;
case 3500000: baud = B3500000; break;
case 4000000: baud = B4000000; break;
default: baud = 0; break;
}
struct termios options;
if (0 != tcgetattr(mFd, &options)) {
qCritical() << "Reading serial port options failed.";
return false;
}
serial_struct ser_info;
if (0 == baud) {
if (0 != ioctl(mFd, TIOCGSERIAL, &ser_info)) {
qCritical() << "Reading ser_info struct failed. Try a standard baudrate.";
return false;
}
ser_info.flags &= ~ASYNC_SPD_MASK;
ser_info.flags |= ASYNC_SPD_CUST | ASYNC_LOW_LATENCY;
ser_info.custom_divisor = ser_info.baud_base / baudrate;
qDebug() << "Baud base: " << ser_info.baud_base;
cfsetspeed(&options, B38400);
if (0 != tcsetattr(mFd, TCSANOW, &options)) {
qCritical() << "Writing serial port options failed";
return false;
}
if (0 != ioctl(mFd, TIOCSSERIAL, &ser_info)) {
qCritical() << "Writing ser_info struct failed";
return false;
}
qDebug() << "Custom type baudrate set";
} else {
cfsetspeed(&options, baud);
if (0 != tcsetattr(mFd, TCSANOW, &options)) {
qCritical() << "Writing serial port options failed";
return false;
}
qDebug() << "Standard type baudrate set";
if (0 != ioctl(mFd, TIOCGSERIAL, &ser_info)) {
qWarning() << "Reading ser_info struct failed.";
} else {
ser_info.flags &= ~ASYNC_SPD_CUST;
ser_info.custom_divisor = 0;
qDebug() << "Baud base: " << ser_info.baud_base;
if (0 != ioctl(mFd, TIOCSSERIAL, &ser_info)) {
qCritical() << "Writing ser_info struct failed";
}
}
}
mSettings.baudrate = baudrate;
return true;
}
bool SerialPort::setDataBits(SerialDataBits dataBits)
{
if (!mIsOpen) {
qCritical() << "Serial port not open.";
return false;
}
struct termios options;
if (0 != tcgetattr(mFd, &options)) {
qCritical() << "Reading serial port options failed.";
return false;
}
options.c_cflag &= ~CSIZE; /* Mask the character size bits */
switch (dataBits) {
case DATA_5:
options.c_cflag |= CS5;
break;
case DATA_6:
options.c_cflag |= CS6;
break;
case DATA_7:
options.c_cflag |= CS7;
break;
default:
options.c_cflag |= CS8;
break;
}
if (0 != tcsetattr(mFd, TCSANOW, &options)) {
qCritical() << "Writing serial port options failed.";
return false;
}
mSettings.dataBits = dataBits;
return true;
}
bool SerialPort::setStopBits(SerialStopBits stopBits)
{
if (!mIsOpen) {
qCritical() << "Serial port not open.";
return false;
}
struct termios options;
if (0 != tcgetattr(mFd, &options)) {
qCritical() << "Reading serial port options failed.";
return false;
}
switch (stopBits) {
case STOP_2:
options.c_cflag |= CSTOPB;
break;
default:
options.c_cflag &= ~CSTOPB;
break;
}
if (0 != tcsetattr(mFd, TCSANOW, &options)) {
qCritical() << "Writing serial port options failed.";
return false;
}
mSettings.stopBits = stopBits;
return true;
}
bool SerialPort::setParity(SerialParity parity)
{
if (!mIsOpen) {
qCritical() << "Serial port not open.";
return false;
}
struct termios options;
if (0 != tcgetattr(mFd, &options)) {
qCritical() << "Reading serial port options failed.";
return false;
}
switch (parity) {
case PARITY_EVEN:
options.c_cflag |= PARENB;
options.c_cflag &= ~PARODD;
break;
case PARITY_ODD:
options.c_cflag |= PARENB;
options.c_cflag |= PARODD;
break;
default:
options.c_cflag &= ~PARENB;
break;
}
if (0 != tcsetattr(mFd, TCSANOW, &options)) {
qCritical() << "Writing serial port options failed.";
return false;
}
mSettings.parity = parity;
return true;
}
bool SerialPort::readByte(char &byte)
{
if (!mIsOpen) {
qCritical() << "Serial port not open.";
return false;
}
{
QMutexLocker locker(&mMutex);
if (mBufferRead == mBufferWrite) {
return false;
}
char tmp = mReadBuffer[mBufferRead];
mBufferRead++;
if (mBufferRead == mBufferSize) {
mBufferRead = 0;
}
byte = tmp;
return true;
}
}
int SerialPort::readBytes(char* buffer, int bytes)
{
if (!mIsOpen) {
qCritical() << "Serial port not open.";
return -1;
}
{
QMutexLocker locker(&mMutex);
for (int i = 0;i < bytes;i++) {
if (mBufferRead == mBufferWrite) {
return i;
}
buffer[i] = mReadBuffer[mBufferRead];
mBufferRead++;
if (mBufferRead == mBufferSize) {
mBufferRead = 0;
}
}
}
return bytes;
}
int SerialPort::readString(QString& string, int length)
{
if (!mIsOpen) {
qCritical() << "Serial port not open.";
return -1;
}
string = "";
QMutexLocker locker(&mMutex);
for (int i = 0;i < length;i++) {
if (mBufferRead == mBufferWrite) {
return i;
}
if ('\0' != mReadBuffer[mBufferRead]) {
string.append(mReadBuffer[mBufferRead]);
}
mBufferRead++;
if (mBufferRead == mBufferSize) {
mBufferRead = 0;
}
}
return length;
}
QByteArray SerialPort::readAll()
{
if (!mIsOpen) {
qCritical() << "Serial port not open.";
return 0;
}
int len = bytesAvailable();
char data[len];
readBytes(data, len);
QByteArray bytes;
bytes.clear();
bytes.append(data, len);
return bytes;
}
int SerialPort::writeData(const char *data, int length, bool block)
{
if (!mIsOpen) {
qCritical() << "Serial port not open.";
return -2;
}
int res = 0;
int written = 0;
fd_set set;
timespec timeout;
if (block) {
while (length) {
FD_ZERO(&set); /* clear the set */
FD_SET(mFd, &set); /* add our file descriptor to the set */
timeout.tv_sec = 0;
timeout.tv_nsec = 1000000;
res = pselect(mFd + 1, NULL, &set, NULL, &timeout, NULL);
if(res < 0) {
qCritical().nospace() << "PSelect failed in writeData (" << res << "), ignoring";
//return res;
} else if(res == 0) {
// Timeout
} else {
res = write(mFd, data + written, length);
if (res >= 0) {
length -= res;
written += res;
} else {
qCritical().nospace() << "Writing to serial port failed (" << res << "), ignoring";
//return res;
}
}
if (!mIsOpen) {
qCritical() << "Serial port closed during write";
return -2;
}
}
return written;
} else {
return write(mFd, data, length);
}
}
bool SerialPort::writeByte(char byte, bool block)
{
if (!mIsOpen) {
qCritical() << "Serial port not open.";
return false;
}
if (1 == writeData(&byte, 1, block)) {
return true;
}
return false;
}
int SerialPort::bytesAvailable()
{
if (!mIsOpen) {
qCritical() << "Serial port not open.";
return -1;
}
{
QMutexLocker locker(&mMutex);
if (mBufferRead <= mBufferWrite) {
return mBufferWrite - mBufferRead;
} else {
return (mBufferSize - 1) - mBufferRead + mBufferWrite;
}
}
}
bool SerialPort::writeString(const QString& string, bool block)
{
if (string.length() == writeData(string.toLocal8Bit().data(), string.length(), block)) {
return true;
} else {
return false;
}
}
int SerialPort::captureBytes(char *buffer, int num, int timeoutMs, const QString& preTransmit)
{
if (!mIsOpen) {
qCritical() << "Serial port not open.";
return -1;
}
{
QMutexLocker locker(&mMutex);
mCaptureBuffer = buffer;
mCaptureBytes = num;
mCaptureWrite = 0;
}
if (preTransmit.length() > 0) {
if (!writeString(preTransmit)) {
return -2;
}
}
mMutex.lock();
mCondition.wait(&mMutex, timeoutMs);
mMutex.unlock();
{
QMutexLocker locker(&mMutex);
mCaptureBytes = 0;
return mCaptureWrite;
}
}
int SerialPort::captureBytes(char *buffer, int num, int timeoutMs, const char *preTransmit, int preTransLen)
{
if (!mIsOpen) {
qCritical() << "Serial port not open.";
return -1;
}
{
QMutexLocker locker(&mMutex);
mCaptureBuffer = buffer;
mCaptureBytes = num;
mCaptureWrite = 0;
}
if (preTransLen > 0) {
if (0 > writeData(preTransmit, preTransLen)) {
return -2;
}
}
mMutex.lock();
mCondition.wait(&mMutex, timeoutMs);
mMutex.unlock();
{
QMutexLocker locker(&mMutex);
mCaptureBytes = 0;
return mCaptureWrite;
}
}
void SerialPort::run()
{
unsigned char buffer[1024];
int res = 0;
int failed_reads = 0;
fd_set set;
timespec timeout;
while (false == mAbort) {
FD_ZERO(&set); /* clear the set */
FD_SET(mFd, &set); /* add our file descriptor to the set */
timeout.tv_sec = 0;
timeout.tv_nsec = 10000000;
res = pselect(mFd + 1, &set, NULL, NULL, &timeout, NULL);
if(res < 0) {
qWarning() << "Select failed in read thread";
} else if(res == 0) {
// Timeout
} else {
res = read(mFd, buffer, 1024);
if (res > 0) {
failed_reads = 0;
QMutexLocker locker(&mMutex);
for (int i = 0;i < res;i++) {
if (mCaptureBytes > 0) {
if (mCaptureBuffer != 0) {
mCaptureBuffer[mCaptureWrite] = buffer[i];
mCaptureWrite++;
}
mCaptureBytes--;
if (mCaptureBytes == 0) {
mCondition.wakeOne();
}
} else {
mReadBuffer[mBufferWrite] = buffer[i];
mBufferWrite++;
if (mBufferWrite == mBufferSize) {
mBufferWrite = 0;
}
Q_EMIT serial_data_available();
}
}
} else {
if (res < 0) {
qCritical().nospace() << "Reading failed. MSG: " << strerror(errno);
} else {
qCritical().nospace() << "Reading serial port returned 0";
}
failed_reads++;
if (failed_reads > 3) {
QMutexLocker locker(&mMutex);
if (mIsOpen) {
close(mFd);
mIsOpen = false;
}
mAbort = true;
qCritical().nospace() << "Too many consecutive failed reads. Closing port.";
Q_EMIT serial_port_error(res);
return;
}
}
}
}
}