source: PinConnection/CommSerialPort.pas

Last change on this file was 575, checked in by chronos, 5 months ago
  • Modified: Remove U prefix from unit names of PinConnection package.
File size: 2.4 KB
Line 
1unit CommSerialPort;
2
3interface
4
5uses
6 Classes, SerialPort, CommPin, SysUtils, DateUtils, SpecializedList,
7 SyncObjs;
8
9type
10
11 { TCommSerialPort }
12
13 TCommSerialPort = class(TCommNode)
14 private
15 procedure Receive(Sender: TCommPin; Stream: TListByte);
16 procedure SetStatus(Sender: TCommPin; AValue: Integer);
17 procedure ReceiveData(Stream: TListByte);
18 protected
19 procedure SetActive(const AValue: Boolean); override;
20 procedure AssignTo(Dest: TPersistent); override;
21 public
22 SerialPort: TSerialPort;
23 Pin: TCommPin;
24 destructor Destroy; override;
25 constructor Create(AOwner: TComponent); override;
26 end;
27
28
29implementation
30
31{ TCommSerialPort }
32
33procedure TCommSerialPort.ReceiveData(Stream: TListByte);
34begin
35 if SerialPort.Active then Pin.Send(Stream);
36end;
37
38procedure TCommSerialPort.SetActive(const AValue: Boolean);
39begin
40 inherited;
41 SerialPort.Active := AValue;
42 FActive := SerialPort.Active;
43end;
44
45procedure TCommSerialPort.AssignTo(Dest: TPersistent);
46begin
47 if Dest is TCommSerialPort then begin
48 TCommSerialPort(Dest).SerialPort.Assign(SerialPort);
49 end else inherited;
50end;
51
52procedure TCommSerialPort.SetStatus(Sender: TCommPin; AValue: Integer);
53begin
54 try
55 SerialPort.Lock.Acquire;
56 if (AValue and 1) = 1 then SerialPort.Parity := paMark
57 else SerialPort.Parity := paSpace;
58 finally
59 SerialPort.Lock.Release;
60 end;
61end;
62
63constructor TCommSerialPort.Create(AOwner: TComponent);
64begin
65 inherited;
66 SerialPort := TSerialPort.Create;
67 SerialPort.OnReceiveData := ReceiveData;
68 Pin := TCommPin.Create;
69 Pin.OnReceive := Receive;
70 Pin.OnSetSatus := SetStatus;
71 Pin.Node := Self;
72end;
73
74destructor TCommSerialPort.Destroy;
75begin
76 SerialPort.OnReceiveData := nil;
77 FreeAndNil(Pin);
78 FreeAndNil(SerialPort);
79 inherited;
80end;
81
82procedure TCommSerialPort.Receive(Sender: TCommPin; Stream: TListByte);
83var
84 S: TMemoryStream;
85begin
86 try
87 S := TMemoryStream.Create;
88 Stream.WriteToStream(S);
89 if SerialPort.Active then begin
90 S.Position := 0;
91 repeat
92 try
93 SerialPort.Lock.Acquire;
94 if SerialPort.CanWrite(0) then
95 SerialPort.SendStreamRaw(S);
96 finally
97 SerialPort.Lock.Release;
98 end;
99 if S.Position <> S.Size then
100 Sleep(1);
101 until S.Position = S.Size;
102 end;
103 finally
104 S.Free;
105 end;
106end;
107
108end.
Note: See TracBrowser for help on using the repository browser.