Purgecomm function failed error 5

Purgecomm Function Failed Error 6 We have collected for you the most relevant information on Purgecomm Function Failed Error 6, as well as possible solutions to this problem. Take a look at the links provided and find the solution that works. Other people have encountered Purgecomm Function Failed Error 6 before you, so use […]

Содержание

  1. Purgecomm Function Failed Error 6
  2. PurgeComm function (winbase.h) — Win32 apps Microsoft Docs
  3. ComPort Library / Discussion / Open Discussion: PurgeComm .
  4. PurgeComm Not Working as Expected on Windows Mobile Device
  5. ComPort Library / Discussion / Help: Purge Comm Error
  6. PKCS#11: Cannot perform signature 6:’CKR_FUNCTION_FAILED .
  7. PurgeComm error for LG client — GSM-Forum
  8. python — How can I fix «[Error 6] The handle is invalid .
  9. C++ (Cpp) PurgeComm Examples — HotExamples
  10. windows — SetupComm, SetCommState, SetCommTimeouts fail .
  11. failure in TComPort — embarcadero.delphi.tools
  12. Purgecomm Function Failed Error 6 Fixes & Solutions
  13. Arduino.ru
  14. Регистрация новых пользователей и создание новых тем теперь только на новом форуме https://forum.arduino.ru
  15. forum.arduino.ru
  16. Arduino Mega, Ошибка работы с COM портом

Purgecomm Function Failed Error 6

We have collected for you the most relevant information on Purgecomm Function Failed Error 6, as well as possible solutions to this problem. Take a look at the links provided and find the solution that works. Other people have encountered Purgecomm Function Failed Error 6 before you, so use the ready-made solutions.

PurgeComm function (winbase.h) — Win32 apps Microsoft Docs

    https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-purgecomm
    If the function fails, the return value is zero. To get extended error information, call GetLastError.

ComPort Library / Discussion / Open Discussion: PurgeComm .

    https://sourceforge.net/p/comport/discussion/261327/thread/8605e2ac/
    Dec 28, 2010 · Some styles failed to load. . That is a driver error, not calling PurgeComm is something you can feel free to do yourself locally, but it’s not a good change to make to the original source code. And I don’t recommend it as a permanent fix.

PurgeComm Not Working as Expected on Windows Mobile Device

    https://social.msdn.microsoft.com/forums/en-US/d2a1336c-8532-4a1f-b950-a1633caf238e/purgecomm-not-working-as-expected-on-windows-mobile-device
    Dec 11, 2008 · PurgeComm to purge the RX and TX queues. All functions called return successfully. On one particular device (Tornado) the purge of the RX queue …

ComPort Library / Discussion / Help: Purge Comm Error

    https://sourceforge.net/p/comport/discussion/261328/thread/11deca09/
    Apr 30, 2013 · Project Management. Content Management System (CMS) Task Management Project Portfolio Management Time Tracking PDF Education

PKCS#11: Cannot perform signature 6:’CKR_FUNCTION_FAILED .

    https://groups.google.com/d/topic/tunnelblick-discuss/62dr1a6AQRY
    Jul 23, 2011 · 2011-07-22 22:14:08 TLS: Initial packet from xxx:443, sid=57b87a50 0c34fae5

PurgeComm error for LG client — GSM-Forum

    https://forum.gsmhosting.com/vbb/f390/purgecomm-error-lg-client-635103/
    Nov 25, 2008 · Welcome to the GSM-Forum forums. You are currently viewing our boards as a guest which gives you limited access to view most discussions and access our other features.

python — How can I fix «[Error 6] The handle is invalid .

    https://stackoverflow.com/questions/3028786/how-can-i-fix-error-6-the-handle-is-invalid-with-pyserial
    SerialException: ReadFile failed ([Error 6] The handle is invalid.) When using a similar program using a c library, the same port responds correctly.

C++ (Cpp) PurgeComm Examples — HotExamples

    https://cpp.hotexamples.com/examples/-/-/PurgeComm/cpp-purgecomm-function-examples.html
    C++ (Cpp) PurgeComm — 29 examples found. These are the top rated real world C++ (Cpp) examples of PurgeComm extracted from open source projects. You can …

windows — SetupComm, SetCommState, SetCommTimeouts fail .

    https://stackoverflow.com/questions/20551935/setupcomm-setcommstate-setcommtimeouts-fail-with-usb-device
    Turns out that i don’t have to do anything with Comm, because it’s not a COM port.The reason my WriteFile was failing was because i was attempting to write to \.LCLD9 rather than \.LCLD9.. The trailing backslash is critical; even though CreateFile returns success both ways.. void WriteToDisplay(String s) < //Open the display var hLineDisplay = CreateFile(«\.LCLD9», …

failure in TComPort — embarcadero.delphi.tools

    http://codeverge.com/embarcadero.delphi.tools/failure-in-tcomport/1055715
    The next time (SetFreq) gives me «ComPort Error: PurgeComm function failed.» in CreateFile in TCustomComPort.CreateHandle; —— CreateHandle is called only from TCustomComPort.Open. The sources that you have shown sofar calls SetFreq in succession without any calls to ComPort.Open. So can you explain how you ended up in CreateHandle in .

Purgecomm Function Failed Error 6 Fixes & Solutions

We are confident that the above descriptions of Purgecomm Function Failed Error 6 and how to fix it will be useful to you. If you have another solution to Purgecomm Function Failed Error 6 or some notes on the existing ways to solve it, then please drop us an email.

Источник

Arduino.ru

Регистрация новых пользователей и создание новых тем теперь только на новом форуме https://forum.arduino.ru

forum.arduino.ru

Доброе время всем! Я написал программу для ардуино, и программу для компа, которая работает с ардуино по modbus протоколу через виртуальный COM порт. По сути с компа задаются некоторые параметры в ардуино и ардуино уже сама работает с утройствами. Программа только опрашивает некоторые параметры в ардуино, чтобы видеть пользователю процесс. Опрос идет цикличный, бесконечный. Где-то через час-два работы в программе выскакивает ошибка «writefile function failed error 31», после чего опрос и дальнейшая работа с ардуино невозможна, при попытке закрыть и открыть порт повторно — выдает другую ошибку «setcommstate function failed 31» и кроме как перезапуска компа (или отключение и включение ардуино заново) ничего не помогает. (а перезапуск любого устройства болезнено влияет на процесс) При этом сама ардуино продолжает выполнять свой алгоритм без сбоев. Получается, что я теряю только управление к ней. Может кто сталкивался с этим?

ОС: Windows 7 x64

Arduino Mega 2560

Программа на Delphi, с использованием компоненты TComPort

Дополню: ардуино питается от usb порта, скорость соединения 19200.

Я тут тоже написал программу, так она мне дату Пасхи на понедельник насчитала. Не подскажете где у меня ошибка?

Предлагаете чтоб я выложил коды программы и прошивки? ))) Пока хочу теорию получить, гуглю много тем по этой ошибке, но толком все связанно с программаторами, а тут не то совсем. сама ошибка «writefile function failed error 31» выпадывает при каких возможных вариантах?

Предлагаете чтоб я выложил коды программы и прошивки? ))) Пока хочу теорию получить, гуглю много тем по этой ошибке, но толком все связанно с программаторами, а тут не то совсем. сама ошибка «writefile function failed error 31» выпадывает при каких возможных вариантах?

так и ищите в Паскале вашу ошибку, ОС: Windows 7 x64, я так понимаю USB-COM, а драйвера подписаны?

Предлагаете чтоб я выложил коды программы и прошивки? ))) Пока хочу теорию получить, гуглю много тем по этой ошибке, но толком все связанно с программаторами, а тут не то совсем. сама ошибка «writefile function failed error 31» выпадывает при каких возможных вариантах?

так и ищите в Паскале вашу ошибку, ОС: Windows 7 x64, я так понимаю USB-COM, а драйвера подписаны?

USB-COM верно, в диспетчере у виртуального порта эти данные: Изготовитель: Arduino LLC (www.arduino.cc)

ВРоде как подписаны ))

Вот я как думаю — если бы ошибка была постоянной, то проблему думаю легче было бы найти, а в моем случае, она может поработать стабильно 40 минут после запуска, а может и 4 часа, без сбоев. И понять эту проблему не получается. казалось что это переполнение буффера приемо-передачи, но у меня после каждого принятого пакета стоит очистка буфера. В инете читаю — народ пишет что проблема в драйверах, другие пишут что вообще эмуляция порта у ардуино криво реализована, и предлагают на хардварные контроллеры перейти. у меня шок

Еще момент — использую я фирменную arduino для отладки проектов, а для работы заливаю их на китайский аналог. На ардуине я еще не столкнулся с этой проблемой, но может и потому что нет того оборудования, которое навешано на конечный продукт, а может я мало времени тестирую у себя. не поймую пока природу явления

Предлагаете чтоб я выложил коды программы и прошивки? )))

Нет, не предлагаю. Мне это не нужно. Проблема-то у Вас, а не у меня 🙂

Докопал чуток проблему и теперь каждый ее сможет смоделировать. Ардуино шлет в порт Serial постоянно данные, хоть какие. Программа на компе запускатся, подключается к порту и читает эти данные. Все вроде нормально, но если нажать на ардуине кнопку Reset (имитация сбоя) программа перестанет читать данные из порта, хотя ардуино исправно станет их слать снова. Теперь вопрос — как восстановить подключение не выключая ардуино и программу? Пока удается только отключится от порта в программе, нажать повторно кнопку резет на ардуине, и снова включить порт в программе. Но это не есть айс, т.к. рестартовать ардуино нельзя. Нужно подключится к ней и мониторить просиходящее в настоящем времени.

Используя компоненту Tcomport для дельфи — исправил в ней процедуру

procedure TCustomComPort.AbortAllAsync;
begin

try
if not PurgeComm(FHandle, PURGE_TXABORT or PURGE_RXABORT) then
raise EComPort.Create(CError_PurgeFailed, GetLastError);
except
end;

Заключив в обработчик try/except. Это позволяет не вывешить программу наглухо зацикливая на ошибке порта PurgeComm function failed (Error 5). Теперь кнопка закрыть и открыть порт работают. Но похоже что-то в коде ардуины нужно прописать для переинициализации порта.

Попробуйте через модуль работать

Копаю этот модуль и разобрать чуток не могу, вообщем собрал простенькую прогу

И чет не пойму в какой момент начинается чтение данных из порта. На ардуине вижу маргает лед порта когда жму Send, но в ответ ничего. на форму бросил мемо1 как прописано внутри кода.

10 MyPort . OpenPort( ‘COM6’ , 19200 );

при закрытии формы

например я сделал так

— примерно такой 1 пакет

Интересная штуковина получилась, но одно пока странно — если нажать пару раз на кнопку ButtonOpen то потом не получается закрыть ни один )))

тут только руками следить )) можно доделать но пока некогда

Новая вводная )) Подключил к ардуине блок реле. В ардуине только 4 таймера (не делей). Решил запитать блок реле от ардуины (там 5-и вольтовые реле и оптическая развязка на управлении реле стоит). В ардуине использую ту же библиотеку с Модбас протоколом. Все работает здорово, пока не запускаю цикл с переключениями реле. Т.е. перед запуском я задаю разные интервалы времени в ардуино с компа через USB используя протокол Модбас, все пишет, все читает, все здорово. Как только нажимаю Старт алгоритма, т.е непосредственное исполнение таймеров и переключение реле — порт тут же отваливается при следуюем обращении во время работы алгоритма с ошибкой writefile function failed error 31. А алгоритм продолжает выполнятся. Вот тут я стал размышлять, алгоритм простой, всего три таймера, ничего она не отправляет в порт, только принимает, но управляют они 4мя релюшками. И я решил снять нагрузку с ардуины и поставить отдельный блок питания на 5В. И все заработало! Теперь собственно вопрос — что не хватает ардуине? Как можно исправить это?

