-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathDataPortSerial.pas
583 lines (523 loc) · 15.3 KB
/
DataPortSerial.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
{
Serial communication port (UART). In Windows it COM-port, real or virtual.
In Linux it /dev/ttyS or /dev/ttyUSB. Also, Linux use file /var/lock/LCK..ttyS for port locking
(C) Sergey Bodrov, 2012-2018
Properties:
Port - port name (COM1, /dev/ttyS01)
BaudRate - data excange speed
MinDataBytes - minimal bytes count in buffer for triggering event OnDataAppear
Methods:
Open() - Opens port. As parameter it use port initialization string:
InitStr = 'Port,BaudRate,DataBits,Parity,StopBits,SoftFlow,HardFlow'
Port - COM port name (COM1, /dev/ttyS01)
BaudRate - connection speed (50..4000000 bits per second), default 9600
DataBits - default 8
Parity - (N - None, O - Odd, E - Even, M - Mark or S - Space) default N
StopBits - (1, 1.5, 2)
SoftFlow - Enable XON/XOFF byte ($11 for resume and $13 for pause transmission), default 1
HardFlow - Enable CTS/RTS handshake, default 0
Events:
OnOpen - Triggered after sucсessful connection.
OnClose - Triggered after disconnection.
}
unit DataPortSerial;
{$IFDEF FPC}
{$MODE DELPHI}
{$DEFINE NO_LIBC}
{$ENDIF}
interface
uses
{$IFNDEF MSWINDOWS}
{$IFNDEF NO_LIBC}
Libc,
KernelIoctl,
{$ELSE}
termio, baseunix, unix,
{$ENDIF}
{$IFNDEF FPC}
Types,
{$ENDIF}
{$ELSE}
Windows,
{$ENDIF}
SysUtils, Classes, DataPort, DataPortUART, synaser, synautil;
type
{ TSerialClient - serial port reader/writer, based on Ararat Synapse }
TSerialClient = class(TThread)
private
FSerial: TBlockSerial;
sFromPort: AnsiString;
sLastError: string;
FSafeMode: Boolean;
FOnIncomingMsgEvent: TMsgEvent;
FOnErrorEvent: TMsgEvent;
FOnConnectEvent: TNotifyEvent;
FDoConfig: Boolean;
procedure SyncProc();
procedure SyncProcOnError();
procedure SyncProcOnConnect();
protected
FParentDataPort: TDataPortUART;
function IsError(): Boolean;
procedure Execute(); override;
public
sPort: string;
BaudRate: Integer;
DataBits: Integer;
Parity: char;
StopBits: TSerialStopBits;
FlowControl: TSerialFlowControl;
CalledFromThread: Boolean;
sToSend: AnsiString;
SleepInterval: Integer;
constructor Create(AParent: TDataPortUART); reintroduce;
property SafeMode: Boolean read FSafeMode write FSafeMode;
property Serial: TBlockSerial read FSerial;
property OnIncomingMsgEvent: TMsgEvent read FOnIncomingMsgEvent
write FOnIncomingMsgEvent;
property OnErrorEvent: TMsgEvent read FOnErrorEvent write FOnErrorEvent;
property OnConnectEvent: TNotifyEvent read FOnConnectEvent write FOnConnectEvent;
{ Set port parameters (baud rate, data bits, etc..) }
procedure Config();
function SendString(const AData: AnsiString): Boolean;
procedure SendStream(st: TStream);
end;
{ TDataPortSerial - serial DataPort }
TDataPortSerial = class(TDataPortUART)
private
FSerialClient: TSerialClient;
function CloseClient(): Boolean;
protected
procedure SetBaudRate(AValue: Integer); override;
procedure SetDataBits(AValue: Integer); override;
procedure SetParity(AValue: AnsiChar); override;
procedure SetStopBits(AValue: TSerialStopBits); override;
procedure SetFlowControl(AValue: TSerialFlowControl); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy(); override;
{ Open serial DataPort
InitStr = 'Port,BaudRate,DataBits,Parity,StopBits,SoftFlow,HardFlow'
Port - COM port name (COM1, /dev/tty01)
BaudRate - connection speed (50..4000000 bits per second), default 9600
DataBits - default 8
Parity - (N - None, O - Odd, E - Even, M - Mark or S - Space) default N
StopBits - (1, 1.5, 2)
SoftFlow - Enable XON/XOFF handshake, default 0
HardFlow - Enable CTS/RTS handshake, default 0 }
procedure Open(const AInitStr: string = ''); override;
procedure Close(); override;
function Push(const AData: AnsiString): Boolean; override;
class function GetSerialPortNames(): string;
{ Get modem wires status (DSR,CTS,Ring,Carrier) }
function GetModemStatus(): TModemStatus; override;
{ Set DTR (Data Terminal Ready) signal }
procedure SetDTR(AValue: Boolean); override;
{ Set RTS (Request to send) signal }
procedure SetRTS(AValue: Boolean); override;
property SerialClient: TSerialClient read FSerialClient;
published
{ Serial port name (COM1, /dev/ttyS01) }
property Port: string read FPort write FPort;
{ BaudRate - connection speed (50..4000000 bits per second), default 9600 }
property BaudRate: Integer read FBaudRate write SetBaudRate;
{ DataBits - default 8 (5 for Baudot code, 7 for true ASCII) }
property DataBits: Integer read FDataBits write SetDataBits;
{ Parity - (N - None, O - Odd, E - Even, M - Mark or S - Space) default N }
property Parity: AnsiChar read FParity write SetParity;
{ StopBits - (stb1, stb15, stb2), default stb1 }
property StopBits: TSerialStopBits read FStopBits write SetStopBits;
{ FlowControl - (sfcNone, sfcSend, sfcReady, sfcSoft) default sfcNone }
property FlowControl: TSerialFlowControl read FFlowControl write SetFlowControl;
{ Minimum bytes in incoming buffer to trigger OnDataAppear }
property MinDataBytes: Integer read FMinDataBytes write FMinDataBytes;
property Active;
property OnDataAppear;
property OnError;
property OnOpen;
property OnClose;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('DataPort', [TDataPortSerial]);
end;
// === TSerialClient ===
constructor TSerialClient.Create(AParent: TDataPortUART);
begin
inherited Create(True);
FParentDataPort := AParent;
SleepInterval := 10;
end;
procedure TSerialClient.Config();
begin
FDoConfig := True;
end;
procedure TSerialClient.SyncProc();
begin
if not CalledFromThread then
begin
CalledFromThread := True;
try
if Assigned(OnIncomingMsgEvent) then
OnIncomingMsgEvent(Self, sFromPort);
finally
CalledFromThread := False;
end;
end;
end;
procedure TSerialClient.SyncProcOnError();
begin
if not CalledFromThread then
begin
CalledFromThread := True;
try
if Assigned(OnErrorEvent) then
OnErrorEvent(Self, sLastError);
finally
CalledFromThread := False;
end;
end;
end;
procedure TSerialClient.SyncProcOnConnect();
begin
if not CalledFromThread then
begin
CalledFromThread := True;
try
if Assigned(OnConnectEvent) then
OnConnectEvent(Self);
finally
CalledFromThread := False;
end;
end;
end;
function TSerialClient.IsError(): Boolean;
begin
Result := (Serial.LastError <> 0) and (Serial.LastError <> ErrTimeout);
if Result then
begin
sLastError := Serial.LastErrorDesc;
if Assigned(FParentDataPort.OnError) then
Synchronize(SyncProcOnError)
else if Assigned(OnErrorEvent) then
OnErrorEvent(Self, sLastError);
Terminate();
end
end;
procedure TSerialClient.Execute();
var
SoftFlow: Boolean;
HardFlow: Boolean;
iStopBits: Integer;
begin
sLastError := '';
SoftFlow := False;
HardFlow := False;
iStopBits := 1;
if Terminated then Exit;
FSerial := TBlockSerial.Create();
try
Serial.DeadlockTimeout := 3000;
Serial.Connect(sPort);
Sleep(SleepInterval);
if Serial.LastError = 0 then
begin
case StopBits of
stb1: iStopBits := SB1;
stb15: iStopBits := SB1andHalf;
stb2: iStopBits := SB2;
end;
if FlowControl = sfcSoft then
SoftFlow := True
else if FlowControl = sfcSend then
HardFlow := True;
Serial.Config(BaudRate, DataBits, Parity, iStopBits, SoftFlow, HardFlow);
FDoConfig := False;
Sleep(SleepInterval);
end;
if not IsError() then
begin
if Assigned(FParentDataPort.OnOpen) then
Synchronize(SyncProcOnConnect)
else if Assigned(OnConnectEvent) then
OnConnectEvent(Self);
end;
while not Terminated do
begin
sLastError := '';
Serial.GetCommState();
if IsError() then
Break;
if FDoConfig then
begin
if FlowControl = sfcSoft then
SoftFlow := True
else if FlowControl = sfcSend then
HardFlow := True;
Serial.Config(BaudRate, DataBits, Parity, iStopBits, SoftFlow, HardFlow);
FDoConfig := False;
Sleep(SleepInterval);
end
else
begin
sFromPort := Serial.RecvPacket(SleepInterval);
end;
if IsError() then
Break
else if (Length(sFromPort) > 0) then
begin
try
if Assigned(FParentDataPort.OnDataAppear) then
Synchronize(SyncProc)
else
if Assigned(OnIncomingMsgEvent) then
OnIncomingMsgEvent(Self, sFromPort);
finally
sFromPort := '';
end;
end;
Sleep(1);
if sToSend <> '' then
begin
if Serial.CanWrite(SleepInterval) then
begin
Serial.SendString(sToSend);
if IsError() then
Break;
sToSend := '';
end;
end;
end;
finally
FreeAndNil(FSerial);
end;
end;
function TSerialClient.SendString(const AData: AnsiString): Boolean;
begin
Result := False;
if not Assigned(Self.Serial) then
Exit;
if SafeMode then
Self.sToSend := Self.sToSend + AData
else
begin
if Serial.CanWrite(100) then
Serial.SendString(AData);
if (Serial.LastError <> 0) and (Serial.LastError <> ErrTimeout) then
begin
sLastError := Serial.LastErrorDesc;
Synchronize(SyncProc);
Exit;
end;
end;
Result := True;
end;
procedure TSerialClient.SendStream(st: TStream);
var
ss: TStringStream;
begin
if not Assigned(Self.Serial) then
Exit;
if SafeMode then
begin
ss := TStringStream.Create('');
try
ss.CopyFrom(st, st.Size);
Self.sToSend := Self.sToSend + ss.DataString;
finally
ss.Free();
end;
end
else
begin
Serial.SendStreamRaw(st);
if Serial.LastError <> 0 then
begin
sLastError := Serial.LastErrorDesc;
Synchronize(SyncProc);
end;
end;
end;
{ TDataPortSerial }
constructor TDataPortSerial.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FSerialClient := nil;
end;
destructor TDataPortSerial.Destroy();
begin
if Assigned(FSerialClient) then
begin
FSerialClient.OnIncomingMsgEvent := nil;
FSerialClient.OnErrorEvent := nil;
FSerialClient.OnConnectEvent := nil;
FreeAndNil(FSerialClient);
end;
inherited Destroy();
end;
function TDataPortSerial.CloseClient(): Boolean;
begin
Result := True;
if Assigned(FSerialClient) then
begin
Result := not FSerialClient.CalledFromThread;
if Result then
begin
FSerialClient.OnIncomingMsgEvent := nil;
FSerialClient.OnErrorEvent := nil;
FSerialClient.OnConnectEvent := nil;
FreeAndNil(FSerialClient);
end
else
FSerialClient.Terminate()
end;
end;
procedure TDataPortSerial.Open(const AInitStr: string = '');
{$IFDEF UNIX}
var
s: string;
{$ENDIF}
begin
inherited Open(AInitStr);
if not CloseClient() then
Exit;
FSerialClient := TSerialClient.Create(Self);
FSerialClient.OnIncomingMsgEvent := OnIncomingMsgHandler;
FSerialClient.OnErrorEvent := OnErrorHandler;
FSerialClient.OnConnectEvent := OnConnectHandler;
FSerialClient.SafeMode := HalfDuplex;
FSerialClient.sPort := FPort;
FSerialClient.BaudRate := FBaudRate;
FSerialClient.DataBits := FDataBits;
FSerialClient.Parity := FParity;
FSerialClient.StopBits := FStopBits;
FSerialClient.FlowControl := FFlowControl;
// Check serial port
//if Pos(Port, synaser.GetSerialPortNames())=0 then Exit;
{$IFDEF UNIX}
// detect lock file name
if Pos('tty', Port) > 0 then
begin
s := '/var/lock/LCK..' + Copy(Port, Pos('tty', Port), maxint);
if FileExists(s) then
begin
// try to remove lock file (if any)
DeleteFile(s);
end;
end;
{$ENDIF}
FSerialClient.Suspended := False;
// don't set FActive - will be set in OnConnect event after successfull connection
end;
procedure TDataPortSerial.Close();
begin
if Assigned(FSerialClient) then
begin
if FSerialClient.CalledFromThread then
FSerialClient.Terminate()
else
FreeAndNil(FSerialClient);
end;
inherited Close();
end;
class function TDataPortSerial.GetSerialPortNames: string;
begin
Result := synaser.GetSerialPortNames();
end;
function TDataPortSerial.GetModemStatus(): TModemStatus;
var
ModemWord: Integer;
begin
if Assigned(SerialClient) and Assigned(SerialClient.Serial) then
begin
ModemWord := SerialClient.Serial.ModemStatus();
{$IFNDEF MSWINDOWS}
FModemStatus.DSR := (ModemWord and TIOCM_DSR) > 0;
FModemStatus.CTS := (ModemWord and TIOCM_CTS) > 0;
FModemStatus.Carrier := (ModemWord and TIOCM_CAR) > 0;
FModemStatus.Ring := (ModemWord and TIOCM_RNG) > 0;
{$ELSE}
FModemStatus.DSR := (ModemWord and MS_DSR_ON) > 0;
FModemStatus.CTS := (ModemWord and MS_CTS_ON) > 0;
FModemStatus.Carrier := (ModemWord and MS_RLSD_ON) > 0;
FModemStatus.Ring := (ModemWord and MS_RING_ON) > 0;
{$ENDIF}
end;
Result := inherited GetModemStatus;
end;
procedure TDataPortSerial.SetDTR(AValue: Boolean);
begin
if Assigned(SerialClient) and Assigned(SerialClient.Serial) then
begin
SerialClient.Serial.DTR := AValue;
end;
inherited SetDTR(AValue);
end;
procedure TDataPortSerial.SetRTS(AValue: Boolean);
begin
if Assigned(SerialClient) and Assigned(SerialClient.Serial) then
begin
SerialClient.Serial.RTS := AValue;
end;
inherited SetRTS(AValue);
end;
function TDataPortSerial.Push(const AData: AnsiString): Boolean;
begin
Result := False;
if Assigned(SerialClient) and FLock.BeginWrite() then
begin
try
Result := SerialClient.SendString(AData);
finally
FLock.EndWrite();
end;
end;
end;
procedure TDataPortSerial.SetBaudRate(AValue: Integer);
begin
inherited SetBaudRate(AValue);
if Active then
begin
SerialClient.BaudRate := FBaudRate;
SerialClient.Config();
end;
end;
procedure TDataPortSerial.SetDataBits(AValue: Integer);
begin
inherited SetDataBits(AValue);
if Active then
begin
SerialClient.DataBits := FDataBits;
SerialClient.Config();
end;
end;
procedure TDataPortSerial.SetParity(AValue: AnsiChar);
begin
inherited SetParity(AValue);
if Active then
begin
SerialClient.Parity := FParity;
SerialClient.Config();
end;
end;
procedure TDataPortSerial.SetFlowControl(AValue: TSerialFlowControl);
begin
inherited SetFlowControl(AValue);
if Active then
begin
SerialClient.FlowControl := FFlowControl;
SerialClient.Config();
end;
end;
procedure TDataPortSerial.SetStopBits(AValue: TSerialStopBits);
begin
inherited SetStopBits(AValue);
if Active then
begin
SerialClient.StopBits := FStopBits;
SerialClient.Config();
end;
end;
end.