-
Notifications
You must be signed in to change notification settings - Fork 791
/
SPComm.pas
2101 lines (1806 loc) · 59.8 KB
/
SPComm.pas
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
// Communications
//
// David Wann.COMM32.PAS Version 1.0
// This Communications Component is implemented using separate Read and Write
// threads. Messages from the threads are posted to the Comm control which is
// an invisible window. To handle data from the comm port, simply
// attach a handler to 'OnReceiveData'. There is no need to free the memory
// buffer passed to this handler. If TAPI is used to open the comm port, some
// changes to this component are needed ('StartComm' currently opens the comm
// port). The 'OnRequestHangup' event is included to assist this.
//
// David Wann
// Stamina Software
// 28/02/96
//
//
// This component is totally free(copyleft), you can do anything in any
// purpose EXCEPT SELL IT ALONE.
//
//
// Author: Small-Pig Team in Taiwan R.O.C.
// Email : [email protected]
// Date : 1997/5/9
//
// Version 1.01 1996/9/4
// - Add setting Parity, Databits, StopBits
// - Add setting Flowcontrol:Dtr-Dsr, Cts-Rts, Xon-Xoff
// - Add setting Timeout information for read/write
//
// Version 1.02 1996/12/24
// - Add Sender parameter to TReceiveDataEvent
//
// Version 2.0 1997/4/15
// - Support separatly DTR/DSR and RTS/CTS hardware flow control setting
// - Support separatly OutX and InX software flow control setting
// - Log file(for debug) may used by many comms at the same time
// - Add DSR sensitivity property
// - You can set error char. replacement when parity error
// - Let XonLim/XoffLim and XonChar/XoffChar setting by yourself
// - You may change flow-control when comm is still opened
// - Change TComm32 to TComm
// - Add OnReceiveError event handler
// - Add OnReceiveError event handler when overrun, framing error,
// parity error
// - Fix some bug
//
// Version 2.01 1997/4/19
// - Support some property for modem
// - Add OnModemStateChange event hander when RLSD(CD) change state
//
// Version 2.02 1997/4/28
// - Bug fix: When receive XOFF character, the system FAULT!!!!
//
// Version 2.5 1997/5/9
// - Add OnSendDataEmpty event handler when all data in buffer
// are sent(send-buffer become empty) this handler is called.
// You may call send data here.
// - Change the ModemState parameters in OnModemStateChange
// to ModemEvent to indicate what modem event make this call
// - Add RING signal detect. When RLSD changed state or
// RING signal was detected, OnModemStateChange handler is called
// - Change XonLim and XoffLim from 100 to 500
// - Remove TWriteThread.WriteData member
// - PostHangupCall is re-design for debuging function
// - Add a boolean property SendDataEmpty, True when send buffer
// is empty
//
// Version 2.58 2004/10/8
unit SPComm;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs;
const
// messages from read/write threads
PWM_GOTCOMMDATA = WM_USER + 1;
PWM_RECEIVEERROR = WM_USER + 2;
PWM_REQUESTHANGUP = WM_USER + 3;
PWM_MODEMSTATECHANGE = WM_USER + 4;
PWM_SENDDATAEMPTY = WM_USER + 5;
type
TParity = (None, Odd, Even, Mark, Space);
TStopBits = (_1, _1_5, _2);
TByteSize = (_5, _6, _7, _8);
TDtrControl = (DtrEnable, DtrDisable, DtrHandshake);
TRtsControl = (RtsEnable, RtsDisable, RtsHandshake, RtsTransmissionAvailable);
ECommsError = class(Exception);
TReceiveDataEvent = procedure(Sender: TObject; Buffer: PAnsiChar;
BufferLength: Word) of object;
TReceiveErrorEvent = procedure(Sender: TObject; EventMask: DWORD) of object;
TModemStateChangeEvent = procedure(Sender: TObject; ModemEvent: DWORD)
of object;
TSendDataEmptyEvent = procedure(Sender: TObject) of object;
const
//
// Modem Event Constant
//
ME_CTS = 1;
ME_DSR = 2;
ME_RING = 4;
ME_RLSD = 8;
type
TReadThread = class(TThread)
protected
procedure Execute; override;
public
hCommFile: THandle;
hCloseEvent: THandle;
hComm32Window: THandle;
// --------------------------------------------------------------------------------
FInBufferSize: Word; // 输入缓冲区大小
FInputLen: Word; // 每次从缓冲区取字节数
// --------------------------------------------------------------------------------
function SetupCommEvent(lpOverlappedCommEvent: POverlapped;
var lpfdwEvtMask: DWORD): Boolean;
function SetupReadEvent(lpOverlappedRead: POverlapped;
lpszInputBuffer: LPSTR; dwSizeofBuffer: DWORD;
var lpnNumberOfBytesRead: DWORD): Boolean;
function HandleCommEvent(lpOverlappedCommEvent: POverlapped;
var lpfdwEvtMask: DWORD; fRetrieveEvent: Boolean): Boolean;
function HandleReadEvent(lpOverlappedRead: POverlapped;
lpszInputBuffer: LPSTR; dwSizeofBuffer: DWORD;
var lpnNumberOfBytesRead: DWORD): Boolean;
function HandleReadData(lpszInputBuffer: LPCSTR;
dwSizeofBuffer: DWORD): Boolean;
function ReceiveData(lpNewString: LPSTR; dwSizeofNewString: DWORD): BOOL;
function ReceiveError(EvtMask: DWORD): BOOL;
function ModemStateChange(ModemEvent: DWORD): BOOL;
procedure PostHangupCall;
end;
TWriteThread = class(TThread)
protected
procedure Execute; override;
function HandleWriteData(lpOverlappedWrite: POverlapped;
pDataToWrite: PAnsiChar; dwNumberOfBytesToWrite: DWORD): Boolean;
public
hCommFile: THandle;
hCloseEvent: THandle;
hComm32Window: THandle;
pFSendDataEmpty: ^Boolean;
procedure PostHangupCall;
end;
TComm = class(TComponent)
private
{ Private declarations }
ReadThread: TReadThread;
WriteThread: TWriteThread;
hCommFile: THandle;
hCloseEvent: THandle;
FHWnd: THandle;
FSendDataEmpty: Boolean; // True if send buffer become empty
// --------------------------------------------------------------------------------
FPortOpen: Boolean; // 追加端口控制字段
FCommPort: BYTE; // 追加端口号字段
FPortOpenError: String; // 追加端口打开错误字段
FOutput: AnsiString; // 追加端口输出字符字段
FInBufferSize: Word; // 输入缓冲区大小
FInputLen: Word; // 每次从缓冲区取字节数
// --------------------------------------------------------------------------------
FCommName: String; // 端口名字段,MSComm为端口号CommPort
FBaudRate: DWORD; // 波特率字段,MSComm在Settings内
FParityCheck: Boolean; // 校验位字段,MSComm在Settings内
FOutx_CtsFlow: Boolean;
FOutx_DsrFlow: Boolean;
FDtrControl: TDtrControl;
FDsrSensitivity: Boolean;
FTxContinueOnXoff: Boolean;
FOutx_XonXoffFlow: Boolean;
FInx_XonXoffFlow: Boolean;
FReplaceWhenParityError: Boolean;
FIgnoreNullChar: Boolean;
FRtsControl: TRtsControl;
FXonLimit: Word;
FXoffLimit: Word;
FByteSize: TByteSize;
FParity: TParity;
FStopBits: TStopBits;
FXonChar: AnsiChar;
FXoffChar: AnsiChar;
FReplacedChar: AnsiChar;
FReadIntervalTimeout: DWORD;
FReadTotalTimeoutMultiplier: DWORD;
FReadTotalTimeoutConstant: DWORD;
FWriteTotalTimeoutMultiplier: DWORD;
FWriteTotalTimeoutConstant: DWORD;
FOnReceiveData: TReceiveDataEvent;
FOnRequestHangup: TNotifyEvent;
FOnReceiveError: TReceiveErrorEvent;
FOnModemStateChange: TModemStateChangeEvent;
FOnSendDataEmpty: TSendDataEmptyEvent;
// --------------------------------------------------------------------------------
procedure SetPortOpen(b: Boolean); // 打开端口
function GetPortOpen: Boolean; // 打开端口
procedure SetCommPort(CommPort: BYTE); // 设置端口号
procedure SetOutput(Buffer: AnsiString);
procedure SetInputLen(StrLen: Word);
procedure SetInBufferSize(StrSize: Word);
// --------------------------------------------------------------------------------
procedure SetBaudRate(Rate: DWORD);
procedure SetParityCheck(b: Boolean);
procedure SetOutx_CtsFlow(b: Boolean);
procedure SetOutx_DsrFlow(b: Boolean);
procedure SetDtrControl(c: TDtrControl);
procedure SetDsrSensitivity(b: Boolean);
procedure SetTxContinueOnXoff(b: Boolean);
procedure SetOutx_XonXoffFlow(b: Boolean);
procedure SetInx_XonXoffFlow(b: Boolean);
procedure SetReplaceWhenParityError(b: Boolean);
procedure SetIgnoreNullChar(b: Boolean);
procedure SetRtsControl(c: TRtsControl);
procedure SetXonLimit(Limit: Word);
procedure SetXoffLimit(Limit: Word);
procedure SetByteSize(Size: TByteSize);
procedure SetParity(p: TParity);
procedure SetStopBits(Bits: TStopBits);
procedure SetXonChar(c: AnsiChar);
procedure SetXoffChar(c: AnsiChar);
procedure SetReplacedChar(c: AnsiChar);
procedure SetReadIntervalTimeout(v: DWORD);
procedure SetReadTotalTimeoutMultiplier(v: DWORD);
procedure SetReadTotalTimeoutConstant(v: DWORD);
procedure SetWriteTotalTimeoutMultiplier(v: DWORD);
procedure SetWriteTotalTimeoutConstant(v: DWORD);
procedure CommWndProc(var msg: TMessage);
procedure _SetCommState;
procedure _SetCommTimeout;
protected
{ Protected declarations }
procedure CloseReadThread;
procedure CloseWriteThread;
procedure ReceiveData(Buffer: PAnsiChar; BufferLength: Word);
procedure ReceiveError(EvtMask: DWORD);
procedure ModemStateChange(ModemEvent: DWORD);
procedure RequestHangup;
procedure _SendDataEmpty;
public
{ Public declarations }
property Handle: THandle read hCommFile;
property SendDataEmpty: Boolean read FSendDataEmpty;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure StartComm;
procedure StopComm;
function WriteCommData(pDataToWrite: PAnsiChar;
dwSizeofDataToWrite: Word): Boolean;
function GetModemState: DWORD;
procedure SetDtrRtsControl(DtrControl: TDtrControl;
RtsControl: TRtsControl);
published
{ Published declarations }
// --------------------------------------------------------------------------------
property PortOpen: Boolean read GetPortOpen write SetPortOpen default False;
// 追加端口号属性
property CommPort: BYTE read FCommPort write SetCommPort default 1;
// 追加端口号属性
property PortOpenError: String read FPortOpenError write FPortOpenError;
// 追加只读端口打开错误字段
property Output: AnsiString read FOutput write SetOutput; // 追加发送数据属性
property InputLen: Word read FInputLen write SetInputLen default 1;
property InBufferSize: Word read FInBufferSize write SetInBufferSize
default 2048;
// --------------------------------------------------------------------------------
property CommName: String read FCommName write FCommName;
property BaudRate: DWORD read FBaudRate write SetBaudRate default 9600;
property ParityCheck: Boolean read FParityCheck write SetParityCheck
default False;
property Outx_CtsFlow: Boolean read FOutx_CtsFlow write SetOutx_CtsFlow
default False;
property Outx_DsrFlow: Boolean read FOutx_DsrFlow write SetOutx_DsrFlow
default False;
property DtrControl: TDtrControl read FDtrControl write SetDtrControl
default DtrDisable;
property DsrSensitivity: Boolean read FDsrSensitivity
write SetDsrSensitivity default False;
property TxContinueOnXoff: Boolean read FTxContinueOnXoff
write SetTxContinueOnXoff default False;
property Outx_XonXoffFlow: Boolean read FOutx_XonXoffFlow
write SetOutx_XonXoffFlow default False;
property Inx_XonXoffFlow: Boolean read FInx_XonXoffFlow
write SetInx_XonXoffFlow default False;
property ReplaceWhenParityError: Boolean read FReplaceWhenParityError
write SetReplaceWhenParityError default False;
property IgnoreNullChar: Boolean read FIgnoreNullChar
write SetIgnoreNullChar default False;
property RtsControl: TRtsControl read FRtsControl write SetRtsControl
default RtsDisable;
property XonLimit: Word read FXonLimit write SetXonLimit;
property XoffLimit: Word read FXoffLimit write SetXoffLimit;
property ByteSize: TByteSize read FByteSize write SetByteSize;
// property Parity: TParity read FParity write FParity;
property Parity: TParity read FParity write SetParity;
property StopBits: TStopBits read FStopBits write SetStopBits;
property XonChar: AnsiChar read FXonChar write SetXonChar;
property XoffChar: AnsiChar read FXoffChar write SetXoffChar;
property ReplacedChar: AnsiChar read FReplacedChar write SetReplacedChar;
property ReadIntervalTimeout: DWORD read FReadIntervalTimeout
write SetReadIntervalTimeout;
property ReadTotalTimeoutMultiplier: DWORD read FReadTotalTimeoutMultiplier
write SetReadTotalTimeoutMultiplier;
property ReadTotalTimeoutConstant: DWORD read FReadTotalTimeoutConstant
write SetReadTotalTimeoutConstant;
property WriteTotalTimeoutMultiplier: DWORD
read FWriteTotalTimeoutMultiplier write SetWriteTotalTimeoutMultiplier;
property WriteTotalTimeoutConstant: DWORD read FWriteTotalTimeoutConstant
write SetWriteTotalTimeoutConstant;
property OnReceiveData: TReceiveDataEvent read FOnReceiveData
write FOnReceiveData;
property OnReceiveError: TReceiveErrorEvent read FOnReceiveError
write FOnReceiveError;
property OnModemStateChange: TModemStateChangeEvent read FOnModemStateChange
write FOnModemStateChange;
property OnRequestHangup: TNotifyEvent read FOnRequestHangup
write FOnRequestHangup;
property OnSendDataEmpty: TSendDataEmptyEvent read FOnSendDataEmpty
write FOnSendDataEmpty;
end;
const
// This is the message posted to the WriteThread
// When we have something to write.
PWM_COMMWRITE = WM_USER + 1;
// Default size of the Input Buffer used by this code.
// --------------------------------------------------------------------------------
// 废除,用InBufferSize属性替代,增强灵活性
// INPUTBUFFERSIZE = 2048;
// INPUTBUFFERSIZE = 1;
// --------------------------------------------------------------------------------
RFCOMM = 340;
procedure Register;
implementation
(* **************************************************************************** *)
// TComm PUBLIC METHODS
(* **************************************************************************** *)
constructor TComm.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
ReadThread := nil;
WriteThread := nil;
hCommFile := 0;
hCloseEvent := 0;
FSendDataEmpty := True;
FCommPort := 1; //
FCommName := 'COM1';
FBaudRate := 9600;
FParityCheck := False;
FOutx_CtsFlow := False;
FOutx_DsrFlow := False;
FDtrControl := DtrDisable;
FDsrSensitivity := False;
FTxContinueOnXoff := False;
FOutx_XonXoffFlow := False;
FInx_XonXoffFlow := False;
FReplaceWhenParityError := False;
FIgnoreNullChar := False;
FRtsControl := RtsDisable;
FXonLimit := 500;
FXoffLimit := 500;
FByteSize := _8;
FParity := None;
FStopBits := _1;
FXonChar := chr($11); // Ctrl-Q
FXoffChar := chr($13); // Ctrl-S
FReplacedChar := chr(0);
FReadIntervalTimeout := 100;
FReadTotalTimeoutMultiplier := 0;
FReadTotalTimeoutConstant := 0;
FWriteTotalTimeoutMultiplier := 0;
FWriteTotalTimeoutConstant := 0;
// -----------------------------------------------------------
FInputLen := 1;
FInBufferSize := 2048;
// -----------------------------------------------------------
if not(csDesigning in ComponentState) then
FHWnd := AllocateHWnd(CommWndProc);
end;
destructor TComm.Destroy;
begin
if not(csDesigning in ComponentState) then
DeallocateHWnd(FHWnd);
inherited Destroy;
end;
//
// FUNCTION: StartComm
//
// PURPOSE: Starts communications over the comm port.
//
// PARAMETERS:
// hNewCommFile - This is the COMM File handle to communicate with.
// This handle is obtained from TAPI.
//
// Output:
// Successful: Startup the communications.
// Failure: Raise a exception
//
// COMMENTS:
//
// StartComm makes sure there isn't communication in progress already,
// creates a Comm file, and creates the read and write threads. It
// also configures the hNewCommFile for the appropriate COMM settings.
//
// If StartComm fails for any reason, it's up to the calling application
// to close the Comm file handle.
//
//
procedure TComm.StartComm;
var
hNewCommFile: THandle;
begin
FPortOpenError := '';
FPortOpen := False;
// Are we already doing comm?
if (hCommFile <> 0) then
begin
FPortOpenError := 'This serial port already opened';
// raise ECommsError.Create( FPortOpenError );
Exit;
end;
hNewCommFile := CreateFile(PChar('//./' + FCommName), GENERIC_READ or
GENERIC_WRITE, 0,
{ not shared }
nil, { no security ?? }
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL or FILE_FLAG_OVERLAPPED,
0 { template } );
if hNewCommFile = INVALID_HANDLE_VALUE then
begin
FPortOpenError := 'Error opening serial port';
// raise ECommsError.Create( FPortOpenError );
Exit;
end;
// Is this a valid comm handle?
// 蓝牙串口可能被识别为Unknown,为了兼容蓝牙串口增加了 FILE_TYPE_UNKNOWN
if ((GetFileType(hNewCommFile) <> FILE_TYPE_CHAR) and
(GetFileType(hNewCommFile) <> FILE_TYPE_UNKNOWN)) then
begin
CloseHandle(hNewCommFile);
FPortOpenError := 'File handle is not a comm handle ';
// raise ECommsError.Create( FPortOpenError );
Exit;
end;
if not SetupComm(hNewCommFile, 4096, 4096) then
begin
CloseHandle(hCommFile);
FPortOpenError := 'Cannot setup comm buffer';
raise ECommsError.Create(FPortOpenError);
end;
// It is ok to continue.
hCommFile := hNewCommFile;
// purge any information in the buffer
PurgeComm(hCommFile, PURGE_TXABORT or PURGE_RXABORT or PURGE_TXCLEAR or
PURGE_RXCLEAR);
FSendDataEmpty := True;
// Setting the time-out value
_SetCommTimeout;
// Querying then setting the comm port configurations.
_SetCommState;
// Create the event that will signal the threads to close.
hCloseEvent := CreateEvent(nil, True, False, nil);
if hCloseEvent = 0 then
begin
CloseHandle(hCommFile);
hCommFile := 0;
FPortOpenError := 'Unable to create event';
// raise ECommsError.Create( FPortOpenError );
Exit;
end;
// Create the Read thread.
try
ReadThread := TReadThread.Create(True { suspended } );
except
ReadThread := nil;
CloseHandle(hCloseEvent);
CloseHandle(hCommFile);
hCommFile := 0;
FPortOpenError := 'Unable to create read thread';
// raise ECommsError.Create( FPortOpenError );
Exit;
end;
ReadThread.hCommFile := hCommFile;
ReadThread.hCloseEvent := hCloseEvent;
ReadThread.hComm32Window := FHWnd;
// ..........................................
ReadThread.FInputLen := FInputLen;
ReadThread.FInBufferSize := FInBufferSize;
// ..........................................
// Comm threads should have a higher base priority than the UI thread.
// If they don't, then any temporary priority boost the UI thread gains
// could cause the COMM threads to loose data.
ReadThread.Priority := tpHighest;
// Create the Write thread.
try
WriteThread := TWriteThread.Create(True { suspended } );
except
CloseReadThread;
WriteThread := nil;
CloseHandle(hCloseEvent);
CloseHandle(hCommFile);
hCommFile := 0;
FPortOpenError := 'Unable to create write thread';
// raise ECommsError.Create( FPortOpenError );
Exit;
end;
WriteThread.hCommFile := hCommFile;
WriteThread.hCloseEvent := hCloseEvent;
WriteThread.hComm32Window := FHWnd;
WriteThread.pFSendDataEmpty := @FSendDataEmpty;
WriteThread.Priority := tpHigher;
ReadThread.Start;
WriteThread.Start;
// Everything was created ok. Ready to go!
end; { TComm.StartComm }
//
// FUNCTION: StopComm
//
// PURPOSE: Stop and end all communication threads.
//
// PARAMETERS:
// none
//
// RETURN VALUE:
// none
//
// COMMENTS:
//
// Tries to gracefully signal all communication threads to
// close, but terminates them if it has to.
//
//
procedure TComm.StopComm;
begin
// No need to continue if we're not communicating.
FPortOpenError := '';
FPortOpen := False;
if hCommFile = 0 then
Exit;
// Close the threads.
CloseReadThread;
CloseWriteThread;
// Not needed anymore.
CloseHandle(hCloseEvent);
// Now close the comm port handle.
CloseHandle(hCommFile);
hCommFile := 0
end; { TComm.StopComm }
//
// FUNCTION: WriteCommData(PAnsiChar, Word)
//
// PURPOSE: Send a String to the Write Thread to be written to the Comm.
//
// PARAMETERS:
// pszStringToWrite - String to Write to Comm port.
// nSizeofStringToWrite - length of pszStringToWrite.
//
// RETURN VALUE:
// Returns TRUE if the PostMessage is successful.
// Returns FALSE if PostMessage fails or Write thread doesn't exist.
//
// COMMENTS:
//
// This is a wrapper function so that other modules don't care that
// Comm writing is done via PostMessage to a Write thread. Note that
// using PostMessage speeds up response to the UI (very little delay to
// 'write' a string) and provides a natural buffer if the comm is slow
// (ie: the messages just pile up in the message queue).
//
// Note that it is assumed that pszStringToWrite is allocated with
// LocalAlloc, and that if WriteCommData succeeds, its the job of the
// Write thread to LocalFree it. If WriteCommData fails, then its
// the job of the calling function to free the string.
//
//
function TComm.WriteCommData(pDataToWrite: PAnsiChar;
dwSizeofDataToWrite: Word): Boolean;
var
Buffer: Pointer;
begin
if (WriteThread <> nil) and (dwSizeofDataToWrite <> 0) then
begin
Buffer := Pointer(LocalAlloc(LPTR, dwSizeofDataToWrite + 1));
Move(pDataToWrite^, Buffer^, dwSizeofDataToWrite);
if PostThreadMessage(WriteThread.ThreadID, PWM_COMMWRITE,
WPARAM(dwSizeofDataToWrite), LPARAM(Buffer)) then
begin
FSendDataEmpty := False;
Result := True;
Exit
end
end;
Result := False
end; { TComm.WriteCommData }
procedure TComm.SetOutput(Buffer: AnsiString);
begin
FOutput := Buffer;
WriteCommData(PAnsiChar(Buffer), Length(Buffer));
end;
procedure TComm.SetInputLen(StrLen: Word);
begin
if StrLen = 0 then
FInputLen := FInBufferSize
else if StrLen <= FInBufferSize then
FInputLen := StrLen;
// ReadThread.FInputLen := FInputLen;
end;
procedure TComm.SetInBufferSize(StrSize: Word);
begin
if StrSize = 0 then
FInBufferSize := 1
else
FInBufferSize := StrSize;
// ReadThread.FInBufferSize := FInBufferSize;
end;
//
// FUNCTION: GetModemState
//
// PURPOSE: Read the state of modem input pin right now
//
// PARAMETERS:
// none
//
// RETURN VALUE:
//
// A DWORD variable containing one or more of following codes:
//
// Value Meaning
// ---------- -----------------------------------------------------------
// MS_CTS_ON The CTS (clear-to-send) signal is on.
// MS_DSR_ON The DSR (data-set-ready) signal is on.
// MS_RING_ON The ring indicator signal is on.
// MS_RLSD_ON The RLSD (receive-line-signal-detect) signal is on.
//
// If this comm have bad handle or not yet opened, the return value is 0
//
// COMMENTS:
//
// This member function calls GetCommModemStatus and return its value.
// Before calling this member function, you must have a successful
// 'StartOpen' call.
//
//
function TComm.GetModemState: DWORD;
var
dwModemState: DWORD;
begin
if not GetCommModemStatus(hCommFile, dwModemState) then
Result := 0
else
Result := dwModemState
end;
(* **************************************************************************** *)
// TComm PROTECTED METHODS
(* **************************************************************************** *)
//
// FUNCTION: CloseReadThread
//
// PURPOSE: Close the Read Thread.
//
// PARAMETERS:
// none
//
// RETURN VALUE:
// none
//
// COMMENTS:
//
// Closes the Read thread by signaling the CloseEvent.
// Purges any outstanding reads on the comm port.
//
// Note that terminating a thread leaks memory.
// Besides the normal leak incurred, there is an event object
// that doesn't get closed. This isn't worth worrying about
// since it shouldn't happen anyway.
//
//
procedure TComm.CloseReadThread;
begin
// If it exists...
if ReadThread <> nil then
begin
// Signal the event to close the worker threads.
SetEvent(hCloseEvent);
// Purge all outstanding reads
PurgeComm(hCommFile, PURGE_RXABORT + PURGE_RXCLEAR);
// Wait 10 seconds for it to exit. Shouldn't happen.
if (WaitForSingleObject(ReadThread.Handle, 10000) = WAIT_TIMEOUT) then
ReadThread.Terminate;
ReadThread.Free;
ReadThread := nil
end
end; { TComm.CloseReadThread }
//
// FUNCTION: CloseWriteThread
//
// PURPOSE: Closes the Write Thread.
//
// PARAMETERS:
// none
//
// RETURN VALUE:
// none
//
// COMMENTS:
//
// Closes the write thread by signaling the CloseEvent.
// Purges any outstanding writes on the comm port.
//
// Note that terminating a thread leaks memory.
// Besides the normal leak incurred, there is an event object
// that doesn't get closed. This isn't worth worrying about
// since it shouldn't happen anyway.
//
//
procedure TComm.CloseWriteThread;
begin
// If it exists...
if WriteThread <> nil then
begin
// Signal the event to close the worker threads.
SetEvent(hCloseEvent);
// Purge all outstanding writes.
PurgeComm(hCommFile, PURGE_TXABORT + PURGE_TXCLEAR);
FSendDataEmpty := True;
// Wait 10 seconds for it to exit. Shouldn't happen.
if WaitForSingleObject(WriteThread.Handle, 10000) = WAIT_TIMEOUT then
WriteThread.Terminate;
WriteThread.Free;
WriteThread := nil
end
end; { TComm.CloseWriteThread }
procedure TComm.ReceiveData(Buffer: PAnsiChar; BufferLength: Word);
begin
if Assigned(FOnReceiveData) then // 如果添加了用户串口事件处理则执行
FOnReceiveData(self, Buffer, BufferLength) // 用户串口事件处理
end;
procedure TComm.ReceiveError(EvtMask: DWORD);
begin
if Assigned(FOnReceiveError) then
FOnReceiveError(self, EvtMask)
end;
procedure TComm.ModemStateChange(ModemEvent: DWORD);
begin
if Assigned(FOnModemStateChange) then
FOnModemStateChange(self, ModemEvent)
end;
procedure TComm.RequestHangup;
begin
if Assigned(FOnRequestHangup) then
FOnRequestHangup(self)
end;
procedure TComm._SendDataEmpty;
begin
if Assigned(FOnSendDataEmpty) then
FOnSendDataEmpty(self)
end;
(* **************************************************************************** *)
// TComm PRIVATE METHODS
(* **************************************************************************** *)
procedure TComm.CommWndProc(var msg: TMessage);
begin
case msg.msg of
PWM_GOTCOMMDATA:
begin
ReceiveData(PAnsiChar(msg.LPARAM), msg.WPARAM);
LocalFree(msg.LPARAM)
end;
PWM_RECEIVEERROR:
ReceiveError(msg.LPARAM);
PWM_MODEMSTATECHANGE:
ModemStateChange(msg.LPARAM);
PWM_REQUESTHANGUP:
RequestHangup;
PWM_SENDDATAEMPTY:
_SendDataEmpty
end
end;
procedure TComm._SetCommState;
var
dcb: Tdcb;
commprop: TCommProp;
fdwEvtMask: DWORD;
begin
// Configure the comm settings.
// NOTE: Most Comm settings can be set through TAPI, but this means that
// the CommFile will have to be passed to this component.
GetCommState(hCommFile, dcb);
GetCommProperties(hCommFile, commprop);
GetCommMask(hCommFile, fdwEvtMask);
// fAbortOnError is the only DCB dependancy in TapiComm.
// Can't guarentee that the SP will set this to what we expect.
{ dcb.fAbortOnError := False; NOT VALID }
dcb.BaudRate := FBaudRate;
dcb.Flags := 1; // Enable fBinary
if FParityCheck then
dcb.Flags := dcb.Flags or 2; // Enable parity check
// setup hardware flow control
if FOutx_CtsFlow then
dcb.Flags := dcb.Flags or 4;
if FOutx_DsrFlow then
dcb.Flags := dcb.Flags or 8;
if FDtrControl = DtrEnable then
dcb.Flags := dcb.Flags or $10
else if FDtrControl = DtrHandshake then
dcb.Flags := dcb.Flags or $20;
if FDsrSensitivity then
dcb.Flags := dcb.Flags or $40;
if FTxContinueOnXoff then
dcb.Flags := dcb.Flags or $80;
if FOutx_XonXoffFlow then
dcb.Flags := dcb.Flags or $100;
if FInx_XonXoffFlow then
dcb.Flags := dcb.Flags or $200;
if FReplaceWhenParityError then
dcb.Flags := dcb.Flags or $400;
if FIgnoreNullChar then
dcb.Flags := dcb.Flags or $800;
if FRtsControl = RtsEnable then
dcb.Flags := dcb.Flags or $1000
else if FRtsControl = RtsHandshake then
dcb.Flags := dcb.Flags or $2000
else if FRtsControl = RtsTransmissionAvailable then
dcb.Flags := dcb.Flags or $3000;
dcb.XonLim := FXonLimit;
dcb.XoffLim := FXoffLimit;
dcb.ByteSize := Ord(FByteSize) + 5;
dcb.Parity := Ord(FParity);
dcb.StopBits := Ord(FStopBits);
dcb.XonChar := FXonChar;
dcb.XoffChar := FXoffChar;
dcb.ErrorChar := FReplacedChar;
SetCommState(hCommFile, dcb)
end;
procedure TComm._SetCommTimeout;
var
commtimeouts: TCommTimeouts;
begin
GetCommTimeouts(hCommFile, commtimeouts);
// The CommTimeout numbers will very likely change if you are
// coding to meet some kind of specification where
// you need to reply within a certain amount of time after
// recieving the last byte. However, If 1/4th of a second
// goes by between recieving two characters, its a good
// indication that the transmitting end has finished, even
// assuming a 1200 baud modem.
commtimeouts.ReadIntervalTimeout := FReadIntervalTimeout;
commtimeouts.ReadTotalTimeoutMultiplier := FReadTotalTimeoutMultiplier;
commtimeouts.ReadTotalTimeoutConstant := FReadTotalTimeoutConstant;
commtimeouts.WriteTotalTimeoutMultiplier := FWriteTotalTimeoutMultiplier;
commtimeouts.WriteTotalTimeoutConstant := FWriteTotalTimeoutConstant;
SetCommTimeouts(hCommFile, commtimeouts);
end;
procedure TComm.SetPortOpen(b: Boolean); // 打开端口
begin
if b = True then
StartComm // 打开端口
else
StopComm; // 关闭端口
end;
function TComm.GetPortOpen: Boolean; // 打开端口
begin
if hCommFile = 0 then
begin
FPortOpen := False;
Result := False;
end
else
begin
FPortOpen := True;
Result := True;
end;
end;
procedure TComm.SetCommPort(CommPort: BYTE);
begin
if (CommPort <> 0) and (CommPort <> FCommPort) then
begin
FCommPort := CommPort;
FCommName := 'COM' + inttostr(CommPort);
end;
end;
procedure TComm.SetBaudRate(Rate: DWORD);
begin
if Rate = FBaudRate then
Exit;
FBaudRate := Rate;
if hCommFile <> 0 then
_SetCommState
end;
procedure TComm.SetParityCheck(b: Boolean);
begin
if b = FParityCheck then
Exit;
FParityCheck := b;
if hCommFile <> 0 then
_SetCommState
end;
procedure TComm.SetOutx_CtsFlow(b: Boolean);
begin
if b = FOutx_CtsFlow then