-
Notifications
You must be signed in to change notification settings - Fork 87
Expand file tree
/
Copy pathSerialPort.cpp
More file actions
1622 lines (1358 loc) · 55.3 KB
/
SerialPort.cpp
File metadata and controls
1622 lines (1358 loc) · 55.3 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
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @file SerialPort.cpp
* @brief 现代C++跨平台串口通信库实现
* @author CSerialPort Team
* @version 3.0.0
* @date 2026-01-01
*
* @copyright MIT License
*/
#include "SerialPort.h"
#include <algorithm>
#include <cstring>
#include <sstream>
#include <thread>
#if CSERIALPORT_PLATFORM_WINDOWS
#include <setupapi.h>
#pragma comment(lib, "setupapi.lib")
#elif CSERIALPORT_PLATFORM_LINUX
#include <sys/stat.h>
#include <glob.h>
#endif
namespace csp {
// ============================================================================
// 平台相关实现类
// ============================================================================
class SerialPort::Impl {
public:
Impl() = default;
~Impl() { close(); }
Impl(const Impl&) = delete;
Impl& operator=(const Impl&) = delete;
// ========================================================================
// 打开/关闭
// ========================================================================
VoidResult open(const std::string& portName, const SerialConfig& config) {
std::lock_guard<std::mutex> lock(mutex_);
if (isOpen_) {
return VoidResult(ErrorCode::AlreadyOpen, "Port is already open");
}
portName_ = portName;
config_ = config;
#if CSERIALPORT_PLATFORM_WINDOWS
std::string devicePath = "\\\\.\\" + portName;
handle_ = CreateFileA(
devicePath.c_str(),
GENERIC_READ | GENERIC_WRITE,
0,
nullptr,
OPEN_EXISTING,
FILE_FLAG_OVERLAPPED,
nullptr
);
if (handle_ == INVALID_HANDLE_VALUE) {
DWORD error = GetLastError();
if (error == ERROR_FILE_NOT_FOUND) {
return VoidResult(ErrorCode::PortNotFound, "Port not found: " + portName);
} else if (error == ERROR_ACCESS_DENIED) {
return VoidResult(ErrorCode::PermissionDenied, "Access denied: " + portName);
} else if (error == ERROR_SHARING_VIOLATION) {
return VoidResult(ErrorCode::PortBusy, "Port is busy: " + portName);
}
return VoidResult(ErrorCode::OpenFailed, "Failed to open port: " + portName);
}
readEvent_ = CreateEvent(nullptr, TRUE, FALSE, nullptr);
if (!readEvent_) {
closeInternal();
return VoidResult(ErrorCode::OpenFailed, "Failed to create read event");
}
writeEvent_ = CreateEvent(nullptr, TRUE, FALSE, nullptr);
if (!writeEvent_) {
closeInternal();
return VoidResult(ErrorCode::OpenFailed, "Failed to create write event");
}
shutdownEvent_ = CreateEvent(nullptr, TRUE, FALSE, nullptr);
if (!shutdownEvent_) {
closeInternal();
return VoidResult(ErrorCode::OpenFailed, "Failed to create shutdown event");
}
if (!SetupComm(handle_, static_cast<DWORD>(config.readBufferSize),
static_cast<DWORD>(config.writeBufferSize))) {
closeInternal();
return VoidResult(ErrorCode::ConfigFailed, "Failed to setup comm buffers");
}
#elif CSERIALPORT_PLATFORM_LINUX
fd_ = ::open(portName.c_str(), O_RDWR | O_NOCTTY | O_NONBLOCK);
if (fd_ < 0) {
if (errno == ENOENT) {
return VoidResult(ErrorCode::PortNotFound, "Port not found: " + portName);
} else if (errno == EACCES) {
return VoidResult(ErrorCode::PermissionDenied, "Access denied: " + portName);
} else if (errno == EBUSY) {
return VoidResult(ErrorCode::PortBusy, "Port is busy: " + portName);
}
return VoidResult(ErrorCode::OpenFailed, "Failed to open port: " + portName);
}
if (tcgetattr(fd_, &originalTermios_) != 0) {
::close(fd_);
fd_ = -1;
return VoidResult(ErrorCode::ConfigFailed, "Failed to get terminal attributes");
}
#endif
auto result = applyConfig(config);
if (!result) {
closeInternal();
return result;
}
isOpen_ = true;
statistics_.reset();
return VoidResult();
}
VoidResult close() {
std::lock_guard<std::mutex> lock(mutex_);
stopAsyncReceiveInternal();
closeInternal();
return VoidResult();
}
bool isOpen() const noexcept {
return isOpen_;
}
SerialConfig config() const noexcept {
return config_;
}
VoidResult setConfig(const SerialConfig& config) {
std::lock_guard<std::mutex> lock(mutex_);
if (!isOpen_) {
return VoidResult(ErrorCode::NotOpen, "Port is not open");
}
auto result = applyConfig(config);
if (result) {
config_ = config;
}
return result;
}
// ========================================================================
// 同步读取
// ========================================================================
Result<ByteBuffer> readInternal(size_t maxBytes, std::optional<Duration> timeout) {
if (!isOpen_) {
return Result<ByteBuffer>(ErrorCode::NotOpen, "Port is not open");
}
ByteBuffer buffer(maxBytes);
size_t bytesRead = 0;
Duration actualTimeout = timeout.value_or(config_.readTimeout);
#if CSERIALPORT_PLATFORM_WINDOWS
OVERLAPPED ov = {};
ov.hEvent = readEvent_;
ResetEvent(readEvent_);
DWORD dwBytesRead = 0;
BOOL result = ReadFile(handle_, buffer.data(), static_cast<DWORD>(maxBytes),
&dwBytesRead, &ov);
if (!result) {
if (GetLastError() == ERROR_IO_PENDING) {
DWORD waitResult = WaitForSingleObject(readEvent_,
static_cast<DWORD>(actualTimeout.count()));
if (waitResult == WAIT_TIMEOUT) {
CancelIo(handle_);
return Result<ByteBuffer>(ErrorCode::Timeout, "Read timeout");
} else if (waitResult == WAIT_OBJECT_0) {
if (!GetOverlappedResult(handle_, &ov, &dwBytesRead, FALSE)) {
statistics_.readErrors.fetch_add(1, std::memory_order_relaxed);
return Result<ByteBuffer>(ErrorCode::ReadFailed, "Read failed");
}
} else {
statistics_.readErrors.fetch_add(1, std::memory_order_relaxed);
return Result<ByteBuffer>(ErrorCode::ReadFailed, "Wait failed");
}
} else {
statistics_.readErrors.fetch_add(1, std::memory_order_relaxed);
return Result<ByteBuffer>(ErrorCode::ReadFailed, "Read failed");
}
}
bytesRead = dwBytesRead;
#elif CSERIALPORT_PLATFORM_LINUX
fd_set readfds;
FD_ZERO(&readfds);
FD_SET(fd_, &readfds);
struct timeval tv;
tv.tv_sec = actualTimeout.count() / 1000;
tv.tv_usec = (actualTimeout.count() % 1000) * 1000;
int selectResult = select(fd_ + 1, &readfds, nullptr, nullptr, &tv);
if (selectResult < 0) {
statistics_.readErrors.fetch_add(1, std::memory_order_relaxed);
return Result<ByteBuffer>(ErrorCode::ReadFailed, "Select failed");
} else if (selectResult == 0) {
return Result<ByteBuffer>(ErrorCode::Timeout, "Read timeout");
}
ssize_t result = ::read(fd_, buffer.data(), maxBytes);
if (result < 0) {
statistics_.readErrors.fetch_add(1, std::memory_order_relaxed);
return Result<ByteBuffer>(ErrorCode::ReadFailed, "Read failed");
}
bytesRead = static_cast<size_t>(result);
#endif
buffer.resize(bytesRead);
statistics_.bytesReceived.fetch_add(bytesRead, std::memory_order_relaxed);
if (bytesRead > 0) {
statistics_.updateLastActivity();
}
return Result<ByteBuffer>(std::move(buffer));
}
Result<ByteBuffer> read(size_t maxBytes, std::optional<Duration> timeout) {
std::lock_guard<std::mutex> lock(mutex_);
return readInternal(maxBytes, timeout);
}
Result<ByteBuffer> readExact(size_t exactBytes, std::optional<Duration> timeout) {
std::lock_guard<std::mutex> lock(mutex_);
ByteBuffer result;
result.reserve(exactBytes);
auto startTime = std::chrono::steady_clock::now();
Duration actualTimeout = timeout.value_or(config_.readTimeout);
while (result.size() < exactBytes) {
auto elapsed = std::chrono::duration_cast<Duration>(
std::chrono::steady_clock::now() - startTime);
if (elapsed >= actualTimeout) {
return Result<ByteBuffer>(ErrorCode::Timeout, "Read exact timeout");
}
Duration remainingTimeout = actualTimeout - elapsed;
size_t remaining = exactBytes - result.size();
auto readResult = readInternal(remaining, remainingTimeout);
if (!readResult) {
return readResult;
}
auto& data = readResult.value();
result.insert(result.end(), data.begin(), data.end());
}
return Result<ByteBuffer>(std::move(result));
}
Result<ByteBuffer> readUntilInternal(Byte delimiter, size_t maxBytes, std::optional<Duration> timeout) {
ByteBuffer result;
result.reserve(std::min(maxBytes, static_cast<size_t>(256)));
// 内部缓冲区用于批量读取
ByteBuffer readBuffer(128);
size_t bufferPos = 0;
size_t bufferLen = 0;
auto startTime = std::chrono::steady_clock::now();
Duration actualTimeout = timeout.value_or(config_.readTimeout);
while (result.size() < maxBytes) {
auto elapsed = std::chrono::duration_cast<Duration>(
std::chrono::steady_clock::now() - startTime);
if (elapsed >= actualTimeout) {
// 如果已经读取了一些数据,返回它们而不是报错
if (!result.empty()) {
break;
}
return Result<ByteBuffer>(ErrorCode::Timeout, "Read until timeout");
}
// 如果缓冲区中还有数据,先处理缓冲区
if (bufferPos < bufferLen) {
while (bufferPos < bufferLen && result.size() < maxBytes) {
Byte b = readBuffer[bufferPos++];
result.push_back(b);
if (b == delimiter) {
return Result<ByteBuffer>(std::move(result));
}
}
continue;
}
// 缓冲区为空,读取更多数据
Duration remainingTimeout = actualTimeout - elapsed;
size_t bytesToRead = std::min(readBuffer.size(), maxBytes - result.size());
auto readResult = readInternal(bytesToRead, remainingTimeout);
if (!readResult) {
if (readResult.error() == ErrorCode::Timeout && !result.empty()) {
break;
}
return readResult;
}
auto& data = readResult.value();
if (data.empty()) {
continue;
}
// 在读取的数据中查找分隔符
for (size_t i = 0; i < data.size() && result.size() < maxBytes; ++i) {
result.push_back(data[i]);
if (data[i] == delimiter) {
return Result<ByteBuffer>(std::move(result));
}
}
}
return Result<ByteBuffer>(std::move(result));
}
Result<ByteBuffer> readUntil(Byte delimiter, size_t maxBytes, std::optional<Duration> timeout) {
std::lock_guard<std::mutex> lock(mutex_);
return readUntilInternal(delimiter, maxBytes, timeout);
}
Result<std::string> readLine(size_t maxBytes, std::optional<Duration> timeout) {
std::lock_guard<std::mutex> lock(mutex_);
auto result = readUntilInternal('\n', maxBytes, timeout);
if (!result) {
return Result<std::string>(result.error(), result.errorMessage());
}
auto& data = result.value();
std::string line(data.begin(), data.end());
while (!line.empty() && (line.back() == '\n' || line.back() == '\r')) {
line.pop_back();
}
return Result<std::string>(std::move(line));
}
// ========================================================================
// 同步写入
// ========================================================================
Result<size_t> write(const Byte* data, size_t size, std::optional<Duration> timeout) {
std::lock_guard<std::mutex> lock(mutex_);
if (!isOpen_) {
return Result<size_t>(ErrorCode::NotOpen, "Port is not open");
}
if (data == nullptr || size == 0) {
return Result<size_t>(static_cast<size_t>(0));
}
Duration actualTimeout = timeout.value_or(config_.writeTimeout);
#if CSERIALPORT_PLATFORM_WINDOWS
OVERLAPPED ov = {};
ov.hEvent = writeEvent_;
ResetEvent(writeEvent_);
DWORD dwBytesWritten = 0;
BOOL result = WriteFile(handle_, data, static_cast<DWORD>(size),
&dwBytesWritten, &ov);
if (!result) {
if (GetLastError() == ERROR_IO_PENDING) {
DWORD waitResult = WaitForSingleObject(writeEvent_,
static_cast<DWORD>(actualTimeout.count()));
if (waitResult == WAIT_TIMEOUT) {
CancelIo(handle_);
return Result<size_t>(ErrorCode::Timeout, "Write timeout");
} else if (waitResult == WAIT_OBJECT_0) {
if (!GetOverlappedResult(handle_, &ov, &dwBytesWritten, FALSE)) {
statistics_.writeErrors.fetch_add(1, std::memory_order_relaxed);
return Result<size_t>(ErrorCode::WriteFailed, "Write failed");
}
} else {
statistics_.writeErrors.fetch_add(1, std::memory_order_relaxed);
return Result<size_t>(ErrorCode::WriteFailed, "Wait failed");
}
} else {
statistics_.writeErrors.fetch_add(1, std::memory_order_relaxed);
return Result<size_t>(ErrorCode::WriteFailed, "Write failed");
}
}
statistics_.bytesSent.fetch_add(dwBytesWritten, std::memory_order_relaxed);
if (dwBytesWritten > 0) {
statistics_.updateLastActivity();
}
return Result<size_t>(static_cast<size_t>(dwBytesWritten));
#elif CSERIALPORT_PLATFORM_LINUX
fd_set writefds;
FD_ZERO(&writefds);
FD_SET(fd_, &writefds);
struct timeval tv;
tv.tv_sec = actualTimeout.count() / 1000;
tv.tv_usec = (actualTimeout.count() % 1000) * 1000;
int selectResult = select(fd_ + 1, nullptr, &writefds, nullptr, &tv);
if (selectResult < 0) {
statistics_.writeErrors.fetch_add(1, std::memory_order_relaxed);
return Result<size_t>(ErrorCode::WriteFailed, "Select failed");
} else if (selectResult == 0) {
return Result<size_t>(ErrorCode::Timeout, "Write timeout");
}
ssize_t result = ::write(fd_, data, size);
if (result < 0) {
statistics_.writeErrors.fetch_add(1, std::memory_order_relaxed);
return Result<size_t>(ErrorCode::WriteFailed, "Write failed");
}
statistics_.bytesSent.fetch_add(result, std::memory_order_relaxed);
if (result > 0) {
statistics_.updateLastActivity();
}
return Result<size_t>(static_cast<size_t>(result));
#endif
}
Result<size_t> write(const ByteBuffer& data, std::optional<Duration> timeout) {
return write(data.data(), data.size(), timeout);
}
Result<size_t> write(const std::string& str, std::optional<Duration> timeout) {
return write(reinterpret_cast<const Byte*>(str.data()), str.size(), timeout);
}
Result<size_t> writeLine(const std::string& line, std::optional<Duration> timeout) {
std::string data = line + "\r\n";
return write(data, timeout);
}
// ========================================================================
// 异步操作
// ========================================================================
std::future<Result<ByteBuffer>> readAsync(size_t maxBytes) {
return std::async(std::launch::async, [this, maxBytes]() {
return read(maxBytes, std::nullopt);
});
}
std::future<Result<size_t>> writeAsync(ByteBuffer data) {
return std::async(std::launch::async, [this, data = std::move(data)]() {
return write(data, std::nullopt);
});
}
std::future<Result<size_t>> writeAsync(std::string str) {
return std::async(std::launch::async, [this, str = std::move(str)]() {
return write(str, std::nullopt);
});
}
// ========================================================================
// 回调模式
// ========================================================================
void setDataCallback(DataCallback callback) {
std::lock_guard<std::mutex> lock(callbackMutex_);
dataCallback_ = std::move(callback);
}
void setEventCallback(EventCallback callback) {
std::lock_guard<std::mutex> lock(callbackMutex_);
eventCallback_ = std::move(callback);
}
void setErrorCallback(ErrorCallback callback) {
std::lock_guard<std::mutex> lock(callbackMutex_);
errorCallback_ = std::move(callback);
}
VoidResult startAsyncReceive() {
std::lock_guard<std::mutex> lock(mutex_);
if (!isOpen_) {
return VoidResult(ErrorCode::NotOpen, "Port is not open");
}
if (asyncReceiving_) {
return VoidResult();
}
asyncReceiving_ = true;
#if CSERIALPORT_PLATFORM_WINDOWS
ResetEvent(shutdownEvent_);
#endif
receiveThread_ = std::thread(&Impl::receiveThreadFunc, this);
return VoidResult();
}
void stopAsyncReceive() {
std::lock_guard<std::mutex> lock(mutex_);
stopAsyncReceiveInternal();
}
bool isAsyncReceiving() const noexcept {
return asyncReceiving_;
}
// ========================================================================
// 缓冲区操作
// ========================================================================
Result<size_t> available() const {
if (!isOpen_) {
return Result<size_t>(ErrorCode::NotOpen, "Port is not open");
}
#if CSERIALPORT_PLATFORM_WINDOWS
COMSTAT comstat;
DWORD errors;
if (!ClearCommError(handle_, &errors, &comstat)) {
return Result<size_t>(ErrorCode::ReadFailed, "Failed to get available bytes");
}
return Result<size_t>(static_cast<size_t>(comstat.cbInQue));
#elif CSERIALPORT_PLATFORM_LINUX
int bytes = 0;
if (ioctl(fd_, FIONREAD, &bytes) < 0) {
return Result<size_t>(ErrorCode::ReadFailed, "Failed to get available bytes");
}
return Result<size_t>(static_cast<size_t>(bytes));
#endif
}
VoidResult flushInput() {
if (!isOpen_) {
return VoidResult(ErrorCode::NotOpen, "Port is not open");
}
#if CSERIALPORT_PLATFORM_WINDOWS
if (!PurgeComm(handle_, PURGE_RXCLEAR | PURGE_RXABORT)) {
return VoidResult(ErrorCode::ReadFailed, "Failed to flush input");
}
#elif CSERIALPORT_PLATFORM_LINUX
if (tcflush(fd_, TCIFLUSH) != 0) {
return VoidResult(ErrorCode::ReadFailed, "Failed to flush input");
}
#endif
return VoidResult();
}
VoidResult flushOutput() {
if (!isOpen_) {
return VoidResult(ErrorCode::NotOpen, "Port is not open");
}
#if CSERIALPORT_PLATFORM_WINDOWS
if (!PurgeComm(handle_, PURGE_TXCLEAR | PURGE_TXABORT)) {
return VoidResult(ErrorCode::WriteFailed, "Failed to flush output");
}
#elif CSERIALPORT_PLATFORM_LINUX
if (tcflush(fd_, TCOFLUSH) != 0) {
return VoidResult(ErrorCode::WriteFailed, "Failed to flush output");
}
#endif
return VoidResult();
}
VoidResult flush() {
auto result = flushInput();
if (!result) return result;
return flushOutput();
}
// ========================================================================
// 控制线
// ========================================================================
VoidResult setDTR(bool state) {
if (!isOpen_) {
return VoidResult(ErrorCode::NotOpen, "Port is not open");
}
#if CSERIALPORT_PLATFORM_WINDOWS
if (!EscapeCommFunction(handle_, state ? SETDTR : CLRDTR)) {
return VoidResult(ErrorCode::ConfigFailed, "Failed to set DTR");
}
#elif CSERIALPORT_PLATFORM_LINUX
int status;
if (ioctl(fd_, TIOCMGET, &status) < 0) {
return VoidResult(ErrorCode::ConfigFailed, "Failed to get modem status");
}
if (state) {
status |= TIOCM_DTR;
} else {
status &= ~TIOCM_DTR;
}
if (ioctl(fd_, TIOCMSET, &status) < 0) {
return VoidResult(ErrorCode::ConfigFailed, "Failed to set DTR");
}
#endif
return VoidResult();
}
VoidResult setRTS(bool state) {
if (!isOpen_) {
return VoidResult(ErrorCode::NotOpen, "Port is not open");
}
#if CSERIALPORT_PLATFORM_WINDOWS
if (!EscapeCommFunction(handle_, state ? SETRTS : CLRRTS)) {
return VoidResult(ErrorCode::ConfigFailed, "Failed to set RTS");
}
#elif CSERIALPORT_PLATFORM_LINUX
int status;
if (ioctl(fd_, TIOCMGET, &status) < 0) {
return VoidResult(ErrorCode::ConfigFailed, "Failed to get modem status");
}
if (state) {
status |= TIOCM_RTS;
} else {
status &= ~TIOCM_RTS;
}
if (ioctl(fd_, TIOCMSET, &status) < 0) {
return VoidResult(ErrorCode::ConfigFailed, "Failed to set RTS");
}
#endif
return VoidResult();
}
Result<bool> getCTS() const {
if (!isOpen_) {
return Result<bool>(ErrorCode::NotOpen, "Port is not open");
}
#if CSERIALPORT_PLATFORM_WINDOWS
DWORD status;
if (!GetCommModemStatus(handle_, &status)) {
return Result<bool>(ErrorCode::ReadFailed, "Failed to get modem status");
}
return Result<bool>((status & MS_CTS_ON) != 0);
#elif CSERIALPORT_PLATFORM_LINUX
int status;
if (ioctl(fd_, TIOCMGET, &status) < 0) {
return Result<bool>(ErrorCode::ReadFailed, "Failed to get modem status");
}
return Result<bool>((status & TIOCM_CTS) != 0);
#endif
}
Result<bool> getDSR() const {
if (!isOpen_) {
return Result<bool>(ErrorCode::NotOpen, "Port is not open");
}
#if CSERIALPORT_PLATFORM_WINDOWS
DWORD status;
if (!GetCommModemStatus(handle_, &status)) {
return Result<bool>(ErrorCode::ReadFailed, "Failed to get modem status");
}
return Result<bool>((status & MS_DSR_ON) != 0);
#elif CSERIALPORT_PLATFORM_LINUX
int status;
if (ioctl(fd_, TIOCMGET, &status) < 0) {
return Result<bool>(ErrorCode::ReadFailed, "Failed to get modem status");
}
return Result<bool>((status & TIOCM_DSR) != 0);
#endif
}
Result<bool> getCD() const {
if (!isOpen_) {
return Result<bool>(ErrorCode::NotOpen, "Port is not open");
}
#if CSERIALPORT_PLATFORM_WINDOWS
DWORD status;
if (!GetCommModemStatus(handle_, &status)) {
return Result<bool>(ErrorCode::ReadFailed, "Failed to get modem status");
}
return Result<bool>((status & MS_RLSD_ON) != 0);
#elif CSERIALPORT_PLATFORM_LINUX
int status;
if (ioctl(fd_, TIOCMGET, &status) < 0) {
return Result<bool>(ErrorCode::ReadFailed, "Failed to get modem status");
}
return Result<bool>((status & TIOCM_CD) != 0);
#endif
}
Result<bool> getRI() const {
if (!isOpen_) {
return Result<bool>(ErrorCode::NotOpen, "Port is not open");
}
#if CSERIALPORT_PLATFORM_WINDOWS
DWORD status;
if (!GetCommModemStatus(handle_, &status)) {
return Result<bool>(ErrorCode::ReadFailed, "Failed to get modem status");
}
return Result<bool>((status & MS_RING_ON) != 0);
#elif CSERIALPORT_PLATFORM_LINUX
int status;
if (ioctl(fd_, TIOCMGET, &status) < 0) {
return Result<bool>(ErrorCode::ReadFailed, "Failed to get modem status");
}
return Result<bool>((status & TIOCM_RI) != 0);
#endif
}
VoidResult sendBreak(Duration duration) {
if (!isOpen_) {
return VoidResult(ErrorCode::NotOpen, "Port is not open");
}
#if CSERIALPORT_PLATFORM_WINDOWS
if (!SetCommBreak(handle_)) {
return VoidResult(ErrorCode::WriteFailed, "Failed to set break");
}
std::this_thread::sleep_for(duration);
if (!ClearCommBreak(handle_)) {
return VoidResult(ErrorCode::WriteFailed, "Failed to clear break");
}
#elif CSERIALPORT_PLATFORM_LINUX
// Linux tcsendbreak: duration 0 sends break for 0.25-0.5 seconds
// For custom duration, we use TIOCSBRK/TIOCCBRK
if (duration.count() <= 0) {
if (tcsendbreak(fd_, 0) < 0) {
return VoidResult(ErrorCode::WriteFailed, "Failed to send break");
}
} else {
if (ioctl(fd_, TIOCSBRK, 0) < 0) {
return VoidResult(ErrorCode::WriteFailed, "Failed to set break");
}
std::this_thread::sleep_for(duration);
if (ioctl(fd_, TIOCCBRK, 0) < 0) {
return VoidResult(ErrorCode::WriteFailed, "Failed to clear break");
}
}
#endif
return VoidResult();
}
// ========================================================================
// 状态
// ========================================================================
std::string portName() const noexcept {
return portName_;
}
PortStatistics statistics() const noexcept {
return statistics_;
}
void resetStatistics() noexcept {
statistics_.reset();
}
// ========================================================================
// 静态方法
// ========================================================================
static std::vector<PortInfo> enumerate() {
std::vector<PortInfo> ports;
#if CSERIALPORT_PLATFORM_WINDOWS
// 使用 SetupAPI 枚举串口(更高效)
GUID guid = {0x86E0D1E0L, 0x8089, 0x11D0, {0x9C, 0xE4, 0x08, 0x00, 0x3E, 0x30, 0x1F, 0x73}};
HDEVINFO hDevInfo = SetupDiGetClassDevs(&guid, nullptr, nullptr, DIGCF_PRESENT);
if (hDevInfo != INVALID_HANDLE_VALUE) {
SP_DEVINFO_DATA devInfoData;
devInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
for (DWORD i = 0; SetupDiEnumDeviceInfo(hDevInfo, i, &devInfoData); ++i) {
// 获取端口名称
HKEY hKey = SetupDiOpenDevRegKey(hDevInfo, &devInfoData, DICS_FLAG_GLOBAL, 0, DIREG_DEV, KEY_READ);
if (hKey != INVALID_HANDLE_VALUE) {
char portName[256] = {0};
DWORD portNameSize = sizeof(portName);
DWORD type = 0;
if (RegQueryValueExA(hKey, "PortName", nullptr, &type,
reinterpret_cast<LPBYTE>(portName), &portNameSize) == ERROR_SUCCESS) {
// 只处理 COM 端口
if (strncmp(portName, "COM", 3) == 0) {
PortInfo info;
info.portName = portName;
// 获取设备描述
char description[256] = {0};
DWORD descSize = sizeof(description);
if (SetupDiGetDeviceRegistryPropertyA(hDevInfo, &devInfoData, SPDRP_FRIENDLYNAME,
nullptr, reinterpret_cast<PBYTE>(description),
descSize, nullptr)) {
info.description = description;
} else if (SetupDiGetDeviceRegistryPropertyA(hDevInfo, &devInfoData, SPDRP_DEVICEDESC,
nullptr, reinterpret_cast<PBYTE>(description),
descSize, nullptr)) {
info.description = description;
}
// 获取硬件 ID
char hardwareId[256] = {0};
DWORD hwIdSize = sizeof(hardwareId);
if (SetupDiGetDeviceRegistryPropertyA(hDevInfo, &devInfoData, SPDRP_HARDWAREID,
nullptr, reinterpret_cast<PBYTE>(hardwareId),
hwIdSize, nullptr)) {
info.hardwareId = hardwareId;
}
// 检查端口是否可用
std::string devicePath = "\\\\.\\" + info.portName;
HANDLE handle = CreateFileA(devicePath.c_str(), GENERIC_READ | GENERIC_WRITE,
0, nullptr, OPEN_EXISTING, 0, nullptr);
if (handle != INVALID_HANDLE_VALUE) {
CloseHandle(handle);
info.isAvailable = true;
} else {
info.isAvailable = (GetLastError() != ERROR_FILE_NOT_FOUND);
}
ports.push_back(info);
}
}
RegCloseKey(hKey);
}
}
SetupDiDestroyDeviceInfoList(hDevInfo);
}
// 如果 SetupAPI 没有找到任何端口,回退到注册表方法
if (ports.empty()) {
HKEY hKey;
if (RegOpenKeyExA(HKEY_LOCAL_MACHINE,
"HARDWARE\\DEVICEMAP\\SERIALCOMM",
0, KEY_READ, &hKey) == ERROR_SUCCESS) {
char valueName[256];
char valueData[256];
DWORD valueNameSize, valueDataSize, valueType;
DWORD index = 0;
while (true) {
valueNameSize = sizeof(valueName);
valueDataSize = sizeof(valueData);
LONG result = RegEnumValueA(hKey, index++, valueName, &valueNameSize,
nullptr, &valueType,
reinterpret_cast<LPBYTE>(valueData),
&valueDataSize);
if (result != ERROR_SUCCESS) break;
if (valueType == REG_SZ) {
PortInfo info;
info.portName = valueData;
info.description = valueName;
// 检查端口是否可用
std::string devicePath = "\\\\.\\" + info.portName;
HANDLE handle = CreateFileA(devicePath.c_str(), GENERIC_READ | GENERIC_WRITE,
0, nullptr, OPEN_EXISTING, 0, nullptr);
if (handle != INVALID_HANDLE_VALUE) {
CloseHandle(handle);
info.isAvailable = true;
} else {
info.isAvailable = (GetLastError() != ERROR_FILE_NOT_FOUND);
}
ports.push_back(info);
}
}
RegCloseKey(hKey);
}
}
#elif CSERIALPORT_PLATFORM_LINUX
const char* patterns[] = {
"/dev/ttyS*",
"/dev/ttyUSB*",
"/dev/ttyACM*",
"/dev/ttyAMA*",
"/dev/rfcomm*",
nullptr
};
for (int i = 0; patterns[i] != nullptr; ++i) {
glob_t globResult;
if (glob(patterns[i], GLOB_NOSORT, nullptr, &globResult) == 0) {
for (size_t j = 0; j < globResult.gl_pathc; ++j) {
PortInfo info;
info.portName = globResult.gl_pathv[j];
int fd = ::open(info.portName.c_str(), O_RDWR | O_NOCTTY | O_NONBLOCK);
if (fd >= 0) {
::close(fd);
info.isAvailable = true;
} else {
info.isAvailable = (errno == EBUSY);
}
ports.push_back(info);
}
globfree(&globResult);
}
}
#endif
return ports;
}
static bool exists(const std::string& portName) {
#if CSERIALPORT_PLATFORM_WINDOWS
std::string devicePath = "\\\\.\\" + portName;
HANDLE handle = CreateFileA(
devicePath.c_str(),
GENERIC_READ | GENERIC_WRITE,
0,
nullptr,
OPEN_EXISTING,
0,
nullptr
);
if (handle != INVALID_HANDLE_VALUE) {
CloseHandle(handle);
return true;
}
return GetLastError() == ERROR_ACCESS_DENIED;
#elif CSERIALPORT_PLATFORM_LINUX
struct stat st;
return stat(portName.c_str(), &st) == 0 && S_ISCHR(st.st_mode);
#endif
}
private:
void closeInternal() {
#if CSERIALPORT_PLATFORM_WINDOWS
if (handle_ != INVALID_HANDLE_VALUE) {
CloseHandle(handle_);
handle_ = INVALID_HANDLE_VALUE;
}
if (readEvent_) {
CloseHandle(readEvent_);
readEvent_ = nullptr;
}
if (writeEvent_) {
CloseHandle(writeEvent_);
writeEvent_ = nullptr;
}
if (shutdownEvent_) {
CloseHandle(shutdownEvent_);
shutdownEvent_ = nullptr;
}
#elif CSERIALPORT_PLATFORM_LINUX
if (fd_ >= 0) {
tcsetattr(fd_, TCSANOW, &originalTermios_);
::close(fd_);
fd_ = -1;