-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserial.cpp
More file actions
981 lines (871 loc) · 19.2 KB
/
serial.cpp
File metadata and controls
981 lines (871 loc) · 19.2 KB
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
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
#include "serial.h"
#include <filesystem>
Serial::Serial() : Serial(
#ifdef WINDOWS
"\\\\.\\COM7",
#else
"/dev/ttyUSB0",
#endif
9600, 8, 'N', 1)
{
}
/**
* Creates an instance of the Serial Class for serial communication.
* Sets the configs accordingly.
* @device: The portname.
* @bRate: The baud rate.
* @dSize: The data size.
* @pType: THe parity type.
* @sBits: The number of stop bits.
*/
Serial::Serial(std::string device, long bRate, long dSize, char pType, float sBits)
{
// Initially, handler and port file descriptor is invalid until port is opened.
#ifdef WINDOWS
handler = INVALID_HANDLE_VALUE;
#else
serialFd = -1;
#endif
setPortName(device);
setBaudRate(bRate);
setDataSize(dSize);
setParity(pType);
setStopBits(sBits);
}
/**
* Closes the serial communication port.
*/
Serial::~Serial()
{
Close();
}
/**
* setPortName - Sets the portName variable.
* @device: The string to be set as the port name.
* Returns: void.
*/
void Serial::setPortName(std::string device)
{
portName = device;
}
/**
* setDataSize - Sets the dataSize variable.
* @dSize: The value to be set as the data size.
* Returns: void.
*/
void Serial::setDataSize(long dSize)
{
// Data size cannot be less than 5 or greater than 8.
dataSize = ((dSize < 5) || (dSize > 8)) ? 8 : dSize;
}
/**
* setParity - Sets the parity variable. Could be:
* N - Parity None, O - Parity Odd, E - Parity Even,
* M - Parity Mark, or S - Parity Space.
* @pType; The character to be set as the parity type.
* Returns: void.
*/
void Serial::setParity(char pType)
{
if ((pType == 'N') || (pType == 'E') || (pType == 'O'))
parity = pType;
else
{
#ifdef WINDOWS
parity = ((pType == 'M') || (pType == 'S')) ? pType : 'N';
#else
parity = 'N';
#endif
}
}
/**
* setStopBits: Sets the stopBIts variable. Could be 2 or 1 (default). Maybe 1.5? for Windows
* @sBits: The float to set as the stop bits.
* Returns: void.
*/
void Serial::setStopBits(float sBits)
{
stopBits = (sBits == 2) ? 2 : 1;
}
/**
* getPortName: Returns the portName used in communication.
* Returns: portName.
*/
std::string Serial::getPortName()
{
return portName;
}
/**
* getDataSize - Returns the dataSize in communication.
* Returns: dataSize.
*/
long Serial::getDataSize()
{
return dataSize;
}
/**
* getParity - Returns the parity used in communication.
* Returns: parity.
*/
char Serial::getParity()
{
return parity;
}
float Serial::getStopBIts()
{
return stopBits;
}
/**
* getBaudRate: Returns the baud rate used in communication.
* Returns: baudRate.
*/
long Serial::getBaudRate()
{
return baudRate;
}
// Definition of some functions that are specific to Windows OS.
#ifdef WINDOWS
/**
* setBaudRate - Sets baudRate variable.
* Also sets stdBaud to true if bRate is one of the standard ones. Otherwise false.
* Returns: void.
*/
void Serial::setBaudRate(long bRate)
{
stdBaud = true;
switch (bRate)
{
case (110):
baudRate = CBR_110;
break;
case (300):
baudRate = CBR_300;
break;
case (600):
baudRate = CBR_600;
break;
case (1200):
baudRate = CBR_1200;
break;
case (2400):
baudRate = CBR_2400;
break;
case (4800):
baudRate = CBR_4800;
break;
case (9600):
baudRate = CBR_9600;
break;
case (14400):
baudRate = CBR_14400;
break;
case (19200):
baudRate = CBR_19200;
break;
case (38400):
baudRate = CBR_38400;
break;
case (57600):
baudRate = CBR_57600;
break;
case (115200):
baudRate = CBR_115200;
break;
case (128000):
baudRate = CBR_128000;
break;
case (256000):
baudRate = CBR_256000;
break;
default:
baudRate = bRate;
stdBaud = false;
}
}
/**
* isOpened - Checks if communication port is open.
* Returns: true, if the port is open. Otherwise false.
*/
bool Serial::isOpened()
{
return (handler != INVALID_HANDLE_VALUE);
}
/**
* Open - Opens comm. port; Sets comm. parameters; Creates read/write overlapped events; and Sets timeouts.
* Returns: 0 on success, otherwise -1.
*/
int Serial::Open()
{
if (isOpened())
return 0;
#ifdef UNICODE
std::wstring wtext(portName.begin(), portName.end());
#else
std::string wtext = portName;
#endif
// Open the port file.
handler = CreateFile(
wtext.c_str(),
GENERIC_READ | GENERIC_WRITE,
0,
0,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED,
0);
// Check that the file was opened successfully. Return -1 if not.
if (handler == INVALID_HANDLE_VALUE)
{
if (GetLastError() == ERROR_FILE_NOT_FOUND)
printf("ERROR: Handle was not attached. Reason: %s not available\n", portName);
else
std::cout << "Error in OPEN!!!" << std::endl;
return (-1);
}
// Purge Communication Buffers.
if (!PurgeComm(handler, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR))
return (-1);
// Get current state of serial communication port .
DCB DCBParameters;
if (!GetCommState(handler, &DCBParameters))
return (-1);
// Set desired communication parameters: BaudRate, pARITY, DataSize,...
// Set Baud Rate.
DCBParameters.BaudRate = baudRate;
// Set Parity.
if (parity == 'N')
DCBParameters.Parity = NOPARITY;
else if (parity == 'E')
DCBParameters.Parity = EVENPARITY;
else if (parity == 'O')
DCBParameters.Parity = ODDPARITY;
else if (parity == 'M')
DCBParameters.Parity = MARKPARITY;
else
DCBParameters.Parity = SPACEPARITY;
// Set Data Size.
DCBParameters.ByteSize = (BYTE)dataSize;
// Set Stop Bits.
DCBParameters.StopBits = (stopBits == 2) ? TWOSTOPBITS : ONESTOPBIT;
// Disable CTS, DSR, XON/XOFF, DTR, RTS flow control and control signal settings.
DCBParameters.fOutxCtsFlow = false;
DCBParameters.fOutxDsrFlow = false;
DCBParameters.fOutX = false;
DCBParameters.fDtrControl = DTR_CONTROL_DISABLE;
DCBParameters.fRtsControl = RTS_CONTROL_DISABLE;
if (!SetCommState(handler, &DCBParameters))
return (-1);
this->Delay(ARDUINO_WAIT_TIME);
// Setup Overlapped Events for read and write.
osRead = {0};
osRead.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
if (osRead.hEvent == NULL)
return (-1);
fWaitOnRead = FALSE;
osWrite = {0};
osWrite.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
if (osWrite.hEvent == NULL)
return (-1);
// Set Read and write timeouts?
// Get original timeouts and save in origTimeouts.
if (!GetCommTimeouts(handler, &origTimeouts))
return (-1);
COMMTIMEOUTS timeouts;
timeouts.ReadIntervalTimeout = 20;
timeouts.ReadTotalTimeoutMultiplier = 15;
timeouts.ReadTotalTimeoutConstant = 100;
timeouts.WriteTotalTimeoutMultiplier = 15;
timeouts.WriteTotalTimeoutConstant = 100;
if (!SetCommTimeouts(handler, &timeouts))
return (-1);
return (0);
}
/**
* Close - Closes communication port; Reverts timeout settings; and Closes Read/Write events.
* Returns: void.
*/
void Serial::Close()
{
if (isOpened())
{
// Set timeout settings back to original.
SetCommTimeouts(handler, &origTimeouts);
// Close REad and Write Events to avoid handle leak.
CloseHandle(osRead.hEvent);
CloseHandle(osWrite.hEvent);
// Close communication port.
CloseHandle(handler);
handler = INVALID_HANDLE_VALUE;
}
}
/**
* Read - Reads from a serial comm port into a buffer.
* @success: Flag to be set as true when read operation is successful.
* Returns: Returns a buffer containing the data read.
*/
char *Serial::Read(bool &success)
{
success = false;
if (!isOpened())
{
return 0;
}
DWORD dwRead;
DWORD length = 11;
BYTE *data = (BYTE *)(&rxdata);
// Overlapped read operation
if (!fWaitOnRead)
{
// Issue read operation.
if (!ReadFile(handler, data, length, &dwRead, &osRead))
{
std::cout << "Here" << std::endl;
if (GetLastError() != ERROR_IO_PENDING)
{ /*Error*/
// std::cout << "ERROR_IO_PENDING" << std::endl;
}
else
{
// std::cout << "Waiting" << std::endl;
fWaitOnRead = TRUE; /*Waiting*/
}
}
else
{
success = true;
} // success
}
// Detect completion of an overlapped read operation
DWORD dwRes;
if (fWaitOnRead)
{
dwRes = WaitForSingleObject(osRead.hEvent, READ_TIMEOUT);
switch (dwRes)
{
// Read completed.
case WAIT_OBJECT_0:
if (!GetOverlappedResult(handler, &osRead, &dwRead, FALSE))
{ /*Error*/
}
else
{
if (dwRead == length)
success = true;
fWaitOnRead = 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;
}
}
// std::cout << "Done" << rxdata << std::endl;
return rxdata;
}
int Serial::readSerialPort(char *buffer, unsigned int buf_size)
{
DWORD bytesRead;
unsigned int toRead = 0;
ClearCommError(handler, &errors, &status);
if (this->status.cbInQue > 0)
{
if (status.cbInQue > buf_size)
{
toRead = buf_size;
}
else
toRead = status.cbInQue;
}
if (ReadFile(handler, buffer, toRead, &bytesRead, NULL))
return bytesRead;
return 0;
}
// std::vector<char> Serial::ReadString(bool &success)
//{
// success = false;
// if (!isOpened())
//{
// return std::vector<char>(); // Return an empty vector if port is not open
//}
//
// const int bufferSize = 1024; // Adjust buffer size as needed
// std::vector<char> buffer(bufferSize); // Buffer to store the read data
// DWORD bytesRead = 0;
// The creation of the overlapped read operation
// if (!fWaitOnRead)
//{
// Issue read operation
// if (!ReadFile(handler, buffer.data(), bufferSize, &bytesRead, &osRead))
//{
// if (GetLastError() != ERROR_IO_PENDING)
//{
// Error occurred
// return std::vector<char>();
//}
// else
//{
// fWaitOnRead = TRUE; // Waiting
//}
//}
// else
//{
// success = true; // Read completed successfully
// return std::vector<char>(buffer.begin(), buffer.begin() + bytesRead);
//}
//}
// Detection of the completion of an overlapped read operation
// DWORD dwRes;
// if (fWaitOnRead)
//{
// dwRes = WaitForSingleObject(osRead.hEvent, READ_TIMEOUT);
// switch (dwRes)
// {
// Read completed
// case WAIT_OBJECT_0:
// if (!GetOverlappedResult(handler, &osRead, &bytesRead, FALSE))
//{
// Error occurred
// return std::vector<char>();
//}
// else
//{
// success = true; // Read completed successfully
// fWaitOnRead = FALSE;
// return std::vector<char>(buffer.begin(), buffer.begin() + bytesRead);
//}
// break;
// case WAIT_TIMEOUT:
// Operation isn't complete yet
// break;
// default:
// Error in the WaitForSingleObject
// break;
//}
//}
// return std::vector<char>(); // Return an empty vector if no data is read
//}
bool Serial::Write(char *buffer, int length)
{
if (!isOpened())
return (false);
BOOL wSuccess = true;
DWORD bytesWritten;
length = std::clamp(length, 0, 1024);
if (!WriteFile(handler, buffer, length, &bytesWritten, &osWrite))
{
// If WriteFile failed, check if write is pending or there is no delay.
if (GetLastError() != ERROR_IO_PENDING)
wSuccess = false;
else
{
if (!GetOverlappedResult(handler, &osWrite, &bytesWritten, TRUE))
wSuccess = false;
else
wSuccess = true;
}
}
return wSuccess;
}
bool Serial::setRTS(bool value)
{
if (isOpened())
{
if (value)
{
if (EscapeCommFunction(handler, SETRTS))
return (true);
}
else
{
if (EscapeCommFunction(handler, CLRRTS))
return (true);
}
}
return (false);
}
bool Serial::setDTR(bool value)
{
if (isOpened())
{
if (value)
{
if (EscapeCommFunction(handler, SETDTR))
return (true);
}
else
{
if (EscapeCommFunction(handler, CLRDTR))
return (true);
}
}
return (false);
}
bool Serial::getCTS(bool &success)
{
success = false;
if (isOpened())
{
DWORD dwModemStatus;
if (GetCommModemStatus(handler, &dwModemStatus))
{
success = true;
return (MS_CTS_ON & dwModemStatus);
}
}
return false;
}
bool Serial::getDSR(bool &success)
{
success = false;
if (isOpened())
{
DWORD dwModemStatus;
if (GetCommModemStatus(handler, &dwModemStatus))
{
success = true;
return (MS_DSR_ON & dwModemStatus);
}
}
return (false);
}
bool Serial::getRI(bool &success)
{
success = false;
if (isOpened())
{
DWORD dwModemStatus;
if (GetCommModemStatus(handler, &dwModemStatus))
{
success = true;
return (MS_RING_ON & dwModemStatus);
}
}
return (false);
}
bool Serial::getCD(bool &success)
{
success = false;
if (isOpened())
{
DWORD dwModemStatus;
if (GetCommModemStatus(handler, &dwModemStatus))
{
success = true;
return (MS_RLSD_ON & dwModemStatus);
}
}
return (false);
}
bool SelectComPort() // added function to find the present serial
{
char lpTargetPath[5000]; // buffer to store the path of the COMPORTS
bool gotPort = false; // in case the port is not found
for (int i = 0; i < 255; i++) // checking ports from COM0 to COM255
{
std::string str = "COM" + std::to_string(i); // converting to COM0, COM1, COM2
DWORD test = QueryDosDevice(str.c_str(), lpTargetPath, 5000);
// Test the return value and error if any
if (test != 0) // QueryDosDevice returns zero if it didn't find an object
{
std::cout << str << ": " << lpTargetPath << std::endl;
gotPort = true;
}
if (::GetLastError() == ERROR_INSUFFICIENT_BUFFER)
{
}
}
return gotPort;
}
#else // Functionality for Linux.
bool Serial::isOpened()
{
return (serialFd != -1);
}
bool Serial::configureTermios()
{
// Get port attributes.
if (tcgetattr(serialFd, &tty) != 0)
{
std::cerr << "Error getting serial port attributes: "
<< strerror(errno) << std::endl;
return false;
}
// memset (&tty, 0, sizeof(tty));
// Reconfigure some port settings.
// Control Modes.
// Parity.
if (parity != 'N')
tty.c_cflag |= PARENB;
if (parity == 'O')
tty.c_cflag |= PARODD;
if (parity == 'N')
tty.c_cflag &= PARENB;
// Stop Bits.
if (stopBits == 2)
tty.c_cflag |= CSTOPB;
else
tty.c_cflag &= ~CSTOPB; // 1 stop bit.
// Data Size.
tty.c_cflag &= ~CSIZE; // Clear data size.
if (dataSize == 5)
tty.c_cflag |= CS5;
else if (dataSize == 6)
tty.c_cflag |= CS6;
else if (dataSize == 7)
tty.c_cflag |= CS7;
else
tty.c_cflag |= CS8; // 8 bits per byte.
tty.c_cflag &= ~CRTSCTS; // Disable hardware flow control.
tty.c_cflag |= CREAD | CLOCAL; // Turn on READ &
// ignore ctrl lines.
// Local Modes.
tty.c_lflag &= ~ICANON; // Disable canonical mode.
tty.c_lflag &= ~ECHO; // DIsable echo.
tty.c_lflag &= ~ECHOE; // Disable erasure.
tty.c_lflag &= ~ECHONL; // DIsable new-line echo.
tty.c_lflag &= ~ISIG; // Disable interpretation of INTR, QUIT and SUSP
// Input MOdes.
tty.c_iflag &= ~(IXON | IXOFF | IXANY); // Disable software flow control.
// DIsable any special handling of received bytes.
tty.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL);
tty.c_oflag &= ~OPOST; // Prevent special intepretation of output bytes.
tty.c_oflag &= ~ONLCR; // Prevent conversion of newline to carriage return/ Line feed.
tty.c_cc[VTIME] = 1; // Timeout for non-blocking read.
tty.c_cc[VMIN] = 0; // MInimum number of characters to read.
// Set baud rate.
if (!stdBaud)
// Do Something if not standard baudRate.
;
cfsetispeed(&tty, baudRate);
cfsetospeed(&tty, baudRate);
// Save new configurations.
if (tcsetattr(serialFd, TCSANOW, &tty) != 0)
{
std::cerr << "Error setting serial port attributes: "
<< strerror(errno) << std::endl;
return false;
}
return true;
}
int Serial::Open()
{
serialFd = open(portName.c_str(), O_RDWR);
if (serialFd == -1)
{
std::cerr << "Error opening serial port: "
<< strerror(errno) << std::endl;
return (-1);
}
// Sleep for a while as arduino uno resets when port is opened.
sleep(3);
if (configureTermios())
return (0);
else
return (-1);
}
void Serial::Close()
{
if (isOpened())
close(serialFd);
serialFd = -1;
}
void Serial::setBaudRate(long bRate)
{
stdBaud = true;
switch (bRate)
{
case 0:
baudRate = B0;
break;
case 50:
baudRate = B50;
break;
case 75:
baudRate = B75;
break;
case 110:
baudRate = B110;
break;
case 134:
baudRate = B134;
break;
case 150:
baudRate = B150;
break;
case 200:
baudRate = B200;
break;
case 300:
baudRate = B300;
break;
case 600:
baudRate = B600;
break;
case 1200:
baudRate = B1200;
break;
case 2400:
baudRate = B2400;
break;
case 4800:
baudRate = B4800;
break;
case 9600:
baudRate = B9600;
break;
case 19200:
baudRate = B19200;
break;
case 38400:
baudRate = B38400;
break;
case 57600:
baudRate = B57600;
break;
case 115200:
baudRate = B115200;
break;
case 230400:
baudRate = B230400;
break;
default:
baudRate = bRate;
stdBaud = false;
break;
}
}
std::string Serial::Read(unsigned int numChars, bool &rSuccess)
{
char buffer[numChars];
int bytesRead = read(serialFd, buffer, numChars);
if (bytesRead == -1)
{
rSuccess = false; // Read operation failed
return ""; // Return empty string
}
rSuccess = true; // Read operation succeeded
return std::string(buffer, bytesRead); // Convert char buffer to string
}
std::vector<char> Serial::Read(unsigned int numChars, bool &rsuccess, int x)
{
rsuccess = false;
std::vector<char> buffer(numChars);
if (!isOpened())
return (buffer);
// Read data from serial port
int bytesRead = read(serialFd, buffer.data(), numChars);
if (bytesRead == -1)
{
// Failed to read from serial port
return (buffer);
}
rsuccess = true;
return (buffer);
}
bool Serial::Write(char *buffer, int length)
{
if (!isOpened())
return (false);
length = std::clamp(length, 0, 1024);
return (write(serialFd, buffer, length) == length);
}
bool Serial::setRTS(bool value)
{
long RTS_flag = TIOCM_RTS;
if (value)
{ // Set RTS pin
if (ioctl(serialFd, TIOCMBIS, &RTS_flag) == -1)
return (false);
}
else
{ // Clear RTS pin
if (ioctl(serialFd, TIOCMBIC, &RTS_flag) == -1)
return (false);
}
return (true);
}
bool Serial::setDTR(bool value)
{
long DTR_flag = TIOCM_DTR;
if (value)
{ // Set DTR pin
if (ioctl(serialFd, TIOCMBIS, &DTR_flag) == -1)
return (false);
}
else
{ // Clear DTR pin
if (ioctl(serialFd, TIOCMBIC, &DTR_flag) == -1)
return (false);
}
return (true);
}
bool Serial::getCTS(bool &success)
{
success = true;
long status;
if (ioctl(serialFd, TIOCMGET, &status) == -1)
success = false;
return ((status & TIOCM_CTS) != 0);
}
bool Serial::getDSR(bool &success)
{
success = true;
long status;
if (ioctl(serialFd, TIOCMGET, &status) == -1)
success = false;
return ((status & TIOCM_DSR) != 0);
}
bool Serial::getRI(bool &success)
{
success = true;
long status;
if (ioctl(serialFd, TIOCMGET, &status) == -1)
success = false;
return ((status & TIOCM_RI) != 0);
}
bool Serial::getCD(bool &success)
{
success = true;
long status;
if (ioctl(serialFd, TIOCMGET, &status) == -1)
success = false;
return ((status & TIOCM_CD) != 0);
}
using std::cout;
namespace fs = std::filesystem;
std::vector<std::string> getAvailablePorts()
{
std::vector<std::string> port_names;
fs::path p("/dev/serial/by-id");
try
{
if (!exists(p))
{
throw std::runtime_error(p.generic_string() + " does not exist");
}
else
{
for (auto de : fs::directory_iterator(p))
{
if (is_symlink(de.symlink_status()))
{
fs::path symlink_points_at = read_symlink(de);
fs::path canonical_path = fs::canonical(p / symlink_points_at);
// cout << canonical_path.generic_string() << std::endl;
port_names.push_back(canonical_path.generic_string());
}
}
}
}
catch (const fs::filesystem_error &ex)
{
cout << ex.what() << '\n';
throw ex;
}
std::sort(port_names.begin(), port_names.end());
return port_names;
}
#endif