我正在使用NodeJS制作状态机,并使用串行端口接收和发送一系列命令以验证通信是否正确,在第二个状态下,我接收了31个字节的数据,并需要在我的设备上重新发送它们第四种状态,为此,我只是复制接收到的数组以稍后发送,但是在我的第四种状态console.log上什么都没有显示,会发生什么?
这是我的代码:
const SerialPort = require('serialport');
const ByteLength = SerialPort.parsers.ByteLength;
const port = new SerialPort("COM6");
const parser = new ByteLength({length: 1});
port.pipe(parser);
var state = 0;
var cache = [];
var history;
parser.on('data', function (data) {
cache.push(data[0]);
flowcontrol();
});
function porterr() {
console.log('error');
process.exit(1);
}
function flowcontrol() {
switch (state) {
case 0:
// ---------------------------------------------
// State 0 -> Recives ENQ, Sends ACK
// ---------------------------------------------
// Receives 1 byte
if (cache.length !== 1) {
return;
}
// Verify answer received
if (cache[0] !== 5) {
// Wrong answer received
porterr();
}
console.log('state ' + state);
// Sends Answer, clears cache, and waits for next state
port.write(Buffer.from([6]));
state++;
cache.length = 0;
break;
case 1:
// ---------------------------------------------
// State 1 -> Recives DATA, Sends ACK
// ---------------------------------------------
// Receives 31 bytes
if (cache.length !== 31) {
return;
}
console.log('state ' + state);
history = cache; // <--- data is saved for later use
// Sends Answer, clears cache, and waits for next state
port.write(Buffer.from([6]));
state++;
cache.length = 0;
break;
case 2:
// ---------------------------------------------
// State 1 -> Recives EOT, Sends ENQ
// ---------------------------------------------
// Receives 1 byte
if (cache.length !== 1) {
return;
}
// Verify answer received
if (cache[0] !== 4) {
// Wrong answer received
porterr();
}
console.log('state ' + state);
// Sends Answer, clears cache, and waits for next state
port.write(Buffer.from([5]));
state++;
cache.length = 0;
break;
case 3:
// ---------------------------------------------
// State 3 -> Recives ACK, Sends DATA
// ---------------------------------------------
// Receives 1 byte
if (cache.length !== 1) {
return;
}
// Verify answer received
if (cache[0] !== 6) {
// Wrong answer received
porterr();
}
console.log('state ' + state);
console.log[history]; // <-- Nothing is shown here!!!
// Sends Answer, clears cache, and waits for next state
//port.write(Buffer.from(history));
//state++;
//cache.length = 0;
break;
default:
console.log('not yet completed');
console.log(cache.length);
break;
}
}
答案 0 :(得分:1)
您不应分配与javascript相等的对象。
为此使用Object.assign或lodash。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
https://lodash.com/docs/4.17.10#cloneDeep
代码中发生的事情是当您更改cache.length = 0的值时;它也改变了历史的价值。 因为它是对象而不是引用类型。