how to implement 9-bit communication under C#.NET & Win32
Posted on 2011-05-08
I've been trying desperatly for the past couple of weeks to implement a 9-bit protocol (a.k.a multidrop) under c#.
just to make clear:
bytes under the protocol are 8 bits, where the first byte of the packet has a parity of 1 (Mark) and addtional bits have the parity of 0 (Space).
writing packets are the easy part, simply setting the parity for each byte.
reading the packets is the problem and here lies my problem:
.NET SerialPort class only signlas that there was a parity error, but not in which bit it was occured. Only closest solution is to use the ParityReplace member - which causes 2 new problems: first byte information is lost and we have no way of identifying whether it is the first byte or a part of the information.
I turned to importing kernel.dll functions such as ReadFile/WriteFile which .NET SerialPort class implements under the hood. The reasonable solution is to use the Space parity settings, set fAbortOnError flag to true, so when a byte with the 1 (Mark) parity bit will be recived, communication will stop until i'll renew it - and so it works.
So what's my problem?
Appearantly, bytes I have yet to recieve, are stored in an internal win32 buffer which only saves the 8-bit data and not the parity bit along it's side. So when my program is dealing with other matters, every byte - whether its parity is 0 or 1 - is inserted to the buffer, causing to the program to read more than a packet length.
consider the code:
WaitCommEvent(mFileHandle, out comEvent, IntPtr.Zero);
ClearCommError(mFileHandle, out errors, out comstat);
ReadFile(mFileHandle, tempBuffer, cMaxPacketSizeInBytes, out actualBytesRead, IntPtr.Zero);
I configured the port to wait for a parity error (mask = parity event).
WaitCommEvent waits for the first parity error to occur (first byte of the packet is 1), ClearCommError releases the closest error and ReadFile (Should) read until the next error (Parity 1 when expected 0).
however ReadFile gives me ALL of the recieved bytes = 15 packets where I made sure to send them with the first byte Parity Marked.
I have scanned the web desparately and I KNOW there is some solution to this other then reprogramming serial.sys driver as there are software packages who implement this protocol.
any help will be most appreciated.