Probleme readfile sur port serie en overlapped

cs_looloo78 Messages postés 15 Date d'inscription vendredi 18 février 2005 Statut Membre Dernière intervention 26 novembre 2010 - 26 nov. 2010 à 14:44
BruNews Messages postés 21040 Date d'inscription jeudi 23 janvier 2003 Statut Modérateur Dernière intervention 21 août 2019 - 26 nov. 2010 à 22:42
Bonjour,

je me permets de poster ce post concernant un programme pour lire sur le port COM1 ou 2.
mais ca ne fonctionne pas, il se met automatiquement en time out et n'effectue pas de loop do while tant qu'il n'y a rien dans le buffer du port serie a la reception.

voici le code.
#include "stdafx.h"
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>

#define RX_SIZE         4096    /* taille tampon d'entrée  */
#define TX_SIZE         4096    /* taille tampon de sortie */
#define MAX_WAIT_READ   500    /* temps max d'attente pour lecture (en ms) */

bool WriteCom(void* buffer);
bool ReadCom() ;
HANDLE h_serialCOM = NULL;

int _tmain(int argc, _TCHAR* argv[])

{	
COMMTIMEOUTS g_cto =
{
    MAX_WAIT_READ,  /* ReadIntervalTimeOut          */
    0,              /* ReadTotalTimeOutMultiplier   */
    MAX_WAIT_READ,  /* ReadTotalTimeOutConstant     */
    0,              /* WriteTotalTimeOutMultiplier  */
    0               /* WriteTotalTimeOutConstant    */
};
DCB g_dcb =
{
    sizeof(DCB),        /* DCBlength            */
    9600,               /* BaudRate             */
    TRUE,               /* fBinary              */
    FALSE,              /* fParity              */
    FALSE,              /* fOutxCtsFlow         */
    FALSE,              /* fOutxDsrFlow         */
    DTR_CONTROL_DISABLE, /* fDtrControl          */
    FALSE,              /* fDsrSensitivity      */
    FALSE,              /* fTXContinueOnXoff    */
    FALSE,              /* fOutX                */
    FALSE,              /* fInX                 */
    FALSE,              /* fErrorChar           */
    FALSE,              /* fNull                */
    RTS_CONTROL_DISABLE, /* fRtsControl          */
    FALSE,              /* fAbortOnError        */
    0,                  /* fDummy2              */
    0,                  /* wReserved            */
    0x100,              /* XonLim               */
    0x100,              /* XoffLim              */
    8,                  /* ByteSize             */
    NOPARITY,           /* Parity               */
    ONESTOPBIT,         /* StopBits             */
    0x11,               /* XonChar              */
    0x13,               /* XoffChar             */
    '?',                /* ErrorChar            */
    0x1A,               /* EofChar              */
    0x10                /* EvtChar              */
};

h_serialCOM = CreateFile("COM2", GENERIC_READ|GENERIC_WRITE, 0, NULL,
                        OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
    if(h_serialCOM == INVALID_HANDLE_VALUE)
    {
        printf("\nErreur lors de l'ouverture du port COM");

    }

    /* affectation taille des tampons d'émission et de réception */
    SetupComm(h_serialCOM, RX_SIZE, TX_SIZE);

    /* configuration du port COM */
    if(!SetCommTimeouts(h_serialCOM, &g_cto) || !SetCommState(h_serialCOM, &g_dcb))
    {
        printf("\nErreur lors de la configuration du port COM");
        CloseHandle(h_serialCOM);
            }

    /* on vide les tampons d'émission et de réception, mise à 1 DTR */
    PurgeComm(h_serialCOM, PURGE_TXCLEAR|PURGE_RXCLEAR|PURGE_TXABORT|PURGE_RXABORT);
    EscapeCommFunction(h_serialCOM, SETDTR);

ReadCom();

return 0;
}
bool ReadCom() 
{
DWORD dwRead;
char lpBuf[50]={0};
bool fres=false;
bool fWaitingOnRead = false;
OVERLAPPED osReader = {0};
// Create the overlapped event. Must be closed before exiting
// to avoid a handle leak.
osReader.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
if (osReader.hEvent == NULL)
return false;
// Error creating overlapped event; abort.

do
{if (!fWaitingOnRead) 
{
// Issue read operation.
if (ReadFile(h_serialCOM, lpBuf, 1, &dwRead, &osReader)==false) 
{
if (GetLastError() != ERROR_IO_PENDING) // read not delayed?
// Error in communications; report it.
printf ("erreur de com");

else
fWaitingOnRead = true;//signaled
}
     else {
// read completed immediately
printf("succes reception :%s",lpBuf);
fres=true;
  }
}	


      if (fWaitingOnRead) 
{
DWORD dwRes = WaitForSingleObject(osReader.hEvent, 500);
switch(dwRes)
{
// Read completed.
case WAIT_OBJECT_0:
if (!GetOverlappedResult(h_serialCOM, &osReader, &dwRead, FALSE))
// Read completed successfully.
printf("\n succes reception :%s",lpBuf);
// Reset flag so that another opertion can be issued.
fWaitingOnRead = false;
fres = true;
break;

case WAIT_TIMEOUT:
printf("\n time out");

// Operation isn't complete yet. fWaitingOnRead flag isn't
// changed since I'll loop back around, and I don't want
// to issue another read until the first one finishes.
//
// This is a good time to do some background work.
fres = false;	
break;

default:
// Error in the WaitForSingleObject; abort.
// This indicates a problem with the OVERLAPPED structure's
// event handle.
printf("\n DEFAULT");
fres = false;
break;
}
}
}
while(fres=false);

}



il ya surement quelquechose qui deconne dans le commtimeout ou bien dans le do while de test readfile.
Comme vous avez pu le constater j'ai essayer de respecter a la lettre l'article sur msdn.
merci
kix

3 réponses

BruNews Messages postés 21040 Date d'inscription jeudi 23 janvier 2003 Statut Modérateur Dernière intervention 21 août 2019
26 nov. 2010 à 18:30
http://www.cppfrance.com/code.aspx?ID=22441
http://www.cppfrance.com/code.aspx?ID=18704

Tu as regardé ces très bons exemples ?

ciao...
BruNews, MVP VC++
0
cs_looloo78 Messages postés 15 Date d'inscription vendredi 18 février 2005 Statut Membre Dernière intervention 26 novembre 2010
26 nov. 2010 à 21:32
Brunews,

j'ai deja regarde le premier 22441 "bases vitales pour la com serie" qui est un tres bon resume mais seulement en non overlapped.
Car il ya toute une logique difficile pour moi a assimile en overlapped.

cependant dans mon programme, ne crois tu pas qu'il y ai un probleme de logique surtout avec les booleens?

kix
0
BruNews Messages postés 21040 Date d'inscription jeudi 23 janvier 2003 Statut Modérateur Dernière intervention 21 août 2019
26 nov. 2010 à 22:42
while(fres=false);
C'est voulu cette AFFECTATION ?

ciao...
BruNews, MVP VC++
0
Rejoignez-nous