Details
Description
The serial transport sends more then required data when IoSession.write() is called with the IoBuffer. The following code is the basic usage of serial transport:
-----------------------------------------------------------------------
SerialAddress a = new SerialAddress("COM1", 115200, SerialAddress.DataBits.DATABITS_8, SerialAddress.StopBits.BITS_1, SerialAddress.Parity.NONE, SerialAddress.FlowControl.NONE);
IoConnector c = new SerialConnector();
c.setHandler(this);
ConnectFuture cf = c.connect(a);
cf.awaitUninterruptibly();
System.out.println("Connection = " + cf.isConnected());
if (cf.isConnected())
{ IoSession s = cf.getSession(); IoBuffer b = IoBuffer.allocate(32); b.put(new String("this is a test message").getBytes()); b.flip(); WriteFuture wf = s.write(b); wf.awaitUninterruptibly(5, TimeUnit.SECONDS); System.out.println("Message Written = " + wf.isWritten()); }-----------------------------------------------------------------------
The message <code>this is a test message</code> should have been sent on the serial port COM1. But the actual output received is (output captured through HDD Free Serial Port Monitor) :
-----------------------------------------------------------------------
74 68 69 73 20 69 73 20 61 20 74 65 73 74 20 6D this is a test m
65 73 73 61 67 65 00 00 00 00 00 00 00 00 00 00 essage..........
-----------------------------------------------------------------------
I have looked into the code, and the reason appears to be the following statement on line # 184 in the file SerialSessionImpl.java.
-----------------------------------------------------------------------
outputStream.write(buf.array());
-----------------------------------------------------------------------
Since buf.array() returns the complete array in the IoBuffer, regardless of the actual count of valid data, so all bytes are sent. I changed this statement to:
-----------------------------------------------------------------------
outputStream.write(buf.array(), buf.position(), writtenBytes);
-----------------------------------------------------------------------
to ensure that only the required bytes starting from the first unread position is sent on the serial port. This works so far for all my cases.
Thanks,
Akbar.