当前位置: 动力学知识库 > 问答 > 编程问答 >

serial port - Error 'Target out of bounds' when connecting through XBee to a server with Node.js/serialport

问题描述:

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.

网友答案:

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: