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 WaitCommEventn");
                if (!WaitCommEvent(port, &dwCommEvent, &osStatus))
                {
                    if (GetLastError() == ERROR_IO_PENDING)      
                    { 
                        //fprintf(stderr, "WaitCommEvent result is ERROR_IO_PENDINGn");
                        fWaitingOnStat = TRUE;
                    } 
                    else
                    {
                        fprintf(stderr, "Error in WaitCommEventn");
                        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 WaitForSingleObjectn");
                DWORD dwRes = WaitForSingleObject(osStatus.hEvent, 500);
                switch(dwRes)
                {
                    case WAIT_OBJECT_0: // Event occurred.
                                        if (!GetOverlappedResult(port, &osStatus, &dwOvRes, FALSE))       
                                        { fprintf(stderr, "Error from GetOverlappedResultn");}// 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_TIMEOUTn");
                                        
                                        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: %in", 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 handlen");
    }

    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 Structuren");
        std::cout << GetLastError() << std::endl;
    }
    else
    {
        printf("Setting DCB Structure Successfulln");
        printf("Baudrate = %dn", dcbSerialParams.BaudRate);
        printf("ByteSize = %dn", dcbSerialParams.ByteSize);
        printf("StopBits = %dn", dcbSerialParams.StopBits);
        printf("Parity   = %dn", 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("nn   Setting Serial Port Timeouts Successfull");
    }*/
    return Status;
}


int ReportStatusEvent(HANDLE port, DWORD event)
{
    //printf("event 0x%lxn", 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.

New contributor

mov_a_dptr is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật