Skip to content

Commit

Permalink
Merge pull request #146 from Grizzelbee/Development
Browse files Browse the repository at this point in the history
Development
  • Loading branch information
Grizzelbee authored Oct 7, 2021
2 parents 4edeac1 + d239c44 commit 35bdd61
Show file tree
Hide file tree
Showing 7 changed files with 105 additions and 84 deletions.
6 changes: 5 additions & 1 deletion dyson-utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,14 @@ const httpsAgent = new https.Agent({ca: rootCas});
rootCas.addFile(path.resolve(__dirname, 'certificates/intermediate.pem'));


module.exports.wait=async function(milliSec){
return setTimeout(()=>{/* do nothing but waiting */}, milliSec);
};



/**
* getDyson2faMail
*
* Does the first part of the dyson 2FA. Requests the one-time-password from the API
*
* @param {object} adapter link to the adapter instance
Expand Down
78 changes: 39 additions & 39 deletions dysonConstants.js

Large diffs are not rendered by default.

52 changes: 32 additions & 20 deletions io-package.json
Original file line number Diff line number Diff line change
@@ -1,30 +1,42 @@
{
"common": {
"name": "dysonairpurifier",
"version": "2.1.1",
"version": "2.1.2",
"news": {
"2.1.2": {
"en": "New: Removed NO2 from general AirQuality to be more compliant to dyson-app\n Upd: Code cleanup\n Upd: Removed delay between sending a command and new values getting displayed (max 30 Secs)",
"de": "Neu: NO2 aus der allgemeinen AirQuality entfernt, um konformer mit der Dyson-App zu sein\n Upd: Code-Bereinigung\n Upd: Verzögerung zwischen dem Senden eines Befehls und der Anzeige neuer Werte entfernt (max. 30 Sek.)",
"ru": "Новое: Удален NO2 из общего AirQuality, чтобы быть более совместимым с приложением dyson\n Upd: Очистка кода\n Upd: Убран разрыв между отправкой команды и отображением новых значений (максимум 30 секунд)",
"pt": "Novo: Removido o NO2 do AirQuality geral para ser mais compatível com o dyson-app\n Upd: Limpeza de código\n Upd: Removida a lacuna entre o envio de um comando e a exibição de novos valores (máximo de 30 segundos)",
"nl": "Nieuw: NO2 verwijderd uit algemene AirQuality om beter te voldoen aan de dyson-app\n Update: code opschonen\n Update: hiaat tussen het verzenden van een opdracht en het weergeven van nieuwe waarden verwijderd (max. 30 seconden)",
"fr": "Nouveau : Suppression du NO2 de AirQuality général pour être plus conforme à l'application dyson\n Mise à jour : Nettoyage du code\n Mise à jour : Suppression de l'écart entre l'envoi d'une commande et l'affichage des nouvelles valeurs (max 30 secondes)",
"it": "Novità: rimosso NO2 dall'AirQuality generale per essere più conforme a dyson-app\n Upd: pulizia del codice\n Upd: rimosso il divario tra l'invio di un comando e la visualizzazione di nuovi valori (max 30 secondi)",
"es": "Nuevo: se eliminó el NO2 de AirQuality general para ser más compatible con la aplicación dyson\n Upd: limpieza de código\n Upd: se eliminó la brecha entre el envío de un comando y la visualización de nuevos valores (máximo 30 segundos)",
"pl": "Nowość: Usunięto NO2 z ogólnej AirQuality, aby był bardziej zgodny z aplikacją dyson\n Aktualizacja: Oczyszczanie kodu\n Aktualizacja: Usunięto przerwę między wysłaniem polecenia a wyświetleniem nowych wartości (maks. 30 sekund)",
"zh-cn": "新功能:从一般空气质量中删除二氧化氮以更符合dyson-app\n 更新:代码清理\n 更新:删除发送命令和显示新值之间的差距(最长 30 秒)"
},
"2.1.1": {
"en": "* (grizzelbee) New: Added some more data points, * (grizzelbee) New: Added switch for temperature unit of the fan display,* (grizzelbee) New: Improved logging of unknown data points,* (germanBluefox) Fix: Fixed icon links,* (grizzelbee) Fix: fixed dependencies badge,* (grizzelbee) Fix: added missing dependency plugin-sentry",
"de": "* (grizzelbee) Neu: Einige weitere Datenpunkte hinzugefügt, * (grizzelbee) Neu: Schalter für Temperatureinheit der Lüfteranzeige hinzugefügt,* (grizzelbee) Neu: Verbesserte Protokollierung unbekannter Datenpunkte,* (germanBluefox) Fix: Icon-Links korrigiert ",
"ru": "* (grizzelbee) Новое: добавлено несколько точек данных, * (grizzelbee) Новое: добавлен переключатель для единицы температуры дисплея вентилятора, * (grizzelbee) Новое: улучшена регистрация неизвестных точек данных, * (germanBluefox) Исправлено: исправлены ссылки на значки ",
"pt": "* (grizzelbee) Novo: Adicionados mais alguns pontos de dados, * (grizzelbee) Novo: Adicionado interruptor para a unidade de temperatura da tela do ventilador, * (grizzelbee) Novo: Registro aprimorado de pontos de dados desconhecidos, * (germanBluefox) Correção: links de ícones corrigidos ",
"nl": "* (grizzelbee) Nieuw: nog wat datapunten toegevoegd, * (grizzelbee) Nieuw: schakelaar toegevoegd voor temperatuureenheid van het ventilatordisplay,* (grizzelbee) Nieuw: verbeterde logging van onbekende datapunten,* (germanBluefox) Fix: vaste pictogramkoppelingen ",
"fr": "* (grizzelbee) Nouveau : ajout de quelques points de données supplémentaires, * (grizzelbee) Nouveau : ajout d'un commutateur pour l'unité de température de l'affichage du ventilateur,* (grizzelbee) Nouveau : enregistrement amélioré des points de données inconnus,* (allemandBluefox) Correction : liens d'icônes fixes ",
"it": "* (grizzelbee) Novità: Aggiunti altri punti dati, * (grizzelbee) Novità: Aggiunto interruttore per l'unità di temperatura del display della ventola,* (grizzelbee) Novità: Migliorata la registrazione dei punti dati sconosciuti,* (germanBluefox) Correzione: Corretti i collegamenti alle icone ",
"es": "* (grizzelbee) Nuevo: se agregaron algunos puntos de datos más, * (grizzelbee) Nuevo: se agregó un interruptor para la unidad de temperatura de la pantalla del ventilador, * (grizzelbee) Nuevo: registro mejorado de puntos de datos desconocidos, * (germanBluefox) Solución: enlaces de íconos fijos ",
"pl": "* (grizzelbee) Nowość: Dodano więcej punktów danych, * (grizzelbee) Nowość: Dodano przełącznik jednostki temperatury na wyświetlaczu wentylatora,* (grizzelbee) Nowość: Ulepszone rejestrowanie nieznanych punktów danych,* (germanBluefox) Poprawka: Naprawiono łącza ikon ",
"zh-cn": "* (grizzelbee) 新功能:添加了更多数据点,* (grizzelbee) 新功能:添加了风扇显示器温度单位的开关,* (grizzelbee) 新功能:改进了未知数据点的记录,* (germanBluefox) 修复:固定图标链接"
"en": "New: Added some more data points, \nNew: Added switch for temperature unit of the fan display,\nNew: Improved logging of unknown data points,* (germanBluefox) Fix: Fixed icon links,\nFix: fixed dependencies badge,\nFix: added missing dependency plugin-sentry",
"de": "Neu: Einige weitere Datenpunkte hinzugefügt, \nNeu: Schalter für Temperatureinheit der Lüfteranzeige hinzugefügt,\nNeu: Verbesserte Protokollierung unbekannter Datenpunkte,* (germanBluefox) Fix: Icon-Links korrigiert ",
"ru": "Новое: добавлено несколько точек данных, \nНовое: добавлен переключатель для единицы температуры дисплея вентилятора, \nНовое: улучшена регистрация неизвестных точек данных,\n (germanBluefox) Исправлено: исправлены ссылки на значки ",
"pt": "Novo: Adicionados mais alguns pontos de dados, \nNovo: Adicionado interruptor para a unidade de temperatura da tela do ventilador, \nNovo: Registro aprimorado de pontos de dados desconhecidos,\n (germanBluefox) Correção: links de ícones corrigidos ",
"nl": "Nieuw: nog wat datapunten toegevoegd, \nNieuw: schakelaar toegevoegd voor temperatuureenheid van het ventilatordisplay,\nNieuw: verbeterde logging van onbekende datapunten,* (germanBluefox) Fix: vaste pictogramkoppelingen ",
"fr": "Nouveau : ajout de quelques points de données supplémentaires, \nNouveau : ajout d'un commutateur pour l'unité de température de l'affichage du ventilateur,\nNouveau : enregistrement amélioré des points de données inconnus,* (allemandBluefox) Correction : liens d'icônes fixes ",
"it": "Novità: Aggiunti altri punti dati, \nNovità: Aggiunto interruttore per l'unità di temperatura del display della ventola,\nNovità: Migliorata la registrazione dei punti dati sconosciuti,* (germanBluefox) Correzione: Corretti i collegamenti alle icone ",
"es": "Nuevo: se agregaron algunos puntos de datos más, \nNuevo: se agregó un interruptor para la unidad de temperatura de la pantalla del ventilador, \nNuevo: registro mejorado de puntos de datos desconocidos,\n (germanBluefox) Solución: enlaces de íconos fijos ",
"pl": "Nowość: Dodano więcej punktów danych, \nNowość: Dodano przełącznik jednostki temperatury na wyświetlaczu wentylatora,\nNowość: Ulepszone rejestrowanie nieznanych punktów danych,* (germanBluefox) Poprawka: Naprawiono łącza ikon ",
"zh-cn": "新功能:添加了更多数据点,\n新功能:添加了风扇显示器温度单位的开关,\n新功能:改进了未知数据点的记录,* (germanBluefox) 修复:固定图标链接"
},
"2.0.1": {
"en": "* Fixed Sentry Error Cannot read property '3' of undefined, * Turning on HeatingMode should work now, * updated dependencies",
"de": "* Sentry Error behoben Kann die Eigenschaft '3' von undefined nicht lesen, * Das Einschalten des Heizmodus sollte jetzt funktionieren, * Abhängigkeiten aktualisiert.",
"ru": "* Исправлена ​​ошибка Sentry. Невозможно прочесть свойство '3' из undefined, * Включение режима отопления теперь должно работать, * обновленные зависимости",
"pt": "* Erro de Sentinela corrigido, não é possível ler a propriedade '3' de indefinido, * Ativar o HeatingMode deve funcionar agora, * dependências atualizadas",
"nl": "* Vaste Sentry-fout Kan eigenschap '3' van undefined niet lezen, * Verwarmingsmodus inschakelen zou nu moeten werken, * bijgewerkte afhankelijkheden",
"fr": "* Correction de l'erreur Sentry Impossible de lire la propriété '3' de non défini, * L'activation du HeatingMode devrait fonctionner maintenant, * Dépendances mises à jour",
"it": "* Risolto errore Sentry Impossibile leggere la proprietà '3' di undefined, * L'attivazione della modalità di riscaldamento dovrebbe funzionare ora, * dipendenze aggiornate",
"es": "* Se corrigió el error de Sentry No se puede leer la propiedad '3' de indefinido, * Activar el modo de calefacción debería funcionar ahora, * dependencias actualizadas",
"pl": "* Naprawiono błąd Sentry Cannot read property '3' undefined, * Włączenie trybu ogrzewania powinno teraz działać, * zaktualizowane zależności",
"en": "* Fixed Sentry Error Cannot read property '3' of undefined,\n Turning on HeatingMode should work now,\n updated dependencies",
"de": "* Sentry Error behoben Kann die Eigenschaft '3' von undefined nicht lesen,\n Das Einschalten des Heizmodus sollte jetzt funktionieren,\n Abhängigkeiten aktualisiert.",
"ru": "* Исправлена ​​ошибка Sentry. Невозможно прочесть свойство '3' из undefined,\n Включение режима отопления теперь должно работать,\n обновленные зависимости",
"pt": "* Erro de Sentinela corrigido, não é possível ler a propriedade '3' de indefinido,\n Ativar o HeatingMode deve funcionar agora,\n dependências atualizadas",
"nl": "* Vaste Sentry-fout Kan eigenschap '3' van undefined niet lezen,\n Verwarmingsmodus inschakelen zou nu moeten werken,\n bijgewerkte afhankelijkheden",
"fr": "* Correction de l'erreur Sentry Impossible de lire la propriété '3' de non défini,\n L'activation du HeatingMode devrait fonctionner maintenant,\n Dépendances mises à jour",
"it": "* Risolto errore Sentry Impossibile leggere la proprietà '3' di undefined,\n L'attivazione della modalità di riscaldamento dovrebbe funzionare ora,\n dipendenze aggiornate",
"es": "* Se corrigió el error de Sentry No se puede leer la propiedad '3' de indefinido,\n Activar el modo de calefacción debería funcionar ahora,\n dependencias actualizadas",
"pl": "* Naprawiono błąd Sentry Cannot read property '3' undefined,\n Włączenie trybu ogrzewania powinno teraz działać,\n zaktualizowane zależności",
"zh-cn": "* 固定哨兵错误无法读取未定义的属性“3”,* 现在应该可以打开加热模式,* 更新依赖项"
},
"2.0.0": {
Expand Down
33 changes: 16 additions & 17 deletions main.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ const adapterName = require('./package.json').name.split('.').pop();

// Load additional modules
const mqtt = require('mqtt');
// const {stringify} = require('flatted');

// Load utils for this adapter
const dysonUtils = require('./dyson-utils.js');
Expand All @@ -21,8 +20,7 @@ const dysonConstants = require('./dysonConstants.js');
// Variable definitions
let adapter = null;
let adapterIsSetUp = false;
let devices = [];
let NO2 = 0; // Numeric representation of current NO2Index
let devices = {};
let VOC = 0; // Numeric representation of current VOCIndex
let PM25 = 0; // Numeric representation of current PM25Index
let PM10 = 0; // Numeric representation of current PM10Index
Expand Down Expand Up @@ -92,7 +90,6 @@ class dysonAirPurifier extends utils.Adapter {
* @param state {object} new state-object of the datapoint after change
*/
async onStateChange(id, state) {
// id=dysonairpurifier.0.VS9-EU-NAB0887A.OscillationAngle
const thisDevice = id.split('.')[2];
const action = id.split('.').pop();
// Warning, state can be null if it was deleted
Expand Down Expand Up @@ -220,11 +217,16 @@ class dysonAirPurifier extends utils.Adapter {
if (devices[mqttDevice].Serial === thisDevice){
this.log.debug('MANUAL CHANGE: device [' + thisDevice + '] -> [' + action +'] -> [' + state.val + ']');
this.log.info('SENDING this data to device (' + thisDevice + '): ' + JSON.stringify(message));
//noinspection JSUnresolvedVariable
devices[mqttDevice].mqttClient.publish(
devices[mqttDevice].ProductType + '/' + thisDevice + '/command',
JSON.stringify(message)
);
// refresh data asap to avoid 30 Sec gap
devices[mqttDevice].mqttClient.publish(
devices[mqttDevice].ProductType + '/' + devices[mqttDevice].Serial + '/command', JSON.stringify({
msg: 'REQUEST-CURRENT-STATE',
time: new Date().toISOString()
}));
}
}
}
Expand All @@ -236,15 +238,15 @@ class dysonAirPurifier extends utils.Adapter {
this.createOrExtendObject(thisDevice + '.AirQuality', {
type: 'state',
common: {
name: 'Overall AirQuality (worst value of all indexes)',
name: 'Overall AirQuality (worst value of all indexes except NO2)',
'read': true,
'write': false,
'role': 'value',
'type': 'number',
'states' : {0:'Good', 1:'Medium', 2:'Bad', 3:'very Bad', 4:'extremely Bad', 5:'worrying'}
},
native: {}
}, Math.max(NO2, VOC, Dust, PM25, PM10));
}, Math.max(VOC, Dust, PM25, PM10));
}
}
}
Expand Down Expand Up @@ -471,12 +473,12 @@ class dysonAirPurifier extends utils.Adapter {
}
// deviceConfig.length>7 means the data field has predefined states attached, that need to be handled
if (deviceConfig.length > 7) {
this.log.debug(`DeviceConfig: length()=${deviceConfig.length}, 7=[${JSON.stringify(deviceConfig[7])}]`);
// this.log.debug(`DeviceConfig: length()=${deviceConfig.length}, 7=[${JSON.stringify(deviceConfig[7])}]`);
let currentStates={};
if (deviceConfig[7]===dysonConstants.LOAD_FROM_PRODUCTS){
this.log.debug(`Sideloading states for token [${deviceConfig[0]}] - Device:[${device.Serial}], Type:[${device.ProductType}].`);
// this.log.debug(`Sideloading states for token [${deviceConfig[0]}] - Device:[${device.Serial}], Type:[${device.ProductType}].`);
currentStates=dysonConstants.PRODUCTS[device.ProductType][deviceConfig[0]];
this.log.debug(`Sideloading: Found states [${JSON.stringify(currentStates)}].`);
// this.log.debug(`Sideloading: Found states [${JSON.stringify(currentStates)}].`);
} else {
currentStates=deviceConfig[7];
}
Expand Down Expand Up @@ -527,7 +529,6 @@ class dysonAirPurifier extends utils.Adapter {
},
native: {}
}, NO2Index);
NO2 = NO2Index;
this.subscribeStates(device.Serial + '.Sensor.NO2Index' );
}

