GetCommState always false - c++

I was trying to make a simple console program that reads all signals from my mouse plugged in with USB. I faced a problem: GetCommState(nCom, &dcb) always returns zero, which is not very usefull for my task.
Here is the code:
int _tmain(int argc, TCHAR *argv[]) {
DCB dcb;
HANDLE hCom;
BOOL fSuccess;
TCHAR *pcCommPort = TEXT("\\\\.\\HCD0"); // USB name
// Open a handle to the specified com port.
hCom = CreateFile(pcCommPort,
GENERIC_READ | GENERIC_WRITE,
0, // must be opened with exclusive-access
NULL, // default security attributes
OPEN_EXISTING, // must use OPEN_EXISTING
0, // not overlapped I/O
NULL); // hTemplate must be NULL for comm devices
if (hCom == INVALID_HANDLE_VALUE) {
// Handle the error.
printf("CreateFile failed with error %d.\n", GetLastError());
Sleep(15000);
return (1);
}
// Initialize the DCB structure.
SecureZeroMemory(&dcb, sizeof(DCB));
dcb.DCBlength = sizeof(DCB);
// Build on the current configuration by first retrieving all current
// settings.
fSuccess = GetCommState(hCom, &dcb);
if (!fSuccess) {
// Handle the error.
printf("GetCommState failed with error %s.\n", GetLastError());
printf("Cannot get first time");
Sleep(12000);
return (2);
}
.......
GetLastError() returns 1, but lurking for this problem gave me no results.
Thats simply a copypaste from msdn example, but it occurs that it didn't work for me.
Tell me please: what should i change to make it return nonzero and let me proceed with another part of task.

USB mice have nothing to do with COM ports, thus calling GetCommState makes no sense at all.
A serial mouse is ancient hardware that is outdated since about 1995. Modern USB mice are based on USB HID protocol.

Related

time out for USB ReadFile() replacing Serial Port code used with serial communications device

I'm working on extending a receipt printing Serial Port (COM) interface for a thermal receipt printer to use a USB interface without needing a Virtual Serial Port. I have a working prototype that will enumerate over the attached USB devices, locate the USB path for a device with a specific vendor id and product id, and open a connection to the device using CreateFile().
The existing Serial Port code uses the Windows API wrapped in a set of functions. The approach I'm taking is to add additional code using the same set of functions but that depend on a USB connection rather than a Serial Port connection. I have previously used the same approach to allow the use of a kitchen printer over either a Serial Port or over a WiFi/LAN connection with minimal changes to existing code successfully.
Unfortunately the existing code that uses the function library depends on the functions to use ReadFile() with a time out specified so that if the thermal printer does not respond to a status request within a reasonable time, the application can mark it as down and allow operations to continue or to use a backup or secondary printer.
How do I specify a time out for a ReadFile() on a file handle from CreateFile() that opens a connection to a communications devices using a USB pathname?
A consideration is this is multi-threaded code used for more than one serial communications device (receipt printer, kitchen printer, scale, etc.) however a thread will have exclusive access to a particular device (kitchen printing functionality opens serial port to kitchen printer only, scale reading functionality opens serial port to scale only, etc.).
In the existing Serial Port code, the function used to set timeouts, SetCommTimeouts(), for a Serial Port connection opened with CreateFile() does not work for a USB connection opened with CreateFile() (see SetupComm, SetCommState, SetCommTimeouts fail with USB device). This means some other mechanism is needed to provide a way to allow for an I/O failure due to a time out when using a USB device pathname.
We are using the following code segment to open a Serial Port, whether to a hardware COM port or a Virtual Serial Port emulating a hardware COM port:
// see Microsoft document HOWTO: Specify Serial Ports Larger than COM9.
// https://support.microsoft.com/en-us/kb/115831
// CreateFile() can be used to get a handle to a serial port. The "Win32 Programmer's Reference" entry for "CreateFile()"
// mentions that the share mode must be 0, the create parameter must be OPEN_EXISTING, and the template must be NULL.
//
// CreateFile() is successful when you use "COM1" through "COM9" for the name of the file;
// however, the value INVALID_HANDLE_VALUE is returned if you use "COM10" or greater.
//
// If the name of the port is \\.\COM10, the correct way to specify the serial port in a call to
// CreateFile() is "\\\\.\\COM10".
//
// NOTES: This syntax also works for ports COM1 through COM9. Certain boards will let you choose
// the port names yourself. This syntax works for those names as well.
wsprintf(wszPortName, TEXT("\\\\.\\COM%d"), usPortId);
/* Open the serial port. */
/* avoid to failuer of CreateFile */
for (i = 0; i < 10; i++) {
hHandle = CreateFile (wszPortName, /* Pointer to the name of the port, PifOpenCom() */
GENERIC_READ | GENERIC_WRITE, /* Access (read-write) mode */
0, /* Share mode */
NULL, /* Pointer to the security attribute */
OPEN_EXISTING,/* How to open the serial port */
0, /* Port attributes */
NULL); /* Handle to port with attribute */
/* to copy */
/* If it fails to open the port, return FALSE. */
if ( hHandle == INVALID_HANDLE_VALUE ) { /* Could not open the port. */
dwError = GetLastError ();
if (dwError == ERROR_FILE_NOT_FOUND || dwError == ERROR_INVALID_NAME || dwError == ERROR_ACCESS_DENIED) {
LeaveCriticalSection(&g_SioCriticalSection);
// the COM port does not exist. probably a Virtual Serial Communications Port
// from a USB device which was either unplugged or turned off.
// or the COM port or Virtual Serial Communications port is in use by some other application.
return PIF_ERROR_COM_ACCESS_DENIED;
}
PifLog (MODULE_PIF_OPENCOM, LOG_ERROR_PIFSIO_CODE_01);
PifLog (MODULE_ERROR_NO(MODULE_PIF_OPENCOM), (USHORT)dwError);
PifLog(MODULE_DATA_VALUE(FAULT_AT_PIFOPENCOM), usPortId);
PifSleep(500);
} else {
break;
}
}
if ( hHandle == INVALID_HANDLE_VALUE ) { /* Could not open the port. */
wsprintf(wszDisplay, TEXT("CreateFile, COM%d, Last Error =%d\n"), usPortId, dwError);
OutputDebugString(wszDisplay);
LeaveCriticalSection(&g_SioCriticalSection);
return PIF_ERROR_COM_ERRORS;
}
/* clear the error and purge the receive buffer */
dwError = (DWORD)(~0); // set all error code bits on
ClearCommError(hHandle, &dwError, NULL);
PurgeComm( hHandle, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR ) ;
The ReadFile() is wrapped within a function and looks like:
fResult = ReadFile(hHandle, pBuffer, (DWORD)usBytes, &dwBytesRead, NULL);
if (PifSioCheckPowerDown(usPort, aPifSioTable) == TRUE) {
return PIF_ERROR_COM_POWER_FAILURE;
}
if (fResult) {
if (!dwBytesRead) return PIF_ERROR_COM_TIMEOUT;
return (SHORT)dwBytesRead;
} else {
SHORT sErrorCode = 0; // error code from PifSubGetErrorCode(). must call after GetLastError().
dwError = GetLastError();
PifLog (MODULE_PIF_READCOM, LOG_ERROR_PIFSIO_CODE_06);
PifLog (MODULE_ERROR_NO(MODULE_PIF_READCOM), (USHORT)dwError);
sErrorCode = PifSubGetErrorCode(hHandle);
PifLog (MODULE_ERROR_NO(MODULE_PIF_READCOM), (USHORT)abs(sErrorCode));
PifLog (MODULE_DATA_VALUE(MODULE_PIF_READCOM), usPort);
return (sErrorCode);
}
I found a number of similar posted questions which involved pipes however the same approach of using overlapped I/O applies.
Breaking ReadFile() blocking - Named Pipe (Windows API)
Win32 API: ReadFile timeout
Device driver: Windows ReadFile function timeout
I also found the following article on the web Peter's blog: Getting a handle on usbprint.sys which provides code and a description of how to find a USB pathname for a USB connected device. I have used some of that code sample in the class below.
I also found an article on codeproject.com, Enumerating windows device by Chuan-Liang Teng which contained an example of enumerating over the connected USB devices and interrogating various settings and details about the devices. The code from that article, though old, was helpful though not necessary for this particular application.
I have a prototype C++ class using overlapped I/O which seems to be replicating the behavior seen with a Serial Port connection using a USB connection to a thermal printer. The full source and Visual Studio 2017 solution and project files are in my GitHub repository https://github.com/RichardChambers/utilities_tools/tree/main/UsbWindows as this snip has the most pertinent parts.
I have done a simple test with modified code in the point of sale application and am now in the process of integrating this into the existing thermal receipt printer source code which already works with a Serial Port.
#include <windows.h>
#include <setupapi.h>
#include <initguid.h>
#include <iostream>
// This is the GUID for the USB device class.
// It is defined in the include file Usbiodef.h of the Microsoft Windows Driver Kit.
// See also https://msdn.microsoft.com/en-us/library/windows/hardware/ff545972(v=vs.85).aspx which
// provides basic documentation on this GUID.
DEFINE_GUID(GUID_DEVINTERFACE_USB_DEVICE, 0xA5DCBF10L, 0x6530, 0x11D2, 0x90, 0x1F, 0x00, 0xC0, 0x4F, 0xB9, 0x51, 0xED);
class UsbSerialDevice
{
public:
// See https://learn.microsoft.com/en-us/windows/win32/ipc/named-pipe-server-using-overlapped-i-o?redirectedfrom=MSDN
// to implement time outs for Write and for Read.
UsbSerialDevice(const wchar_t* wszVendorIdIn = nullptr);
~UsbSerialDevice();
int CreateEndPoint(const wchar_t* wszVendorId = nullptr, DWORD dwDesiredAccess = (GENERIC_READ | GENERIC_WRITE));
void CloseEndPoint(void);
int ListEndPoint(const wchar_t* wszVendorIdIn);
int ReadStream(void* bString, size_t nBytes);
int WriteStream(void* bString, size_t nBytes);
DWORD SetWriteTimeOut(DWORD msTimeout);
DWORD SetReadTimeOut(DWORD msTimeout);
DWORD m_dwError; // GetLastError() for last action
DWORD m_dwErrorWrite; // GetLastError() for last write
DWORD m_dwErrorRead; // GetLastError() for last read
DWORD m_dwBytesWritten; // number of bytes last write
DWORD m_dwBytesRead; // number of bytes last read
DWORD m_dwWait; // WaitForSingleObject() return value
private:
HANDLE m_hFile;
OVERLAPPED m_oOverlap;
COMMTIMEOUTS m_timeOut;
const unsigned short m_idLen = 255;
wchar_t m_wszVendorId[255 + 1] = { 0 };
};
UsbSerialDevice::UsbSerialDevice(const wchar_t* wszVendorIdIn) :
m_dwError(0),
m_dwErrorWrite(0),
m_dwErrorRead(0),
m_dwBytesWritten(0),
m_dwBytesRead(0),
m_dwWait(0),
m_hFile(INVALID_HANDLE_VALUE)
{
memset(&m_oOverlap, 0, sizeof(m_oOverlap));
m_oOverlap.hEvent = INVALID_HANDLE_VALUE;
if (wszVendorIdIn != nullptr) ListEndPoint(wszVendorIdIn);
}
void UsbSerialDevice::CloseEndPoint(void )
{
if (m_hFile && m_hFile != INVALID_HANDLE_VALUE) CloseHandle(m_hFile);
if (m_oOverlap.hEvent && m_oOverlap.hEvent != INVALID_HANDLE_VALUE) CloseHandle(m_oOverlap.hEvent);
}
UsbSerialDevice::~UsbSerialDevice()
{
CloseEndPoint();
}
/*
* Returns: -1 - file handle is invalid
* 0 - write failed. See m_dwErrorWrite for GetLastError() value
* 1 - write succedded.
*/
int UsbSerialDevice::WriteStream(void* bString, size_t nBytes)
{
SetLastError(0);
m_dwError = m_dwErrorWrite = 0;
m_dwBytesWritten = 0;
m_dwWait = WAIT_FAILED;
if (m_hFile && m_hFile != INVALID_HANDLE_VALUE) {
BOOL bWrite = WriteFile(m_hFile, bString, nBytes, 0, &m_oOverlap);
m_dwError = m_dwErrorWrite = GetLastError();
if (!bWrite && m_dwError == ERROR_IO_PENDING) {
SetLastError(0);
m_dwError = m_dwErrorWrite = 0;
m_dwWait = WaitForSingleObject(m_oOverlap.hEvent, m_timeOut.WriteTotalTimeoutConstant);
BOOL bCancel = FALSE;
switch (m_dwWait) {
case WAIT_OBJECT_0: // The state of the specified object is signaled.
break;
case WAIT_FAILED: // The function has failed. To get extended error information, call GetLastError.
m_dwError = m_dwErrorWrite = GetLastError();
bCancel = CancelIo(m_hFile);
break;
case WAIT_TIMEOUT: // The time-out interval elapsed, and the object's state is nonsignaled.
case WAIT_ABANDONED: // thread owning mutex terminated before releasing or signaling object.
bCancel = CancelIo(m_hFile);
m_dwError = m_dwErrorRead = ERROR_COUNTER_TIMEOUT;
break;
}
bWrite = GetOverlappedResult(m_hFile, &m_oOverlap, &m_dwBytesRead, FALSE);
}
return bWrite; // 0 or FALSE if failed, 1 or TRUE if succeeded.
}
return -1;
}
/*
* Returns: -1 - file handle is invalid
* 0 - read failed. See m_dwErrorRead for GetLastError() value
* 1 - read succedded.
*/
int UsbSerialDevice::ReadStream(void* bString, size_t nBytes)
{
SetLastError(0);
m_dwError = m_dwErrorRead = 0;
m_dwBytesRead = 0;
m_dwWait = WAIT_FAILED;
if (m_hFile && m_hFile != INVALID_HANDLE_VALUE) {
BOOL bRead = ReadFile(m_hFile, bString, nBytes, &m_dwBytesRead, &m_oOverlap);
m_dwError = m_dwErrorRead = GetLastError();
if (!bRead && m_dwError == ERROR_IO_PENDING) {
SetLastError(0);
m_dwError = m_dwErrorRead = 0;
m_dwWait = WaitForSingleObject(m_oOverlap.hEvent, m_timeOut.ReadTotalTimeoutConstant);
BOOL bCancel = FALSE;
switch (m_dwWait) {
case WAIT_OBJECT_0: // The state of the specified object is signaled.
break;
case WAIT_FAILED: // The function has failed. To get extended error information, call GetLastError.
m_dwError = m_dwErrorWrite = GetLastError();
bCancel = CancelIo(m_hFile);
break;
case WAIT_TIMEOUT: // The time-out interval elapsed, and the object's state is nonsignaled.
case WAIT_ABANDONED: // thread owning mutex terminated before releasing or signaling object.
bCancel = CancelIo(m_hFile);
m_dwError = m_dwErrorRead = ERROR_COUNTER_TIMEOUT;
break;
}
bRead = GetOverlappedResult(m_hFile, &m_oOverlap, &m_dwBytesRead, FALSE);
}
return bRead; // 0 or FALSE if failed, 1 or TRUE if succeeded.
}
return -1;
}
int UsbSerialDevice::ListEndPoint(const wchar_t* wszVendorIdIn)
{
m_dwError = ERROR_INVALID_HANDLE;
if (wszVendorIdIn == nullptr) return 0;
HDEVINFO hDevInfo;
// we need to make sure the vendor and product id codes are in lower case
// as this is needed for the CreateFile() function to open the connection
// to the USB device correctly. this lower case conversion applies to
// any alphabetic characters in the identifier.
//
// for example "VID_0FE6&PID_811E" must be converted to "vid_0fe6&pid_811e"
wchar_t wszVendorId[256] = { 0 };
for (unsigned short i = 0; i < 255 && (wszVendorId[i] = towlower(wszVendorIdIn[i])); i++);
// We will try to get device information set for all USB devices that have a
// device interface and are currently present on the system (plugged in).
hDevInfo = SetupDiGetClassDevs(&GUID_DEVINTERFACE_USB_DEVICE, NULL, 0, DIGCF_DEVICEINTERFACE | DIGCF_PRESENT);
if (hDevInfo != INVALID_HANDLE_VALUE)
{
DWORD dwMemberIdx;
BOOL bContinue = TRUE;
SP_DEVICE_INTERFACE_DATA DevIntfData;
// Prepare to enumerate all device interfaces for the device information
// set that we retrieved with SetupDiGetClassDevs(..)
DevIntfData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
dwMemberIdx = 0;
// Next, we will keep calling this SetupDiEnumDeviceInterfaces(..) until this
// function causes GetLastError() to return ERROR_NO_MORE_ITEMS. With each
// call the dwMemberIdx value needs to be incremented to retrieve the next
// device interface information.
for (BOOL bContinue = TRUE; bContinue; ) {
PSP_DEVICE_INTERFACE_DETAIL_DATA DevIntfDetailData;
SP_DEVINFO_DATA DevData;
DWORD dwSize;
dwMemberIdx++;
SetupDiEnumDeviceInterfaces(hDevInfo, NULL, &GUID_DEVINTERFACE_USB_DEVICE, dwMemberIdx, &DevIntfData);
if (GetLastError() == ERROR_NO_MORE_ITEMS) break;
// As a last step we will need to get some more details for each
// of device interface information we are able to retrieve. This
// device interface detail gives us the information we need to identify
// the device (VID/PID), and decide if it's useful to us. It will also
// provide a DEVINFO_DATA structure which we can use to know the serial
// port name for a virtual com port.
DevData.cbSize = sizeof(DevData);
// Get the required buffer size. Call SetupDiGetDeviceInterfaceDetail with
// a NULL DevIntfDetailData pointer, a DevIntfDetailDataSize
// of zero, and a valid RequiredSize variable. In response to such a call,
// this function returns the required buffer size at dwSize.
SetupDiGetDeviceInterfaceDetail(hDevInfo, &DevIntfData, NULL, 0, &dwSize, NULL);
// Allocate memory for the DeviceInterfaceDetail struct. Don't forget to
// deallocate it later!
DevIntfDetailData = (PSP_DEVICE_INTERFACE_DETAIL_DATA)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwSize);
DevIntfDetailData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);
if (SetupDiGetDeviceInterfaceDetail(hDevInfo, &DevIntfData, DevIntfDetailData, dwSize, &dwSize, &DevData))
{
if (wcsstr(DevIntfDetailData->DevicePath, wszVendorId)) {
wcscpy_s(m_wszVendorId, DevIntfDetailData->DevicePath);
}
}
HeapFree(GetProcessHeap(), 0, DevIntfDetailData);
}
SetupDiDestroyDeviceInfoList(hDevInfo);
}
return 0;
}
int UsbSerialDevice::CreateEndPoint(const wchar_t* wszVendorIdIn, DWORD dwDesiredAccess)
{
if (wszVendorIdIn) {
ListEndPoint(wszVendorIdIn);
}
m_dwError = ERROR_INVALID_HANDLE;
// Finally we can start checking if we've found a useable device,
// by inspecting the DevIntfDetailData->DevicePath variable.
//
// The DevicePath looks something like this for a Brecknell 67xx Series Serial Scale
// \\?\usb#vid_1a86&pid_7523#6&28eaabda&0&2#{a5dcbf10-6530-11d2-901f-00c04fb951ed}
//
// The VID for a particular vendor will be the same for a particular vendor's equipment.
// The PID is variable for each device of the vendor.
//
// As you can see it contains the VID/PID for the device, so we can check
// for the right VID/PID with string handling routines.
// See https://github.com/Microsoft/Windows-driver-samples/blob/master/usb/usbview/vndrlist.h
// See https://blog.peter.skarpetis.com/archives/2005/04/07/getting-a-handle-on-usbprintsys/
// which describes a sample USB thermal receipt printer test application.
SetLastError(0);
m_hFile = CreateFile(m_wszVendorId, dwDesiredAccess, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_ALWAYS, FILE_FLAG_OVERLAPPED, 0);
if (m_hFile == INVALID_HANDLE_VALUE) {
m_dwError = GetLastError();
// wprintf(_T(" CreateFile() failed. GetLastError() = %d\n"), m_dwError);
}
else {
m_oOverlap.hEvent = CreateEvent(
NULL, // default security attribute
TRUE, // manual-reset event
TRUE, // initial state = signaled
NULL); // unnamed event object
m_timeOut.ReadIntervalTimeout = 0;
m_timeOut.ReadTotalTimeoutMultiplier = 0;
m_timeOut.ReadTotalTimeoutConstant = 5000;
m_timeOut.WriteTotalTimeoutMultiplier = 0;
m_timeOut.WriteTotalTimeoutConstant = 5000;
m_dwError = 0; // GetLastError();
return 1;
}
return 0;
}

