And, I missed something in my reply above regarding your last question. As Barry points out, you can get incomplete messages and/or multiple messages. Yes, your code must handle those conditions.
I usually do something as follows:
// serial port.
var mySerialPort=CF.extender[0].serial[0]; // port #1
// Buffer defined at activity level (I usually attach buffer to serial port).
var currentBuffer = '';
// if attaching field to port - mySerialPort.currentBuffer = '';
function processData(data)
{
if (!data)
{
// we got timeout with no data.
return;
}
// if attached to serial port - this.currentBuffer += data;
currentBuffer += data;
// splitData is a custom function to extract individual messages from
// all data received thus far.
var o = splitData(currentBuffer) // returns an object with 2 fields: complete
// msgs array and remaining data, if any.
// if no remaining data, return array plus
// empty string.
var completeMsgs = o.completeMsgs;
// if attached to serial port - this.currentBuffer = o.partialData;
currentBuffer = o.partialData;
if (completeMsgs)
{
var index = 0;
var len = completeMsgs.length;
while (index < len)
{
var message = completeMsgs[index];
// logic to process single message;
index++;
}
}
}
mySerialPort.onData = processData;
mySerialPort.onTimeout = processData; // see note below.
Note that onTimeout(data) will also be fired if timeout condition occurs with any data received up to point of timeout so you should be prepared to write a single processData(data) function that is called from both the onData() and onTimeout() callbacks of the Serial Port.
Last edited by Lyndel McGee on February 10, 2010 17:49.