refactor mqtt client

This commit is contained in:
ari committed 2025-11-14 11:44:57 -05:00
1 parent 44c999437b
commit 5f18fd6315
17 files changed
+1987 -851

No files matched your search

+20 -59
View File
@@ -73,7 +73,7 @@ var RETURN_CODES = {
};
/** MQTT constructor */
function MQTT(server, options) {
export function MQTT(server: string, options: Partial<MQTTOptions>) {
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<string, any>,
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<MQTTOptions>) {
return new MQTT(server, options);
}
export function connect(options): MQTT {
export function connect(
options: Partial<Flic2HassMQTTOptions> & { 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;
}
+708 -637
View File
File diff suppressed because it is too large. Load diff
+4 -4
View File
@@ -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<typeof makeHAmqtt>;
export function makeHAmqtt(
mqttServer: MQTT,
options: Partial<HAmqttOptions> = {},
mqttServer: FlicMQTT,
_options: Partial<HAmqttOptions> = {},
) {
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 => {
+2 -2
View File
@@ -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<FlicHubOptions> = {},
) => {
const options = makeOptions(_options);
+10 -10
View File
@@ -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();
+69
View File
@@ -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,
},
);
};
+26 -131
View File
@@ -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<IRControllerOpt> = {},
mqtt: FlicMQTT,
_options: Partial<IRControllerOpt> = {},
) => {
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");
};
+38
View File
@@ -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");
});
};
+54
View File
@@ -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()}`,
);
}
}
});
};
+46
View File
@@ -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<typeof makeIRSharedState>;
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<typeof getConstants>;
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],
};
};
+40
View File
@@ -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<number, string> = {
0: "ACCEPTED",
1: "UNACCEPTABLE_PROTOCOL_VERSION",
2: "IDENTIFIER_REJECTED",
3: "SERVER_UNAVAILABLE",
4: "BAD_USER_NAME_OR_PASSWORD",
5: "NOT_AUTHORIZED",
};
+433
View File
@@ -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<T extends MQTTEventName> = 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<MQTTEventName, _Listener<any>[]> = {
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<MQTTOptions>,
) {
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<T extends MQTTEventName>(type: T, fn: _Listener<T>) {
if (!this.__listeners[type]) {
this.__listeners[type] = [];
}
this.__listeners[type].push(fn);
}
emit<T extends MQTTEventName>(type: T, ...data: Parameters<_Listener<T>>) {
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<string, number>,
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);
});
}
}
+161
View File
@@ -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>,
): 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]));
};
+4 -1
View File
@@ -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/*"]
}
+130
View File
@@ -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<number>,
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<number>,
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;
+231
View File
@@ -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;
}
+11 -7
View File
@@ -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<MQTTOpt> & { host: string };
mqtt: Partial<Flic2HassMQTTOptions> & { host: string };
debug?: boolean;
ha?: Partial<HAmqttOptions>;
flicBtns?: Partial<ButtonControllerOpt> & { disabled?: boolean };