#1
  1. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2013
    Location
    India
    Posts
    65
    Rep Power
    20

    My program can't detect when the device from COM port is disconnected.


    Dear Friends, I'm writing one program in C which is communicating to Virtual Comport to send the commands to USB modem(to send SMS by AT commands). It works fine when the device is connected with the computer.But it is unable to handle the errors when someone dissconnect the device from the computer. I mean when there is no device on COM port the program is not indicating any errors not even notifications(May be i don't know how to get notifications !). Here my code indicates clear error befor connecting to the device. If it is not connected I am getting error. But after taking HANDLE by creating file(CreateFile function) When the device is disconnected(Forcly removed from the computer) I am unable to find the error. Even when I check from GetLastError() it gives me no error. Kindly suggest me what to do ?
    Following is the file in which I am dealing with COM port functions.

    Don't confuse yourself with "ProjectSMS.h". It is header created by me. And the "windows.h" is included in that header.

    Code:
    #include "ProjectSMS.h"
    HANDLE hComport;
    
    int ConnectWithModem(void) // Tested OK
    {
        char COM[]="COM";
        char numberOfComport[2];
        unsigned long result;
    
        itoa(comportNumber,numberOfComport,10);
        strcat(COM,numberOfComport);
    
    
    
        hComport = CreateFile(COM,
                            GENERIC_READ | GENERIC_WRITE,
                            0,
                            0,
                            OPEN_EXISTING,
                            FILE_ATTRIBUTE_NORMAL,
                            0);
    
        result = GetLastError();
    
        if(hComport == INVALID_HANDLE_VALUE ||
           result == ERROR_FILE_NOT_FOUND ||
           result == ERROR_DEVICE_NOT_CONNECTED) {
    
            printf("%lu",result);
            printf("\nReturning from first if\n");
            CloseHandle(hComport);
    
            return 1;
        }
    
        DCB dcbSerialParams = {0};
    
        dcbSerialParams.DCBlength = sizeof(dcbSerialParams);
    
        if(!GetCommState(hComport, &dcbSerialParams)) {
    
            printf("\nReturning from second if\n");
            CloseHandle(hComport);
    
            return 1;
        }
    
        dcbSerialParams.BaudRate = CBR_9600; // This has to be programmed for user input.
        dcbSerialParams.ByteSize = 8;
        dcbSerialParams.StopBits = ONESTOPBIT;
        dcbSerialParams.Parity = NOPARITY;
    
        if(!SetCommState(hComport, & dcbSerialParams)) {
    
            printf("\nReturning from third if\n");
            CloseHandle(hComport);
    
            return 1;
        }
    
        COMMTIMEOUTS timeouts = {0};
    
        timeouts.ReadIntervalTimeout = 50;
        timeouts.ReadTotalTimeoutConstant = 50;
        timeouts.ReadTotalTimeoutMultiplier = 10;
        timeouts.WriteTotalTimeoutConstant = 50;
        timeouts.WriteTotalTimeoutMultiplier = 10;
    
        if(!SetCommTimeouts(hComport, &timeouts)) {
    
            printf("\nReturning from third if\n");
            CloseHandle(hComport);
    
            return 1;
        }
    
        return 0;
    }
    
    int DissconnectWithModem(void) //Tested OK
    {
        if(CloseHandle(hComport)) {
            return 0;
        }
        else {
            return 1;
        }
    }
    
    int SendDataToModem(const char * data) //Tested OK
    {
        int lengthOfData = strlen(data);
    
        DWORD dwBytesRead = 0;
    
        if(!WriteFile(hComport,data,lengthOfData, &dwBytesRead,NULL)) {
    
           CloseHandle(hComport);
            return 1;
        }
    
        printf("LAST ERROR While Sending : %lu",GetLastError());
        getch();
    
        return 0;
    }
    
    int ReceiveDataFromComport(char *receivedData, int numberOfCharacter) //Tested OK but Confusing in size of the character
    {
        DWORD dwBytesRead = 0;
        if(!ReadFile( hComport, receivedData, numberOfCharacter, &dwBytesRead,NULL)) {
    
            CloseHandle(hComport);
            return 1;
        }
    
        printf("LAST ERROR While Receiving : %lu",GetLastError());
        getch();
    
        return 0;
    }
  2. #2
  3. Contributing User

    Join Date
    Aug 2003
    Location
    UK
    Posts
    5,109
    Rep Power
    1802
    Disconnecting the USB cable in a VCP connaection is not the same as disconnecting a serial cable in a real COM port. In a VCP, the serial port is emulated by teh connected device, so disconnecting it is more like pulling out the COM interface that disconnecting the cable.

    Windows' defauly usbser.sys device driver does not handle that particularly well and it is difficult to handle. When the hardware disappears, the driver is unloaded.

    The solution I employed was to use a replacement device driver from a company called Thesycon. This driver can be configured as "static" meaning that on disconnection, the driver remains loaded and restarts automatically when reconnected, or allows the port to be closed gracefully. It makes the USB cable behave much more like serial cable. This however is a commercial rather than hobbiest solution - the driver is not free. The demo version allows a connection to be used for four hours before requiring a PC reboot to start again. That may work for you experminentally, but you cannot distribute the demo driver.
    Last edited by clifford; June 1st, 2013 at 01:54 PM.
  4. #3
  5. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2013
    Location
    India
    Posts
    65
    Rep Power
    20

    Exclamation


    I was confused but, your answer gave me some way to think. Will it require more CPU resource to open and close the HANDLE ? What if I create (Rather Open ) HANDLE of COM port before sending the command and close the HANDLE after receiving the replay from modem. So If i have to send 10 message (For Example) I have to 10 times open and close the COM port from Win API. Will it be overhead ?
  6. #4
  7. Contributing User

    Join Date
    Aug 2003
    Location
    UK
    Posts
    5,109
    Rep Power
    1802
    Originally Posted by jaysinhp
    Will it be overhead ?
    In the scheme of things, the overhead will be trivial. That might be a good solution if the device does not send data autonomously.
  8. #5
  9. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2013
    Location
    India
    Posts
    65
    Rep Power
    20
    Originally Posted by clifford
    In the scheme of things, the overhead will be trivial. That might be a good solution if the device does not send data autonomously.
    I have solved it. I think solution was in front of my eyes. I was controlling device by "AT" commands. Now After sending each command I was listening the replay from Modem. So what I did after receiving data from Modem by Receive function I checked the value of dwBytesRead(out) if it is 0 (NULL) then it seems that device is disconnected.
    Still it doesn't satisfied me but kind of okay solution. In addition I have tried Opening and Closing handle of COM port after sending each command but It doesn't work. After disconnecting device still program was opening the COM port. Don't know the reason.

IMN logo majestic logo threadwatch logo seochat tools logo