All the work

This commit is contained in:
Ariel Sosnovsky committed 2023-11-01 17:11:09 -04:00
1 parent f6767c9e8f
commit 2a1efb2aff
15 files changed
+4921 -264

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
.vscode
node_modules
dist
build
.parcel-cache
+12
View File
@@ -0,0 +1,12 @@
{
"jsc": {
"target": "es3",
"parser": {
"syntax": "typescript",
}
},
"minify": false,
"isModule": true,
"sourceMaps": false,
"inlineSourcesContent": false
}
+61 -26
View File
@@ -1,10 +1,13 @@
# flic2hass
## A Flic SDK utility to publish all of your Flic buttons to Home Assistant via MQTT
A Flic SDK utility to publish all of your Flic buttons to Home Assistant via MQTT as well control the onboard IR module.
Requirements:
* A Flic Hub
* A functional MQTT server
## Basic Steps:
## Basic Steps
**1. Connect to Flic Hub IDE:**
@@ -16,40 +19,72 @@ Requirements:
* One in the Web IDE, click "Create Module".
* Give the new module a name. "`MQTT`" is a good option but anything will work.
**3. Insert `main.js` and `mqtt.js`:**
**3. Insert `lib.js`:**
* Copy content from `main.js` in this repo to main.js in the flic IDE.
* Copy content from `lib.js` in this repo to lib.js in the flic IDE.
* Right click the folder in the left pane and select "New File".
* Name the file `mqtt.js` (IT MUST BE NAMED THIS).
* Copy content from `mqtt.js` in this repo to mqtt.js in the flic IDE.
* Name the file `lib.js` (IT MUST BE NAMED THIS).
* Copy content from `lib.js` in this repo to lib.js in the flic IDE.
**4. Update variables in `main.js`:**
**4. Setup `main.js`:**
* Modify `server`, `hatopic`, `authentication` with your details.
* Copy the following to `main.js`
```js
require("./lib").start(
require("buttons"),
require("ir"),
"0",
{
mqtt: {
host: "set-this-to-yours",
username: "set-this-to-yours",
password: "set-this-to-yours",
}
}
)
```
* Modify `host`, `username`, `password` with your details.
*If your MQTT server does not require authentication:*
* Delete:
```javascript
var username = 'flichub';
var password = 'xxxxx';
```
* Replace:
```javascript
var mqtt = require("./mqtt").create(server,{'username':username,'password':password});
```
With:
```javascript
var mqtt = require("./mqtt").create(server);
```
* Delete `username` & `password`:
1. Start the module in the IDE by clicking the green play button, and watch the Console output (it's extremely verbose right now)
*If the module didn't start correctly, try powercycling your Flic Hub and reconnect. Verify the Module saved properly and is running.*
2. Once the module has started and you have verified it is working as expected, turn on the "restart after crash" checkbox to ensure the module is always running after any unexpected crash or hub power cycle.
## Additional Configuration
The setup example contains just the bare minimum changes, if you wish to play around with the configuration or need to enable expanded logging see the following complete configuration file.
```jsonc
{
"mqtt": {
"host": "", // MQTT Host
"port": 1883, // MQTT Port
"client_id": "", // MQTT Identifier
"username": "", // MQTT Username
"password": "" // MQTT Password
},
"debug": false, // Enable debug logging for all modules
"ha": {
"debug": false, // Enable debug logging for just home-assistant related things
"topics": {
"homeassistant": "homeassistant", // MQTT Prefix for homeassistant auto-discover
"flic": "flic", // MQTT Prefix for state values
}
},
"flicBtns": {
"disabled": false, // Do not publish button events
"debug": false // Enable debug logging for button related things
},
"flicIR": {
"disabled": false, // Do not publish IR events
"debug": false // Enable debug logging for IR related things
},
}
```
+1176
View File
File diff suppressed because it is too large. Load diff
-230
View File
@@ -1,230 +0,0 @@
var server = "mqtt.home";
var hatopic = "homeassistant";
var flictopic = "flic";
var username = "";
var password = "";
var mqtt = require("./mqtt").create(server,{'username':username,'password':password});
var buttonManager = require("buttons");
var myButtons = {}; //Dictionary of Button objects
//This runs when a button is added via Flic's interface
buttonManager.on("buttonAdded", function(obj){
var button = buttonManager.getButton(obj.bdaddr);
console.log("\nNew button Added! "+button.serialNumber+" "+button.name);
console.log("\nRAW obj info: " + JSON.stringify(obj, null, 4) + "\n");
console.log("\nRAW button info: " + JSON.stringify(button, null, 4) + "\n");
if (button.serialNumber == null || button.name == null) {
return;
}
if (button.serialNumber) {
register_button(button);
}
});
//This runs when a button is added via Flic's interface
buttonManager.on("buttonConnected", function(obj){
var button = buttonManager.getButton(obj.bdaddr);
console.log("\nNew button Connected! "+button.serialNumber+" "+button.name);
console.log("\nRAW obj info: " + JSON.stringify(obj, null, 4) + "\n");
console.log("\nRAW button info: " + JSON.stringify(button, null, 4) + "\n");
if (button.serialNumber == null || button.name == null) {
return;
}
if (button.serialNumber) {
register_button(button);
}
});
//This runs when a button is added via Flic's interface
buttonManager.on("buttonReady", function(obj){
var button = buttonManager.getButton(obj.bdaddr);
console.log("\nNew button Ready! "+button.serialNumber+" "+button.name);
console.log("\nRAW obj info: " + JSON.stringify(obj, null, 4) + "\n");
console.log("\nRAW button info: " + JSON.stringify(button, null, 4) + "\n");
if (button.serialNumber == null || button.name == null) {
return;
}
if (button.serialNumber) {
register_button(button);
}
});
//This runs when a button is deleted via Flic's interface
buttonManager.on("buttonDeleted", function(obj){
//Well crap. If it's deleted, it doesn't have an object anymore.
//So that means I have to save it by address, not ID so I can delete it from MQTT later
console.log("\nDeleting button "+obj.bdaddr);
console.log("\nRAW obj info: " + JSON.stringify(obj, null, 4) + "\n");
var configtopic = hatopic+"/sensor/"+myButtons[obj.bdaddr].serialNumber;
mqtt.publish(configtopic+"/action/config", null, {retain: false } );
if (myButtons[obj.bdaddr]) {
delete myButtons[obj.bdaddr];
//myButtons.delete[obj.bdaddr];
}
});
buttonManager.on("buttonSingleOrDoubleClickOrHold", function(obj) {
//This runs when a button is clicked.
var button = buttonManager.getButton(obj.bdaddr);
console.log("\nRAW obj info: " + JSON.stringify(obj, null, 4) + "\n");
console.log("\nRAW button info: " + JSON.stringify(button, null, 4) + "\n");
var clickType = obj.isSingleClick ? "click" : obj.isDoubleClick ? "double_click" : "hold";
var sn = button.serialNumber;
if (!myButtons[button.bdaddr]) {
console.log("**** Found an unregistered button. It must be new! ***")
register_button(button);
}
if (myButtons[button.bdaddr].name!=button.name) {
console.log("*Name changed from "+myButtons[button.bdaddr].name+" to "+button.name);
register_button(button);
}
var btntopic = flictopic+"/"+sn;
mqtt.publish(btntopic + "/action", clickType);
console.log(btntopic+"/action: \t"+clickType);
mqtt.publish(btntopic + "/action", "ok");
mqtt.publish(btntopic + "/battery", button.batteryStatus+""); //NOW it seems to just want text, no decoration!
console.log(btntopic+"/battery: \t"+button.batteryStatus);
});
buttonManager.on("buttonUp", function(obj) {
var button = buttonManager.getButton(obj.bdaddr);
console.log("\nButton Released! " + button.serialNumber + " " + button.name);
publishButtonState(button, "released");
});
buttonManager.on("buttonDown", function(obj) {
var button = buttonManager.getButton(obj.bdaddr);
console.log("\nButton Pressed! " + button.serialNumber + " " + button.name);
publishButtonState(button, "pressed");
});
function publishButtonState(button, state) {
var sn = button.serialNumber;
var statetopic = flictopic + "/" + sn + "/state";
mqtt.publish(statetopic, state);
console.log(statetopic + ": \t" + state);
}
function register_button(button) {
//Register one button
//This sets up the MQTT Discovery topics to publish the Flic button
//NOTE: When a button is added via the Flic interface, it gets named
//a bit late. So the API returns null for the name.
//What's worse, it continues to return null until you restart the
//Javascript app running in the Hub. I have no idea how to get the
//new name without crashing the app and relying on the
//"Restart after crash" flag - and I'm not willing to do that.
//TL;DR - new buttons are named "null" until the Hub is rebooted.
console.log("\nRAW device info: " + JSON.stringify(button, null, 4) + "\n");
if (button.serialNumber == null) {
console.log("**Error registering button, still no serialNumber")
return;
}
var configtopic = hatopic + "/sensor/" + button.serialNumber;
var buttontopic = flictopic + "/" + button.serialNumber;
var obj = {};
obj.device = {
name: button.name,
identifiers: [button.serialNumber],
manufacturer: "Flic",
model: "Button"
};
//Setup config and destination for button press
obj.name = "Button Action";
obj.state_topic = buttontopic + "/action";
obj.unique_id = "Flic_" + button.serialNumber + "_action";
payload = JSON.stringify(obj, null, 4);
console.log(configtopic + "/action/config:\t" + payload);
mqtt.publish(configtopic + "/action/config", payload, {
retain: true
});
// Setup config and destination for button state
obj.name = "Button State";
obj.state_topic = buttontopic + "/state";
obj.unique_id = "Flic_" + button.serialNumber + "_state";
payload = JSON.stringify(obj, null, 4);
console.log(configtopic + "/state/config:\t" + payload);
mqtt.publish(configtopic + "/state/config", payload, {
retain: true
});
//Setup config and destination for battery level report
obj.name = "Battery Level";
obj.state_topic = buttontopic + "/battery";
obj.unique_id = "Flic_" + button.serialNumber + "_battery";
obj.device_class = "battery";
obj.entity_category = "diagnostic";
//obj.unit_of_measurement = "%"; //It doesn't seem to actually like this.
payload = JSON.stringify(obj, null, 4);
console.log(configtopic + "/battery/config:\t" + payload);
mqtt.publish(configtopic + "/battery/config", payload, {
retain: true
});
myButtons[button.bdaddr] = {
name: button.name,
serialNumber: button.serialNumber
};
console.log("\nmyButtons: " + JSON.stringify(myButtons, null, 4) + "\n");
}
//This sets up the MQTT Discovery topics to publish all the Flic buttons
function register_allbuttons(){
var buttons = buttonManager.getButtons();
for (var i = 0; i < buttons.length; i++) {
register_button(buttons[i]);
}
}
//This runs on startup, it performs the actual "discovery" announcement for
//HomeAssistant to add the device to its inventory
mqtt.on('connected', function(){
console.log("\n'Connected' event\n");
register_allbuttons();
});
// Added by heroash88 to reconnect if MQTT server goes down
mqtt.on('disconnected', function() {
console.log("\n'Disconnected' event\n");
mqtt.connect();
});
mqtt.on('error', function () {
console.log("\n'Error' event\n");
setTimeout(function () {
throw new Error("Crashed")
}, 1000);
});
mqtt.connect();
+3084
View File
File diff suppressed because it is too large. Load diff
+24
View File
@@ -0,0 +1,24 @@
{
"name": "flic2hass",
"version": "1.0.0",
"description": "Flic Hub MQTT Server",
"scripts": {
"build": "swc src/ -d dist/ && rollup dist/index.js --file lib.js -f cjs"
},
"repository": {
"type": "git",
"url": "git+https://github.com/asosnovsky/flic2hass.git"
},
"author": "Ariel Sosnovsky <ariel@sosnovsky.ca>",
"license": "ISC",
"bugs": {
"url": "https://github.com/asosnovsky/flic2hass/issues"
},
"homepage": "https://github.com/asosnovsky/flic2hass#readme",
"devDependencies": {
"@swc/cli": "^0.1.62",
"@swc/core": "^1.3.95",
"rollup": "^4.2.0",
"typescript": "^5.2.2"
}
}
+139
View File
@@ -0,0 +1,139 @@
import { HAComponent, HADevice, HAmqtt } from "./HAmqtt";
import { makeLogger } from "./Logger";
import { Button, ButtonModule } from "./flicTypes";
export type ButtonControllerOpt = {
debug: boolean;
}
export const makeOptions = (opt: Partial<ButtonControllerOpt>): ButtonControllerOpt => ({
debug: false,
...opt,
})
const ENTITIES: Record<string, [HAComponent, Record<string, any>]> = {
"action": ['sensor', { icon: 'mdi:gesture-tap-button' }],
"state": ['sensor', { icon: 'mdi:radiobox-indeterminate-variant' }],
"battery": ['sensor', { unit_of_measurement: '%', device_class: 'battery' }],
"connected": ['binary_sensor', { device_class: 'connectivity' }],
"ready": ['binary_sensor', { device_class: 'running' }],
}
export type ButtonController = ReturnType<typeof makeButtonController>;
export function makeButtonController(
ha: HAmqtt,
buttonModule: ButtonModule,
options: Partial<ButtonControllerOpt> = {},
) {
options = makeOptions(options);
const logger = makeLogger('btnc', options.debug)
logger.info("Starting Flic ButtonController with", JSON.stringify(options, null, 4));
const getDeviceFromButton = (button: Button): HADevice => {
return {
name: button.name,
identifiers: [button.serialNumber, button.uuid],
manufacturer: 'Flic',
model: `v${button.flicVersion}_${button.color.trim().length > 0 ? button.color : 'white'}`,
sw: String(button.firmwareVersion),
hw: String(button.flicVersion),
}
}
const genButtonUniqueId = (bdaddr: string): string => bdaddr.replace(/:/g, '_')
const registerButton = (button: Button) => {
logger.info('Registering', JSON.stringify(button, null, 4))
const haDevice = getDeviceFromButton(button);
Object.keys(ENTITIES).forEach(objectId => {
ha.registerEntity(
`Button ${objectId}`,
ENTITIES[objectId][0],
genButtonUniqueId(button.bdaddr),
objectId,
haDevice,
{
...ENTITIES[objectId][1],
availability: [
{
payload_available: 'ON',
payload_not_available: 'OFF',
topic: ha.genFlicPrefix(genButtonUniqueId(button.bdaddr), 'ready')
},
{
payload_available: 'ON',
payload_not_available: 'OFF',
topic: ha.genFlicPrefix(genButtonUniqueId(button.bdaddr), 'connected')
}
],
availability_mode: 'all',
},
)
});
}
const deregisterButton = (button: Button) => {
logger.info('Deregistering', JSON.stringify(button, null, 4))
Object.keys(ENTITIES).forEach(objectId => {
ha.deregisterEntity(
ENTITIES[objectId][0],
genButtonUniqueId(button.bdaddr),
objectId,
)
});
}
const publishButtonState = (button: Button, state: 'released' | 'pressed') => {
ha.publishState(genButtonUniqueId(button.bdaddr), 'state', state);
}
const publishButtonAction = (button: Button, state: string) => {
ha.publishState(genButtonUniqueId(button.bdaddr), 'action', state);
}
const publishButtonMeta = (button: Button) => {
ha.publishState(genButtonUniqueId(button.bdaddr), 'battery', button.batteryStatus);
ha.publishState(genButtonUniqueId(button.bdaddr), 'connected', button.connected ? 'ON' : "OFF");
ha.publishState(genButtonUniqueId(button.bdaddr), 'ready', button.ready ? 'ON' : "OFF");
}
const addBtn = (eventName: string) => (obj: { bdaddr: string }) => {
const button = buttonModule.getButton(obj.bdaddr);
logger.info(eventName, "upserting", button.name, genButtonUniqueId(button.bdaddr));
registerButton(button);
}
const start = () => {
logger.info("Starting...")
buttonModule.on('buttonAdded', addBtn('buttonAdded'));
buttonModule.on('buttonConnected', addBtn('buttonConnected'));
buttonModule.on('buttonReady', addBtn('buttonReady'));
buttonModule.on('buttonUpdated', addBtn('buttonUpdated'));
buttonModule.on('buttonDeleted', (btn) => {
logger.debug('buttonDeleted', JSON.stringify(btn, null, 4))
deregisterButton(btn);
publishButtonMeta(btn);
});
buttonModule.on('buttonDisconnected', ({ bdaddr }) => {
publishButtonMeta(buttonModule.getButton(bdaddr));
});
buttonModule.on('buttonDown', ({ bdaddr }) => {
const btn = buttonModule.getButton(bdaddr);
publishButtonState(btn, 'pressed');
publishButtonMeta(btn);
});
buttonModule.on('buttonUp', ({ bdaddr }) => {
const btn = buttonModule.getButton(bdaddr);
publishButtonState(btn, 'released');
publishButtonMeta(btn);
});
buttonModule.on('buttonSingleOrDoubleClickOrHold', obj => {
const btn = buttonModule.getButton(obj.bdaddr);
publishButtonAction(
btn,
obj.isSingleClick ? "click" : obj.isDoubleClick ? "double_click" : "hold",
);
publishButtonMeta(btn);
});
logger.info("Registering all buttons...")
buttonModule.getButtons().forEach(registerButton);
setInterval(() => buttonModule.getButtons().forEach(publishButtonMeta), 1000);
logger.info('is up')
}
return {
start,
publishButtonAction,
publishButtonMeta,
publishButtonState,
}
}
+93
View File
@@ -0,0 +1,93 @@
import { makeLogger } from "./Logger";
import { MQTT } from "./mqtt";
export type HAmqttOptions = {
debug: boolean,
topics: {
homeassistant: string,
flic: string,
}
}
export type MQTTPublishOpt = {
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)
}
export type HADevice = {
name: string,
identifiers: string[],
manufacturer: string,
model: string,
sw?: string,
hw?: string,
}
export type HAComponent = 'sensor' | 'binary_sensor' | 'button' | 'switch' | 'text';
export const makeOptions = (opt: Partial<HAmqttOptions>): HAmqttOptions => ({
debug: false,
...opt,
topics: {
homeassistant: 'homeassistant',
flic: 'flic',
...opt.topics,
}
})
export type HAmqtt = ReturnType<typeof makeHAmqtt>;
export function makeHAmqtt(
mqttServer: MQTT,
options: Partial<HAmqttOptions> = {},
) {
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 => {
return `${options.topics.flic}/${nodeId}/${objectId}`
}
const genHAPrefix = (component: HAComponent, nodeId: string, objectId: string) => {
return `${options.topics.homeassistant}/${component}/${nodeId}/${objectId}`
}
const publishState = (nodeId: string, objectId: string, state: any, opt: MQTTPublishOpt = {}) => {
const btntopic = genFlicPrefix(nodeId, objectId);
mqttServer.publish(btntopic, state + "", opt);
logger.debug(btntopic, state, JSON.stringify(opt))
}
const registerEntity = (
name: string,
component: HAComponent,
nodeId: string,
objectId: string,
device: HADevice,
additionalProps: Record<string, any> = {},
) => {
const configtopic = genHAPrefix(component, nodeId, objectId) + "/config"
const configObj = {
...additionalProps,
name,
state_topic: genFlicPrefix(nodeId, objectId),
unique_id: `Flic_${nodeId}_${objectId}`,
device,
};
mqttServer.publish(configtopic, JSON.stringify(configObj), {
retain: true,
});
logger.debug(configtopic, JSON.stringify(configObj, null, 4));
}
const deregisterEntity = (
component: HAComponent,
nodeId: string,
objectId: string,
) => {
const configtopic = genHAPrefix(component, nodeId, objectId) + "/config"
mqttServer.publish(configtopic, null, { retain: false });
logger.debug(configtopic, null);
}
return {
deregisterEntity,
registerEntity,
publishState,
genFlicPrefix,
}
}
+145
View File
@@ -0,0 +1,145 @@
import { HADevice, HAmqtt } from "./HAmqtt";
import { makeLogger } from "./Logger";
import { IRModule } from "./flicTypes";
import { MQTT } from "./mqtt";
const NODE_ID = 'FlicHubIR';
const convertUint32Array2Str = (arr: Uint32Array): string => {
let outStr = []
for (let i = 0; i < arr.length; i++) {
outStr.push(arr[i].toString(32))
}
return outStr.join('_')
}
const convertStr2Uint32Array = (s: string): Uint32Array => {
const a = s.split('_');
return new Uint32Array(a.slice(0, a.length - 2).map(v => parseInt(v, 32)))
}
export type IRControllerOpt = {
debug: boolean;
}
export const makeOptions = (opt: Partial<IRControllerOpt>): IRControllerOpt => ({
debug: false,
...opt,
})
export const makeIRController = (
ir: IRModule,
ha: HAmqtt,
mqtt: MQTT,
uniqueId: string,
options: Partial<IRControllerOpt> = {},
) => {
options = makeOptions(options);
const logger = makeLogger('ir', options.debug);
const haDevice: HADevice = {
name: 'IR',
manufacturer: 'Flic',
model: `${NODE_ID}${uniqueId}`,
identifiers: ['FlicHubIR']
}
const nodeId = `${NODE_ID}${uniqueId}`;
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');
let currentSignal: string | null = null;
const set_topics = [
RECORD_SIGNAL_SET,
VALUE_SIGNAL_SET,
PLAY_SIGNAL_SET,
VALUE_SIGNAL_STATE,
];
return {
start() {
logger.info('starting...')
logger.debug('setting up entities...')
ha.registerEntity(
'Record Signal',
'switch',
nodeId,
'record',
haDevice,
{
icon: 'mdi:record-rec',
command_topic: RECORD_SIGNAL_SET,
device_class: 'switch',
}
)
ha.registerEntity(
'Signal',
'text',
nodeId,
'signal',
haDevice,
{
command_topic: VALUE_SIGNAL_SET,
icon: 'mdi:broadcast',
max: 255,
}
)
ha.registerEntity(
'Play Signal',
'button',
nodeId,
'play',
haDevice,
{
icon: 'mdi:play',
command_topic: PLAY_SIGNAL_SET,
}
)
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')
}
}
}
+19
View File
@@ -0,0 +1,19 @@
export type Logger = ReturnType<typeof makeLogger>;
export function makeLogger(
prefix: string,
debugMode: boolean = false,
) {
return {
info(...args: any[]) {
console.log(`${prefix}|INFO| ${args.map(String).join('\t')}`)
},
error(...args: any[]) {
console.log(`${prefix}|ERROR| ${args.map(String).join('\t')}`)
},
debug(...args: any[]) {
if (debugMode) {
console.log(`${prefix}|DEBUG| ${args.map(String).join('\t')}`)
}
}
}
}
+39
View File
@@ -0,0 +1,39 @@
export type Button = {
bdaddr: string // Device address of button
serialNumber: string // Serial number
color: string // Colour of the button (lowercase)
name: string // The user assigned button name
activeDisconnect: boolean // The user has explicitly disconnected the button
connected: boolean // The connection to the button is currently established
ready: boolean // The connection is verified (see buttonReady)
batteryStatus: number | null // Battery level in percent (0-100), or null if unknown
firmwareVersion: number | null // Firmware version of button, or null if unknown
flicVersion: number | null // Flic version (1 or 2)
uuid: string // A 32 characters long hex string, unique for every button
key: number | null // A 40 characters long hex string (only for Flic 2)
}
export interface ButtonModule {
getButtons(): Button[],
getButton(bdaddr: string): Button,
on(ev: "buttonAdded", cb: (btn: Button) => void): void,
on(ev: "buttonUpdated", cb: (btn: Button) => void): void,
on(ev: "buttonDeleted", cb: (btn: Button) => void): void,
on(ev: "buttonConnected", cb: (btn: Button) => void): void,
on(ev: "buttonReady", cb: (obj: { bdaddr: string }) => void): void,
on(ev: "buttonDisconnected", cb: (obj: { bdaddr: string }) => void): void,
on(ev: "buttonDown", cb: (obj: { bdaddr: string }) => void): void,
on(ev: "buttonUp", cb: (obj: { bdaddr: string }) => void): void,
on(ev: "buttonClickOrHold", cb: (obj: { bdaddr: string, isClick: boolean, isHold: boolean }) => void): void,
on(ev: "buttonSingleOrDoubleClick", cb: (obj: { bdaddr: string, isSingleClick: boolean, isDoubleClick: boolean }) => void): void,
on(ev: "buttonSingleOrDoubleClickOrHold", cb: (obj: { bdaddr: string, isSingleClick: boolean, isDoubleClick: boolean, isHold: boolean }) => void): void,
}
export interface IRModule {
record(): void;
cancelRecord(): void;
play(arr: Uint32Array, cb: (err: any | undefined) => void): void;
on(ev: 'recordComplete', cb: (d: Uint32Array) => void): void;
}
+76
View File
@@ -0,0 +1,76 @@
import { ButtonControllerOpt, makeButtonController } from "./ButtonController";
import { HAmqttOptions, makeHAmqtt } from './HAmqtt';
import { IRControllerOpt, makeIRController } from "./IRController";
import { makeLogger } from "./Logger";
import { ButtonModule, IRModule } from './flicTypes';
import * as mqtt from './mqtt';
export type MQTTOpt = {
host: string;
port: number;
client_id: string;
keep_alive: boolean;
clean_session: boolean;
username: string;
password: string;
}
export type Options = {
mqtt: Partial<MQTTOpt> & { host: string };
debug?: boolean;
ha?: Partial<HAmqttOptions>;
flicBtns?: Partial<ButtonControllerOpt> & { disabled?: boolean };
flicIR?: Partial<IRControllerOpt> & { disabled?: boolean };
}
export const start = (
buttonModule: ButtonModule,
irModule: IRModule,
uniqueId: string,
options: Options,
) => {
const mqttServer = mqtt.create(
options.mqtt.host,
{ ...options.mqtt, keep_alive: true },
);
const logger = makeLogger('root', options.debug ?? false);
options.ha = options.ha ?? {}
options.flicBtns = options.flicBtns ?? {}
options.ha.debug = options.ha.debug ?? options.debug ?? false
options.flicBtns.debug = options.flicBtns.debug ?? options.debug ?? false
const ha = makeHAmqtt(mqttServer, options.ha);
mqttServer.on('connected', () => {
logger.info("connected to mqtt")
if (!options.flicBtns?.disabled) {
makeButtonController(
ha, buttonModule, options.flicBtns,
).start();
}
if (!options.flicIR?.disabled) {
makeIRController(
irModule,
ha,
mqttServer,
uniqueId,
options.flicIR,
).start();
}
logger.info("all services up!")
});
mqttServer.on('error', function (err) {
logger.info("'Error' event", JSON.stringify(err));
setTimeout(function () {
throw new Error("Crashed")
}, 1000);
});
mqttServer.on("disconnected", function (err) {
logger.info("'Error' disconnected", JSON.stringify(err));
setTimeout(function () {
throw new Error("Crashed")
}, 1000);
});
mqttServer.on("close", function (err) {
logger.info("'Error' close", JSON.stringify(err));
setTimeout(function () {
throw new Error("Crashed")
}, 1000);
});
mqttServer.connect()
}
+38 -8
View File
@@ -138,10 +138,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);
});
}
}
@@ -164,7 +164,7 @@ MQTT.prototype.C = {
var fromCharCode = String.fromCharCode;
/** MQTT string (length MSB, LSB + data) */
function mqttStr(s) {
export function mqttStr(s) {
var payloadarray = [s.length >> 8, s.length & 255];
var i = 2;
var messagearray = s.split('');
@@ -178,6 +178,13 @@ 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) {
@@ -281,8 +288,8 @@ function mqttUnsubscribe(topic) {
}
/** Create escaped hex value from number */
function createEscapedHex(number) {
return fromCharCode(parseInt(number.toString(16), 16));
function createEscapedHex(n: number): string {
return fromCharCode(parseInt(n.toString(16), 16));
}
// Handle a single packet of data
@@ -329,7 +336,7 @@ MQTT.prototype.packetHandler = function(data) {
this.client.write([((parsedData.qos == 1) ? TYPE.PUBACK : TYPE.PUBREC) << 4, 2, parsedData.pid]);
}
this.emit('publish', parsedData);
this.emit('message', parsedData.topic, parsedData.message);
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) {
@@ -568,13 +575,36 @@ MQTT.prototype.mqttConnect = function (clean) {
/* Exports *************************************/
/** This is 'exported' so it can be used with `require('MQTT.js').create(server, options)` */
exports.create = function (server, options) {
export function create(server, options): MQTT {
return new MQTT(server, options);
};
exports.connect = function (options) {
export function connect(options): MQTT {
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;
};
+10
View File
@@ -0,0 +1,10 @@
{
"compilerOptions": {
"target": "ES2015",
"module": "ESNext"
},
"include": [
"src/**/*",
"rollup.config.ts"
],
}