-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathceserial.h
660 lines (579 loc) · 16 KB
/
ceserial.h
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
// File: ceserial.h
// Description: ceSerial communication class for Windows and Linux
// WebSite: http://cool-emerald.blogspot.sg/2017/05/serial-port-programming-in-c-with.html
// MIT License (https://opensource.org/licenses/MIT)
// Copyright (c) 2018 Yan Naing Aye
// References
// https://en.wikibooks.org/wiki/Serial_Programming/termios
// http://www.silabs.com/documents/public/application-notes/an197.pdf
// https://msdn.microsoft.com/en-us/library/ff802693.aspx
// http://www.cplusplus.com/forum/unices/10491/
#ifndef CESERIAL_H
#define CESERIAL_H
#include <string>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#if defined(_WIN64) || defined(__WIN32__) || defined(_WIN32) || defined(WIN32) || defined(__WINDOWS__) || defined(__TOS_WIN__) || defined(__CYGWIN__)
#ifndef CE_WINDOWS
#define CE_WINDOWS
#endif
#elif defined(__linux__) || defined(unix) || defined(__unix) || defined(__unix__)
#ifndef CE_LINUX
#define CE_LINUX
#endif
#else
#ifndef CE_NOS
#define CE_NOS
#endif
#endif
#ifdef CE_WINDOWS
#include <windows.h>
#endif
class ceSerial {
private:
char rxchar;
std::string port;
long baud;
long dsize;
char parity;
float stopbits;
bool stdbaud;
#ifdef CE_WINDOWS
HANDLE hComm; //handle
OVERLAPPED osReader;
OVERLAPPED osWrite;
BOOL fWaitingOnRead;
COMMTIMEOUTS timeouts_ori;
#else
long fd;//serial_fd
#endif
public:
static void Delay(unsigned long ms);
ceSerial();
ceSerial(std::string Device, long BaudRate, long DataSize, char ParityType, float NStopBits);
~ceSerial();
long Open(void);//return 0 if success
void Close();
char ReadChar(bool& success);//return read char if success
bool WriteChar(const char ch);////return success flag
bool Write(const char *data);//write null terminated string and return success flag
bool Write(const char *data,long n);
bool SetRTS(bool value);//return success flag
bool SetDTR(bool value);//return success flag
bool GetCTS(bool& success);
bool GetDSR(bool& success);
bool GetRI(bool& success);
bool GetCD(bool& success);
bool IsOpened();
void SetPortName(std::string Port);
std::string GetPort();
void SetBaudRate(long baudrate);
long GetBaudRate();
void SetDataSize(long nbits);
long GetDataSize();
void SetParity(char p);
char GetParity();
void SetStopBits(float nbits);
float GetStopBits();
};
//-----------------------------------------------------------------------------
#ifdef CE_WINDOWS
#define READ_TIMEOUT 10 // milliseconds
#else
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
#include <sys/ioctl.h>
#include <linux/serial.h>
#endif
inline void ceSerial::Delay(unsigned long ms) {
#ifdef CE_WINDOWS
Sleep(ms);
#else
usleep(ms*1000);
#endif
}
inline ceSerial::ceSerial() :
#ifdef CE_WINDOWS
ceSerial("\\\\.\\COM1", 9600, 8, 'N', 1)
#else
ceSerial("/dev/ttyS0", 9600, 8, 'N', 1)
#endif
{
}
inline ceSerial::ceSerial(std::string Device, long BaudRate,long DataSize,char ParityType,float NStopBits):stdbaud(true) {
#ifdef CE_WINDOWS
hComm = INVALID_HANDLE_VALUE;
#else
fd = -1;
#endif // defined
SetBaudRate(BaudRate);
SetDataSize(DataSize);
SetParity(ParityType);
SetStopBits(NStopBits);
SetPortName(Device);
}
inline ceSerial::~ceSerial() {
Close();
}
inline void ceSerial::SetPortName(std::string Device) {
port = Device;
}
inline std::string ceSerial::GetPort() {
return port;
}
inline void ceSerial::SetDataSize(long nbits) {
if ((nbits < 5) || (nbits > 8)) nbits = 8;
dsize=nbits;
}
inline long ceSerial::GetDataSize() {
return dsize;
}
inline void ceSerial::SetParity(char p) {
if ((p != 'N') && (p != 'E') && (p != 'O')) {
#ifdef CE_WINDOWS
if ((p != 'M') && (p != 'S')) p = 'N';
#else
p = 'N';
#endif
}
parity = p;
}
inline char ceSerial::GetParity() {
return parity;
}
inline void ceSerial::SetStopBits(float nbits) {
if (nbits >= 2) stopbits = 2;
#ifdef CE_WINDOWS
else if(nbits >= 1.5) stopbits = 1.5;
#endif
else stopbits = 1;
}
inline float ceSerial::GetStopBits() {
return stopbits;
}
#ifdef CE_WINDOWS
inline void ceSerial::SetBaudRate(long baudrate) {
stdbaud = true;
if (baudrate == 110) baud = CBR_110;
else if (baudrate == 300) baud = CBR_300;
else if (baudrate == 600) baud = CBR_600;
else if (baudrate == 1200) baud = CBR_1200;
else if (baudrate == 2400) baud = CBR_2400;
else if (baudrate == 4800) baud = CBR_4800;
else if (baudrate == 9600) baud = CBR_9600;
else if (baudrate == 14400) baud = CBR_14400;
else if (baudrate == 19200) baud = CBR_19200;
else if (baudrate == 38400) baud = CBR_38400;
else if (baudrate == 57600) baud = CBR_57600;
else if (baudrate == 115200) baud = CBR_115200;
else if (baudrate == 128000) baud = CBR_128000;
else if (baudrate == 256000) baud = CBR_256000;
else {
baud = baudrate;
stdbaud = false;
}
}
inline long ceSerial::GetBaudRate() {
return baud;
}
inline long ceSerial::Open() {
if (IsOpened()) return 0;
#ifdef UNICODE
std::wstring wtext(port.begin(),port.end());
#else
std::string wtext = port;
#endif
hComm = CreateFile(wtext.c_str(),
GENERIC_READ | GENERIC_WRITE,
0,
0,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED,
0);
if (hComm == INVALID_HANDLE_VALUE) {return -1;}
if (PurgeComm(hComm, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR) == 0) {return -1;}//purge
//get initial state
DCB dcbOri;
bool fSuccess;
fSuccess = GetCommState(hComm, &dcbOri);
if (!fSuccess) {return -1;}
DCB dcb1 = dcbOri;
dcb1.BaudRate = baud;
if (parity == 'E') dcb1.Parity = EVENPARITY;
else if (parity == 'O') dcb1.Parity = ODDPARITY;
else if (parity == 'M') dcb1.Parity = MARKPARITY;
else if (parity == 'S') dcb1.Parity = SPACEPARITY;
else dcb1.Parity = NOPARITY;
dcb1.ByteSize = (BYTE)dsize;
if(stopbits==2) dcb1.StopBits = TWOSTOPBITS;
else if (stopbits == 1.5) dcb1.StopBits = ONE5STOPBITS;
else dcb1.StopBits = ONESTOPBIT;
dcb1.fOutxCtsFlow = false;
dcb1.fOutxDsrFlow = false;
dcb1.fOutX = false;
dcb1.fDtrControl = DTR_CONTROL_DISABLE;
dcb1.fRtsControl = RTS_CONTROL_DISABLE;
fSuccess = SetCommState(hComm, &dcb1);
this->Delay(60);
if (!fSuccess) {return -1;}
fSuccess = GetCommState(hComm, &dcb1);
if (!fSuccess) {return -1;}
osReader = { 0 };// Create the overlapped event.
// Must be closed before exiting to avoid a handle leak.
osReader.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
if (osReader.hEvent == NULL) {return -1;}// Error creating overlapped event; abort.
fWaitingOnRead = FALSE;
osWrite = { 0 };
osWrite.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
if (osWrite.hEvent == NULL) {return -1;}
if (!GetCommTimeouts(hComm, &timeouts_ori)) { return -1; } // Error getting time-outs.
COMMTIMEOUTS timeouts;
timeouts.ReadIntervalTimeout = 20;
timeouts.ReadTotalTimeoutMultiplier = 15;
timeouts.ReadTotalTimeoutConstant = 100;
timeouts.WriteTotalTimeoutMultiplier = 15;
timeouts.WriteTotalTimeoutConstant = 100;
if (!SetCommTimeouts(hComm, &timeouts)) { return -1;} // Error setting time-outs.
return 0;
}
inline void ceSerial::Close() {
if (IsOpened())
{
SetCommTimeouts(hComm, &timeouts_ori);
CloseHandle(osReader.hEvent);
CloseHandle(osWrite.hEvent);
CloseHandle(hComm);//close comm port
hComm = INVALID_HANDLE_VALUE;
}
}
inline bool ceSerial::IsOpened() {
if(hComm == INVALID_HANDLE_VALUE) return false;
else return true;
}
inline bool ceSerial::Write(const char *data) {
if (!IsOpened()) {
return false;
}
BOOL fRes;
DWORD dwWritten;
long n = strlen(data);
if (n < 0) n = 0;
else if(n > 1024) n = 1024;
// Issue write.
if (!WriteFile(hComm, data, n, &dwWritten, &osWrite)) {
// WriteFile failed, but it isn't delayed. Report error and abort.
if (GetLastError() != ERROR_IO_PENDING) {fRes = FALSE;}
else {// Write is pending.
if (!GetOverlappedResult(hComm, &osWrite, &dwWritten, TRUE)) fRes = FALSE;
else fRes = TRUE;// Write operation completed successfully.
}
}
else fRes = TRUE;// WriteFile completed immediately.
return fRes;
}
inline bool ceSerial::Write(const char *data,long n) {
if (!IsOpened()) {
return false;
}
BOOL fRes;
DWORD dwWritten;
if (n < 0) n = 0;
else if(n > 1024) n = 1024;
// Issue write.
if (!WriteFile(hComm, data, n, &dwWritten, &osWrite)) {
// WriteFile failed, but it isn't delayed. Report error and abort.
if (GetLastError() != ERROR_IO_PENDING) {fRes = FALSE;}
else {// Write is pending.
if (!GetOverlappedResult(hComm, &osWrite, &dwWritten, TRUE)) fRes = FALSE;
else fRes = TRUE;// Write operation completed successfully.
}
}
else fRes = TRUE;// WriteFile completed immediately.
return fRes;
}
inline bool ceSerial::WriteChar(const char ch) {
char s[2];
s[0]=ch;
s[1]=0;//null terminated
return Write(s);
}
inline char ceSerial::ReadChar(bool& success) {
success = false;
if (!IsOpened()) {return 0;}
DWORD dwRead;
DWORD length=1;
BYTE* data = (BYTE*)(&rxchar);
//the creation of the overlapped read operation
if (!fWaitingOnRead) {
// Issue read operation.
if (!ReadFile(hComm, data, length, &dwRead, &osReader)) {
if (GetLastError() != ERROR_IO_PENDING) { /*Error*/}
else { fWaitingOnRead = TRUE; /*Waiting*/}
}
else {if(dwRead==length) success = true;}//success
}
//detection of the completion of an overlapped read operation
DWORD dwRes;
if (fWaitingOnRead) {
dwRes = WaitForSingleObject(osReader.hEvent, READ_TIMEOUT);
switch (dwRes)
{
// Read completed.
case WAIT_OBJECT_0:
if (!GetOverlappedResult(hComm, &osReader, &dwRead, FALSE)) {/*Error*/ }
else {
if (dwRead == length) success = true;
fWaitingOnRead = FALSE;
// Reset flag so that another opertion can be issued.
}// Read completed successfully.
break;
case WAIT_TIMEOUT:
// Operation isn't complete yet.
break;
default:
// Error in the WaitForSingleObject;
break;
}
}
return rxchar;
}
inline bool ceSerial::SetRTS(bool value) {
bool r = false;
if (IsOpened()) {
if (value) {
if (EscapeCommFunction(hComm, SETRTS)) r = true;
}
else {
if (EscapeCommFunction(hComm, CLRRTS)) r = true;
}
}
return r;
}
inline bool ceSerial::SetDTR(bool value) {
bool r = false;
if (IsOpened()) {
if (value) {
if (EscapeCommFunction(hComm, SETDTR)) r = true;
}
else {
if (EscapeCommFunction(hComm, CLRDTR)) r = true;
}
}
return r;
}
inline bool ceSerial::GetCTS(bool& success) {
success = false;
bool r = false;
if (IsOpened()) {
DWORD dwModemStatus;
if (GetCommModemStatus(hComm, &dwModemStatus)){
r = MS_CTS_ON & dwModemStatus;
success = true;
}
}
return r;
}
inline bool ceSerial::GetDSR(bool& success) {
success = false;
bool r = false;
if (IsOpened()) {
DWORD dwModemStatus;
if (GetCommModemStatus(hComm, &dwModemStatus)) {
r = MS_DSR_ON & dwModemStatus;
success = true;
}
}
return r;
}
inline bool ceSerial::GetRI(bool& success) {
success = false;
bool r = false;
if (IsOpened()) {
DWORD dwModemStatus;
if (GetCommModemStatus(hComm, &dwModemStatus)) {
r = MS_RING_ON & dwModemStatus;
success = true;
}
}
return r;
}
inline bool ceSerial::GetCD(bool& success) {
success = false;
bool r = false;
if (IsOpened()) {
DWORD dwModemStatus;
if (GetCommModemStatus(hComm, &dwModemStatus)) {
r = MS_RLSD_ON & dwModemStatus;
success = true;
}
}
return r;
}
#else //for POSIX
inline long ceSerial::Open(void) {
struct serial_struct serinfo;
struct termios settings;
memset(&settings, 0, sizeof(settings));
settings.c_iflag = 0;
settings.c_oflag = 0;
settings.c_cflag = CREAD | CLOCAL;//see termios.h for more information
if(dsize==5) settings.c_cflag |= CS5;//no change
else if (dsize == 6) settings.c_cflag |= CS6;
else if (dsize == 7) settings.c_cflag |= CS7;
else settings.c_cflag |= CS8;
if(stopbits==2) settings.c_cflag |= CSTOPB;
if(parity!='N') settings.c_cflag |= PARENB;
if (parity == 'O') settings.c_cflag |= PARODD;
settings.c_lflag = 0;
settings.c_cc[VMIN] = 1;
settings.c_cc[VTIME] = 0;
fd = open(port.c_str(), O_RDWR | O_NONBLOCK);
if (fd == -1) {
return -1;
}
if (!stdbaud) {
// serial driver to interpret the value B38400 differently
serinfo.reserved_char[0] = 0;
if (ioctl(fd, TIOCGSERIAL, &serinfo) < 0) { return -1;}
serinfo.flags &= ~ASYNC_SPD_MASK;
serinfo.flags |= ASYNC_SPD_CUST;
serinfo.custom_divisor = (serinfo.baud_base + (baud / 2)) / baud;
if (serinfo.custom_divisor < 1) serinfo.custom_divisor = 1;
if (ioctl(fd, TIOCSSERIAL, &serinfo) < 0) { return -1; }
if (ioctl(fd, TIOCGSERIAL, &serinfo) < 0) { return -1; }
if (serinfo.custom_divisor * baud != serinfo.baud_base) {
/*
warnx("actual baudrate is %d / %d = %f\n",
serinfo.baud_base, serinfo.custom_divisor,
(float)serinfo.baud_base / serinfo.custom_divisor);
*/
}
cfsetospeed(&settings, B38400);
cfsetispeed(&settings, B38400);
}
else {
cfsetospeed(&settings, baud);
cfsetispeed(&settings, baud);
}
tcsetattr(fd, TCSANOW, &settings);
int flags = fcntl(fd, F_GETFL, 0);
fcntl(fd, F_SETFL, flags | O_NONBLOCK);
if (!stdbaud) {
// driver to interpret B38400 as 38400 baud again
ioctl(fd, TIOCGSERIAL, &serinfo);
serinfo.flags &= ~ASYNC_SPD_MASK;
ioctl(fd, TIOCSSERIAL, &serinfo);
}
return 0;
}
inline void ceSerial::Close() {
if(IsOpened()) close(fd);
fd=-1;
}
inline bool ceSerial::IsOpened() {
if(fd== (-1)) return false;
else return true;
}
inline void ceSerial::SetBaudRate(long baudrate) {
stdbaud = true;
if (baudrate == 0) baud = B0;
else if (baudrate == 50) baud = B50;
else if (baudrate == 75) baud = B75;
else if (baudrate == 110) baud = B110;
else if (baudrate == 134) baud = B134;
else if (baudrate == 150) baud = B150;
else if (baudrate == 200) baud = B200;
else if (baudrate == 300) baud = B300;
else if (baudrate == 600) baud = B600;
else if (baudrate == 1200) baud = B1200;
else if (baudrate == 2400) baud = B2400;
else if (baudrate == 4800) baud = B4800;
else if (baudrate == 9600) baud = B9600;
else if (baudrate == 19200) baud = B19200;
else if (baudrate == 38400) baud = B38400;
else if (baudrate == 57600) baud = B57600;
else if (baudrate == 115200) baud = B115200;
else if (baudrate == 230400) baud = B230400;
else {
baud = baudrate;
stdbaud = false;
}
}
inline long ceSerial::GetBaudRate() {
return baud;
}
inline char ceSerial::ReadChar(bool& success) {
success=false;
if (!IsOpened()) {return 0; }
success=read(fd, &rxchar, 1)==1;
return rxchar;
}
inline bool ceSerial::Write(const char *data) {
if (!IsOpened()) {return false; }
long n = strlen(data);
if (n < 0) n = 0;
else if(n > 1024) n = 1024;
return (write(fd, data, n)==n);
}
inline bool ceSerial::Write(const char *data,long n) {
if (!IsOpened()) {return false; }
if (n < 0) n = 0;
else if(n > 1024) n = 1024;
return (write(fd, data, n)==n);
}
inline bool ceSerial::WriteChar(const char ch) {
char s[2];
s[0]=ch;
s[1]=0;//null terminated
return Write(s);
}
inline bool ceSerial::SetRTS(bool value) {
long RTS_flag = TIOCM_RTS;
bool success=true;
if (value) {//Set RTS pin
if (ioctl(fd, TIOCMBIS, &RTS_flag) == -1) success=false;
}
else {//Clear RTS pin
if (ioctl(fd, TIOCMBIC, &RTS_flag) == -1) success=false;
}
return success;
}
inline bool ceSerial::SetDTR(bool value) {
long DTR_flag = TIOCM_DTR;
bool success=true;
if (value) {//Set DTR pin
if (ioctl(fd, TIOCMBIS, &DTR_flag) == -1) success=false;
}
else {//Clear DTR pin
if (ioctl(fd, TIOCMBIC, &DTR_flag) == -1) success=false;
}
return success;
}
inline bool ceSerial::GetCTS(bool& success) {
success=true;
long status;
if(ioctl(fd, TIOCMGET, &status)== -1) success=false;
return ((status & TIOCM_CTS) != 0);
}
inline bool ceSerial::GetDSR(bool& success) {
success=true;
long status;
if(ioctl(fd, TIOCMGET, &status)== -1) success=false;
return ((status & TIOCM_DSR) != 0);
}
inline bool ceSerial::GetRI(bool& success) {
success=true;
long status;
if(ioctl(fd, TIOCMGET, &status)== -1) success=false;
return ((status & TIOCM_RI) != 0);
}
inline bool ceSerial::GetCD(bool& success) {
success=true;
long status;
if(ioctl(fd, TIOCMGET, &status)== -1) success=false;
return ((status & TIOCM_CD) != 0);
}
#endif
#endif // CESERIAL_H