Пример #1
0
int _CRTAPI1 main(int argc, char *argv[]) {
    CHAR *myPort = "COM1";
    DCB myDcb;
    DWORD junk;
    COMMTIMEOUTS myTimeOuts;
    DWORD numberActuallyRead;
    DWORD numberActuallyWritten;
    UCHAR readBuff[1000];
    HANDLE comHandle;
    DWORD startingTicks;
    OVERLAPPED readOl;
    OVERLAPPED writeOl;
    UCHAR writeBuff[5] = {0,1,2,3,4};

    if (argc > 1) {

        myPort = argv[1];

    }

    if ((comHandle = CreateFile(
                     myPort,
                     GENERIC_READ | GENERIC_WRITE,
                     0,
                     NULL,
                     CREATE_ALWAYS,
                     FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED,
                     NULL
                     )) == ((HANDLE)-1)) {

        FAILURE;

    }

    if (!(readOl.hEvent = CreateEvent(
                             NULL,
                             TRUE,
                             FALSE,
                             NULL
                             ))) {

        FAILURE;

    }

    if (!(writeOl.hEvent = CreateEvent(
                             NULL,
                             TRUE,
                             FALSE,
                             NULL
                             ))) {

        FAILURE;

    }

    if (!GetCommState(
             comHandle,
             &myDcb
             )) {

        FAILURE;

    }

    myDcb.BaudRate = 19200;
    myDcb.ByteSize = 8;
    myDcb.StopBits = ONESTOPBIT;
    myDcb.Parity = NOPARITY;
    myDcb.fOutxCtsFlow = FALSE;
    myDcb.fOutxDsrFlow = FALSE;
    myDcb.fDsrSensitivity = FALSE;
    myDcb.fOutX = FALSE;
    myDcb.fInX = FALSE;
    myDcb.fRtsControl = RTS_CONTROL_ENABLE;
    myDcb.fDtrControl = DTR_CONTROL_ENABLE;
    if (!SetCommState(
            comHandle,
            &myDcb
            )) {

        FAILURE;

    }

    //
    // Test to make sure that all maxdword on read is illegal.
    //

    myTimeOuts.ReadIntervalTimeout = MAXDWORD;
    myTimeOuts.ReadTotalTimeoutMultiplier = MAXDWORD;
    myTimeOuts.ReadTotalTimeoutConstant = MAXDWORD;
    myTimeOuts.WriteTotalTimeoutMultiplier = MAXDWORD;
    myTimeOuts.WriteTotalTimeoutConstant = MAXDWORD;

    if (SetCommTimeouts(
             comHandle,
             &myTimeOuts
             )) {

        FAILURE;

    }

    //
    // Test that MAXDWORD,0,0 will return immediately with whatever
    // is there
    //

    myTimeOuts.ReadIntervalTimeout = MAXDWORD;
    myTimeOuts.ReadTotalTimeoutMultiplier = 0;
    myTimeOuts.ReadTotalTimeoutConstant = 0;
    myTimeOuts.WriteTotalTimeoutMultiplier = MAXDWORD;
    myTimeOuts.WriteTotalTimeoutConstant = MAXDWORD;

    if (!SetCommTimeouts(
             comHandle,
             &myTimeOuts
             )) {

        FAILURE;

    }

    startingTicks = GetTickCount();
    if (!ReadFile(
             comHandle,
             &readBuff[0],
             1000,
             &numberActuallyRead,
             &readOl
             )) {

        if (GetLastError() != ERROR_IO_PENDING) {

            FAILURE;

        }

        if (!GetOverlappedResult(
                 comHandle,
                 &readOl,
                 &numberActuallyRead,
                 TRUE
                 )) {

            FAILURE;

        }

    }

    //
    // We certainly should have gotten back in less than a
    // a half a second.
    //

    if ((GetTickCount() - startingTicks) > 500) {

        FAILURE;

    }

    if (numberActuallyRead) {

        FAILURE;

    }

    //
    // Write out five bytes and make sure that is what we get back
    //

    if (!WriteFile(
             comHandle,
             &writeBuff[0],
             5,
             &numberActuallyWritten,
             &writeOl
             )) {

        if (GetLastError() != ERROR_IO_PENDING) {

            FAILURE;

        }

        if (!GetOverlappedResult(
                 comHandle,
                 &writeOl,
                 &numberActuallyWritten,
                 TRUE
                 )) {

            FAILURE;

        }

        if (numberActuallyWritten != 5) {

            FAILURE;

        }

    }

    //
    // Give some time for the chars to get there.
    //

    Sleep (100);

    startingTicks = GetTickCount();
    if (!ReadFile(
             comHandle,
             &readBuff[0],
             1000,
             &numberActuallyRead,
             &readOl
             )) {

        if (GetLastError() != ERROR_IO_PENDING) {

            FAILURE;

        }

        if (!GetOverlappedResult(
                 comHandle,
                 &readOl,
                 &numberActuallyRead,
                 TRUE
                 )) {

            FAILURE;

        }

    }

    //
    // We certainly should have gotten back in less than a
    // a half a second.
    //

    if ((GetTickCount() - startingTicks) > 500) {

        FAILURE;

    }

    if (numberActuallyRead != 5) {

        FAILURE;

    }

    //
    // Test that the os2 wait for something works.
    //
    // First test that if there is something in the buffer
    // it returns right away.
    //
    // Then test that if there isn't something, then if we
    // put in the amount expected before the timeout expires
    // that it returns.
    //
    // The test that if there isn't something and nothing
    // happens before the timeout it returns after the timeout
    // with nothing.
    //
    myTimeOuts.ReadIntervalTimeout = MAXDWORD;
    myTimeOuts.ReadTotalTimeoutMultiplier = 0;
    myTimeOuts.ReadTotalTimeoutConstant = 5000;
    myTimeOuts.WriteTotalTimeoutMultiplier = MAXDWORD;
    myTimeOuts.WriteTotalTimeoutConstant = MAXDWORD;

    if (!SetCommTimeouts(
             comHandle,
             &myTimeOuts
             )) {

        FAILURE;

    }

    if (!WriteFile(
             comHandle,
             &writeBuff[0],
             5,
             &numberActuallyWritten,
             &writeOl
             )) {

        if (GetLastError() != ERROR_IO_PENDING) {

            FAILURE;

        }

        if (!GetOverlappedResult(
                 comHandle,
                 &writeOl,
                 &numberActuallyWritten,
                 TRUE
                 )) {

            FAILURE;

        }

        if (numberActuallyWritten != 5) {

            FAILURE;

        }

    }

    //
    // Give some time for the chars to get there.
    //

    Sleep (100);
    startingTicks = GetTickCount();
    if (!ReadFile(
             comHandle,
             &readBuff[0],
             1000,
             &numberActuallyRead,
             &readOl
             )) {

        if (GetLastError() != ERROR_IO_PENDING) {

            FAILURE;

        }

        //
        // Give it at most a 1/2 second to finish for
        // the irp to complete immediately.
        //

        Sleep(500);
        if (!GetOverlappedResult(
                 comHandle,
                 &readOl,
                 &numberActuallyRead,
                 FALSE
                 )) {

            FAILURE;

        }

    }

    if ((GetTickCount() - startingTicks) > 1000) {

        FAILURE;

    }

    if (numberActuallyRead != 5) {

        FAILURE;

    }

    //
    // Do the second os2 test
    //

    if (ReadFile(
             comHandle,
             &readBuff[0],
             1000,
             &numberActuallyRead,
             &readOl
             )) {

        FAILURE;

    }

    if (GetLastError() != ERROR_IO_PENDING) {

        FAILURE;

    }

    //
    // Give it a second for the the read to complete
    //
    //

    Sleep(1000);

    //
    // Call the GetOverlapped and make sure that it returns
    // ERROR_IO_INCOMPLETE.
    //

    if (GetOverlappedResult(
            comHandle,
            &readOl,
            &numberActuallyRead,
            FALSE
            )) {

            FAILURE;

    }

    if (GetLastError() != ERROR_IO_INCOMPLETE) {

        FAILURE;

    }

    //
    // Do the write file and make sure that there is enough
    // time for the chars to make it.
    //

    if (!WriteFile(
             comHandle,
             &writeBuff[0],
             5,
             &numberActuallyWritten,
             &writeOl
             )) {

        if (GetLastError() != ERROR_IO_PENDING) {

            FAILURE;

        }

        if (!GetOverlappedResult(
                 comHandle,
                 &writeOl,
                 &numberActuallyWritten,
                 TRUE
                 )) {

            FAILURE;

        }

        if (numberActuallyWritten != 5) {

            FAILURE;

        }

    }

    //
    // Give some time for the chars to get there.
    //

    Sleep(100);

    //
    // Wait for no more than 6 seconds for the IO to complete
    //

    if (WaitForSingleObject(
            readOl.hEvent,
            6000
            ) != WAIT_OBJECT_0) {

        FAILURE;

    }

    //
    // Make sure we got everything we wrote
    //

    if (!GetOverlappedResult(
            comHandle,
            &readOl,
            &numberActuallyRead,
            FALSE
            )) {

        FAILURE;

    }

    if (numberActuallyRead != 5) {

        FAILURE;

    }

    //
    // Do the third os2 wait for something test.
    //

    startingTicks = GetTickCount();
    if (ReadFile(
             comHandle,
             &readBuff[0],
             1000,
             &numberActuallyRead,
             &readOl
             )) {

        FAILURE;

    }

    if (GetLastError() != ERROR_IO_PENDING) {

        FAILURE;

    }

    //
    // Give it a second for the the read to complete
    //
    //

    Sleep(1000);

    //
    // Call the GetOverlapped and make sure that it returns
    // ERROR_IO_INCOMPLETE.
    //

    if (GetOverlappedResult(
            comHandle,
            &readOl,
            &numberActuallyRead,
            FALSE
            )) {

            FAILURE;

    }

    if (GetLastError() != ERROR_IO_INCOMPLETE) {

        FAILURE;

    }

    //
    // Wait for no more than 10 seconds for the IO to complete
    //

    if (WaitForSingleObject(
            readOl.hEvent,
            10000
            ) != WAIT_OBJECT_0) {

        FAILURE;

    }

    //
    // It shouldn't be more than 6 seconds for the Io to be done.
    //

    if ((GetTickCount() - startingTicks) > 6000) {

        FAILURE;

    }

    //
    // Make sure we got everything we wrote, which in this case is zero.
    //

    if (!GetOverlappedResult(
            comHandle,
            &readOl,
            &numberActuallyRead,
            FALSE
            )) {

        FAILURE;

    }

    if (numberActuallyRead) {

        FAILURE;

    }

    //
    // Test the graphics mode quick return.
    //
    // First test that if there is something in the buffer
    // it returns right away.
    //
    // Then test that if there isn't something, then if we
    // put in 2 characters it returns right away with one
    // and then the other read will return right away with
    // 1.
    //
    // Then test that if there isn't something and nothing
    // happens before the timeout it returns after the timeout
    // with nothing.
    //
    myTimeOuts.ReadIntervalTimeout = MAXDWORD;
    myTimeOuts.ReadTotalTimeoutMultiplier = MAXDWORD;
    myTimeOuts.ReadTotalTimeoutConstant = 5000;
    myTimeOuts.WriteTotalTimeoutMultiplier = MAXDWORD;
    myTimeOuts.WriteTotalTimeoutConstant = MAXDWORD;

    if (!SetCommTimeouts(
             comHandle,
             &myTimeOuts
             )) {

        FAILURE;

    }

    if (!WriteFile(
             comHandle,
             &writeBuff[0],
             5,
             &numberActuallyWritten,
             &writeOl
             )) {

        if (GetLastError() != ERROR_IO_PENDING) {

            FAILURE;

        }

        if (!GetOverlappedResult(
                 comHandle,
                 &writeOl,
                 &numberActuallyWritten,
                 TRUE
                 )) {

            FAILURE;

        }

        if (numberActuallyWritten != 5) {

            FAILURE;

        }

    }

    //
    // Give some time for the chars to get there.
    //

    Sleep (100);
    startingTicks = GetTickCount();
    if (!ReadFile(
             comHandle,
             &readBuff[0],
             1000,
             &numberActuallyRead,
             &readOl
             )) {

        if (GetLastError() != ERROR_IO_PENDING) {

            FAILURE;

        }

        //
        // Give it at most a 1/2 second to finish for
        // the irp to complete immediately.
        //

        Sleep(500);
        if (!GetOverlappedResult(
                 comHandle,
                 &readOl,
                 &numberActuallyRead,
                 FALSE
                 )) {

            FAILURE;

        }

    }

    if ((GetTickCount() - startingTicks) > 1000) {

        FAILURE;

    }

    if (numberActuallyRead != 5) {

        FAILURE;

    }

    //
    // Do the second graphics wait test.
    //
    if (ReadFile(
             comHandle,
             &readBuff[0],
             1000,
             &numberActuallyRead,
             &readOl
             )) {

        FAILURE;

    }

    if (GetLastError() != ERROR_IO_PENDING) {

        FAILURE;

    }

    //
    // Give it a second for the the read to complete
    //
    //

    Sleep(1000);

    //
    // Call the GetOverlapped and make sure that it returns
    // ERROR_IO_INCOMPLETE.
    //

    if (GetOverlappedResult(
            comHandle,
            &readOl,
            &numberActuallyRead,
            FALSE
            )) {

            FAILURE;

    }

    if (GetLastError() != ERROR_IO_INCOMPLETE) {

        FAILURE;

    }

    //
    // Do the write file and make sure that there is enough
    // time for the chars to make it.
    //

    if (!WriteFile(
             comHandle,
             &writeBuff[0],
             5,
             &numberActuallyWritten,
             &writeOl
             )) {

        if (GetLastError() != ERROR_IO_PENDING) {

            FAILURE;

        }

        if (!GetOverlappedResult(
                 comHandle,
                 &writeOl,
                 &numberActuallyWritten,
                 TRUE
                 )) {

            FAILURE;

        }

        if (numberActuallyWritten != 5) {

            FAILURE;

        }

    }

    //
    // Give some time for the chars to get there.
    //

    Sleep(100);

    //
    // Wait for no more than 1 second for the IO to complete
    //

    if (WaitForSingleObject(
            readOl.hEvent,
            1000
            ) != WAIT_OBJECT_0) {

        FAILURE;

    }

    //
    // Make sure we got everything we wrote
    //

    if (!GetOverlappedResult(
            comHandle,
            &readOl,
            &numberActuallyRead,
            FALSE
            )) {

        FAILURE;

    }

    if (numberActuallyRead != 1) {

        FAILURE;

    }
    startingTicks = GetTickCount();
    if (!ReadFile(
             comHandle,
             &readBuff[0],
             1000,
             &numberActuallyRead,
             &readOl
             )) {

        if (GetLastError() != ERROR_IO_PENDING) {

            FAILURE;

        }

        //
        // Give it at most a 1/2 second to finish for
        // the irp to complete immediately.
        //

        Sleep(500);
        if (!GetOverlappedResult(
                 comHandle,
                 &readOl,
                 &numberActuallyRead,
                 FALSE
                 )) {

            FAILURE;

        }

    }

    if ((GetTickCount() - startingTicks) > 1000) {

        FAILURE;

    }

    if (numberActuallyRead != 4) {

        FAILURE;

    }

    //
    // Do the third graphics wait test.
    //

    startingTicks = GetTickCount();
    if (ReadFile(
             comHandle,
             &readBuff[0],
             1000,
             &numberActuallyRead,
             &readOl
             )) {

        FAILURE;

    }

    if (GetLastError() != ERROR_IO_PENDING) {

        FAILURE;

    }

    //
    // Give it a second for the the read to complete
    //
    //

    Sleep(1000);

    //
    // Call the GetOverlapped and make sure that it returns
    // ERROR_IO_INCOMPLETE.
    //

    if (GetOverlappedResult(
            comHandle,
            &readOl,
            &numberActuallyRead,
            FALSE
            )) {

            FAILURE;

    }

    if (GetLastError() != ERROR_IO_INCOMPLETE) {

        FAILURE;

    }

    //
    // Wait for no more than 10 seconds for the IO to complete
    //

    if (WaitForSingleObject(
            readOl.hEvent,
            10000
            ) != WAIT_OBJECT_0) {

        FAILURE;

    }

    //
    // It shouldn't be more than 6 seconds for the Io to be done.
    //

    if ((GetTickCount() - startingTicks) > 6000) {

        FAILURE;

    }

    //
    // Make sure we got everything we wrote, which in this case is zero.
    //

    if (!GetOverlappedResult(
            comHandle,
            &readOl,
            &numberActuallyRead,
            FALSE
            )) {

        FAILURE;

    }

    if (numberActuallyRead) {

        FAILURE;

    }


    return 1;

}
Пример #2
0
/**
  * Opens the serial port
  * @param device Device name, eg. COM1 or /dev/ttyUSB0.
  * @param speed Baudrate for the device, eg. SERIAL_9600 etc.
  * @return serial_port object if success, 0 in case of failure.
  */
