@signalk/streams
Version:
Utilities for handling streams of Signal K data
54 lines (53 loc) • 1.67 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const dgram_1 = require("dgram");
const stream_1 = require("stream");
class Udp extends stream_1.Transform {
options;
debug;
socket = null;
pipeTo = null;
constructor(options) {
super({ objectMode: false });
this.options = options;
const createDebug = options.createDebug ?? require('debug');
this.debug = createDebug('signalk:streams:udp');
}
pipe(pipeTo) {
this.pipeTo = pipeTo;
super.pipe(pipeTo);
const socket = (0, dgram_1.createSocket)('udp4');
this.socket = socket;
if (this.options.outEvent && this.options.port !== undefined) {
this.options.app.on(this.options.outEvent, (d) => {
this.debug('sending over udp: %s', d);
socket.send(d, 0, d.length, this.options.port, this.options.host ?? '255.255.255.255');
});
}
socket.on('message', (message) => {
this.debug(message.toString());
this.push(message);
});
socket.on('error', (err) => {
this.options.app.setProviderError(this.options.providerId, err.message);
console.error('UdpProvider:' + err);
});
socket.bind(this.options.port, () => {
socket.setBroadcast(true);
});
return pipeTo;
}
_transform(chunk, encoding, done) {
done();
}
end() {
if (this.socket) {
this.socket.close();
}
if (this.pipeTo) {
this.pipeTo.end();
}
return this;
}
}
exports.default = Udp;