From 5f18fd631508060549478d53176fd29d64c5e9d1 Mon Sep 17 00:00:00 2001 From: Ari Sosnovsky Date: Fri, 14 Nov 2025 11:44:57 -0500 Subject: [PATCH] refactor mqtt client --- {src => _legacy}/mqtt.ts | 79 +- lib.js | 1345 +++++++++++++----------- src/ha_mqtt/index.ts | 8 +- src/hub_controller/index.ts | 4 +- src/index.ts | 20 +- src/ir_controller/entity_controller.ts | 69 ++ src/ir_controller/index.ts | 157 +-- src/ir_controller/ir_handler.ts | 38 + src/ir_controller/mqtt_handler.ts | 54 + src/ir_controller/utils.ts | 46 + src/mqtt_client/constants.ts | 40 + src/mqtt_client/index.ts | 433 ++++++++ src/mqtt_client/utils.ts | 161 +++ tsconfig.json | 5 +- types/flic.sdk.globals.d.ts | 130 +++ types/flic.sdk.net.d.ts | 231 ++++ types/options.types.d.ts | 18 +- 17 files changed, 1987 insertions(+), 851 deletions(-) rename {src => _legacy}/mqtt.ts (89%) create mode 100644 src/ir_controller/entity_controller.ts create mode 100644 src/ir_controller/ir_handler.ts create mode 100644 src/ir_controller/mqtt_handler.ts create mode 100644 src/mqtt_client/constants.ts create mode 100644 src/mqtt_client/index.ts create mode 100644 src/mqtt_client/utils.ts create mode 100644 types/flic.sdk.globals.d.ts create mode 100644 types/flic.sdk.net.d.ts diff --git a/src/mqtt.ts b/_legacy/mqtt.ts similarity index 89% rename from src/mqtt.ts rename to _legacy/mqtt.ts index 807a3d7..10afcf5 100644 --- a/src/mqtt.ts +++ b/_legacy/mqtt.ts @@ -73,7 +73,7 @@ var RETURN_CODES = { }; /** MQTT constructor */ -function MQTT(server, options) { +export function MQTT(server: string, options: Partial) { this.server = server; options = options || {}; this.port = options.port || C.DEF_PORT; @@ -143,10 +143,10 @@ Object.prototype.on = function (type, fn) { __listeners[type].push(fn); }; -Object.prototype.emit = function (type, ...data) { +Object.prototype.emit = function (type, data) { if (__listeners[type]) { __listeners[type].map(function (fn) { - fn(...data); + fn(data); }); } }; @@ -183,16 +183,8 @@ export function mqttStr(s) { return payloadarray; } -export function mqttInt2Str(arr: number[] | Uint8Array): string { - let outStr = ""; - for (var i = 0; i < arr.length; i++) { - outStr += createEscapedHex(arr[i]); - } - return outStr; -} - /** MQTT packet length formatter - algorithm from reference docs */ -function mqttPacketLength(length) { +function mqttPacketLength(length: number) { var encLength = []; var i = 0; do { @@ -335,7 +327,6 @@ MQTT.prototype.packetHandler = function (data) { } // Get the data for this packet var pData = data.slice(1 + dLen.lenBy, pLen); - // more than one packet? re-emit it so we handle it later if (data.length > pLen) { this.client.emit("data", data.slice(pLen, data.length)); @@ -364,11 +355,7 @@ MQTT.prototype.packetHandler = function (data) { ]); } this.emit("publish", parsedData); - this.emit( - "message", - mqttInt2Str(parsedData.topic), - mqttInt2Str(parsedData.message), - ); + this.emit("message", parsedData.topic, parsedData.message); } else if (type === TYPE.PUBACK) { this.emit("puback", (data.charCodeAt(2) << 8) | data.charCodeAt(3)); } else if (type === TYPE.PUBREC) { @@ -454,9 +441,10 @@ MQTT.prototype.connect = function (client) { } else { try { var self = this; - client = require("net") - .Socket() - .connect({ host: mqo.server, port: mqo.port }, onConnect); + client = require("net").connect( + { host: mqo.server, port: mqo.port }, + onConnect, + ); client.on("error", function (err) { self.emit("error", err.message); }); @@ -524,17 +512,20 @@ MQTT.prototype.publish = function (topic, message, opts) { }; /** Subscribe to topic (filter) */ -MQTT.prototype.subscribe = function (topics, opts) { +MQTT.prototype.subscribe = function ( + topics: string[] | string | Record, + opts: { qos?: any }, +) { if (!this.client) return; opts = opts || {}; - var subs = []; + var subs: { topic: string; qos: any }[] = []; if ("string" === typeof topics) { topics = [topics]; } if (Array.isArray(topics)) { topics.forEach( - function (topic) { + function (topic: string) { subs.push({ topic: topic, qos: opts.qos || this.C.DEF_QOS, @@ -551,7 +542,7 @@ MQTT.prototype.subscribe = function (topics, opts) { } subs.forEach( - function (sub) { + function (sub: { topic: string; qos: any }) { var subpacket = mqttSubscribe(sub.topic, sub.qos); this.client.write(subpacket); }.bind(this), @@ -619,44 +610,14 @@ MQTT.prototype.mqttConnect = function (clean) { /* Exports *************************************/ /** This is 'exported' so it can be used with `require('MQTT.js').create(server, options)` */ -export function create(server, options): MQTT { +export function create(server: string, options: Partial) { return new MQTT(server, options); } -export function connect(options): MQTT { +export function connect( + options: Partial & { host: string }, +) { var mqtt = new MQTT(options.host, options); mqtt.connect(); return mqtt; } - -export interface MQTT { - connect(): void; - publish( - topic: string, - message: string, - opts: - | { - retain?: boolean; // the server should retain this message and send it out again to new subscribers - dup?: boolean; // indicate the message is a duplicate because original wasn't ACKed (QoS > 0 only) - } - | undefined, - ): void; - subscribe(topics: string[]): void; - unsubscribe(topic: string): void; - on( - ev: "publish", - cb: (data: { topic: Buffer; message: Buffer }) => void, - ): void; - on(ev: "message", cb: (topic: string, message: string) => void): void; - on(ev: "puback", cb: (data) => void): void; - on(ev: "pubcomp", cb: (data) => void): void; - on(ev: "subscribed_fail", cb: (data) => void): void; - on(ev: "subscribed", cb: (data) => void): void; - on(ev: "unsubscribed", cb: (data) => void): void; - on(ev: "ping_reply", cb: (data) => void): void; - on(ev: "connected", cb: (data) => void): void; - on(ev: "connect", cb: (data) => void): void; - on(ev: "error", cb: (data) => void): void; - on(ev: "disconnected", cb: (data) => void): void; - on(ev: "close", cb: (data) => void): void; -} diff --git a/lib.js b/lib.js index 5ea1f50..bb9b2ad 100644 --- a/lib.js +++ b/lib.js @@ -2,6 +2,7 @@ var buttonModule = require('buttons'); var ir = require('ir'); +var net = require('net'); var flichub = require('flicapp'); var hubinfo = require('hubinfo'); @@ -31,7 +32,7 @@ function makeLogger(prefix) { }; } -function _define_property$6(obj, key, value) { +function _define_property$7(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, @@ -54,7 +55,7 @@ function _object_spread$6(target) { })); } ownKeys.forEach(function(key) { - _define_property$6(target, key, source[key]); + _define_property$7(target, key, source[key]); }); } return target; @@ -177,7 +178,7 @@ var ENTITIES = { ] }; -function _define_property$5(obj, key, value) { +function _define_property$6(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, @@ -200,7 +201,7 @@ function _object_spread$5(target) { })); } ownKeys.forEach(function(key) { - _define_property$5(target, key, source[key]); + _define_property$6(target, key, source[key]); }); } return target; @@ -370,7 +371,7 @@ function makeButtonController(ha) { }; } -function _define_property$4(obj, key, value) { +function _define_property$5(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, @@ -393,7 +394,7 @@ function _object_spread$4(target) { })); } ownKeys.forEach(function(key) { - _define_property$4(target, key, source[key]); + _define_property$5(target, key, source[key]); }); } return target; @@ -428,7 +429,7 @@ var makeOptions$2 = function(opt) { }); }; -function _define_property$3(obj, key, value) { +function _define_property$4(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, @@ -451,7 +452,7 @@ function _object_spread$3(target) { })); } ownKeys.forEach(function(key) { - _define_property$3(target, key, source[key]); + _define_property$4(target, key, source[key]); }); } return target; @@ -476,8 +477,8 @@ function _object_spread_props$1(target, source) { return target; } function makeHAmqtt(mqttServer) { - var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}; - options = makeOptions$2(options); + var _options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}; + var options = makeOptions$2(_options); var logger = makeLogger("mqtt:ha", options.debug); logger.info("starting...", JSON.stringify(options, null, 4)); var genFlicPrefix = function(nodeId, objectId) { @@ -549,7 +550,7 @@ function makeHAmqtt(mqttServer) { }; } -function _define_property$2(obj, key, value) { +function _define_property$3(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, @@ -572,7 +573,7 @@ function _object_spread$2(target) { })); } ownKeys.forEach(function(key) { - _define_property$2(target, key, source[key]); + _define_property$3(target, key, source[key]); }); } return target; @@ -585,22 +586,145 @@ var convertUint32Array2Str = function(arr) { } return outStr.join("_"); }; -var convertStr2Uint32Array = function(s) { - var a = s.split("_"); - return new Uint32Array(a.slice(0, a.length - 2).map(function(v) { - return parseInt(v, 32); - })); -}; var makeOptions$1 = function(opt) { return _object_spread$2({ debug: false, uniqueId: "0" }, opt); }; +var makeIRSharedState = function() { + var currentSignal = ""; + var isRecording = false; + return { + isRecording: function isRecording1() { + return isRecording; + }, + setRecordingState: function setRecordingState(newValue) { + isRecording = newValue; + }, + currentSignal: function currentSignal1() { + return currentSignal; + }, + setCurrentSignal: function setCurrentSignal(newValue) { + currentSignal = newValue; + } + }; +}; +var getConstants$1 = function(ha, options) { + var nodeId = "".concat(NODE_ID$1).concat(options.uniqueId); + var LIFELINE_SGINAL = ha.genFlicPrefixObject(nodeId, "lifeline"); + var RECORD_SIGNAL = ha.genFlicPrefixObject(nodeId, "record"); + var RECORD_SIGNAL_SET = ha.genFlicPrefixObject(nodeId, "record/set"); + var VALUE_SIGNAL_SET = ha.genFlicPrefixObject(nodeId, "signal/set"); + var VALUE_SIGNAL_STATE = ha.genFlicPrefixObject(nodeId, "signal"); + var PLAY_SIGNAL = ha.genFlicPrefixObject(nodeId, "play"); + var PLAY_SIGNAL_SET = ha.genFlicPrefixObject(nodeId, "play/set"); + return { + NODE_ID: nodeId, + LIFELINE_SGINAL: LIFELINE_SGINAL, + RECORD_SIGNAL: RECORD_SIGNAL, + RECORD_SIGNAL_SET: RECORD_SIGNAL_SET, + VALUE_SIGNAL_SET: VALUE_SIGNAL_SET, + VALUE_SIGNAL_STATE: VALUE_SIGNAL_STATE, + PLAY_SIGNAL: PLAY_SIGNAL, + PLAY_SIGNAL_SET: PLAY_SIGNAL_SET, + set_topics: [ + RECORD_SIGNAL_SET, + VALUE_SIGNAL_SET, + PLAY_SIGNAL_SET + ] + }; +}; -var makeIRController = function(ha, mqtt) { - var options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {}; - options = makeOptions$1(options); +var registerEntities = function(ha, haDevice, param) { + var NODE_ID = param.NODE_ID, LIFELINE_SGINAL = param.LIFELINE_SGINAL, RECORD_SIGNAL = param.RECORD_SIGNAL, RECORD_SIGNAL_SET = param.RECORD_SIGNAL_SET, VALUE_SIGNAL_SET = param.VALUE_SIGNAL_SET, VALUE_SIGNAL_STATE = param.VALUE_SIGNAL_STATE, PLAY_SIGNAL = param.PLAY_SIGNAL, PLAY_SIGNAL_SET = param.PLAY_SIGNAL_SET; + var availability = [ + { + payload_available: "ON", + payload_not_available: "unavailable", + topic: LIFELINE_SGINAL.mqttPrefix + } + ]; + ha.startLifeLine("IR Connnected", NODE_ID, haDevice, LIFELINE_SGINAL.objectId); + ha.registerEntity("Record Signal", "switch", NODE_ID, RECORD_SIGNAL.objectId, haDevice, { + icon: "mdi:record-rec", + command_topic: RECORD_SIGNAL_SET.mqttPrefix, + device_class: "switch", + availability: availability + }); + ha.registerEntity("Signal", "text", NODE_ID, VALUE_SIGNAL_STATE.objectId, haDevice, { + command_topic: VALUE_SIGNAL_SET.mqttPrefix, + icon: "mdi:broadcast", + max: 255, + availability: availability + }); + ha.registerEntity("Play Signal", "button", NODE_ID, PLAY_SIGNAL.objectId, haDevice, { + icon: "mdi:play", + command_topic: PLAY_SIGNAL_SET.mqttPrefix, + availability: availability + }); +}; + +var irMQTTHandler = function(mqtt, ha, nodeId, logger, state, param) { + var RECORD_SIGNAL_SET = param.RECORD_SIGNAL_SET, VALUE_SIGNAL_SET = param.VALUE_SIGNAL_SET, RECORD_SIGNAL = param.RECORD_SIGNAL; + logger.info("Registering ir mqtt handler ".concat(nodeId, " ").concat(state.currentSignal())); + mqtt.on("message", function(topic, message) { + logger.info("message:", JSON.stringify({ + topic: topic, + message: message, + state: state, + currentSignal: state.currentSignal() + })); + if (topic === VALUE_SIGNAL_SET.mqttPrefix) { + state.setCurrentSignal(message); + logger.info("setting currentSignal", message); + } else if (topic === RECORD_SIGNAL_SET.mqttPrefix) { + logger.info("IR module is being set to ".concat(message)); + if (message === "OFF" && state.isRecording()) { + try { + ir.cancelRecord(); + state.setRecordingState(false); + } catch (err) { + logger.error("Failed to stop record, check you have the latest version of the sdk!"); + state.setRecordingState(true); + ha.publishState(nodeId, RECORD_SIGNAL.objectId, "OFF", { + dup: false + }); + } + } else if (!state.isRecording()) { + ir.record(); + state.setRecordingState(true); + } else { + logger.info("Doing nothing state.isRecording()=".concat(state.isRecording(), " state.currentSignal()=").concat(state.currentSignal())); + } + } + }); +}; + +var handleIREvents = function(ha, logger, nodeId, state, param) { + var VALUE_SIGNAL_STATE = param.VALUE_SIGNAL_STATE, RECORD_SIGNAL = param.RECORD_SIGNAL; + ir.on("recordComplete", function(data) { + logger.info("recordComplete", data); + if (data.length === 0) { + logger.error("Failed to record any data"); + return; + } + var stringMessage = convertUint32Array2Str(data); + logger.info("recording completed with", JSON.stringify({ + stringMessage: stringMessage + })); + state.setCurrentSignal(stringMessage); + ha.publishState(nodeId, VALUE_SIGNAL_STATE.objectId, stringMessage, { + retain: true + }); + state.setRecordingState(false); + ha.publishState(nodeId, RECORD_SIGNAL.objectId, "OFF"); + }); +}; + +var startIRController = function(ha, mqtt) { + var _options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {}; + var options = makeOptions$1(_options); var logger = makeLogger("ir", options.debug); var haDevice = { name: "IR", @@ -611,177 +735,32 @@ var makeIRController = function(ha, mqtt) { ], configuration_url: "https://hubsdk.flic.io/" }; - var nodeId = "".concat(NODE_ID$1).concat(options.uniqueId); - var LIFELINE_SGINAL = ha.genFlicPrefix(nodeId, "lifeline"); - var RECORD_SIGNAL_SET = ha.genFlicPrefix(nodeId, "record/set"); - var VALUE_SIGNAL_SET = ha.genFlicPrefix(nodeId, "signal/set"); - var VALUE_SIGNAL_STATE = ha.genFlicPrefix(nodeId, "signal"); - var PLAY_SIGNAL_SET = ha.genFlicPrefix(nodeId, "play/set"); - var availability = [ - { - payload_available: "ON", - payload_not_available: "unavailable", - topic: LIFELINE_SGINAL - } - ]; - var currentSignal = null; - var set_topics = [ - RECORD_SIGNAL_SET, - VALUE_SIGNAL_SET, - PLAY_SIGNAL_SET, - VALUE_SIGNAL_STATE - ]; - return { - start: function start() { - logger.info("starting..."); - logger.debug("setting up entities..."); - ha.startLifeLine("IR Connnected", nodeId, haDevice); - ha.registerEntity("IR Available", "binary_sensor", nodeId, "lifeline", haDevice, { - device_class: "connectivity", - expire_after: 5, - off_delay: 3, - entity_category: "diagnostic", - payload_available: "ON", - payload_not_available: "OFF" - }); - ha.registerEntity("Record Signal", "switch", nodeId, "record", haDevice, { - icon: "mdi:record-rec", - command_topic: RECORD_SIGNAL_SET, - device_class: "switch", - availability: availability - }); - ha.registerEntity("Signal", "text", nodeId, "signal", haDevice, { - command_topic: VALUE_SIGNAL_SET, - icon: "mdi:broadcast", - max: 255, - availability: availability - }); - ha.registerEntity("Play Signal", "button", nodeId, "play", haDevice, { - icon: "mdi:play", - command_topic: PLAY_SIGNAL_SET, - availability: availability - }); - logger.debug("setting default states...."); - ha.publishState(nodeId, "record", "OFF"); - ha.publishState(nodeId, "play", "OFF"); - logger.debug("registering events"); - mqtt.on("message", function(topic, message) { - logger.debug("message:", JSON.stringify({ - topic: topic, - message: message - })); - if (topic === RECORD_SIGNAL_SET) { - logger.debug("starting record"); - ir.record(); - ha.publishState(nodeId, "record", "ON"); - } else if (topic === PLAY_SIGNAL_SET) { - if (currentSignal !== null) { - logger.info("playing", currentSignal); - var arr = null; - try { - arr = convertStr2Uint32Array(currentSignal); - } catch (err) { - logger.error("invalid string signal set", JSON.stringify(err), err); - return; - } - ir.play(arr, function(err) { - if (err) { - logger.error("failed to play signal", JSON.stringify(err), err); - } else { - logger.debug("signal played!"); - } - }); - } else { - logger.error("cannot play an unset signal"); - } - } else if (topic === VALUE_SIGNAL_STATE) { - currentSignal = message; - logger.info("setting currentSignal", currentSignal); - } else if (topic === VALUE_SIGNAL_SET) { - ha.publishState(nodeId, "signal", message, { - retain: true - }); - } - }); - ir.on("recordComplete", function(data) { - var stringMessage = convertUint32Array2Str(data); - logger.debug("recording completed with", JSON.stringify({ - data: data, - stringMessage: stringMessage, - rev: convertStr2Uint32Array(stringMessage) - })); - if (stringMessage.length > 255) { - logger.error("stringMessage is too big! size=", stringMessage.length, "max=255"); - } - ha.publishState(nodeId, "signal", stringMessage, { - retain: true - }); - ha.publishState(nodeId, "record", "OFF"); - }); - logger.debug("subscribing to", set_topics); - mqtt.subscribe(set_topics); - logger.info("is up"); - } - }; + var constants = getConstants$1(ha, options); + var nodeId = constants.NODE_ID; + var state = makeIRSharedState(); + logger.info("starting..."); + logger.debug("setting up entities..."); + registerEntities(ha, haDevice, constants); + logger.debug("setting default states...."); + ha.publishState(nodeId, constants.RECORD_SIGNAL.objectId, "OFF"); + ha.publishState(nodeId, constants.PLAY_SIGNAL.objectId, "OFF"); + logger.debug("registering events"); + irMQTTHandler(mqtt, ha, nodeId, logger, state, constants); + handleIREvents(ha, logger, nodeId, state, constants); + logger.debug("subscribing to", constants.set_topics); + mqtt.subscribe(constants.set_topics.map(function(x) { + return x.mqttPrefix; + })); + logger.info("is up"); }; -/* Copyright (c) 2013 Gordon Williams, Pur3 Ltd - ------------------------------------------------------------------------------- - -All sections of code within this repository are licensed under an MIT License: - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. - ------------------------------------------------------------------------------ - -Modified by Flic Shortcut Labs. - -*/ /** 'private' constants */ function _array_like_to_array(arr, len) { - if (len == null || len > arr.length) len = arr.length; - for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i]; - return arr2; -} -function _array_without_holes(arr) { - if (Array.isArray(arr)) return _array_like_to_array(arr); -} -function _iterable_to_array(iter) { - if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); -} -function _non_iterable_spread() { - throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); -} -function _to_consumable_array(arr) { - return _array_without_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_spread(); -} -function _unsupported_iterable_to_array(o, minLen) { - if (!o) return; - if (typeof o === "string") return _array_like_to_array(o, minLen); - var n = Object.prototype.toString.call(o).slice(8, -1); - if (n === "Object" && o.constructor) n = o.constructor.name; - if (n === "Map" || n === "Set") return Array.from(n); - if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen); -} -var C = { +/** 'private' constants */ var C = { PROTOCOL_LEVEL: 4, DEF_PORT: 1883, - DEF_KEEP_ALIVE: 60 + DEF_KEEP_ALIVE: 60, + DEF_QOS: 0, + CONNECT_TIMEOUT: 10000, + PING_INTERVAL: 40 }; /** Control packet types */ var TYPE = { CONNECT: 1, @@ -799,10 +778,6 @@ var C = { PINGRESP: 13, DISCONNECT: 14 }; -var pakId = Math.floor(Math.random() * 65534); -Uint8Array.prototype.charCodeAt = function(a, b) { - return this.toString().charCodeAt(a, b); -}; /** Return Codes http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc385349256 @@ -814,153 +789,7 @@ Uint8Array.prototype.charCodeAt = function(a, b) { 4: "BAD_USER_NAME_OR_PASSWORD", 5: "NOT_AUTHORIZED" }; -/** MQTT constructor */ function MQTT(server, options) { - this.server = server; - options = options || {}; - this.port = options.port || C.DEF_PORT; - this.client_id = options.client_id || mqttUid(); - this.keep_alive = options.keep_alive || C.DEF_KEEP_ALIVE; - this.clean_session = options.clean_session || true; - this.username = options.username; - this.password = options.password; - this.client = false; - this.connected = false; - /* if keep_alive is less than the ping interval we need to use - a shorter ping interval, otherwise we'll just time out! */ this.ping_interval = this.keep_alive < this.C.PING_INTERVAL ? this.keep_alive - 5 : this.C.PING_INTERVAL; - this.protocol_name = options.protocol_name || "MQTT"; - this.protocol_level = options.protocol_level || C.PROTOCOL_LEVEL; - if (typeof this.client_id == "string") { - var payloadarray = [ - this.client_id.length >> 8, - this.client_id.length & 255 - ]; - var i = 2; - var messagearray = this.client_id.split(""); - for(var j = 0; j < this.client_id.length; j++){ - var _char = messagearray[j]; - var numberrepres = _char.charCodeAt(0); - payloadarray[i] = numberrepres; - i = i + 1; - } - this.client_id = payloadarray; - } - if (this.password) { - var payloadarray = [ - this.password.length >> 8, - this.password.length & 255 - ]; - var i = 2; - var messagearray = this.password.split(""); - for(var j = 0; j < this.password.length; j++){ - var _char = messagearray[j]; - var numberrepres = _char.charCodeAt(0); - payloadarray[i] = numberrepres; - i = i + 1; - } - this.password = payloadarray; - } - if (this.username) { - var payloadarray = [ - this.username.length >> 8, - this.username.length & 255 - ]; - var i = 2; - var messagearray = this.username.split(""); - for(var j = 0; j < this.username.length; j++){ - var _char = messagearray[j]; - var numberrepres = _char.charCodeAt(0); - payloadarray[i] = numberrepres; - i = i + 1; - } - this.username = payloadarray; - } -} -var __listeners = {}; -Object.prototype.on = function(type, fn) { - if (!__listeners[type]) { - __listeners[type] = []; - } - __listeners[type].push(fn); -}; -Object.prototype.emit = function(type) { - for(var _len = arguments.length, data = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++){ - data[_key - 1] = arguments[_key]; - } - if (__listeners[type]) { - __listeners[type].map(function(fn) { - fn.apply(void 0, _to_consumable_array(data)); - }); - } -}; -if (!Buffer.from) { - Buffer.from = function(a) { - return new Buffer(a); - }; -} -/** 'public' constants here */ MQTT.prototype.C = { - DEF_QOS: 0, - CONNECT_TIMEOUT: 10000, - PING_INTERVAL: 40 -}; -/* Utility functions ***************************/ var fromCharCode = String.fromCharCode; -/** MQTT string (length MSB, LSB + data) */ function mqttStr(s) { - var payloadarray = [ - s.length >> 8, - s.length & 255 - ]; - var i = 2; - var messagearray = s.split(""); - for(var j = 0; j < s.length; j++){ - var _char = messagearray[j]; - var numberrepres = _char.charCodeAt(0); - payloadarray[i] = numberrepres; - i = i + 1; - } - return payloadarray; -} -function mqttInt2Str(arr) { - var outStr = ""; - for(var i = 0; i < arr.length; i++){ - outStr += createEscapedHex(arr[i]); - } - return outStr; -} -/** MQTT packet length formatter - algorithm from reference docs */ function mqttPacketLength(length) { - var encLength = []; - var i = 0; - do { - var encByte = length & 127; - length = length >> 7; - // if there are more data to encode, set the top bit of this byte - if (length > 0) { - encByte += 128; - } - encLength[i] = encByte; - i++; - }while (length > 0); - return encLength; -} -/** MQTT packet length decoder - algorithm from reference docs */ function mqttPacketLengthDec(length) { - var bytes = 0; - var decL = 0; - var lb = 0; - do { - lb = length[bytes]; - decL |= (lb & 127) << bytes++ * 7; - }while (lb & 128 && bytes < 4); - return { - decLen: decL, - lenBy: bytes - }; -} -/** MQTT standard packet formatter */ function mqttPacket(cmd, variable, payload) { - var cmdAndLengthArray = [ - cmd - ].concat(mqttPacketLength(variable.length + payload.length)); - var headerAndPayloadArray = cmdAndLengthArray.concat(variable).concat(payload); - var messageBuffer = Buffer.from(headerAndPayloadArray); - return messageBuffer; -} + /** Generate random UID */ var mqttUid = function() { function s4() { var numberstring = Math.floor(1 + Math.random() * 10); @@ -988,28 +817,97 @@ function mqttInt2Str(arr) { return output; }; }(); -/** Generate PID */ function mqttPid() { - pakId = pakId > 65534 ? 1 : ++pakId; - return [ - pakId >> 8, - pakId & 0xff +/** MQTT string (length MSB, LSB + data) */ var mqttStr = function(s) { + var payloadarray = [ + s.length >> 8, + s.length & 255 ]; -} -/** Get PID from message */ function getPid(data) { + var i = 2; + var messagearray = s.split(""); + for(var j = 0; j < s.length; j++){ + var _char = messagearray[j]; + var numberrepres = _char.charCodeAt(0); + payloadarray[i] = numberrepres; + i = i + 1; + } + return payloadarray; +}; +var getClientId = function(options) { + if (typeof options.client_id == "string") { + return mqttStr(options.client_id); + } + return options.client_id; +}; +var setOptionDefaults = function(options) { + return { + port: options.port || C.DEF_PORT, + client_id: options.client_id || mqttUid(), + keep_alive: options.keep_alive || C.DEF_KEEP_ALIVE, + clean_session: options.clean_session || true, + username: options.username, + password: options.password, + protocol_name: options.protocol_name || "MQTT", + protocol_level: options.protocol_level || C.PROTOCOL_LEVEL + }; +}; +/** MQTT packet length formatter - algorithm from reference docs */ var mqttPacketLength = function(length) { + var encLength = []; + var i = 0; + do { + var encByte = length & 127; + length = length >> 7; + // if there are more data to encode, set the top bit of this byte + if (length > 0) { + encByte += 128; + } + encLength[i] = encByte; + i++; + }while (length > 0); + return encLength; +}; +var mqttPacketLengthDec = function(length) { + var bytes = 0; + var decL = 0; + var lb = 0; + do { + lb = length[bytes]; + decL |= (lb & 127) << bytes++ * 7; + }while (lb & 128 && bytes < 4); + return { + decLen: decL, + lenBy: bytes + }; +}; +var createBufferFromArray = function(a) { + if (Buffer.from) { + return Buffer.from(a); + } else { + return new Buffer(a); + } +}; +/** MQTT standard packet formatter */ var mqttPacket = function(cmd, variable, payload) { + var cmdAndLengthArray = [ + cmd + ].concat(mqttPacketLength(variable.length + payload.length)); + var headerAndPayloadArray = cmdAndLengthArray.concat(variable).concat(payload); + var messageBuffer = createBufferFromArray(headerAndPayloadArray); + return messageBuffer; +}; +/** Get PID from message */ var getPid = function(data) { return data.slice(0, 2); -} -/** PUBLISH control packet */ function mqttPublish(topic, message, qos, flags) { +}; +/** PUBLISH control packet */ var createMqttPublishPacket = function(topic, message, qos, flags, pid) { var cmd = TYPE.PUBLISH << 4 | qos << 1 | flags; var variable = mqttStr(topic); // Packet id must be included for QOS > 0 if (qos > 0) { - var newvariable = variable.concat(mqttPid()); + var newvariable = variable.concat(pid); return mqttPacket(cmd, newvariable, message); } else { return mqttPacket(cmd, variable, message); } -} -/** SUBSCRIBE control packet */ function mqttSubscribe(topic, qos) { +}; +/** SUBSCRIBE control packet */ var createMqttSubscribePacket = function(topic, qos, pid) { var cmd = TYPE.SUBSCRIBE << 4 | 2; var payloadarray = []; var i = 0; @@ -1020,294 +918,467 @@ function mqttInt2Str(arr) { payloadarray[i] = numberrepres; i = i + 1; } - return mqttPacket(cmd, mqttPid(), mqttStr(topic).concat([ + return mqttPacket(cmd, pid, mqttStr(topic).concat([ qos ])); -} -/** UNSUBSCRIBE control packet */ function mqttUnsubscribe(topic) { - var cmd = TYPE.UNSUBSCRIBE << 4 | 2; - return mqttPacket(cmd, mqttPid(), mqttStr(topic)); -} -/** Create escaped hex value from number */ function createEscapedHex(n) { - return fromCharCode(parseInt(n.toString(16), 16)); -} -// Handle a single packet of data -MQTT.prototype.packetHandler = function(data) { - // if we had some data left over from last - // time, add it on - if (this.partData && this.partData.length > 0) { - data = Buffer.from(Array.prototype.slice.call(this.partData).concat(Array.prototype.slice.call(data))); - this.partData = []; - } - // Figure out packet length... - var dLen = mqttPacketLengthDec(data.slice(1, data.length)); - var pLen = dLen.decLen + dLen.lenBy + 1; - // less than one packet? - if (data.length < pLen) { - this.partData = data; - return; - } - // Get the data for this packet - var pData = data.slice(1 + dLen.lenBy, pLen); - // more than one packet? re-emit it so we handle it later - if (data.length > pLen) { - this.client.emit("data", data.slice(pLen, data.length)); - } - // Now handle this MQTT packet - var cmd = data[0]; - var type = cmd >> 4; - if (type === TYPE.PUBLISH) { - var qos = (cmd & 0x6) >> 1; - var topic_len = pData[0] << 8 | pData[1]; - var msg_start = 2 + topic_len + (qos ? 2 : 0); - var parsedData = { - topic: pData.slice(2, 2 + topic_len), - message: pData.slice(msg_start, pData.length), - dup: (cmd & 0x8) >> 3, - qos: qos, - pid: qos ? pData.slice(2 + topic_len, 4 + topic_len) : 0, - retain: cmd & 0x1 - }; - if (parsedData.qos) { - this.client.write([ - (parsedData.qos == 1 ? TYPE.PUBACK : TYPE.PUBREC) << 4, - 2, - parsedData.pid - ]); - } - this.emit("publish", parsedData); - this.emit("message", mqttInt2Str(parsedData.topic), mqttInt2Str(parsedData.message)); - } else if (type === TYPE.PUBACK) { - this.emit("puback", data.charCodeAt(2) << 8 | data.charCodeAt(3)); - } else if (type === TYPE.PUBREC) { - var pubrelArray = [ - TYPE.PUBREL << 4 | 2, - 2 - ]; - var pidArray = Array.prototype.slice.call(getPid(pData)); - var pubrecResponse = pubrelArray.concat(pidArray); - this.client.write(Buffer.from(pubrecResponse)); - } else if (type === TYPE.PUBREL) { - var pubcompArray = [ - TYPE.PUBCOMP << 4, - 2 - ]; - var pidArray = Array.prototype.slice.call(getPid(pData)); - var pubrelResponse = pubcompArray.concat(pidArray); - this.client.write(pubrelResponse); - } else if (type === TYPE.PUBCOMP) { - this.emit("pubcomp", data.charCodeAt(2) << 8 | data.charCodeAt(3)); - } else if (type === TYPE.SUBACK) { - if (pData.length > 0) { - if (pData[pData.length - 1] == 0x80) { - this.emit("subscribed_fail"); - } else { - this.emit("subscribed"); - } - } - } else if (type === TYPE.UNSUBACK) { - this.emit("unsubscribed"); - } else if (type === TYPE.PINGREQ) { - this.client.write([ - TYPE.PINGRESP << 4, - 0 - ]); - } else if (type === TYPE.PINGRESP) { - this.emit("ping_reply"); - } else if (type === TYPE.CONNACK) { - if (this.ctimo) clearTimeout(this.ctimo); - this.ctimo = undefined; - this.partData = []; - var returnCode = pData[1]; - if (RETURN_CODES[returnCode] === "ACCEPTED") { - this.connected = true; - // start pinging - if (this.pintr) clearInterval(this.pintr); - this.pintr = setInterval(this.ping.bind(this), this.ping_interval * 1000); - // emit connected events - this.emit("connected"); - this.emit("connect"); - } else { - var mqttError = "Connection refused, "; - this.connected = false; - if (returnCode > 0 && returnCode < 6) { - mqttError += RETURN_CODES[returnCode]; - } else { - mqttError += "unknown return code: " + returnCode + "."; - } - this.emit("error", mqttError); - } - } else { - this.emit("error", "MQTT unsupported packet type: " + type); - } }; -/* Public interface ****************************/ /** Establish connection and set up keep_alive ping */ MQTT.prototype.connect = function(client) { - if (this.connected) return; - var mqo = this; - var onConnect = function onConnect() { - mqo.client = client; - // write connection message - var teststring = mqo.mqttConnect(mqo.client_id); - client.write(teststring); - // handle connection timeout if too slow - mqo.ctimo = setTimeout(function() { - mqo.ctimo = undefined; - mqo.emit("disconnected"); - mqo.disconnect(); - }, mqo.C.CONNECT_TIMEOUT); - // Incoming data - client.on("data", mqo.packetHandler.bind(mqo)); - // Socket closed - client.on("end", function() { - mqo._scktClosed(); + +function _array_like_to_array(arr, len) { + if (len == null || len > arr.length) len = arr.length; + for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i]; + return arr2; +} +function _array_without_holes(arr) { + if (Array.isArray(arr)) return _array_like_to_array(arr); +} +function _class_call_check(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } +} +function _defineProperties(target, props) { + for(var i = 0; i < props.length; i++){ + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ("value" in descriptor) descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } +} +function _create_class(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + return Constructor; +} +function _define_property$2(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true }); - }; - if (client) { - onConnect(); } else { - try { - var self = this; - client = require("net").Socket().connect({ - host: mqo.server, - port: mqo.port - }, onConnect); - client.on("error", function(err) { - self.emit("error", err.message); - }); - } catch (e) { - this.client = false; - this.emit("error", e.message); - } + obj[key] = value; } -}; -/** Called internally when the connection closes */ MQTT.prototype._scktClosed = function() { - if (this.connected) { + return obj; +} +function _iterable_to_array(iter) { + if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); +} +function _non_iterable_spread() { + throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); +} +function _to_consumable_array(arr) { + return _array_without_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_spread(); +} +function _unsupported_iterable_to_array(o, minLen) { + if (!o) return; + if (typeof o === "string") return _array_like_to_array(o, minLen); + var n = Object.prototype.toString.call(o).slice(8, -1); + if (n === "Object" && o.constructor) n = o.constructor.name; + if (n === "Map" || n === "Set") return Array.from(n); + if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen); +} +var FlicMQTT = /*#__PURE__*/ function() { + function FlicMQTT(server, _options) { + _class_call_check(this, FlicMQTT); + _define_property$2(this, "server", void 0); + _define_property$2(this, "options", void 0); + _define_property$2(this, "clientId", void 0); + _define_property$2(this, "connected", void 0); + _define_property$2(this, "pingInterval", void 0); + _define_property$2(this, "username", void 0); + _define_property$2(this, "password", void 0); + _define_property$2(this, "client", void 0); + _define_property$2(this, "__listeners", void 0); + _define_property$2(this, "pakId", void 0); + _define_property$2(this, "partData", void 0); + _define_property$2(this, "ctimo", void 0); + _define_property$2(this, "pintr", void 0); + this.server = server; this.connected = false; - this.client = false; - if (this.pintr) clearInterval(this.pintr); - if (this.ctimo) clearTimeout(this.ctimo); - this.pintr = this.ctimo = undefined; - this.emit("disconnected"); - this.emit("close"); - } -}; -/** Disconnect from server */ MQTT.prototype.disconnect = function() { - if (!this.client) return; - try { - this.client.write(Buffer.from([ - TYPE.DISCONNECT << 4, - 0 - ])); - } catch (e) { - return this._scktClosed(); - } - this.client.end(); - this.client = false; -}; -/** Publish message using specified topic. - opts = { - retain: bool // the server should retain this message and send it out again to new subscribers - dup : bool // indicate the message is a duplicate because original wasn't ACKed (QoS > 0 only) - } -*/ MQTT.prototype.publish = function(topic, message, opts) { - if (!this.client) return; - opts = opts || {}; - try { - var payloadarray = []; - var i = 0; - var messagearray = message.split(""); - for(var j = 0; j < message.length; j++){ - var _char = messagearray[j]; - var numberrepres = _char.charCodeAt(0); - payloadarray[i] = numberrepres; - i = i + 1; + this.username = null; + this.password = null; + this.client = null; + this.__listeners = { + close: [], + connected: [], + connect: [], + disconnected: [], + end: [], + error: [], + data: [], + publish: [], + message: [], + puback: [], + pubcomp: [], + subscribed: [], + unsubscribed: [], + subscribed_fail: [], + ping_reply: [] + }; + this.pakId = Math.floor(Math.random() * 65534); + this.partData = []; + this.ctimo = null; + this.pintr = null; + this.options = setOptionDefaults(_options); + this.clientId = getClientId(this.options); + if (this.options.username) { + this.username = mqttStr(this.options.username); } - var publishMessage = mqttPublish(topic, payloadarray, opts.qos || this.C.DEF_QOS, (opts.retain ? 1 : 0) | (opts.dup ? 8 : 0)); - this.client.write(publishMessage); - } catch (e) { - this._scktClosed(); - } -}; -/** Subscribe to topic (filter) */ MQTT.prototype.subscribe = function(topics, opts) { - if (!this.client) return; - opts = opts || {}; - var subs = []; - if ("string" === typeof topics) { - topics = [ - topics - ]; - } - if (Array.isArray(topics)) { - topics.forEach((function(topic) { - subs.push({ - topic: topic, - qos: opts.qos || this.C.DEF_QOS - }); - }).bind(this)); - } else { - Object.keys(topics).forEach(function(k) { - subs.push({ - topic: k, - qos: topics[k] - }); - }); - } - subs.forEach((function(sub) { - var subpacket = mqttSubscribe(sub.topic, sub.qos); - this.client.write(subpacket); - }).bind(this)); -}; -/** Unsubscribe to topic (filter) */ MQTT.prototype.unsubscribe = function(topic) { - if (!this.client) return; - this.client.write(mqttUnsubscribe(topic)); -}; -/** Send ping request to server */ MQTT.prototype.ping = function() { - if (!this.client) return; - try { - this.client.write(Buffer.from([ - TYPE.PINGREQ << 4, - 0 - ])); - } catch (e) { - this._scktClosed(); - } -}; -/* Packet specific functions *******************/ /** Create connection flags */ MQTT.prototype.createFlagsForConnection = function(options) { - var flags = 0; - flags |= this.username ? 0x80 : 0; - flags |= this.username && this.password ? 0x40 : 0; - flags |= options.clean_session ? 0x02 : 0; - return flags; -}; -/** CONNECT control packet - Clean Session and Userid/Password are currently only supported - connect flag. Wills are not - currently supported. - */ MQTT.prototype.mqttConnect = function(clean) { - var cmd = TYPE.CONNECT << 4; - var flags = this.createFlagsForConnection({ - clean_session: clean - }); - var keep_alive = [ - this.keep_alive >> 8, - this.keep_alive & 255 - ]; - /* payload */ var payload = this.client_id; - if (this.username) { - payload = payload.concat(this.username); - if (this.password) { - payload = payload.concat(this.password); + if (this.options.password) { + this.password = mqttStr(this.options.password); } + this.pingInterval = this.options.keep_alive < C.PING_INTERVAL ? this.options.keep_alive - 5 : C.PING_INTERVAL; } - return mqttPacket(cmd, mqttStr(this.protocol_name)/*protocol name*/ .concat([ - this.protocol_level - ])/*protocol level*/ .concat([ - flags - ]).concat(keep_alive), payload); -}; -/* Exports *************************************/ /** This is 'exported' so it can be used with `require('MQTT.js').create(server, options)` */ function create(server, options) { - return new MQTT(server, options); -} + _create_class(FlicMQTT, [ + { + key: "isConnected", + value: function isConnected() { + return this.client !== null; + } + }, + { + key: "on", + value: function on(type, fn) { + if (!this.__listeners[type]) { + this.__listeners[type] = []; + } + this.__listeners[type].push(fn); + } + }, + { + key: "emit", + value: function emit(type) { + for(var _len = arguments.length, data = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++){ + data[_key - 1] = arguments[_key]; + } + if (this.__listeners[type]) { + this.__listeners[type].map(function(fn) { + fn.apply(void 0, _to_consumable_array(data)); + }); + } + } + }, + { + key: "mqttPid", + value: function mqttPid() { + this.pakId = this.pakId > 65534 ? 1 : ++this.pakId; + return [ + this.pakId >> 8, + this.pakId & 0xff + ]; + } + }, + { + key: "connect", + value: function connect() { + console.log("Connecting..." + JSON.stringify({ + connected: this.connected + })); + if (this.connected) { + return; + } + var mqo = this; + try { + var client = this.client = net.createConnection({ + host: this.server, + port: this.options.port + }, function() { + // write connection message + var teststring = mqo.mqttConnect(!!mqo.clientId); + client.write(teststring); + // handle connection timeout if too slow + mqo.ctimo = setTimeout(function() { + mqo.ctimo = null; + mqo.emit("disconnected"); + mqo.disconnect(); + }, C.CONNECT_TIMEOUT); + // Incoming data + var handler = mqo.packetHandler.bind(mqo); + client.on("data", handler); + // Socket closed + client.on("end", function() { + mqo._scktClosed(); + }); + }); + } catch (e) { + this.client = null; + this.emit("error", e.message); + } + } + }, + { + /** Called internally when the connection closes */ key: "_scktClosed", + value: function _scktClosed() { + if (this.connected) { + this.client = null; + this.connected = false; + if (this.pintr) clearInterval(this.pintr); + if (this.ctimo) clearTimeout(this.ctimo); + this.pintr = this.ctimo = undefined; + this.emit("disconnected"); + this.emit("close"); + } + } + }, + { + /** Disconnect from server */ key: "disconnect", + value: function disconnect() { + if (!this.client) return; + try { + this.client.write(createBufferFromArray([ + TYPE.DISCONNECT << 4, + 0 + ])); + } catch (e) { + return this._scktClosed(); + } + this.client.end(); + this.client = null; + } + }, + { + /** Create connection flags */ key: "createFlagsForConnection", + value: function createFlagsForConnection(clean) { + var flags = 0; + flags |= this.username ? 0x80 : 0; + flags |= this.username && this.password ? 0x40 : 0; + flags |= clean ? 0x02 : 0; + return flags; + } + }, + { + /** CONNECT control packet + Clean Session and Userid/Password are currently only supported + connect flag. Wills are not + currently supported. + */ key: "mqttConnect", + value: function mqttConnect(clean) { + var cmd = TYPE.CONNECT << 4; + var flags = this.createFlagsForConnection(clean); + var keep_alive = [ + this.options.keep_alive >> 8, + this.options.keep_alive & 255 + ]; + /* payload */ var payload = this.clientId; + if (this.username) { + payload = payload.concat(this.username); + if (this.password) { + payload = payload.concat(this.password); + } + } + return mqttPacket(cmd, mqttStr(this.options.protocol_name)/*protocol name*/ .concat([ + this.options.protocol_level + ])/*protocol level*/ .concat([ + flags + ]).concat(keep_alive), payload); + } + }, + { + key: "packetHandler", + value: function packetHandler(data) { + if (!this.client) { + this.emit("error", "disconnected mid packet handling"); + throw new Error("disconnected mid packet handling"); + } + // if we had some data left over from last + // time, add it on + if (this.partData && this.partData.length > 0) { + data = createBufferFromArray(Array.prototype.slice.call(this.partData).concat(Array.prototype.slice.call(data))); + this.partData = []; + } + // Figure out packet length... + var dLen = mqttPacketLengthDec(data.slice(1, data.length)); + var pLen = dLen.decLen + dLen.lenBy + 1; + // less than one packet? + if (data.length < pLen) { + this.partData = data; + return; + } + // Get the data for this packet + var pData = data.slice(1 + dLen.lenBy, pLen); + // Handle this MQTT packet + var cmd = data[0]; + var type = cmd >> 4; + if (type === TYPE.PUBLISH) { + var qos = (cmd & 0x6) >> 1; + var topic_len = pData[0] << 8 | pData[1]; + var msg_start = 2 + topic_len + (qos ? 2 : 0); + var parsedData = { + topic: pData.slice(2, 2 + topic_len).toString("utf8"), + message: pData.slice(msg_start, pData.length).toString("utf8"), + dup: (cmd & 0x8) >> 3, + qos: qos, + pid: qos ? pData.slice(2 + topic_len, 4 + topic_len) : 0, + retain: cmd & 0x1 + }; + if (parsedData.qos) { + var _d = (parsedData.qos == 1 ? TYPE.PUBACK : TYPE.PUBREC) << 4; + this.client.write([ + _d, + 2, + parsedData.pid + ]); + } + this.emit("publish", parsedData); + this.emit("message", parsedData.topic, parsedData.message); + } else if (type === TYPE.PUBACK) { + this.emit("puback", data.toString().charCodeAt(2) << 8 | data.toString().charCodeAt(3)); + } else if (type === TYPE.PUBREC) { + var pubrelArray = [ + TYPE.PUBREL << 4 | 2, + 2 + ]; + var pidArray = Array.prototype.slice.call(getPid(pData)); + var pubrecResponse = pubrelArray.concat(pidArray); + this.client.write(Buffer.from(pubrecResponse)); + } else if (type === TYPE.PUBREL) { + var pubcompArray = [ + TYPE.PUBCOMP << 4, + 2 + ]; + var pidArray = Array.prototype.slice.call(getPid(pData)); + var pubrelResponse = pubcompArray.concat(pidArray); + this.client.write(pubrelResponse); + } else if (type === TYPE.PUBCOMP) { + this.emit("pubcomp", data.toString().charCodeAt(2) << 8 | data.toString().charCodeAt(3)); + } else if (type === TYPE.SUBACK) { + if (pData.length > 0) { + if (pData[pData.length - 1] == 0x80) { + this.emit("subscribed_fail"); + } else { + this.emit("subscribed"); + } + } + } else if (type === TYPE.UNSUBACK) { + this.emit("unsubscribed"); + } else if (type === TYPE.PINGREQ) { + this.client.write([ + TYPE.PINGRESP << 4, + 0 + ]); + } else if (type === TYPE.PINGRESP) { + this.emit("ping_reply"); + } else if (type === TYPE.CONNACK) { + if (this.ctimo) clearTimeout(this.ctimo); + this.ctimo = undefined; + this.partData = []; + var returnCode = pData[1]; + if (RETURN_CODES[returnCode] === "ACCEPTED") { + this.connected = true; + // start pinging + if (this.pintr) clearInterval(this.pintr); + this.pintr = setInterval(this.ping.bind(this), this.pingInterval * 1000); + // emit connected events + this.emit("connected"); + this.emit("connect"); + } else { + var mqttError = "Connection refused, "; + this.connected = false; + if (returnCode > 0 && returnCode < 6) { + mqttError += RETURN_CODES[returnCode]; + } else { + mqttError += "unknown return code: " + returnCode + "."; + } + this.emit("error", mqttError); + } + // more than one packet? re-emit it so we handle it later + if (data.length > pLen) { + this.client.emit("data", data.slice(pLen, data.length)); + } + } else { + this.emit("error", "MQTT unsupported packet type: " + type); + } + } + }, + { + /** Unsubscribe to topic (filter) */ key: "unsubscribe", + value: function unsubscribe(topic) { + if (!this.client) return; + var cmd = TYPE.UNSUBSCRIBE << 4 | 2; + this.client.write(mqttPacket(cmd, this.mqttPid(), mqttStr(topic))); + } + }, + { + /** Send ping request to server */ key: "ping", + value: function ping() { + if (!this.client) return; + try { + this.client.write(Buffer.from([ + TYPE.PINGREQ << 4, + 0 + ])); + } catch (e) { + this._scktClosed(); + } + } + }, + { + /** Publish message using specified topic. + opts = { + retain: bool // the server should retain this message and send it out again to new subscribers + dup : bool // indicate the message is a duplicate because original wasn't ACKed (QoS > 0 only) + } + */ key: "publish", + value: function publish(topic, message, opts) { + if (!this.client) return; + opts = opts || {}; + try { + var payloadarray = []; + var i = 0; + var messagearray = message.split(""); + for(var j = 0; j < message.length; j++){ + var _char = messagearray[j]; + var numberrepres = _char.charCodeAt(0); + payloadarray[i] = numberrepres; + i = i + 1; + } + var publishMessage = createMqttPublishPacket(topic, payloadarray, opts.qos || C.DEF_QOS, (opts.retain ? 1 : 0) | (opts.dup ? 8 : 0), this.mqttPid()); + this.client.write(publishMessage); + } catch (e) { + this._scktClosed(); + } + } + }, + { + /** Subscribe to topic (filter) */ key: "subscribe", + value: function subscribe(topics) { + var opts = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}; + if (!this.client) return; + var client = this.client; + var mqo = this; + opts = opts || {}; + var subs = []; + if ("string" === typeof topics) { + topics = [ + topics + ]; + } + if (Array.isArray(topics)) { + topics.forEach(function(topic) { + subs.push({ + topic: topic, + qos: opts.qos || C.DEF_QOS + }); + }); + } else { + Object.keys(topics).forEach(function(k) { + subs.push({ + topic: k, + qos: topics[k] + }); + }); + } + subs.forEach(function(sub) { + var subpacket = createMqttSubscribePacket(sub.topic, sub.qos, mqo.mqttPid()); + client.write(subpacket); + }); + } + } + ]); + return FlicMQTT; +}(); function _define_property$1(obj, key, value) { if (key in obj) { @@ -1468,7 +1539,7 @@ function _object_spread_props(target, source) { return target; } var start = function(options) { - var mqttServer = create(options.mqtt.host, _object_spread_props(_object_spread({}, options.mqtt), { + var mqttServer = new FlicMQTT(options.mqtt.host, _object_spread_props(_object_spread({}, options.mqtt), { keep_alive: true })); var _options_debug; @@ -1497,7 +1568,7 @@ var start = function(options) { makeButtonController(ha, options.flicBtns).start(); } if (!((_options_flicIR = options.flicIR) === null || _options_flicIR === void 0 ? void 0 : _options_flicIR.disabled)) { - makeIRController(ha, mqttServer, options.flicIR).start(); + startIRController(ha, mqttServer, options.flicIR); } if (!((_options_flicHub = options.flicHub) === null || _options_flicHub === void 0 ? void 0 : _options_flicHub.disabled)) { startFlicHubController(ha, mqttServer, options.flicHub); @@ -1510,16 +1581,16 @@ var start = function(options) { throw new Error("Crashed"); }, 1000); }); - mqttServer.on("disconnected", function(err) { - logger.info("'Error' disconnected", JSON.stringify(err)); + mqttServer.on("disconnected", function() { + logger.info("Lost access - disconnected"); setTimeout(function() { - throw new Error("Crashed"); + throw new Error("disconnected"); }, 1000); }); - mqttServer.on("close", function(err) { - logger.info("'Error' close", JSON.stringify(err)); + mqttServer.on("close", function() { + logger.info("Lost access - close"); setTimeout(function() { - throw new Error("Crashed"); + throw new Error("closed"); }, 1000); }); mqttServer.connect(); diff --git a/src/ha_mqtt/index.ts b/src/ha_mqtt/index.ts index 312e1b6..f53dd11 100644 --- a/src/ha_mqtt/index.ts +++ b/src/ha_mqtt/index.ts @@ -1,13 +1,13 @@ import { makeLogger } from "../Logger"; -import { MQTT } from "../mqtt"; +import { FlicMQTT } from "../mqtt_client/index"; import { makeOptions } from "./utils"; export type HAmqtt = ReturnType; export function makeHAmqtt( - mqttServer: MQTT, - options: Partial = {}, + mqttServer: FlicMQTT, + _options: Partial = {}, ) { - options = makeOptions(options); + const options = makeOptions(_options); const logger = makeLogger("mqtt:ha", options.debug); logger.info("starting...", JSON.stringify(options, null, 4)); const genFlicPrefix = (nodeId: string, objectId: string): string => { diff --git a/src/hub_controller/index.ts b/src/hub_controller/index.ts index 5fc6318..fd9e3ac 100644 --- a/src/hub_controller/index.ts +++ b/src/hub_controller/index.ts @@ -1,6 +1,6 @@ import { HAmqtt } from "../ha_mqtt/index"; import { makeLogger } from "../Logger"; -import { MQTT } from "../mqtt"; +import { FlicMQTT } from "../mqtt_client/index"; import flichub from "flicapp"; import { makeOptions, @@ -12,7 +12,7 @@ import { virtualDeviceUpdateHandler } from "./virtual_device_update"; export const startFlicHubController = ( ha: HAmqtt, - mqtt: MQTT, + mqtt: FlicMQTT, _options: Partial = {}, ) => { const options = makeOptions(_options); diff --git a/src/index.ts b/src/index.ts index 54a64f2..8f89447 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,14 +1,14 @@ import { makeButtonController } from "./button_controller/index"; import { makeHAmqtt } from "./ha_mqtt/index"; -import { makeIRController } from "./ir_controller/index"; +import { startIRController } from "./ir_controller/index"; import { makeLogger } from "./Logger"; -import * as mqtt from "./mqtt"; +import { FlicMQTT } from "./mqtt_client/index"; import { startFlicHubController } from "./hub_controller/index"; export const start = (options: Options) => { - const mqttServer = mqtt.create(options.mqtt.host, { + const mqttServer = new FlicMQTT(options.mqtt.host, { ...options.mqtt, keep_alive: true, }); @@ -28,7 +28,7 @@ export const start = (options: Options) => { makeButtonController(ha, options.flicBtns).start(); } if (!options.flicIR?.disabled) { - makeIRController(ha, mqttServer, options.flicIR).start(); + startIRController(ha, mqttServer, options.flicIR); } if (!options.flicHub?.disabled) { startFlicHubController(ha, mqttServer, options.flicHub); @@ -41,16 +41,16 @@ export const start = (options: Options) => { throw new Error("Crashed"); }, 1000); }); - mqttServer.on("disconnected", function (err) { - logger.info("'Error' disconnected", JSON.stringify(err)); + mqttServer.on("disconnected", function () { + logger.info("Lost access - disconnected"); setTimeout(function () { - throw new Error("Crashed"); + throw new Error("disconnected"); }, 1000); }); - mqttServer.on("close", function (err) { - logger.info("'Error' close", JSON.stringify(err)); + mqttServer.on("close", function () { + logger.info("Lost access - close"); setTimeout(function () { - throw new Error("Crashed"); + throw new Error("closed"); }, 1000); }); mqttServer.connect(); diff --git a/src/ir_controller/entity_controller.ts b/src/ir_controller/entity_controller.ts new file mode 100644 index 0000000..94cd85f --- /dev/null +++ b/src/ir_controller/entity_controller.ts @@ -0,0 +1,69 @@ +import { HAmqtt } from "../ha_mqtt/index"; +import { IRConstants } from "./utils"; + +export const registerEntities = ( + ha: HAmqtt, + haDevice: HADevice, + { + NODE_ID, + LIFELINE_SGINAL, + RECORD_SIGNAL, + RECORD_SIGNAL_SET, + VALUE_SIGNAL_SET, + VALUE_SIGNAL_STATE, + PLAY_SIGNAL, + PLAY_SIGNAL_SET, + }: IRConstants, +) => { + const availability = [ + { + payload_available: "ON", + payload_not_available: "unavailable", + topic: LIFELINE_SGINAL.mqttPrefix, + }, + ]; + ha.startLifeLine( + "IR Connnected", + NODE_ID, + haDevice, + LIFELINE_SGINAL.objectId, + ); + ha.registerEntity( + "Record Signal", + "switch", + NODE_ID, + RECORD_SIGNAL.objectId, + haDevice, + { + icon: "mdi:record-rec", + command_topic: RECORD_SIGNAL_SET.mqttPrefix, + device_class: "switch", + availability, + }, + ); + ha.registerEntity( + "Signal", + "text", + NODE_ID, + VALUE_SIGNAL_STATE.objectId, + haDevice, + { + command_topic: VALUE_SIGNAL_SET.mqttPrefix, + icon: "mdi:broadcast", + max: 255, + availability, + }, + ); + ha.registerEntity( + "Play Signal", + "button", + NODE_ID, + PLAY_SIGNAL.objectId, + haDevice, + { + icon: "mdi:play", + command_topic: PLAY_SIGNAL_SET.mqttPrefix, + availability, + }, + ); +}; diff --git a/src/ir_controller/index.ts b/src/ir_controller/index.ts index 8946869..824361a 100644 --- a/src/ir_controller/index.ts +++ b/src/ir_controller/index.ts @@ -2,20 +2,24 @@ import ir from "ir"; import { HAmqtt } from "../ha_mqtt/index"; import { makeLogger } from "../Logger"; -import { MQTT } from "../mqtt"; +import { FlicMQTT } from "../mqtt_client/index"; import { + IRConstants, NODE_ID, - convertStr2Uint32Array, - convertUint32Array2Str, + getConstants, + makeIRSharedState, makeOptions, } from "./utils"; +import { registerEntities } from "./entity_controller"; +import { irMQTTHandler as handleMqttIREvents } from "./mqtt_handler"; +import { handleIREvents } from "./ir_handler"; -export const makeIRController = ( +export const startIRController = ( ha: HAmqtt, - mqtt: MQTT, - options: Partial = {}, + mqtt: FlicMQTT, + _options: Partial = {}, ) => { - options = makeOptions(options); + const options = makeOptions(_options); const logger = makeLogger("ir", options.debug); const haDevice: HADevice = { name: "IR", @@ -24,130 +28,21 @@ export const makeIRController = ( identifiers: ["FlicHubIR"], configuration_url: "https://hubsdk.flic.io/", }; - const nodeId = `${NODE_ID}${options.uniqueId}`; - const LIFELINE_SGINAL = ha.genFlicPrefix(nodeId, "lifeline"); - const RECORD_SIGNAL_SET = ha.genFlicPrefix(nodeId, "record/set"); - const VALUE_SIGNAL_SET = ha.genFlicPrefix(nodeId, "signal/set"); - const VALUE_SIGNAL_STATE = ha.genFlicPrefix(nodeId, "signal"); - const PLAY_SIGNAL_SET = ha.genFlicPrefix(nodeId, "play/set"); - const availability = [ - { - payload_available: "ON", - payload_not_available: "unavailable", - topic: LIFELINE_SGINAL, - }, - ]; - let currentSignal: string | null = null; + const constants: IRConstants = getConstants(ha, options); + const nodeId = constants.NODE_ID; - const set_topics = [ - RECORD_SIGNAL_SET, - VALUE_SIGNAL_SET, - PLAY_SIGNAL_SET, - VALUE_SIGNAL_STATE, - ]; + const state = makeIRSharedState(); - return { - start() { - logger.info("starting..."); - logger.debug("setting up entities..."); - ha.startLifeLine("IR Connnected", nodeId, haDevice); - ha.registerEntity( - "IR Available", - "binary_sensor", - nodeId, - "lifeline", - haDevice, - { - device_class: "connectivity", - expire_after: 5, - off_delay: 3, - entity_category: "diagnostic", - payload_available: "ON", - payload_not_available: "OFF", - }, - ); - ha.registerEntity("Record Signal", "switch", nodeId, "record", haDevice, { - icon: "mdi:record-rec", - command_topic: RECORD_SIGNAL_SET, - device_class: "switch", - availability, - }); - ha.registerEntity("Signal", "text", nodeId, "signal", haDevice, { - command_topic: VALUE_SIGNAL_SET, - icon: "mdi:broadcast", - max: 255, - availability, - }); - ha.registerEntity("Play Signal", "button", nodeId, "play", haDevice, { - icon: "mdi:play", - command_topic: PLAY_SIGNAL_SET, - availability, - }); - logger.debug("setting default states...."); - ha.publishState(nodeId, "record", "OFF"); - ha.publishState(nodeId, "play", "OFF"); - logger.debug("registering events"); - mqtt.on("message", (topic, message) => { - logger.debug("message:", JSON.stringify({ topic, message })); - if (topic === RECORD_SIGNAL_SET) { - logger.debug("starting record"); - ir.record(); - ha.publishState(nodeId, "record", "ON"); - } else if (topic === PLAY_SIGNAL_SET) { - if (currentSignal !== null) { - logger.info("playing", currentSignal); - let arr: Uint32Array | null = null; - try { - arr = convertStr2Uint32Array(currentSignal); - } catch (err) { - logger.error( - "invalid string signal set", - JSON.stringify(err), - err, - ); - return; - } - ir.play(arr, (err) => { - if (err) { - logger.error("failed to play signal", JSON.stringify(err), err); - } else { - logger.debug("signal played!"); - } - }); - } else { - logger.error("cannot play an unset signal"); - } - } else if (topic === VALUE_SIGNAL_STATE) { - currentSignal = message; - logger.info("setting currentSignal", currentSignal); - } else if (topic === VALUE_SIGNAL_SET) { - ha.publishState(nodeId, "signal", message, { retain: true }); - } - }); - ir.on("recordComplete", (data) => { - const stringMessage = convertUint32Array2Str(data); - logger.debug( - "recording completed with", - JSON.stringify({ - data, - stringMessage, - rev: convertStr2Uint32Array(stringMessage), - }), - ); - if (stringMessage.length > 255) { - logger.error( - "stringMessage is too big! size=", - stringMessage.length, - "max=255", - ); - } - ha.publishState(nodeId, "signal", stringMessage, { retain: true }); - ha.publishState(nodeId, "record", "OFF"); - }); - - logger.debug("subscribing to", set_topics); - mqtt.subscribe(set_topics); - logger.info("is up"); - }, - }; + logger.info("starting..."); + logger.debug("setting up entities..."); + registerEntities(ha, haDevice, constants); + logger.debug("setting default states...."); + ha.publishState(nodeId, constants.RECORD_SIGNAL.objectId, "OFF"); + ha.publishState(nodeId, constants.PLAY_SIGNAL.objectId, "OFF"); + logger.debug("registering events"); + handleMqttIREvents(mqtt, ha, nodeId, logger, state, constants); + handleIREvents(ha, logger, nodeId, state, constants); + logger.debug("subscribing to", constants.set_topics); + mqtt.subscribe(constants.set_topics.map((x) => x.mqttPrefix)); + logger.info("is up"); }; diff --git a/src/ir_controller/ir_handler.ts b/src/ir_controller/ir_handler.ts new file mode 100644 index 0000000..96d0e8b --- /dev/null +++ b/src/ir_controller/ir_handler.ts @@ -0,0 +1,38 @@ +import ir from "ir"; +import { Logger } from "../Logger"; +import { + IRConstants, + IRState, + convertStr2Uint32Array, + convertUint32Array2Str, +} from "./utils"; +import { HAmqtt } from "../ha_mqtt/index"; + +export const handleIREvents = ( + ha: HAmqtt, + logger: Logger, + nodeId: string, + state: IRState, + { VALUE_SIGNAL_STATE, RECORD_SIGNAL }: IRConstants, +) => { + ir.on("recordComplete", (data) => { + logger.info("recordComplete", data); + if (data.length === 0) { + logger.error("Failed to record any data"); + return; + } + const stringMessage = convertUint32Array2Str(data); + logger.info( + "recording completed with", + JSON.stringify({ + stringMessage, + }), + ); + state.setCurrentSignal(stringMessage); + ha.publishState(nodeId, VALUE_SIGNAL_STATE.objectId, stringMessage, { + retain: true, + }); + state.setRecordingState(false); + ha.publishState(nodeId, RECORD_SIGNAL.objectId, "OFF"); + }); +}; diff --git a/src/ir_controller/mqtt_handler.ts b/src/ir_controller/mqtt_handler.ts new file mode 100644 index 0000000..d1953d1 --- /dev/null +++ b/src/ir_controller/mqtt_handler.ts @@ -0,0 +1,54 @@ +import ir from "ir"; +import { Logger } from "../Logger"; +import { FlicMQTT } from "../mqtt_client/index"; +import { IRConstants, IRState, convertStr2Uint32Array } from "./utils"; +import { HAmqtt } from "../ha_mqtt/index"; + +export const irMQTTHandler = ( + mqtt: FlicMQTT, + ha: HAmqtt, + nodeId: string, + logger: Logger, + state: IRState, + { RECORD_SIGNAL_SET, VALUE_SIGNAL_SET, RECORD_SIGNAL }: IRConstants, +) => { + logger.info(`Registering ir mqtt handler ${nodeId} ${state.currentSignal()}`); + mqtt.on("message", (topic, message) => { + logger.info( + "message:", + JSON.stringify({ + topic, + message, + state, + currentSignal: state.currentSignal(), + }), + ); + if (topic === VALUE_SIGNAL_SET.mqttPrefix) { + state.setCurrentSignal(message); + logger.info("setting currentSignal", message); + } else if (topic === RECORD_SIGNAL_SET.mqttPrefix) { + logger.info(`IR module is being set to ${message}`); + if (message === "OFF" && state.isRecording()) { + try { + ir.cancelRecord(); + state.setRecordingState(false); + } catch (err) { + logger.error( + `Failed to stop record, check you have the latest version of the sdk!`, + ); + state.setRecordingState(true); + ha.publishState(nodeId, RECORD_SIGNAL.objectId, "OFF", { + dup: false, + }); + } + } else if (!state.isRecording()) { + ir.record(); + state.setRecordingState(true); + } else { + logger.info( + `Doing nothing state.isRecording()=${state.isRecording()} state.currentSignal()=${state.currentSignal()}`, + ); + } + } + }); +}; diff --git a/src/ir_controller/utils.ts b/src/ir_controller/utils.ts index 304690b..41e669f 100644 --- a/src/ir_controller/utils.ts +++ b/src/ir_controller/utils.ts @@ -1,3 +1,5 @@ +import { HAmqtt } from "../ha_mqtt/index"; + export const NODE_ID = "FlicHubIR"; export const convertUint32Array2Str = (arr: Uint32Array): string => { let outStr = []; @@ -18,3 +20,47 @@ export const makeOptions = ( uniqueId: "0", ...opt, }); + +export type IRState = ReturnType; +export const makeIRSharedState = () => { + let currentSignal = ""; + let isRecording: boolean = false; + return { + isRecording() { + return isRecording; + }, + setRecordingState(newValue: boolean) { + isRecording = newValue; + }, + currentSignal() { + return currentSignal; + }, + setCurrentSignal(newValue: string) { + currentSignal = newValue; + }, + }; +}; + +export type IRConstants = ReturnType; +export type IRConstantsNames = keyof IRConstants; +export const getConstants = (ha: HAmqtt, options: IRControllerOpt) => { + const nodeId = `${NODE_ID}${options.uniqueId}`; + const LIFELINE_SGINAL = ha.genFlicPrefixObject(nodeId, "lifeline"); + const RECORD_SIGNAL = ha.genFlicPrefixObject(nodeId, "record"); + const RECORD_SIGNAL_SET = ha.genFlicPrefixObject(nodeId, "record/set"); + const VALUE_SIGNAL_SET = ha.genFlicPrefixObject(nodeId, "signal/set"); + const VALUE_SIGNAL_STATE = ha.genFlicPrefixObject(nodeId, "signal"); + const PLAY_SIGNAL = ha.genFlicPrefixObject(nodeId, "play"); + const PLAY_SIGNAL_SET = ha.genFlicPrefixObject(nodeId, "play/set"); + return { + NODE_ID: nodeId, + LIFELINE_SGINAL, + RECORD_SIGNAL, + RECORD_SIGNAL_SET, + VALUE_SIGNAL_SET, + VALUE_SIGNAL_STATE, + PLAY_SIGNAL, + PLAY_SIGNAL_SET, + set_topics: [RECORD_SIGNAL_SET, VALUE_SIGNAL_SET, PLAY_SIGNAL_SET], + }; +}; diff --git a/src/mqtt_client/constants.ts b/src/mqtt_client/constants.ts new file mode 100644 index 0000000..0a60435 --- /dev/null +++ b/src/mqtt_client/constants.ts @@ -0,0 +1,40 @@ +/** 'private' constants */ +export const C = { + PROTOCOL_LEVEL: 4, // MQTT protocol level + DEF_PORT: 1883, // MQTT default server port + DEF_KEEP_ALIVE: 60, // Default keep_alive (s) + DEF_QOS: 0, // Default QOS level + CONNECT_TIMEOUT: 10000, // Time (ms) to wait for CONNACK + PING_INTERVAL: 40, // Server ping interval (s) +}; + +/** Control packet types */ +export const TYPE = { + CONNECT: 1, + CONNACK: 2, + PUBLISH: 3, + PUBACK: 4, + PUBREC: 5, + PUBREL: 6, + PUBCOMP: 7, + SUBSCRIBE: 8, + SUBACK: 9, + UNSUBSCRIBE: 10, + UNSUBACK: 11, + PINGREQ: 12, + PINGRESP: 13, + DISCONNECT: 14, +}; + +/** + Return Codes + http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc385349256 + **/ +export const RETURN_CODES: Record = { + 0: "ACCEPTED", + 1: "UNACCEPTABLE_PROTOCOL_VERSION", + 2: "IDENTIFIER_REJECTED", + 3: "SERVER_UNAVAILABLE", + 4: "BAD_USER_NAME_OR_PASSWORD", + 5: "NOT_AUTHORIZED", +}; diff --git a/src/mqtt_client/index.ts b/src/mqtt_client/index.ts new file mode 100644 index 0000000..87d55af --- /dev/null +++ b/src/mqtt_client/index.ts @@ -0,0 +1,433 @@ +import net, { Socket } from "net"; +import { C, RETURN_CODES, TYPE } from "./constants"; +import { + mqttStr, + getClientId, + setOptionDefaults, + mqttPacketLengthDec, + mqttPacket, + createBufferFromArray, + getPid, + createMqttPublishPacket, + createMqttSubscribePacket, +} from "./utils"; +export type ParsedMQTTData = { + topic: string; + message: string; + dup: number; + qos: number; + pid: number | Buffer; + retain: number; +}; +type MQTTEventMapping = { + error: (err: string) => void; + disconnected: () => void; + connected: () => void; + connect: () => void; + close: () => void; + end: () => void; + data: (d: number[]) => void; + publish: (d: ParsedMQTTData) => void; + message: ( + topic: ParsedMQTTData["topic"], + message: ParsedMQTTData["message"], + ) => void; + puback: (n: number) => void; + pubcomp: (n: number) => void; + subscribed_fail: () => void; + subscribed: () => void; + unsubscribed: () => void; + ping_reply: () => void; +}; +type MQTTEventName = keyof MQTTEventMapping; +type _Listener = MQTTEventMapping[T]; +export class FlicMQTT { + private options: MQTTOptions; + private clientId: number[]; + private connected: boolean = false; + private pingInterval: number; + private username: number[] | null = null; + private password: number[] | null = null; + private client: Socket | null = null; + private __listeners: Record[]> = { + close: [], + connected: [], + connect: [], + disconnected: [], + end: [], + error: [], + data: [], + publish: [], + message: [], + puback: [], + pubcomp: [], + subscribed: [], + unsubscribed: [], + subscribed_fail: [], + ping_reply: [], + }; + private pakId = Math.floor(Math.random() * 65534); + + public partData: number[] | Buffer = []; + public ctimo: any | null = null; + public pintr: any | null = null; + + constructor( + private server: string, + _options: Partial, + ) { + this.options = setOptionDefaults(_options); + this.clientId = getClientId(this.options); + if (this.options.username) { + this.username = mqttStr(this.options.username); + } + if (this.options.password) { + this.password = mqttStr(this.options.password); + } + this.pingInterval = + this.options.keep_alive < C.PING_INTERVAL + ? this.options.keep_alive - 5 + : C.PING_INTERVAL; + } + + isConnected() { + return this.client !== null; + } + + on(type: T, fn: _Listener) { + if (!this.__listeners[type]) { + this.__listeners[type] = []; + } + this.__listeners[type].push(fn); + } + + emit(type: T, ...data: Parameters<_Listener>) { + if (this.__listeners[type]) { + this.__listeners[type].map(function (fn) { + fn(...data); + }); + } + } + + mqttPid() { + this.pakId = this.pakId > 65534 ? 1 : ++this.pakId; + return [this.pakId >> 8, this.pakId & 0xff]; + } + + connect() { + console.log( + "Connecting..." + + JSON.stringify({ + connected: this.connected, + }), + ); + if (this.connected) { + return; + } + const mqo = this; + try { + const client = (this.client = net.createConnection( + { host: this.server, port: this.options.port }, + () => { + // write connection message + const teststring = mqo.mqttConnect(!!mqo.clientId); + client.write(teststring); + // handle connection timeout if too slow + mqo.ctimo = setTimeout(function () { + mqo.ctimo = null; + mqo.emit("disconnected"); + mqo.disconnect(); + }, C.CONNECT_TIMEOUT); + // Incoming data + const handler = mqo.packetHandler.bind(mqo); + client.on("data", handler as any); + // Socket closed + client.on("end", function () { + mqo._scktClosed(); + }); + }, + )); + } catch (e) { + this.client = null; + this.emit("error", (e as Error).message); + } + } + + /** Called internally when the connection closes */ + _scktClosed() { + if (this.connected) { + this.client = null; + this.connected = false; + if (this.pintr) clearInterval(this.pintr); + if (this.ctimo) clearTimeout(this.ctimo); + this.pintr = this.ctimo = undefined; + this.emit("disconnected"); + this.emit("close"); + } + } + + /** Disconnect from server */ + disconnect() { + if (!this.client) return; + try { + this.client.write(createBufferFromArray([TYPE.DISCONNECT << 4, 0])); + } catch (e) { + return this._scktClosed(); + } + this.client.end(); + this.client = null; + } + + /** Create connection flags */ + createFlagsForConnection(clean: boolean) { + var flags = 0; + flags |= this.username ? 0x80 : 0; + flags |= this.username && this.password ? 0x40 : 0; + flags |= clean ? 0x02 : 0; + return flags; + } + /** CONNECT control packet + Clean Session and Userid/Password are currently only supported + connect flag. Wills are not + currently supported. + */ + mqttConnect(clean: boolean) { + var cmd = TYPE.CONNECT << 4; + var flags = this.createFlagsForConnection(clean); + + var keep_alive = [ + this.options.keep_alive >> 8, + this.options.keep_alive & 255, + ]; + + /* payload */ + var payload = this.clientId; + if (this.username) { + payload = payload.concat(this.username); + if (this.password) { + payload = payload.concat(this.password); + } + } + return mqttPacket( + cmd, + mqttStr(this.options.protocol_name) /*protocol name*/ + .concat([this.options.protocol_level]) /*protocol level*/ + .concat([flags]) + .concat(keep_alive), + payload, + ); + } + + packetHandler(data: Buffer) { + if (!this.client) { + this.emit("error", "disconnected mid packet handling"); + throw new Error("disconnected mid packet handling"); + } + // if we had some data left over from last + // time, add it on + if (this.partData && this.partData.length > 0) { + data = createBufferFromArray( + Array.prototype.slice + .call(this.partData) + .concat(Array.prototype.slice.call(data)), + ); + this.partData = []; + } + + // Figure out packet length... + var dLen = mqttPacketLengthDec(data.slice(1, data.length)); + var pLen = dLen.decLen + dLen.lenBy + 1; + // less than one packet? + if (data.length < pLen) { + this.partData = data; + return; + } + // Get the data for this packet + var pData = data.slice(1 + dLen.lenBy, pLen); + + // Handle this MQTT packet + var cmd = data[0]; + var type = cmd >> 4; + if (type === TYPE.PUBLISH) { + var qos = (cmd & 0x6) >> 1; + var topic_len = (pData[0] << 8) | pData[1]; + var msg_start = 2 + topic_len + (qos ? 2 : 0); + var parsedData: ParsedMQTTData = { + topic: pData.slice(2, 2 + topic_len).toString("utf8"), + message: pData.slice(msg_start, pData.length).toString("utf8"), + dup: (cmd & 0x8) >> 3, + qos: qos, + pid: qos ? pData.slice(2 + topic_len, 4 + topic_len) : 0, + retain: cmd & 0x1, + }; + if (parsedData.qos) { + const _d = (parsedData.qos == 1 ? TYPE.PUBACK : TYPE.PUBREC) << 4; + this.client.write([_d, 2, parsedData.pid] as any); + } + this.emit("publish", parsedData); + this.emit("message", parsedData.topic, parsedData.message); + } else if (type === TYPE.PUBACK) { + this.emit( + "puback", + (data.toString().charCodeAt(2) << 8) | data.toString().charCodeAt(3), + ); + } else if (type === TYPE.PUBREC) { + var pubrelArray = [(TYPE.PUBREL << 4) | 2, 2]; + var pidArray = Array.prototype.slice.call(getPid(pData)); + var pubrecResponse = pubrelArray.concat(pidArray); + this.client.write(Buffer.from(pubrecResponse)); + } else if (type === TYPE.PUBREL) { + var pubcompArray = [TYPE.PUBCOMP << 4, 2]; + var pidArray = Array.prototype.slice.call(getPid(pData)); + var pubrelResponse = pubcompArray.concat(pidArray); + this.client.write(pubrelResponse as any); + } else if (type === TYPE.PUBCOMP) { + this.emit( + "pubcomp", + (data.toString().charCodeAt(2) << 8) | data.toString().charCodeAt(3), + ); + } else if (type === TYPE.SUBACK) { + if (pData.length > 0) { + if (pData[pData.length - 1] == 0x80) { + this.emit("subscribed_fail"); + } else { + this.emit("subscribed"); + } + } + } else if (type === TYPE.UNSUBACK) { + this.emit("unsubscribed"); + } else if (type === TYPE.PINGREQ) { + this.client.write([TYPE.PINGRESP << 4, 0] as any); + } else if (type === TYPE.PINGRESP) { + this.emit("ping_reply"); + } else if (type === TYPE.CONNACK) { + if (this.ctimo) clearTimeout(this.ctimo); + this.ctimo = undefined; + this.partData = []; + var returnCode = pData[1]; + if (RETURN_CODES[returnCode] === "ACCEPTED") { + this.connected = true; + // start pinging + if (this.pintr) clearInterval(this.pintr); + this.pintr = setInterval( + this.ping.bind(this), + this.pingInterval * 1000, + ); + // emit connected events + this.emit("connected"); + this.emit("connect"); + } else { + var mqttError = "Connection refused, "; + this.connected = false; + if (returnCode > 0 && returnCode < 6) { + mqttError += RETURN_CODES[returnCode]; + } else { + mqttError += "unknown return code: " + returnCode + "."; + } + this.emit("error", mqttError); + } + // more than one packet? re-emit it so we handle it later + if (data.length > pLen) { + this.client.emit("data", data.slice(pLen, data.length)); + } + } else { + this.emit("error", "MQTT unsupported packet type: " + type); + } + } + + /** Unsubscribe to topic (filter) */ + unsubscribe(topic: string) { + if (!this.client) return; + var cmd = (TYPE.UNSUBSCRIBE << 4) | 2; + this.client.write(mqttPacket(cmd, this.mqttPid(), mqttStr(topic))); + } + + /** Send ping request to server */ + ping() { + if (!this.client) return; + try { + this.client.write(Buffer.from([TYPE.PINGREQ << 4, 0])); + } catch (e) { + this._scktClosed(); + } + } + + /** Publish message using specified topic. + opts = { + retain: bool // the server should retain this message and send it out again to new subscribers + dup : bool // indicate the message is a duplicate because original wasn't ACKed (QoS > 0 only) + } + */ + publish( + topic: string, + message: string, + opts: { + qos?: number; + retain?: boolean; + dup?: boolean; + }, + ) { + if (!this.client) return; + opts = opts || {}; + try { + var payloadarray = []; + var i = 0; + var messagearray = message.split(""); + for (var j = 0; j < message.length; j++) { + var char = messagearray[j]; + var numberrepres = char.charCodeAt(0); + payloadarray[i] = numberrepres; + i = i + 1; + } + var publishMessage = createMqttPublishPacket( + topic, + payloadarray, + opts.qos || C.DEF_QOS, + (opts.retain ? 1 : 0) | (opts.dup ? 8 : 0), + this.mqttPid(), + ); + this.client.write(publishMessage); + } catch (e) { + this._scktClosed(); + } + } + + /** Subscribe to topic (filter) */ + subscribe( + topics: string[] | string | Record, + opts: { qos?: number } = {}, + ) { + if (!this.client) return; + const client = this.client; + const mqo = this; + opts = opts || {}; + + var subs: { topic: string; qos: number }[] = []; + if ("string" === typeof topics) { + topics = [topics]; + } + if (Array.isArray(topics)) { + topics.forEach((topic) => { + subs.push({ + topic: topic, + qos: opts.qos || C.DEF_QOS, + }); + }); + } else { + Object.keys(topics).forEach(function (k) { + subs.push({ + topic: k, + qos: (topics as any)[k], + }); + }); + } + subs.forEach((sub) => { + var subpacket = createMqttSubscribePacket( + sub.topic, + sub.qos, + mqo.mqttPid(), + ); + client.write(subpacket); + }); + } +} diff --git a/src/mqtt_client/utils.ts b/src/mqtt_client/utils.ts new file mode 100644 index 0000000..6b01ee5 --- /dev/null +++ b/src/mqtt_client/utils.ts @@ -0,0 +1,161 @@ +import { C, TYPE } from "./constants"; + +/** Generate random UID */ +export const mqttUid = (function () { + function s4() { + var numberstring = Math.floor(1 + Math.random() * 10); + if (numberstring == 10) numberstring = 9; + numberstring = 97 + numberstring; + return numberstring; + } + + return function () { + var output = [ + 0, + 12, + s4(), + s4(), + s4(), + s4(), + s4(), + s4(), + s4(), + s4(), + s4(), + s4(), + s4(), + s4(), + ]; + return output; + }; +})(); +/** MQTT string (length MSB, LSB + data) */ +export const mqttStr = (s: string) => { + var payloadarray = [s.length >> 8, s.length & 255]; + var i = 2; + var messagearray = s.split(""); + for (var j = 0; j < s.length; j++) { + var char = messagearray[j]; + var numberrepres = char.charCodeAt(0); + payloadarray[i] = numberrepres; + i = i + 1; + } + return payloadarray; +}; +export const getClientId = (options: MQTTOptions): number[] => { + if (typeof options.client_id == "string") { + return mqttStr(options.client_id); + } + return options.client_id; +}; +export const setOptionDefaults = ( + options: Partial, +): MQTTOptions => ({ + port: options.port || C.DEF_PORT, + client_id: options.client_id || mqttUid(), + keep_alive: options.keep_alive || C.DEF_KEEP_ALIVE, + clean_session: options.clean_session || true, + username: options.username, + password: options.password, + protocol_name: options.protocol_name || "MQTT", + protocol_level: options.protocol_level || C.PROTOCOL_LEVEL, +}); + +/** MQTT packet length formatter - algorithm from reference docs */ +export const mqttPacketLength = (length: number) => { + var encLength: number[] = []; + var i = 0; + do { + var encByte = length & 127; + length = length >> 7; + // if there are more data to encode, set the top bit of this byte + if (length > 0) { + encByte += 128; + } + encLength[i] = encByte; + i++; + } while (length > 0); + return encLength; +}; + +/** MQTT packet length decoder - algorithm from reference docs */ +export type MqttPacketLengthDec = { decLen: number; lenBy: number }; +export const mqttPacketLengthDec = ( + length: number[] | Buffer, +): MqttPacketLengthDec => { + var bytes = 0; + var decL = 0; + var lb = 0; + do { + lb = length[bytes]; + decL |= (lb & 127) << (bytes++ * 7); + } while (lb & 128 && bytes < 4); + return { decLen: decL, lenBy: bytes }; +}; + +export const createBufferFromArray = (a: number[]) => { + if (Buffer.from) { + return Buffer.from(a); + } else { + return new Buffer(a); + } +}; + +/** MQTT standard packet formatter */ +export const mqttPacket = ( + cmd: number, + variable: number[], + payload: number[], +) => { + var cmdAndLengthArray = [cmd].concat( + mqttPacketLength(variable.length + payload.length), + ); + var headerAndPayloadArray = cmdAndLengthArray + .concat(variable) + .concat(payload); + var messageBuffer = createBufferFromArray(headerAndPayloadArray); + return messageBuffer; +}; + +/** Get PID from message */ +export const getPid = (data: Buffer) => { + return data.slice(0, 2); +}; + +/** PUBLISH control packet */ +export const createMqttPublishPacket = ( + topic: string, + message: number[], + qos: number, + flags: number, + pid: number[], +) => { + var cmd = (TYPE.PUBLISH << 4) | (qos << 1) | flags; + var variable = mqttStr(topic); + // Packet id must be included for QOS > 0 + if (qos > 0) { + var newvariable = variable.concat(pid); + return mqttPacket(cmd, newvariable, message); + } else { + return mqttPacket(cmd, variable, message); + } +}; + +/** SUBSCRIBE control packet */ +export const createMqttSubscribePacket = ( + topic: string, + qos: number, + pid: number[], +) => { + var cmd = (TYPE.SUBSCRIBE << 4) | 2; + var payloadarray = []; + var i = 0; + var messagearray = topic.split(""); + for (var j = 0; j < topic.length; j++) { + var char = messagearray[j]; + var numberrepres = char.charCodeAt(0); + payloadarray[i] = numberrepres; + i = i + 1; + } + return mqttPacket(cmd, pid, mqttStr(topic).concat([qos])); +}; diff --git a/tsconfig.json b/tsconfig.json index 21ebd16..668d095 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,7 +1,10 @@ { "compilerOptions": { "target": "ES2015", - "module": "ESNext" + "module": "ESNext", + "strict": true, + "esModuleInterop": true, + "typeRoots": ["./node_modules/@types", "types/*"] }, "include": ["src/**/*", "rollup.config.ts", "types/*"] } diff --git a/types/flic.sdk.globals.d.ts b/types/flic.sdk.globals.d.ts new file mode 100644 index 0000000..1e1fb31 --- /dev/null +++ b/types/flic.sdk.globals.d.ts @@ -0,0 +1,130 @@ +// globals.d.ts +// TypeScript declarations for Flic Hub Studio Global Functions & Classes +// https://studio.flic.io/static/documentation/#165_global_functions_and_classes + +/** + * Global Buffer class (Node.js-like, partial support) + * Unsupported: poolSize, indexOf, lastIndexOf, swap16/32/64, BigInt methods + * Supported encodings: 'utf8', 'hex', 'base64' + */ +declare class Buffer extends Uint8Array { + /** Create Buffer from string, array, etc. */ + constructor( + source: string | ArrayBuffer | ArrayBufferView | number | Array, + encoding?: "utf8" | "hex" | "base64", + ); + + /** Length of the buffer */ + readonly length: number; + + /** Convert to string */ + toString( + encoding?: "utf8" | "hex" | "base64", + start?: number, + end?: number, + ): string; + + /** Write string to buffer */ + write( + string: string, + offset?: number, + length?: number, + encoding?: "utf8" | "hex" | "base64", + ): number; + + /** Copy between buffers */ + copy( + target: Buffer, + targetStart?: number, + sourceStart?: number, + sourceEnd?: number, + ): number; + + /** Fill buffer with value */ + fill( + value: string | number | Buffer, + offset?: number, + end?: number, + encoding?: "utf8" | "hex" | "base64", + ): this; + + /** Compare two buffers */ + equals(otherBuffer: Buffer): boolean; + + /** Slice buffer */ + slice(start?: number, end?: number): Buffer; + + /** Static: Allocate new buffer */ + static alloc( + size: number, + fill?: string | number | Buffer, + encoding?: "utf8" | "hex" | "base64", + ): Buffer; + + /** Static: Concatenate buffers */ + static concat(list: Buffer[], totalLength?: number): Buffer; + + /** Static: From string or array */ + static from( + source: string | ArrayBuffer | ArrayBufferView | Array, + encoding?: "utf8" | "hex" | "base64", + ): Buffer; + + /** Static: Check if value is Buffer */ + static isBuffer(obj: any): obj is Buffer; + + /** Static: Byte length of string */ + static byteLength( + string: string, + encoding?: "utf8" | "hex" | "base64", + ): number; +} + +/** + * TextEncoder (Web API) + * Only UTF-8 supported + * encodeInto() is NOT supported + */ +declare class TextEncoder { + readonly encoding: "utf-8"; + + encode(input?: string): Uint8Array; +} + +/** + * TextDecoder (Web API) + * Only UTF-8 supported + */ +declare class TextDecoder { + constructor( + label?: "utf-8", + options?: { fatal?: boolean; ignoreBOM?: boolean }, + ); + + readonly encoding: "utf-8"; + readonly fatal: boolean; + readonly ignoreBOM: boolean; + + decode(input?: BufferSource, options?: { stream?: boolean }): string; +} + +/** + * Timer API (Node.js-like) + */ +declare function setTimeout( + callback: (...args: any[]) => void, + ms?: number, + ...args: any[] +): number; +declare function setInterval( + callback: (...args: any[]) => void, + ms?: number, + ...args: any[] +): number; +declare function clearTimeout(timeoutId: number): void; +declare function clearInterval(intervalId: number): void; + +/** + * Debug printing (console.log alias) + */ +declare function print(...args: any[]): void; diff --git a/types/flic.sdk.net.d.ts b/types/flic.sdk.net.d.ts new file mode 100644 index 0000000..478947c --- /dev/null +++ b/types/flic.sdk.net.d.ts @@ -0,0 +1,231 @@ +// net.d.ts +// TypeScript declarations for Flic Hub Studio 'net' (TCP) module +// Based on: https://studio.flic.io/static/documentation/#63_tcp_module + +declare module "net" { + import { EventEmitter } from "events"; + /** + * Creates a TCP server. + */ + function createServer( + options?: ServerOptions, + connectionListener?: (socket: Socket) => void, + ): Server; + + /** + * Creates a TCP socket and connects it to the specified port and host. + */ + function createConnection( + options: ConnectOptions, + connectionListener?: () => void, + ): Socket; + + /** + * Alternative signature for createConnection. + */ + function createConnection( + port: number, + host?: string, + connectionListener?: () => void, + ): Socket; + + /** + * TCP Server class. + */ + class Server extends EventEmitter { + constructor( + options?: ServerOptions, + connectionListener?: (socket: Socket) => void, + ); + + /** + * Start listening for connections. + */ + listen(options: ListenOptions, callback?: () => void): this; + listen( + port?: number, + host?: string, + backlog?: number, + callback?: () => void, + ): this; + listen(port?: number, host?: string, callback?: () => void): this; + listen(port?: number, callback?: () => void): this; + + /** + * Stop the server from accepting new connections. + */ + close(callback?: (err?: Error) => void): this; + + /** + * Returns the bound address, family, and port of the server. + */ + address(): AddressInfo | null; + + /** + * Asynchronously get the number of concurrent connections. + */ + getConnections(callback: (err: Error | null, count: number) => void): void; + + /** + * Whether the server is currently listening. + */ + readonly listening: boolean; + + // Events + on(event: "close", listener: () => void): this; + on(event: "connection", listener: (socket: Socket) => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "listening", listener: () => void): this; + } + + /** + * TCP Socket class. + */ + export class Socket extends EventEmitter { + constructor(options?: SocketOptions); + + /** + * Initiate a connection. + */ + connect(options: ConnectOptions, connectionListener?: () => void): this; + connect(port: number, host?: string, connectionListener?: () => void): this; + + /** + * Send data on the socket. + */ + write( + data: string | Buffer | Uint8Array, + encoding?: string, + callback?: (err?: Error) => void, + ): boolean; + write( + data: string | Buffer | Uint8Array, + callback?: (err?: Error) => void, + ): boolean; + + /** + * Half-close the socket (send FIN). + */ + end( + data?: string | Buffer | Uint8Array, + encoding?: string, + callback?: () => void, + ): this; + end(data?: string | Buffer | Uint8Array, callback?: () => void): this; + end(callback?: () => void): this; + + /** + * Abruptly close the socket. + */ + destroy(exception?: Error): this; + + /** + * Pause reading data. + */ + pause(): this; + + /** + * Resume reading after pause(). + */ + resume(): this; + + /** + * Set encoding for incoming data. + */ + setEncoding(encoding?: "utf8" | "hex" | "base64" | null): this; + + /** + * Disable Nagle's algorithm (enable no delay). + */ + setNoDelay(noDelay?: boolean): this; + + /** + * Enable/disable TCP keep-alive. + */ + setKeepAlive(enable?: boolean, initialDelay?: number): this; + + /** + * Get local address info. + */ + address(): AddressInfo | null; + + // Read-only properties + readonly connecting: boolean; + readonly destroyed: boolean; + readonly localAddress?: string; + readonly localPort?: number; + readonly remoteAddress?: string; + readonly remotePort?: number; + readonly remoteFamily?: string; + readonly bytesRead: number; + readonly bytesWritten: number; + + // Events + on(event: "close", listener: (hadError: boolean) => void): this; + on(event: "connect", listener: () => void): this; + on(event: "data", listener: (data: Buffer | string) => void): this; + on(event: "drain", listener: () => void): this; + on(event: "end", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on( + event: "lookup", + listener: ( + err: Error | null, + address: string | null, + family: string, + host: string, + ) => void, + ): this; + on(event: "ready", listener: () => void): this; + } + + // Option Interfaces + + interface ServerOptions { + /** + * Allow half-open TCP connections. + * Default: false + */ + allowHalfOpen?: boolean; + + /** + * Pause incoming connections until resume() is called. + * Default: false + */ + pauseOnConnect?: boolean; + } + + interface SocketOptions { + /** + * Allow half-open TCP connections. + * Default: false + */ + allowHalfOpen?: boolean; + } + + interface ConnectOptions { + port: number; + host?: string; + } + + interface ListenOptions { + port?: number; + host?: string; + backlog?: number; + } + + interface AddressInfo { + address: string; + family: "IPv4"; + port: number; + } + + // Module export + const net: { + createServer: typeof createServer; + createConnection: typeof createConnection; + Server: typeof Server; + Socket: typeof Socket; + }; + export default net; +} diff --git a/types/options.types.d.ts b/types/options.types.d.ts index 09d93c3..caea052 100644 --- a/types/options.types.d.ts +++ b/types/options.types.d.ts @@ -20,17 +20,21 @@ type FlicHubOptions = { uniqueId: string; debug: boolean; }; -type MQTTOpt = { - host: string; +type MQTTOptions = { port: number; - client_id: string; - keep_alive: boolean; + client_id: string | number[]; + keep_alive: number | boolean; clean_session: boolean; - username: string; - password: string; + username?: string; + password?: string; + protocol_name: string; + protocol_level: number; +}; +type Flic2HassMQTTOptions = MQTTOptions & { + host: string; }; type Options = { - mqtt: Partial & { host: string }; + mqtt: Partial & { host: string }; debug?: boolean; ha?: Partial; flicBtns?: Partial & { disabled?: boolean };