where : ibrtses delphi
Delphi - a communication thread
disclaimer
the source code of this page may not appear correctly in certain browsers
due to special characters. Have a look at the source of this HTML page
with notepad instead
A communication thread
It is quite common that communication is a sequence of messages where
the sequence matters. Communication applications are special in this respect as messages can disappear. This means, it can be a requirement
to have the replies of previous messages before issuing the next.
This functionality is best done with a thread.
The messages to be sent come from various events, timer, buttons,
whatver and are gathered with a Queue.
{
formcreate:
CQ:=TSimpleMsgQueue.create;
CommThread.queue:=CQ;
CommThread.sp:=sp;
Commthread.lostpackets:=0;
CS:=TCommThread.create(false);
rxcame:=true;
procedure TForm1.SendMsgClick(Sender: TObject);
var u:TMyMsg;
s,v:shortstring;
i,j:integer;
begin
s:=a_command;
v:=just_a_header+s;
calcCRC(v);
v:=header+v;
i:=length(v);
u:=TMyMsg.create(i);
u.asstring:=v;
u.delay:=0;
CQ.queuein(u);
end;
procedure TForm1.MakeDelayClick(Sender: TObject);
var u:TMyMsg;
i,j:integer;
begin
u:=TMyMsg.create(0);
u.delay:=1000;
CQ.queuein(u);
end;
}
unit CommThread;
interface
uses
Windows,Classes,StdCtrls,MyMsgQueue,OoMisc,Adport;
const
//mtimeout=500;
sleeptime=50;
type
TCommThread = class(TThread)
private
{ Private declarations }
protected
procedure Execute; override;
procedure send;
end;
VAR queue:TSimpleMsgQueue;
sp: TApdComPort;
h:shortstring;
rxcame:boolean;
rxstring:shortstring;
rxstate:integer;
lostpackets:integer;
mtimeout:integer;
ErrorLog:TMemo;
PacketOrigin:integer;
implementation
uses mystrings;
{ Important: Methods and properties of objects in VCL can only be used in a
method called using Synchronize, for example,
Synchronize(UpdateCaption);
and UpdateCaption could look like,
procedure TCommThread.UpdateCaption;
begin
Form1.Caption := 'Updated in a thread';
end; }
{ TCommThread }
procedure TCommThread.send;
begin
sp.putstring(h);
end;
procedure TCommThread.Execute;
var p:TMyMsg;
tcount:integer;
z:shortstring;
begin
{ Place thread code here }
tcount:=0;
while not terminated do begin
if (queue.count < > 0)and(rxcame) then begin
p:=queue.queueout;
h:=p.asstring;
PacketOrigin:=p.origin;
if (h < > '') then rxcame:=false; // empty packets are a delay only
rxstring:='';
rxstate:=0;
tcount:=0;
sleep(p.delay); // wait before send
sleep(50);
synchronize(send);
p.destroy;
end;
sleep(sleeptime);
if (not rxcame) then begin
inc(tcount);
if ((tcount*sleeptime) > mtimeout) then begin
inc(lostpackets);
tcount:=0;
synchronize(send);
end;
end;
end; // while
end;
end.
Feedback is welcome
sponsored links
Delphi index
ibrt home
last updated: 12.april.04 or perhaps later
Copyright (99,2004) Ing.Büro R.Tschaggelar