任何人都有XBee现在如何与serialport
交互的更新副本。
meterInterface
是传递到serialport
'use strict';
const Serialport = require('serialport');
const xbee_api = require('xbee-api');
const XBEE_C = xbee_api.constants;
const MeterAPI = require('./MeterAPI');
class XBeeMeter extends MeterAPI {
constructor(meterInterface) {
super(meterInterface);
this.timeout = 5000;
this.meterInterface = meterInterface;
this.xbeeAPI = new xbee_api.XBeeAPI({
api_mode: 2
});
this.xbeeAPI.setMaxListeners(0);
this.isOpen = false;
this.serialport = new Serialport(
meterInterface,
{ baudRate: 9600, parser: this.xbeeAPI.rawParser() },
error => {
this.isOpen = true;
console.error(error);
}
);
this.broadcastAddr = '000000000000ffff';
this.xbeeAPI.parser.on('frame_object', receivedFrame => {
console.log('Received frame', receivedFrame);
});
this.xbeeAPI.on('frame_object', receivedFrame => {
if (receivedFrame.type === XBEE_C.FRAME_TYPE.ZIGBEE_RECEIVE_PACKET) {
const amph = receivedFrame.data.readUInt32LE();
const id = receivedFrame.remote64.toUpperCase();
console.log('Receiving data', amph, id);
}
});
}
xbeeCommand(frame, waitForReply = true) {
return new Promise((resolve, reject) => {
const callback = function(receivedFrame) {
if (receivedFrame.id == frame.id) {
switch (receivedFrame.deliveryStatus) {
case XBEE_C.DELIVERY_STATUS.SUCCESS:
if (!waitForReply) {
resolve();
}
break;
default:
reject(XBEE_C.DELIVERY_STATUS[receivedFrame.deliveryStatus]);
break;
}
}
const dataReceived =
receivedFrame.type == XBEE_C.FRAME_TYPE.ZIGBEE_RECEIVE_PACKET &&
receivedFrame.remote64.toUpperCase() == frame.destination64.toUpperCase();
if (dataReceived) {
resolve(receivedFrame.data);
}
};
// console.log(this.xbeeAPI.buildFrame(frame).toJSON());
this.serialport.on('frame_object', () => {
console.log('Frame object');
});
this.xbeeAPI.on('frame_object', callback);
this.serialport.write(this.xbeeAPI.buildFrame(frame));
setTimeout(() => {
this.xbeeAPI.removeListener('frame_object', callback);
reject(new Error('Timeout error'));
}, this.timeout);
});
}
xbeeFrame(destination, data) {
return {
type: XBEE_C.FRAME_TYPE.ZIGBEE_TRANSMIT_REQUEST,
id: this.xbeeAPI.nextFrameId(),
destination64: destination,
broadcastRadius: 0x00,
options: 0x00,
data
};
}
reset(id) {
console.log(`Resetting ${id} meter`);
return this.xbeeCommand(this.xbeeFrame(id, [0x30]), false);
}
status(id) {
if (id) {
return this.xbeeCommand(this.xbeeFrame(id, [0x10]));
}
if (!this.isOpen) {
console.log('Serialport is not open');
return null;
}
console.log(`Getting the statuses of all meters via broadcast: ${this.broadcastAddr}`);
const reqFrame = this.xbeeFrame(this.broadcastAddr, [0x10]);
this.serialport.write(this.xbeeAPI.buildFrame(reqFrame));
}
enable(id, state) {
console.log(`changing the state of ${id} to ${state}`);
const frame = state ? this.xbeeFrame(id, [0x1]) : this.xbeeFrame(id, [0x2]);
return this.xbeeCommand(frame, false);
}
}
module.exports = XBeeMeter;
由于某些原因,未调用frame_object
侦听器。谁能帮忙。