Expand Down Expand Up @@ -575,10 +576,10 @@ class dysonAirPurifier extends utils.Adapter {
*
* creates the data fields for the values itself and the index if the device has a PM 10 sensor
*
* @param message {object} the received mqtt message
* @param {object} message the received mqtt message
* @param {number} message[].pm10
* @param row {string} the current data row
* @param device {object} the device object the data is valid for
* @param {string} row the current data row
* @param {object} device the device object the data is valid for
*/
createPM10(message, row, device) {
// PM10 QualityIndex
Expand Down Expand Up @@ -699,6 +700,7 @@ class dysonAirPurifier extends utils.Adapter {
this.subscribeStates(device.Serial + '.Sensor.PM25Index' );
}


/**
* main
*
Expand Down Expand Up @@ -740,9 +742,7 @@ class dysonAirPurifier extends utils.Adapter {
// Subscribes to the status topic to receive updates
//noinspection JSUnresolvedVariable
devices[thisDevice].mqttClient.subscribe(devices[thisDevice].ProductType + '/' + devices[thisDevice].Serial + '/status/current', function () {

// Sends an initial request for the current state
//noinspection JSUnresolvedVariable
devices[thisDevice].mqttClient.publish(devices[thisDevice].ProductType + '/' + devices[thisDevice].Serial + '/command', JSON.stringify({
msg: 'REQUEST-CURRENT-STATE',
time: new Date().toISOString()
Expand All @@ -755,7 +755,6 @@ class dysonAirPurifier extends utils.Adapter {
//noinspection JSUnresolvedVariable
adapterLog.debug('Updating device [' + devices[thisDevice].Serial + '] (polling API scheduled).');
try {
//noinspection JSUnresolvedVariable
devices[thisDevice].mqttClient.publish(devices[thisDevice].ProductType + '/' + devices[thisDevice].Serial + '/command', JSON.stringify({
msg: 'REQUEST-CURRENT-STATE',
time: new Date().toISOString()
Expand Down
Loading

0 comments on commit 35bdd61

Please sign in to comment.