Новая вводная )) Подключил к ардуине блок реле. В ардуине только 4 таймера (не делей). Решил запитать блок реле от ардуины (там 5-и вольтовые реле и оптическая развязка на управлении реле стоит). В ардуине использую ту же библиотеку с Модбас протоколом. Все работает здорово, пока не запускаю цикл с переключениями реле. Т.е. перед запуском я задаю разные интервалы времени в ардуино с компа через USB используя протокол Модбас, все пишет, все читает, все здорово. Как только нажимаю Старт алгоритма, т.е непосредственное исполнение таймеров и переключение реле — порт тут же отваливается при следуюем обращении во время работы алгоритма с ошибкой writefile function failed error 31. А алгоритм продолжает выполнятся. Вот тут я стал размышлять, алгоритм простой, всего три таймера, ничего она не отправляет в порт, только принимает, но управляют они 4мя релюшками. И я решил снять нагрузку с ардуины и поставить отдельный блок питания на 5В. И все заработало! Теперь собственно вопрос — что не хватает ардуине? Как можно исправить это?

какие-то у вас сержантские замашки )))

Вот вроде бы нашел решение, но в голове не укладывается, ведь схема у меня работает на ULN2003 и ULN2002 это полевые транзисторные сборки, как я могу просаживать питанием ардуино — не укладывается в голове. Вот та схема подключения. J1 это порт Arduino Mega, порт J7 выходы на нагрузку (Между контактом J7 и +24 стоит нагрузка). J3 это входы от датчиков (24Вольта). На J4 подаю +5 от самой ардуины. Может где резисторов не хватает??

Источник

Old
11-22-2008, 10:50

 
#1 (permalink)

DexterGSM

Freak Poster

 

DexterGSM's Avatar

 

Join Date: Aug 2000

Location: gsm

Posts: 277

Member: 1919

Status: Offline

Thanks Meter: 8

PurgeComm error for LG client


Hello,
I have problem with connection with LG phones,

I have installed driver v4.7 and now always have when push ‘Read Info’
error «PurgeComm function failed (win error code :6)»

B.R.
Dexter

 

Old
11-22-2008, 11:41

 
#2 (permalink)

quattro

Freak Poster

 

Join Date: Jan 2004

Age: 47

Posts: 144

Member: 51005

Status: Offline

Thanks Meter: 6

i have the same problem:
Looking for phone…
Error: Internal! > COM port routine > 3

 

Old
11-22-2008, 11:44

 
#3 (permalink)

KulanKendi

No Life Poster

 

Join Date: Nov 2006

Posts: 2,463

Member: 384655

Status: Offline

Thanks Meter: 516

Fixed try now

b.r.

Quote:

Originally Posted by quattro View Post

i have the same problem:
Looking for phone…
Error: Internal! > COM port routine > 3

 

Old
11-22-2008, 13:14

 
#4 (permalink)

quattro

Freak Poster

 

Join Date: Jan 2004

Age: 47

Posts: 144

Member: 51005

Status: Offline

Thanks Meter: 6

not work
in vista «looking for phone» and block
in xp «phone not found»

 

Old
11-22-2008, 13:22

 
#5 (permalink)

quattro

Freak Poster

 

Join Date: Jan 2004

Age: 47

Posts: 144

Member: 51005

Status: Offline

Thanks Meter: 6

or in vista «PurgeComm function failed (win error code:5)

 

Old
11-22-2008, 14:40

 
#6 (permalink)

KulanKendi

No Life Poster

 

Join Date: Nov 2006

Posts: 2,463

Member: 384655

Status: Offline

Thanks Meter: 516

what driver version and what client version?

b.r.

Quote:

Originally Posted by quattro View Post

or in vista «PurgeComm function failed (win error code:5)

 

Old
11-22-2008, 16:37

 
#7 (permalink)

quattro

Freak Poster

 

Join Date: Jan 2004

Age: 47

Posts: 144

Member: 51005

Status: Offline

Thanks Meter: 6

client 1.05
driver all: 4.6, 4.7

 

Old
11-22-2008, 17:12

 
#8 (permalink)

KulanKendi

No Life Poster

 

Join Date: Nov 2006

Posts: 2,463

Member: 384655

Status: Offline

Thanks Meter: 516

oka try now 1.06

b.r.

Quote:

Originally Posted by quattro View Post

client 1.05
driver all: 4.6, 4.7

 

Old
11-22-2008, 17:13

 
#9 (permalink)

wuwei

Freak Poster

 

Join Date: May 2006

Location: Paris

Age: 40

Posts: 492

Member: 277109

Status: Offline

Sonork: 100.1590647

Thanks Meter: 83

Quote:

Originally Posted by quattro View Post

client 1.05
driver all: 4.6, 4.7

client is already updated to 1.06, u can try it! it works for me

BR

 

Old
11-22-2008, 17:30

 
#10 (permalink)

quattro

Freak Poster

 

Join Date: Jan 2004

Age: 47

Posts: 144

Member: 51005

Status: Offline

Thanks Meter: 6

works for me too but after i change the serial port from 100 lower than 10.
anyway, very fast answers. thx

 

Old
11-23-2008, 00:58

 
#11 (permalink)

KulanKendi

No Life Poster

 

Join Date: Nov 2006

Posts: 2,463

Member: 384655

Status: Offline

Thanks Meter: 516

will check this problem too soon.

b.r.

Quote:

Originally Posted by quattro View Post

works for me too but after i change the serial port from 100 lower than 10.
anyway, very fast answers. thx

 

Old
11-24-2008, 13:51

 
#12 (permalink)

GsmHgvnl

No Life Poster

 

GsmHgvnl's Avatar

 

Join Date: Sep 2004

Location: Hoogeveen

Age: 35

Posts: 574

Member: 82928

Status: Offline

Thanks Meter: 17

I have same problem with V1.06

Error: Internal! > COM port routine > 3

 

Old
11-24-2008, 14:10

 
#13 (permalink)

KulanKendi

No Life Poster

 

Join Date: Nov 2006

Posts: 2,463

Member: 384655

Status: Offline

Thanks Meter: 516

try drivers 4.7 and 4.9 from support

b.r.

Quote:

Originally Posted by GsmHgvnl View Post

I have same problem with V1.06

Error: Internal! > COM port routine > 3

 

Old
11-24-2008, 15:04

 
#14 (permalink)

DexterGSM

Freak Poster

 

DexterGSM's Avatar

 

Join Date: Aug 2000

Location: gsm

Posts: 277

Member: 1919

Status: Offline

Thanks Meter: 8

Nothing new with U960 ? I have same error with v1.06

Looking for phone…
Phone detected.
Phone Model: U960
Phone IMEI: 355773-01-115380-0
NAND Info: toshiba_tya000bc00bogg | 0098:00CA | 40:800 |
Revision: U960-MSM6280-V10a-MAY-14-2007-H3G-IT
Brand info: U960FL-V10a-01-222-99-00-00-00-MAY-14-2007+0
Compiled date: May 14 200714:23:56MAY 14 200717:00:00U960
PhoneLock Code: 0000
Connecting to server…
Phone and Version are supported.
Reading simlock data…
Connecting to server…
>> BrokenBad data received,block no: 1:7
Communication Closed.

 

Old
11-25-2008, 05:54

 
#15 (permalink)

KulanKendi

No Life Poster

 

Join Date: Nov 2006

Posts: 2,463

Member: 384655

Status: Offline

Thanks Meter: 516

try latest update version 1.07

b.r.

Quote:

Originally Posted by DexterGSM View Post

Nothing new with U960 ? I have same error with v1.06

Looking for phone…
Phone detected.
Phone Model: U960
Phone IMEI: 355773-01-115380-0
NAND Info: toshiba_tya000bc00bogg | 0098:00CA | 40:800 |
Revision: U960-MSM6280-V10a-MAY-14-2007-H3G-IT
Brand info: U960FL-V10a-01-222-99-00-00-00-MAY-14-2007+0
Compiled date: May 14 200714:23:56MAY 14 200717:00:00U960
PhoneLock Code: 0000
Connecting to server…
Phone and Version are supported.
Reading simlock data…
Connecting to server…
>> BrokenBad data received,block no: 1:7
Communication Closed.

 

I'm using TComPort to talk to a device from my D2010 app. The first time this 
function is called, it works. The next time (SetFreq) gives me "ComPort Error: 
PurgeComm function failed." in CreateFile in TCustomComPort.CreateHandle;

The only way I've found to clear it is to re-boot the box.

The main app calls a dll which does the comm port processing.

Any insight greatly appreciated!
Mike

{code}
//MAIN

type
   TSetMode = function (mode:pAnsiChar):LongBool; stdcall;
   TSetFreq = function (F:pAnsiChar; AB: integer):LongBool; stdcall;

procedure TfrmLog.SetFreqMode(freq,mode: boolean; AB: integer; freqin: pAnsiChar);
var
   SetFreq: TSetFreq;
   SetMode: TSetMode;
   SFreq: single;
   Smode: String;
begin
   if (freq) and (TryStrToFloat(edtLogFreq.Text, SFreq)) then
   begin
     dllFunc := 'SetFreq';
     if Rhandle = 0 then
       RHandle := SafeLoadLibrary(pChar(Radiodll));
     if RHandle <> 0 then
     begin
       SetFreq := GetProcAddress(RHandle, dllFunc );
       if @SetFreq  <> nil then
         SetFreq(freqin, AB);
      sleep(200);
     end;
   end;
   if mode then
   begin
     Smode := cboLogMode.Text;
     if cboLogMode.Text = 'PSK31' then
       SMode := 'PSK'
     else
     if cboLogMode.Text = 'SSB' then
     begin
       if TryStrToFloat(edtLogFreq.Text, SFreq) then
       begin
         if (SFreq < 9) then
           Smode := 'LSB'
         else
           Smode := 'USB';
       end;
     end;
     dllFunc := 'SetMode';
     SetMode := GetProcAddress(RHandle, dllFunc );
     if @SetMode  <> nil then
       SetMode(pAnsiChar(Smode));
   end;
end;

//DLL:

function SetFreq(F: PAnsiChar; AB: integer): LongBool; stdcall;
var
   rstr: string;
   Freq: Ansistring;
   i: integer;
begin
   result := true;
   if (F = nil) and (AB = 0) then
   begin
     result := false;
     exit;
   end;
   Freq := F;
   i := pos('.', string(Freq));
   if i > 0 then
     rstr := copy(string(Freq), 1, i - 1) + copy(string(Freq), i + 1, 
length(string(Freq)))
   else
     exit;
   if StrToFloat(string(Freq)) < 10 then
     rstr := '0000' + rstr
   else
     rstr := '000' + rstr;
   while length(rstr) < 11 do
     rstr := rstr + '0';
   if AB = 0 then // not split
   begin
     rstr := 'FA' + rstr + ';';
     ComPort.WriteStr(AnsiString(rstr));
     ComPort.WriteStr('LK0;FR0;FT0;RT0;XT0;');
   end
   else
   begin
     ComPort.WriteStr('LK1;SWT13;SWT13;FR0;FT1;RT0;XT0;');
     rstr := 'FB' + rstr + ';';
     ComPort.WriteStr(AnsiString(rstr));
   end;
   if dll.Log then
     dll.WriteToLog(string(Freq) + ' - ' + rstr);
end;

function SetMode(M: PAnsiChar): LongBool; stdcall;
var
   MStr,SubStr,PStr: Ansistring;
begin
   result := true;
   if (M = nil) then
   begin
     result := false;
     exit;
   end;
   if M = 'CW' then
     MStr := '3;'
   else if (M = 'LSB') then
     MStr := '1;'
   else if (M = 'USB') then
     MStr := '2;'
   else if M = 'AM' then
     MStr := '5;'
   else if M = 'FM' then
     MStr := '4;'
   else if (M = 'TTY') or (M = 'RTTY') then
   begin
     MStr := '6;';
     SubStr := 'DT1;';
     PStr := 'PC1001;';
   end
   else if (M = 'PSK') then
   begin
     MStr := '6;';
     SubStr := 'DT0;';
     pStr := 'PC0251;';
   end
   else
     MStr := '';
   if MStr <> '' then
     MStr := 'MD' + MStr;
   ComPort.WriteStr(MStr);
   ComPort.WriteStr(SubStr);
   ComPort.WriteStr(PStr);
end;

Mike

