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.

4

1 回答 1

0

当您尝试操作未在缓冲区中分配的位置时,您会收到该错误。在此代码buf[i].copy(pBuf, pos);中,由 给出的位置pos不在pBuf.

缓冲区的大小是固定的,因此您不能将它们视为字符串(附加/写入您喜欢的尽可能多的数据),因此当targetStart参数copy恰好大于 BufferLength 时,您会收到该错误。

不仅如此,您还应该检查此错误之前的复制操作是否有效。由于空间不足,很可能是部分写入。

于 2013-05-22T16:41:13.750 回答