I'm trying to write hex data to my serial port. However, although GetOverlappedResult returns true, the number of bytes sent is always 0 despite my sending 1 or 2 or 8 bytes.
I'm able to open/close the port and receive hex messages. I just can't figure how to write data to my serial port for it to be picked up by another virtual serial port.
I referenced a 'TimeReader' project a colleague found online. I've tested the ports with virtual serial ports using Serial Port Utility, and managed to communicate successfully between them. Searching online did not help me solve the problem entirely.
How I create the handle:
serialPortHandle = CreateFile(("COM2"),
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
OPEN_EXISTING,
FILE_FLAG_OVERLAPPED | FILE_FLAG_NO_BUFFERING,
NULL);
How I create my data:
typedef struct
{
int len;
char data[1];
}Message;
(and later in my main function)
message.len = 8;
message.data[0] = 0x30;
How I call WriteFile:
OVERLAPPED osWriteS = { 0 };
osWriteS.Offset = 0;
osWriteS.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
DWORD bytesSent;
_cprintf("message: %x\r\n", message.data[0]);
_cprintf("message len: %i\r\n", message.len);
if (WriteFile(serialPortHandle, message.data, message.len, &bytesSent, &osWriteS) == false)
{
_cprintf("bytes sent before overlap: %x\n", bytesSent);
if (GetLastError() != ERROR_IO_PENDING)
{
_cprintf("Failed to send message\n");
return;
}
else
{
bool _overlappedResult = GetOverlappedResult(serialPortHandle, &osWriteS, &bytesSent, TRUE);
_cprintf("overlapped: %x\n", _overlappedResult);
_cprintf("bytes: %x\n", bytesSent);
}
}
if (bytesSent != message.len)
{
_cprintf("Failed to send complete message\n");
return;
}
Printing GetOverlappedResult returns a value of 1, yet the bytesSent = 0 despite the message containing 1 byte, and no data was received from another serial port waiting for this to send data.
Could anyone please help me provide insight to the problem? Thank you!