![]() |
| ||
|
|
Новости |
Поиск |
FAQ |
Статьи |
Книги |
Новости VCL
| | Форумы ЧАТ |
Орешник |
|
| |||
| |||
« предыдущая ветвь | форум | следующая ветвь »
Проблема с преоброзованием байтов из ком порта [D7, WinXP]
Рафик © (2006-03-30 10:07:00)procedure ReadComm;
var
Resive:array [0..255] of char;
begin
TransMask:=0;
WaitCommEvent(CommHandle,TransMask,@Ovr); ClearCommError(CommHandle,Errs,@Stat);
Kols := Stat.cbInQue;
ReadFile(CommHandle,Resive,Kols,Kols,@Ovr) ;
Form1.Edit2.Text:=Resive;
end;
В результате в едите "с*NЂ?РNЂЁЊ„юќВMЂDЋ„юp\x10њюDЋ„юLЋ„юЁЊ„юЁЊ„"
Что я неправильно делаю помогите пожалуста!
tesseract (2006-03-30 17:59:00) [1]
> Зависает на этом процессе чего может быть?
А она от порта ждёт информации.
А ты в ожидание забубухал и маску порта и чтения файла см [3] .
Забыл правда WaitCommEvent
Пример ожидания маски и получения сколько пришло:
function TcomPort.pApiGetInCount: dword;
var hCurState:TCOMSTAT;
ErrCode:cardinal;
begin
ClearCommError(hCom, ErrCode, @hCurState);
result:=hCurState.cbInQue;
end;
function TcomPort.pDirectGetInCount: dword;
var State:TSerialStatus;
skip:dword;
begin
DeviceIOControl(hCom,GetCtrlCode(27),nil,0,@State,sizeof(state),skip,nil);
result:=state.AmountInInQueue;
end;
function TcomPort.fApiMaskWait(size:cardinal):boolean;
var tMask:Cardinal;
fSignaled:integer;
tmp:cardinal;
begin
result:=false;
tMask:=0;
if WaitCommEvent(hCom,tMask,@MaskOL) then exit;
fSignaled:= WaitForSingleObject(MaskOl.hEvent,WaitInt);
if fSignaled = WAIT_TIMEOUT then begin cancelIo(hcom); exit; end;
if (fSignaled = WAIT_OBJECT_0) then
begin
// смотрим что у нас
// Читаем
if GetOverlappedResult(hCom, MaskOL,tmp ,true) then
begin
// Сравниваем произошедшее событие с прибытием символа
if (tMask xor EV_RXCHAR)=0 then
begin
if PApiGetInCount>=size then result:=true else result:=false;
end; // if (tmask and EV_RXCHAR)
end; // if GetOverlappedResult(hCom, REadOL, ReadBytes,false) then
end; // if (fSignaled = WAIT_OBJECT_0) then
end;
Сергей М. (2006-03-30 15:42:00) [2]Справку читать пытался ?
Рафик (2006-03-30 15:27:00) [3]Прислали бы мне целый проект рабочий я б его поюзал и разобрался бы!
Рафик (2006-03-30 15:15:00) [4]Ну скажите что сделать чтоб он заработал я не понимаю, не доходит чуток
Сергей М. (2006-03-30 15:13:00) [5]
> WaitCommEvent(CommHandle,TransMask,@Ovr); //ждем
Нет, не ждем.
У тебя, еще раз повторяю, - overlapped-режим.
Читай справку и вникай :
If the overlapped operation cannot be completed immediately, the function returns FALSE and the GetLastError function returns ERROR_IO_PENDING, indicating that the operation is executing in the background. When this happens, the system sets the hEvent member of the OVERLAPPED structure to the not-signaled state before WaitCommEvent returns, and then it sets it to the signaled state when one of the specified events or an error occurs. The calling process can use one of the wait functions to determine the event object's state and then use the GetOverlappedResult function to determine the results of the WaitCommEvent operation. GetOverlappedResult reports the success or failure of the operation, and the variable pointed to by the lpEvtMask parameter is set to indicate the event that occurred.
Чтоне понятно ?
Рафик (2006-03-30 14:57:00) [6]procedure ReadComm;
var
Resive:array [0..255] of char;
begin
while true do
begin
TransMask:=0;
WaitCommEvent(CommHandle,TransMask,@Ovr); //ждем
if (TransMask and EV_RXFLAG)=EV_RXFLAG then //проверяем нужное событие
begin
ClearCommError(CommHandle,Errs,@Stat);//сбрасываем флаг
Kols := Stat.cbInQue;
ReadFile(CommHandle,Resive,Kols,Kols,@Ovr);//читаем
//тут должна идти обработка принятой информации из Resive
Form1.Edit1.Text:=string(Resive);
//не очень хороший вариант вывода, но для примера подойдет
end;//mask
end;//while
end;
Зависает на этом процессе чего может быть?
Сергей М. (2006-03-30 11:04:00) [7]Дождаться события, хэндл которого указан в структуре ovr.
Либо вообще не использовать overlapped-режим
Рафик (2006-03-30 10:39:00) [8]Удалено модератором
tesseract (2006-03-30 10:35:00) [9]
> Неверно используешь overlapped-режим.
И это тоже но
FillChar(Resive,255,#32);
исчезнет мусор.
пример overlapped Для маски и readFile желательны разные overlapped структуры.
fSignaled:= WaitForSingleObject(MaskOl.hEvent,WaitInt);
if fSignaled = WAIT_TIMEOUT then begin cancelIo(hcom); exit; end;
if (fSignaled = WAIT_OBJECT_0) then
begin
// смотрим что у нас
// Читаем
if GetOverlappedResult(hCom, MaskOL,tmp ,true) then
// Сравниваем произошедшее событие с прибытием символа
if (tMask xor EV_RXCHAR)=0 then
begin
succ :=ReadFile(hCom,buffer,inBuf,result,@REadOL);
if not succ then
begin
tmp:=GetLastError;
if tmp=ERROR_IO_PENDING then
if WaitForSingleObject(ReadOl.hEvent,WaitInt)=WAIT_OBJECT_0 then
GetOverlappedResult(hCom, ReadOL, result,true);
end;
end;
end;
Старик (2006-03-30 10:35:00) [10]Удалено модератором
Примечание: Личная переписка
Рафик (2006-03-30 10:30:00) [11]Так как мне получить данные в Hex?
Сергей М. (2006-03-30 10:18:00) [12]
> Что я неправильно делаю
Неверно используешь overlapped-режим.