Witam.
Posiadam program, który komunikuje się ze sterownikami PLC. Mój problem polega na tym, że odczyt/zapis bufora rs232 spowalnia cały program. Wiem, że powinienem zrobić odczyt/zapis w wątku, w związku z tym prosiłbym o pomoc.
Poniżej zamieszczam kod modułu odpowiedzialnego za komunikacje:
unit Srl_Com;
interface
uses WinTypes, WinProcs, Messages, Classes, SysUtils;
type Array_type=array[0..110] of Char;
TComm_Obj = class(TObject)
DeviceID, n: Cardinal;
TempWrt: integer;
Check: byte;
ReadStat: LongBool;
Build: LongBool;
DCB: TDCB;
Buffor1:Array_type;
Buffor:array[0..20] of Char;
PortNr: array[0..12] of Char;
DCBStruct:array[0..56] of Char;
procedure Set_Params(Nr_portu, Boudrate, parity, bits: integer);
procedure EndComm;
procedure Komunikuj(Check1:PChar);
procedure ReadComm(var Buffer; BytesToRead: Integer);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Serial_comm: TComm_Obj;
const
Group_nr: integer=1;
Tmp1:word=0;
implementation
procedure TComm_Obj.Set_Params(Nr_portu, Boudrate, parity, bits: integer);
var
sString: array[0..5] of Char;
Numer:array[0..3] of Char;
s: AnsiString;
timeouts: TCommTimeouts;
begin
FillChar(timeouts, SizeOf(timeouts), 0);
// wszystkie czasy są w milisekundach (ms)
timeouts.ReadIntervalTimeout := 0; // maks. opoznienie pomiedzy dwoma kolejnymi bajtami dla odczytu
timeouts.ReadTotalTimeoutConstant := 650; // stale opoznienie dla odczytu
timeouts.ReadTotalTimeoutMultiplier := 0; // opoznienie dla kazdego odczytywanego bajta - 5
timeouts.WriteTotalTimeoutConstant := 650 ; // stale opoznienie dla zapisu
timeouts.WriteTotalTimeoutMultiplier := 0; // opoznienie dla kazdego wysylanego bajta - 5
s := '\\.\COM' + IntToStr(Nr_portu);
DeviceID := CreateFile(@s[1], GENERIC_READ or GENERIC_WRITE,
0, nil, OPEN_EXISTING, 0, 0);
if DeviceID = INVALID_HANDLE_VALUE then
raise EInOutError.Create('Nie można otworzyć portu COM' + IntToStr(Nr_portu));
GetCommState(DeviceID, DCB);
FillChar(DCBStruct, sizeof(DCBStruct), #0);
s := 'COM' + IntToStr(Nr_portu) + ':12,E,7';
StrCopy(DCBStruct, @s[1]);
Build := BuildCommDCB(DCBStruct, DCB);
DCB.StopBits := ONESTOPBIT;
if not SetCommState(DeviceID, DCB) then
raise EInOutError.Create('Nie można zmienić parametrów portu COM' + IntToStr(Nr_portu));
if not SetCommTimeouts(DeviceID, timeouts) then
raise EInOutError.Create('Nie można zmienić opóźnień dla portu COM ' + IntToStr(Nr_portu));
SetupComm(DeviceID, 512, 1024);
end;
procedure TComm_Obj.EndComm;
begin
CloseHandle(DeviceID);
// CloseComm(DeviceID);
end;
procedure TComm_Obj.Komunikuj(Check1:PChar);
var
written: Cardinal;
begin
FillChar (Buffor, SizeOf(Buffor), #0);
StrECopy (Buffor, Check1);
WriteFile(DeviceID, Buffor, SizeOf(Buffor), written, nil);
// WriteComm (DeviceID, Buffor, Sizeof(Buffor));
end;
procedure TComm_Obj.ReadComm(var Buffer; BytesToRead: Integer);
var
read: Cardinal;
begin
ReadStat := ReadFile(DeviceID, Buffer, BytesToRead, read, nil);
end;
end.