9/9/2010 7:47:03 PM

> {quote:title=Mike Reublin wrote:}{quote}
> The main app calls a dll which does the comm port processing.

The way you use this dll is not ideal.

You're loading the dll each time you'll use it...

You'd better load the dll once at the startup, then import all exported functions.

You're loading the dll, assuming the ComPort object remain the same between calls... You could have problem in there.

So put your SetFreq/SetMode var global to your main program.

Your problem sounds like a ComPort instance error, and a  previous ComPort not freed as expected.

IMHO It's worth making some code refactoring here, and use the dll in a "clean" way.

Arnaud

9/10/2010 9:42:35 AM

On 9/10/2010 5:42 AM, Arnaud BOUCHEZ wrote:
>> {quote:title=Mike Reublin wrote:}{quote}
>> The main app calls a dll which does the comm port processing.
>
> The way you use this dll is not ideal.
>
> You're loading the dll each time you'll use it...
>
> You'd better load the dll once at the startup, then import all exported functions.
>
> You're loading the dll, assuming the ComPort object remain the same between calls... You could have problem in there.
>
> So put your SetFreq/SetMode var global to your main program.
>
> Your problem sounds like a ComPort instance error, and a  previous ComPort not freed as expected.
>
> IMHO It's worth making some code refactoring here, and use the dll in a "clean" way.

Thanks Arnaud.

I'm not loading it each time. RHandle is global. After loading the first time, 
Rhandle won't be zero. Did you mean something else?

{code}
if Rhandle = 0 then
       RHandle := SafeLoadLibrary(pChar(Radiodll));
{code}

I can't use the form

function SetFreq(F:pAnsiChar; AB: integer): LongBool; stdcall; external 'SomeDLL.dll'

to import the the functions because any one of 15 different dll's may be used for 
this same purpose, depending on what hardware the user has.

Why/how would the comm object change between calls?

AFAICS, the comport is only instantiated once. Do you see it differently?

By refactoring, do you mean re-writing? Probably so. Have you an example of a clean way?

Mike

9/10/2010 3:15:51 PM

> {quote:title=Mike Reublin wrote:}{quote}
> I'm not loading it each time. RHandle is global. After loading the first time, 
> Rhandle won't be zero. Did you mean something else?

OK, it was very difficult to get it with your code unformated in the post (a missing {code} at the end of the code).

> Why/how would the comm object change between calls?

it depends on your code. did you try with Delphi 2007? Perhaps there is a problem in your TComPort library adaptation to Delphi 2010.

> AFAICS, the comport is only instantiated once. Do you see it differently?

It's very difficult to guess what's wrong without having the whole code.
We don't have the WriteStr() part on the post.
Can't guess how the ComPort is instantiated and used.

Perhaps you're changing your dll name between instances... then you're calling the previous dll because rHandle was previously set..

> By refactoring, do you mean re-writing? Probably so. Have you an example of a clean way?

At least, use globals for your SetFreq/SetMode prototypes, don't use GetProcAddress() before every call.
Use classes and properties, and inheritance to handle multiple dll names and exported functions.
These classes may contain the whole RHandle/SetFreq/SetMode, not as global variables or form property, but as clean Delphi types.
And you could be able to use RadioOne.SetFreq() or such.

Arnaud

9/10/2010 4:16:55 PM

On 9/10/2010 12:16 PM, Arnaud BOUCHEZ wrote:
>> {quote:title=Mike Reublin wrote:}{quote}
>> I'm not loading it each time. RHandle is global. After loading the first time,
>> Rhandle won't be zero. Did you mean something else?
>
> OK, it was very difficult to get it with your code unformated in the post (a missing {code} at the end of the code).
Oops, sorry. I'll post the dll on attachments as "DLLSource".
>
>> Why/how would the comm object change between calls?
>
> it depends on your code. did you try with Delphi 2007? Perhaps there is a problem in your TComPort library adaptation to Delphi 2010.

I don't have D2007. But it reacts the sane in D7, with the pre-D2010 changes to the 
component.
>
>> AFAICS, the comport is only instantiated once. Do you see it differently?
>
> It's very difficult to guess what's wrong without having the whole code.
> We don't have the WriteStr() part on the post.

It's in the source of Cport.pas. That's not where the error surfaces.
{code}
function TCustomComPort.WriteStr(const Str: AnsiString): Integer;
begin
   if FOverlapped then
       result := _WriteStrWrapper(Str)
   else begin
     result := 0;
     if _SyncWrite(PAnsiChar(Str),Length(Str)) then
         result := Length(Str);
   end;
end;
{code}

> Can't guess how the ComPort is instantiated and used.

See attachments group for "DLLSource"
>
> Perhaps you're changing your dll name between instances... then you're calling the previous dll because rHandle was previously set..

No.
>
>> By refactoring, do you mean re-writing? Probably so. Have you an example of a clean way?
>
> At least, use globals for your SetFreq/SetMode prototypes, don't use GetProcAddress() before every call.
> Use classes and properties, and inheritance to handle multiple dll names and exported functions.
> These classes may contain the whole RHandle/SetFreq/SetMode, not as global variables or form property, but as clean Delphi types.
> And you could be able to use RadioOne.SetFreq() or such.

Sorry, you lost me here. I need code snippets. While I don't doubt your suggestions 
are better structured ways, I have a hard time seeing it as the error source. But 
then I'm still learning.

Mike

9/10/2010 5:41:46 PM

"Mike Reublin" wrote:
> I'm using TComPort to talk to a device from my D2010 app. The first 
> time this
> function is called, it works. The next time (SetFreq) gives me 
> "ComPort Error:
> PurgeComm function failed." in CreateFile in 
> TCustomComPort.CreateHandle;

Mike,
Since you have the source (I guess you do) you could lookup in which 
places this error is raised and why. Put break points before and 
investigate the factors that may trigger the error.

Cheers
Tom

Tom

9/10/2010 7:07:25 PM

On 9/10/2010 3:07 PM, Tom Brunberg wrote:
> "Mike Reublin" wrote:
>> I'm using TComPort to talk to a device from my D2010 app. The first
>> time this
>> function is called, it works. The next time (SetFreq) gives me
>> "ComPort Error:
>> PurgeComm function failed." in CreateFile in
>> TCustomComPort.CreateHandle;
>
> Mike,
> Since you have the source (I guess you do) you could lookup in which
> places this error is raised and why. Put break points before and
> investigate the factors that may trigger the error.
>
> Cheers
> Tom


Hi Tom.

Yes, I do and I have traced into it. CreateFile is a functon in the Windows unit. 
Doesn't tell me anything. Googling for PurgeComm didn't give me anything eihter. Do 
you see anything?

{code}
procedure TCustomComPort.CreateHandle;
var
  dev:String;
  flags:Cardinal;
begin
   dev :='\.' + FPort;
   if FOverlapped then  { This is a big change from classic TComPort }
       flags := FILE_FLAG_OVERLAPPED
   else
       flags := 0;
   FHandle := CreateFile(
     PChar(dev),
     GENERIC_READ or GENERIC_WRITE,
     0,
     nil,
     OPEN_EXISTING,
     flags,
     0);
   if FHandle = INVALID_HANDLE_VALUE then begin
     {$ifdef CPORT_CALLTRACE}
     OutputDebugString( PChar('CreateHandle: CreateFile '+dev));
     {$endif}
     raise EComPort.Create(CError_OpenFailed, GetLastError,FPort);
   end;
end;
{code}

Mike

9/10/2010 9:12:51 PM

"Mike Reublin" <[email protected]> wrote
> I'm using TComPort to talk to a device from my D2010 app. The first time this
> function is called, it works. The next time (SetFreq) gives me "ComPort Error:
> PurgeComm function failed." in CreateFile in TCustomComPort.CreateHandle;
> ... Any insight greatly appreciated!

Mike,

Can you make a small test program that demonstrates the problem?

Also, I note that there are some interesting related results from the Google:
http://www.google.com/#sclient=psy&hl=en&q=ComPort+Error+%22PurgeComm+function+failed%22

Rgds, JohnH

John

9/10/2010 10:47:44 PM

"Mike Reublin" wrote:
> On 9/10/2010 3:07 PM, Tom Brunberg wrote:
>> "Mike Reublin" wrote:
>>> I'm using TComPort to talk to a device from my D2010 app. The 
>>> first
>>> time this
>>> function is called, it works. The next time (SetFreq) gives me
>>> "ComPort Error:
>>> PurgeComm function failed." in CreateFile in
>>> TCustomComPort.CreateHandle;
>>
>> Mike,
>> Since you have the source (I guess you do) you could lookup in 
>> which
>> places this error is raised and why. Put break points before and
>> investigate the factors that may trigger the error.

Mike,
Ok, I downloaded TComPort to get a wider picture and searched for 
where PurgeComm errors are raised:
procedure TComPort.ClearBuffer(Input, Output: Boolean);
....
  if not PurgeComm(FHandle, Flag) then
    raise EComPort.Create(CError_PurgeFailed, GetLastError);

and

procedure TComPort.AbortAllAsync;
....
  if not PurgeComm(FHandle, PURGE_TXABORT or PURGE_RXABORT) then
    raise EComPort.Create(CError_PurgeFailed, GetLastError);

In addition TComPort calls PurgeComm in one place without raising an 
error on failure:
procedure TComThread.Execute;
....
  PurgeComm(FComPort.Handle, PURGE_TXCLEAR or PURGE_RXCLEAR);

> Yes, I do and I have traced into it. CreateFile is a functon in the 
> Windows unit.
> Doesn't tell me anything. Googling for PurgeComm didn't give me 
> anything eihter.

