Merge pull request #73 from icanos/feature/new-api-version

updated to comply with new api version
This commit is contained in:
Marcus Westin 2020-03-13 12:04:30 +01:00 committed by GitHub
commit bb8f43f4a4
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 167 additions and 110 deletions

View file

@ -5,7 +5,8 @@ const _ = require('lodash');
API_APP_ID = 'zHtVqXt8k4yFyk2QGmgp48D9xZr2G94xWYnF4dak'; API_APP_ID = 'zHtVqXt8k4yFyk2QGmgp48D9xZr2G94xWYnF4dak';
API_BASE_URL = 'https://cloud.plejd.com/parse/'; API_BASE_URL = 'https://cloud.plejd.com/parse/';
API_LOGIN_URL = 'login'; API_LOGIN_URL = 'login';
API_SITES_URL = 'functions/getSites'; API_SITE_LIST_URL = 'functions/getSiteList';
API_SITE_DETAILS_URL = 'functions/getSiteById';
// #region logging // #region logging
let debug = ''; let debug = '';
@ -56,31 +57,41 @@ class PlejdApi extends EventEmitter {
} }
}); });
logger('sending POST to ' + API_BASE_URL + API_LOGIN_URL); return new Promise((resolve, reject) => {
logger('sending POST to ' + API_BASE_URL + API_LOGIN_URL);
instance.post( instance.post(
API_LOGIN_URL, API_LOGIN_URL,
{ {
'username': this.username, 'username': this.username,
'password': this.password 'password': this.password
}) })
.then((response) => { .then((response) => {
console.log('plejd-api: got session token response'); console.log('plejd-api: got session token response');
self.sessionToken = response.data.sessionToken; self.sessionToken = response.data.sessionToken;
self.emit('loggedIn');
}) if (!self.sessionToken) {
.catch((error) => { console.log('plejd-api: error: no session token received');
if (error.response.status === 400) { reject('no session token received.');
console.log('error: server returned status 400. probably invalid credentials, please verify.'); }
}
else { resolve();
console.log('error: unable to retrieve session token response: ' + error); })
} .catch((error) => {
}); if (error.response.status === 400) {
console.log('error: server returned status 400. probably invalid credentials, please verify.');
}
else {
console.log('error: unable to retrieve session token response: ' + error);
}
reject('unable to retrieve session token response: ' + error);
});
});
} }
getCryptoKey(callback) { getSites() {
console.log('plejd-api: getCryptoKey()'); console.log('plejd-api: getSites()');
const self = this; const self = this;
const instance = axios.create({ const instance = axios.create({
@ -92,20 +103,65 @@ class PlejdApi extends EventEmitter {
} }
}); });
logger('sending POST to ' + API_BASE_URL + API_SITES_URL); return new Promise((resolve, reject) => {
logger('sending POST to ' + API_BASE_URL + API_SITE_LIST_URL);
instance.post(API_SITES_URL) instance.post(API_SITE_LIST_URL)
.then((response) => { .then((response) => {
console.log('plejd-api: got sites response'); console.log('plejd-api: got site list response');
self.site = response.data.result.find(x => x.site.title == self.siteName); const site = response.data.result.find(x => x.site.title == self.siteName);
self.cryptoKey = self.site.plejdMesh.cryptoKey;
this.emit('ready', self.cryptoKey, self.site); if (!site) {
}) console.log('plejd-api: error: failed to find a site named ' + self.siteName);
.catch((error) => { reject('failed to find a site named ' + self.siteName);
console.log('error: unable to retrieve the crypto key. error: ' + error); return;
return Promise.reject('unable to retrieve the crypto key. error: ' + error); }
});
resolve(site);
})
.catch((error) => {
console.log('plejd-api: error: unable to retrieve list of sites. error: ' + error);
return reject('plejd-api: unable to retrieve list of sites. error: ' + error);
});
});
}
getSite(siteId) {
console.log('plejd-api: getSites()');
const self = this;
const instance = axios.create({
baseURL: API_BASE_URL,
headers: {
'X-Parse-Application-Id': API_APP_ID,
'X-Parse-Session-Token': this.sessionToken,
'Content-Type': 'application/json'
}
});
return new Promise((resolve, reject) => {
logger('sending POST to ' + API_BASE_URL + API_SITE_DETAILS_URL);
instance.post(API_SITE_DETAILS_URL, { siteId: siteId })
.then((response) => {
console.log('plejd-api: got site details response');
if (response.data.result.length === 0) {
const msg = 'no site with ID ' + siteId + ' was found.';
console.log('plejd-api: error: ' + msg);
reject(msg);
return;
}
self.site = response.data.result[0];
self.cryptoKey = self.site.plejdMesh.cryptoKey;
resolve(self.cryptoKey);
})
.catch((error) => {
console.log('plejd-api: error: unable to retrieve the crypto key. error: ' + error);
return reject('plejd-api: unable to retrieve the crypto key. error: ' + error);
});
});
} }
getDevices() { getDevices() {

View file

@ -1,6 +1,6 @@
{ {
"name": "Plejd", "name": "Plejd",
"version": "0.4.2", "version": "0.4.3",
"slug": "plejd", "slug": "plejd",
"description": "Adds support for the Swedish home automation devices from Plejd.", "description": "Adds support for the Swedish home automation devices from Plejd.",
"url": "https://github.com/icanos/hassio-plejd/", "url": "https://github.com/icanos/hassio-plejd/",

View file

@ -4,7 +4,7 @@ const fs = require('fs');
const PlejdService = require('./ble.bluez'); const PlejdService = require('./ble.bluez');
const SceneManager = require('./scene.manager'); const SceneManager = require('./scene.manager');
const version = "0.4.2"; const version = "0.4.3";
async function main() { async function main() {
console.log('starting Plejd add-on v. ' + version); console.log('starting Plejd add-on v. ' + version);
@ -19,96 +19,97 @@ async function main() {
const plejdApi = new api.PlejdApi(config.site, config.username, config.password); const plejdApi = new api.PlejdApi(config.site, config.username, config.password);
const client = new mqtt.MqttClient(config.mqttBroker, config.mqttUsername, config.mqttPassword); const client = new mqtt.MqttClient(config.mqttBroker, config.mqttUsername, config.mqttPassword);
plejdApi.once('loggedIn', () => { plejdApi.login().then(() => {
plejdApi.on('ready', (cryptoKey, site) => { // load all sites and find the one that we want (from config)
const devices = plejdApi.getDevices(); plejdApi.getSites().then((site) => {
// load the site and retrieve the crypto key
plejdApi.getSite(site.site.siteId).then((cryptoKey) => {
// parse all devices from the API
const devices = plejdApi.getDevices();
client.on('connected', () => { client.on('connected', () => {
console.log('plejd-mqtt: connected to mqtt.'); console.log('plejd-mqtt: connected to mqtt.');
client.discover(devices); client.discover(devices);
}); });
client.init(); client.init();
// init the BLE interface // init the BLE interface
const sceneManager = new SceneManager(site, devices); const sceneManager = new SceneManager(plejdApi.site, devices);
const plejd = new PlejdService(cryptoKey, devices, sceneManager, config.connectionTimeout, config.writeQueueWaitTime, true); const plejd = new PlejdService(cryptoKey, devices, sceneManager, config.connectionTimeout, config.writeQueueWaitTime, true);
plejd.on('connectFailed', () => { plejd.on('connectFailed', () => {
console.log('plejd-ble: were unable to connect, will retry connection in 10 seconds.'); console.log('plejd-ble: were unable to connect, will retry connection in 10 seconds.');
setTimeout(() => { setTimeout(() => {
plejd.init(); plejd.init();
}, 10000); }, 10000);
}); });
plejd.init(); plejd.init();
plejd.on('authenticated', () => { plejd.on('authenticated', () => {
console.log('plejd: connected via bluetooth.'); console.log('plejd: connected via bluetooth.');
}); });
// subscribe to changes from Plejd // subscribe to changes from Plejd
plejd.on('stateChanged', (deviceId, command) => { plejd.on('stateChanged', (deviceId, command) => {
client.updateState(deviceId, command); client.updateState(deviceId, command);
}); });
plejd.on('sceneTriggered', (deviceId, scene) => { plejd.on('sceneTriggered', (deviceId, scene) => {
client.sceneTriggered(scene); client.sceneTriggered(scene);
}); });
// subscribe to changes from HA // subscribe to changes from HA
client.on('stateChanged', (device, command) => { client.on('stateChanged', (device, command) => {
const deviceId = device.id; const deviceId = device.id;
if (device.typeName === 'Scene') { if (device.typeName === 'Scene') {
// we're triggering a scene, lets do that and jump out. // we're triggering a scene, lets do that and jump out.
// since scenes aren't "real" devices. // since scenes aren't "real" devices.
plejd.triggerScene(device.id); plejd.triggerScene(device.id);
return; return;
} }
let state = 'OFF'; let state = 'OFF';
let commandObj = {}; let commandObj = {};
if (typeof command === 'string') { if (typeof command === 'string') {
// switch command // switch command
state = command; state = command;
commandObj = { state: state }; commandObj = { state: state };
// since the switch doesn't get any updates on whether it's on or not, // since the switch doesn't get any updates on whether it's on or not,
// we fake this by directly send the updateState back to HA in order for // we fake this by directly send the updateState back to HA in order for
// it to change state. // it to change state.
client.updateState(deviceId, { state: state === 'ON' ? 1 : 0 }); client.updateState(deviceId, { state: state === 'ON' ? 1 : 0 });
} }
else { else {
state = command.state; state = command.state;
commandObj = command; commandObj = command;
} }
if (state === 'ON') { if (state === 'ON') {
plejd.turnOn(deviceId, commandObj); plejd.turnOn(deviceId, commandObj);
} }
else { else {
plejd.turnOff(deviceId, commandObj); plejd.turnOff(deviceId, commandObj);
} }
}); });
client.on('settingsChanged', (settings) => { client.on('settingsChanged', (settings) => {
if (settings.module === 'mqtt') { if (settings.module === 'mqtt') {
client.updateSettings(settings); client.updateSettings(settings);
} }
else if (settings.module === 'ble') { else if (settings.module === 'ble') {
plejd.updateSettings(settings); plejd.updateSettings(settings);
} }
else if (settings.module === 'api') { else if (settings.module === 'api') {
plejdApi.updateSettings(settings); plejdApi.updateSettings(settings);
} }
});
}); });
}); });
plejdApi.getCryptoKey();
}); });
plejdApi.login();
} }
main(); main();