0

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Senica Gonzalez
  • 7,996
  • 16
  • 66
  • 108

1 Answers1

0

You get that error when you try to manipulate a position not allocated within the buffer. In this code buf[i].copy(pBuf, pos); the position given by pos is not in pBuf.

Buffers are fixed in size, so you cannot treat them like strings (append/write as much data you like), so when the targetStart argument of copy happens to greater than BufferLength you get that error.

Not only this, you should check if the copy operation before this error was valid. Most likely it was partially written, due to insufficient space.

user568109
  • 47,225
  • 17
  • 99
  • 123