hassio-plejd/plejd/main.js

80 lines
2.1 KiB
JavaScript
Raw Normal View History

2019-12-04 11:17:06 +01:00
const api = require('./api');
const mqtt = require('./mqtt');
const fs = require('fs');
2020-01-17 15:00:54 +00:00
const PlejdService = require('./ble.bluez');
2019-12-04 11:17:06 +01:00
2020-01-24 11:00:23 +01:00
const version = "0.3.1";
2019-12-23 11:51:04 +00:00
2019-12-04 11:17:06 +01:00
async function main() {
2019-12-23 11:51:04 +00:00
console.log('starting Plejd add-on v. ' + version);
2020-01-20 19:21:54 +00:00
const rawData = fs.readFileSync('/data/plejd.json');
2019-12-04 11:17:06 +01:00
const config = JSON.parse(rawData);
const plejdApi = new api.PlejdApi(config.site, config.username, config.password);
const client = new mqtt.MqttClient(config.mqttBroker, config.mqttUsername, config.mqttPassword);
plejdApi.once('loggedIn', () => {
2020-01-20 12:28:02 +00:00
plejdApi.getCryptoKey();
2020-01-17 15:00:54 +00:00
plejdApi.on('ready', (cryptoKey) => {
2019-12-04 11:17:06 +01:00
const devices = plejdApi.getDevices();
2019-12-04 18:52:50 +01:00
client.on('connected', () => {
2019-12-04 11:17:06 +01:00
console.log('plejd-mqtt: connected to mqtt.');
client.discover(devices);
});
client.init();
// init the BLE interface
2019-12-19 09:58:53 +00:00
const plejd = new PlejdService(cryptoKey, true);
2020-01-20 12:28:02 +00:00
plejd.on('connectFailed', () => {
2020-01-20 21:32:46 +00:00
console.log('plejd-ble: were unable to connect, will retry connection in 10 seconds.');
2020-01-20 12:28:02 +00:00
setTimeout(() => {
plejd.init();
}, 10000);
});
2020-01-18 15:50:46 +00:00
plejd.init();
2020-01-20 12:28:02 +00:00
2019-12-19 09:58:53 +00:00
plejd.on('authenticated', () => {
2019-12-04 11:17:06 +01:00
console.log('plejd: connected via bluetooth.');
});
// subscribe to changes from Plejd
2019-12-21 15:01:15 +00:00
plejd.on('stateChanged', (deviceId, command) => {
client.updateState(deviceId, command);
2019-12-04 11:17:06 +01:00
});
plejd.on('sceneTriggered', (deviceId, scene) => {
2019-12-22 17:48:16 +00:00
client.sceneTriggered(scene);
});
2019-12-04 11:17:06 +01:00
// subscribe to changes from HA
2019-12-21 15:01:15 +00:00
client.on('stateChanged', (deviceId, command) => {
if (command.state === 'ON') {
plejd.turnOn(deviceId, command);
2019-12-04 11:17:06 +01:00
}
else {
2019-12-21 15:01:15 +00:00
plejd.turnOff(deviceId, command);
2019-12-04 11:17:06 +01:00
}
});
client.on('settingsChanged', (settings) => {
if (settings.module === 'mqtt') {
client.updateSettings(settings);
}
else if (settings.module === 'ble') {
plejd.updateSettings(settings);
}
else if (settings.module === 'api') {
plejdApi.updateSettings(settings);
}
2020-01-15 09:33:54 +00:00
});
2019-12-04 11:17:06 +01:00
});
});
plejdApi.login();
}
main();