UNPKG

@homenet/plugin-mqttpublish

Version:

Publishes all events on the event bus to MQTT

68 lines (67 loc) 3.12 kB
"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __param = (this && this.__param) || function (paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } }; Object.defineProperty(exports, "__esModule", { value: true }); var mqtt = require("mqtt"); function create(annotate) { var MqttPublisherPluginLoader = (function () { function MqttPublisherPluginLoader(config, events, logger) { this.config = config; this.events = events; this.logger = logger; this.mqttConnected = false; this.init(); } MqttPublisherPluginLoader.prototype.load = function () { var _this = this; this.logger.info('Loading MQTT publisher'); this.events.onAny(function (name, e) { var data = e.data; var topic = name.replace(/\./g, '/'); _this.mqttClient.publish(topic, JSON.stringify(data)); }); }; MqttPublisherPluginLoader.prototype.init = function () { var _this = this; this.logger.info('Starting MQTT publisher'); var mqttConfig = this.config.mqtt || {}; var host = mqttConfig.host || 'localhost'; var mqttUri = 'mqtt://' + host; this.logger.info('Connecting to broker ' + mqttUri); var mqttClient = mqtt.connect(mqttUri); this.mqttConnected = false; mqttClient.on('connect', function () { _this.logger.info('MQTT connected'); _this.mqttConnected = true; }); mqttClient.on('close', function () { _this.logger.info('MQTT closed'); _this.mqttConnected = false; }); mqttClient.on('offline', function () { _this.logger.info('MQTT offline'); _this.mqttConnected = false; }); this.mqttClient = mqttClient; // mqttClient.on('error', console.error); // mqttClient.on('message', console.log); // mqttClient.on('message', (topic, message) => {}); }; return MqttPublisherPluginLoader; }()); MqttPublisherPluginLoader = __decorate([ annotate.plugin(), __param(0, annotate.service('IConfig')), __param(1, annotate.service('IEventBus')), __param(2, annotate.service('ILogger')) ], MqttPublisherPluginLoader); return { MqttPublisherPluginLoader: MqttPublisherPluginLoader }; } exports.create = create;