void ReadConsoleWriteSerial()

in BusTools/MinComm/main.cpp [293:372]


void ReadConsoleWriteSerial (HANDLE serialHandle)
{
    HANDLE stdIn = GetStdHandle(STD_INPUT_HANDLE);
    if (!SetConsoleMode(stdIn, ENABLE_PROCESSED_INPUT)) {
        throw wexception(
            L"Failed to set console mode for stdin. (GetLastError() = 0x%x)",
            GetLastError());
    }

    Event overlappedEvent(CreateEventW(NULL, TRUE, FALSE, NULL));
    if (!overlappedEvent.IsValid()) {
        throw wexception(
            L"Failed to create event for overlapped IO. "
            L"(GetLastError() = 0x%x)",
            GetLastError());
    }

    for (;;) {
        WCHAR wbuf[512];
        DWORD charsRead;
        if (!ReadConsole(
                stdIn,
                wbuf,
                ARRAYSIZE(wbuf),
                &charsRead,
                NULL)) {

            throw wexception(
                L"Failed to read console. (GetLastError = 0x%x)",
                GetLastError());
        }

        // convert to ANSI
        CHAR buf[ARRAYSIZE(wbuf)];
        int bytesConverted = WideCharToMultiByte(
                CP_ACP,
                0,          // dwFlags
                wbuf,
                charsRead,
                buf,
                sizeof(buf),
                NULL,       // lpDefaultChar
                NULL);      // lpUsedDefaultChar
        if (!bytesConverted) {
            throw wexception(
                L"Failed to convert wide string to ANSI. "
                L"(GetLastError() = 0x%x)",
                GetLastError());
        }


        auto overlapped = OVERLAPPED();
        overlapped.hEvent = overlappedEvent.Get();

        DWORD bytesWritten;
        if (!WriteFile(
                serialHandle,
                buf,
                bytesConverted,
                &bytesWritten,
                &overlapped) && (GetLastError() != ERROR_IO_PENDING)) {

            throw wexception(
                L"Write to serial device failed. (GetLastError() = 0x%x)",
                GetLastError());
        }

        if (!GetOverlappedResult(
                serialHandle,
                &overlapped,
                &bytesWritten,
                TRUE)) {

            throw wexception(
                L"GetOverlappedResult() for SetCommTimeouts() failed. "
                L"(GetLastError() = 0x%x)",
                GetLastError());
        }
    }
}