Win32上的异步串行I / O-如何创建警报事件

问题描述 投票:0回答:1

我尝试遵循Allen Denver的article实现异步串行端口I / O。本文中未提及的是如何以一种有用的方式在主程序循环中调用函数或在何处调用函数。将它们置于每秒返回的循环中之后,很明显,不需要定期调用ReadFile()了。我尝试将WaitCommEvent()放入循环中,以便仅当字符到达端口时才进行读取。这导致了一系列错误。在尝试将代码简化为可以在此处发布的内容时,甚至以OVERLAPPED模式打开文件的尝试也开始失败,因此似乎无法发布有用的示例。但是,我将发布与基本概念类似的内容,即如果我可以简单地通过异步事件(例如,串行端口上显示的字符)来触发读写,则我并不在乎读写是否必须同步。艾伦·丹佛(Allen Denver)的文章中涉及的异步函数非常复杂,从我的示例中我还不清楚如何触发到达端口的字符的读取。

在下面的代码中,while(1)循环的主体中注释了五行,在该循环中,我试图等待字符到达。即使以重叠模式打开端口(在原始代码中),WaitCommEvent()错误似乎也引用了挂起的I / O,并且发送和接收函数都具有自己的OVERLAPPED结构。解决此问题的正确方法是什么?

/* WINSIO.c                                                        2020-01-22 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <windows.h>
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
int ConfigureSerialPort(HANDLE hPort)
{
  int Status;
  DCB dcb = {0};
  COMMTIMEOUTS timeouts;

  dcb.DCBlength = sizeof(dcb);

  Status = GetCommTimeouts(hPort, &timeouts);
  GetCommTimeouts(hPort, &timeouts);
  timeouts.ReadIntervalTimeout          = 50;
  timeouts.ReadTotalTimeoutConstant     = 50;
  timeouts.ReadTotalTimeoutMultiplier   = 50;
  timeouts.WriteTotalTimeoutConstant    = 50;
  timeouts.WriteTotalTimeoutMultiplier  = 10;
  if (!SetCommTimeouts(hPort, &timeouts)) {
    printf("Error setting timeouts on port!\n");
  }

  Status = GetCommState(hPort, &dcb);
  dcb.BaudRate =          19200;
  dcb.Parity =            NOPARITY;
  dcb.fBinary =           TRUE;             // Binary mode; no EOF check 
  dcb.fParity =           FALSE;            // Enable parity checking 
  dcb.fOutxCtsFlow =      FALSE;            // No CTS output flow control 
  dcb.fOutxDsrFlow =      FALSE;            // No DSR output flow control 
  dcb.fDtrControl =       DTR_CONTROL_DISABLE; // DTR flow control type 
  dcb.fDsrSensitivity =   FALSE;            // DSR sensitivity 
  dcb.fTXContinueOnXoff = FALSE;            // XOFF continues Tx 
  dcb.fOutX =             FALSE;            // No XON/XOFF out flow control 
  dcb.fInX =              FALSE;            // No XON/XOFF in flow control
  dcb.fErrorChar =        FALSE;            // Disable error replacement 
  dcb.fNull =             FALSE;            // Disable null stripping 
  dcb.fRtsControl =       RTS_CONTROL_DISABLE; // RTS flow control 
  dcb.fAbortOnError =     FALSE;            // Do not abort reads/writes on err
  dcb.ByteSize =          8;                // Number of bits/byte, 4-8 
  dcb.StopBits =          ONESTOPBIT;       // 0,1,2 = 1, 1.5, 2
  dcb.EvtChar =           0x84;             // 'T' 

  if (!SetCommState (hPort, &dcb)) {
    printf("Unable to configure serial port!\n");
  }
  return 0;
};
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
int sendpckt(HANDLE hComm, unsigned length, unsigned char * pckt)
{
    unsigned long NbytesWritten = 0;
    int result;
    DWORD dwCommEvent;
    OVERLAPPED oWrite;

    oWrite.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
    if (oWrite.hEvent == NULL)
      return FALSE; // Error creating overlapped event handle.

    result = WriteFile(hComm, pckt, length, &NbytesWritten, NULL);
    //result = WriteFile(hComm, pckt, length, &NbytesWritten, &oWrite);

    if (!result) printf("Err: %d\n", GetLastError());
    WaitCommEvent(hComm, &dwCommEvent, &oWrite);

//    printf("Wrote? %d:%d\n", result, NbytesWritten);
    CloseHandle(oWrite.hEvent);
    return 0;
};
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
int recvpckt(HANDLE hComm, unsigned char * pckt)
{
  int Status, idx = 0, len = 0;
  unsigned long Nbytes;
  unsigned char chRead;
  OVERLAPPED oRead;

    do {
      //Status = ReadFile(hComm, &chRead, 1, &Nbytes, &oRead);
      Status = ReadFile(hComm, &chRead, 1, &Nbytes, NULL);
      if (Status) {
      pckt[idx++] = chRead;
      if(Nbytes > 0) len = idx;
       }
      }
     while(Nbytes > 0);
  return len;
};
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
int args(int argc, char * argv[], char * port) 
{
  static int i;
  i = atoi(argv[1]);
  sprintf(port, "\\\\.\\COM%d", i);
  return i;
};
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
void main(int argc, char *argv[]) {

  HANDLE hPort;
  int result, len, Status;
  DWORD dwCommEvent;
  OVERLAPPED o;
  unsigned idx = 0;
  unsigned char TXBUF[] = "T", RXBUF[2048], port[64];

  if (argc > 1) result = args(argc, argv, port);
   SetConsoleTitle(port); // To specify serial port number on open 
  hPort = CreateFile (port, GENERIC_READ | GENERIC_WRITE, 0, NULL,
                       //OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL); 
                       OPEN_EXISTING, 0, NULL); 

  ConfigureSerialPort(hPort);
    if (hPort == INVALID_HANDLE_VALUE) {
     printf("Error in openning serial port\n");
     exit(0); // No point in going on if serial port didn't open
     }
    else
     printf("Serial Port Open\n");

    Status = SetCommMask(hPort, EV_RXCHAR);
  if (Status == FALSE) printf("Error! Setting CommMask\n");

  o.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
  if (o.hEvent == NULL) printf("Error creating overlapped event; abort.\n");

  while (1) {

    sendpckt(hPort, 1, TXBUF);
    printf("Sending 0x%.2X\n", TXBUF[0]);

//  Status = WaitCommEvent(hPort, &dwCommEvent, &o); // Wait for chars
//  if (Status == FALSE)
//    printf("Error Setting WaitCommEvent()%d\n", GetLastError());
//  else { // If WaitCommEvent() == TRUE then Read the received data 

//    printf("Chars Recveived\n");  
    len = recvpckt(hPort, RXBUF);
    if (len > 0) 
    {
    printf("RCVD(%d): ", len);
    }

  for (idx=0; idx<len; idx++)
   {
    printf("%d:0x%.2X ", idx+1, RXBUF[idx]);
   }

//    }
    SleepEx(1000, TRUE); // How often to look for data in RX buffer
  }
  CloseHandle(o.hEvent); // Close the Event Handle
  CloseHandle(hPort); // Close the serial port
}

在丽塔·汉(Rita Han)非常感谢的反馈后,发布了其他代码。从其他帖子中可以明显看出,我的“同步”示例并没有说明问题。因此,我将附加大多数工作的异步版本,但是还有很多不足之处。如果可以简化到丽塔·韩(Rita Han)的榜样,那就太好了。此示例执行“功能”,意味着它同时发送和接收。问题是,如最初所述,它需要定期轮询端口以查看是否存在字符,这是一个巨大的负担。下面的代码几乎与Allen Denver的代码完全相同,并且没有提供我正在寻找的基于事件的响应,但是它确实发送和接收字符。我目前正在通过具有两个串行端口的空调制解调器电缆运行它,因此该行为非常容易观察到。通过更改SleepEX()语句上的超时值,可以清除对轮询串行端口的依赖。与Rita Han的反馈一样有用,该代码没有表现出我正在寻找的行为。如果有人可以采用以下示例,并使其响应到达串行端口而不是等待轮询的字符,那就是我要寻找的。我需要使用ReadFileEX()吗?还有其他方法可以在此处注册需要混合的事件吗?约瑟夫·纽科默(Joseph M. Newcomer)否认了串行事件在article中的所有使用,称它们仅出于16位窗口兼容性而存在,然后继续提供比艾伦·丹佛(Allen Denver)更复杂的示例,说明如何对串行端口进行编程。真的需要这么难吗?

/* WINAIO.c                                                        2020-01-22 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <windows.h>

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
int ConfigureSerialPort(HANDLE hPort) {
  int Status;
  DCB dcb = {0};
  COMMTIMEOUTS timeouts;

  dcb.DCBlength = sizeof(dcb);

  Status = GetCommTimeouts(hPort, & timeouts);
  GetCommTimeouts(hPort, & timeouts);
  timeouts.ReadIntervalTimeout = 50;
  timeouts.ReadTotalTimeoutConstant = 50;
  timeouts.ReadTotalTimeoutMultiplier = 50;
  timeouts.WriteTotalTimeoutConstant = 50;
  timeouts.WriteTotalTimeoutMultiplier = 10;
  if (!SetCommTimeouts(hPort, & timeouts)) {
    printf("Error setting timeouts on port!\n");
  }

  Status = GetCommState(hPort, & dcb);
  dcb.BaudRate = 19200;
  dcb.Parity = NOPARITY;
  dcb.fBinary = TRUE; // Binary mode; no EOF check 
  dcb.fParity = FALSE; // Enable parity checking 
  dcb.fOutxCtsFlow = FALSE; // No CTS output flow control 
  dcb.fOutxDsrFlow = FALSE; // No DSR output flow control 
  dcb.fDtrControl = DTR_CONTROL_DISABLE; // DTR flow control type 
  dcb.fDsrSensitivity = FALSE; // DSR sensitivity 
  dcb.fTXContinueOnXoff = FALSE; // XOFF continues Tx 
  dcb.fOutX = FALSE; // No XON/XOFF out flow control 
  dcb.fInX = FALSE; // No XON/XOFF in flow control
  dcb.fErrorChar = FALSE; // Disable error replacement 
  dcb.fNull = FALSE; // Disable null stripping 
  dcb.fRtsControl = RTS_CONTROL_DISABLE; // RTS flow control 
  dcb.fAbortOnError = FALSE; // Do not abort reads/writes on err
  dcb.ByteSize = 8; // Number of bits/byte, 4-8 
  dcb.StopBits = ONESTOPBIT; // 0,1,2 = 1, 1.5, 2
  dcb.EvtChar = 0x84; // 'T' 

  if (!SetCommState(hPort, & dcb)) {
    printf("Unable to configure serial port!\n");
  }
  return 0;
};
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
int sendpckt(HANDLE hComm, unsigned length, unsigned char *pckt) {
  unsigned long NbytesWritten = 0;
  OVERLAPPED ovl = {0};
  BOOL fRes;

  ovl.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
  if (ovl.hEvent == NULL)
    return FALSE; // Error creating overlapped event handle.

  //Issue Write.
  if (!WriteFile(hComm, pckt, length, & NbytesWritten, & ovl)) {
    if (GetLastError() != ERROR_IO_PENDING) {
      fRes = FALSE; // WriteFile failed, but isn't delayed. Report error...
    } else {
      //Write is pending.
      if (!GetOverlappedResult(hComm, & ovl, & NbytesWritten, TRUE))
        fRes = FALSE;
      else
        fRes = TRUE;
    }
  } else // Write operation completed successfully.
    fRes = TRUE;
  //    printf(" 0X%.2X ", chWrite);
  CloseHandle(ovl.hEvent);
  return fRes;
};
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
int recvpckt(HANDLE hComm, unsigned char *pckt) {
  # define READ_TIMEOUT 500 // milliseconds
  int len = 0;
  unsigned long Nbytes;
  unsigned char chRead, BUF[2048];
  BOOL fWaitingOnRead = FALSE;
  OVERLAPPED ovl = {0};
  DWORD dwRes;

  /*
  Status = SetCommMask(hComm, EV_RXFLAG);
  if (Status == FALSE) printf("Error! Setting CommMask\n");
//  else                 printf("Setting CommMask Succesful\n");
//  */

  ovl.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
  if (ovl.hEvent == NULL) printf("Error creating overlapped event; abort.\n");

  if (!fWaitingOnRead) {
    // Issue read operation
    if (!ReadFile(hComm, & BUF, 2048, & Nbytes, & ovl))
    //if(!ReadFile(hComm, &chRead, 1, &Nbytes, &ovl))
    {
      if (GetLastError() != ERROR_IO_PENDING) // read not delayed?
        // Error in communications; report it
        printf("Error in Communications...\n");
      else {
        fWaitingOnRead = TRUE;
        //   printf("l:%d ", len); // shows loop alive
      }
    } else {
      if (Nbytes > 0) {
        // read completed immediately
        memcpy(pckt, BUF, Nbytes);
        len = Nbytes;
        printf("Immediate Read Completion\n");
        //HandleASuccessfulRead(lpbuf, dwRead);
      }
    }
  }
  if (fWaitingOnRead) {
    dwRes = WaitForSingleObject(ovl.hEvent, READ_TIMEOUT);
    switch (dwRes) {
      // Read completed.
    case WAIT_OBJECT_0:
      if (!GetOverlappedResult(hComm, & ovl, & Nbytes, FALSE))
        printf("Error in Communications Lower Portion\n");
      // Error in communications; report it.
      else {
        if (Nbytes > 0) {
          // Read completed successfully
          // HandleASuccessfulRead(lpbuf, dwRead);
          // Will run away and execute here every time
          fWaitingOnRead = FALSE;
          memcpy(pckt, BUF, Nbytes);
          len = Nbytes;
          printf("Read Completion After Wait\n");
        }
      }
    case WAIT_TIMEOUT:
      //printf("l:%d %d\n", len,rxstate);
      // 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.
      // Good time to do some background work.
      break;

    default:
      // Error in the WaitForSingleObject; abort.
      // This indicates a problem with the OVERLAPPED structure's event handle
      break;
    }
  }
  CloseHandle(ovl.hEvent);
  return Nbytes;
};
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
int args(int argc, char *argv[], char *port) {
  static int i;
  i = atoi(argv[1]);
  sprintf(port, "\\\\.\\COM%d", i);
  return i;
};
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
void main(int argc, char *argv[]) {

  HANDLE hPort;
  int result, len, Status;
  DWORD dwCommEvent;
  OVERLAPPED o;
  unsigned idx = 0;
  unsigned char TXBUF[] = "T", RXBUF[2048], port[64];

  if (argc > 1) result = args(argc, argv, port);
  SetConsoleTitle(port); // To specify serial port number on open 
  hPort = CreateFile(port, GENERIC_READ | GENERIC_WRITE, 0, NULL,
    OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
  //OPEN_EXISTING, 0, NULL); 

  ConfigureSerialPort(hPort);
  if (hPort == INVALID_HANDLE_VALUE) {
    printf("Error in openning serial port\n");
    exit(0); // No point in going on if serial port didn't open
  } else
    printf("Serial Port Open\n");

  Status = SetCommMask(hPort, EV_RXCHAR);
  if (Status == FALSE) printf("Error! Setting CommMask\n");

  o.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
  if (o.hEvent == NULL) printf("Error creating overlapped event; abort.\n");

  while (1) { // This is the loop for getting work done.

    sendpckt(hPort, 1, TXBUF);
    printf("Sending 0x%.2X\n", TXBUF[0]);

    //  Status = WaitCommEvent(hPort, &dwCommEvent, &o); // Wait for chars
    //  if (Status == FALSE)
    //    printf("Error Setting WaitCommEvent()%d\n", GetLastError());
    //  else { // If WaitCommEvent() == TRUE then Read the received data 

    //    printf("Chars Recveived\n");  
    len = recvpckt(hPort, RXBUF);
    if (len > 0) {
      printf("RCVD(%d): ", len);
    }

    for (idx = 0; idx < len; idx++) {
      printf("%d:0x%.2X ", idx + 1, RXBUF[idx]);
    }

    //    }
    SleepEx(1000, TRUE); // How often to look for data in RX buffer
    // And how often to send data to the other port
  }
  CloseHandle(o.hEvent); // Close the Event Handle
  CloseHandle(hPort); // Close the serial port
}
c asynchronous winapi
1个回答
0
投票
  • 如果要异步写入和读取,请在FILE_FLAG_OVERLAPPED中用CreateFile打开串行端口。
  • 对于CreateFile中的lpNumberOfBytesRead参数:如果此操作是异步操作,请使用ReadFile作为此参数,以避免潜在的错误结果。您可以通过NULLInternalHigh检查读取的长度。
  • OVERLAPPEDReadFile可能会导致错误代码WriteFile,这不是故障;它指定写操作正在异步完成中。

以下是您可以参考的示例:

WriteFile
热门问题
推荐问题
最新问题