All the work
This commit is contained in:
1 parent
f6767c9e8f
commit
2a1efb2aff
15 files changed
+5006
-349
No files matched your search
@@ -0,0 +1,5 @@
|
|||||||
|
.vscode
|
||||||
|
node_modules
|
||||||
|
dist
|
||||||
|
build
|
||||||
|
.parcel-cache
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
{
|
||||||
|
"jsc": {
|
||||||
|
"target": "es3",
|
||||||
|
"parser": {
|
||||||
|
"syntax": "typescript",
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"minify": false,
|
||||||
|
"isModule": true,
|
||||||
|
"sourceMaps": false,
|
||||||
|
"inlineSourcesContent": false
|
||||||
|
}
|
||||||
@@ -1,10 +1,13 @@
|
|||||||
# flic2hass
|
# 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:
|
Requirements:
|
||||||
|
|
||||||
* A Flic Hub
|
* A Flic Hub
|
||||||
* A functional MQTT server
|
* A functional MQTT server
|
||||||
## Basic Steps:
|
|
||||||
|
## Basic Steps
|
||||||
|
|
||||||
**1. Connect to Flic Hub IDE:**
|
**1. Connect to Flic Hub IDE:**
|
||||||
|
|
||||||
@@ -16,40 +19,72 @@ Requirements:
|
|||||||
* One in the Web IDE, click "Create Module".
|
* One in the Web IDE, click "Create Module".
|
||||||
* Give the new module a name. "`MQTT`" is a good option but anything will work.
|
* 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".
|
* Right click the folder in the left pane and select "New File".
|
||||||
* Name the file `mqtt.js` (IT MUST BE NAMED THIS).
|
* Name the file `lib.js` (IT MUST BE NAMED THIS).
|
||||||
* Copy content from `mqtt.js` in this repo to mqtt.js in the flic IDE.
|
* 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:*
|
*If your MQTT server does not require authentication:*
|
||||||
|
|
||||||
* Delete:
|
* Delete `username` & `password`:
|
||||||
|
|
||||||
```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);
|
|
||||||
```
|
|
||||||
|
|
||||||
1. Start the module in the IDE by clicking the green play button, and watch the Console output (it's extremely verbose right now)
|
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.*
|
*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.
|
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
|
||||||
|
},
|
||||||
|
}
|
||||||
|
```
|
||||||
@@ -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();
|
|
||||||
Generated
+3084
File diff suppressed because it is too large.
Load diff
@@ -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"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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')}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -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()
|
||||||
|
}
|
||||||
+122
-92
@@ -31,32 +31,32 @@ Modified by Flic Shortcut Labs.
|
|||||||
/** 'private' constants */
|
/** 'private' constants */
|
||||||
var C = {
|
var C = {
|
||||||
PROTOCOL_LEVEL: 4, // MQTT protocol level
|
PROTOCOL_LEVEL: 4, // MQTT protocol level
|
||||||
DEF_PORT : 1883, // MQTT default server port
|
DEF_PORT: 1883, // MQTT default server port
|
||||||
DEF_KEEP_ALIVE: 60 // Default keep_alive (s)
|
DEF_KEEP_ALIVE: 60 // Default keep_alive (s)
|
||||||
};
|
};
|
||||||
|
|
||||||
/** Control packet types */
|
/** Control packet types */
|
||||||
var TYPE = {
|
var TYPE = {
|
||||||
CONNECT : 1,
|
CONNECT: 1,
|
||||||
CONNACK : 2,
|
CONNACK: 2,
|
||||||
PUBLISH : 3,
|
PUBLISH: 3,
|
||||||
PUBACK : 4,
|
PUBACK: 4,
|
||||||
PUBREC : 5,
|
PUBREC: 5,
|
||||||
PUBREL : 6,
|
PUBREL: 6,
|
||||||
PUBCOMP : 7,
|
PUBCOMP: 7,
|
||||||
SUBSCRIBE : 8,
|
SUBSCRIBE: 8,
|
||||||
SUBACK : 9,
|
SUBACK: 9,
|
||||||
UNSUBSCRIBE: 10,
|
UNSUBSCRIBE: 10,
|
||||||
UNSUBACK : 11,
|
UNSUBACK: 11,
|
||||||
PINGREQ : 12,
|
PINGREQ: 12,
|
||||||
PINGRESP : 13,
|
PINGRESP: 13,
|
||||||
DISCONNECT : 14
|
DISCONNECT: 14
|
||||||
};
|
};
|
||||||
|
|
||||||
var pakId = Math.floor(Math.random() * 65534);
|
var pakId = Math.floor(Math.random() * 65534);
|
||||||
|
|
||||||
Uint8Array.prototype.charCodeAt = function(a,b) {
|
Uint8Array.prototype.charCodeAt = function (a, b) {
|
||||||
return this.toString().charCodeAt(a,b);
|
return this.toString().charCodeAt(a, b);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -92,7 +92,7 @@ function MQTT(server, options) {
|
|||||||
this.protocol_level = (options.protocol_level || C.PROTOCOL_LEVEL);
|
this.protocol_level = (options.protocol_level || C.PROTOCOL_LEVEL);
|
||||||
|
|
||||||
if (typeof this.client_id == 'string') {
|
if (typeof this.client_id == 'string') {
|
||||||
var payloadarray =[this.client_id.length >> 8, this.client_id.length & 255];
|
var payloadarray = [this.client_id.length >> 8, this.client_id.length & 255];
|
||||||
var i = 2;
|
var i = 2;
|
||||||
var messagearray = this.client_id.split('');
|
var messagearray = this.client_id.split('');
|
||||||
for (var j = 0; j < this.client_id.length; j++) {
|
for (var j = 0; j < this.client_id.length; j++) {
|
||||||
@@ -104,7 +104,7 @@ function MQTT(server, options) {
|
|||||||
this.client_id = payloadarray;
|
this.client_id = payloadarray;
|
||||||
}
|
}
|
||||||
if (this.password) {
|
if (this.password) {
|
||||||
var payloadarray =[this.password.length >> 8, this.password.length & 255];
|
var payloadarray = [this.password.length >> 8, this.password.length & 255];
|
||||||
var i = 2;
|
var i = 2;
|
||||||
var messagearray = this.password.split('');
|
var messagearray = this.password.split('');
|
||||||
for (var j = 0; j < this.password.length; j++) {
|
for (var j = 0; j < this.password.length; j++) {
|
||||||
@@ -116,7 +116,7 @@ function MQTT(server, options) {
|
|||||||
this.password = payloadarray;
|
this.password = payloadarray;
|
||||||
}
|
}
|
||||||
if (this.username) {
|
if (this.username) {
|
||||||
var payloadarray =[this.username.length >> 8, this.username.length & 255];
|
var payloadarray = [this.username.length >> 8, this.username.length & 255];
|
||||||
var i = 2;
|
var i = 2;
|
||||||
var messagearray = this.username.split('');
|
var messagearray = this.username.split('');
|
||||||
for (var j = 0; j < this.username.length; j++) {
|
for (var j = 0; j < this.username.length; j++) {
|
||||||
@@ -131,32 +131,32 @@ function MQTT(server, options) {
|
|||||||
|
|
||||||
var __listeners = {};
|
var __listeners = {};
|
||||||
|
|
||||||
Object.prototype.on = function(type, fn) {
|
Object.prototype.on = function (type, fn) {
|
||||||
if (!__listeners[type]) {
|
if (!__listeners[type]) {
|
||||||
__listeners[type] = [];
|
__listeners[type] = [];
|
||||||
}
|
}
|
||||||
__listeners[type].push(fn);
|
__listeners[type].push(fn);
|
||||||
}
|
}
|
||||||
|
|
||||||
Object.prototype.emit = function (type, data) {
|
Object.prototype.emit = function (type, ...data) {
|
||||||
if (__listeners[type]) {
|
if (__listeners[type]) {
|
||||||
__listeners[type].map(function (fn) {
|
__listeners[type].map(function (fn) {
|
||||||
fn(data);
|
fn(...data);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!Buffer.from) {
|
if (!Buffer.from) {
|
||||||
Buffer.from = function(a) {
|
Buffer.from = function (a) {
|
||||||
return new Buffer(a);
|
return new Buffer(a);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 'public' constants here */
|
/** 'public' constants here */
|
||||||
MQTT.prototype.C = {
|
MQTT.prototype.C = {
|
||||||
DEF_QOS : 0, // Default QOS level
|
DEF_QOS: 0, // Default QOS level
|
||||||
CONNECT_TIMEOUT: 10000, // Time (ms) to wait for CONNACK
|
CONNECT_TIMEOUT: 10000, // Time (ms) to wait for CONNACK
|
||||||
PING_INTERVAL : 40 // Server ping interval (s)
|
PING_INTERVAL: 40 // Server ping interval (s)
|
||||||
};
|
};
|
||||||
|
|
||||||
/* Utility functions ***************************/
|
/* Utility functions ***************************/
|
||||||
@@ -164,34 +164,41 @@ MQTT.prototype.C = {
|
|||||||
var fromCharCode = String.fromCharCode;
|
var fromCharCode = String.fromCharCode;
|
||||||
|
|
||||||
/** MQTT string (length MSB, LSB + data) */
|
/** MQTT string (length MSB, LSB + data) */
|
||||||
function mqttStr(s) {
|
export function mqttStr(s) {
|
||||||
var payloadarray =[s.length >> 8, s.length & 255];
|
var payloadarray = [s.length >> 8, s.length & 255];
|
||||||
var i = 2;
|
var i = 2;
|
||||||
var messagearray = s.split('');
|
var messagearray = s.split('');
|
||||||
for (var j = 0; j < s.length; j++) {
|
for (var j = 0; j < s.length; j++) {
|
||||||
var char = messagearray[j];
|
var char = messagearray[j];
|
||||||
var numberrepres = char.charCodeAt(0);
|
var numberrepres = char.charCodeAt(0);
|
||||||
payloadarray[i] = numberrepres;
|
payloadarray[i] = numberrepres;
|
||||||
i = i + 1;
|
i = i + 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
return payloadarray;
|
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 */
|
/** MQTT packet length formatter - algorithm from reference docs */
|
||||||
function mqttPacketLength(length) {
|
function mqttPacketLength(length) {
|
||||||
var encLength = [];
|
var encLength = [];
|
||||||
var i = 0;
|
var i = 0;
|
||||||
do {
|
do {
|
||||||
var encByte = length & 127;
|
var encByte = length & 127;
|
||||||
length = length >> 7;
|
length = length >> 7;
|
||||||
// if there are more data to encode, set the top bit of this byte
|
// if there are more data to encode, set the top bit of this byte
|
||||||
if (length > 0) {
|
if (length > 0) {
|
||||||
encByte += 128;
|
encByte += 128;
|
||||||
}
|
}
|
||||||
encLength[i] = encByte;
|
encLength[i] = encByte;
|
||||||
i++;
|
i++;
|
||||||
} while (length > 0);
|
} while (length > 0);
|
||||||
return encLength;
|
return encLength;
|
||||||
}
|
}
|
||||||
@@ -203,9 +210,9 @@ function mqttPacketLengthDec(length) {
|
|||||||
var lb = 0;
|
var lb = 0;
|
||||||
do {
|
do {
|
||||||
lb = length[bytes];
|
lb = length[bytes];
|
||||||
decL |= (lb & 127) << (bytes++*7);
|
decL |= (lb & 127) << (bytes++ * 7);
|
||||||
} while ((lb & 128) && (bytes < 4))
|
} while ((lb & 128) && (bytes < 4))
|
||||||
return {"decLen": decL, "lenBy": bytes};
|
return { "decLen": decL, "lenBy": bytes };
|
||||||
}
|
}
|
||||||
|
|
||||||
/** MQTT standard packet formatter */
|
/** MQTT standard packet formatter */
|
||||||
@@ -219,7 +226,7 @@ function mqttPacket(cmd, variable, payload) {
|
|||||||
/** Generate random UID */
|
/** Generate random UID */
|
||||||
var mqttUid = (function () {
|
var mqttUid = (function () {
|
||||||
function s4() {
|
function s4() {
|
||||||
var numberstring = Math.floor((1 + Math.random()*10));
|
var numberstring = Math.floor((1 + Math.random() * 10));
|
||||||
if (numberstring == 10) numberstring = 9;
|
if (numberstring == 10) numberstring = 9;
|
||||||
numberstring = 97 + numberstring;
|
numberstring = 97 + numberstring;
|
||||||
return numberstring;
|
return numberstring;
|
||||||
@@ -239,7 +246,7 @@ function mqttPid() {
|
|||||||
|
|
||||||
/** Get PID from message */
|
/** Get PID from message */
|
||||||
function getPid(data) {
|
function getPid(data) {
|
||||||
return data.slice(0,2);
|
return data.slice(0, 2);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** PUBLISH control packet */
|
/** PUBLISH control packet */
|
||||||
@@ -258,15 +265,15 @@ function mqttPublish(topic, message, qos, flags) {
|
|||||||
/** SUBSCRIBE control packet */
|
/** SUBSCRIBE control packet */
|
||||||
function mqttSubscribe(topic, qos) {
|
function mqttSubscribe(topic, qos) {
|
||||||
var cmd = TYPE.SUBSCRIBE << 4 | 2;
|
var cmd = TYPE.SUBSCRIBE << 4 | 2;
|
||||||
var payloadarray =[];
|
var payloadarray = [];
|
||||||
var i = 0;
|
var i = 0;
|
||||||
var messagearray = topic.split('');
|
var messagearray = topic.split('');
|
||||||
for (var j = 0; j < topic.length; j++) {
|
for (var j = 0; j < topic.length; j++) {
|
||||||
var char = messagearray[j];
|
var char = messagearray[j];
|
||||||
var numberrepres = char.charCodeAt(0);
|
var numberrepres = char.charCodeAt(0);
|
||||||
payloadarray[i] = numberrepres;
|
payloadarray[i] = numberrepres;
|
||||||
i = i + 1;
|
i = i + 1;
|
||||||
}
|
}
|
||||||
return mqttPacket(cmd,
|
return mqttPacket(cmd,
|
||||||
mqttPid(),
|
mqttPid(),
|
||||||
mqttStr(topic).concat([qos]));
|
mqttStr(topic).concat([qos]));
|
||||||
@@ -281,12 +288,12 @@ function mqttUnsubscribe(topic) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** Create escaped hex value from number */
|
/** Create escaped hex value from number */
|
||||||
function createEscapedHex(number) {
|
function createEscapedHex(n: number): string {
|
||||||
return fromCharCode(parseInt(number.toString(16), 16));
|
return fromCharCode(parseInt(n.toString(16), 16));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Handle a single packet of data
|
// Handle a single packet of data
|
||||||
MQTT.prototype.packetHandler = function(data) {
|
MQTT.prototype.packetHandler = function (data) {
|
||||||
|
|
||||||
// if we had some data left over from last
|
// if we had some data left over from last
|
||||||
// time, add it on
|
// time, add it on
|
||||||
@@ -318,18 +325,18 @@ MQTT.prototype.packetHandler = function(data) {
|
|||||||
var topic_len = pData[0] << 8 | pData[1];
|
var topic_len = pData[0] << 8 | pData[1];
|
||||||
var msg_start = 2 + topic_len + (qos ? 2 : 0);
|
var msg_start = 2 + topic_len + (qos ? 2 : 0);
|
||||||
var parsedData = {
|
var parsedData = {
|
||||||
topic : pData.slice(2, 2 + topic_len),
|
topic: pData.slice(2, 2 + topic_len),
|
||||||
message: pData.slice(msg_start, pData.length),
|
message: pData.slice(msg_start, pData.length),
|
||||||
dup : (cmd & 0x8) >> 3,
|
dup: (cmd & 0x8) >> 3,
|
||||||
qos : qos,
|
qos: qos,
|
||||||
pid : qos?pData.slice(2+topic_len,4+topic_len):0,
|
pid: qos ? pData.slice(2 + topic_len, 4 + topic_len) : 0,
|
||||||
retain : cmd & 0x1
|
retain: cmd & 0x1
|
||||||
};
|
};
|
||||||
if (parsedData.qos) {
|
if (parsedData.qos) {
|
||||||
this.client.write([((parsedData.qos == 1)?TYPE.PUBACK:TYPE.PUBREC) << 4, 2, parsedData.pid]);
|
this.client.write([((parsedData.qos == 1) ? TYPE.PUBACK : TYPE.PUBREC) << 4, 2, parsedData.pid]);
|
||||||
}
|
}
|
||||||
this.emit('publish', parsedData);
|
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) {
|
} else if (type === TYPE.PUBACK) {
|
||||||
this.emit('puback', data.charCodeAt(2) << 8 | data.charCodeAt(3));
|
this.emit('puback', data.charCodeAt(2) << 8 | data.charCodeAt(3));
|
||||||
} else if (type === TYPE.PUBREC) {
|
} else if (type === TYPE.PUBREC) {
|
||||||
@@ -345,8 +352,8 @@ MQTT.prototype.packetHandler = function(data) {
|
|||||||
} else if (type === TYPE.PUBCOMP) {
|
} else if (type === TYPE.PUBCOMP) {
|
||||||
this.emit('pubcomp', data.charCodeAt(2) << 8 | data.charCodeAt(3));
|
this.emit('pubcomp', data.charCodeAt(2) << 8 | data.charCodeAt(3));
|
||||||
} else if (type === TYPE.SUBACK) {
|
} else if (type === TYPE.SUBACK) {
|
||||||
if(pData.length > 0) {
|
if (pData.length > 0) {
|
||||||
if(pData[pData.length - 1] == 0x80) {
|
if (pData[pData.length - 1] == 0x80) {
|
||||||
this.emit('subscribed_fail');
|
this.emit('subscribed_fail');
|
||||||
} else {
|
} else {
|
||||||
this.emit('subscribed');
|
this.emit('subscribed');
|
||||||
@@ -442,11 +449,11 @@ MQTT.prototype._scktClosed = function () {
|
|||||||
/** Disconnect from server */
|
/** Disconnect from server */
|
||||||
MQTT.prototype.disconnect = function () {
|
MQTT.prototype.disconnect = function () {
|
||||||
if (!this.client) return;
|
if (!this.client) return;
|
||||||
try {
|
try {
|
||||||
this.client.write(Buffer.from([(TYPE.DISCONNECT << 4), 0]));
|
this.client.write(Buffer.from([(TYPE.DISCONNECT << 4), 0]));
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
return this._scktClosed();
|
return this._scktClosed();
|
||||||
}
|
}
|
||||||
this.client.end();
|
this.client.end();
|
||||||
this.client = false;
|
this.client = false;
|
||||||
};
|
};
|
||||||
@@ -461,7 +468,7 @@ MQTT.prototype.publish = function (topic, message, opts) {
|
|||||||
if (!this.client) return;
|
if (!this.client) return;
|
||||||
opts = opts || {};
|
opts = opts || {};
|
||||||
try {
|
try {
|
||||||
var payloadarray =[];
|
var payloadarray = [];
|
||||||
var i = 0;
|
var i = 0;
|
||||||
var messagearray = message.split('');
|
var messagearray = message.split('');
|
||||||
for (var j = 0; j < message.length; j++) {
|
for (var j = 0; j < message.length; j++) {
|
||||||
@@ -490,16 +497,16 @@ MQTT.prototype.subscribe = function (topics, opts) {
|
|||||||
topics.forEach(function (topic) {
|
topics.forEach(function (topic) {
|
||||||
subs.push({
|
subs.push({
|
||||||
topic: topic,
|
topic: topic,
|
||||||
qos : opts.qos || this.C.DEF_QOS
|
qos: opts.qos || this.C.DEF_QOS
|
||||||
});
|
});
|
||||||
}.bind(this));
|
}.bind(this));
|
||||||
} else {
|
} else {
|
||||||
Object
|
Object
|
||||||
.keys(topics)
|
.keys(topics)
|
||||||
.forEach(function (k) {
|
.forEach(function (k) {
|
||||||
subs.push({
|
subs.push({
|
||||||
topic: k,
|
topic: k,
|
||||||
qos : topics[k]
|
qos: topics[k]
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -531,9 +538,9 @@ MQTT.prototype.ping = function () {
|
|||||||
/** Create connection flags */
|
/** Create connection flags */
|
||||||
MQTT.prototype.createFlagsForConnection = function (options) {
|
MQTT.prototype.createFlagsForConnection = function (options) {
|
||||||
var flags = 0;
|
var flags = 0;
|
||||||
flags |= ( this.username ) ? 0x80 : 0;
|
flags |= (this.username) ? 0x80 : 0;
|
||||||
flags |= ( this.username && this.password ) ? 0x40 : 0;
|
flags |= (this.username && this.password) ? 0x40 : 0;
|
||||||
flags |= ( options.clean_session ) ? 0x02 : 0;
|
flags |= (options.clean_session) ? 0x02 : 0;
|
||||||
return flags;
|
return flags;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -560,21 +567,44 @@ MQTT.prototype.mqttConnect = function (clean) {
|
|||||||
}
|
}
|
||||||
return mqttPacket(cmd,
|
return mqttPacket(cmd,
|
||||||
mqttStr(this.protocol_name)/*protocol name*/.concat(
|
mqttStr(this.protocol_name)/*protocol name*/.concat(
|
||||||
[this.protocol_level]) /*protocol level*/.concat(
|
[this.protocol_level]) /*protocol level*/.concat(
|
||||||
[flags]).concat(keep_alive),
|
[flags]).concat(keep_alive),
|
||||||
payload);
|
payload);
|
||||||
};
|
};
|
||||||
|
|
||||||
/* Exports *************************************/
|
/* Exports *************************************/
|
||||||
|
|
||||||
/** This is 'exported' so it can be used with `require('MQTT.js').create(server, options)` */
|
/** 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);
|
return new MQTT(server, options);
|
||||||
};
|
};
|
||||||
|
|
||||||
exports.connect = function (options) {
|
export function connect(options): MQTT {
|
||||||
var mqtt = new MQTT(options.host, options);
|
var mqtt = new MQTT(options.host, options);
|
||||||
mqtt.connect();
|
mqtt.connect();
|
||||||
return mqtt;
|
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;
|
||||||
|
};
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "ES2015",
|
||||||
|
"module": "ESNext"
|
||||||
|
},
|
||||||
|
"include": [
|
||||||
|
"src/**/*",
|
||||||
|
"rollup.config.ts"
|
||||||
|
],
|
||||||
|
}
|
||||||
Reference in new issue
Block a user