c++winapiserial-port

sending file via com port always stops at a particular number of line in file


I am trying to send a txt file via com port to a plotter. The program reads a line from the txt file, sends it on the COM port to the plotter and waits for the acknowledgment which is a single ';' character.

The problem is that after sending the 12290th line from the txt file, the program always "stops" (no matter what the line, or the next line contains), which means that it waits for the acknowledgment. I cannot check for it, but I am pretty confident it was sent, beacuse the plotter would reset if it could not send via COM port.

I can't find what is the problem.

int main(int argc, char ** argv)
{
    HANDLE port = CreateFile(L"\\\\.\\COM12", GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
    if((port == INVALID_HANDLE_VALUE) || (port == NULL))
    {
        DWORD error = GetLastError();
        fprintf(stderr, "Could not open port.  Error 0x%lx.\n", error);
        return 1;
    }
    
    initcomport(port);

    DWORD flags = EV_RXFLAG;
    BOOL success = SetCommMask(port, flags);
    if (!success)
    {
        fprintf(stderr, "Could not set comm mask.\n");
    }

    OVERLAPPED osStatus = {0};
    osStatus.hEvent = CreateEvent(NULL, true, false, NULL);
    assert(osStatus.hEvent);
    if( osStatus.hEvent == NULL ) // error creating overlapped event handle
    {
        return -1;
    }

    std::string line;
    std::string PltFilename;
    std::cout << "give the path + filename + extension:" << std::endl;
    std::cin >> PltFilename;

    std::ifstream fin(PltFilename);
    if(!fin)
    {
        return -1;
    }
    
    int cmd_done_flag = 0;

    DWORD dwCommEvent = 0;
    BOOL fWaitingOnStat = FALSE;

    while (true)
    {
        if(std::getline(fin,line))
        {
            cmd_done_flag = 0;
            m_transmit(port, osStatus, line, 255);
        }
        else
        {
            std::cout << std::endl << "Plot end" << std::endl;
            break;
        }

        while(cmd_done_flag == 0)
        {
            // Issue a status event check if one hasn't been issued already.
            if (!fWaitingOnStat)
            {
                //fprintf(stderr, "Calling WaitCommEvent\n");
                if (!WaitCommEvent(port, &dwCommEvent, &osStatus))
                {
                    if (GetLastError() == ERROR_IO_PENDING)      
                    { 
                        //fprintf(stderr, "WaitCommEvent result is ERROR_IO_PENDING\n");
                        fWaitingOnStat = TRUE;
                    } 
                    else
                    {
                        fprintf(stderr, "Error in WaitCommEvent\n");
                        break; 
                    }
                }
                else { cmd_done_flag = ReportStatusEvent(port, dwCommEvent);} // WaitCommEvent returned immediately. // Deal with status event as appropriate.
            }

            // Check on overlapped operation.
            if (fWaitingOnStat)
            {
                DWORD dwOvRes;
                // Wait a little while for an event to occur.
                //fprintf(stderr, "Calling WaitForSingleObject\n");
                DWORD dwRes = WaitForSingleObject(osStatus.hEvent, 500);
                switch(dwRes)
                {
                    case WAIT_OBJECT_0: // Event occurred.
                                        if (!GetOverlappedResult(port, &osStatus, &dwOvRes, FALSE))       
                                        { fprintf(stderr, "Error from GetOverlappedResult\n");}// An error occurred in the overlapped operation; // call GetLastError to find out what it was // and abort if it is fatal.
                                        else{ cmd_done_flag = ReportStatusEvent(port, dwCommEvent);}// Status event is stored in the event flag // specified in the original WaitCommEvent call. // Deal with the status event as appropriate.
                                        // Set fWaitingOnStat flag to indicate that a new // WaitCommEvent is to be issued.
                                        fWaitingOnStat = FALSE;
                                        break;

                    case WAIT_TIMEOUT:  // Operation isn't complete yet. fWaitingOnStatusHandle flag // isn't changed since I'll loop back around and I don't want
                                        // to issue another WaitCommEvent until the first one finishes. // This is a good time to do some background work.
                                        //fprintf(stderr, "WAIT_TIMEOUT\n");
                                        
                                        break;

                    case ERROR_IO_INCOMPLETE:  
                                                break;

                    default:            // Error in the WaitForSingleObject; abort // This indicates a problem with the OVERLAPPED structure's event handle
                                        printf("Error in WaitForSingleObject: %i\n", GetLastError());
                                        CloseHandle(osStatus.hEvent);
                                        return 70;
                }
            }
        }
       
    }

    CloseHandle(osStatus.hEvent);
    CloseHandle(port);
    //DeleteFileW(*ComportFilename);
    fin.close();
    std::cout << "program will close, press a key to continue" << std::endl;
    _getch();

    return 0;
}

BOOL m_transmit(HANDLE HandleCom, OVERLAPPED HandleOverlapped, std::string DataToTransmit, unsigned int retries)
{
    BOOL retval = FALSE;
    while(retries>0)
    {
        retval = transmit(HandleCom, HandleOverlapped, DataToTransmit);
        if(retval==TRUE)
        {
            break;
        }
        else
        {
            Sleep(10);
            retries--;
        }
    }
    return retval;
}


BOOL transmit(HANDLE HandleCom, OVERLAPPED HandleOverlapped, std::string DataToTransmit)
{
    BOOL Status;
    //DataToTransmit should be  char or byte array, otherwise write will fail
    DWORD  NumOfBytesToWrite;              // No of bytes to write into the port
    DWORD  NumOfBytesWritten = 0;          // No of bytes written to the port
    DWORD dwRes;
    BOOL fWaiting = 1;

    NumOfBytesToWrite = strlen(DataToTransmit.c_str()); // Calculating the no of bytes to write into the port

    if( (HandleCom == INVALID_HANDLE_VALUE) || (HandleCom == NULL) )
    {
        printf("Invalid handle\n");
    }

    if( !WriteFile( HandleCom, DataToTransmit.c_str(), NumOfBytesToWrite, &NumOfBytesWritten, &HandleOverlapped ) )
    {
        if( GetLastError() != ERROR_IO_PENDING )// WriteFile failed, but isn't delayed. Report error and abort.
        {
            Status = FALSE;
        }
        else
        {   // Write is pending.
            while(fWaiting)
            {
                dwRes = WaitForSingleObject( HandleOverlapped.hEvent, 1000 );
                switch( dwRes )
                {
                    // OVERLAPPED structure's event has been signaled. 
                    case WAIT_OBJECT_0: if( !GetOverlappedResult( HandleCom, &HandleOverlapped, &NumOfBytesWritten, FALSE ) )
                                        {
                                            Status = FALSE;
                                            std::cout << "send error:" << GetLastError() << std::endl;
                                        }
                                        else// Write operation completed successfully.
                                        {
                                            //std::cout<<"delayed but sent, " << NumOfBytesWritten << " bytes" <<std::endl;
                                            std::cout << DataToTransmit.c_str() << std::endl;
                                            Status = TRUE;
                                        } 
                                        fWaiting = 0;
                                        break;
                                        
                    case WAIT_TIMEOUT:  std::cout << "write timed out. Errorcode?:" << GetLastError() << std::endl;
                                        break;

                    default:    //An error has occurred in WaitForSingleObject. This usually indicates a problem with the OVERLAPPED structure's event handle.
                                printf("transmit error: %i", GetLastError());
                                return FALSE;
                }
            
            }
        }
    }
    else  // WriteFile completed immediately.
    {
        //std::cout<<"sent immediately, " << NumOfBytesWritten << " bytes" <<std::endl;
        std::cout << DataToTransmit.c_str() << std::endl;
        Status = TRUE;
    }
    FlushFileBuffers(HandleCom);
    return Status;
}

BOOL initcomport(HANDLE hComm)
{
    /*------------------------------- Setting the Parameters for the SerialPort ------------------------------*/
    DCB dcbSerialParams = {0}; // Initializing DCB structure
    dcbSerialParams.DCBlength = sizeof(dcbSerialParams);

    BOOL Status = GetCommState(hComm, &dcbSerialParams); //retreives  the current settings

    if(Status == FALSE)
    {
        printf("Error! in GetCommState()\n");
    }

    dcbSerialParams.BaudRate = CBR_9600;   // Setting BaudRate = 9600
    dcbSerialParams.ByteSize = 8;          // Setting ByteSize = 8
    dcbSerialParams.StopBits = ONESTOPBIT; // Setting StopBits = 1
    dcbSerialParams.Parity = NOPARITY;     // Setting Parity = None
    dcbSerialParams.EvtChar = CMD_DONE_FLAG_CHAR;   // Byte which triggers EV_RXFLAG if received
    
    Status = SetCommState(hComm, &dcbSerialParams); //Configuring the port according to settings in DCB

    if(Status == FALSE)
    {
        printf("Error! in Setting DCB Structure\n");
        std::cout << GetLastError() << std::endl;
    }
    else
    {
        printf("Setting DCB Structure Successfull\n");
        printf("Baudrate = %d\n", dcbSerialParams.BaudRate);
        printf("ByteSize = %d\n", dcbSerialParams.ByteSize);
        printf("StopBits = %d\n", dcbSerialParams.StopBits);
        printf("Parity   = %d\n", dcbSerialParams.Parity);
    }
    /*------------------------------------ Setting Timeouts --------------------------------------------------*/
    /*COMMTIMEOUTS timeouts = {0};
    timeouts.ReadIntervalTimeout = 50;
    timeouts.ReadTotalTimeoutConstant = 50;
    timeouts.ReadTotalTimeoutMultiplier = 10;
    timeouts.WriteTotalTimeoutConstant = 50;
    timeouts.WriteTotalTimeoutMultiplier = 10;

    if (SetCommTimeouts(hComm, &timeouts) == FALSE)
    {
        printf("\n   Error! in Setting Time Outs");
        Status = 1;
    }
    else
    {
        printf("\n\n   Setting Serial Port Timeouts Successfull");
    }*/
    return Status;
}


int ReportStatusEvent(HANDLE port, DWORD event)
{
    //printf("event 0x%lx\n", s);

    int received_EV_RXFLAG = 0;

    if (event & EV_ERR) 
    {
        DWORD errors;
        COMSTAT stat;
        printf(" err");
        BOOL success = ClearCommError(port, &errors, &stat);
        if (success)
        {
            if (errors & CE_BREAK) { printf(" break"); }
            if (errors & CE_FRAME) { printf(" frame"); }
            if (errors & CE_OVERRUN) { printf(" overrun"); }
            if (errors & CE_RXOVER) { printf(" rxover"); }
            if (errors & CE_RXPARITY) { printf(" rxparity"); }

            assert(0 == (errors & ~(CE_BREAK | CE_FRAME |
                        CE_OVERRUN | CE_RXOVER | CE_RXPARITY)));
        }
    }

    if (event & EV_RING) { printf(" ring"); }
    if (event & EV_BREAK) { printf(" break"); }
    if (event & EV_CTS) { printf(" cts"); }
    if (event & EV_DSR) { printf(" dsr"); }
    if (event & EV_RLSD) { printf(" rlsd"); }
    if (event & EV_RXCHAR) 
    { 
        //printf(" rxchar"); 
    }
    if (event & EV_RXFLAG) 
    {
        received_EV_RXFLAG = 1;         
    }
    if (event & EV_TXEMPTY) 
    { 
        //printf(" txempty"); 
    }
    FlushFileBuffers(port);

    return received_EV_RXFLAG;
}

I tried debugging it but I don't see differences in the variables between the good and the bad state. I have even ported this to c but the behaviour is the same.

After closing the program and restarting, it will work again till the 12290th line.

The file which i use for testing around the problematic part: enter image description here


Solution

  • I remembered I used purgecomm() a while ago in an other project, so I started to test with the flags. Put it after flushfilebuffers(), and if I use PURGE_RXCLEAR flag the program will run till the end of the file. Now I looked up flushfilebuffers documentation and it says for communication devices it only flushes the tx buffer. My bad :D