@csllc/j1939
Version:
J1939 transport layer for CANBUS communication
95 lines (68 loc) • 1.82 kB
JavaScript
const J1939 = require('../..');
const { Duplex } = require('stream');
/**
* Class definition for a mock bus that just cross-connects the transmit and
* receive, with a configurable delay and some other levers you can pull to
* create error conditions
*
* @class Bus (name)
*/
class Bus extends Duplex {
constructor(options) {
super({ objectMode: true });
this.options = options;
this.bOpen = false;
}
// required functions for a readable stream, we don't need to do anything
_read() {}
// required functions for a writable stream, we don't need to do anything
_write() {}
// Error out any requests we are waiting for
_flushRequestQueue() {}
isOpen() {
return this.bOpen;
}
// open the port. In this case, cross-connect the objects so sending from
// one causes a receipt by the other
open(port) {
let me = this;
me.bOpen = true;
port.on('write', function(data) {
// console.log('incoming data', data);
setTimeout(function() {
me.push(data);
}, me.options.delay);
});
me.emit('open');
}
close() {
this.emit('close');
}
write(msg) {
this.emit('write', msg);
}
}
module.exports = class J1939Mock extends J1939 {
constructor(options) {
let remote = new Bus({ delay: 5 });
super(remote, options);
this.local = new Bus({ delay: 5 });
this.remote = remote;
// this.local.on('data', function(data) {
// console.log('local data:', data);
// })
}
localBus() {
return this.local;
}
openBus() {
this.openLocal();
this.openRemote();
}
openLocal() {
this.local.open(this.remote);
}
openRemote() {
this.remote.open(this.local);
}
};