I have an XBee module that accepts data on ttyAMA0 of a Debian server that is running Node.js with 'serialport' installed.
I keep getting an out-of-bounds error from the following code which take an XBee packet up to the length it should be. It then gets sent to another function for checksum validation. But the problem is the darn buffer.
var receivingPacket = false;
xbee.on('data', function (data) {
if(receivingPacket == false && data[0] == 0x7e){
receivingPacket = true;
buf = [];
bufLen = 0;
bufUsed = 0;
if(data[3] == 0x90){ //Received Transmission
bufLen = data[2] + 4; //Start byte, start length byte, end length byte, checksum byte
}
}
if(receivingPacket == true && bufUsed >= bufLen){
var pBuf = new Buffer(bufUsed); //In case we get another packet right behind it
var pos = 0;
for(var i = 0, len = buf.length; i<len; i++){
try{
buf[i].copy(pBuf, pos);
}
catch(e){ //Sometimes we get a corrupt packet, discard and wait for the next one
receivingPacket = false;
console.log(e);
return false;
}
pos += buf[i].length;
}
receivingPacket = false;
processPacket(pBuf);
}
else
if(receivingPacket == true){
buf.push(data);
bufUsed += data.length;
}
});
I added the receivingPacket
as part of testing, it should not be necessary. The problem seems to be the line with copy, buf[i].copy(pBuf, pos);
. I don't know if I need to clear the buffer somehow.
The error is
[RangeError targetStart out of bounds]
which would be pos in my case.