首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Win32上的异步串行I/O --如何创建警报事件

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

Stack Overflow用户
提问于 2020-01-22 20:07:55
回答 2查看 1.5K关注 0票数 2

我试着遵循艾伦丹佛的文章来实现异步串行端口I/O。本文中没有提到的是如何或在何处以有用的方式调用主程序循环中的函数。在将它们放入每秒钟返回的循环中之后,显然不需要定期调用ReadFile()。我尝试在循环中放置一个WaitCommEvent(),这样只有当字符到达端口时才会进行读取。造成了一连串的错误。在试图将代码简化为我可以在这里发布的东西时,即使我以重叠模式打开文件的尝试也开始失败,因此我似乎无法发布一个有用的示例。但是,我将发布一些类似于基本概念的文章,即如果我只需要在串行端口上显示字符之类的异步事件来触发读和写,那么我并不关心读写是否必须是同步的。艾伦丹佛的文章中的异步函数非常复杂,从他的例子中我还不清楚如何触发到达端口的字符的读取。

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

代码语言:javascript
复制
/* 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
}

发布额外的代码后,非常感谢从丽塔韩反馈。从其他帖子中可以清楚看到的是,我的同步示例没有理解这一点。因此,我附加了主要工作的异步版本,但是还有很多需要改进的地方。如果能把它简化成韩丽塔的例子的长度,那就太棒了。此示例执行“函数”,意思是它同时发送和接收。问题是,正如最初所述,它需要定期轮询端口中的字符,这是一个非常大的拖放。下面的代码是艾伦丹佛的代码的一个几乎相同的更新,它没有提供基于事件的响应,但它确实发送和接收字符。我目前正在一个带有两个串口的空调制解调器电缆上运行它,因此这种行为很容易观察到。通过更改SleepEX()语句的超时值,可以清楚地了解对串行端口轮询的依赖。尽管丽塔·韩的反馈很有用,但代码并没有显示我想要的行为。如果有人可以以下面的例子为例,让它响应到达串行端口的字符,而不是等待被轮询,那就是我要找的。我需要使用ReadFileEX()吗?是否有其他方式来注册需要混合在这里的事件?JosephM.Newcomer在这个文章中折扣所有串行事件的使用,说它们只存在于16位窗口兼容性,然后提供了一个比艾伦丹佛更复杂的如何编程串行端口的例子。真的需要这么难吗?

代码语言:javascript
复制
/* 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
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-01-23 08:22:26

  • 使用FILE_FLAG_OVERLAPPEDCreateFile中打开串行端口,如果您想异步地写入和读取。
  • 对于NULL中的lpNumberOfBytesRead参数:如果这是一个异步操作,则对该参数使用ReadFile以避免潜在的错误结果。您可以通过InternalHigh of 重叠检查读取长度。
  • ReadFileWriteFile可能导致错误代码ERROR_IO_PENDING,它不是失败;它指定写操作是异步等待完成的。

下面是一个您可以参考的示例:

代码语言:javascript
复制
int sendpckt(HANDLE hComm, unsigned length, unsigned char * pckt)
{
    BOOL result;
    DWORD dwCommEvent;
    OVERLAPPED oWrite = { 0 };
    DWORD errCode;

    result = SetCommMask(hComm, EV_TXEMPTY);
    if (!result) printf("Err: %d\n", GetLastError());

    result = WriteFile(hComm, pckt, length, NULL, &oWrite);
    if (result == FALSE)
    {
        errCode = GetLastError();

        if (errCode != ERROR_IO_PENDING)
            printf("Error! Setting CommMask\n");
    }

    OVERLAPPED commOverlapped = { 0 };

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

    assert(commOverlapped.hEvent);

    result = WaitCommEvent(hComm, &dwCommEvent, &commOverlapped);
    if (!dwCommEvent)
        printf("Error Setting WaitCommEvent()%d\n", GetLastError());
    else
    {
        // If WaitCommEvent() == TRUE then Read the received data 
        if (dwCommEvent & EV_TXEMPTY)
        {
            printf("Send complete.\n");
        }

    }

    CloseHandle(oWrite.hEvent);
    CloseHandle(commOverlapped.hEvent);

    return 0;
};
    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
int recvpckt(HANDLE hComm, unsigned char * pckt)
{
    BOOL result;
    int len = 0;
    OVERLAPPED oRead = { 0 };
    DWORD errCode;
    DWORD dwCommEvent;

    result = SetCommMask(hComm, EV_RXCHAR);
    if (!result) printf("Err: %d\n", GetLastError());

    result = ReadFile(hComm, pckt, 2048, NULL, &oRead);
    if (result == FALSE)
    {
        errCode = GetLastError();

        if (errCode != ERROR_IO_PENDING)
            printf("nError! Setting CommMask\n");
    }

    OVERLAPPED commOverlapped = { 0 };

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

    assert(commOverlapped.hEvent);

    result = WaitCommEvent(hComm, &dwCommEvent, &commOverlapped);
    if (!dwCommEvent)
        printf("Error Setting WaitCommEvent()%d\n", GetLastError());
    else
    {
        if (dwCommEvent & EV_TXEMPTY)
        {
            printf("Chars Recveived\n");
            len = oRead.InternalHigh;
        }

    }

    CloseHandle(oRead.hEvent);
    CloseHandle(commOverlapped.hEvent);

    return len;
};

void main(int argc, char *argv[]) {

    HANDLE hPort;
    int len;
    unsigned idx = 0;
    unsigned char TXBUF[] = "T", RXBUF[2048], port[64] = "COM8";

    SetConsoleTitle(port); // To specify serial port number on open 
    hPort = CreateFile(port, GENERIC_READ | GENERIC_WRITE, 0, NULL,
        OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 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");

    while (1) {

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

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

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

        SleepEx(1000, TRUE); // How often to look for data in RX buffer
    }

    CloseHandle(hPort); // Close the serial port
}

更新:

另一种方法是在没有SetCommMaskWaitCommEvent的情况下使用SetCommMask。以读操作为例:

代码语言:javascript
复制
int recvpckt(HANDLE hComm, unsigned char * pckt)
{
    BOOL result;
    int len = 0;
    OVERLAPPED oRead = { 0 };
    DWORD errCode;
    DWORD dwCommEvent;

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

    assert(oRead.hEvent);

    result = ReadFile(hComm, pckt, 2048, NULL, &oRead);
    if (result == FALSE)
    {
        errCode = GetLastError();

        if (errCode != ERROR_IO_PENDING)
            printf("nError! Setting CommMask\n");
    }

    DWORD dwWaitResult = WaitForSingleObject(oRead.hEvent, INFINITE);
    switch (dwWaitResult)
    {
    case WAIT_OBJECT_0:
        printf("Received.\n");
        break;
    case WAIT_TIMEOUT:
        printf("Timeout.\n");
        break;
    case WAIT_FAILED:
        printf("Failed.\n");
        break;
    case WAIT_ABANDONED:
        printf("Abandoned.\n");
        return FALSE;
    }

    CloseHandle(oRead.hEvent);

    return len;
};
票数 3
EN

Stack Overflow用户

发布于 2020-02-20 16:30:55

根据Rita的示例发布一个完整的功能解决方案:

代码语言:javascript
复制
/* ExAIO.c                                                         2020-02-20 */
#include <stdio.h>
#include <assert.h>
#include <windows.h>

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

  dcb.DCBlength = sizeof(dcb);

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

  Status = GetCommState(hComm, & 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 error
  dcb.ByteSize          = 8;            // Number of bits/byte, 4-8 
  dcb.StopBits          = ONESTOPBIT;   // 0,1,2 = 1, 1.5, 2
  dcb.EvtChar           = 0x7E;         // Flag

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

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

    // Initialize the rest of the OVERLAPPED structure to zero.
    oWrite.Internal     = 0;
    oWrite.InternalHigh = 0;
    oWrite.Offset       = 0;
    oWrite.OffsetHigh   = 0;

    assert(oWrite.hEvent);

    result = WriteFile(hComm, pckt, length, NULL, &oWrite);
    if (result == FALSE) {
       errCode = GetLastError();
     if (errCode != ERROR_IO_PENDING) printf("Error! Setting CommMask\n");
    }

    dwWaitResult = WaitForSingleObject(oWrite.hEvent, INFINITE);

    switch(dwWaitResult) {
      case WAIT_OBJECT_0:
        printf("No Wait. Send complete.\n");
        break;
      case WAIT_TIMEOUT:
        printf("Wait Timeout.\n");
        break;
      case WAIT_FAILED:
        printf("Wait Failed.\n");
        break;
      case WAIT_ABANDONED:
        printf("Wait Abandoned.\n");
        break;
      default:
        break;
    }

    CloseHandle(oWrite.hEvent);
    return 0;
};
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
int recvpckt(HANDLE hComm, unsigned char * pckt)
{
    BOOL result;
    DWORD dwWaitResult, errCode, BytesRead = 0;
    OVERLAPPED oRead = { 0 };

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

    // Initialize the rest of the OVERLAPPED structure to zero.
    oRead.Internal     = 0;
    oRead.InternalHigh = 0;
    oRead.Offset       = 0;
    oRead.OffsetHigh   = 0;

    assert(oRead.hEvent);

    result = ReadFile(hComm, pckt, 2048, &BytesRead, &oRead);
    if (result == FALSE) {
        errCode = GetLastError();
      if (errCode != ERROR_IO_PENDING) printf("nError! Setting CommMask\n");
    }

    dwWaitResult = WaitForSingleObject(oRead.hEvent, INFINITE);

    switch (dwWaitResult) {
    case WAIT_OBJECT_0:
        printf("Received: ");
        if (BytesRead > 0) {
          printf("%d byte(s) -- ", BytesRead);
        }
        else printf("Nothing\n");
        break;
    case WAIT_TIMEOUT:
        printf("RX Timeout.\n");
        break;
    case WAIT_FAILED:
        printf("RX Wait Failed: \n");
        if (BytesRead > 0) {
          printf("%d byte(s) -- ", BytesRead);
        }
        else printf("Nothing\n");
        break;
    case WAIT_ABANDONED:
        printf("RX Abandoned.\n");
        return FALSE;
    default:
        break;
    }

    CloseHandle(oRead.hEvent);
    return BytesRead;
};
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
int args(int argc, char * argv[], char * port) 
{
  static int i;
  i = atoi(argv[1]);
  sprintf(port, "\\\\.\\COM%d", i);
  return i;
};
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
char *TimeNow(char * TimeString)
{
  SYSTEMTIME st;
  GetSystemTime(&st);
  sprintf(TimeString, "%.2d:%.2d:%.2d.%.3d",
    st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);
  return TimeString;
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
void main(int argc, char *argv[]) 
{
    HANDLE hPort;
    int len;
    unsigned idx=0, portNum;
    unsigned char TXBUF[2048], RXBUF[2048], port[64], timeString[14], SendMe=0;

    if (argc > 1) portNum = args(argc, argv, port);
    else 
    {
      printf("Please identify the serial port number to open.\n");
      exit(0);
    }
    SetConsoleTitle(port); // To specify serial port number on open 

    hPort = CreateFile(port, GENERIC_READ | GENERIC_WRITE, 0, NULL,
        OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 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 %d Open at %s\n", portNum, TimeNow(timeString));
    }

    while (1) {
        TXBUF[0] = (SendMe++)%256;
        printf("Sending 0x%.2X at %s ", TXBUF[0], TimeNow(timeString));
        sendpckt(hPort, 1, TXBUF);

        len = recvpckt(hPort, RXBUF);
        if (len > 0) {
           printf("%s RCVD[%d byte(s)]: ", TimeNow(timeString), len);
         for (idx = 0; idx < len; idx++)
         {
            printf("%d:0x%.2X ", idx+1, RXBUF[idx]);
         }
          printf("\n");
        }

        SleepEx(1000, TRUE); // How often to send data out TX buffer
    }
    printf("Error: %d", GetLastError());
    CloseHandle(hPort); // Close the serial port
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59867506

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档