serial_port* serial_open(const char* device, int speed) {
    serial_port *port;

#ifdef LINUX
    // Open linux serial port
    int fd = open(device, O_RDWR|O_NOCTTY|O_NDELAY);
    struct termios tio;
    if(fd < 0) {
        print_linux_error();
        return 0;
    }

    // Select speed
    speed_t spd = 0;
    switch(speed) {
        case SERIAL_1200: spd = B1200; break;
        case SERIAL_2400: spd = B2400; break;
        case SERIAL_4800: spd = B4800; break;
        case SERIAL_9600: spd = B9600; break;
        case SERIAL_19200: spd = B19200; break;
        case SERIAL_38400: spd = B38400; break;
#ifdef B5600
        case SERIAL_56000:  spd = B56000;  break;
#endif
        case SERIAL_57600: spd = B57600; break;
        case SERIAL_115200: spd = B115200; break;
#ifdef B128000
        case SERIAL_128000:  spd = B128000;  break;
#endif
        case SERIAL_230400: spd = B230400; break;
#ifdef B256000
        case SERIAL_256000:  spd = B256000;  break;
#endif
        default:
            sprintf(error_str, "Speed not supported!");
            return 0;
    }

    // Get port attributes
    if(tcgetattr(fd, &tio) != 0) {
        print_linux_error();
        return 0;
    }

    // Set flags ...
    tio.c_cflag &= ~(PARENB|CSTOPB|CSIZE|CRTSCTS); // No flow control
    tio.c_cflag |= CS8|CREAD|CLOCAL; // 8bits, read on, ignore ctrl lines
    tio.c_lflag = 0;
    tio.c_iflag = IGNPAR;
    tio.c_oflag = 0;
    tio.c_cc[VMIN]  = 0;
    tio.c_cc[VTIME] = 0;

    // Attempt to set line speed for input & output
    if(cfsetispeed(&tio, spd) != 0) {
        print_linux_error();
        return 0;
    }
    if(cfsetospeed(&tio, spd) != 0) {
        print_linux_error();
        return 0;
    }

    // Attempt to set configuration
    if(tcsetattr(fd, TCSANOW, &tio) != 0) {
        print_linux_error();
        return 0;
    }
#else
    // Open windows serial port
    HANDLE wsid = CreateFile(device,
                             GENERIC_READ|GENERIC_WRITE,
                             0,
                             0,
                             OPEN_EXISTING,
                             FILE_ATTRIBUTE_NORMAL,
                             0);
    if(wsid == INVALID_HANDLE_VALUE) {
        print_windows_error();
        return 0;
    }

    // Get params
    DCB dcbSerialParams = {0};
    dcbSerialParams.DCBlength = sizeof(dcbSerialParams);
    if (!GetCommState(wsid, &dcbSerialParams)) {
        print_windows_error();
        return 0;
    }

    // Set new params. Remember to disable flow control etc.
    dcbSerialParams.ByteSize = 8;
    dcbSerialParams.StopBits = ONESTOPBIT;
    dcbSerialParams.Parity = NOPARITY;
    dcbSerialParams.fOutxCtsFlow = FALSE;
    dcbSerialParams.fOutxDsrFlow = FALSE;
    dcbSerialParams.fRtsControl = RTS_CONTROL_DISABLE;

    // Select speed
    switch(speed) {
        case SERIAL_1200: dcbSerialParams.BaudRate = CBR_1200; break;
        case SERIAL_2400: dcbSerialParams.BaudRate = CBR_2400; break;
        case SERIAL_4800: dcbSerialParams.BaudRate = CBR_4800; break;
        case SERIAL_9600: dcbSerialParams.BaudRate = CBR_9600; break;
        case SERIAL_14400: dcbSerialParams.BaudRate = CBR_14400; break;
        case SERIAL_19200: dcbSerialParams.BaudRate = CBR_19200; break;
        case SERIAL_38400: dcbSerialParams.BaudRate = CBR_38400; break;
        case SERIAL_56000: dcbSerialParams.BaudRate = CBR_56000; break;
        case SERIAL_57600: dcbSerialParams.BaudRate = CBR_57600; break;
        case SERIAL_115200: dcbSerialParams.BaudRate = CBR_115200; break;
        case SERIAL_128000: dcbSerialParams.BaudRate = CBR_128000; break;
        case SERIAL_256000: dcbSerialParams.BaudRate = CBR_256000; break;
        default:
            sprintf(error_str, "Speed not supported!");
            return 0;
    }

    // Set serial port settings
    if(!SetCommState(wsid, &dcbSerialParams)) {
        print_windows_error();
        return 0;
    }

    // Set serial port timeouts
    COMMTIMEOUTS timeouts;
    timeouts.ReadIntervalTimeout = MAXDWORD;
    timeouts.ReadTotalTimeoutMultiplier = 0;
    timeouts.ReadTotalTimeoutConstant = 0;
    timeouts.WriteTotalTimeoutMultiplier = 0;
    timeouts.WriteTotalTimeoutConstant = 0;

    // Set timeouts
    if(!SetCommTimeouts(wsid, &timeouts)) {
        print_windows_error();
        return 0;
    }
#endif

    // Reserve serial port stuff
    port = malloc(sizeof(serial_port));
#ifdef LINUX
    port->handle = fd;
#else
    port->handle = wsid;
#endif
    port->ok = 1;
    return port;
}
Пример #3
0
// --- функция открытия порта --------------------------------------------------
HANDLE MainWindow::OpenPort(QString PortName)
{
    HANDLE PortToOpen = CreateFileA
            (
                PortName.toAscii(),           // имя порта
                GENERIC_READ | GENERIC_WRITE, // можно читать и писать
                0,                            // ни с кем портом не делиться
                NULL,                         // потомкам хэндл не доступен
                OPEN_EXISTING,                // открыть существующий порт
                FILE_ATTRIBUTE_NORMAL,        // без атрибутов
                0
            );

    if(PortToOpen==INVALID_HANDLE_VALUE)
    {
        logstr = tr("] <font color=red>не удалось открыть порт</font>");
        string2log(logstr);
    } else
    {
        logstr = "[";
        currtime = currtime.currentTime();
        logstr.append(currtime.toString());
        logstr.append(tr("] порт <b>") + portstr + tr("</b> открыт"));
        ui->log->append(logstr);

        // очистка буферов порта
        if(!PurgeComm(PortToOpen, PURGE_RXABORT | PURGE_TXABORT | PURGE_RXCLEAR | PURGE_TXCLEAR))
        {
            logstr = tr("] <font color=red>не удалось очистить буферы порта</font>");
            string2log(logstr);
            CloseHandle(PortToOpen);
            return INVALID_HANDLE_VALUE;
        } else {
            logstr = tr("] буферы порта очищены");
            string2log(logstr);
               }

        // настройка параметров порта
        DCB dcb;
        BOOL PortState;
        dcb.DCBlength = sizeof(DCB);
        PortState = GetCommState(PortToOpen,&dcb);
        dcb.BaudRate=config->value("port/Baud_Rate", "2400").value<int>();
        dcb.ByteSize=config->value("port/DataBits", "8").value<int>();
        dcb.Parity=config->value("port/Parity", "0").value<int>();
        dcb.StopBits=config->value("port/StopBits", "1").value<int>();

        if(!SetCommState(PortToOpen,&dcb))
        {
            logstr = tr("] <font color=red>не удалось настроить порт</font>");
            string2log(logstr);
            CloseHandle(PortToOpen);
            return INVALID_HANDLE_VALUE;
        } else {
            logstr = tr("] порт настроен");
            string2log(logstr);
               }

        // установка таймаутов
        COMMTIMEOUTS CommTimeOuts;
        CommTimeOuts.ReadIntervalTimeout = 0xFFFFFFFF;
        CommTimeOuts.ReadTotalTimeoutMultiplier = 0;
        CommTimeOuts.ReadTotalTimeoutConstant = TIMEOUT;
        CommTimeOuts.WriteTotalTimeoutMultiplier = 0;
        CommTimeOuts.WriteTotalTimeoutConstant = TIMEOUT;
        if(!SetCommTimeouts(PortToOpen, &CommTimeOuts))
        {
            logstr = tr("] <font color=red>ошибка выставления таймаутов</font>");
            string2log(logstr);
            CloseHandle(PortToOpen);
            return INVALID_HANDLE_VALUE;
        }
        else {
            logstr = tr("] таймауты выставлены");
            string2log(logstr);
             }
    }
    return PortToOpen;
}
Пример #4
0
bool
Serial::open(QString &err)
{
#ifndef Q_OS_WIN32
    //
    // Linux and Mac OSX use stdio / termio / tcsetattr
    //
    assert(fd < 0);
    fd = ::open(path.toLatin1().constData(), O_RDWR | O_NOCTTY | O_NONBLOCK);
    if (fd < 0) {
        err = QString("open: ") + strerror(errno);
        return false;
    }
    struct termios tty;
    int flags = fcntl(fd, F_GETFL, 0);
    if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) {
        perror("fcntl");
        assert(0);
    }
    if (tcgetattr(fd, &tty) == -1) {
        perror("tcgetattr");
        assert(0);
    }
    tty.c_cflag &= ~CRTSCTS; /* no hardware flow control */
    tty.c_cflag &= ~(PARENB | PARODD); /* no parity */
    tty.c_cflag &= ~CSTOPB; /* 1 stop bit */
    tty.c_cflag &= ~CSIZE; /* clear size bits */
    tty.c_cflag |= CS8; /* 8 bits */
    tty.c_cflag |= CLOCAL | CREAD; /* ignore modem control lines */
    if (cfsetspeed(&tty, B9600) == -1) {
        perror("cfsetspeed");
        assert(0);
    }
    tty.c_iflag = IGNBRK; /* ignore BREAK condition on input */
    tty.c_lflag = 0;
    tty.c_oflag = 0;
    tty.c_cc[VMIN] = 1; /* all reads return at least one character */
    if (tcsetattr(fd, TCSANOW, &tty) == -1) {
        perror("tcsetattr");
        assert(0);
    }
    tcflush(fd, TCIOFLUSH); // clear out the garbage
    return true;
#else
Q_UNUSED(err);
    //
    // Windows uses CreateFile / DCB / SetCommState
    //

    DCB deviceSettings;    // serial port settings baud rate et al
    COMMTIMEOUTS timeouts; // timeout settings on serial ports

    // if deviceFilename references a port above COM9
    // then we need to open "\\.\COMX" not "COMX"
	QString portSpec = "\\\\.\\" + path;
    wchar_t deviceFilenameW[32]; // \\.\COM32 needs 9 characters, 32 should be enough?
    MultiByteToWideChar(CP_ACP, 0, portSpec.toLatin1(), -1, (LPWSTR)deviceFilenameW,
                    sizeof(deviceFilenameW));

    // win32 commport API
    fd = CreateFile (deviceFilenameW, GENERIC_READ|GENERIC_WRITE,
        FILE_SHARE_DELETE|FILE_SHARE_WRITE|FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);

    if (fd == INVALID_HANDLE_VALUE) return _isOpen = false;

    if (GetCommState (fd, &deviceSettings) == false) return _isOpen = false;

    // so we've opened the comm port lets set it up for
    deviceSettings.BaudRate = CBR_9600;
    deviceSettings.fParity = NOPARITY;
    deviceSettings.ByteSize = 8;
    deviceSettings.StopBits = ONESTOPBIT;
    deviceSettings.EofChar = 0x0;
    deviceSettings.ErrorChar = 0x0;
    deviceSettings.EvtChar = 0x0;
    deviceSettings.fBinary = TRUE;
    deviceSettings.fRtsControl = 0x0;
    deviceSettings.fOutxCtsFlow = FALSE;


    if (SetCommState(fd, &deviceSettings) == false) {
        CloseHandle(fd);
        return _isOpen = false;
    }

    timeouts.ReadIntervalTimeout = 0;
    timeouts.ReadTotalTimeoutConstant = 5000;
    timeouts.ReadTotalTimeoutMultiplier = 50;
    timeouts.WriteTotalTimeoutConstant = 5000;
    timeouts.WriteTotalTimeoutMultiplier = 0;
    SetCommTimeouts(fd, &timeouts);

    return _isOpen = true;
