UNPKG

@allgemein/eventbus

Version:
71 lines 2.23 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.AbstractMqttConnection = void 0; const events_1 = require("events"); const mqtt_1 = require("mqtt"); const lodash_1 = require("lodash"); // import {E_ERROR, E_READY} from './MqttConstants'; class AbstractMqttConnection extends events_1.EventEmitter { constructor(options) { super(); this.inc = 0; this.ready = false; this.options = options; } isOpened() { return this.ready; } getClient(connect = true) { if (connect) { return this.connect(); } if (this.client) { return this.client; } throw new Error('no client found'); } async connect() { if (this.ready) { return this.client; } this.ready = false; let tmp = null; this.client = await new Promise((resolve, reject) => { tmp = (err) => { err.message = err.message + ' (#connect)'; reject(err); }; const client = (0, mqtt_1.connect)(this.options.url, this.options); client.on(E_ERROR, tmp); client.on(E_CONNECT, () => { client.removeListener(E_ERROR, tmp); client.on(E_ERROR, this.onError.bind(this)); resolve(client); }); }); this.ready = true; return this.client; } async quit() { if (!this.ready) { return; } this.ready = false; const disconnectOpts = (0, lodash_1.get)(this.options, 'disconnect', { force: true, options: {} }); return new Promise((resolve, reject) => { this.client.end(disconnectOpts.force, disconnectOpts.options, () => { resolve(); }); }); } onError(err) { // need restart! this.ready = false; this.client = null; err.message = err.message + ' (#onError ' + this.constructor.name + ')'; console.error(err); // TODO check reopen? } } exports.AbstractMqttConnection = AbstractMqttConnection; //# sourceMappingURL=AbstractMqttConnection.js.map