Configuring serial port with Windows API: CreateFile failed with error 2 (ERROR_FILE_NOT_FOUND)

I'm trying to create a C++ program to communicate with a serial port device using Windows API in Visual Studio Community 2017 on Windows 7. Running this example from MSDN with one change - using this:
const wchar_t *pcCommPort = TEXT("\\.\COM16"); // Most systems have a COM1 port
instead of this (otherwise it wouldn't compile):
TCHAR *pcCommPort = TEXT("COM1"); // Most systems have a COM1 port
I get a CreateFile error 2 (ERROR_FILE_NOT_FOUND). I'm quite clueless what's going wrong here.
Here's the code:
#include "stdafx.h"
void PrintCommState(DCB dcb)
{
// Print some of the DCB structure values
_tprintf(TEXT("\nBaudRate = %d, ByteSize = %d, Parity = %d, StopBits = %d\n"),
dcb.BaudRate,
dcb.ByteSize,
dcb.Parity,
dcb.StopBits);
}
int _tmain(int argc, TCHAR *argv[])
{
DCB dcb;
HANDLE hCom;
BOOL fSuccess;
const wchar_t *pcCommPort = TEXT("\\.\COM16"); // Most systems have a COM1 port
// Open a handle to the specified com port.
hCom = CreateFile(pcCommPort,
GENERIC_READ | GENERIC_WRITE,
0, // must be opened with exclusive-access
NULL, // default security attributes
OPEN_EXISTING, // must use OPEN_EXISTING
0, // not overlapped I/O
NULL); // hTemplate must be NULL for comm devices
if (hCom == INVALID_HANDLE_VALUE)
{
// Handle the error.
printf("CreateFile failed with error %d.\n", GetLastError());
system("PAUSE");
return (1);
}
// Initialize the DCB structure.
SecureZeroMemory(&dcb, sizeof(DCB));
dcb.DCBlength = sizeof(DCB);
// Build on the current configuration by first retrieving all current
// settings.
fSuccess = GetCommState(hCom, &dcb);
if (!fSuccess)
{
// Handle the error.
printf("GetCommState failed with error %d.\n", GetLastError());
return (2);
}
PrintCommState(dcb); // Output to console
// Fill in some DCB values and set the com state:
// 57,600 bps, 8 data bits, no parity, and 1 stop bit.
dcb.BaudRate = CBR_9600; // baud rate
dcb.ByteSize = 8; // data size, xmit and rcv
dcb.Parity = NOPARITY; // parity bit
dcb.StopBits = ONESTOPBIT; // stop bit
fSuccess = SetCommState(hCom, &dcb);
if (!fSuccess)
{
// Handle the error.
printf("SetCommState failed with error %d.\n", GetLastError());
return (3);
}
// Get the comm config again.
fSuccess = GetCommState(hCom, &dcb);
if (!fSuccess)
{
// Handle the error.
printf("GetCommState failed with error %d.\n", GetLastError());
return (2);
}
PrintCommState(dcb); // Output to console
_tprintf(TEXT("Serial port %s successfully reconfigured.\n"), pcCommPort);
return (0);
}
There are two different defines that control the ANSI/Unicode character stuff:
#define UNICODE controls the Windows SDK API (LPTSTR and TEXT)
#define _UNICODE controls the C Run Time (TCHAR, _TEXT and _T)
You normally define none or both and if you don't you have to use the correct combinations:
const TCHAR* cstr = _T("Hello");
LPCTSTR winstr = TEXT("World");
The other issue with your code is that you are using TCHAR* and not const TCHAR*. Depending on your compiler version and switches, literal strings might be located in the read-only data section of the binary so make sure the type is a pointer to a constant string.
If you are still unsure of the sizes you can do this:
LPCTSTR x;
printf("TEXT=%d LPCTSTR=%d _T=%d TCHAR=%d\n", sizeof(TEXT("")), sizeof(*x), sizeof(_T("")), sizeof(TCHAR));
I just tested on a virtual machine with a COM port and the plain name works just fine:
LPCTSTR pcCommPort = TEXT("COM1");
HANDLE hCom = CreateFile(pcCommPort,
GENERIC_READ | GENERIC_WRITE,
0, // must be opened with exclusive-access
NULL, // default security attributes
OPEN_EXISTING, // must use OPEN_EXISTING
0, // not overlapped I/O
NULL); // hTemplate must be NULL for comm devices
If you want to use a COM port above 9 you have to use the Win32 device path syntax:
LPCTSTR pcCommPortWin32DevicePath = TEXT("\\\\.\\COM16");
HANDLE hCom = CreateFile(pcCommPortWin32DevicePath, ...);
(MSDN describes the string as it should look in memory, not in your code. Your clue to this is the single slash in the example string. This means you must double all backslashes to get a correct C literal string.)
You need to escape backslashes in string literals, eg
const TCHAR *pcCommPort = TEXT("\\\\.\\COM16");

Which ReadFile parameter in this code is incorrect? (Error code 87)

(Edit: I didn't exclude any code except the headers and the main() function's brackets. Nothing is written between lines of code listed here.)
.
I used the ReadFile function to read this COM3 port (which returned no INVALID_HANDLE_VALUE or ERROR_FILE_NOT_FOUND):
LPCTSTR portName = "COM3" ;
HANDLE hSerial;
hSerial = CreateFile(portName,
GENERIC_READ | GENERIC_WRITE,
0, // exclusive access
NULL, // default security attributes
OPEN_EXISTING,
FILE_FLAG_OVERLAPPED,
NULL);
And the ReadFile function in question uses following parameters:
DWORD n = 512 ;
char szBuff[n] = {0};
DWORD dwBytesRead = 0;
if(!ReadFile(hSerial, szBuff, n, &dwBytesRead, NULL))
{
cout << "ReadFile error. Error code: " << GetLastError() << endl ;
cin.get() ;
return 0 ;
}
What changes should I introduce to cause the read to succeed?
(I searched through the function's documentation and other StackOverflow questions, tested lots of things, but couldn't find an answer.)
In ReadFile documentation you can read:
lpOverlapped [in, out, optional]
A pointer to an OVERLAPPED structure is required if the hFile parameter was opened with FILE_FLAG_OVERLAPPED, otherwise it can be NULL.
so since you specified FILE_FLAG_OVERLAPPED in CreateFile you should provide OVERLAPPED in ReadFile.
In CreateFile you can read on parameters for Communications Resources:
... and the handle can be opened for overlapped I/O.
so you can skip FILE_FLAG_OVERLAPPED in CreateFile
Marcin Jędrzejewski's answer is correct about the mismatch between the overlapped IO Flag and the ReadFile function, but I will leave this up just to be helpful.
You are missing a lot of initialisation which may be helpful to you when operating a COM port.
This code is used to open, configure, and read from a COM port on windows using C++.
FOR REFERENCE
READ_BUFFER_SIZE = 1024;
WRITE_BUFFER_SIZE = 1024;
COM_READ_BUFFER_SIZE = 1024;
COM_WRITE_BUFFER_SIZE = 1024;
READ_TIMEOUT = 50;
WRITE_TIMEOUT = 100;
port = "\\.\COM6"
portFormat = "9600,N,8,1" /* for information on this, google the MODE command for windows. */
HANDLE hComPort;
DCB dcbComConfig;
OPENING COM PORT
DWORD dwStoredFlags = EV_BREAK | EV_ERR | EV_RXCHAR;
COMMTIMEOUTS timeouts;
FillMemory(&dcbComConfig, sizeof(dcbComConfig), 0);
dcbComConfig.DCBlength = sizeof(dcbComConfig);
/* assign a COM format to the COM Port. */
if(!BuildCommDCB(portFormat, &dcbComConfig))
{
printf("Failed to build comm format data %s\n", portFormat);
}
/* Open the COM port with overlapped IO. */
hComPort = CreateFile(port, GENERIC_READ | GENERIC_WRITE, 0, 0,
OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
if (hComPort == INVALID_HANDLE_VALUE)
{
printf("Error opening port %s\n", port);
}
/* Set the COM Ports internal Read and Write buffer sizes. */
if(!SetupComm(hComPort, COM_READ_BUFFER_SIZE, COM_WRITE_BUFFER_SIZE))
{
printf("Could not set COM buffers\n");
}
/* assign the previously created COM Format to the COM Port. */
if(!SetCommState(hComPort, &dcbComConfig))
{
printf("Error setting com to format data.\n");
}
/* Mask what events you want to look for in the COM Port. */
if (!SetCommMask(hComPort, dwStoredFlags))
{
printf("Error setting communications mask\n");
}
/*-- Read Timeouts set like this so we can use the event based reading. --*/
timeouts.ReadIntervalTimeout = MAXDWORD;
timeouts.ReadTotalTimeoutMultiplier = 0;
timeouts.ReadTotalTimeoutConstant = 0;
timeouts.WriteTotalTimeoutMultiplier = 10;
timeouts.WriteTotalTimeoutConstant = 100;
if (!SetCommTimeouts(hComPort, &timeouts))
{
printf("Error setting time-outs.\n");
}
READING COM PORT
DWORD dwRead = 0;
DWORD dwComEvent = EV_RXCHAR;
DWORD lpErrors = 0;
char readBuffer[READ_BUFFER_SIZE];
/* Create the Overlapped IO Read Event. */
OVERLAPPED osRead = {0};
osRead.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
/* Used to monitor the COM Port State. */
COMSTAT ComStatus;
/* Loop at 20Hz to read the COM Port until a Kill event has been set. */
while(WaitForSingleObject(hKillEvent, 50) == WAIT_TIMEOUT)
{
/* Wait for a COM Event to occur ( Read Event in this Case ). */
if (WaitCommEvent(hComPort, &dwComEvent , NULL))
{
/* If the COM Port had an error Clear it. */
ClearCommError(hComPort, &lpErrors, &ComStatus);
/*-- Reset read operation's OVERLAPPED structure's hEvent --*/
ResetEvent(osRead.hEvent);
if (ReadFile(hComPort, readBuffer, ComStatus.cbInQue, &dwRead, &osRead))
{
/*-- bytes have been read; process it --*/
USE_DATA(readBuffer, dwRead);
}
else
{
/*-- An error occurred in the ReadFile call --*/
printf("ReadFile encountered an error.\n");
break;
}
}
else
{
/*-- Error in WaitCommEvent --*/
printf("WaitCommEvent encountered an error.\n");
break;
}
}
/* Close the Overlapped IO Read Event. */
CloseHandle(osRead.hEvent);
The top answer is correct. In this case, opening with FILE_FLAG_OVERLAPPED, ReadFile expects an OVERLAPPED structure as last argument.
Would like to add that you can also get 'parameter is incorrect' error if you do supply an OVERLAPPED struct, but forget to ZeroMemory it.
From the documentation:
Any unused members of this structure should always be initialized to zero before the structure is used in a function call. Otherwise, the function may fail and return ERROR_INVALID_PARAMETER.
So don't forget to:
OVERLAPPED ovl;
ZeroMemory(&ovl, sizeof(ovl));
...
ReadFile(hSerial, szBuff, n, &dwBytesRead, &ovl);

write to serial port with win32 API- port won't open until i open it else where

I tried to write to a serial port in C++ with WIN32 API , the WriteFile doesn't return ERROR_IO_PENDING but nothing happens, But after i write to the port using another program (in C#) the c++ program works until i restart windows 7 , here is the write code:
static DCB dcb = {0};
static HANDLE hComm;
static int _tmain(int argc, _TCHAR* argv[])
{
hComm = CreateFile(
L"\\\\.\\COM3",
GENERIC_WRITE | GENERIC_READ,
0,
NULL,
OPEN_EXISTING,
NULL,
NULL
);
if (hComm == INVALID_HANDLE_VALUE) // error opening port; abort
printf_s("INVALID_HANDLE_VALUE\n");
if (GetCommState(hComm, &dcb))// DCB is ready for use.
{
dcb.BaudRate = CBR_19200; //19200 Baud
dcb.ByteSize = 8; //8 data bits
dcb.Parity = NOPARITY; //no parity
dcb.StopBits = ONESTOPBIT; //1 stop
printf_s("set UP DCB\n");
}
else // Error getting current DCB settings
printf_s("ERROR getting \n"+GetLastError());
osWrite.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
WriteABuffer("!serialCMDtoSend\r",sizeof("!serialCMDtoSend\r");
}
static BOOL WriteABuffer(char * lpBuf, DWORD dwToWrite)
{
// Issue write.
if (!WriteFile(hComm, lpBuf, dwToWrite, &dwWritten, &osWrite))
{
if (GetLastError() != ERROR_IO_PENDING) { // WriteFile failed, but it isn't delayed. Report error and abort.
fRes = FALSE;
}
else {
// Write is pending.
if (!GetOverlappedResult(hComm, &osWrite, &dwWritten, TRUE))
fRes = FALSE;
else
fRes = TRUE;// Write operation completed successfully.
}
}
else
fRes = TRUE; // WriteFile completed immediately.
return fRes;
}
can anybody see my bug ?
This works by accident. You forgot to specify FILE_FLAG_OVERLAPPED in the CreateFile call so you can never get overlapped I/O. You probably didn't know about this because your error handling is broken, you have no idea what the error code looks like when GetLastError doesn't return ERROR_IO_PENDING. It works by accident when WriteFile doesn't have to block because the data fits in the driver's transmit buffer. Modulo the handshaking setup as Ben explained.
There's no point at all in using overlapped I/O and calling GetOverlappedResult(TRUE) immediately. You might as well use non-overlapped I/O, a lot easier to get going. Only use it if you have something else useful to do and can call WaitForMultipleObjects() to check if the write completed. That's usually hard to deal with in the case of writing, writing asynchronous code isn't easy.
Sometimes starting with a clean DCB is better than using GetCommState. For example, you aren't turning off flow control, so behavior depends on how the last program left it.
You definitely need to be setting the flow control fields correctly:
fOutxCtsFlow
fOutxDsrFlow
fDtrControl
fDsrSensitivity
fOutX
fInX
fRtsControl
In general, I suggest NOT using GetCommState if you don't want your program to depend on prior settings. Instead, start with everything zero:
DCB dcb = { sizeof dcb };
dcb.fBinary = TRUE;
dcb.BaudRate = 19200; //19200 Baud
dcb.ByteSize = 8; //8 data bits
dcb.Parity = NOPARITY; //no parity
dcb.StopBits = ONESTOPBIT; //1 stop
In addition to your dependence on prior settings, GetCommState is failing because you didn't set DCBlength (the documentation clearly says this must be set by you, the caller. GetCommState can't fill in the buffer without first checking the size you supply.).

ReadFile() says it failed, but the error code is ERROR_SUCCESS

I'm using ReadFile() on Windows to read data from a serial port. This code was working fine at one point in time, but it's now failing and I'm trying to track down the source of the problem, so I doubt it's a problem with the serial configuration or timeouts, since none of that has changed.
ReadFile() returns false, indicating that an error occurred. However, when I immediately check the value of GetLastError(), it returns 0, which is ERROR_SUCCESS. The number of bytes read is 0, so I'm inclined to think that indeed something has gone wrong, but that error code is utterly useless.
Any ideas? Thanks.
EDIT: Here are some relevant code snippets:
#define GPS_COM_PORT L"COM3"
// for reference, the device communicates at 115200 baud,
// no parity, 1 stop bit, no flow control
// open gps com port
hGpsUart = CreateFile(GPS_COM_PORT, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
if (hGpsUart == INVALID_HANDLE_VALUE)
{
if (GetLastError() == ERROR_FILE_NOT_FOUND)
{
msg.setText("GPS COM port does not exist!");
msg.exec();
QApplication::quit();
}
msg.setText("Error occurred while trying to open GPS COM port!");
msg.exec();
QApplication::quit();
}
// set gps com port settings
dcbSerialParams.DCBlength = sizeof(dcbSerialParams);
if (!GetCommState(hGpsUart, &dcbSerialParams))
{
msg.setText("Could not get GPS COM port settings!");
msg.exec();
QApplication::quit();
}
dcbSerialParams.BaudRate = CBR_115200;
dcbSerialParams.ByteSize = 8;
dcbSerialParams.StopBits = ONESTOPBIT;
dcbSerialParams.Parity = NOPARITY;
if (!SetCommState(hGpsUart, &dcbSerialParams))
{
msg.setText("Could not set GPS COM port settings!");
msg.exec();
QApplication::quit();
}
// set gps com port timeouts
timeouts.ReadIntervalTimeout = MAXDWORD;
timeouts.ReadTotalTimeoutConstant = 0;
timeouts.ReadTotalTimeoutMultiplier = 0;
timeouts.WriteTotalTimeoutConstant = 50;
timeouts.WriteTotalTimeoutMultiplier = 10;
if (!SetCommTimeouts(hGpsUart, &timeouts))
{
msg.setText("Could not set GPS COM port timeouts!");
msg.exec();
QApplication::quit();
}
// ... later in the code ...
char buf[161] = {0};
DWORD bytes_read = 0;
// This returns false...
if (!ReadFile(hGpsUart, buf, 160, &bytes_read, NULL))
{
// Yet in here, GetLastError() returns ERROR_SUCCESS (0)
QMessageBox msg;
msg.setText("Error reading from GPS UART!");
msg.exec();
}
I think the key to your observations is the phrase in your source that says "Yet in here, GetLastError() returns ERROR_SUCCESS (0)"
The call to GetLastError has to be the very next Win32 call made after the (presumably) failing call. As an experiment, try putting an explicit call to GetLastError() within your failure handler, but just before the message box call. I suspect you'll see the true failure code.
Good luck!
The constructor of QMessageBox may be doing something that clears `GetLastError'. Try this:
if (!ReadFile(hGpsUart, buf, 160, &bytes_read, NULL))
{
int LastError = GetLastError() ;
QMessageBox msg;
msg.setText(QString("Error %1 reading from GPS UART!").arg(LastError));
msg.exec();
}