#endif
}
Пример #5
0
JNIEXPORT jboolean JNICALL Java_com_fazecast_jSerialComm_SerialPort_configTimeouts(JNIEnv *env, jobject obj, jlong serialPortFD)
{
	// Get port timeouts from Java class
	HANDLE serialPortHandle = (HANDLE)serialPortFD;
	if (serialPortHandle == INVALID_HANDLE_VALUE)
		return JNI_FALSE;
	COMMTIMEOUTS timeouts = {0};
	int timeoutMode = env->GetIntField(obj, timeoutModeField);
	DWORD readTimeout = (DWORD)env->GetIntField(obj, readTimeoutField);
	DWORD writeTimeout = (DWORD)env->GetIntField(obj, writeTimeoutField);

	// Set updated port timeouts
	timeouts.WriteTotalTimeoutMultiplier = 0;
	switch (timeoutMode)
	{
		case com_fazecast_jSerialComm_SerialPort_TIMEOUT_READ_SEMI_BLOCKING:		// Read Semi-blocking
			timeouts.ReadIntervalTimeout = MAXDWORD;
			timeouts.ReadTotalTimeoutMultiplier = MAXDWORD;
			timeouts.ReadTotalTimeoutConstant = readTimeout;
			timeouts.WriteTotalTimeoutConstant = writeTimeout;
			break;
		case (com_fazecast_jSerialComm_SerialPort_TIMEOUT_READ_SEMI_BLOCKING | com_fazecast_jSerialComm_SerialPort_TIMEOUT_WRITE_SEMI_BLOCKING):	// Read/Write Semi-blocking
			timeouts.ReadIntervalTimeout = MAXDWORD;
			timeouts.ReadTotalTimeoutMultiplier = MAXDWORD;
			timeouts.ReadTotalTimeoutConstant = readTimeout;
			timeouts.WriteTotalTimeoutConstant = writeTimeout;
			break;
		case (com_fazecast_jSerialComm_SerialPort_TIMEOUT_READ_SEMI_BLOCKING | com_fazecast_jSerialComm_SerialPort_TIMEOUT_WRITE_BLOCKING):		// Read Semi-blocking/Write Blocking
			timeouts.ReadIntervalTimeout = MAXDWORD;
			timeouts.ReadTotalTimeoutMultiplier = MAXDWORD;
			timeouts.ReadTotalTimeoutConstant = readTimeout;
			timeouts.WriteTotalTimeoutConstant = writeTimeout;
			break;
		case com_fazecast_jSerialComm_SerialPort_TIMEOUT_READ_BLOCKING:		// Read Blocking
			timeouts.ReadIntervalTimeout = 0;
			timeouts.ReadTotalTimeoutMultiplier = 0;
			timeouts.ReadTotalTimeoutConstant = readTimeout;
			timeouts.WriteTotalTimeoutConstant = writeTimeout;
			break;
		case (com_fazecast_jSerialComm_SerialPort_TIMEOUT_READ_BLOCKING | com_fazecast_jSerialComm_SerialPort_TIMEOUT_WRITE_SEMI_BLOCKING):	// Read Blocking/Write Semi-blocking
			timeouts.ReadIntervalTimeout = 0;
			timeouts.ReadTotalTimeoutMultiplier = 0;
			timeouts.ReadTotalTimeoutConstant = readTimeout;
			timeouts.WriteTotalTimeoutConstant = writeTimeout;
			break;
		case (com_fazecast_jSerialComm_SerialPort_TIMEOUT_READ_BLOCKING | com_fazecast_jSerialComm_SerialPort_TIMEOUT_WRITE_BLOCKING):		// Read/Write Blocking
			timeouts.ReadIntervalTimeout = 0;
			timeouts.ReadTotalTimeoutMultiplier = 0;
			timeouts.ReadTotalTimeoutConstant = readTimeout;
			timeouts.WriteTotalTimeoutConstant = writeTimeout;
			break;
		case com_fazecast_jSerialComm_SerialPort_TIMEOUT_SCANNER:			// Scanner Mode
			timeouts.ReadIntervalTimeout = MAXDWORD;
			timeouts.ReadTotalTimeoutMultiplier = MAXDWORD;
			timeouts.ReadTotalTimeoutConstant = 0x0FFFFFFF;
			timeouts.WriteTotalTimeoutConstant = 0;
			break;
		case com_fazecast_jSerialComm_SerialPort_TIMEOUT_NONBLOCKING:		// Non-blocking
		default:
			timeouts.ReadIntervalTimeout = MAXDWORD;
			timeouts.ReadTotalTimeoutMultiplier = 0;
			timeouts.ReadTotalTimeoutConstant = 0;
			timeouts.WriteTotalTimeoutConstant = 0;
			break;
	}

	// Apply changes
	return SetCommTimeouts(serialPortHandle, &timeouts);
}
bool WinSerialPort::connect(const char *portName, const int baudRate, const size_t inQueueSize, const size_t outQueueSize)
#endif
{
	hComPort_ = CreateFile(
		portName,
		GENERIC_READ | GENERIC_WRITE,
		0,    // exclusive access 
		NULL, // default security attributes 
		OPEN_EXISTING,
		FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED,
		NULL 
	);
	if (INVALID_HANDLE_VALUE == hComPort_)
	{
		// Handle the error. 
		std::cerr << "CreateFile failed with error, " << GetLastError() << ": Port:" << portName << ", BaudRate:" << baudRate << ", Parity:None, Stop bits:1" << std::endl;
		//::CloseHandle(hComPort_);
		return false;
	}

	// Set the event mask. 
	//if (!SetCommMask(hComPort_, EV_CTS | EV_DSR))
	if (!SetCommMask(hComPort_, EV_RXCHAR))
	{
		// Handle the error. 
		std::cerr << "SetCommMask failed with error: " << GetLastError() << std::endl;
		return false;
	}
	
	// set sizes of inqueue & outqueue
	SetupComm(hComPort_, (DWORD)inQueueSize, (DWORD)outQueueSize);	
	
	// purse port
	PurgeComm(hComPort_, PURGE_TXABORT | PURGE_TXCLEAR | PURGE_RXABORT | PURGE_RXCLEAR);
	
	// set timeouts
	COMMTIMEOUTS timeouts;
	timeouts.ReadIntervalTimeout = 0xFFFFFFFF;
	timeouts.ReadTotalTimeoutMultiplier = 0;
	timeouts.ReadTotalTimeoutConstant = 0;
	timeouts.WriteTotalTimeoutMultiplier = 2 * CBR_9600 / baudRate;
	timeouts.WriteTotalTimeoutConstant = 0;
	SetCommTimeouts(hComPort_, &timeouts);
	
	// set dcb
	DCB dcb;
	dcb.DCBlength = sizeof(DCB);
	GetCommState(hComPort_, &dcb);
	//dcb.fBinary = TRUE;  // Windows does not support nonbinary mode transfers, so this member must be TRUE
	dcb.BaudRate = baudRate;
	dcb.ByteSize = 8;
	dcb.Parity = NOPARITY;  // no parity
	dcb.StopBits = ONESTOPBIT;  // 1 stop bit
	//dcb.fInX = dcb.fOutX = TRUE;  // use Xon & Xoff
	//dcb.XonChar = SWL_SERIAL_PROTOCOL__ASCII_XON;
	//dcb.XoffChar = SWL_SERIAL_PROTOCOL__ASCII_XOFF;
	//dcb.XonLim = 100;
	//dcb.XoffLim = 100;
	if (!::SetCommState(hComPort_, &dcb))
	{
		std::cerr << "SetCommState failed with error: " << GetLastError() << std::endl;
		return false;
	}

	return true;
}
Пример #7
0
static void RS485_Configure_Status(
    void)
{
    DCB dcb = { 0 };
    COMMTIMEOUTS ctNew;


    dcb.DCBlength = sizeof(dcb);
    /* get current DCB settings */
    if (!GetCommState(RS485_Handle, &dcb)) {
        fprintf(stderr, "Unable to get status from %s\n", RS485_Port_Name);
        RS485_Print_Error();
        exit(1);
    }

    /* update DCB rate, byte size, parity, and stop bits size */
    dcb.BaudRate = RS485_Baud;
    dcb.ByteSize = (unsigned char) RS485_ByteSize;
    dcb.Parity = (unsigned char) RS485_Parity;
    dcb.StopBits = (unsigned char) RS485_StopBits;

    /* update flow control settings */
    dcb.fDtrControl = RS485_DTRControl;
    dcb.fRtsControl = RS485_RTSControl;
    /*
       dcb.fOutxCtsFlow    = CTSOUTFLOW(TTYInfo);
       dcb.fOutxDsrFlow    = DSROUTFLOW(TTYInfo);
       dcb.fDsrSensitivity = DSRINFLOW(TTYInfo);
       dcb.fOutX           = XONXOFFOUTFLOW(TTYInfo);
       dcb.fInX            = XONXOFFINFLOW(TTYInfo);
       dcb.fTXContinueOnXoff = TXAFTERXOFFSENT(TTYInfo);
       dcb.XonChar         = XONCHAR(TTYInfo);
       dcb.XoffChar        = XOFFCHAR(TTYInfo);
       dcb.XonLim          = XONLIMIT(TTYInfo);
       dcb.XoffLim         = XOFFLIMIT(TTYInfo);
       // DCB settings not in the user's control
       dcb.fParity = TRUE;
     */
    if (!SetCommState(RS485_Handle, &dcb)) {
        fprintf(stderr, "Unable to set status on %s\n", RS485_Port_Name);
        RS485_Print_Error();
    }
    /* configure the COM port timeout values */
    ctNew.ReadIntervalTimeout = MAXDWORD;
    ctNew.ReadTotalTimeoutMultiplier = MAXDWORD;
    ctNew.ReadTotalTimeoutConstant = 1000;
    ctNew.WriteTotalTimeoutMultiplier = 0;
    ctNew.WriteTotalTimeoutConstant = 0;
    if (!SetCommTimeouts(RS485_Handle, &ctNew)) {
        RS485_Print_Error();
    }
    /* Get rid of any stray characters */
    if (!PurgeComm(RS485_Handle, PURGE_TXABORT | PURGE_RXABORT)) {
        fprintf(stderr, "Unable to purge %s\n", RS485_Port_Name);
        RS485_Print_Error();
    }
    /* Set the Comm buffer size */
    SetupComm(RS485_Handle, MAX_MPDU, MAX_MPDU);
    /* raise DTR */
    if (!EscapeCommFunction(RS485_Handle, SETDTR)) {
        fprintf(stderr, "Unable to set DTR on %s\n", RS485_Port_Name);
        RS485_Print_Error();
    }
}
Пример #8
0
void inicializar(){

    // Handle to the Serial port
	LPCSTR  ComPortName = "COM4";  // Name of the Serial port(May Change) to be opened,
	BOOL  Status;                          // Status of the various operations
    // Bytes read by ReadFile()
	int i = 0;

	hComm = CreateFile( ComPortName,                  // Name of the Port to be Opened
                        GENERIC_READ | GENERIC_WRITE, // Read/Write Access
						0,                            // No Sharing, ports cant be shared
						NULL,                         // No Security
					    OPEN_EXISTING,                // Open existing port only
                         FILE_ATTRIBUTE_NORMAL,                            // Non Overlapped I/O
                        NULL);                        // Null for Comm Devices

	if (hComm == INVALID_HANDLE_VALUE)
		printf("\n    Error! - Port %s can't be opened\n", ComPortName);
	else
		printf("Port opened\n");//std::wcout <<"\n    Port " << ComPortName << " Opened\n ";

	/*------------------------------- Setting the Parameters for the SerialPort ------------------------------*/

	DCB dcbSerialParams = { 0 };                         // Initializing DCB structure
	dcbSerialParams.DCBlength = sizeof(dcbSerialParams);

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

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

	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

	Status = SetCommState(hComm, &dcbSerialParams);  //Configuring the port according to settings in DCB

	if (Status == FALSE)
		{
			printf("\n    Error! in Setting DCB Structure");
		}
	else //If Successfull display the contents of the DCB Structure
		{
			printf("\n\n    Setting DCB Structure Successfull\n");
			printf("\n       Baudrate = %d", dcbSerialParams.BaudRate);
			printf("\n       ByteSize = %d", dcbSerialParams.ByteSize);
			printf("\n       StopBits = %d", dcbSerialParams.StopBits);
			printf("\n       Parity   = %d", 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\n    Error! in Setting Time Outs");
	else
		printf("\n\n    Setting Serial Port Timeouts Successfull");

	/*------------------------------------ Setting Receive Mask ----------------------------------------------*/

	Status = SetCommMask(hComm, EV_RXCHAR); //Configure Windows to Monitor the serial device for Character Reception

	if (Status == FALSE)
		printf("\n\n    Error! in Setting CommMask");
	else
		printf("\n\n    Setting CommMask successfull");
}
Пример #9
0
RS232::RS232(char *Port,char *Parite,int Vitesse,int Data,char *StopBit,int TimeOut)
{
    mutex.lock();

    taille_donnee = 20;

    DWORD dwError;					// n° de l'erreur
    BOOL flag_etat;					// tout c'est bien passé
    wchar_t *pwc      = (wchar_t *)malloc( sizeof( wchar_t ));

/*--------------------------------------------------------*/
/*                 Ouverture du port de Com               */
/*--------------------------------------------------------*/

mbstowcs(pwc, Port, 5 );

        port_handle = CreateFile(
                pwc,                         	// Choix du port « COM »
                GENERIC_READ | GENERIC_WRITE, 	// accès pour lire et écrire sur le port
                0,                            	// accès exclusif au port de COM
                NULL,                         	// sécurité par défaut
                OPEN_EXISTING,                	// Doit être à cette valeur car se n'est pas un fichier
                0,              		// mode asynchrone
                NULL);

/*-----------------------------------------------------------*/
/*         Vérifier si handle ouvert correctement            */
/*-----------------------------------------------------------*/
        if (port_handle == INVALID_HANDLE_VALUE)
                {
                        dwError = GetLastError();
                        /* Fichier non créer gérer l'erreur */
                }

/*-----------------------------------------------------------*/
/* Lecture Configuration initiale                            */
/*-----------------------------------------------------------*/
        creation_ok = GetCommState(port_handle, &configuration);

/*-------------------------------------------------------------------*/
/* 					Configuration du port                            */
/*-------------------------------------------------------------------*/

// Gestion de la vitesse
        configuration.BaudRate = Vitesse;

// Gestion du nombre de bits
        configuration.ByteSize = Data;

// Gestion de la parité
        if (strcmp(Parite,"Aucune")==0)
                configuration.Parity = NOPARITY;

        if (strcmp(Parite,"Paire")==0)
                configuration.Parity = EVENPARITY;

        if (strcmp(Parite,"Impaire")==0)
                configuration.Parity = ODDPARITY;

// Gestion du Stop Bit
        if (strcmp(StopBit,"2")==0)
                configuration.StopBits = TWOSTOPBITS;

        else if (strcmp(StopBit,"1.5")==0)
                configuration.StopBits = ONE5STOPBITS;

        else
                configuration.StopBits = ONESTOPBIT;

// configuration.configurationlength;

        configuration.fBinary = 1;
        configuration.fParity = 0;
        configuration.fOutxCtsFlow = 0;
        configuration.fOutxDsrFlow = 0;
        configuration.fDtrControl = 0;
        configuration.fDsrSensitivity = 0;
        configuration.fTXContinueOnXoff = 0;
        configuration.fRtsControl = 0;

 /*----------------------------------*/
 /*    Définition des timeouts       */
 /*----------------------------------*/

        temps_attente.ReadIntervalTimeout = MAXWORD;
        temps_attente.ReadTotalTimeoutMultiplier = 0;
        temps_attente.ReadTotalTimeoutConstant = TimeOut; // pas de time out = 0
        temps_attente.WriteTotalTimeoutMultiplier = 0;
        temps_attente.WriteTotalTimeoutConstant = 0;

// configurer le timeout

        SetCommTimeouts(port_handle,&temps_attente);

/*-----------------------------------------------*/
/* Configurer le port	                          */
/*-----------------------------------------------*/
        flag_etat = SetCommState(port_handle, &configuration);

        mutex.unlock();
}
Пример #10
0
bool ClsSerial::API_Open(UINT uiComPort, DCB &r_Dcb)
{
	DWORD dwError = 0;
	CString cstrPort;

    if( uiComPort >= 10)
		cstrPort.Format( _T("\\\\.\\COM%d"), uiComPort);
	else
		cstrPort.Format( _T("COM%d"), uiComPort);

    m_hdlCom =CreateFile( cstrPort,
                          GENERIC_READ | GENERIC_WRITE,  
						  //0,  
						  FILE_SHARE_READ | FILE_SHARE_WRITE,  
						  NULL, 
						  OPEN_EXISTING, 
						  FILE_FLAG_OVERLAPPED,
						  NULL);

	m_hdlRdEvent	   = CreateEvent(NULL, FALSE, FALSE, NULL);
	m_hdlWtEvent	   = CreateEvent(NULL, FALSE, FALSE, NULL);
	m_OverlapRd.hEvent = m_hdlRdEvent;
	m_OverlapWt.hEvent = m_hdlWtEvent;


    if ( m_hdlCom     == INVALID_HANDLE_VALUE ||
		 m_hdlRdEvent == INVALID_HANDLE_VALUE ||
		 m_hdlWtEvent == INVALID_HANDLE_VALUE	)
    {
        return false;
    }


    if (!ClearCommError(m_hdlCom, &dwError, &m_COMSTAT))
    {
        return false;
    }


    if (!PurgeComm(m_hdlCom, PURGE_RXCLEAR | PURGE_TXCLEAR))
    {
        return false;
    }


	//Set Configuration
    if (!GetCommState(m_hdlCom, &m_DCB))
    {
        return false;
    }

    m_DCB.BaudRate = r_Dcb.BaudRate;
    m_DCB.ByteSize = r_Dcb.ByteSize;
    m_DCB.Parity   = r_Dcb.Parity;
    m_DCB.StopBits = r_Dcb.StopBits;

    if (!SetCommState(m_hdlCom, &m_DCB))
    {
        return false;
    }


	//Set Buffer
    if (!SetupComm(m_hdlCom, 1024, 1024))
    {
        return false;
    }


	//Set Timeout
	COMMTIMEOUTS time_out;
	time_out.ReadIntervalTimeout         = MAXDWORD;
	time_out.ReadTotalTimeoutConstant    = 500;
	time_out.ReadTotalTimeoutMultiplier  = 20;
	time_out.WriteTotalTimeoutConstant   = 500;
	time_out.WriteTotalTimeoutMultiplier = 20;

	if( !SetCommTimeouts(m_hdlCom,&time_out) )
    {
        return false;
    }
	
	return true;
}
Пример #11
0
bool SerialPortBase::OpenPort(UnicodeString strCommName,int baud,int stopBits,int parity)
{
	// 打开串口
	HANDLE hdl = CreateFile(strCommName.c_str(),
							GENERIC_READ|GENERIC_WRITE,
							0,
							NULL,
							OPEN_EXISTING,
							FILE_FLAG_OVERLAPPED | FILE_ATTRIBUTE_NORMAL, //正常模式.非异步.
							NULL
							);

	if (hdl == INVALID_HANDLE_VALUE)
	{
		//打开异常.
		return false;
	}

	this->m_hSerialPort = hdl;

	// 读取串口设置.
	if (GetCommState(hdl,&m_stSettings) == false)
	{
		CloseHandle(hdl);
		return false;
	}

	// 修改设置.
	m_stSettings.BaudRate = baud;//this->m_iBardRate;
	m_stSettings.fParity  = parity;//this->m_iParityMode;
	m_stSettings.StopBits = stopBits;//this->m_iStopBits;
	m_stSettings.ByteSize = 8;

	if (SetCommState(hdl,&m_stSettings) == false)
	{
		CloseHandle(hdl);
		return false;
	}

	// 超时设置.
	if (GetCommTimeouts(hdl,&m_stTimeout) == false)
	{
		CloseHandle(hdl);
		return false;
	}

	// 事件设置.
	if(SetCommMask(hdl,EV_RXCHAR | EV_ERR | EV_CTS | EV_DSR | EV_BREAK | EV_TXEMPTY | EV_RING | EV_RLSD)==false)//监控接收事件.
    {
		CloseHandle(hdl);
		return false;
    }

	//m_stTimeout.ReadTotalTimeoutConstant = 100;
	//m_stTimeout.ReadTotalTimeoutMultiplier = 1;
	m_stTimeout.ReadIntervalTimeout = 50; // 字符间超时.设置位100ms,若100ms内无数据则认为无法读取数据.

	if (SetCommTimeouts(hdl,&m_stTimeout) == false )
	{
		CloseHandle(hdl);
		return false;
	}
	// 完成设置.
	// 清空缓冲区.
	PurgeComm(hdl,PURGE_TXABORT | PURGE_RXABORT |PURGE_TXCLEAR |PURGE_RXCLEAR );

	if (ovl.hEvent != NULL)
	{
		ResetEvent(ovl.hEvent);
	}
	else
	{
        ovl.hEvent = CreateEvent(NULL,TRUE,FALSE,NULL);
	}

	if (ovr.hEvent != NULL)
	{
		ResetEvent(ovr.hEvent);
	}
	else
	{
        ovr.hEvent = CreateEvent(NULL,TRUE,FALSE,NULL);
	}

	if (ovw.hEvent != NULL)
	{
		ResetEvent(ovw.hEvent);
	}
	else
	{
        ovw.hEvent = CreateEvent(NULL,TRUE,FALSE,NULL);
	}

	this->m_bPortOpen = true;
	//pthread->m_bTerminated = false;
	//this->pthread->Started

    pthread->ThreadResume();

	return true;
}
Пример #12
0
/*-------------------------------------------------------------------------
 Open a comm port and get ready for I/O
 Call with a pointer to an uninitizlized serio_t.
 If you call this, don't call serio_open_handle().
-------------------------------------------------------------------------*/
serio_res_t serio_open(serio_t *serio, long baud, const char *portname)
{
	COMMTIMEOUTS	CommTimeOuts ;
	DCB				dcb ;
	SECURITY_ATTRIBUTES SecurityAttributes;
	HANDLE h;

	/*--- Set up Win32 stuff ---*/

	if		(baud <= CBR_9600)	baud = CBR_9600;
	else if (baud <= CBR_19200)	baud = CBR_19200;
	else if (baud <= CBR_38400)	baud = CBR_38400;
	else						baud = CBR_57600;

	/* Let child processes inherit this handle. */
	memset(&SecurityAttributes, 0, sizeof(SECURITY_ATTRIBUTES));
	SecurityAttributes.nLength =				sizeof( SECURITY_ATTRIBUTES );
	SecurityAttributes.lpSecurityDescriptor =	NULL;
	SecurityAttributes.bInheritHandle =			TRUE;

	h = CreateFile(portname, GENERIC_READ | GENERIC_WRITE,
		0,                    // exclusive access
		&SecurityAttributes,
		OPEN_EXISTING,
		FILE_ATTRIBUTE_NORMAL
#ifdef USE_OVERLAP
		| FILE_FLAG_OVERLAPPED // overlapped I/O
#endif
		, NULL);

	if (INVALID_HANDLE_VALUE == h) {
		DPRINT(("serio_open: CreateFile(%s...) failed\n", portname));
		return serio_RES_BAD;
	}

	// Set the size of the input and output buffer.
	if (!SetupComm( h, 4096, 0 )) {
		DPRINT(("serio_open: SetupComm failed\n"));
		return serio_RES_BUG;
	}

	// purge any information in the buffer
	if (!PurgeComm( h, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR)) {
		DPRINT(("serio_open: PurgeComm failed\n"));
		return serio_RES_BUG;
	}

	// set the time-out parameters for all read and write operations
#if 1
	// Cause ReadFile to never wait.
	// Works OK in Win95.
	CommTimeOuts.ReadIntervalTimeout = MAXDWORD ;
	CommTimeOuts.ReadTotalTimeoutMultiplier = 0 ;
	CommTimeOuts.ReadTotalTimeoutConstant = 0 ;
#elif 0
	// Cause ReadFile to wait 50 milliseconds, then time out unconditionally.
	// Fails sometimes in Win95; the overlapped read *never* completes.
	CommTimeOuts.ReadIntervalTimeout = 0 ;
	CommTimeOuts.ReadTotalTimeoutMultiplier = 0 ;
	CommTimeOuts.ReadTotalTimeoutConstant = 50 ;
#elif 0
	// Cause ReadFile to wait 100 milliseconds for traffic to start, but
	// wait only 10 milliseconds for traffic to resume if it goes silent
	// after starting.
	// Fails sometimes in Win95; the overlapped read *never* completes.
	CommTimeOuts.ReadIntervalTimeout = 10 ;
	CommTimeOuts.ReadTotalTimeoutMultiplier = 0 ;
	CommTimeOuts.ReadTotalTimeoutConstant = 100 ;
#endif
	CommTimeOuts.WriteTotalTimeoutMultiplier = 0 ;
	CommTimeOuts.WriteTotalTimeoutConstant = 1000 ;	/* will writes timeout? */

	if (!SetCommTimeouts( h, &CommTimeOuts )) {
		DPRINT(("serio_open: SetCommTimeouts failed\n"));
		return serio_RES_BUG;
	}

	dcb.DCBlength = sizeof( DCB ) ;

	if (!GetCommState( h, &dcb)) {
		DPRINT(("serio_open: GetCommState failed\n"));
		return serio_RES_BUG;
	}

	dcb.BaudRate = baud;
	dcb.Parity = FALSE ;
	dcb.fBinary = TRUE ;
	dcb.fOutxCtsFlow = FALSE ;
	dcb.fOutxDsrFlow = FALSE ;
	dcb.Parity = NOPARITY ;
	dcb.ByteSize = 8 ;
	dcb.StopBits = ONESTOPBIT ;

	if (!SetCommState( h, &dcb)) {
		DPRINT(("serio_open: SetCommState failed\n"));
		return serio_RES_BUG;
	}

	return serio_open_handle(serio, h);
}
Пример #13
0
JNIEXPORT jlong JNICALL FUNC(open0)(JNIEnv *env, jobject jobj, jstring portName, jint baudRate, jint byteSize, jint parity, jint stopBits)
{
	const wchar_t * cportName = (const wchar_t *)env->GetStringChars(portName, NULL);
	HANDLE handle = CreateFile(cportName,
		GENERIC_READ | GENERIC_WRITE,
		0,
		NULL,
		OPEN_EXISTING,
		FILE_FLAG_OVERLAPPED,
		NULL);

	if (handle == INVALID_HANDLE_VALUE) {
		throwIOException(env, "Error opening serial port");
		return -1;
	}
	
	DCB dcb = { 0 };

	if (!GetCommState(handle, &dcb)) {
		throwIOException(env, "Error getting DCB");
		return -1;
	}

	dcb.BaudRate = baudRate;
	dcb.ByteSize = (BYTE)byteSize;

	switch (parity) {
	case 0: // None
		dcb.fParity = FALSE;
		break;
	case 1: // Even
		dcb.fParity = TRUE;
		dcb.Parity = EVENPARITY;
		break;
	case 2: // Odd
		dcb.fParity = TRUE;
		dcb.Parity = ODDPARITY;
		break;
	}

	switch (stopBits) {
	case 0:
		dcb.StopBits = ONESTOPBIT;
		break;
	case 1:
		dcb.StopBits = TWOSTOPBITS;
		break;
	}

	if (!SetCommState(handle, &dcb)) {
		throwIOException(env, "Error setting DCB");
		return -1;
	}

	COMMTIMEOUTS timeouts = { 0 };
	timeouts.ReadIntervalTimeout = MAXDWORD;
	timeouts.ReadTotalTimeoutMultiplier = MAXDWORD;
	timeouts.ReadTotalTimeoutConstant = 200;
	if (!SetCommTimeouts(handle, &timeouts)) {
		throwIOException(env, "Error setting timeouts");
		return -1;
	}

	return (jlong)handle;
}
Пример #14
0
int OpenComport(int comport_number, int baudrate)
{
  if((comport_number>15)||(comport_number<0))
  {
    printf("illegal comport number\n");
    return(1);
  }

  switch(baudrate)
  {
    case     110 : strcpy(baudr, "baud=110 data=8 parity=N stop=1");
                   break;
    case     300 : strcpy(baudr, "baud=300 data=8 parity=N stop=1");
                   break;
    case     600 : strcpy(baudr, "baud=600 data=8 parity=N stop=1");
                   break;
    case    1200 : strcpy(baudr, "baud=1200 data=8 parity=N stop=1");
                   break;
    case    2400 : strcpy(baudr, "baud=2400 data=8 parity=N stop=1");
                   break;
    case    4800 : strcpy(baudr, "baud=4800 data=8 parity=N stop=1");
                   break;
    case    9600 : strcpy(baudr, "baud=9600 data=8 parity=N stop=1");
                   break;
    case   19200 : strcpy(baudr, "baud=19200 data=8 parity=N stop=1");
                   break;
    case   38400 : strcpy(baudr, "baud=38400 data=8 parity=N stop=1");
                   break;
    case   57600 : strcpy(baudr, "baud=57600 data=8 parity=N stop=1");
                   break;
    case  115200 : strcpy(baudr, "baud=115200 data=8 parity=N stop=1");
                   break;
    case  128000 : strcpy(baudr, "baud=128000 data=8 parity=N stop=1");
                   break;
    case  256000 : strcpy(baudr, "baud=256000 data=8 parity=N stop=1");
                   break;
    default      : printf("invalid baudrate\n");
                   return(1);
                   break;
  }

  Cport[comport_number] = CreateFileA(comports[comport_number],
                      GENERIC_READ|GENERIC_WRITE,
                      0,                          /* no share  */
                      NULL,                       /* no security */
                      OPEN_EXISTING,
                      0,                          /* no threads */
                      NULL);                      /* no templates */

  if(Cport[comport_number]==INVALID_HANDLE_VALUE)
  {
    printf("unable to open comport\n");
    return(1);
  }

  DCB port_settings;
  memset(&port_settings, 0, sizeof(port_settings));  /* clear the new struct  */
  port_settings.DCBlength = sizeof(port_settings);

  if(!BuildCommDCBA(baudr, &port_settings))
  {
    printf("unable to set comport dcb settings\n");
    CloseHandle(Cport[comport_number]);
    return(1);
  }

  if(!SetCommState(Cport[comport_number], &port_settings))
  {
    printf("unable to set comport cfg settings\n");
    CloseHandle(Cport[comport_number]);
    return(1);
  }

  COMMTIMEOUTS Cptimeouts;

  Cptimeouts.ReadIntervalTimeout         = MAXDWORD;
  Cptimeouts.ReadTotalTimeoutMultiplier  = 0;
  Cptimeouts.ReadTotalTimeoutConstant    = 0;
  Cptimeouts.WriteTotalTimeoutMultiplier = 0;
  Cptimeouts.WriteTotalTimeoutConstant   = 0;

  if(!SetCommTimeouts(Cport[comport_number], &Cptimeouts))
  {
    printf("unable to set comport time-out settings\n");
    CloseHandle(Cport[comport_number]);
    return(1);
  }

  return(0);
}
Пример #15
0
HANDLE SerialInit(char *ComPortName, DWORD BaudRate, int ByteSize, int StopBit, char ParityChar, char Protocol, int RxTimeOut, int TxTimeOut, int RxBufSize, int TxBufSize) 
{
	HANDLE			hCom;
	BOOL			bPortReady;
	DCB				dcb;
	COMMTIMEOUTS	CommTimeouts;
	int				Parity;

	switch(ParityChar) {
		case 'N':
		case 'n':
			Parity = NOPARITY;
			break;
		case 'E':
		case 'e':
			Parity = EVENPARITY;
			break;
		case 'O':
		case 'o':
			Parity = ODDPARITY;
			break;
		default:
			return NULL;	// illegal parameter !
	}
	
	switch(StopBit)
	{
		case 1:
			StopBit = ONESTOPBIT;
			break;
		case 2:
			StopBit = TWOSTOPBITS;
			break;
		default:
			return NULL;	// illegal parameter !
	}

	hCom = CreateFile(	ComPortName, 
						GENERIC_READ | GENERIC_WRITE,
						0, // exclusive access
						NULL, // no security
						OPEN_EXISTING,
						0, // no overlapped I/O
						NULL); // null template 

	if(hCom == INVALID_HANDLE_VALUE) return NULL;

	bPortReady = SetupComm(hCom, RxBufSize, TxBufSize); // set Rx and Tx buffer sizes

	// Port settings are specified in a Data Communication Block (DCB). 

	bPortReady = GetCommState(hCom, &dcb);

	dcb.BaudRate	= BaudRate;
	dcb.ByteSize	= ByteSize;
	dcb.Parity		= Parity;
	dcb.StopBits	= StopBit;
	dcb.fAbortOnError = TRUE;

	switch(Protocol) {
	case 'D':	// DTR/DSR
	case 'd':
		// set XON/XOFF
		dcb.fOutX	= FALSE;
		dcb.fInX	= FALSE;
		// set RTSCTS
		dcb.fOutxCtsFlow = FALSE;
		dcb.fRtsControl = RTS_CONTROL_DISABLE; 
		// set DSRDTR
		dcb.fOutxDsrFlow = TRUE;
		dcb.fDtrControl = DTR_CONTROL_HANDSHAKE; 
		break;
	case 'R':	// RTS/CTS
	case 'r':
		// set XON/XOFF
		dcb.fOutX	= FALSE;
		dcb.fInX	= FALSE;
		// set RTSCTS
		dcb.fOutxCtsFlow = TRUE;
		dcb.fRtsControl = RTS_CONTROL_HANDSHAKE; 
		// set DSRDTR
		dcb.fOutxDsrFlow = FALSE;
		dcb.fDtrControl = DTR_CONTROL_DISABLE; 
		break;
	case 'X':	// XON/XOFF
	case 'x':
		// set XON/XOFF
		dcb.fOutX	= TRUE;
		dcb.fInX	= TRUE;
		dcb.fTXContinueOnXoff = TRUE;
		dcb.XoffChar = ASCII_XOFF;
		dcb.XoffLim = RxBufSize - (RxBufSize / 4);
		dcb.XonChar = ASCII_XON;
		dcb.XonLim = RxBufSize - (RxBufSize / 2);
		// set RTSCTS
		dcb.fOutxCtsFlow = FALSE;
		dcb.fRtsControl = RTS_CONTROL_DISABLE; 
		// set DSRDTR
		dcb.fOutxDsrFlow = FALSE;
		dcb.fDtrControl = DTR_CONTROL_DISABLE;
		break;
	case 'N':	// NOPROTOCOL
	case 'n':
	default:
		// set XON/XOFF
		dcb.fOutX	= FALSE;
		dcb.fInX	= FALSE;
		// set RTSCTS
		dcb.fOutxCtsFlow = FALSE;
		dcb.fRtsControl = RTS_CONTROL_DISABLE; 
		// set DSRDTR
		dcb.fOutxDsrFlow = FALSE;
		dcb.fDtrControl = DTR_CONTROL_DISABLE; 
		break;
	}

	bPortReady = SetCommState(hCom, &dcb);

	// Set timeouts
	CommTimeouts.ReadIntervalTimeout = RxTimeOut;
	CommTimeouts.ReadTotalTimeoutMultiplier = 0;
	CommTimeouts.ReadTotalTimeoutConstant = RxTimeOut;

	CommTimeouts.WriteTotalTimeoutMultiplier = 0;
	CommTimeouts.WriteTotalTimeoutConstant = TxTimeOut;

	bPortReady = SetCommTimeouts(hCom, &CommTimeouts);

	return hCom;
}
Пример #16
0
int _CRTAPI1 main(int argc,char *argv[]) {

    char *MyPort = "COM1";
    DWORD ValueFromEscape = 0;
    DWORD CharFunc;
    DWORD ThreadId;
    DWORD ReadThreadId;
    HANDLE ReadHandle;
    int scanfval;

    if (argc > 1) {

        MyPort = argv[1];

    }

    WaitEvent = CreateEvent(
                    NULL,
                    TRUE,
                    FALSE,
                    NULL
                    );

    if (!WaitEvent) {

        printf("Wait Event could not be created\n");
        exit(1);

    }

    ReadEvent = CreateEvent(
                    NULL,
                    TRUE,
                    FALSE,
                    NULL
                    );

    if (!ReadEvent) {

        printf("Read Event could not be created\n");
        exit(1);

    }

    IoSemaphore = CreateSemaphore(
                      NULL,
                      1,
                      1,
                      NULL
                      );

    if (!IoSemaphore) {

        printf("IoSemaphore could not be created\n");
        exit(1);

    }

    if ((hFile = CreateFile(
                     MyPort,
                     GENERIC_READ | GENERIC_WRITE,
                     0,
                     NULL,
                     CREATE_ALWAYS,
                     FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED,
                     NULL
                     )) != ((HANDLE)-1)) {

        DCB MyDcb;
        COMMTIMEOUTS NewTimeouts;

        printf("We successfully opened the %s port.\n",MyPort);


        //
        // We've successfully opened the file.  Set the state of
        // the comm device.  First we get the old values and
        // adjust to our own.
        //

        if (!GetCommState(
                 hFile,
                 &MyDcb
                 )) {

            printf("Couldn't get the comm state: %d\n",GetLastError());
            exit(1);

        }

        MyDcb.BaudRate = 19200;
        MyDcb.ByteSize = 8;
        MyDcb.Parity = NOPARITY;
        MyDcb.StopBits = ONESTOPBIT;
        MyDcb.EvtChar = 'a';

        if (!SetCommState(
                hFile,
                &MyDcb
                )) {

            printf("Couldn't set the comm state: %d\n",GetLastError());
            exit(1);

        }

        if (!SetCommTimeouts(
                 hFile,
                 &NewTimeouts
                 )) {

            printf("Couldn't set the comm timeouts: %d\n",GetLastError());
            exit(1);

        }

    } else {

        printf("Could not open the comm port: %d\n",GetLastError());

    }

    //
    // Create the thread that will wait for the
    // comm events.
    //

    if (!CreateThread(
              NULL,
              0,
              WaitCommThread,
              NULL,
              0,
              &ThreadId
              )) {

        printf("Could not create the wait thread.\n");
        exit(1);

    }

    if (!CreateThread(
              NULL,
              0,
              SetMaskThread,
              NULL,
              0,
              &ThreadId
              )) {

        printf("Could not create the set mask thread.\n");
        exit(1);

    }

    if ((ReadHandle = CreateThread(
                          NULL,
                          0,
                          ReadThread,
                          NULL,
                          0,
                          &ThreadId
                          )) == 0) {

        printf("Could not create the read thread.\n");
        exit(1);

    }

    WaitForSingleObject(ReadHandle,-1);

}
Пример #17
0
//............................................................................
bool comOpen(char const *comName, int baudRate) {
    DCB dcb = {0};
    char comSettings[120];

    l_com = 0;
    sprintf(comSettings,
            COM_SETTINGS,
            baudRate);

    l_com = CreateFile(comName,
                         GENERIC_READ | GENERIC_WRITE,
                         0,                                // exclusive access
                         NULL,                            // no security attrs
                         OPEN_EXISTING,
                         0,                   // standard (not-overlapped) I/O
                         NULL);

    if (l_com == INVALID_HANDLE_VALUE) {
        printf("Error by opening the COM port: %s at the baud rate %d\n",
               comName, baudRate);
        return false;
    }

    dcb.DCBlength = sizeof(DCB);
    if (!GetCommState(l_com, &dcb)) {
        printf("Error by retreiving port settings\n");
        return (HANDLE)0;
    }

    dcb.fAbortOnError = 0;                             // don't abort on error
    // Fill in the DCB
    if (!BuildCommDCB(comSettings, &dcb)) {
        printf("Error by parsing command line parameters\n");
        return false;
    }

    if (!SetCommState(l_com, &dcb)) {
        printf("Error setting up the port\n");
        return false;
    }

    SetupComm(l_com, BUF_SIZE, BUF_SIZE);        // setup the device buffers

    // purge any information in the buffers
    PurgeComm(l_com, PURGE_TXABORT | PURGE_RXABORT |
                     PURGE_TXCLEAR | PURGE_RXCLEAR);

    // the timeouts for the serial communication are set accorging to the
    // following remark from the Win32 help documentation:
    //
    // If an application sets ReadIntervalTimeout and
    // ReadTotalTimeoutMultiplier to MAXDWORD and sets
    // ReadTotalTimeoutConstant to a value greater than zero and less than
    // MAXDWORD, one of the following occurs when the ReadFile function
    // is called:
    // 1. If there are any characters in the input buffer, ReadFile
    // returns immediately with the characters in the buffer.
    // 2. If there are no characters in the input buffer, ReadFile waits
    // until a character arrives and then returns immediately.
    // 3. If no character arrives within the time specified by
    // ReadTotalTimeoutConstant, ReadFile times out.
    //
    l_timeouts.ReadIntervalTimeout = MAXDWORD;
    l_timeouts.ReadTotalTimeoutMultiplier = MAXDWORD;
    l_timeouts.ReadTotalTimeoutConstant = 50;
    l_timeouts.WriteTotalTimeoutMultiplier = 0;
    l_timeouts.WriteTotalTimeoutConstant = 50;
    SetCommTimeouts(l_com, &l_timeouts);

    return true;                                                    // success
}
Пример #18
0
/* Function: rtIOStreamOpen =================================================
 * Abstract:
 *  Open the connection with the target.
 */
int rtIOStreamOpen(int argc, void * argv[])
{
    unsigned int        comNum     = 0;
    int result = RTIOSTREAM_NO_ERROR;
    int streamID;
    HANDLE serialHandle;
    int closeFile = false;
    SerialCommsData *sd;

    initSerialCommsDataStructure();

    for (streamID = 0; streamID < N_SERIAL_PORTS; streamID++) {
        if (SerialData[streamID].port[0] == 0) {
            break;
        }
    }
    if (streamID == N_SERIAL_PORTS) {
        printf( "All %d elements of the SerialCommsData structure are already in use.",  N_SERIAL_PORTS );
        return RTIOSTREAM_ERROR;
    }

    sd = &SerialData[streamID];

    sd->baud = BAUD_UNINITIALIZED;

    processArgs(argc, argv, sd);

    if (sd->baud == BAUD_UNINITIALIZED) {
        printf( "A valid bit rate must be specified via the -baud option.");
        sd->port[0] = 0;
        return RTIOSTREAM_ERROR;
    }

    initDCB( sd->baud );

    serialHandle = (void *) CreateFile( sd->port, 
                                        GENERIC_READ | GENERIC_WRITE,
                                        0, NULL, OPEN_EXISTING,
                                        FILE_ATTRIBUTE_NORMAL, NULL);

    if (serialHandle == INVALID_HANDLE_VALUE) {
        DWORD err = GetLastError( );
        printf( "CreateFile failed, error %d or 0x%08x. One possible "
                "cause is that COM ports COM10 or greater must be "
                "identified by a fully qualified name, e.g. "
                "\\\\.\\COM10.\n", err, err);
        sd->port[0] = 0;
        streamID = RTIOSTREAM_ERROR;
        goto EXIT_POINT;
    }
    sd->serialHandle = serialHandle;

    if (!SetCommTimeouts(serialHandle, &cto_blocking)) {
        printf( "SetCommTimeouts failed\n");
        streamID = RTIOSTREAM_ERROR;
        closeFile = true;
        goto EXIT_POINT;
    }

    if (!SetCommState(serialHandle, &dcb)) {
        printf( "SetCommState failed\n");
        streamID = RTIOSTREAM_ERROR;
        closeFile = true;
	goto EXIT_POINT;
    }

    result = serialDataFlush( sd);      /* clear out old data on the port */
    if (result == RTIOSTREAM_ERROR) {
        printf( "serialDataFlush failed\n");
        streamID = RTIOSTREAM_ERROR;
        closeFile = true;
	goto EXIT_POINT;
    }

  EXIT_POINT:
    if (closeFile) {
        CloseHandle(serialHandle);
        sd->port[0] = 0;
    }
    return streamID;
}
Пример #19
0
static co_rc_t coserial_main(int argc, char *argv[])
{
	co_rc_t rc;
	co_module_t module;
	HANDLE out_handle, in_handle;
	int select_time;

	rc = handle_parameters(&g_daemon_parameters, argc, argv);
	if (!CO_OK(rc))
		return rc;

	rc = co_reactor_create(&g_reactor);
	if (!CO_OK(rc))
		return rc;
	
	co_debug("connecting to monitor");

	module = CO_MODULE_SERIAL0 + g_daemon_parameters.index;
	rc = co_user_monitor_open(g_reactor, monitor_receive,
				  g_daemon_parameters.instance,
				  &module, 1,
				  &g_monitor_handle);
	if (!CO_OK(rc))
		return rc;

	if (g_daemon_parameters.filename_specified == PTRUE) {
		char name [strlen(g_daemon_parameters.filename) + 4+1];
		DCB dcb;
		COMMTIMEOUTS commtimeouts = {
			1,	/* ReadIntervalTimeout */
			0,	/* ReadTotalTimeoutMultiplier */
			0,	/* ReadTotalTimeoutConstant */
			0,	/* WriteTotalTimeoutMultiplier */
			0 };	/* WriteTotalTimeoutConstant */

		if (g_daemon_parameters.filename[0] != '\\') {
			/* short windows name */
			if (strncasecmp(g_daemon_parameters.filename, "COM", 3) != 0)
				co_terminal_print("warning: host serial device '%s' is not a COM port\n",
						    g_daemon_parameters.filename);
			snprintf(name, sizeof(name), "\\\\.\\%s", g_daemon_parameters.filename);
		} else {
			/* windows full name device */
			strncpy(name, g_daemon_parameters.filename, sizeof(name));
		}

		co_debug("open device '%s'", name);
		out_handle = \
		in_handle = CreateFile (name,
				GENERIC_READ | GENERIC_WRITE, 0, NULL,
				OPEN_EXISTING,
				FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
		if (in_handle == INVALID_HANDLE_VALUE) {
			co_terminal_print_last_error(g_daemon_parameters.filename);
			return CO_RC(ERROR);
		}

		if (g_daemon_parameters.mode_specified == PTRUE) {
			co_debug("set mode: %s", g_daemon_parameters.mode);

			if (!GetCommState(in_handle, &dcb)) {
				co_terminal_print_last_error("GetCommState");
				return CO_RC(ERROR);
			}
		
			/* Set defaults. user can overwrite ot */
			dcb.fOutxCtsFlow = FALSE; /* Disable Handshake */
			dcb.fDtrControl = DTR_CONTROL_ENABLE;
			dcb.fRtsControl = RTS_CONTROL_ENABLE;

			if (!BuildCommDCB(g_daemon_parameters.mode, &dcb)) {
				/*co_terminal_print_last_error("colinux-serial-daemon: BuildCommDCB");*/
				co_terminal_print("colinux-serial-daemon: error in mode parameter '%s'\n",
							g_daemon_parameters.mode);
				return CO_RC(ERROR);
			}

			if (!SetCommState(in_handle, &dcb)) {
				co_terminal_print_last_error("SetCommState");
				return CO_RC(ERROR);
			}
		} else {
			if (!EscapeCommFunction(in_handle, SETDTR)) {
				co_terminal_print_last_error("Warning EscapeCommFunction DTR");
				/* return CO_RC(ERROR); */
			}

			if (!EscapeCommFunction(in_handle, SETRTS)) {
				co_terminal_print_last_error("Warning EscapeCommFunction RTS");
				/* return CO_RC(ERROR); */
			}
		}

		if (!SetCommTimeouts(in_handle, &commtimeouts)) {
			co_terminal_print_last_error("SetCommTimeouts");
			return CO_RC(ERROR);
		}

		if (!SetupComm(in_handle, 2048, 2048)) {
			co_terminal_print_last_error("SetupComm");
			return CO_RC(ERROR);
		}

		select_time = -1;
	} else {
		co_debug("std input/output");
		out_handle = GetStdHandle(STD_OUTPUT_HANDLE);
		in_handle  = GetStdHandle(STD_INPUT_HANDLE);
		select_time = 100;
	}

	co_debug("connected");

	rc = co_winnt_reactor_packet_user_create(g_reactor, 
						 out_handle, in_handle,
						 std_receive, &g_reactor_handle);
	if (!CO_OK(rc))
		return rc;

	co_terminal_print("colinux-serial-daemon: running\n");

	while (CO_OK(rc)) {
		rc = co_reactor_select(g_reactor, select_time);
		if (CO_RC_GET_CODE(rc) == CO_RC_BROKEN_PIPE)
			return CO_RC(OK); /* Normal, if linux shut down */

		if (!g_daemon_parameters.filename_specified)
			if ( _kbhit() )
				send_userinput();
	}

	return -1;
}
Пример #20
0
int sio_open(sio_s *sio)
{
	char filename[30];
	
#if defined(SIO_TTY)
	
	struct termios t;
	int fd, c_stop, c_data, i_parity, c_parity;
	speed_t speed;
	
	if (sio_isopen(sio))
		return -1;
					 
	// sprintf(filename, "/dev/ttyS%hd", sio->info.port - 1);
	sprintf(filename, "%s%hd", sio->info.serial_device, sio->info.port - 1 );	

	fd = open(filename, O_RDWR );

	if (fd == -1){
		fprintf(stderr, "Failed to open serial port %s.\n", filename );
		return -1;
	}
	
	if (tcgetattr(fd, &t))
	{
		fprintf(stderr, "Failed to tcgetattr for serial port %s.\n", filename );

		close(fd);
		return -1;
	}
	
	switch(sio->info.baud)
	{
	case 0: speed = B0; break;
	case 50: speed = B50; break;
	case 75: speed = B75; break;
	case 110: speed = B110; break;
	case 134: speed = B134; break;
	case 150: speed = B150; break;
	case 300: speed = B300; break;
	case 600: speed = B600; break;
	case 1200: speed = B1200; break;
	case 1800: speed = B1800; break;
	case 2400: speed = B2400; break;
	case 4800: speed = B4800; break;
	case 9600: speed = B9600; break;
	case 19200: speed = B19200; break;
	case 38400: speed = B38400; break;
	case 57600: speed = B57600; break;
	case 115200: speed = B115200; break;
	case 230400: speed = B230400; break;
	default: speed = B0; break;
	}

	if (speed == B0)
	{
		close(fd);
		return -1;
	}
	
	if (cfsetospeed(&t, speed))
	{
		close(fd);
		return -1;
	}

	if (cfsetispeed(&t, speed))
	{
		close(fd);
		return -1;
	}
	
	switch(sio->info.stopbits)
	{
	case 1: c_stop = 0; break;
	case 2: c_stop = CSTOPB; break;
	default: close(fd); return -1;
	}

	switch(sio->info.databits)
	{
	case 5: c_data = CS5; break;
	case 6: c_data = CS6; break;
	case 7: c_data = CS7; break;
	case 8: c_data = CS8; break;
	default: close(fd); return -1;
	}

	switch(sio->info.parity)
	{
	case SIO_PARITY_NONE:
		i_parity = IGNPAR;
		c_parity = 0;
		break;
		
	case SIO_PARITY_EVEN:
		i_parity = INPCK;
		c_parity = PARENB;
		break;

	case SIO_PARITY_ODD:
		i_parity = INPCK;
		c_parity = PARENB | PARODD;
		break;

	default:
		close(fd);
		return -1;
	}

  t.c_oflag = 0;

  /*
    ICANON  : enable canonical input
    disable all echo functionality, and don't send signals to calling program
  */
   t.c_lflag = ICANON;

  /*
    initialize all control characters
    default values can be found in /usr/include/termios.h, and are given
    in the comments, but we don't need them here
  */
   t.c_cc[VINTR]    = 0;     /* Ctrl-c */
   t.c_cc[VQUIT]    = 0;     /* Ctrl-\ */
   t.c_cc[VERASE]   = 0;     /* del */
   t.c_cc[VKILL]    = 0;     /* @ */
   t.c_cc[VEOF]     = 4;     /* Ctrl-d */
   t.c_cc[VTIME]    = 0;     /* inter-character timer unused */
   t.c_cc[VMIN]     = 1;     /* blocking read until 1 character arrives */
   t.c_cc[VSWTC]    = 0;     /* '\0' */
   t.c_cc[VSTART]   = 0;     /* Ctrl-q */
   t.c_cc[VSTOP]    = 0;     /* Ctrl-s */
   t.c_cc[VSUSP]    = 0;     /* Ctrl-z */
   t.c_cc[VEOL]     = 0;     /* '\0' */
   t.c_cc[VREPRINT] = 0;     /* Ctrl-r */
   t.c_cc[VDISCARD] = 0;     /* Ctrl-u */
   t.c_cc[VWERASE]  = 0;     /* Ctrl-w */
   t.c_cc[VLNEXT]   = 0;     /* Ctrl-v */
   t.c_cc[VEOL2]    = 0;     /* '\0' */

	if (tcsetattr(fd, TCSANOW, &t))
	{
		close(fd);
		return -1;
	}
	
	sio->fd = fd;
	
	return 0;
#elif defined(SIO_WIN32)
	HANDLE fd;
	HANDLE hComm;
	DCB dcb;
	COMMTIMEOUTS cto = { MAXDWORD, 0, 0, 4, 4 }; 

	if (sio_isopen(sio))
		return -1;
			 
	sprintf(filename, "\\\\.\\COM%d", sio->info.port); 

	hComm = fd = CreateFileA( filename , GENERIC_READ | GENERIC_WRITE, 0, NULL,
			     OPEN_EXISTING, 0, NULL);
	
	if (fd == INVALID_HANDLE_VALUE){
		fprintf(stderr, "Failed to open port %s ", filename );
		return -1;
	}

	if (!SetCommTimeouts(hComm, &cto))
	{
		fprintf(stderr, "SetCommState failed." );
		//_close(fd);
		//return -1;
	}
	
	dcb.DCBlength = sizeof(dcb);
	memset(&dcb, sizeof(dcb), 0);

	if (!GetCommState(hComm, &dcb))
	{
		//_close(fd);
		//return -1;	
		fprintf(stderr, "GetCommState failed." );
	}

	dcb.BaudRate = sio->info.baud;
	dcb.fBinary = TRUE;
	dcb.fParity = (sio->info.parity == SIO_PARITY_NONE) ? FALSE : TRUE;
	dcb.fOutxCtsFlow = FALSE;
	dcb.fOutxDsrFlow = FALSE;
	dcb.fDtrControl = DTR_CONTROL_DISABLE;
	dcb.fDsrSensitivity = FALSE;
	dcb.fTXContinueOnXoff = FALSE;
	dcb.fOutX = FALSE;
	dcb.fInX = FALSE;
	dcb.fErrorChar = FALSE;
	dcb.fNull = FALSE;
	dcb.fRtsControl = RTS_CONTROL_DISABLE;
	dcb.fAbortOnError = FALSE;
	dcb.ByteSize = sio->info.databits;

	switch (sio->info.parity)
	{
	case SIO_PARITY_NONE: dcb.Parity = 0; break;
	case SIO_PARITY_ODD: dcb.Parity = 1; break;
	case SIO_PARITY_EVEN: dcb.Parity = 2; break;		
	default: CloseHandle(fd); return -1;
	}

	switch (sio->info.stopbits)
	{
	case 1: dcb.StopBits = 0; break;
	case 2: dcb.StopBits = 2; break;
	default: CloseHandle(fd); return -1;
	}

	if (!SetCommState(hComm, &dcb))
	{
		fprintf(stderr, "SetCommState failed." );
		//_close(fd);
		//return -1;
	}	

	sio->fd = fd;
	sio->hComm = hComm;

	return 0;
#endif
}
Пример #21
0
/* -------------------------------------------------------------------- */
int  Tserial::connect          (char *port_arg, int rate_arg, serial_parity parity_arg)
{
    int erreur;
    DCB  dcb;
    COMMTIMEOUTS cto = { 0, 0, 0, 0, 0 };

    /* --------------------------------------------- */
    if (serial_handle!=INVALID_HANDLE_VALUE)
        CloseHandle(serial_handle);
    serial_handle = INVALID_HANDLE_VALUE;

    erreur = 0;

    if (port_arg!=0)
    {
        strncpy(port, port_arg, 10);
        rate      = rate_arg;
        parityMode= parity_arg;
        memset(&dcb,0,sizeof(dcb));

        /* -------------------------------------------------------------------- */
        // set DCB to configure the serial port
        dcb.DCBlength       = sizeof(dcb);                   
        
        /* ---------- Serial Port Config ------- */
        dcb.BaudRate        = rate;

        switch(parityMode)
        {
            case spNONE:
                            dcb.Parity      = NOPARITY;
                            dcb.fParity     = 0;
                            break;
            case spEVEN:
                            dcb.Parity      = EVENPARITY;
                            dcb.fParity     = 1;
                            break;
            case spODD:
                            dcb.Parity      = ODDPARITY;
                            dcb.fParity     = 1;
                            break;
        }


        dcb.StopBits        = ONESTOPBIT;
        dcb.ByteSize        = 8;
        
        dcb.fOutxCtsFlow    = 0;
        dcb.fOutxDsrFlow    = 0;
        dcb.fDtrControl     = DTR_CONTROL_DISABLE;
        dcb.fDsrSensitivity = 0;
        dcb.fRtsControl     = RTS_CONTROL_DISABLE;
        dcb.fOutX           = 0;
        dcb.fInX            = 0;
        
        /* ----------------- misc parameters ----- */
        dcb.fErrorChar      = 0;
        dcb.fBinary         = 1;
        dcb.fNull           = 0;
        dcb.fAbortOnError   = 0;
        dcb.wReserved       = 0;
        dcb.XonLim          = 2;
        dcb.XoffLim         = 4;
        dcb.XonChar         = 0x13;
        dcb.XoffChar        = 0x19;
        dcb.EvtChar         = 0;
        
        /* -------------------------------------------------------------------- */
        serial_handle    = CreateFile(port, GENERIC_READ | GENERIC_WRITE,
                               0, NULL, OPEN_EXISTING,NULL,NULL);
                   // opening serial port


        if (serial_handle    != INVALID_HANDLE_VALUE)
        {
            if(!SetCommMask(serial_handle, 0))
                erreur = 1;

            // set timeouts
            if(!SetCommTimeouts(serial_handle,&cto))
                erreur = 2;

            // set DCB
            if(!SetCommState(serial_handle,&dcb))
                erreur = 4;
        }
        else
            erreur = 8;
    }
    else
        erreur = 16;


    /* --------------------------------------------- */
    if (erreur!=0)
    {
        CloseHandle(serial_handle);
        serial_handle = INVALID_HANDLE_VALUE;
    }
    return(erreur);
}
Пример #22
0
int InitSerialPort(PortType Port, BaudrateType BaudRate, ParityType Parity,
					                int Bits, int Stopbits)
{
   /* Method data declaration      */
   char *PortId = "";
   COMMTIMEOUTS   NewTimeout = {0};
   DCB            DeviceControlBlock;

   /* Method code declaration      */

   /*check for correct port */
   switch (Port) {
      case COM1:
        PortId = "COM1";
	    break;

      case COM2 :
        PortId = "COM2";
	    break;

      case COM3 :
        PortId = "COM3";
        break;

      case COM4 :
        PortId = "COM4";
      	break;

      case COM5 :
        PortId = "COM5";
      	break;

      case COM6 :
        PortId = "COM6";
      	break;

      case COM7 :
        PortId = "COM7";
      	break;

      default:
	    return -1;
	    break;
   }

   /* Open the selected port */
   ComPort = CreateFile( PortId,
                         GENERIC_READ | GENERIC_WRITE,
                         0,
                         0,
                         OPEN_EXISTING,
                         0,
                         0);

   /* check if port could be openend */
   if(ComPort != INVALID_HANDLE_VALUE) {

      /* Set the comm timeouts such, that read returns immediately */
      /* independent if any bytes are availlable or not            */
      GetCommTimeouts(ComPort,&OldTimeout);
      NewTimeout.ReadIntervalTimeout = MAXDWORD;
      SetCommTimeouts(ComPort, &NewTimeout);

      /* Setup the device controlblock (Baudrate and other parameters) */
      DeviceControlBlock.DCBlength = sizeof(DCB);
      GetCommState(ComPort, &DeviceControlBlock);
      BuildCommDCB("baud=1200 parity=N data=8 stop=1", &DeviceControlBlock);
      switch (BaudRate) {
		case Bd600 :
           DeviceControlBlock.BaudRate = CBR_600;
		   break;

		case Bd1200 :
           DeviceControlBlock.BaudRate = CBR_1200;
		   break;

		case Bd2400 :
           DeviceControlBlock.BaudRate = CBR_2400;
	       break;

		case Bd4800 :
           DeviceControlBlock.BaudRate = CBR_4800;
	       break;

		case Bd9600 :
           DeviceControlBlock.BaudRate = CBR_9600;
	       break;

		case Bd19200 :
           DeviceControlBlock.BaudRate = CBR_19200;
	       break;

        default:
	       /* illegal baudrate... */
           ShutdownSerialPort();
	       return -2;
	       break;
      }
      switch (Bits) {
         case 5:
         case 6:
         case 7:
         case 8:
            DeviceControlBlock.ByteSize = Bits;
            break;

         default:
            ShutdownSerialPort();
	        return -3;
	        break;
      }
      switch (Stopbits) {
         case 1: DeviceControlBlock.StopBits = 0; break;  // 1 = 1.5
         case 2: DeviceControlBlock.StopBits = 2; break;
         default: ShutdownSerialPort(); return -4; break;
      }
      switch (Parity) {
         case P_NONE:  DeviceControlBlock.fParity = 0;
                     DeviceControlBlock.Parity  = 0;
                     break;
         case P_EVEN:  DeviceControlBlock.fParity = 1;
                     DeviceControlBlock.Parity  = 2;
                     break;
         case P_ODD:   DeviceControlBlock.fParity = 1;
                     DeviceControlBlock.Parity  = 1;
                     break;
         case P_MARK:  DeviceControlBlock.fParity = 1;
                     DeviceControlBlock.Parity  = 3;
                     break;
         case P_SPACE: DeviceControlBlock.fParity = 1;
                     DeviceControlBlock.Parity  = 4;
                     break;
         default:    ShutdownSerialPort();
                     return -5;
                     break;
      }
      SetCommState(ComPort, &DeviceControlBlock);
   }
   return 0;
}
Пример #23
0
int RS232_OpenComport(int comport_number, int baudrate, const char *mode)
{
  if((comport_number>=RS232_PORTNR)||(comport_number<0))
  {
    printf("illegal comport number\n");
    return(1);
  }

  switch(baudrate)
  {
    case     110 : strcpy(mode_str, "baud=110");
                   break;
    case     300 : strcpy(mode_str, "baud=300");
                   break;
    case     600 : strcpy(mode_str, "baud=600");
                   break;
    case    1200 : strcpy(mode_str, "baud=1200");
                   break;
    case    2400 : strcpy(mode_str, "baud=2400");
                   break;
    case    4800 : strcpy(mode_str, "baud=4800");
                   break;
    case    9600 : strcpy(mode_str, "baud=9600");
                   break;
    case   19200 : strcpy(mode_str, "baud=19200");
                   break;
    case   38400 : strcpy(mode_str, "baud=38400");
                   break;
    case   57600 : strcpy(mode_str, "baud=57600");
                   break;
    case  115200 : strcpy(mode_str, "baud=115200");
                   break;
    case  128000 : strcpy(mode_str, "baud=128000");
                   break;
    case  256000 : strcpy(mode_str, "baud=256000");
                   break;
    case  500000 : strcpy(mode_str, "baud=500000");
                   break;
    case 1000000 : strcpy(mode_str, "baud=1000000");
                   break;
    default      : printf("invalid baudrate\n");
                   return(1);
                   break;
  }

  if(strlen(mode) != 3)
  {
    printf("invalid mode \"%s\"\n", mode);
    return(1);
  }

  switch(mode[0])
  {
    case '8': strcat(mode_str, " data=8");
              break;
    case '7': strcat(mode_str, " data=7");
              break;
    case '6': strcat(mode_str, " data=6");
              break;
    case '5': strcat(mode_str, " data=5");
              break;
    default : printf("invalid number of data-bits '%c'\n", mode[0]);
              return(1);
              break;
  }

  switch(mode[1])
  {
    case 'N':
    case 'n': strcat(mode_str, " parity=n");
              break;
    case 'E':
    case 'e': strcat(mode_str, " parity=e");
              break;
    case 'O':
    case 'o': strcat(mode_str, " parity=o");
              break;
    default : printf("invalid parity '%c'\n", mode[1]);
              return(1);
              break;
  }

  switch(mode[2])
  {
    case '1': strcat(mode_str, " stop=1");
              break;
    case '2': strcat(mode_str, " stop=2");
              break;
    default : printf("invalid number of stop bits '%c'\n", mode[2]);
              return(1);
              break;
  }

  strcat(mode_str, " dtr=on rts=on");

/*
http://msdn.microsoft.com/en-us/library/windows/desktop/aa363145%28v=vs.85%29.aspx

http://technet.microsoft.com/en-us/library/cc732236.aspx
*/

  Cport[comport_number] = CreateFileA(comports[comport_number],
                      GENERIC_READ|GENERIC_WRITE,
                      0,                          /* no share  */
                      NULL,                       /* no security */
                      OPEN_EXISTING,
                      0,                          /* no threads */
                      NULL);                      /* no templates */

  if(Cport[comport_number]==INVALID_HANDLE_VALUE)
  {
    printf("unable to open comport\n");
    return(1);
  }

  DCB port_settings;
  memset(&port_settings, 0, sizeof(port_settings));  /* clear the new struct  */
  port_settings.DCBlength = sizeof(port_settings);

  if(!BuildCommDCBA(mode_str, &port_settings))
  {
    printf("unable to set comport dcb settings\n");
    CloseHandle(Cport[comport_number]);
    return(1);
  }

  if(!SetCommState(Cport[comport_number], &port_settings))
  {
    printf("unable to set comport cfg settings\n");
    CloseHandle(Cport[comport_number]);
    return(1);
  }

  COMMTIMEOUTS Cptimeouts;

  Cptimeouts.ReadIntervalTimeout         = MAXDWORD;
  Cptimeouts.ReadTotalTimeoutMultiplier  = 0;
  Cptimeouts.ReadTotalTimeoutConstant    = 0;
  Cptimeouts.WriteTotalTimeoutMultiplier = 0;
  Cptimeouts.WriteTotalTimeoutConstant   = 0;

  if(!SetCommTimeouts(Cport[comport_number], &Cptimeouts))
  {
    printf("unable to set comport time-out settings\n");
    CloseHandle(Cport[comport_number]);
    return(1);
  }

  return(0);
}
//open
//	Opens the serial port using stored information
//	Sets the baud rate to the stored baud rate
//	8 data bits, no parity, one stop bit
bool serial_port::serial_open()
{
    printf("SerialPort: Opening serial port %s at baud rate %d.\n", port_name, baud_rate);

	#ifdef WIN32
	file_descriptor = CreateFile(port_name, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);

    if((int)file_descriptor < 0)
    {
   	    printf("SerialPort: Port %s could not be opened: %d.\n", port_name, file_descriptor);
        return false;
    }

	SetupComm(file_descriptor, 1, 128);
	GetCommState(file_descriptor, &dcb);

	dcb.BaudRate = baud_rate;                   //Set baud rate
	dcb.ByteSize = 8;                           //8 data bits
	dcb.Parity = NOPARITY;                      //Parity = none
	dcb.StopBits = ONESTOPBIT;                  //One stop bit
	dcb.fAbortOnError = TRUE;                   //Abort on error
	dcb.fOutX = FALSE;                          //XON/XOFF off for transmit
	dcb.fInX = FALSE;                           //XON/XOFF off for receive
	dcb.fOutxCtsFlow = FALSE;                   //Turn off CTS flow control
	dcb.fRtsControl = RTS_CONTROL_DISABLE;      //Options DISABLE, ENABLE, HANDSHAKE
	dcb.fOutxDsrFlow = FALSE;                   //Turn off DSR flow control
	dcb.fDtrControl = DTR_CONTROL_DISABLE;      //Disable DTR control

	SetCommState(file_descriptor, &dcb);

	COMMTIMEOUTS timeouts = {0};
	timeouts.ReadIntervalTimeout = 50;
	timeouts.ReadTotalTimeoutConstant=50;
	timeouts.ReadTotalTimeoutMultiplier=10;
	timeouts.WriteTotalTimeoutConstant=50;
	timeouts.WriteTotalTimeoutMultiplier=10;
	SetCommTimeouts(file_descriptor, &timeouts);

    #else

	file_descriptor = open(port_name, O_RDWR | O_NOCTTY | O_NDELAY);

	if(file_descriptor < 0)
	{
		printf("SerialPort: Port %s could not be opened: %d.\n", port_name, file_descriptor);
		return false;
	}

	serial_struct ss;
	ioctl(file_descriptor, TIOCGSERIAL, &ss);
	ss.flags = (ss.flags & ~ASYNC_SPD_MASK) | ASYNC_SPD_CUST | ASYNCB_LOW_LATENCY;
	ss.custom_divisor = (ss.baud_base + (baud_rate / 2)) / baud_rate;
	int closestSpeed = ss.baud_base / ss.custom_divisor;

	if((float)closestSpeed < ((float)baud_rate * (98.0f/100.0f)) || (float)closestSpeed > ((float)baud_rate * (102.0f/100.0f)))
	{
		printf("SerialPort: Cannot set %s to %d.  Closest possible speed is %d.\n", port_name, baud_rate, closestSpeed);
	}
	else
	{
		printf("SerialPort: %s speed set to %d.\n", port_name, baud_rate);
	}

	fcntl(file_descriptor, F_SETFL, 0);
	#endif

    printf("SerialPort: Serial port %s opened successfully.\n", port_name);
    return true;
}
Пример #25
0
extern "C" __declspec(dllexport) int GccOpenGps(int com_port, int rate)
{
	wchar_t comport[10];
	if(com_port >= 100)
	{
		logRawNmea = true;
		com_port -= 100;
	}
	else { logRawNmea = false; }
	if(com_port == 13)
	{
		wcscpy(comport, L"\\nmea.txt");
		filemode = true;
	}
	else
	{
		swprintf(comport, L"COM%i:", com_port);
		filemode = false;
	}
	__hGpsPort = CreateFile(comport, GENERIC_READ|GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
/*
// for some reason sprintf did not work to write all these in one line ...
if     (com_port == 1)  __hGpsPort = CreateFile(L"COM1:", GENERIC_READ|GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
else if(com_port == 2)  __hGpsPort = CreateFile(L"COM2:", GENERIC_READ|GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
else if(com_port == 3)  __hGpsPort = CreateFile(L"COM3:", GENERIC_READ|GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
else if(com_port == 4)  __hGpsPort = CreateFile(L"COM4:", GENERIC_READ|GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
else if(com_port == 5)  __hGpsPort = CreateFile(L"COM5:", GENERIC_READ|GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
else if(com_port == 6)  __hGpsPort = CreateFile(L"COM6:", GENERIC_READ|GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
else if(com_port == 7)  __hGpsPort = CreateFile(L"COM7:", GENERIC_READ|GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
else if(com_port == 8)  __hGpsPort = CreateFile(L"COM8:", GENERIC_READ|GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
else if(com_port == 9)  __hGpsPort = CreateFile(L"COM9:", GENERIC_READ|GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
else if(com_port == 10) __hGpsPort = CreateFile(L"COM10:",GENERIC_READ|GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
else if(com_port == 11) __hGpsPort = CreateFile(L"COM11:",GENERIC_READ|GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
else if(com_port == 12) __hGpsPort = CreateFile(L"COM12:",GENERIC_READ|GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
else if(com_port == 13) __hGpsPort = CreateFile(L"COM13:",GENERIC_READ|GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
else if(com_port == 14) __hGpsPort = CreateFile(L"COM14:",GENERIC_READ|GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
*/
    if(__hGpsPort == INVALID_HANDLE_VALUE)
    {
        DWORD dwLastError = GetLastError();

        switch(dwLastError)
        {
          case ERROR_ACCESS_DENIED:
            return -1;
            break;
          case ERROR_FILE_NOT_FOUND:
            return -2;
            break;
          default:
            return -3;
            break;
        }
    }

	if(!filemode)
	{
		// COM port setting
		DCB dcb;

		if (GetCommState(__hGpsPort,&dcb))	//fails on some devices with internal GPS - in these cases it's not necessarry anyway
		{
			// Set baud rate and other params
			dcb.BaudRate = (DWORD)rate;
			dcb.Parity   = NOPARITY;
			dcb.StopBits = ONESTOPBIT;
			dcb.ByteSize = 8;

			// use defaults for other fields (found on web)
			dcb.fBinary         = TRUE;	
			dcb.fParity         = FALSE;
			dcb.fOutxCtsFlow    = FALSE;	      
			dcb.fOutxDsrFlow    = FALSE;	      
			dcb.fDtrControl     = DTR_CONTROL_ENABLE; 
			dcb.fDsrSensitivity = FALSE;	      
			dcb.fOutX           = FALSE;	      
			dcb.fInX            = FALSE;	      
			dcb.fNull           = FALSE;	      
			dcb.fRtsControl     = RTS_CONTROL_ENABLE; 
			dcb.fAbortOnError   = FALSE;	      

			if (SetCommState(__hGpsPort,&dcb) == 0)
				{ return -5; }
		}

		// set mask which events to monitor 
		SetCommMask(__hGpsPort, EV_RXCHAR);

		// set buffer sizes (defaults in Windows)
		SetupComm( __hGpsPort, 4096, 2048);

		// Clear all chars from COM
		PurgeComm(__hGpsPort,PURGE_TXABORT|PURGE_RXABORT|PURGE_TXCLEAR|PURGE_RXCLEAR);

		// Setup the comm timeouts. This is important: MAXDWORD for ReadIntervalTimeout means return immediately.
		COMMTIMEOUTS CommTimeOuts;
		CommTimeOuts.ReadIntervalTimeout            = 10;
		CommTimeOuts.ReadTotalTimeoutMultiplier     = 0;
		CommTimeOuts.ReadTotalTimeoutConstant       = 300;
		CommTimeOuts.WriteTotalTimeoutMultiplier    = 0;
		CommTimeOuts.WriteTotalTimeoutConstant      = 10;
		if (SetCommTimeouts( __hGpsPort, &CommTimeOuts ) == 0)
			{ return -6; }

		DWORD dwErrors;
		COMSTAT ComStat;
		ClearCommError(__hGpsPort,&dwErrors, &ComStat);
	}
    // reset read buffer
    __save_str = "";
    __read_lock = false;

	if (logRawNmea)
	{
		FILE *file = fopen("\\tmp.txt", "w");
		fprintf(file, "");
		fclose(file);
	}

	//FILE *filex = fopen("\\debug.txt", "w");
	//fprintf(filex, "debugfile\n");
	HANDLE initfile = CreateFile(L"\\GccInitGps.txt", GENERIC_READ,FILE_SHARE_READ, NULL,OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
	if(initfile != INVALID_HANDLE_VALUE)			//file exists -> send init data to GPS device
	{
		char c; unsigned long r,w; BOOL a;
		while(1)
		{
			if(!ReadFile(initfile, &c, 1, &r, NULL) || r==0)
				break;
			for(int i=0; i<1000; i++)
			{
				a=WriteFile(__hGpsPort, &c, 1, &w, NULL);		//w==0 if buffer full?
				//fprintf(filex, "read=%i  char=%c  written=%i  ret=%i\n",r,c,w,a);
				if(w == 1) break;
			}
		}
		CloseHandle(initfile);
	}
	//fclose(filex);
    return 1;
}
Пример #26
0
Serial::Serial(char *portName)
{
    //We're not yet connected
    this->connected = false;

    //Try to connect to the given port throuh CreateFile
    this->hSerial = CreateFileA(portName,
                                GENERIC_READ | GENERIC_WRITE,
                                0,
                                NULL,
                                OPEN_EXISTING,
                                FILE_ATTRIBUTE_NORMAL,
                                NULL);

    //Check if the connection was successfull
    if(this->hSerial==INVALID_HANDLE_VALUE)
    {
        //If not success full display an Error
        if(GetLastError()==ERROR_FILE_NOT_FOUND) {

            //Print Error if neccessary
            printf("ERROR: Handle was not attached. Reason: %s not available.\n", portName);

        }
        else
        {
            printf("ERROR!!!");
        }
    }
    else
    {
        //If connected we try to set the comm parameters
        DCB dcbSerialParams = {0};

        COMMTIMEOUTS timeouts = {0};

        //setting timeouts
        timeouts.ReadIntervalTimeout = 50;
        timeouts.ReadTotalTimeoutConstant = 50;
        timeouts.ReadTotalTimeoutMultiplier = 50;
        timeouts.WriteTotalTimeoutConstant = 50;
        timeouts.WriteTotalTimeoutMultiplier = 50;
        //SetCommTimeouts set the time out parameters for all read and write operation
        if (!SetCommTimeouts(hSerial, &timeouts))
        {
            printf("Not SetCommTimeouts, cannot set the timeout parameters to serial port\n");
        }

        //Try to get the current
        if (!GetCommState(this->hSerial, &dcbSerialParams))
        {
            //If impossible, show an error
            printf("failed to get current serial parameters!");
        }
        else
        {
            //Define serial connection parameters for the arduino board
            dcbSerialParams.BaudRate=CBR_9600;
            dcbSerialParams.ByteSize=8;
            dcbSerialParams.StopBits=ONESTOPBIT;
            dcbSerialParams.Parity=NOPARITY;
            //Setting the DTR to Control_Enable ensures that the Arduino is properly
            //reset upon establishing a connection
            dcbSerialParams.fDtrControl = DTR_CONTROL_ENABLE;

            //Set the parameters and check for their proper application
            if(!SetCommState(hSerial, &dcbSerialParams))
            {
                printf("ALERT: Could not set Serial Port parameters");
            }
            else
            {
                //If everything went fine we're connected
                this->connected = true;
                //Flush any remaining characters in the buffers
                PurgeComm(this->hSerial, PURGE_RXCLEAR | PURGE_TXCLEAR);
                //We wait 2s as the arduino board will be reseting
                Sleep(ARDUINO_WAIT_TIME);
            }
        }
    }

}
Пример #27
0
// 포트 sPortName을 dwBaud 속도로 연다.
// ThreadWatchComm 함수에서 포트에 무언가 읽혔을 때 MainWnd에 알리기
// 위해 WM_COMM_READ메시지를 보낼때 같이 보낼 wPortID값을 전달 받는다.
BOOL CCommThread::OpenPort(char *sPortName, DWORD dwBaud, BYTE wPortID)
{
	// Local 변수.
	COMMTIMEOUTS	timeouts;
	DCB				dcb;
	DWORD			dwThreadID;

	// 변수 초기화
	m_bConnected = FALSE;
	m_wPortID	= wPortID; // COM1-> 0, COM2->1,,,,,

	// overlapped structure 변수 초기화.
	m_osRead.Offset = 0;
	m_osRead.OffsetHigh = 0;
	if (! (m_osRead.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL)))	
		return FALSE;
	m_osWrite.Offset = 0;
	m_osWrite.OffsetHigh = 0;
	if (! (m_osWrite.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL)))
		return FALSE;
	
	// 포트 열기
//	m_sPortName = sPortName;
	m_hComm = CreateFile( LPCSTR(sPortName), // LPCSTR("COM4"), 
//	m_hComm = CreateFileA( LPCSTR("COM4"), 
		GENERIC_READ | GENERIC_WRITE, 0, NULL,
		OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, 
		NULL);
	if (m_hComm == (HANDLE) -1) return FALSE;

	// 포트 상태 설정.

	// EV_RXCHAR event 설정
	SetCommMask( m_hComm, EV_RXCHAR);	

	// InQueue, OutQueue 크기 설정.
	SetupComm( m_hComm, 4096, 4096);	

	// 포트 비우기.
	PurgeComm( m_hComm,					
		PURGE_TXABORT | PURGE_TXCLEAR | PURGE_RXABORT | PURGE_RXCLEAR);

	// timeout 설정.
	timeouts.ReadIntervalTimeout = 0xFFFFFFFF;
	timeouts.ReadTotalTimeoutMultiplier = 0;
	timeouts.ReadTotalTimeoutConstant = 0;
	timeouts.WriteTotalTimeoutMultiplier = 2*CBR_9600 / dwBaud;
	timeouts.WriteTotalTimeoutConstant = 0;
	SetCommTimeouts( m_hComm, &timeouts);

	// dcb 설정
	dcb.DCBlength = sizeof(DCB);
	GetCommState( m_hComm, &dcb);	// 예전 값을 읽음.
	dcb.BaudRate = dwBaud;
	dcb.ByteSize = 8;
	dcb.Parity = 0;
	dcb.StopBits = 0;
	dcb.fInX = dcb.fOutX = 0;		// Xon, Xoff 사용안함.
	dcb.XonChar = ASCII_XON;
	dcb.XoffChar = ASCII_XOFF;
	dcb.XonLim = 100;
	dcb.XoffLim = 100;
	if (! SetCommState( m_hComm, &dcb))	return FALSE;

	// 포트 감시 쓰레드 생성.
	m_bConnected = TRUE;
	m_hThreadWatchComm = CreateThread( NULL, 0, 
		(LPTHREAD_START_ROUTINE)ThreadWatchComm, this, 0, &dwThreadID);
	if (! m_hThreadWatchComm)
	{
		ClosePort();
		return FALSE;
	}
    
	return TRUE;
}
Пример #28
0
/*!
   Opens a serial port.  Note that this function does not specify which device to open.  If you need
   to open a device by name, see QextSerialPort::open(const char*).  This function has no effect
   if the port associated with the class is already open.  The port is also configured to the current
   settings, as stored in the Settings structure.
 */
bool QextSerialPort::open(OpenMode mode)
{
    unsigned long confSize     = sizeof(COMMCONFIG);

    Win_CommConfig.dwSize = confSize;
    DWORD dwFlagsAndAttributes = 0;
    if (queryMode() == QextSerialPort::EventDriven) {
        dwFlagsAndAttributes += FILE_FLAG_OVERLAPPED;
    }
    QMutexLocker lock(mutex);
    if (mode == QIODevice::NotOpen) {
        return isOpen();
    }
    if (!isOpen()) {
        /*open the port*/
        Win_Handle = CreateFileA(port.toAscii(), GENERIC_READ | GENERIC_WRITE,
                                 0, NULL, OPEN_EXISTING, dwFlagsAndAttributes, NULL);
        if (Win_Handle != INVALID_HANDLE_VALUE) {
            QIODevice::open(mode);
            /*configure port settings*/
            GetCommConfig(Win_Handle, &Win_CommConfig, &confSize);
            GetCommState(Win_Handle, &(Win_CommConfig.dcb));

            /*set up parameters*/
            Win_CommConfig.dcb.fBinary = TRUE;
            Win_CommConfig.dcb.fInX    = FALSE;
            Win_CommConfig.dcb.fOutX   = FALSE;
            Win_CommConfig.dcb.fAbortOnError = FALSE;
            Win_CommConfig.dcb.fNull   = FALSE;
            setBaudRate(Settings.BaudRate);
            setDataBits(Settings.DataBits);
            setStopBits(Settings.StopBits);
            setParity(Settings.Parity);
            setFlowControl(Settings.FlowControl);
            setTimeout(Settings.Timeout_Millisec);
            SetCommConfig(Win_Handle, &Win_CommConfig, sizeof(COMMCONFIG));

            // init event driven approach
            if (queryMode() == QextSerialPort::EventDriven) {
                Win_CommTimeouts.ReadIntervalTimeout = MAXDWORD;
                Win_CommTimeouts.ReadTotalTimeoutMultiplier  = 0;
                Win_CommTimeouts.ReadTotalTimeoutConstant    = 0;
                Win_CommTimeouts.WriteTotalTimeoutMultiplier = 0;
                Win_CommTimeouts.WriteTotalTimeoutConstant   = 0;
                SetCommTimeouts(Win_Handle, &Win_CommTimeouts);
                if (!SetCommMask(Win_Handle, EV_TXEMPTY | EV_RXCHAR | EV_DSR)) {
                    qWarning() << "failed to set Comm Mask. Error code:", GetLastError();
                    return false;
                }
                winEventNotifier = new QWinEventNotifier(overlap.hEvent, this);
                connect(winEventNotifier, SIGNAL(activated(HANDLE)), this, SLOT(onWinEvent(HANDLE)));
                connect(&fakeTxEmpty, SIGNAL(timeout()), this, SLOT(triggerTxEmpty()));
                fakeTxEmpty.start(10000);
                WaitCommEvent(Win_Handle, &eventMask, &overlap);
            }
        }
    } else {
        return false;
    }
    return isOpen();
}
Пример #29
0
static BOOL CALLBACK Main_DlgProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
	char data[512];
	char errmsg[512];

	switch (uMsg) {
	case WM_COMMAND:
		{
			WORD wNotifyCode = HIWORD(wParam);
			WORD wID = LOWORD(wParam);
			HWND hwndCtl = (HWND)lParam;

			if (wID == IDOK) {
				HANDLE hCom = CreateFile("COM1", GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
				if (hCom != INVALID_HANDLE_VALUE) {
					DCB dcb;

					if (GetCommState(hCom, &dcb) == FALSE) {
						wsprintf(errmsg, "GetCommState error: %d", GetLastError());
						MessageBox(hwnd, errmsg, NULL, MB_OK);

						goto close_handle;
					}
					
					dcb.BaudRate = CBR_9600;
					dcb.Parity = NOPARITY;
					dcb.ByteSize = 8;
					dcb.StopBits = ONESTOPBIT;
					dcb.fDtrControl = DTR_CONTROL_DISABLE;
					dcb.fRtsControl = RTS_CONTROL_DISABLE;

					if (SetCommState(hCom, &dcb) == FALSE) {
						wsprintf(errmsg, "SetCommState error: %d", GetLastError());
						MessageBox(hwnd, errmsg, NULL, MB_OK);

						goto close_handle;
					}

					COMMTIMEOUTS to;
					if (GetCommTimeouts(hCom, &to) == FALSE) {
						wsprintf(errmsg, "GetCommTimeouts error: %d", GetLastError());
						MessageBox(hwnd, errmsg, NULL, MB_OK);

						goto close_handle;
					}

					to.ReadIntervalTimeout = 0;
					to.ReadTotalTimeoutMultiplier = 0;
					to.ReadTotalTimeoutConstant = 3000;
					to.WriteTotalTimeoutMultiplier = 0;
					to.WriteTotalTimeoutConstant = 1000;
					
					if (SetCommTimeouts(hCom, &to) == FALSE) {
						wsprintf(errmsg, "SetCommTimeouts error: %d", GetLastError());
						MessageBox(hwnd, errmsg, NULL, MB_OK);

						goto close_handle;
					}

					DWORD dwWritten;
					dwWritten = 0;
					if (WriteFile(hCom, "\x02PON\x03", lstrlen("\x02PON\x03"), &dwWritten, NULL) == FALSE) {
						wsprintf(errmsg, "WriteFile error: %d", GetLastError());
						MessageBox(hwnd, errmsg, NULL, MB_OK);

						goto close_handle;
					}

					Sleep(200);

					DWORD dwRead;
					dwRead = 0;
					if (ReadFile(hCom, data, 5, &dwRead, NULL) == FALSE) {
						wsprintf(errmsg, "ReadFile error: %d", GetLastError());
						MessageBox(hwnd, errmsg, NULL, MB_OK);
						
						goto close_handle;
					} else {
						wsprintf(errmsg, "%d bytes Read: %d", dwRead, GetLastError());
						MessageBox(hwnd, errmsg, NULL, MB_OK);

						MessageBox(hwnd, data, "Read", MB_OK);
					}

close_handle:
					CloseHandle(hCom);
				} else {
					MessageBox(hwnd, "'COM1' がオープンできません。", NULL, MB_OK);
				}
				return TRUE;
			} else if (wID == IDCANCEL) {
				EndDialog(hwnd, 1);
				return TRUE;
			}
		}
		break;

	case WM_CLOSE:
		EndDialog(hwnd, 0);
		return TRUE;
	}

	return FALSE;
}
Пример #30
0
int set_serial (struct serial *s, struct serial_mode *serial_mode)

{

#ifdef WIN32

	COMMTIMEOUTS timeouts;
	DCB dcbSerial;
	memset (&dcbSerial, 0, sizeof (dcbSerial));
	dcbSerial.DCBlength = sizeof (dcbSerial);
	if (!GetCommState (s->h, &dcbSerial))
	{
		return (-1);
	}
	dcbSerial.BaudRate = serial_mode->baud_rate;
	dcbSerial.ByteSize = serial_mode->data_bits;
	switch (serial_mode->stop_bits)
	{
	case 1:
		dcbSerial.StopBits = ONESTOPBIT;
		break;
	case 2:
		dcbSerial.StopBits = TWOSTOPBITS;
		break;
	default:
		error (1, 0, "invalid stop bit setting");
	}
	switch (serial_mode->parity)
	{
	case UART_ODDPARITY:
		dcbSerial.Parity = ODDPARITY;
		dcbSerial.fParity = TRUE;
		break;
	case UART_EVENPARITY:
		dcbSerial.Parity = EVENPARITY;
		dcbSerial.fParity = TRUE;
		break;
	case UART_NOPARITY:
		dcbSerial.Parity = NOPARITY;
		dcbSerial.fParity = FALSE;
		break;
	default:
		error (1, 0, "invalid parity serial_mode");
	}
	if (!SetCommState (s->h, &dcbSerial))
	{
		error (0, 0, "could not set serial port settings");
		return (-1);
	}
	timeouts.ReadIntervalTimeout = 0;
	timeouts.ReadTotalTimeoutConstant = 10;
	timeouts.ReadTotalTimeoutMultiplier = 0;
	timeouts.WriteTotalTimeoutConstant = 10;
	timeouts.WriteTotalTimeoutMultiplier = 10;
	if (!SetCommTimeouts (s->h, &timeouts))
	{
		return (-1);
	}

#else

	struct termios termios;
	speed_t speed;
	tcgetattr (s->fd, &termios);
	cfmakeraw (&termios);
	termios.c_cflag &= ~CSIZE;
	switch (serial_mode->data_bits)
	{
	case 8:
		termios.c_cflag |= CS8;
		break;
	case 7:
		termios.c_cflag |= CS7;
		break;
	case 6:
		termios.c_cflag |= CS6;
		break;
	case 5:
		termios.c_cflag |= CS5;
		break;
	default:
		error (1, 0, "invalid serial byte size");
	}
	switch (serial_mode->stop_bits)
	{
	case 2:
		termios.c_cflag |= CSTOPB;
		break;
	case 1:
		termios.c_cflag &= ~CSTOPB;
		break;
	default:
		error (1, 0, "invalid number of stop bits");
	}
	switch (serial_mode->parity)
	{
	case UART_ODDPARITY:
		termios.c_cflag |= PARENB;
		termios.c_cflag |= PARODD;
		break;
	case UART_EVENPARITY:
		termios.c_cflag |= PARENB;
		termios.c_cflag &= ~PARODD;
		break;
	case UART_NOPARITY:
		termios.c_cflag &= ~PARENB;
		break;
	default:
		error (1, 0, "invalid parity serial_mode");
	}
	if (baudrate (serial_mode->baud_rate, &speed) == -1)
	{
		error (0, 0, "warning: unsupported baud rate: %d", serial_mode->baud_rate);
		return (-1);
	}
	if (cfsetspeed (&termios, speed) == -1) error (1, 0, "could not set serial baud rate");
	termios.c_cc [VTIME] = 1;
	termios.c_cc [VMIN] = 0;
	if (tcsetattr (s->fd, TCSANOW, &termios) == -1) error (1, 0, "could not set serial attributes");

#endif

	return (0);
}