-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathSerialPort.h
1391 lines (1192 loc) · 44 KB
/
SerialPort.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
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
/*
Module : SerialPort.h
Purpose: Interface for a set of C++ wrapper classes for serial ports
Created: PJN / 31-05-1999
History: PJN / 03-06-1999 1. Fixed problem with code using CancelIo which does not exist on 95.
2. Fixed leaks which can occur in sample app when an exception is thrown
PJN / 16-06-1999 1. Fixed a bug whereby CString::ReleaseBuffer was not being called in
CSerialException::GetErrorMessage
PJN / 29-09-1999 1. Fixed a simple copy and paste bug in CSerialPort::SetDTR
PJN / 08-05-2000 1. Fixed an unreferrenced variable in CSerialPort::GetOverlappedResult in VC 6
PJN / 10-12-2000 1. Made class destructor virtual
PJN / 15-01-2001 1. Attach method now also allows you to specify whether the serial port
is being attached to in overlapped mode
2. Removed some ASSERTs which were unnecessary in some of the functions
3. Updated the Read method which uses OVERLAPPED IO to also return the bytes
read. This allows calls to WriteFile with a zeroed overlapped structure (This
is required when dealing with TAPI and serial communications)
4. Now includes copyright message in the source code and documentation.
PJN / 24-03-2001 1. Added a BytesWaiting method
PJN / 04-04-2001 1. Provided an overriden version of BytesWaiting which specifies a timeout
PJN / 23-04-2001 1. Fixed a memory leak in DataWaiting method
PJN / 01-05-2002 1. Fixed a problem in Open method which was failing to initialize the DCB
structure incorrectly, when calling GetState. Thanks to Ben Newson for this fix.
PJN / 29-05-2002 1. Fixed an problem where the GetProcAddress for CancelIO was using the
wrong calling convention
PJN / 07-08-2002 1. Changed the declaration of CSerialPort::WaitEvent to be consistent with the
rest of the methods in CSerialPort which can operate in "OVERLAPPED" mode. A note
about the usage of this: If the method succeeds then the overlapped operation
has completed synchronously and there is no need to do a WaitForSingle/MultipleObjects.
If any other unexpected error occurs then a CSerialException will be thrown. See
the implementation of the CSerialPort::DataWaiting which has been rewritten to use
this new design pattern. Thanks to Serhiy Pavlov for spotting this inconsistency.
PJN / 20-09-2002 1. Addition of an additional ASSERT in the internal _OnCompletion function.
2. Addition of an optional out parameter to the Write method which operates in
overlapped mode. Thanks to Kevin Pinkerton for this addition.
PJN / 10-04-2006 1. Updated copyright details.
2. Addition of a CSERIALPORT_EXT_CLASS and CSERIALPORT_EXT_API macros which makes
the class easier to use in an extension dll.
3. Removed derivation of CSerialPort from CObject as it was not really needed.
4. Fixed a number of level 4 warnings in the sample app.
5. Reworked the overlapped IO methods to expose the LPOVERLAPPED structure to client
code.
6. Updated the documentation to use the same style as the web site.
7. Did a spell check of the HTML documentation.
8. Updated the documentation on possible blocking in Read/Ex function. Thanks to
D Kerrison for reporting this issue.
9. Fixed a minor issue in the sample app when the code is compiled using /Wp64
PJN / 02-06-2006 1. Removed the bOverlapped as a member variable from the class. There was no
real need for this setting, since the SDK functions will perform their own
checking of how overlapped operations should
2. Fixed a bug in GetOverlappedResult where the code incorrectly checking against
the error ERROR_IO_PENDING instead of ERROR_IO_INCOMPLETE. Thanks to Sasho Darmonski
for reporting this bug.
3. Reviewed all TRACE statements for correctness.
PJN / 05-06-2006 1. Fixed an issue with the creation of the internal event object. It was incorrectly
being created as an auto-reset event object instead of a manual reset event object.
Thanks to Sasho Darmonski for reporting this issue.
PJN / 24-06-2006 1. Fixed some typos in the history list. Thanks to Simon Wong for reporting this.
2. Made the class which handles the construction of function pointers at runtime a
member variable of CSerialPort
3. Made AfxThrowSerialPortException part of the CSerialPort class. Thanks to Simon Wong
for reporting this.
4. Removed the unnecessary CSerialException destructor. Thanks to Simon Wong for
reporting this.
5. Fixed a minor error in the TRACE text in CSerialPort::SetDefaultConfig. Again thanks
to Simon Wong for reporting this.
6. Code now uses new C++ style casts rather than old style C casts where necessary.
Again thanks to Simon Wong for reporting this.
7. CSerialException::GetErrorMessage now uses the strsafe functions. This does mean
that the code now requires the Platform SDK if compiled using VC 6.
PJN / 25-06-2006 1. Combined the functionality of the CSerialPortData class into the main CSerialPort class.
2. Renamed AfxThrowSerialPortException to ThrowSerialPortException and made the method
public.
PJN / 05-11-2006 1. Minor update to stdafx.h of sample app to avoid compiler warnings in VC 2005.
2. Reverted the use of the strsafe.h header file. Instead now the code uses the VC 2005
Safe CRT and if this is not available, then we fail back to the standard CRT.
PJN / 25-01-2007 1. Minor update to remove strsafe.h from stdafx.h of the sample app.
2. Updated copyright details.
PJN / 24-12-2007 1. CSerialException::GetErrorMessage now uses the FORMAT_MESSAGE_IGNORE_INSERTS flag. For more information please see Raymond
Chen's blog at http://blogs.msdn.com/oldnewthing/archive/2007/11/28/6564257.aspx. Thanks to Alexey Kuznetsov for reporting this
issue.
2. Simplified the code in CSerialException::GetErrorMessage somewhat.
3. Optimized the CSerialException constructor code.
4. Code now uses newer C++ style casts instead of C style casts.
5. Reviewed and updated all the TRACE logging in the module
6. Replaced all calls to ZeroMemory with memset
PJN / 30-12-2007 1. Updated the sample app to clean compile on VC 2008
2. CSerialException::GetErrorMessage now uses Checked::tcsncpy_s if compiled using VC 2005 or later.
PJN / 18-05-2008 1. Updated copyright details.
2. Changed the actual values for Parity enum so that they are consistent with the Parity define values in the Windows SDK
header file WinBase.h. This avoids the potential issue where you use the CSerialPort enum parity values in a call to the
raw Win32 API calls. Thanks to Robert Krueger for reporting this issue.
PJN / 21-06-2008 1. Code now compiles cleanly using Code Analysis (/analyze)
2. Updated code to compile correctly using _ATL_CSTRING_EXPLICIT_CONSTRUCTORS define
3. The code now only supports VC 2005 or later.
4. CSerialPort::Read, Write, GetOverlappedResult & WaitEvent now throw an exception irrespective of whether the last error
is ERROR_IO_PENDING or not
5. Replaced all calls to ZeroMemory with memset
PJN / 04-07-2008 1. Provided a version of the Open method which takes a string instead of a numeric port number value. This allows the code
to support some virtual serial port packages which do not use device names of the form "COM%d". Thanks to David Balazic for
suggesting this addition.
PJN / 25-01-2012 1. Updated copyright details.
2. Updated sample app and class to compile cleanly on VC 2010 and later.
PJN / 28-02-2015 1. Updated sample project settings to more modern default values.
2. Updated copyright details.
3. Reworked the CSerialPort and CSerialPortException classes to optionally compile without MFC. By default
the classes now use STL classes and idioms but if you define CSERIALPORT_MFC_EXTENSIONS the classes will
revert back to the MFC behaviour.
4. Remove logic to use GetProcAddress to access CancelIO functionality.
5. Updated the code to clean compile on VC 2013
6. Added SAL annotations to all the code
7. Addition of a GetDefaultConfig method which takes a string
8. Addition of a SetDefaultConfig method which takes a string
PJN / 26-04-2015 1. Removed unnecessary inclusion of WinError.h
2. Removed the CSerialPort::DataWaiting method as it depends on the port being open in overlapped mode. Instead client code
can simply call CSerialPort::WaitEvent directly themselves. Removing this method also means that the CSerialPort::m_hEvent
handle has not also been removed.
3. The CSerialPort::WriteEx method has been reworked to expose all the parameters of the underlying WriteFileEx API. This
rework also fixes a memory leak in WriteEx which can sometimes occur. This reworks also means that the
CSerialPort::_OnCompletion and CSerialPort::_OnCompletion methods have been removed. Thanks to Yufeng Huang for reporting
this issue.
4. The CSerialPort::ReadEx method has been reworked to expose all the parameters of the underlying ReadFileEx API. This
rework also fixes a memory leak in ReadEx which can sometimes occur. This reworks also means that the
CSerialPort::_OnCompletion and CSerialPort::_OnCompletion methods have been removed. Thanks to Yufeng Huang for reporting
this issue.
PJN / 17-12-2015 1. Verified the code compiles cleanly on VC 2015.
PJN / 22-05-2016 1. Updated copyright details.
2. Fixed some typos in SerialPort.h, SerialPort.cpp and SerialPort.htm where CSERIALPORT_MFC_EXTENSTIONS was being used
instead of CSERIALPORT_MFC_EXTENSIONS. Thanks to Nicholas Buse for reporting this issue.
PJN / 16-08-2017 1. Updated copyright details.
2. Updated declarations of CSerialException::GetErrorMessage to be consistent with CException base class implementations
3. Fixed up the SAL annotations on CSerialPort::GetConfig. Thanks to Wang Jinhai for reporting this issue.
PJN / 17-12-2017 1. Replaced NULL throughout the codebase with nullptr. This means that the minimum requirement for the framework is now
VC 2010.
2. Updated the code to compile cleanly when _ATL_NO_AUTOMATIC_NAMESPACE is defined.
3. Provided a CSerialPort::CancelIoEx method which encapsulates the CancelIoEx API. Thanks to Victor Derks for this
suggestion.
4. Fixed code in CSerialPort::GetDefaultConfig as it does not have a return value. Thanks to Victor Derks for reporting
this bug.
5. Fixed code in CSerialPort::SetDefaultConfig as it does not have a return value. Thanks to Victor Derks for reporting
this bug.
6. The sal header file is now included before the fallback SAL macros are defined in SerialPort.h. Thanks to Victor Derks
for reporting this issue.
7. Reworked the code to now be a header only implementation.
8. Provided a new CSerialPort2 class which is a non exception based version of CSerialPort
9. Provided methods in CSerialPort & CSerialPort2 which encapsulate the GetOverlappedResultEx API.
10. Provided a new Open method in CSerialPort & CSerialPort2 which just opens the port without explicit configuration.
11. Provided a new Open method in CSerialPort & CSerialPort2 which encapsulates the OpenCommPort API.
PJN / 01-07-2018 1. Updated copyright details.
2. Fixed a number of C++ core guidelines compiler warnings. These changes mean that the code
will now only compile on VC 2017 or later.
PJN / 16-09-2018 1. Fixed a number of compiler warnings when using VS 2017 15.8.4
PJN / 21-12-2018 1. Fixed issues in CSerialPort2::Open where sometimes the function would return FALSE, but would leave the serial port in
an open state. Thanks to "Guan" for reporting this issue.
PJN / 29-01-2019 1. Updated copyright details.
2. Fixed a bug in the two CSerialPort::Open methods where they were incorrectly defined as having a return value of
BOOL instead of the correct return value of void. Thanks to Boris Usievich for reporting this bug.
PJN / 21-04-2019 1. Updated the sample app to clean compile on VC 2019
2. Removed the code path supported by the non defunct CSERIALPORT_MFC_EXTENSIONS enum
PJN / 10-09-2019 1. Replaced enum with enum class throughout the code
2. Fixed a number of compiler warnings when the code is compiled with VS 2019 Preview
PJN / 07-11-2019 1. Updated initialization of various structs to use C++ 11 list initialization
PJN / 12-04-2020 1. Updated copyright details.
2. Fixed more Clang-Tidy static code analysis warnings in the code.
PJN / 17-02-2022 1. Updated copyright details.
2. Updated the code to use C++ uniform initialization for all variable declarations
Copyright (c) 1999 - 2022 by PJ Naughter. (Web: www.naughter.com, Email: [email protected])
All rights reserved.
Copyright / Usage Details:
You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise)
when your product is released in binary form. You are allowed to modify the source code in any way you want
except you cannot modify the copyright details at the top of each module. If you want to distribute source
code with your application, then you are only allowed to distribute versions released by the author. This is
to maintain a single distribution point for the source code.
*/
///////////////////// Macros / Structs etc ////////////////////////////////////
#pragma once
#ifndef __SERIALPORT_H__
#define __SERIALPORT_H__
#ifndef CSERIALPORT_EXT_CLASS
#define CSERIALPORT_EXT_CLASS
#endif //#ifndef CSERIALPORT_EXT_CLASS
///////////////////// Includes ////////////////////////////////////////////////
#include <exception>
#ifndef __ATLBASE_H__
#pragma message("To avoid this message, please put atlbase.h in your pre compiled header (normally stdafx.h)")
#include <atlbase.h>
#endif //#ifndef __ATLBASE_H__
#ifndef __ATLSTR_H__
#pragma message("To avoid this message, please put atlstr.h in your pre compiled header (normally stdafx.h)")
#include <atlstr.h>
#endif //#ifndef __ATLSTR_H__
///////////////////// Classes /////////////////////////////////////////////////
class CSERIALPORT_EXT_CLASS CSerialException : public std::exception
{
public:
//Constructors / Destructors
CSerialException(_In_ DWORD dwError) noexcept : m_dwError{ dwError }
{
}
//Methods
#pragma warning(suppress: 26429)
virtual BOOL GetErrorMessage2(_Out_writes_z_(nMaxError) LPTSTR lpszError, _In_ UINT nMaxError, _Out_opt_ PUINT pnHelpContext = nullptr) const
{
//Validate our parameters
#pragma warning(suppress: 26477)
ATLASSERT(lpszError != nullptr);
if (pnHelpContext != nullptr)
*pnHelpContext = 0;
//What will be the return value from this function (assume the worst)
BOOL bSuccess{ FALSE };
LPTSTR lpBuffer{ nullptr };
const DWORD dwReturn = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
nullptr, m_dwError, MAKELANGID(LANG_NEUTRAL, SUBLANG_SYS_DEFAULT),
#pragma warning(suppress: 26490)
reinterpret_cast<LPTSTR>(&lpBuffer), 0, nullptr);
if (dwReturn == 0)
*lpszError = _T('\0');
else
{
bSuccess = TRUE;
ATL::Checked::tcsncpy_s(lpszError, nMaxError, lpBuffer, _TRUNCATE);
LocalFree(lpBuffer);
}
return bSuccess;
}
//Data members
DWORD m_dwError;
#pragma warning(suppress: 26495)
};
//Non exception based version of the class
class CSERIALPORT_EXT_CLASS CSerialPort2
{
public:
//Enums
enum class FlowControl
{
NoFlowControl,
CtsRtsFlowControl,
CtsDtrFlowControl,
DsrRtsFlowControl,
DsrDtrFlowControl,
XonXoffFlowControl
};
enum class Parity
{
NoParity = 0,
OddParity = 1,
EvenParity = 2,
MarkParity = 3,
SpaceParity = 4
};
enum class StopBits
{
OneStopBit = 0,
OnePointFiveStopBits = 1,
TwoStopBits = 2
};
//Constructors / Destructors
CSerialPort2() noexcept : m_hComm{ INVALID_HANDLE_VALUE }
{
}
CSerialPort2(_In_ const CSerialPort2&) = delete;
CSerialPort2(CSerialPort2&& port) noexcept : m_hComm{ INVALID_HANDLE_VALUE }
{
Attach(port.Detach());
}
virtual ~CSerialPort2()
{
Close();
}
//General Methods
CSerialPort2& operator=(_In_ const CSerialPort2&) = delete;
CSerialPort2& operator=(CSerialPort2&& port) noexcept
{
Attach(port.Detach());
return *this;
}
__if_exists(OpenCommPort)
{
BOOL Open(_In_ ULONG uPortNumber, _In_ DWORD dwDesiredAccess, _In_ DWORD dwFlagsAndAttributes) noexcept
{
Close(); //In case we are already open
//Call CreateFile to open the comms port
m_hComm = OpenCommPort(uPortNumber, dwDesiredAccess, dwFlagsAndAttributes);
return (m_hComm != INVALID_HANDLE_VALUE);
}
}
BOOL Open(_In_z_ LPCTSTR pszPort, _In_ BOOL bOverlapped = FALSE) noexcept
{
Close(); //In case we are already open
//Call CreateFile to open the comms port
m_hComm = CreateFile(pszPort, GENERIC_READ | GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, bOverlapped ? FILE_FLAG_OVERLAPPED : 0, nullptr);
return (m_hComm != INVALID_HANDLE_VALUE);
}
BOOL Open(_In_ int nPort, _In_ DWORD dwBaud = 9600, _In_ Parity parity = Parity::NoParity, _In_ BYTE DataBits = 8,
_In_ StopBits stopBits = StopBits::OneStopBit, _In_ FlowControl fc = FlowControl::NoFlowControl, _In_ BOOL bOverlapped = FALSE)
{
//Form the string version of the port number
ATL::CAtlString sPort;
sPort.Format(_T("\\\\.\\COM%d"), nPort);
//Delegate the work to the other version of Open
return Open(sPort, dwBaud, parity, DataBits, stopBits, fc, bOverlapped);
}
BOOL Open(_In_z_ LPCTSTR pszPort, _In_ DWORD dwBaud = 9600, _In_ Parity parity = Parity::NoParity, _In_ BYTE DataBits = 8,
_In_ StopBits stopBits = StopBits::OneStopBit, _In_ FlowControl fc = FlowControl::NoFlowControl, _In_ BOOL bOverlapped = FALSE) noexcept
{
//Delegate to the other version of this method
if (!Open(pszPort, bOverlapped))
return FALSE;
//Get the current state prior to changing it
DCB dcb{};
dcb.DCBlength = sizeof(DCB);
if (!GetState(dcb))
{
const DWORD dwLastError{ GetLastError() };
Close();
SetLastError(dwLastError);
return FALSE;
}
//Setup the baud rate
dcb.BaudRate = dwBaud;
//Setup the Parity
switch (parity)
{
case Parity::EvenParity:
{
dcb.Parity = EVENPARITY;
break;
}
case Parity::MarkParity:
{
dcb.Parity = MARKPARITY;
break;
}
case Parity::NoParity:
{
dcb.Parity = NOPARITY;
break;
}
case Parity::OddParity:
{
dcb.Parity = ODDPARITY;
break;
}
case Parity::SpaceParity:
{
dcb.Parity = SPACEPARITY;
break;
}
default:
{
#pragma warning(suppress: 26477)
ATLASSERT(FALSE);
break;
}
}
//Setup the data bits
dcb.ByteSize = DataBits;
//Setup the stop bits
switch (stopBits)
{
case StopBits::OneStopBit:
{
dcb.StopBits = ONESTOPBIT;
break;
}
case StopBits::OnePointFiveStopBits:
{
dcb.StopBits = ONE5STOPBITS;
break;
}
case StopBits::TwoStopBits:
{
dcb.StopBits = TWOSTOPBITS;
break;
}
default:
{
#pragma warning(suppress: 26477)
ATLASSERT(FALSE);
break;
}
}
//Setup the flow control
dcb.fDsrSensitivity = FALSE;
switch (fc)
{
case FlowControl::NoFlowControl:
{
dcb.fOutxCtsFlow = FALSE;
dcb.fOutxDsrFlow = FALSE;
dcb.fOutX = FALSE;
dcb.fInX = FALSE;
break;
}
case FlowControl::CtsRtsFlowControl:
{
dcb.fOutxCtsFlow = TRUE;
dcb.fOutxDsrFlow = FALSE;
dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
dcb.fOutX = FALSE;
dcb.fInX = FALSE;
break;
}
case FlowControl::CtsDtrFlowControl:
{
dcb.fOutxCtsFlow = TRUE;
dcb.fOutxDsrFlow = FALSE;
dcb.fDtrControl = DTR_CONTROL_HANDSHAKE;
dcb.fOutX = FALSE;
dcb.fInX = FALSE;
break;
}
case FlowControl::DsrRtsFlowControl:
{
dcb.fOutxCtsFlow = FALSE;
dcb.fOutxDsrFlow = TRUE;
dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
dcb.fOutX = FALSE;
dcb.fInX = FALSE;
break;
}
case FlowControl::DsrDtrFlowControl:
{
dcb.fOutxCtsFlow = FALSE;
dcb.fOutxDsrFlow = TRUE;
dcb.fDtrControl = DTR_CONTROL_HANDSHAKE;
dcb.fOutX = FALSE;
dcb.fInX = FALSE;
break;
}
case FlowControl::XonXoffFlowControl:
{
dcb.fOutxCtsFlow = FALSE;
dcb.fOutxDsrFlow = FALSE;
dcb.fOutX = TRUE;
dcb.fInX = TRUE;
dcb.XonChar = 0x11;
dcb.XoffChar = 0x13;
dcb.XoffLim = 100;
dcb.XonLim = 100;
break;
}
default:
{
#pragma warning(suppress: 26477)
ATLASSERT(FALSE);
break;
}
}
//Now that we have all the settings in place, make the changes
if (!SetState(dcb))
{
const DWORD dwLastError{ GetLastError() };
Close();
SetLastError(dwLastError);
return FALSE;
}
return TRUE;
}
void Close() noexcept
{
if (IsOpen())
{
//Close down the comms port
CloseHandle(m_hComm);
m_hComm = INVALID_HANDLE_VALUE;
}
}
void Attach(_In_ HANDLE hComm) noexcept
{
Close();
//Validate our parameters, now that the port has been closed
#pragma warning(suppress: 26477)
ATLASSERT(m_hComm == INVALID_HANDLE_VALUE);
m_hComm = hComm;
}
HANDLE Detach() noexcept
{
HANDLE hComm{ m_hComm }; //What will be the return value from this function
m_hComm = INVALID_HANDLE_VALUE;
return hComm;
}
operator HANDLE() const noexcept
{
return m_hComm;
}
_NODISCARD BOOL IsOpen() const noexcept
{
return m_hComm != INVALID_HANDLE_VALUE;
}
//Reading / Writing Methods
_Must_inspect_result_ BOOL Read(_Out_writes_bytes_(dwNumberOfBytesToRead) __out_data_source(FILE) void* lpBuffer, _In_ DWORD dwNumberOfBytesToRead, _Out_ DWORD& dwBytesRead) noexcept
{
//Validate our parameters
#pragma warning(suppress: 26477)
ATLASSERT(IsOpen());
dwBytesRead = 0;
return ReadFile(m_hComm, lpBuffer, dwNumberOfBytesToRead, &dwBytesRead, nullptr);
}
_Must_inspect_result_ BOOL Read(_Out_writes_bytes_to_opt_(dwNumberOfBytesToRead, *lpNumberOfBytesRead) __out_data_source(FILE) void* lpBuffer, _In_ DWORD dwNumberOfBytesToRead, _In_ OVERLAPPED& overlapped, _Inout_opt_ DWORD* lpNumberOfBytesRead = nullptr) noexcept
{
//Validate our parameters
#pragma warning(suppress: 26477)
ATLASSERT(IsOpen());
return ReadFile(m_hComm, lpBuffer, dwNumberOfBytesToRead, lpNumberOfBytesRead, &overlapped);
}
_Must_inspect_result_ BOOL ReadEx(_Out_writes_bytes_opt_(dwNumberOfBytesToRead) __out_data_source(FILE) LPVOID lpBuffer, _In_ DWORD dwNumberOfBytesToRead, _Inout_ LPOVERLAPPED lpOverlapped, _In_ LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine) noexcept
{
//Validate our parameters
#pragma warning(suppress: 26477)
ATLASSERT(IsOpen());
return ReadFileEx(m_hComm, lpBuffer, dwNumberOfBytesToRead, lpOverlapped, lpCompletionRoutine);
}
BOOL Write(_In_reads_bytes_opt_(dwNumberOfBytesToWrite) const void* lpBuffer, _In_ DWORD dwNumberOfBytesToWrite, _Out_ DWORD& dwBytesWritten) noexcept
{
//Validate our parameters
#pragma warning(suppress: 26477)
ATLASSERT(IsOpen());
dwBytesWritten = 0;
return WriteFile(m_hComm, lpBuffer, dwNumberOfBytesToWrite, &dwBytesWritten, nullptr);
}
BOOL Write(_In_reads_bytes_opt_(dwNumberOfBytesToWrite) const void* lpBuffer, _In_ DWORD dwNumberOfBytesToWrite, _In_ OVERLAPPED& overlapped, _Out_opt_ DWORD* lpNumberOfBytesWritten = nullptr) noexcept
{
//Validate our parameters
#pragma warning(suppress: 26477)
ATLASSERT(IsOpen());
return WriteFile(m_hComm, lpBuffer, dwNumberOfBytesToWrite, lpNumberOfBytesWritten, &overlapped);
}
BOOL WriteEx(_In_reads_bytes_opt_(dwNumberOfBytesToWrite) LPCVOID lpBuffer, _In_ DWORD dwNumberOfBytesToWrite, _Inout_ LPOVERLAPPED lpOverlapped, _In_ LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine) noexcept
{
//Validate our parameters
#pragma warning(suppress: 26477)
ATLASSERT(IsOpen());
return WriteFileEx(m_hComm, lpBuffer, dwNumberOfBytesToWrite, lpOverlapped, lpCompletionRoutine);
}
BOOL TransmitChar(_In_ char cChar) noexcept
{
//Validate our parameters
#pragma warning(suppress: 26477)
ATLASSERT(IsOpen());
return TransmitCommChar(m_hComm, cChar);
}
BOOL GetOverlappedResult(_In_ OVERLAPPED& overlapped, _Out_ DWORD& dwBytesTransferred, _In_ BOOL bWait) noexcept
{
//Validate our parameters
#pragma warning(suppress: 26477)
ATLASSERT(IsOpen());
return ::GetOverlappedResult(m_hComm, &overlapped, &dwBytesTransferred, bWait);
}
__if_exists(::GetOverlappedResultEx)
{
BOOL GetOverlappedResultEx(_In_ OVERLAPPED& overlapped, _Out_ DWORD& dwBytesTransferred, _In_ DWORD dwMilliseconds, _In_ BOOL bAlertable) noexcept
{
//Validate our parameters
#pragma warning(suppress: 26477)
ATLASSERT(IsOpen());
return ::GetOverlappedResultEx(m_hComm, &overlapped, &dwBytesTransferred, dwMilliseconds, bAlertable);
}
}
BOOL CancelIo() noexcept
{
//Validate our parameters
#pragma warning(suppress: 26477)
ATLASSERT(IsOpen());
return ::CancelIo(m_hComm);
}
__if_exists(::CancelIoEx)
{
BOOL CancelIoEx(_In_opt_ LPOVERLAPPED lpOverlapped = nullptr) noexcept
{
//Validate our parameters
#pragma warning(suppress: 26477)
ATLASSERT(IsOpen());
return ::CancelIoEx(m_hComm, lpOverlapped);
}
}
BOOL BytesWaiting(_Out_ DWORD& dwBytesWaiting) noexcept
{
//Validate our parameters
#pragma warning(suppress: 26477)
ATLASSERT(IsOpen());
//Check to see how many characters are unread
dwBytesWaiting = 0;
COMSTAT stat{};
if (!GetStatus(stat))
return FALSE;
dwBytesWaiting = stat.cbInQue;
return TRUE;
}
//Configuration Methods
_Return_type_success_(return != 0) BOOL GetConfig(_Out_ COMMCONFIG& config) noexcept
{
//Validate our parameters
#pragma warning(suppress: 26477)
ATLASSERT(IsOpen());
DWORD dwSize{ sizeof(COMMCONFIG) };
return GetCommConfig(m_hComm, &config, &dwSize);
}
static BOOL GetDefaultConfig(_In_ int nPort, _Out_ COMMCONFIG& config)
{
//Create the device name as a string
ATL::CAtlString sPort;
sPort.Format(_T("COM%d"), nPort);
//Delegate to the other version of the method
return GetDefaultConfig(sPort, config);
}
static BOOL GetDefaultConfig(_In_z_ LPCTSTR pszPort, _Out_ COMMCONFIG& config) noexcept
{
DWORD dwSize{ sizeof(COMMCONFIG) };
return GetDefaultCommConfig(pszPort, &config, &dwSize);
}
BOOL SetConfig(_In_ COMMCONFIG& config) noexcept
{
//Validate our parameters
#pragma warning(suppress: 26477)
ATLASSERT(IsOpen());
constexpr const DWORD dwSize{ sizeof(COMMCONFIG) };
return SetCommConfig(m_hComm, &config, dwSize);
}
static BOOL SetDefaultConfig(_In_ int nPort, _In_ COMMCONFIG& config)
{
//Create the device name as a string
ATL::CAtlString sPort;
sPort.Format(_T("COM%d"), nPort);
//Delegate to the other version of the method
return SetDefaultConfig(sPort, config);
}
static BOOL SetDefaultConfig(_In_z_ LPCTSTR pszPort, _In_ COMMCONFIG& config) noexcept
{
constexpr const DWORD dwSize{ sizeof(COMMCONFIG) };
return SetDefaultCommConfig(pszPort, &config, dwSize);
}
//Misc RS232 Methods
BOOL ClearBreak() noexcept
{
//Validate our parameters
#pragma warning(suppress: 26477)
ATLASSERT(IsOpen());
return ClearCommBreak(m_hComm);
}
BOOL SetBreak() noexcept
{
//Validate our parameters
#pragma warning(suppress: 26477)
ATLASSERT(IsOpen());
return SetCommBreak(m_hComm);
}
BOOL ClearError(_Out_ DWORD& dwErrors) noexcept
{
//Validate our parameters
#pragma warning(suppress: 26477)
ATLASSERT(IsOpen());
return ClearCommError(m_hComm, &dwErrors, nullptr);
}
BOOL GetStatus(_Out_ COMSTAT& stat) noexcept
{
//Validate our parameters
#pragma warning(suppress: 26477)
ATLASSERT(IsOpen());
DWORD dwErrors{ 0 };
return ClearCommError(m_hComm, &dwErrors, &stat);
}
BOOL GetState(_Out_ DCB& dcb) noexcept
{
//Validate our parameters
#pragma warning(suppress: 26477)
ATLASSERT(IsOpen());
return GetCommState(m_hComm, &dcb);
}
BOOL SetState(_In_ DCB& dcb) noexcept
{
//Validate our parameters
#pragma warning(suppress: 26477)
ATLASSERT(IsOpen());
return SetCommState(m_hComm, &dcb);
}
BOOL Escape(_In_ DWORD dwFunc) noexcept
{
//Validate our parameters
#pragma warning(suppress: 26477)
ATLASSERT(IsOpen());
return EscapeCommFunction(m_hComm, dwFunc);
}
BOOL ClearDTR() noexcept
{
return Escape(CLRDTR);
}
BOOL ClearRTS() noexcept
{
return Escape(CLRRTS);
}
BOOL SetDTR() noexcept
{
return Escape(SETDTR);
}
BOOL SetRTS() noexcept
{
return Escape(SETRTS);
}
BOOL SetXOFF() noexcept
{
return Escape(SETXOFF);
}
BOOL SetXON() noexcept
{
return Escape(SETXON);
}
BOOL GetProperties(_Inout_ COMMPROP& properties) noexcept
{
//Validate our parameters
#pragma warning(suppress: 26477)
ATLASSERT(IsOpen());
return GetCommProperties(m_hComm, &properties);
}
BOOL GetModemStatus(_Out_ DWORD& dwModemStatus) noexcept
{
//Validate our parameters
#pragma warning(suppress: 26477)
ATLASSERT(IsOpen());
return GetCommModemStatus(m_hComm, &dwModemStatus);
}
//Timeouts
BOOL SetTimeouts(_In_ COMMTIMEOUTS& timeouts) noexcept
{
//Validate our parameters
#pragma warning(suppress: 26477)
ATLASSERT(IsOpen());
return SetCommTimeouts(m_hComm, &timeouts);
}
BOOL GetTimeouts(_Out_ COMMTIMEOUTS& timeouts) noexcept
{
//Validate our parameters
#pragma warning(suppress: 26477)
ATLASSERT(IsOpen());
return GetCommTimeouts(m_hComm, &timeouts);
}
BOOL Set0Timeout() noexcept
{
COMMTIMEOUTS Timeouts{};
Timeouts.ReadIntervalTimeout = MAXDWORD;
return SetTimeouts(Timeouts);
}
BOOL Set0WriteTimeout() noexcept
{
COMMTIMEOUTS Timeouts{};
GetTimeouts(Timeouts);
Timeouts.WriteTotalTimeoutMultiplier = 0;
Timeouts.WriteTotalTimeoutConstant = 0;
return SetTimeouts(Timeouts);
}
BOOL Set0ReadTimeout() noexcept
{
COMMTIMEOUTS Timeouts{};
GetTimeouts(Timeouts);
Timeouts.ReadIntervalTimeout = MAXDWORD;
Timeouts.ReadTotalTimeoutMultiplier = 0;
Timeouts.ReadTotalTimeoutConstant = 0;
return SetTimeouts(Timeouts);
}
//Event Methods
BOOL SetMask(_In_ DWORD dwMask) noexcept
{
//Validate our parameters
#pragma warning(suppress: 26477)
ATLASSERT(IsOpen());
return SetCommMask(m_hComm, dwMask);
}
BOOL GetMask(_Out_ DWORD& dwMask) noexcept
{
//Validate our parameters
#pragma warning(suppress: 26477)
ATLASSERT(IsOpen());
return GetCommMask(m_hComm, &dwMask);
}
BOOL WaitEvent(_Inout_ DWORD& dwMask) noexcept
{
//Validate our parameters
#pragma warning(suppress: 26477)
ATLASSERT(IsOpen());
return WaitCommEvent(m_hComm, &dwMask, nullptr);
}
BOOL WaitEvent(_Inout_ DWORD& dwMask, _Inout_ OVERLAPPED& overlapped) noexcept
{
//Validate our parameters
#pragma warning(suppress: 26477)
ATLASSERT(IsOpen());
#pragma warning(suppress: 26477)
ATLASSERT(overlapped.hEvent != nullptr);
return WaitCommEvent(m_hComm, &dwMask, &overlapped);
}
//Queue Methods
BOOL Flush() noexcept
{
//Validate our parameters
#pragma warning(suppress: 26477)
ATLASSERT(IsOpen());
return FlushFileBuffers(m_hComm);
}
BOOL Purge(_In_ DWORD dwFlags) noexcept
{
//Validate our parameters
#pragma warning(suppress: 26477)
ATLASSERT(IsOpen());
return PurgeComm(m_hComm, dwFlags);
}
BOOL TerminateOutstandingWrites() noexcept
{
return Purge(PURGE_TXABORT);
}
BOOL TerminateOutstandingReads() noexcept
{
return Purge(PURGE_RXABORT);
}
BOOL ClearWriteBuffer() noexcept
{
return Purge(PURGE_TXCLEAR);
}
BOOL ClearReadBuffer() noexcept
{
return Purge(PURGE_RXCLEAR);
}
BOOL Setup(_In_ DWORD dwInQueue, _In_ DWORD dwOutQueue) noexcept
{
//Validate our parameters
#pragma warning(suppress: 26477)
ATLASSERT(IsOpen());
return SetupComm(m_hComm, dwInQueue, dwOutQueue);
}
protected:
//Member variables
HANDLE m_hComm; //Handle to the comms port
};
//Exception based version of the class
class CSERIALPORT_EXT_CLASS CSerialPort : public CSerialPort2
{
public:
//General Methods
__if_exists(OpenCommPort)
{
#pragma warning(suppress: 26434)
void Open(_In_ ULONG uPortNumber, _In_ DWORD dwDesiredAccess, _In_ DWORD dwFlagsAndAttributes)
{
const BOOL bSuccess{ __super::Open(uPortNumber, dwDesiredAccess, dwFlagsAndAttributes) };
if (!bSuccess)
ThrowSerialException();
}
}
#pragma warning(suppress: 26434)
void Open(_In_z_ LPCTSTR pszPort, _In_ BOOL bOverlapped = FALSE)
{
const BOOL bSuccess{ __super::Open(pszPort, bOverlapped) };
if (!bSuccess)
ThrowSerialException();
}