Really?
PurgeComm as well as CreateFile as Windows API functions are to be 
found on msdn
as well as in the Delphi help (just make sure you don't filter out the 
Windows SDK help.

> Do
> you see anything?
>

Well, I see that PurgeComm is not called in 
TCustomComPort.CreateHandle and you claim it is raised in the 
CreateFile call. Goes beyond my comprehension.

But then I'm alo puzzled because you said that the error occurs the 
second time you call SetFreq. Why are you recreating the comport? Did 
you for sure close it in between?

Cheers
Tom

Tom

9/10/2010 11:08:26 PM

Arnaud, Tom, John, thank you all for your responses. I found the solution, and it was 
some bad Unicode-ing on my part. I had changed the parameter passed into the dll from 
pChar to pAnsiChar.

I don't know why that made what happened happen. Explanation, anyone?

Regards, Mike

Mike

9/11/2010 1:51:29 AM

On 9/10/2010 7:08 PM, Tom Brunberg wrote:
> "Mike Reublin" wrote:
>> On 9/10/2010 3:07 PM, Tom Brunberg wrote:
>>> "Mike Reublin" wrote:
>>>> I'm using TComPort to talk to a device from my D2010 app. The
>>>> first
>>>> time this
>>>> function is called, it works. The next time (SetFreq) gives me
>>>> "ComPort Error:
>>>> PurgeComm function failed." in CreateFile in
>>>> TCustomComPort.CreateHandle;
>>>
>>> Mike,
>>> Since you have the source (I guess you do) you could lookup in
>>> which
>>> places this error is raised and why. Put break points before and
>>> investigate the factors that may trigger the error.
>
> Mike,
> Ok, I downloaded TComPort to get a wider picture and searched for
> where PurgeComm errors are raised:
> procedure TComPort.ClearBuffer(Input, Output: Boolean);
> ...
>    if not PurgeComm(FHandle, Flag) then
>      raise EComPort.Create(CError_PurgeFailed, GetLastError);
>
> and
>
> procedure TComPort.AbortAllAsync;
> ...
>    if not PurgeComm(FHandle, PURGE_TXABORT or PURGE_RXABORT) then
>      raise EComPort.Create(CError_PurgeFailed, GetLastError);
>
> In addition TComPort calls PurgeComm in one place without raising an
> error on failure:
> procedure TComThread.Execute;
> ...
>    PurgeComm(FComPort.Handle, PURGE_TXCLEAR or PURGE_RXCLEAR);
>
>> Yes, I do and I have traced into it. CreateFile is a functon in the
>> Windows unit.
>> Doesn't tell me anything. Googling for PurgeComm didn't give me
>> anything eihter.
>
> Really?
> PurgeComm as well as CreateFile as Windows API functions are to be
> found on msdn
> as well as in the Delphi help (just make sure you don't filter out the
> Windows SDK help.

I didn't say I didn't read about them, I just didn't understand what I read, or 
related to my problem.
>
>> Do
>> you see anything?
>>
>
> Well, I see that PurgeComm is not called in
> TCustomComPort.CreateHandle and you claim it is raised in the
> CreateFile call. Goes beyond my comprehension.
>
Mine too..... <vbg>

> But then I'm alo puzzled because you said that the error occurs the
> second time you call SetFreq. Why are you recreating the comport? Did
> you for sure close it in between?
>

I'm not recreating the port. Anyhow, problem solved, if not understood. See my post 
below. And thanks.

Regards, Mike

Mike

9/11/2010 12:57:43 PM

OK, so I'm suffering from premature congratulation. There is still a problem. This 
all worked well in D7, and survived the port to D2010, then for no reason I can 
discern, started to fail.

There are two devices attached to the same serial port by a "Y" cable. The first is a 
radio, the second an antenna controller.

The antenna controller is a passive (as far as the serial port goes) device, it 
doesn't reply back, it just follows whatever the radio does. If it is off, the port 
responds properly, and is able to set the radio. The radio gets three sets of commands.

If the antenna controller is on, the second command fails, so it does have an effect. 
If I switch the order in which the first two commands are sent, the third fails.

My main app calls a dll which handles the serial calls and responses.

{code}
function SetFreq(F: PChar; AB: integer): LongBool; stdcall;
var
   rstr, Freq, macrostr: string;
   i: integer;
begin
   Freq := F;
   i := pos('.', string(Freq));
   if i > 0 then
     rstr := copy(string(Freq), 1, i - 1) + copy(string(Freq), i + 1, 
length(string(Freq)))
   else
     exit;
   if StrToFloat(string(Freq)) < 10 then
     rstr := '0000' + rstr
   else
     rstr := '000' + rstr;
   while length(rstr) < 11 do
     rstr := rstr + '0';
   if AB = 0 then // not split
   begin
     rstr := 'FA' + rstr + ';';
     ComPort.WriteStr(AnsiString(rstr));  //< 1st sent "FA0001040000;"
     macrostr := 'LK0;FR0;FT0;RT0;XT0;';
     ComPort.WriteStr(AnsiString(macrostr));  //< 2nd sent "'LK0;FR0;FT0;RT0;XT0;"
   end;
end;

function SetMode(M: PChar): LongBool; stdcall;
var
   MStr,SubStr,PStr: Ansistring;
begin
   result := true;
   SubStr := '';
   PStr := '';
   if M = 'CW' then
     MStr := '3;'
   if MStr <> '' then
     MStr := 'MD' + MStr;
   ComPort.WriteStr(AnsiString(MStr));  //< 3rd sent "MD3;"
end;
{code}

In CPort.pas we eventually get to the WriteAsync function. WriteFile always returns 
false, but the radio does get set. One of the writes (2nd or 3rd) fails, Pending is 
set to false. The error message is "PurgeComm function failed on COM5". It seems like 
the solution would be to call WaitForSingleObject(FHandle, 5000);, but that didn't 
help. This error seems to be associated with error code 997. The actual error code is 
5, ERROR_ACCESS_DENIED, so that confuses me too.

This is driving me crazy...... and it's a very short ride <vbg>.

{code}
function TCustomComPort.WriteAsync(const Buffer:PCPortAnsiChar; Count: Integer; var 
AsyncPtr: PCPortAsync): Integer;
var
   Success : Boolean;
   Pending : Boolean;
   BytesTrans: DWORD;
begin
   if AsyncPtr = nil then
     raise EComPort.CreateNoWinCode(CError_InvalidAsync);
   CPortPrepareAsync(okWrite, Buffer, Count, AsyncPtr);

   Success := WriteFile(FHandle, Buffer^, Count, BytesTrans, @AsyncPtr^.Overlapped);
   Pending := (GetLastError = ERROR_IO_PENDING);
   if not (Success or Pending) then
     raise EComPort.Create(CError_WriteFailed, GetLastError,FPort);
   SendSignalToLink(leTx, True);
   Result := BytesTrans;
end;
{code}

Mike

9/17/2010 10:55:23 PM

"Mike Reublin" wrote:
> OK, so I'm suffering from premature congratulation. There is still a 
> problem. This
> all worked well in D7, and survived the port to D2010, then for no 
> reason I can
> discern, started to fail.
>
> There are two devices attached to the same serial port by a "Y" 
> cable. The first is a
> radio, the second an antenna controller.
>
> The antenna controller is a passive (as far as the serial port goes) 
> device, it
> doesn't reply back, it just follows whatever the radio does. If it 
> is off, the port
> responds properly, and is able to set the radio. The radio gets 
> three sets of commands.
>
> If the antenna controller is on, the second command fails, so it 
> does have an effect.
> If I switch the order in which the first two commands are sent, the 
> third fails.

Mike,
The obvious questions are:
Are you 200% sure, that the antenna controller really is passive, and 
doesn't try to respond to message 1 (The 'FA000..')?
How do you know?
Are we talking about RS232 or RS485?
How is the 'Y' connection done?

> In CPort.pas we eventually get to the WriteAsync function. WriteFile 
> always returns
> false, but the radio does get set. One of the writes (2nd or 3rd) 
> fails, Pending is
> set to false. The error message is "PurgeComm function failed on 
> COM5". It seems like
> the solution would be to call WaitForSingleObject(FHandle, 5000);, 
> but that didn't
> help. This error seems to be associated with error code 997. The 
> actual error code is
> 5, ERROR_ACCESS_DENIED, so that confuses me too.

This looks suspicious in CPort.pas (version 4Beta_D2010)
{code}
// create exception with windows error code
constructor EComPort.Create(ACode: Integer; AWinCode: Integer; 
port:String);
begin
  FWinCode := AWinCode;
  FCode := ACode;
//  inherited CreateFmt(ComErrorMessages[ACode] + {_(}' (win error 
code: %d)'{)}, [AWinCode]);
  inherited Create('COM Port Error: '+ComErrorMessage(AWinCode)+' on 
'+port);
end;
{code}
ComErrorMessage returns a message that has nothing to do with the 
error codes that GetLastError returns, therefor passing AWinCode to 
the function is wrong.
If the error message shows 'PurgeComm function failed' it really means 
ERROR_ACCESS_DENIED as you concluded yourself.
I suggest you switch the line that is outcommented to get correct 
error messages.

Cheers
Tom

PS. I'll be out for the rest of the weekend.

Tom

9/18/2010 10:02:28 AM

"Mike Reublin" <[email protected]> wrote
> The antenna controller is a passive ... device, 

Mike, 

Is it wired properly?  
It should not have any connection to PC inputs CD,  RxD, DSR, or CTS.

> If it is off, the port responds properly, and is able to set the radio. 
> ... If the antenna controller is on, the second command fails

Rgds, JohnH

John

9/18/2010 1:18:50 PM

On 9/18/2010 6:02 AM, Tom Brunberg wrote:
> "Mike Reublin" wrote:
>> OK, so I'm suffering from premature congratulation. There is still a
>> problem. This
>> all worked well in D7, and survived the port to D2010, then for no
>> reason I can
>> discern, started to fail.
>>
>> There are two devices attached to the same serial port by a "Y"
>> cable. The first is a
>> radio, the second an antenna controller.
>>
>> The antenna controller is a passive (as far as the serial port goes)
>> device, it
>> doesn't reply back, it just follows whatever the radio does. If it
>> is off, the port
>> responds properly, and is able to set the radio. The radio gets
>> three sets of commands.
>>
>> If the antenna controller is on, the second command fails, so it
>> does have an effect.
>> If I switch the order in which the first two commands are sent, the
>> third fails.
>
Thanks, Tom.
> Mike,
> The obvious questions are:
> Are you 200% sure, that the antenna controller really is passive, and
> doesn't try to respond to message 1 (The 'FA000..')?

Pretty certain, the only pins (DB9 connector) connected are 2 (RX data) and 5(Signal 
ground).

> How do you know?

I think by the pins connected, and the manual says only that "controller will listen 
to your radio".

> Are we talking about RS232 or RS485?

RS232.

> How is the 'Y' connection done?

A DB9 connects to the serial port on the 'puter. Two cables exit it, one going to the 
radio, one to the antenna controller.

Between the computer and radio the pins connected (straight through) are:
2. RXD
3. TXD
4. DTR
5. Signal gnd.
6. DSR
7. RTS
8. CTS

Between the computer and controller (straight through):
2. RXD
5. Signal gnd.

>
>> In CPort.pas we eventually get to the WriteAsync function. WriteFile
>> always returns
>> false, but the radio does get set. One of the writes (2nd or 3rd)
>> fails, Pending is
>> set to false. The error message is "PurgeComm function failed on
>> COM5". It seems like
>> the solution would be to call WaitForSingleObject(FHandle, 5000);,
>> but that didn't
>> help. This error seems to be associated with error code 997. The
>> actual error code is
>> 5, ERROR_ACCESS_DENIED, so that confuses me too.
>
> This looks suspicious in CPort.pas (version 4Beta_D2010)
> {code}
> // create exception with windows error code
> constructor EComPort.Create(ACode: Integer; AWinCode: Integer;
> port:String);
> begin
>    FWinCode := AWinCode;
>    FCode := ACode;
> //  inherited CreateFmt(ComErrorMessages[ACode] + {_(}' (win error
> code: %d)'{)}, [AWinCode]);
>    inherited Create('COM Port Error: '+ComErrorMessage(AWinCode)+' on
> '+port);
> end;
> {code}
> ComErrorMessage returns a message that has nothing to do with the
> error codes that GetLastError returns, therefor passing AWinCode to
> the function is wrong.
> If the error message shows 'PurgeComm function failed' it really means
> ERROR_ACCESS_DENIED as you concluded yourself.
> I suggest you switch the line that is outcommented to get correct
> error messages.
>

Doing it this way returns the same error message. The error codes are defined in 
ComErrorMessage. I think they aren't the windows error codes, but maybe should be.

{code}
//  inherited CreateFmt(ComErrorMessages[ACode] + {_(}' (win error code: %d)'{)}, 
[AWinCode]);
   inherited Create('COM Port Error: '+ComErrorMessage(AWinCode)+' on '+port);
{code}
> Cheers
> Tom
>
> PS. I'll be out for the rest of the weekend.

Enjoy! I'm sure I'll still be here... :-{

Mike

9/18/2010 11:16:59 PM

On 9/18/2010 9:18 AM, John Herbster wrote:
> "Mike Reublin"<[email protected]>  wrote
>> The antenna controller is a passive ... device,
>
> Mike,
>
> Is it wired properly?
> It should not have any connection to PC inputs CD,  RxD, DSR, or CTS.
>
>> If it is off, the port responds properly, and is able to set the radio.
>> ... If the antenna controller is on, the second command fails
>
> Rgds, JohnH

Hi John.

Yep, the problem isn't there. See my response to Tom for the wiring.
It worked fine for over a year, and it works fine using other (commercial) programs. 
I'm fairly certain it's a programming glitch, but that doesn't make total sense either.

Posted from my front porch in beautiful downtown WitsEnd........

Mike

9/18/2010 11:21:40 PM

"Mike Reublin" wrote:
> On 9/18/2010 6:02 AM, Tom Brunberg wrote:
>> "Mike Reublin" wrote:
>>> There are two devices attached to the same serial port by a "Y"
>>> cable. The first is a
>>> radio, the second an antenna controller.
>>>
>>> The antenna controller is a passive (as far as the serial port 
>>> goes)
>>> device, it
>>> doesn't reply back, it just follows whatever the radio does.

Mike,

Am I correct in my understanding that the radio sends "commands" to 
the antenna controller, not the PC?
Well, actually further down you quote the manual "controller will 
listen to your radio", so I guess the answer is yes.

>>> If it
>>> is off, the port
>>> responds properly, and is able to set the radio. The radio gets
>>> three sets of commands.
>>>
>>> If the antenna controller is on, the second command fails, so it
>>> does have an effect.
>>> If I switch the order in which the first two commands are sent, 
>>> the
>>> third fails.

So, will the FA000... message trigger some activity on the serial line 
outward from the radio?

>> How is the 'Y' connection done?
>
> A DB9 connects to the serial port on the 'puter. Two cables exit it, 
> one going to the
> radio, one to the antenna controller.
>
> Between the computer and radio the pins connected (straight through) 
> are:
> 2. RXD
> 3. TXD
> 4. DTR
> 5. Signal gnd.
> 6. DSR
> 7. RTS
> 8. CTS
>
> Between the computer and controller (straight through):
> 2. RXD
> 5. Signal gnd.

Ok, this would work if the radio is internally connected as a DCE 
(Data Communication Equipment) and the controller is internally 
connected as a DTE (Data Terminal Equipment). You wrote elsewhere that 
this has been working with your D7 version so I guess we can conclude 
the connection to be OK.
If you have an interest in DCE and DTE connections take a look at
http://www.camiresearch.com/Data_Com_Basics/RS232_standard.html

>>> In CPort.pas we eventually get to the WriteAsync function. 
>>> WriteFile
>>> always returns
>>> false, but the radio does get set. One of the writes (2nd or 3rd)
>>> fails, Pending is
>>> set to false. The error message is "PurgeComm function failed on
>>> COM5". It seems like
>>> the solution would be to call WaitForSingleObject(FHandle, 5000);,
>>> but that didn't
>>> help. This error seems to be associated with error code 997. The
>>> actual error code is
>>> 5, ERROR_ACCESS_DENIED, so that confuses me too.
>>
>> This looks suspicious in CPort.pas (version 4Beta_D2010)
>> {code}
>> // create exception with windows error code
>> constructor EComPort.Create(ACode: Integer; AWinCode: Integer;
>> port:String);
>> begin
>>    FWinCode := AWinCode;
>>    FCode := ACode;
>> //  inherited CreateFmt(ComErrorMessages[ACode] + {_(}' (win error
>> code: %d)'{)}, [AWinCode]);
>>    inherited Create('COM Port Error: '+ComErrorMessage(AWinCode)+' 
>> on
>> '+port);
>> end;
>> {code}
>> ComErrorMessage returns a message that has nothing to do with the
>> error codes that GetLastError returns, therefor passing AWinCode to
>> the function is wrong.
>> If the error message shows 'PurgeComm function failed' it really 
>> means
>> ERROR_ACCESS_DENIED as you concluded yourself.
>> I suggest you switch the line that is outcommented to get correct
>> error messages.
>
> Doing it this way returns the same error message. The error codes 
> are defined in
> ComErrorMessage. I think they aren't the windows error codes, but 
> maybe should be.
>
> {code}
> //  inherited CreateFmt(ComErrorMessages[ACode] + {_(}' (win error 
> code: %d)'{)},
> [AWinCode]);
>   inherited Create('COM Port Error: '+ComErrorMessage(AWinCode)+' on 
> '+port);
> {code}

Geee, I didn't know I could be that ambiguous in my writing ;-)
I showed you the code as it is in the CPort.pas file I have, and 
indicated which version I have downloaded.
I then suggested that you could switch to the outcommented line to get 
correct error messages.
And then you respond with "Doing it this way returns the same error 
message." and a copy of the two lines with the same line outcommented 
as I wrote to you. Of course it returns the same message if you dont 
switch to the outcommented one!

CPort.pas (the version I have) defines on lines 569 .. 591 internal 
CPort error codes.
The messages that corresponds to these error codes are defined and 
returned by the ComErrorMessage function which is supposed to get  a 
CPort internal error code as the index parameter, *not* a Windows 
error code returned by GetLastError.
The line in the EComPort.create constructor that is in use (in the 
version of CPort that I have) is wrong:
    inherited Create('COM Port Error: '+ComErrorMessage(AWinCode)+' on 
'+port);
It passes AWinCode to the call to ComErrorMessage, when it should pass 
ACode.
ACode is the CPort internal error code and AWinCode is the Windows 
error code returned by GetLastError.

So I repeat my suggestion to use this line (remove the comment marks)
  //  inherited CreateFmt(ComErrorMessages[ACode] + ' (win error code: 
%d)', [AWinCode]);
and outcomment (add comment marks) the line
    inherited Create('COM Port Error: '+ComErrorMessage(AWinCode)+' on 
'+port);

Let's then see what the error message is *exactly* when your problem 
occurs.

Cheers
Tom

Tom

9/19/2010 8:35:08 PM

On 9/19/2010 4:35 PM, Tom Brunberg wrote:
> "Mike Reublin" wrote:
>> On 9/18/2010 6:02 AM, Tom Brunberg wrote:
>>> "Mike Reublin" wrote:
>>>> There are two devices attached to the same serial port by a "Y"
>>>> cable. The first is a
>>>> radio, the second an antenna controller.
>>>>
>>>> The antenna controller is a passive (as far as the serial port
>>>> goes)
>>>> device, it
>>>> doesn't reply back, it just follows whatever the radio does.
>
> Mike,
>
> Am I correct in my understanding that the radio sends "commands" to
> the antenna controller, not the PC?

The radio responds to changes made to it, whether commanded by the PC or from the 
physical buttons and knobbies on the radio front panel, by broadcasting those 
changes. Both the PC and the controller get them. The controller is just 
eavesdropping on that traffic.

> Well, actually further down you quote the manual "controller will
> listen to your radio", so I guess the answer is yes.

No.

>
>>>> If it is off, the port responds properly, and is able to set the radio. The radio gets
>>>> three sets of commands.
>>>>
>>>> If the antenna controller is on, the second command fails, so it
>>>> does have an effect.
>>>> If I switch the order in which the first two commands are sent,
>>>> the third fails.
>
> So, will the FA000... message trigger some activity on the serial line
> outward from the radio?
>

Yes.

>>> How is the 'Y' connection done?
>>
>> A DB9 connects to the serial port on the 'puter. Two cables exit it,
>> one going to the
>> radio, one to the antenna controller.
>>
>> Between the computer and radio the pins connected (straight through)
>> are:
>> 2. RXD
>> 3. TXD
>> 4. DTR
>> 5. Signal gnd.
>> 6. DSR
>> 7. RTS
>> 8. CTS
>>
>> Between the computer and controller (straight through):
>> 2. RXD
>> 5. Signal gnd.
>
> Ok, this would work if the radio is internally connected as a DCE
> (Data Communication Equipment) and the controller is internally
> connected as a DTE (Data Terminal Equipment). You wrote elsewhere that
> this has been working with your D7 version so I guess we can conclude
> the connection to be OK.

Plus it works with two other programs.

While you were off cavorting (I hope), I copied the code to my flaptop, also running 
D2010 but the OS is Win7 x64 Home. Using the same USB to serial adapter, it worked 
flawlessly. I copied the exe and dll from the flaptop back onto my XP box, and it 
sort of works the first time, but pulses the radio between transmit and  recieve, 
(shouldn't do that) and I get a ba-ding ba-dong sound from the PC. The radio can be 
set to transmit by setting either DTR or RTS high.

Using your change to the error handling (more on that below), the second time through 
it fails with "WriteFile function failed(Win error code:5)" in WriteAsync.  Closing 
the app throws another exception "PurgeComm function failed(Win error code:5)" in 
AbortAllAsync.

Not sure if this contains anything useful, or is a distractor.

> If you have an interest in DCE and DTE connections take a look at
> http://www.camiresearch.com/Data_Com_Basics/RS232_standard.html
>
I have read that.

>>>> In CPort.pas we eventually get to the WriteAsync function.
>>>> WriteFile always returns false, but the radio does get set. One of the writes (2nd or 3rd)
>>>> fails, Pending is set to false. The error message is "PurgeComm function failed on
>>>> COM5". It seems like the solution would be to call WaitForSingleObject(FHandle, 5000);,
>>>> but that didn't help. This error seems to be associated with error code 997. The
>>>> actual error code is 5, ERROR_ACCESS_DENIED, so that confuses me too.
>>>
>>> This looks suspicious in CPort.pas (version 4Beta_D2010)
>>> {code}
>>> // create exception with windows error code
>>> constructor EComPort.Create(ACode: Integer; AWinCode: Integer;
>>> port:String);
>>> begin
>>>     FWinCode := AWinCode;
>>>     FCode := ACode;
>>> //  inherited CreateFmt(ComErrorMessages[ACode] + {_(}' (win error
>>> code: %d)'{)}, [AWinCode]);
>>>     inherited Create('COM Port Error: '+ComErrorMessage(AWinCode)+'
>>> on +port);
>>> end;
>>> {code}
>>> ComErrorMessage returns a message that has nothing to do with the
>>> error codes that GetLastError returns, therefor passing AWinCode to
>>> the function is wrong.
>>> If the error message shows 'PurgeComm function failed' it really
>>> means ERROR_ACCESS_DENIED as you concluded yourself.
>>> I suggest you switch the line that is outcommented to get correct
>>> error messages.
>>
>> Doing it this way returns the same error message. The error codes
>> are defined in
>> ComErrorMessage. I think they aren't the windows error codes, but
>> maybe should be.
>>
>> {code}
>> //  inherited CreateFmt(ComErrorMessages[ACode] + {_(}' (win error
>> code: %d)'{)},[AWinCode]);
>>    inherited Create('COM Port Error: '+ComErrorMessage(AWinCode)+' on
>> '+port);
>> {code}
>
> Geee, I didn't know I could be that ambiguous in my writing ;-)
> I showed you the code as it is in the CPort.pas file I have, and
> indicated which version I have downloaded.
> I then suggested that you could switch to the outcommented line to get
> correct error messages.
> And then you respond with "Doing it this way returns the same error
> message." and a copy of the two lines with the same line outcommented
> as I wrote to you. Of course it returns the same message if you dont
> switch to the outcommented one!

Your success at disambiguation is no guarantee my compliance is correct. It was 
sleepy in here, and I'm fat and old..... <vbg>

I changed it and got a different message. Actually the line as written won't compile, 
so I made another change, and now it's
{code}
inherited CreateFmt(ComErrorMessage(ACode) + {_(}' (win error code: %d)'{)}, [AWinCode]);

//instead of

inherited CreateFmt(ComErrorMessages[ACode] + {_(}' (win error code: %d)'{)},[AWinCode]);
{code}
>
> CPort.pas (the version I have) defines on lines 569 .. 591 internal
> CPort error codes.
> The messages that corresponds to these error codes are defined and
> returned by the ComErrorMessage function which is supposed to get  a
> CPort internal error code as the index parameter, *not* a Windows
> error code returned by GetLastError.
> The line in the EComPort.create constructor that is in use (in the
> version of CPort that I have) is wrong:
>      inherited Create('COM Port Error: '+ComErrorMessage(AWinCode)+' on
> '+port);
> It passes AWinCode to the call to ComErrorMessage, when it should pass
> ACode.
> ACode is the CPort internal error code and AWinCode is the Windows
> error code returned by GetLastError.
>
> So I repeat my suggestion to use this line (remove the comment marks)
>    //  inherited CreateFmt(ComErrorMessages[ACode] + ' (win error code:
> %d)', [AWinCode]);
> and outcomment (add comment marks) the line
>      inherited Create('COM Port Error: '+ComErrorMessage(AWinCode)+' on
> '+port);
>
> Let's then see what the error message is *exactly* when your problem
> occurs.
>

Since it's passing a constant to the function, I'd guess it's going to be the same 
every time. The Win code might be different, in my case it's a 5, 
ERROR_ACCESS_DENIED. See above.

Regards, Mike

Mike

9/20/2010 4:30:17 PM

"Mike Reublin" wrote:
>
> No.

Ok, Mike, I think I got it anyway.

>>>>> If it is off, the port responds properly, and is able to set the 
>>>>> radio. The radio gets
>>>>> three sets of commands.
>>>>>
>>>>> If the antenna controller is on, the second command fails, so it
>>>>> does have an effect.
>>>>> If I switch the order in which the first two commands are sent,
>>>>> the third fails.
>>
>> So, will the FA000... message trigger some activity on the serial 
>> line
>> outward from the radio?
>
> Yes.
>
> Plus it works with two other programs.

Ok, no problem with the cable.

> While you were off cavorting (I hope)

Cavorting is probably not the right expression, but yes we had a good 
time with some friends.

> I copied the code to my flaptop, also running
> D2010 but the OS is Win7 x64 Home. Using the same USB to serial 
> adapter, it worked
> flawlessly. I copied the exe and dll from the flaptop back onto my 
> XP box, and it
> sort of works the first time, but pulses the radio between transmit 
> and  recieve,
> (shouldn't do that) and I get a ba-ding ba-dong sound from the PC. 
> The radio can be
> set to transmit by setting either DTR or RTS high.

Aaah, a USB to Serial adapter! Maybe the driver is different (64 bit 
vs. 32 bit) on the two PCs?

Or, (warning for wild guess with not much knowledge about the topic) 
could it be that the USB connector in the XP box doesn't provide the 
power required for the converter?

Did you test the two other programs on the Win7 or the XP machine?

> Using your change to the error handling (more on that below), the 
> second time through
> it fails with "WriteFile function failed(Win error code:5)" in 
> WriteAsync.  Closing
> the app throws another exception "PurgeComm function failed(Win 
> error code:5)" in
> AbortAllAsync.
>
> Not sure if this contains anything useful, or is a distractor.

Well, it is less of a distractor to have correct error messages than 
incorrect ones, no?

To remind you, in an earlier message I wrote about the PurgeComm 
error:
-----
Well, I see that PurgeComm is not called in
TCustomComPort.CreateHandle and you claim it is raised in the
CreateFile call. Goes beyond my comprehension.
-----
Now, that I know that the error was *not* about a call to PurgeComm to 
begin with, I feel much less distracted.

Once more I must return to the very first message in this thread, 
where you wrote:
-----
I'm using TComPort to talk to a device from my D2010 app. The first 
time this
function is called, it works. The next time (SetFreq) gives me 
"ComPort Error:
PurgeComm function failed." in CreateFile in 
TCustomComPort.CreateHandle;
-----
CreateHandle is called only from TCustomComPort.Open. The sources that 
you have shown sofar calls SetFreq in succession without any calls to 
ComPort.Open. So can you explain how you ended up in CreateHandle in 
conjunction with the second call to SetFreq? Or was it a totally new 
session?

> I changed it and got a different message. Actually the line as 
> written won't compile,
> so I made another change, and now it's
> {code}
> inherited CreateFmt(ComErrorMessage(ACode) + {_(}' (win error code: 
> %d)'{)}, [AWinCode]);
> //instead of
> inherited CreateFmt(ComErrorMessages[ACode] + {_(}' (win error code: 
> %d)'{)},[AWinCode]);
> {code}

Yeah, sorry for not spotting that one, ComErrorMessage has been an 
array in the past.

> Since it's passing a constant to the function, I'd guess it's going 
> to be the same
> every time. The Win code might be different, in my case it's a 5,
> ERROR_ACCESS_DENIED. See above.

There are about 25 different places in CPort.pas like for example
{code}
  if not ClearCommError(FHandle, Errors, @ComStat) then
    raise EComPort.Create(CError_ClearComFailed, GetLastError, FPort);
{code}
with any of the CError_xxxx constants passed to the EComPort.Create 
function so the messages will vary accordingly.

In your case it seems to be that you try to access the ComPort when 
windows thinks that you cant. Keeping in mind that it works in one PC 
and not in another one, strongly points in the direction of USB to 
Serial versus PC incompatibility somehow.
Then again, I guess the other two applications that work, are tested 
on your XP box, or?

Cheers
Tom

Tom

9/21/2010 12:22:22 AM

If you are using a USB to serial adapter, be sure it is one with the 
reliable chipset! Do a google search and you'll find the correct chip set, I 
don't remember it off the top of my head, but there was one that was 
definitely flakey. And as Tom said, the drivers could be different.

Dan


"Tom Brunberg" <[email protected]> wrote in message 
news:[email protected]
> "Mike Reublin" wrote:
>>
>> No.
>
> Ok, Mike, I think I got it anyway.
>
>>>>>> If it is off, the port responds properly, and is able to set the
>>>>>> radio. The radio gets
>>>>>> three sets of commands.
>>>>>>
>>>>>> If the antenna controller is on, the second command fails, so it
>>>>>> does have an effect.
>>>>>> If I switch the order in which the first two commands are sent,
>>>>>> the third fails.
>>>
>>> So, will the FA000... message trigger some activity on the serial
>>> line
>>> outward from the radio?
>>
>> Yes.
>>
>> Plus it works with two other programs.
>
> Ok, no problem with the cable.
>
>> While you were off cavorting (I hope)
>
> Cavorting is probably not the right expression, but yes we had a good
> time with some friends.
>
>> I copied the code to my flaptop, also running
>> D2010 but the OS is Win7 x64 Home. Using the same USB to serial
>> adapter, it worked
>> flawlessly. I copied the exe and dll from the flaptop back onto my
>> XP box, and it
>> sort of works the first time, but pulses the radio between transmit
>> and  recieve,
>> (shouldn't do that) and I get a ba-ding ba-dong sound from the PC.
>> The radio can be
>> set to transmit by setting either DTR or RTS high.
>
> Aaah, a USB to Serial adapter! Maybe the driver is different (64 bit
> vs. 32 bit) on the two PCs?
>
> Or, (warning for wild guess with not much knowledge about the topic)
> could it be that the USB connector in the XP box doesn't provide the
> power required for the converter?
>
> Did you test the two other programs on the Win7 or the XP machine?
>
>> Using your change to the error handling (more on that below), the
>> second time through
>> it fails with "WriteFile function failed(Win error code:5)" in
>> WriteAsync.  Closing
>> the app throws another exception "PurgeComm function failed(Win
>> error code:5)" in
>> AbortAllAsync.
>>
>> Not sure if this contains anything useful, or is a distractor.
>
> Well, it is less of a distractor to have correct error messages than
> incorrect ones, no?
>
> To remind you, in an earlier message I wrote about the PurgeComm
> error:
> -----
> Well, I see that PurgeComm is not called in
> TCustomComPort.CreateHandle and you claim it is raised in the
> CreateFile call. Goes beyond my comprehension.
> -----
> Now, that I know that the error was *not* about a call to PurgeComm to
> begin with, I feel much less distracted.
>
> Once more I must return to the very first message in this thread,
> where you wrote:
> -----
> I'm using TComPort to talk to a device from my D2010 app. The first
> time this
> function is called, it works. The next time (SetFreq) gives me
> "ComPort Error:
> PurgeComm function failed." in CreateFile in
> TCustomComPort.CreateHandle;
> -----
> CreateHandle is called only from TCustomComPort.Open. The sources that
> you have shown sofar calls SetFreq in succession without any calls to
> ComPort.Open. So can you explain how you ended up in CreateHandle in
> conjunction with the second call to SetFreq? Or was it a totally new
> session?
>
>> I changed it and got a different message. Actually the line as
>> written won't compile,
>> so I made another change, and now it's
>> {code}
>> inherited CreateFmt(ComErrorMessage(ACode) + {_(}' (win error code:
>> %d)'{)}, [AWinCode]);
>> //instead of
>> inherited CreateFmt(ComErrorMessages[ACode] + {_(}' (win error code:
>> %d)'{)},[AWinCode]);
>> {code}
>
> Yeah, sorry for not spotting that one, ComErrorMessage has been an
> array in the past.
>
>> Since it's passing a constant to the function, I'd guess it's going
>> to be the same
>> every time. The Win code might be different, in my case it's a 5,
>> ERROR_ACCESS_DENIED. See above.
>
> There are about 25 different places in CPort.pas like for example
> {code}
>  if not ClearCommError(FHandle, Errors, @ComStat) then
>    raise EComPort.Create(CError_ClearComFailed, GetLastError, FPort);
> {code}
> with any of the CError_xxxx constants passed to the EComPort.Create
> function so the messages will vary accordingly.
>
> In your case it seems to be that you try to access the ComPort when
> windows thinks that you cant. Keeping in mind that it works in one PC
> and not in another one, strongly points in the direction of USB to
> Serial versus PC incompatibility somehow.
> Then again, I guess the other two applications that work, are tested
> on your XP box, or?
>
> Cheers
> Tom

Daniel

9/21/2010 2:09:00 AM

"Mike Reublin" wrote:
> ERROR_ACCESS_DENIED

Mike,
I come to the access denied error later but first:

I looked through your code in Elecr.pas (from the post to 
attachments).
In StartCom(..)
{code}
  ComPort.SyncMethod := smWindowSync; // not for d2010
{code}
(just curious: why the comment "not for d2010")
...
then you set the event mask
{code}
  ComPort.Events := [evRxChar, evTxEmpty, evRxFlag, evRing, evBreak, 
evCTS, evDSR, evError, evRLSD, evRx80Full];
{code}
and then a handler for evRxChar
{code}
  ComPort.OnRxChar := TComPortRxHandler.ComPortRxChar;
{code}
If we then look at CPort.pas
in TComThread.Execute there's a call
{code}
      DispatchComMsg;
{code}
and in TComThread.DispatchComMsg
{code}
  case FComPort.SyncMethod of
...
    smWindowSync: SendEvents;
...
{code}
and in TComThread.SendEvents
{code}
...
  if evRxChar in FEvents then
    SendMessage(FComPort.FWindow, CM_COMPORT, EV_RXCHAR, 0);
...
{code}
but I can't see that you ever set FComPort.FWindow to anything.

So, AFAICS here's a contradiction: you set an OnRxChar event handler 
which never gets called, and you send a message to a nil handle. 
Please confirm that you never seen any received data or explain how 
you receive it.

If you would set
{code}
    ComPort.SyncMethod := smThreadSync
{code}
or
{code}
    ComPort.SyncMethod := smNone
{code}
then TComThread.DispatchComMsg would call
either
{code}
  Synchronize(DoEvents); // call events in main thread
{code}
or
{code}
  smNone:       DoEvents; // call events inside monitoring thread
{code}
and TComThread.DoEvents would call
{code}
  if evRxChar in FEvents then
    FComPort.CallRxChar;
{code}
and your OnRxChar would handle the received data.



Then to the ERROR_ACCESS_DENIED errors.

http://msdn.microsoft.com/en-us/library/ff802693.aspx

"One of the communications event flags specified in the call to 
SetCommMask is possibly EV_ERR. The occurrence of the EV_ERR event 
indicates that an error condition exists in the communications port. 
Other errors can occur in the port that do not cause the EV_ERR event 
to occur. In either case, errors associated with the communications 
port cause all I/O operations to be suspended until removal of the 
error condition. ClearCommError is the function to call to detect 
errors and clear the error condition."

In the code you have provided I can't see any handler for the evError 
event, thus I suspect that the com port gets locked by an error and 
therefore doesn't allow access.

Cheers
Tom

Tom

9/21/2010 9:42:53 AM

On 9/20/2010 8:22 PM, Tom Brunberg wrote:
>> I copied the code to my flaptop, also running D2010 but the OS is Win7 x64 Home. Using the same USB to serial
>> adapter, it worked flawlessly. I copied the exe and dll from the flaptop back onto my
>> XP box, and it sort of works the first time, but pulses the radio between transmit
>> and  recieve, (shouldn't do that) and I get a ba-ding ba-dong sound from the PC.
>> The radio can be set to transmit by setting either DTR or RTS high.
>
> Aaah, a USB to Serial adapter! Maybe the driver is different (64 bit
> vs. 32 bit) on the two PCs?

Probably. But if the other programs work using the same hardware......?

>
> Or, (warning for wild guess with not much knowledge about the topic)
> could it be that the USB connector in the XP box doesn't provide the
> power required for the converter?
>

It's plugged into one of the on-board jacks. Possible I suppose, but those other two 
programs that work indicate it's not hardware.

> Did you test the two other programs on the Win7 or the XP machine?

Both

>
>> Using your change to the error handling (more on that below), the
>> second time through it fails with "WriteFile function failed(Win error code:5)" in
>> WriteAsync.  Closing the app throws another exception "PurgeComm function failed(Win
>> error code:5)" in AbortAllAsync.
>>
>> Not sure if this contains anything useful, or is a distractor.
>
> Well, it is less of a distractor to have correct error messages than
> incorrect ones, no?
>

It is.

> To remind you, in an earlier message I wrote about the PurgeComm
> error:
> -----
> Well, I see that PurgeComm is not called in
> TCustomComPort.CreateHandle and you claim it is raised in the
> CreateFile call. Goes beyond my comprehension.
> -----
> Now, that I know that the error was *not* about a call to PurgeComm to
> begin with, I feel much less distracted.
>
> Once more I must return to the very first message in this thread,
> where you wrote:
> -----
> I'm using TComPort to talk to a device from my D2010 app. The first
> time this
> function is called, it works. The next time (SetFreq) gives me
> "ComPort Error:
> PurgeComm function failed." in CreateFile in
> TCustomComPort.CreateHandle;
> -----

When I run from the IDE the failure occurs when
ComPort.WriteStr('LK0;FR0;FT0;RT0;XT0;');
in SetFreq is executed.

Running outside the IDE it fails on the second call to SetFreq, but I can't tell 
which line.

> CreateHandle is called only from TCustomComPort.Open. The sources that
> you have shown sofar calls SetFreq in succession without any calls to
> ComPort.Open. So can you explain how you ended up in CreateHandle in
> conjunction with the second call to SetFreq? Or was it a totally new
> session?
>
No, I can't explain that, and as I remember, it was the same session. But that's not 
happening any more.

>> I changed it and got a different message. Actually the line as
>> written won't compile,
>> so I made another change, and now it's
>> {code}
>> inherited CreateFmt(ComErrorMessage(ACode) + {_(}' (win error code:
>> %d)'{)}, [AWinCode]);
>> //instead of
>> inherited CreateFmt(ComErrorMessages[ACode] + {_(}' (win error code:
>> %d)'{)},[AWinCode]);
>> {code}
>
> Yeah, sorry for not spotting that one, ComErrorMessage has been an
> array in the past.
>
>> Since it's passing a constant to the function, I'd guess it's going
>> to be the same
>> every time. The Win code might be different, in my case it's a 5,
>> ERROR_ACCESS_DENIED. See above.
>
> There are about 25 different places in CPort.pas like for example
> {code}
>    if not ClearCommError(FHandle, Errors, @ComStat) then
>      raise EComPort.Create(CError_ClearComFailed, GetLastError, FPort);
> {code}
> with any of the CError_xxxx constants passed to the EComPort.Create
> function so the messages will vary accordingly.

Well, yes. My point was that the error message returned will always be the same, 
regardless of the Win error code. I'd think (there I go again) that there might be 
more than one cause of a write failure.

>
> In your case it seems to be that you try to access the ComPort when
> windows thinks that you cant. Keeping in mind that it works in one PC
> and not in another one, strongly points in the direction of USB to
> Serial versus PC incompatibility somehow.
> Then again, I guess the other two applications that work, are tested
> on your XP box, or?

XP and Win7

>
> Cheers
> Tom

Mike

9/21/2010 11:53:18 AM

On 9/20/2010 10:09 PM, Daniel Sox wrote:
> If you are using a USB to serial adapter, be sure it is one with the
> reliable chipset! Do a google search and you'll find the correct chip set, I
> don't remember it off the top of my head, but there was one that was
> definitely flakey. And as Tom said, the drivers could be different.
>
> Dan

Thanks Dan.
The current one is using an FTDI chip, which is supposed to be the "good" one. I was 
using an adapter with the Prolific chip. There is no difference in the operation.

Mike

9/21/2010 11:55:58 AM

Mike,

I haven't followed this whole conversation, but have you ever thought of using 
an protocol analyzer to monitor serial traffic and timing in both directions?

Rgds, JohnH

John

9/21/2010 1:50:16 PM

"Tom Brunberg" wrote:
> So, AFAICS here's a contradiction: you set an OnRxChar event handler
> which never gets called, and you send a message to a nil handle.
> Please confirm that you never seen any received data or explain how
> you receive it.

Mike,
I will never, ever again trust my eyes in the morning ;-)
Looking at the code again, it's all there.

In TCustomComPort.Open
{code}
      if (FSyncMethod = smWindowSync) then
...
        FWindow := AllocateHWnd(WindowMethod);
{code}
and in TCustomComPort.WindowMethod(var Message: TMessage)
{code}
          case wParam of
            EV_RXCHAR:   CallRxChar;
            EV_TXEMPTY:  CallTxEmpty;
            EV_BREAK:    CallBreak;
            EV_RING:     CallRing;
            EV_CTS:      CallCTSChange;
            EV_DSR:      CallDSRChange;
            EV_RXFLAG:   CallRxFlag;
            EV_RLSD:     CallRLSDChange;
            EV_ERR:      CallError;
            EV_RX80FULL: CallRx80Full;
          end
{code}
and in TCustomComPort.CallRxChar
{code}
  if Count > 0 then
    DoRxChar(Count);
{code}
and in TCustomComPort.DoRxChar(Count: Integer)
{code}
  if Assigned(FOnRxChar) then
    FOnRxChar(Self, Count);
{code}
your OnRxChar handler is called.


This also ruins my thoughts about the error event, because CallError 
calls LastErrors, which in turn calls ClearCommErrors.

I have no further "good" ideas, sorry.

Cheers
Tom

Tom

9/21/2010 2:04:25 PM

On 9/21/2010 5:42 AM, Tom Brunberg wrote:
> "Mike Reublin" wrote:
>> ERROR_ACCESS_DENIED
>
> Mike,
> I come to the access denied error later but first:
>
> I looked through your code in Elecr.pas (from the post to
> attachments).
> In StartCom(..)
> {code}
>    ComPort.SyncMethod := smWindowSync; // not for d2010
> {code}
> (just curious: why the comment "not for d2010")

I don't remember, maybe from the help file:
"SyncMethod should usually be set to smThreadSync. Use smWindowSync in Windows NT 
service applications to define in which thread should events be called."

But if NOT set to smWindowSync, the handler for receive doesn't fire.

> ..
> then you set the event mask
> {code}
>    ComPort.Events := [evRxChar, evTxEmpty, evRxFlag, evRing, evBreak,
> evCTS, evDSR, evError, evRLSD, evRx80Full];
> {code}
> and then a handler for evRxChar
> {code}
>    ComPort.OnRxChar := TComPortRxHandler.ComPortRxChar;
> {code}
> If we then look at CPort.pas
> in TComThread.Execute there's a call
> {code}
>        DispatchComMsg;
> {code}
> and in TComThread.DispatchComMsg
> {code}
>    case FComPort.SyncMethod of
> ..
>      smWindowSync: SendEvents;
> ..
> {code}
> and in TComThread.SendEvents
> {code}
> ..
>    if evRxChar in FEvents then
>      SendMessage(FComPort.FWindow, CM_COMPORT, EV_RXCHAR, 0);
> ..
> {code}
> but I can't see that you ever set FComPort.FWindow to anything.

It's set in
{code}
procedure TCustomComPort.Open;
if (FEvents = []) then
   FThreadCreated := False
else
begin
   if (FSyncMethod = smWindowSync) then
     FWindow := AllocateHWnd(WindowMethod);
...
...
...
{code}
>
> So, AFAICS here's a contradiction: you set an OnRxChar event handler
> which never gets called, and you send a message to a nil handle.
> Please confirm that you never seen any received data or explain how
> you receive it.

Ahh, but it does get called.
>
> If you would set
> {code}
>      ComPort.SyncMethod := smThreadSync
> {code}
> or
> {code}
>      ComPort.SyncMethod := smNone
> {code}
> then TComThread.DispatchComMsg would call
> either
> {code}
>    Synchronize(DoEvents); // call events in main thread
> {code}
> or
> {code}
>    smNone:       DoEvents; // call events inside monitoring thread
> {code}
> and TComThread.DoEvents would call
> {code}
>    if evRxChar in FEvents then
>      FComPort.CallRxChar;
> {code}
> and your OnRxChar would handle the received data.

It does handle it. It does NOT handle it if SyncMethod is set to anything other than 
smWindowSync.
>
> Then to the ERROR_ACCESS_DENIED errors.
>
> http://msdn.microsoft.com/en-us/library/ff802693.aspx
>
> "One of the communications event flags specified in the call to
> SetCommMask is possibly EV_ERR. The occurrence of the EV_ERR event
> indicates that an error condition exists in the communications port.
> Other errors can occur in the port that do not cause the EV_ERR event
> to occur. In either case, errors associated with the communications
> port cause all I/O operations to be suspended until removal of the
> error condition. ClearCommError is the function to call to detect
> errors and clear the error condition."
>
> In the code you have provided I can't see any handler for the evError
> event, thus I suspect that the com port gets locked by an error and
> therefore doesn't allow access.
>

I suspect you're correct. Tracking down the error however........

I added the call to ClearCommError as below. Errno comes back zero. The failure is 
moved from SetFreq to SetMode.
{code}
   ComPort.WriteStr(AnsiString(rstr));
   OK := ClearCommError(Comport.Handle, errno, nil);
   ComPort.WriteStr('LK0;FR0;FT0;RT0;XT0;');
   OK := ClearCommError(Comport.Handle, errno, nil);
{code}

In SetMode the error is the same WriteFile function failure with a win code of 5.

I'm noticing now when the first call to WriteStr is made in SetFreq a dialog box (I 
think) flashes by very very fast. No way to read it.

And there's the sound and the Xmit/Rx toggle (6 times).

And a new feature. When closing the app, I get a dialog box with "Runtime error 216 
at address 09357DB8.". Google mostly tells me that's a sign of a virus.

I keep coming back to the fact that with the supposedly non-communicative control box 
turned off, it works error free. Is it possible the controller is loading up the RX 
line? But then how would it work from the Win 7 box?

I guess stuff like this is why we get the big bucks. Oh wait! I'm retired. NO 
bucks... ;-o>

Mike

9/21/2010 4:52:10 PM

On 9/21/2010 10:04 AM, Tom Brunberg wrote:
> Mike,
> I will never, ever again trust my eyes in the morning ;-)
> Looking at the code again, it's all there.

Mine aren't so good anymore any time of day.......

>
> In TCustomComPort.Open
> {code}
>        if (FSyncMethod = smWindowSync) then
> ..
>          FWindow := AllocateHWnd(WindowMethod);
> {code}
> and in TCustomComPort.WindowMethod(var Message: TMessage)
> {code}
>            case wParam of
>              EV_RXCHAR:   CallRxChar;
>              EV_TXEMPTY:  CallTxEmpty;
>              EV_BREAK:    CallBreak;
>              EV_RING:     CallRing;
>              EV_CTS:      CallCTSChange;
>              EV_DSR:      CallDSRChange;
>              EV_RXFLAG:   CallRxFlag;
>              EV_RLSD:     CallRLSDChange;
>              EV_ERR:      CallError;
>              EV_RX80FULL: CallRx80Full;
>            end
> {code}
> and in TCustomComPort.CallRxChar
> {code}
>    if Count>  0 then
>      DoRxChar(Count);
> {code}
> and in TCustomComPort.DoRxChar(Count: Integer)
> {code}
>    if Assigned(FOnRxChar) then
>      FOnRxChar(Self, Count);
> {code}
> your OnRxChar handler is called.
>
>
> This also ruins my thoughts about the error event, because CallError
> calls LastErrors, which in turn calls ClearCommErrors.
>
> I have no further "good" ideas, sorry.

OH NO!
Tom, thanks very much for riding with me. If the muse happens to strike, get back to me.

Regards, Mike
>
> Cheers
> Tom

Mike

9/21/2010 9:25:09 PM

On 9/21/2010 9:50 AM, John Herbster wrote:
> Mike,
>
> I haven't followed this whole conversation, but have you ever thought of using
> an protocol analyzer to monitor serial traffic and timing in both directions?
>
> Rgds, JohnH

John,

I had thought of it, but not acted. So I downloaded one on a trial basis, and 
couldn't get it to show anything. It has a slightly older sibling (freeware) which 
does show the traffic, but it didn't tell me anything I didn't already know from 
stepping thru the code.

The one I couldn't get to work supposedly monitors the state of the lines, which 
seems like it might be useful. I'll play with it some more.

Do you have one you like? Any hints generally on how to use, what to look for?

Regards, Mike

Mike

9/21/2010 9:31:52 PM

>> I haven't followed this whole conversation, but have you ever thought of 
>> using
>> an protocol analyzer to monitor serial traffic and timing in both directions?

"Mike Reublin" wrote
> Do you have one you like? Any hints generally on how to use, what to look for?

I don't have one.  Once 25 years ago, I used a hardware-in-a-box protocol 
analyzer that would capture the input, output, and control signals, with timing 
info.

Once about 15 years ago, I created a duplex serial analyzer with Delphi and two 
comports on a laptop.  But, as I recall, the problem was solved before I got to 
use it.

Regards, JohnH

John

9/21/2010 10:19:39 PM

On 9/21/2010 6:19 PM, John Herbster wrote:
>>> I haven't followed this whole conversation, but have you ever thought of
>>> using
>>> an protocol analyzer to monitor serial traffic and timing in both directions?
>
> "Mike Reublin" wrote
>> Do you have one you like? Any hints generally on how to use, what to look for?
>
> I don't have one.  Once 25 years ago, I used a hardware-in-a-box protocol
> analyzer that would capture the input, output, and control signals, with timing
> info.
>
> Once about 15 years ago, I created a duplex serial analyzer with Delphi and two
> comports on a laptop.  But, as I recall, the problem was solved before I got to
> use it.
>
> Regards, JohnH

Dang, I thought you were gonna give me the secret to resolution... ;-o>

There is definitely an interaction with the two devices that shouldn't be there. I 
just cobbled up a little test program using nrComLib and it works as long as the 
controller box is turned off.

Would one of these monitors be likely to be able to tell me the state of the lines? 
I'm still looking.

Mike

9/22/2010 1:48:16 AM

Mike Reublin wrote:

> Do you have one you like? Any hints generally on how to use, what to look
> for?

Portmon by Mark Russinovich has helped me a couple of times
http://technet.microsoft.com/en-us/sysinternals/bb896644.aspx

The only problem with this one, compared to an external monitor, is that you
don't see the actual electrical signals, only the commands and data sent
to/from the port itself.

-- 
Anders Isaksson, Sweden
BlockCAD: http://www.blockcad.net  
Gallery: http://www.blockcad.net/gallery/index.htm

Anders

9/22/2010 1:38:43 PM

On 9/22/2010 9:38 AM, Anders Isaksson wrote:
> Mike Reublin wrote:
>
>> Do you have one you like? Any hints generally on how to use, what to look
>> for?
>
> Portmon by Mark Russinovich has helped me a couple of times
> http://technet.microsoft.com/en-us/sysinternals/bb896644.aspx
>
> The only problem with this one, compared to an external monitor, is that you
> don't see the actual electrical signals, only the commands and data sent
> to/from the port itself.
>

Thanks, Anders.

I'll check it out.

Mike

9/22/2010 9:00:29 PM

I found a workaround, if not a real cause. Putting the devices on a real serial port 
stopped the weirdness. There are other devices connected by USB/serial adapters and 
the work OK. Now to find out what's wrong with the USB setup.

Again, thanks to all.

Mike

9/22/2010 9:03:35 PM

Mike Reublin wrote:
> I found a workaround, if not a real cause. Putting the devices on a real serial port 
> stopped the weirdness. There are other devices connected by USB/serial adapters and 
> the work OK. Now to find out what's wrong with the USB setup.


This might be a current thing. Do you have the the specs for the antenna 
and radio? IIRC, each USB hub allows a default current limit of 500mA 
per port. Open the device manager, find the hub for the ports used by 
the antenna and radio by selecting the "Energy" tab (or something else, 
I'm translating here :) ). It displays the current limit per port and 
what each device (your adapter in this case) has asked for upon 
initialization.

HTH,
Ronaldo

Ronaldo

9/22/2010 10:34:22 PM

On 9/22/2010 6:34 PM, Ronaldo Souza wrote:
>
> This might be a current thing. Do you have the the specs for the antenna
> and radio? IIRC, each USB hub allows a default current limit of 500mA
> per port. Open the device manager, find the hub for the ports used by
> the antenna and radio by selecting the "Energy" tab (or something else,
> I'm translating here :) ). It displays the current limit per port and
> what each device (your adapter in this case) has asked for upon
> initialization.
>
> HTH,
> Ronaldo

Sorry for not getting back sooner, Ronaldo. My internet connection has been down.

No, I don't have current draw specs for the hardware. I can't find anything like 
"Energy" tab. Can you be more specific as to how you got to it?

Since this all worked well until very recently, I wouldn't suspect this as a cause. 
But I don't discount it totally either.

I'd sure like to find a cure!

Mike

9/24/2010 1:33:58 PM

Hi Mike,

> I'd sure like to find a cure!

Me too!  :)

See the attachments NG.

-- 
Good luck,
Ronaldo

Ronaldo

9/24/2010 8:51:39 PM

On 9/24/2010 4:51 PM, Ronaldo Souza wrote:
> Hi Mike,
>
>> I'd sure like to find a cure!
>
> Me too!  :)
>
> See the attachments NG.
>

Thanks! Now I see it. Nothing plugged in exceeds the stated 500mA available per port. 
The iPod does use 500mA, but it's usually plugged into the laptop.

The quest continues.....

Mike

9/25/2010 2:03:15 PM

On 9/25/2010 10:03 AM, Mike Reublin wrote:
> On 9/24/2010 4:51 PM, Ronaldo Souza wrote:
>> Hi Mike,
>>
>>> I'd sure like to find a cure!
>>
>> Me too!  :)
>>
>> See the attachments NG.
>>
>
> Thanks! Now I see it. Nothing plugged in exceeds the stated 500mA available per port.
> The iPod does use 500mA, but it's usually plugged into the laptop.
>
> The quest continues.....

Quest ended..... in an unlikely (to me) place...

Someone suggested that the problem may be that windows was detecting the port as a 
serial mouse. Apparently that was correct, adding /NoSerialMice to the boot.ini file 
fixed it. Google it.

Mike

10/8/2010 8:59:17 PM

"Mike Reublin" wrote:
> Quest ended..... in an unlikely (to me) place...
>
> Someone suggested that the problem may be that windows was detecting 
> the port as a
> serial mouse. Apparently that was correct, adding /NoSerialMice to 
> the boot.ini file
> fixed it. Google it.

Glad to hear Mike!

And thank you for reporting back. This is good info to keep in mind.
Still it doesn't explain why switching power to the antenna controller 
(which was only listening to the radio to PC comm.)  had an influence. 
But hey, if it works, let's keep fingers crossed.

Cheers
Tom

Tom

10/10/2010 8:14:23 AM

On 10/10/2010 4:14 AM, Tom Brunberg wrote:
> "Mike Reublin" wrote:
>> Quest ended..... in an unlikely (to me) place...
>>
>> Someone suggested that the problem may be that windows was detecting
>> the port as a
>> serial mouse. Apparently that was correct, adding /NoSerialMice to
>> the boot.ini file
>> fixed it. Google it.
>
> Glad to hear Mike!
>
> And thank you for reporting back. This is good info to keep in mind.
> Still it doesn't explain why switching power to the antenna controller
> (which was only listening to the radio to PC comm.)  had an influence.
> But hey, if it works, let's keep fingers crossed.
>
> Cheers
> Tom

No it doesn't explain that. I did talk to the controller people, and they said that 
the controller never put anything on the line, and felt the problem was a case of a 
bad ground connection (it was not, so my VOM sez).

Changing band segments on the controller by using the buttons on the front panel of 
the controller (so nothing is writing to the serial port) pulsed the radio into 
transmit 7 times, so *SOMETHING* was being put on the line. Just bad mojo, I guess.

Anyhoo... Thanks again to you and the other guys who responded.

Regards,
Mike

Mike

10/10/2010 4:01:25 PM

Similar Posts:

  • failures that aren’t failures
  • Assertion Failure #2
  • firefox crash on Mac Quad G5 and «Talkback» failure, failure, failure, failure, failure………
  • Webparts failure
  • cs_close failure
  • superreview requested: [Bug 226141] DRefTool analysis for tree files : [Attachment 135868] handle alloc failures. nsTreeBodyFrame::EnsureColumns() ignores failure, nsTreeRange:: returns failure
  • Total perl6 test failure; are recent changes to IMCC involved?
  • Failure 3 and Failure 53
  • HTML::Tidy — test failure
  • Inheritance failure?
  • RE: Trying to publish site. I get this failure/error.
  • Loop Failure
  • Merge trees — NW653 edir 8736
  • AD driver not sending PW failure notifications
  • superreview cancelled: [Bug 226141] DRefTool analysis for tree files : [Attachment 135868] handle alloc failures. nsTreeBodyFrame::EnsureColumns() ignores failure, nsTreeRange:: returns failure
  • Failure to install Consoleone
  • Read Failure
  • DVI output failure
  • RE: Connect failure: OCIEnvNlsCreate (check ORACLE_HOME and NLSsettings etc.)
  • CORBA::COMM FAILURE
  • Too many simultaneous connections. (Failure)
  • Fwd: failure notice
  • Solaris gcc optimisation failures; was RE: [PATCH pp_hot.c] test failure in op/dor.t
  • superreview granted: [Bug 218025] International (Polish) characters cause pop3 login failure : [Attachment 134288] fix another possible case of this

2 / 2 / 6

Регистрация: 11.06.2013

Сообщений: 170

1

13.07.2015, 09:58. Показов 2428. Ответов 2


Добрый день.
Подскажите пожалуйста.
Стоят весы, данные с которых считываются по последовательному СОМ порту. (COM1)
Спец.шнур, один конец в COM порт ПК, другой в весы.
Так считаю вес с весов :

Delphi
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
procedure TForm1.Button2Click(Sender: TObject);
Var
V : SmallInt;
Diskr : ShortInt;
Weight : Double;
dk:Double;
begin
//19200 скорость
//8 бит данный
//1 стоп бит
//четность - even
ComPort1.Open;
 
SetLength(Buf,1);
Buf[0]:=$48;                      //Запрос дискретности
ComPort1.Write(@Buf[0],1);
Sleep(50);
SetLength(Buf,2);
ComPort1.Read(@Buf[0],2);          //считать 2 байта дискретности
CopyMemory(@Diskr,@Buf[1],1);      //1 байт не ебет - дискретность во втором
 
SetLength(Buf,1);
Buf[0]:=$45;                      //Запрос веса
ComPort1.Write(@Buf[0],1);
Sleep(50);
SetLength(Buf,2);
ComPort1.Read(@Buf[0],2);       //считать 2 байта веса
CopyMemory(@V,@Buf[0],2);
if v and 32768 > 1 then         //если 15 бит равен 1
    v :=  0-(v and 32767);      //стереть 15 бит нафиг и оставшееся вычесть из 0
                                //для получения нормального отрицательного веса
if Diskr = 0 then Weight :=  v* 0.001 ;     //1 грамм или 0.001 кг
if Diskr = 1 then Weight :=  v* 0.0001 ;    //0.1 грамм или 0.0001 кг
if Diskr = 4 then Weight :=  v* 0.01 ;      //10 грамм или 0.01 кг
if Diskr = 5 then Weight :=  v* 0.1 ;       //100 грамм или 0.1 кг
label3.Caption:= FloatToStr(Weight)
ComPort1.Close;
end;

Вылетает следующая ошибки : com port error : purgecomm function failed on com1.
Подскажите как с ней бороться

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Понравилась статья? Поделить с друзьями:
  • Submit canceled due to a script error please contact your system administrator перевод
  • Purchase completed error occurred blackhawk rescue mission 5
  • System error 1312 has occurred
  • Sublime text как изменить цвет фона
  • Puppeteer error timeout error