当从HID设备读取数据时,窗口ReadFile()不会返回

时间:2017-01-17 00:35:55

标签: c++ hid

我正在尝试编写一个从HID设备发送和接收数据的程序。该装置采用ASTM协议进行通信。我正在使用hidsdi.h库与设备进行通信。到目前为止,我已经能够掌握设备。我现在正试图向设备发送消息,以便它发送响应作为回应。

我的代码:

HANDLE hDevice = CreateFile(devicePath, GENERIC_READ | GENERIC_WRITE, 0, NULL,
        OPEN_EXISTING, 0, NULL);
    if (hDevice == INVALID_HANDLE_VALUE)
    {
        // error…
    }

    char DataBuffer[] = "X";
    DWORD dwBytesToWrite = (DWORD)strlen(DataBuffer);
    DWORD dwBytesWritten = 0;
    BOOL bErrorFlag = FALSE;
    uint8_t * pTmpBuf = (uint8_t *)calloc(inputReportLength, sizeof(uint8_t));
    uint8_t * pAppBuffer = (uint8_t *)calloc(inputReportLength, sizeof(uint8_t));
    DWORD nRead;

    if (pTmpBuf == NULL)
    {
        //return error(“memory allocation failed”);
    }
    try{
        if (pTmpBuf == NULL)
        {
            ;// memory allocation error…
        }
        //
        // copy data to be sent, reserving the 1st byte for report ID
        //
        memcpy(pTmpBuf + 1, DataBuffer, sizeof(DataBuffer));
        bErrorFlag = WriteFile(hDevice, pTmpBuf, dwBytesToWrite, &dwBytesWritten, NULL);
        free(pTmpBuf);

        pTmpBuf = (uint8_t *)calloc(inputReportLength, sizeof(uint8_t));

        if (!bErrorFlag)
        {
            bErrorFlag = ReadFile(hDevice, pTmpBuf, inputReportLength, &nRead, NULL);
            DWORD dwError = GetLastError();

            if (!bErrorFlag)
            {
                memcpy(pAppBuffer, pTmpBuf + 1, nRead - 1);
                free(pTmpBuf);
            }


        }

        CloseHandle(hDevice);
        hDevice = INVALID_HANDLE_VALUE;

似乎WriteFile函数成功地向设备发送数据,但是当编译器尝试执行ReadFile()函数时,永远不会返回控件并且执行只会挂起。我还没有实现任何超时功能,我认为默认会有超时但编译器永远不会在ReadFile之后执行下一行。 我是ASTM通信协议的新手,还有很多东西,我仍然试图理解和包围我的手。

根据我的文档,框架的结构看起来像这样:

<STX> FN text <ETB> C1 C2 <CR> <LF>

其中每个字段都有一定的ASCII值。当我发送数据或发送消息的char表示足够时,我是否需要以这种方式对消息进行编码?就像我在代码中所做的那样。

根据文档,我需要执行以下操作以获取设备的响应:

1) Send “X” to the meter.
2) Meter responds with <EOT> HEADER <ENQ> within 2 seconds.
3) Send <NAK> to reject data transfer
4) Meter responds with <EOT> to indicate it is exiting the transfer phase.
5) Send <ENQ> to the meter to initiate sending remote commands.
6) Meter responds with <ACK> to indicate it is ready to receive remote commands.
7) Send remote commands.
Send <EOT> to the meter to indicate remote commands are complete.

我非常感谢有人帮助我。

可以找到设备的软件指南here

0 个答案:

没有答案