hassio-plejd/plejd/main.js

62 lines
1.7 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');
2019-12-19 09:58:53 +00:00
const PlejdService = require('./ble');
2019-12-04 11:17:06 +01:00
async function main() {
const rawData = fs.readFileSync('/data/plejd.json');
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', () => {
plejdApi.getCryptoKey((cryptoKey) => {
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);
plejd.on('authenticated', () => {
2019-12-04 11:17:06 +01:00
console.log('plejd: connected via bluetooth.');
});
// subscribe to changes from Plejd
2019-12-19 09:58:53 +00:00
plejd.on('stateChanged', (deviceId, state) => {
2019-12-04 11:17:06 +01:00
client.updateState(deviceId, state);
});
2019-12-19 09:58:53 +00:00
plejd.on('dimChanged', (deviceId, state, dim) => {
2019-12-04 11:17:06 +01:00
client.updateState(deviceId, state);
client.updateBrightness(deviceId, dim);
});
// subscribe to changes from HA
2019-12-19 09:58:53 +00:00
client.on('stateChanged', (deviceId, state) => {
2019-12-04 11:17:06 +01:00
if (state) {
2019-12-19 09:58:53 +00:00
plejd.turnOn(deviceId);
2019-12-04 11:17:06 +01:00
}
else {
2019-12-19 09:58:53 +00:00
plejd.turnOff(deviceId);
2019-12-04 11:17:06 +01:00
}
});
2019-12-19 09:58:53 +00:00
client.on('brightnessChanged', (deviceId, brightness) => {
2019-12-04 11:17:06 +01:00
if (brightness > 0) {
2019-12-19 09:58:53 +00:00
plejd.turnOn(deviceId, brightness);
2019-12-04 11:17:06 +01:00
}
else {
2019-12-19 09:58:53 +00:00
plejd.turnOff(deviceId);
2019-12-04 11:17:06 +01:00
}
});
});
});
plejdApi.login();
}
main();