@signalk/streams
Version:
Utilities for handling streams of Signal K data
96 lines • 3.58 kB
JavaScript
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const net_1 = __importDefault(require("net"));
const stream_1 = require("stream");
const reconnect_core_1 = __importDefault(require("reconnect-core"));
const GPSD_DEFAULT_PORT = 2947;
const GPSD_WATCH_COMMAND = '?WATCH={"class":"WATCH","nmea":true,"json":false}\n';
class Gpsd extends stream_1.Transform {
hostname;
port;
debug;
noDataReceivedTimeout;
options;
reconnector = null;
constructor(options) {
super();
this.options = options;
this.port = options.port ?? GPSD_DEFAULT_PORT;
this.hostname = options.hostname ?? options.host ?? 'localhost';
this.noDataReceivedTimeout = (options.noDataReceivedTimeout ?? 0) * 1000;
const createDebug = options.createDebug ?? require('debug');
this.debug = createDebug('signalk:streams:gpsd');
}
pipe(pipeTo) {
if (this.reconnector) {
return super.pipe(pipeTo);
}
const label = `${this.hostname}:${this.port}`;
this.options.app.setProviderStatus(this.options.providerId, `Connecting to ${label}`);
this.reconnector = (0, reconnect_core_1.default)((opts) => {
return net_1.default.connect(opts);
})({ maxDelay: 5 * 1000 }, (socket) => {
if (this.noDataReceivedTimeout > 0) {
socket.setTimeout(this.noDataReceivedTimeout);
this.debug(`Socket idle timeout set to ${this.noDataReceivedTimeout}ms`);
socket.on('timeout', () => {
this.debug(`Idle timeout on ${label}`);
socket.end();
});
}
socket.write(GPSD_WATCH_COMMAND);
this.debug(`Sent WATCH command to ${label}`);
socket.on('data', (data) => {
this.write(data);
});
})
.on('connect', () => {
const msg = `Connected to ${label}`;
this.options.app.setProviderStatus(this.options.providerId, msg);
this.debug(msg);
})
.on('reconnect', (n, delay) => {
const msg = `Reconnect ${label} retry ${n} delay ${delay}`;
if (n > 0) {
this.options.app.setProviderError(this.options.providerId, msg);
}
this.debug(msg);
})
.on('disconnect', () => {
const msg = `Disconnected from ${label}`;
this.options.app.setProviderError(this.options.providerId, msg);
this.debug(msg);
})
.on('error', (err) => {
let msg;
if (err.message && err.message.length > 0) {
msg = err.message;
}
else if (err.errors) {
msg = err.errors.toString();
}
else {
msg = err.toString();
}
this.options.app.setProviderError(this.options.providerId, msg);
console.error(`GpsdProvider: ${msg}`);
})
.connect({ host: this.hostname, port: this.port });
super.pipe(pipeTo);
return pipeTo;
}
end() {
if (this.reconnector) {
this.reconnector.disconnect();
}
return this;
}
_transform(data, encoding, callback) {
callback(null, data);
}
}
exports.default = Gpsd;
//# sourceMappingURL=gpsd.js.map