diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index e51ae78b..1b23d971 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -2,9 +2,9 @@ name: Build on: push: - branches: [ beta ] + branches: [ beta, alpha ] pull_request: - branches: [ beta ] + branches: [ beta, alpha ] jobs: build: @@ -12,7 +12,7 @@ jobs: strategy: fail-fast: false matrix: - node-version: [16.x, 17.x, 18.x, 20.x] + node-version: [20.x, 21.x] steps: - uses: actions/checkout@v3 - name: Use Node.js ${{ matrix.node-version }} diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index 2b819225..fbdb01f4 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -28,7 +28,7 @@ jobs: # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL - uses: github/codeql-action/init@v1 + uses: github/codeql-action/init@v2 with: languages: ${{ matrix.language }} # If you wish to specify custom queries, you can do so here or in a config file. @@ -39,7 +39,7 @@ jobs: # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). # If this step fails, then you should remove it and run the build manually (see below) - name: Autobuild - uses: github/codeql-action/autobuild@v1 + uses: github/codeql-action/autobuild@v2 # ℹ️ Command-line programs to run using the OS shell. # 📚 https://git.io/JvXDl @@ -53,4 +53,4 @@ jobs: # make release - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@v1 + uses: github/codeql-action/analyze@v2 diff --git a/changelog.asciidoc b/changelog.asciidoc deleted file mode 100644 index 67b1f129..00000000 --- a/changelog.asciidoc +++ /dev/null @@ -1,5 +0,0 @@ -== Changelog - -=== Homebridge - -Voir changelog.asciidoc de plugin-homebridge diff --git a/index.js b/index.js index 28d1f01a..4bc848ef 100755 --- a/index.js +++ b/index.js @@ -20,6 +20,8 @@ let Access, Accessory, Service, Characteristic, AdaptiveLightingController, UUID const fs = require('fs'); const inherits = require('util').inherits; const myLogger = require('./lib/myLogger').myLogger; +const express = require('express'); + const debug = {}; debug.DEBUG = 100; debug.INFO = 200; @@ -88,7 +90,17 @@ function JeedomPlatform(logger, config, api) { } else { this.log('info',"Adresse Jeedom bien configurée :"+config.url); } + + this.app = express(); + this.app.get('/config', this.ConfigCMD.bind(this)); + this.app.use((err, req, res, _next) => { + res.type('json'); + console.log('error',err); + res.json({'result':'ko','msg':err}); + }); + this.DEV_DEBUG = DEV_DEBUG; // for passing by + this.USE_QUEUES = config.USE_QUEUES || 1; // 0 = NO, or 1 or 2 etc for the concurrent tasks this.jeedomClient = require('./lib/jeedom-api').createClient(config.url, config.apikey, this, config.myPlugin); this.rooms = {}; this.updateSubscriptions = []; @@ -107,9 +119,16 @@ function JeedomPlatform(logger, config, api) { } if (api) { this.api = api; - this.api.on('didFinishLaunching',function(){ + this.api.on('didFinishLaunching',() => { + /** Listen **/ + let port=0; + if(fs.existsSync('/homebridge/')) { port=8582; } // if docker, use the port next to homebridge-config-ui + this.server = this.app.listen(port, '0.0.0.0', () => { + this.log('info',"On écoute les messages sur le port "+this.server.address().port); + this.jeedomClient.daemonIsReady(this.server.address().port); + }); this.addAccessories(); - }.bind(this)); + }); } } catch (e) { @@ -118,45 +137,84 @@ function JeedomPlatform(logger, config, api) { } } +JeedomPlatform.prototype.ConfigCMD = function(req, res) { + res.type('json'); + res.status(202); + + this.log('info','Recu une configuration de jeedom :'+JSON.stringify(req.query)); + + if ('setting' in req.query === false) { + const error="Pour faire une config, le démon a besoin de son nom"; + this.log('error',error); + res.json({'result':'ko','msg':error}); + return; + } + if ('value' in req.query === false) { + const error="Pour faire une config, le démon a besoin d'une valeur a configurer"; + this.log('error',error); + res.json({'result':'ko','msg':error}); + return; + } + + switch(req.query.setting) { + case 'sendLoglevel': + this.debugLevel = req.query.value; + this.log.changeLevel(this.debugLevel); + break; + case 'changeUSE_QUEUES': + this.USE_QUEUES=parseInt(req.query.value); + this.jeedomClient.changeQueueSys(this.USE_QUEUES); + break; + default: { + const error = "Configuration inexistante"; + this.log('error','ERROR CONFIG: ' + req.query.setting + ' : '+error); + res.json({'result':'ko','msg':error}); + return; + } + } + this.log('conf',"Configuration de : "+req.query.setting+" effectuée avec la valeur : "+((typeof req.query.value == "object")?JSON.stringify(req.query.value):req.query.value)); + res.json({'result':'ok','value':req.query.value}); +}; + + // -- addAccessories // -- Desc : Accessories creation, we get a full model from jeedom and put it in local cache // -- Return : nothing JeedomPlatform.prototype.addAccessories = function() { try{ - const that = this; - that.log('Synchronisation Jeedom <> Homebridge...'); - that.jeedomClient.getModel() - .then(function(model){ // we got the base Model from the API + this.log('Synchronisation Jeedom <> Homebridge...'); + this.jeedomClient.getModel() + .then((model) => { // we got the base Model from the API if(model && typeof model === 'object' && model.config && typeof model.config === 'object' && model.config.datetime) { - that.lastPoll=model.config.datetime; + this.lastPoll=model.config.datetime; - that.log('debug','Enumération des objets Jeedom (Pièces)...'); + this.log('debug','Enumération des objets Jeedom (Pièces)...'); if(model.objects && typeof model.objects === 'object' && Object.keys(model.objects).length !== 0) { - model.objects.map(function(r){ - that.rooms[r.id] = r.name; - that.log('debug','Pièce > ' + r.name); + model.objects.map((r) => { + this.rooms[r.id] = r.name; + this.log('debug','Pièce > ' + r.name); }); } else { - that.log('error','Pièce > '+model.objects); - throw new Error('Rooms list empty or invalid'); + this.log('error','Pièce > '+model.objects); + throw new Error("Liste des pièces vide ou invalide, vérifiez que vous avez bien coché au moins une pièce à envoyer à homebridge !"); } - that.log('Enumération des scénarios Jeedom...'); - that.JeedomScenarios2HomeKitAccessories(model.scenarios); + this.log('Enumération des scénarios Jeedom...'); + this.JeedomScenarios2HomeKitAccessories(model.scenarios); - that.log('Enumération des périphériques Jeedom...'); + this.log('Enumération des périphériques Jeedom...'); if(model.eqLogics && typeof model.eqLogics === 'object' && Object.keys(model.eqLogics).length !== 0) { - that.JeedomDevices2HomeKitAccessories(model.eqLogics); + this.JeedomDevices2HomeKitAccessories(model.eqLogics); } else { - that.log('error','Périf > '+model.eqLogics); + this.log('error','Périf > '+model.eqLogics); throw new Error('eqLogics list empty'); } } else { - that.log('error','Model invalide > ',model); + this.log('error','Model invalide > ',model); throw new Error('Invalid Model'); } - }).catch(function(err) { - that.log('error','#2 Erreur de récupération des données Jeedom: ' , err); + }).catch((err) => { + this.log('error','#2 Erreur de récupération des données Jeedom: ' , err); if(err && err.stack) { console.error(err.stack); } }); } @@ -168,28 +226,22 @@ JeedomPlatform.prototype.addAccessories = function() { JeedomPlatform.prototype.JeedomScenarios2HomeKitAccessories = function(scenarios) { try{ - const that = this; + if (scenarios) { - scenarios.sort(function compare(a, b) { + scenarios.sort((a, b) => { // reorder by room name asc and name asc - const aC = that.rooms[a.object_id]+a.name; - const bC = that.rooms[b.object_id]+b.name; - if (aC > bC) { - return 1; - } - if (aC < bC) { - return -1; - } - return 0; + const aC = this.rooms[a.object_id] + a.name; + const bC = this.rooms[b.object_id] + b.name; + return aC.localeCompare(bC); }); - scenarios.map(function(scenario) { + scenarios.map((scenario) => { if (scenario.isActive == '1' && scenario.object_id != null && scenario.sendToHomebridge == '1') { - that.log('debug','Scenario > '+JSON.stringify(scenario).replace("\n",'')); - that.log('┌──── ' + that.rooms[scenario.object_id] + ' > ' +scenario.name+' ('+scenario.id+')'); + this.log('debug','Scenario > '+JSON.stringify(scenario).replace("\n",'')); + this.log('┌──── ' + this.rooms[scenario.object_id] + ' > ' +scenario.name+' ('+scenario.id+')'); const HBservice = { @@ -208,11 +260,11 @@ JeedomPlatform.prototype.JeedomScenarios2HomeKitAccessories = function(scenarios Serv.subtype = Serv.subtype || ''; Serv.subtype = scenario.id + '-' + Serv.subtype; - if(that.fakegato && !scenario.hasLogging) { + if(this.fakegato && !scenario.hasLogging) { // HBservice.characteristics.push(Characteristic.Sensitivity,Characteristic.Duration,Characteristic.LastActivation); // eqLogic.loggingService = {type:"motion", options:{storage:'googleDrive',folder:'fakegato',keyPath:'/home/pi/.homebridge/'},subtype:Serv.eqID+'-history',cmd_id:Serv.eqID}; - scenario.loggingService = {type:"switch", options:{storage:'fs',path:that.pathHomebridgeConf},subtype:Serv.eqID+'-history',cmd_id:Serv.eqID}; + scenario.loggingService = {type:"switch", options:{storage:'fs',path:this.pathHomebridgeConf},subtype:Serv.eqID+'-history',cmd_id:Serv.eqID}; scenario.hasLogging=true; } @@ -220,29 +272,29 @@ JeedomPlatform.prototype.JeedomScenarios2HomeKitAccessories = function(scenarios scenario.eqType_name = "Scenario"; scenario.logicalId = ""; - const createdAccessory = that.createAccessory([HBservice], scenario); - that.addAccessory(createdAccessory); - that.log('└─────────'); + const createdAccessory = this.createAccessory([HBservice], scenario); + this.addAccessory(createdAccessory); + this.log('└─────────'); } else { - that.log('debug','Scenario > '+JSON.stringify(scenario).replace("\n",'')); - that.log('┌──── ' + that.rooms[scenario.object_id] + ' > ' +scenario.name+' ('+scenario.id+')'); + this.log('debug','Scenario > '+JSON.stringify(scenario).replace("\n",'')); + this.log('┌──── ' + this.rooms[scenario.object_id] + ' > ' +scenario.name+' ('+scenario.id+')'); var Messg= '│ Scenario '; Messg += scenario.isVisible == '1' ? 'visible' : 'invisible'; Messg += scenario.isActive == '1' ? ', activé' : ', désactivé'; Messg += scenario.object_id != null ? '' : ', pas dans une pièce'; Messg += scenario.sendToHomebridge == '1' ? '' : ', pas coché pour Homebridge'; - that.log(Messg); + this.log(Messg); scenario.eqType_name = "Scenario"; scenario.logicalId = ""; - that.delAccessory( - that.createAccessory([], scenario) // create a cached lookalike object for unregistering it + this.delAccessory( + this.createAccessory([], scenario) // create a cached lookalike object for unregistering it ); - that.log('└─────────'); + this.log('└─────────'); } }); @@ -262,49 +314,42 @@ JeedomPlatform.prototype.JeedomScenarios2HomeKitAccessories = function(scenarios // -- Return : nothing JeedomPlatform.prototype.JeedomDevices2HomeKitAccessories = function(devices) { try{ - const that = this; if (devices) { - devices.sort(function compare(a, b) { + devices.sort((a, b) => { // reorder by room name asc and name asc - const aC = that.rooms[a.object_id]+a.name; - const bC = that.rooms[b.object_id]+b.name; - if (aC > bC) { - return 1; - } - if (aC < bC) { - return -1; - } - return 0; + const aC = this.rooms[a.object_id] + a.name; + const bC = this.rooms[b.object_id] + b.name; + return aC.localeCompare(bC); }); - devices.map(function(device) { + devices.map((device) => { if (// device.isVisible == '1' && device.isEnable == '1' && device.object_id != null && device.sendToHomebridge != '0') { - that.AccessoireCreateHomebridge( - that.jeedomClient.ParseGenericType( + this.AccessoireCreateHomebridge( + this.jeedomClient.ParseGenericType( device, - that.jeedomClient.getDeviceCmdFromCache(device.id) + this.jeedomClient.getDeviceCmdFromCache(device.id) ) ); } else { - that.log('debug','eqLogic > '+JSON.stringify(device).replace("\n",'')); - that.log('┌──── ' + that.rooms[device.object_id] + ' > ' +device.name+((device.pseudo)?' > pseudo: '+device.pseudo:'')+' ('+device.id+')'); + this.log('debug','eqLogic > '+JSON.stringify(device).replace("\n",'')); + this.log('┌──── ' + this.rooms[device.object_id] + ' > ' +device.name+((device.pseudo)?' > pseudo: '+device.pseudo:'')+' ('+device.id+')'); var Messg= '│ Accessoire '; Messg += device.isVisible == '1' ? 'visible' : 'invisible'; Messg += device.isEnable == '1' ? ', activé' : ', désactivé'; Messg += device.object_id != null ? '' : ', pas dans une pièce'; Messg += device.sendToHomebridge != '0' ? '' : ', pas coché pour Homebridge'; - that.log(Messg); + this.log(Messg); - that.delAccessory( - that.createAccessory([], device) // create a cached lookalike object for unregistering it + this.delAccessory( + this.createAccessory([], device) // create a cached lookalike object for unregistering it ); - that.log('└─────────'); + this.log('└─────────'); } }); @@ -312,38 +357,38 @@ JeedomPlatform.prototype.JeedomDevices2HomeKitAccessories = function(devices) { var countA=0; if(!hasError) { - that.log('┌────RAMASSE-MIETTES─────'); - that.log('│ (Suppression des accessoires qui sont dans le cache mais plus dans jeedom (peut provenir de renommage ou changement de pièce))'); + this.log('┌────RAMASSE-MIETTES─────'); + this.log('│ (Suppression des accessoires qui sont dans le cache mais plus dans jeedom (peut provenir de renommage ou changement de pièce))'); var hasDeleted = false; - for (const a in that.accessories) + for (const a in this.accessories) { - if (that.accessories.hasOwnProperty(a)) { - if(!that.accessories[a].reviewed && - that.accessories[a].displayName) { - that.log('│ ┌──── Trouvé: '+that.accessories[a].displayName); - that.delAccessory(that.accessories[a],true); - that.log('│ │ Supprimé du cache !'); - that.log('│ └─────────'); + if (this.accessories.hasOwnProperty(a)) { + if(!this.accessories[a].reviewed && + this.accessories[a].displayName) { + this.log('│ ┌──── Trouvé: '+this.accessories[a].displayName); + this.delAccessory(this.accessories[a],true); + this.log('│ │ Supprimé du cache !'); + this.log('│ └─────────'); hasDeleted=true; - }else if(that.accessories[a].reviewed && - that.accessories[a].displayName) {countA++;} + }else if(this.accessories[a].reviewed && + this.accessories[a].displayName) {countA++;} } } - if(!hasDeleted) {that.log('│ Rien à supprimer');} - that.log('└────────────────────────'); + if(!hasDeleted) {this.log('│ Rien à supprimer');} + this.log('└────────────────────────'); } else { - that.log('error','!!! ERREUR DETECTÉE, ON QUITTE HOMEBRIDGE !!!'); + this.log('error','!!! ERREUR DETECTÉE, ON QUITTE HOMEBRIDGE !!!'); process.exit(1); } - const endLog = '--== Homebridge est démarré et a intégré '+countA+' accessoire'+ (countA>1 ? 's' : '') +' ! (Si vous avez un Warning Avahi, ne pas en tenir compte) ==--'; - that.log(endLog); - if(countA >= 150) {that.log('error','!!! ATTENTION !!! Vous avez '+countA+' accessoires + Jeedom et HomeKit en supporte 150 max au total !!');} - else if(countA >= 140) {that.log('warn','!! Avertissement, vous avez '+countA+' accessoires + Jeedom et HomeKit en supporte 150 max au total !!');} + const endLog = '--== Homebridge est démarré et a intégré '+countA+' accessoire'+ (countA>1 ? 's' : '') +' ! ==--'; + this.log(endLog); + if(countA >= 150) {this.log('error','!!! ATTENTION !!! Vous avez '+countA+' accessoires + Jeedom et HomeKit en supporte 150 max au total !!');} + else if(countA >= 140) {this.log('warn','!! Avertissement, vous avez '+countA+' accessoires + Jeedom et HomeKit en supporte 150 max au total !!');} - that.log('debug','==START POLLING=='); - that.startPollingUpdate(); + this.log('debug','==START POLLING=='); + this.startPollingUpdate(); } catch(e){ this.log('error','Erreur de la fonction JeedomDevices2HomeKitAccessories :',e); @@ -359,280 +404,278 @@ JeedomPlatform.prototype.JeedomDevices2HomeKitAccessories = function(devices) { JeedomPlatform.prototype.AccessoireCreateHomebridge = function(eqLogic) { var createdAccessory; try { - const that = this; var HBservices = []; var HBservice = null; const eqServicesCopy = eqLogic.services; - that.log('debug','eqLogic > '+JSON.stringify(eqLogic).replace("\n",'')); - that.log('┌──── ' + that.rooms[eqLogic.object_id] + ' > ' + eqLogic.name +((eqLogic.pseudo)?' > pseudo: '+eqLogic.pseudo:'')+ ' (' + eqLogic.id + ')'); + this.log('debug','eqLogic > '+JSON.stringify(eqLogic).replace("\n",'')); + this.log('┌──── ' + this.rooms[eqLogic.object_id] + ' > ' + eqLogic.name +((eqLogic.pseudo)?' > pseudo: '+eqLogic.pseudo:'')+ ' (' + eqLogic.id + ')'); eqLogic.origName=eqLogic.name; if(eqLogic.pseudo) { eqLogic.name = eqLogic.pseudo; } if (eqLogic.services.light) { - eqLogic.services.light.forEach(function(cmd) { - if (cmd.state) { - let LightType="Switch"; - HBservice = { - controlService : new Service.Lightbulb(eqLogic.name), - characteristics : [Characteristic.On], + eqLogic.services.light.forEach((cmd) => { + if (!cmd.state) {return;} + let LightType="Switch"; + HBservice = { + controlService : new Service.Lightbulb(eqLogic.name), + characteristics : [Characteristic.On], + }; + const Serv = HBservice.controlService; + Serv.eqLogic=eqLogic; + Serv.actions={}; + Serv.infos={}; + Serv.infos.state=cmd.state; + if(eqLogic.OnAfterBrightness) {Serv.OnAfterBrightness=true;} + if(eqLogic.ignoreOnCommandOnBrightnessChange) {Serv.ignoreOnCommandOnBrightnessChange=true;} + + eqServicesCopy.light.forEach((cmd2) => { + if (cmd2.on) { + Serv.actions.on=cmd2.on; + } else if (cmd2.off) { + Serv.actions.off=cmd2.off; + } else if (cmd2.slider) { + Serv.actions.slider=cmd2.slider; + } else if (cmd2.setcolor) { + Serv.actions.setcolor=cmd2.setcolor; + } else if (cmd2.setcolor_temp) { + Serv.actions.setcolor_temp=cmd2.setcolor_temp; + } else if (cmd2.color) { + Serv.infos.color=cmd2.color; + } else if (cmd2.color_temp) { + Serv.infos.color_temp=cmd2.color_temp; + } else if (cmd2.state_bool) { + Serv.infos.state_bool=cmd2.state_bool; + } else if (cmd2.brightness) { + Serv.infos.brightness=cmd2.brightness; + } + }); + if (Serv.actions.on && !Serv.actions.off) {this.log('warn','Pas de type générique "Action/Lumière OFF"');} + if (!Serv.actions.on && Serv.actions.off) {this.log('warn','Pas de type générique "Action/Lumière ON"');} + if (!Serv.actions.on && !Serv.actions.off) {this.log('warn','Pas de type générique "Action/Lumière ON" et "Action/Lumière OFF"');} + if (Serv.infos.color && !Serv.actions.setcolor) {this.log('warn','Pas de type générique "Action/Lumière Couleur"');} + if (!Serv.infos.color && Serv.actions.setcolor) {this.log('warn','Pas de type générique "Info/Lumière Couleur"');} + if (Serv.infos.color_temp && !Serv.actions.setcolor_temp) {this.log('warn','Pas de type générique "Action/Lumière Température Couleur"');} + if (!Serv.infos.color_temp && Serv.actions.setcolor_temp) {this.log('warn','Pas de type générique "Info/Lumière Température Couleur"');} + + if(Serv.actions.slider) { + if(Serv.actions.slider.configuration && Serv.actions.slider.configuration.maxValue && parseInt(Serv.actions.slider.configuration.maxValue)) { + Serv.maxBright = parseInt(Serv.actions.slider.configuration.maxValue); + } else { + Serv.maxBright = 100; // if not set in Jeedom it's 100 + } + LightType += '_Slider,'+Serv.maxBright; + HBservice.characteristics.push(Characteristic.Brightness); + Serv.addCharacteristic(Characteristic.Brightness); + } else { + this.log('info','La lumière n\'a pas de variateur'); + } + if(Serv.infos.color) { + LightType += "_RGB"; + HBservice.characteristics.push(Characteristic.Hue); + Serv.addCharacteristic(Characteristic.Hue); + HBservice.characteristics.push(Characteristic.Saturation); + Serv.addCharacteristic(Characteristic.Saturation); + Serv.HSBValue = { + hue : 0, + saturation : 0, + brightness : 0, }; - const Serv = HBservice.controlService; - Serv.eqLogic=eqLogic; - Serv.actions={}; - Serv.infos={}; - Serv.infos.state=cmd.state; - if(eqLogic.OnAfterBrightness) {Serv.OnAfterBrightness=true;} - if(eqLogic.ignoreOnCommandOnBrightnessChange) {Serv.ignoreOnCommandOnBrightnessChange=true;} - - eqServicesCopy.light.forEach(function(cmd2) { - if (cmd2.on) { - Serv.actions.on=cmd2.on; - } else if (cmd2.off) { - Serv.actions.off=cmd2.off; - } else if (cmd2.slider) { - Serv.actions.slider=cmd2.slider; - } else if (cmd2.setcolor) { - Serv.actions.setcolor=cmd2.setcolor; - } else if (cmd2.setcolor_temp) { - Serv.actions.setcolor_temp=cmd2.setcolor_temp; - } else if (cmd2.color) { - Serv.infos.color=cmd2.color; - } else if (cmd2.color_temp) { - Serv.infos.color_temp=cmd2.color_temp; - } else if (cmd2.state_bool) { - Serv.infos.state_bool=cmd2.state_bool; - } else if (cmd2.brightness) { - Serv.infos.brightness=cmd2.brightness; - } - }); - if (Serv.actions.on && !Serv.actions.off) {that.log('warn','Pas de type générique "Action/Lumière OFF"');} - if (!Serv.actions.on && Serv.actions.off) {that.log('warn','Pas de type générique "Action/Lumière ON"');} - if (!Serv.actions.on && !Serv.actions.off) {that.log('warn','Pas de type générique "Action/Lumière ON" et "Action/Lumière OFF"');} - if (Serv.infos.color && !Serv.actions.setcolor) {that.log('warn','Pas de type générique "Action/Lumière Couleur"');} - if (!Serv.infos.color && Serv.actions.setcolor) {that.log('warn','Pas de type générique "Info/Lumière Couleur"');} - if (Serv.infos.color_temp && !Serv.actions.setcolor_temp) {that.log('warn','Pas de type générique "Action/Lumière Température Couleur"');} - if (!Serv.infos.color_temp && Serv.actions.setcolor_temp) {that.log('warn','Pas de type générique "Info/Lumière Température Couleur"');} + Serv.RGBValue = { + red : 0, + green : 0, + blue : 0, + }; + // Serv.countColorCharacteristics = 0; + Serv.timeoutIdColorCharacteristics = 0; + } + if(Serv.infos.color_temp) { + LightType += "_Temp"; + const props = {}; - if(Serv.actions.slider) { - if(Serv.actions.slider.configuration && Serv.actions.slider.configuration.maxValue && parseInt(Serv.actions.slider.configuration.maxValue)) { - Serv.maxBright = parseInt(Serv.actions.slider.configuration.maxValue); - } else { - Serv.maxBright = 100; // if not set in Jeedom it's 100 + if(Serv.actions.setcolor_temp && Serv.actions.setcolor_temp.configuration && Serv.actions.setcolor_temp.configuration.maxValue && Serv.actions.setcolor_temp.configuration.minValue && parseInt(Serv.actions.setcolor_temp.configuration.maxValue) && parseInt(Serv.actions.setcolor_temp.configuration.minValue)) { + if(parseInt(Serv.actions.setcolor_temp.configuration.maxValue) > 500 && parseInt(Serv.actions.setcolor_temp.configuration.minValue) > 500) { // Kelvin + // convert to Mired (and take the max value to the min) + props.minValue = parseInt(1000000/Serv.actions.setcolor_temp.configuration.maxValue); + props.maxValue = parseInt(1000000/Serv.actions.setcolor_temp.configuration.minValue); + Serv.colorTempType="kelvin"; + LightType+=Serv.colorTempType; + } else { // already mired + props.minValue = parseInt(Serv.actions.setcolor_temp.configuration.minValue); + props.maxValue = parseInt(Serv.actions.setcolor_temp.configuration.maxValue); + Serv.colorTempType="mired"; + LightType+=Serv.colorTempType; } - LightType += '_Slider,'+Serv.maxBright; - HBservice.characteristics.push(Characteristic.Brightness); - Serv.addCharacteristic(Characteristic.Brightness); } else { - that.log('info','La lumière n\'a pas de variateur'); - } - if(Serv.infos.color) { - LightType += "_RGB"; - HBservice.characteristics.push(Characteristic.Hue); - Serv.addCharacteristic(Characteristic.Hue); - HBservice.characteristics.push(Characteristic.Saturation); - Serv.addCharacteristic(Characteristic.Saturation); - Serv.HSBValue = { - hue : 0, - saturation : 0, - brightness : 0, - }; - Serv.RGBValue = { - red : 0, - green : 0, - blue : 0, - }; - // Serv.countColorCharacteristics = 0; - Serv.timeoutIdColorCharacteristics = 0; - } - if(Serv.infos.color_temp) { - LightType += "_Temp"; - const props = {}; - - if(Serv.actions.setcolor_temp && Serv.actions.setcolor_temp.configuration && Serv.actions.setcolor_temp.configuration.maxValue && Serv.actions.setcolor_temp.configuration.minValue && parseInt(Serv.actions.setcolor_temp.configuration.maxValue) && parseInt(Serv.actions.setcolor_temp.configuration.minValue)) { - if(parseInt(Serv.actions.setcolor_temp.configuration.maxValue) > 500 && parseInt(Serv.actions.setcolor_temp.configuration.minValue) > 500) { // Kelvin - // convert to Mired (and take the max value to the min) - props.minValue = parseInt(1000000/Serv.actions.setcolor_temp.configuration.maxValue); - props.maxValue = parseInt(1000000/Serv.actions.setcolor_temp.configuration.minValue); - Serv.colorTempType="kelvin"; - LightType+=Serv.colorTempType; - } else { // already mired - props.minValue = parseInt(Serv.actions.setcolor_temp.configuration.minValue); - props.maxValue = parseInt(Serv.actions.setcolor_temp.configuration.maxValue); - Serv.colorTempType="mired"; - LightType+=Serv.colorTempType; - } - } else { - that.log('error','"Action/Lumière Température Couleur" doit avoir un minimum et un maximum !'); - props.minValue = 0; // if not set in Jeedom it's 0 - props.maxValue = 20000; // if not set in Jeedom it's 100 - } - const unite = Serv.infos.color_temp.unite ? Serv.infos.color_temp.unite : ''; - if(unite) {props.unit=unite;} - HBservice.characteristics.push(Characteristic.ColorTemperature); - Serv.addCharacteristic(Characteristic.ColorTemperature); - Serv.getCharacteristic(Characteristic.ColorTemperature).setProps(props); + this.log('error','"Action/Lumière Température Couleur" doit avoir un minimum et un maximum !'); + props.minValue = 0; // if not set in Jeedom it's 0 + props.maxValue = 20000; // if not set in Jeedom it's 100 } + const unite = Serv.infos.color_temp.unite ? Serv.infos.color_temp.unite : ''; + if(unite) {props.unit=unite;} + HBservice.characteristics.push(Characteristic.ColorTemperature); + Serv.addCharacteristic(Characteristic.ColorTemperature); + Serv.getCharacteristic(Characteristic.ColorTemperature).setProps(props); + } - if(eqLogic.hasAdaptive) { - if (that.adaptiveLightingSupport()) { - LightType+='_Adaptive'; - } else { - eqLogic.hasAdaptive=false; - } + if(eqLogic.hasAdaptive) { + if (this.adaptiveLightingSupport()) { + LightType+='_Adaptive'; + } else { + eqLogic.hasAdaptive=false; } - - // add Active, Tampered and Defect Characteristics if needed - HBservice=that.createStatusCharact(HBservice,eqServicesCopy); - - that.log('info','La lumière est du type :',LightType); - Serv.LightType = LightType; - Serv.cmd_id = cmd.state.id; - Serv.eqID = eqLogic.id; - Serv.subtype = Serv.subtype || ''; - Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; - HBservices.push(HBservice); } + + // add Active, Tampered and Defect Characteristics if needed + HBservice=this.createStatusCharact(HBservice,eqServicesCopy); + + this.log('info','La lumière est du type :',LightType); + Serv.LightType = LightType; + Serv.cmd_id = cmd.state.id; + Serv.eqID = eqLogic.id; + Serv.subtype = Serv.subtype || ''; + Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; + HBservices.push(HBservice); }); if(!HBservice) { - that.log('warn','Pas de type générique "Info/Lumière Etat"'); + this.log('warn','Pas de type générique "Info/Lumière Etat"'); } else { HBservice = null; } } if (eqLogic.services.flap) { - eqLogic.services.flap.forEach(function(cmd) { - if (cmd.state || cmd.stateClosing) { - HBservice = { - controlService : new Service.WindowCovering(eqLogic.name), - characteristics : [Characteristic.CurrentPosition, Characteristic.TargetPosition, Characteristic.PositionState], - }; - const Serv = HBservice.controlService; - Serv.eqLogic=eqLogic; - Serv.actions={}; - Serv.infos={}; - if(cmd.stateClosing) { - Serv.infos.state=cmd.stateClosing; - if(Serv.infos.state.subType == 'binary') { - if(Serv.infos.state.display && Serv.infos.state.display.invertBinary) { - Serv.FlapType="Opening"; - } else { - Serv.FlapType="Closing"; - } + eqLogic.services.flap.forEach((cmd) => { + if (!cmd.state && !cmd.stateClosing) {return;} + HBservice = { + controlService : new Service.WindowCovering(eqLogic.name), + characteristics : [Characteristic.CurrentPosition, Characteristic.TargetPosition, Characteristic.PositionState], + }; + const Serv = HBservice.controlService; + Serv.eqLogic=eqLogic; + Serv.actions={}; + Serv.infos={}; + + if(cmd.stateClosing) { + Serv.infos.state=cmd.stateClosing; + if(Serv.infos.state.subType == 'binary') { + if(Serv.infos.state.display && Serv.infos.state.display.invertBinary) { + Serv.FlapType="Opening"; } else { Serv.FlapType="Closing"; } - } else if(cmd.state) { - Serv.infos.state=cmd.state; - if(Serv.infos.state.subType == 'binary') { - if(Serv.infos.state.display && Serv.infos.state.display.invertBinary) { - Serv.FlapType="Closing"; - } else { - Serv.FlapType="Opening"; - } + } else { + Serv.FlapType="Closing"; + } + } else if(cmd.state) { + Serv.infos.state=cmd.state; + if(Serv.infos.state.subType == 'binary') { + if(Serv.infos.state.display && Serv.infos.state.display.invertBinary) { + Serv.FlapType="Closing"; } else { Serv.FlapType="Opening"; } - } - - eqServicesCopy.flap.forEach(function(cmd2) { - if (cmd2.up) { - Serv.actions.up = cmd2.up; - } else if (cmd2.down) { - Serv.actions.down = cmd2.down; - } else if (cmd2.slider) { - Serv.actions.slider = cmd2.slider; - } else if (cmd2.HorTiltSlider) { - Serv.actions.HorTiltSlider = cmd2.HorTiltSlider; - } else if (cmd2.VerTiltSlider) { - Serv.actions.VerTiltSlider = cmd2.VerTiltSlider; - } else if (cmd2.HorTiltState) { - Serv.infos.HorTiltState = cmd2.HorTiltState; - } else if (cmd2.VerTiltState) { - Serv.infos.VerTiltState = cmd2.VerTiltState; - } - }); - if(Serv.actions.up && !Serv.actions.down) {that.log('warn','Pas de type générique "Action/Volet Bouton Descendre"');} - if(!Serv.actions.up && Serv.actions.down) {that.log('warn','Pas de type générique "Action/Volet Bouton Monter"');} - if(!Serv.actions.up && !Serv.actions.down) {that.log('warn','Pas de type générique "Action/Volet Bouton Descendre" et "Action/Volet Bouton Monter"');} - if(!Serv.actions.up && !Serv.actions.down && !Serv.actions.slider) {that.log('warn','Pas de type générique "Action/Volet Bouton Slider" et "Action/Volet Bouton Monter" et "Action/Volet Bouton Descendre"');} - if(Serv.actions.HorTiltSlider && !Serv.infos.HorTiltState) {that.log('warn','Pas de type générique "Info/Volet Etat Inclinaison Horizontale" malgré l\'action "Action/Volet Slider Inclinaison Horizontale"');} - if(Serv.actions.VerTiltSlider && !Serv.infos.VerTiltState) {that.log('warn','Pas de type générique "Info/Volet Etat Inclinaison Verticale" malgré l\'action "Action/Volet Slider Inclinaison Verticale"');} - if(!Serv.actions.HorTiltSlider && Serv.infos.HorTiltState) {that.log('warn','Pas de type générique "Action/Volet Slider Inclinaison Horizontale" malgré l\'état "Info/Volet Etat Inclinaison Horizontale"');} - if(!Serv.actions.VerTiltSlider && Serv.infos.VerTiltState) {that.log('warn','Pas de type générique "Action/Volet Slider Inclinaison Verticale" malgré l\'état "Info/Volet Etat Inclinaison Verticale"');} - Serv.minValue=0; - if(Serv.infos.state.subType == 'binary') { - Serv.maxValue=1; - Serv.getCharacteristic(Characteristic.TargetPosition).setProps({minStep:100}); } else { - Serv.maxValue=100; + Serv.FlapType="Opening"; + } + } + + eqServicesCopy.flap.forEach((cmd2) => { + if (cmd2.up) { + Serv.actions.up = cmd2.up; + } else if (cmd2.down) { + Serv.actions.down = cmd2.down; + } else if (cmd2.slider) { + Serv.actions.slider = cmd2.slider; + } else if (cmd2.HorTiltSlider) { + Serv.actions.HorTiltSlider = cmd2.HorTiltSlider; + } else if (cmd2.VerTiltSlider) { + Serv.actions.VerTiltSlider = cmd2.VerTiltSlider; + } else if (cmd2.HorTiltState) { + Serv.infos.HorTiltState = cmd2.HorTiltState; + } else if (cmd2.VerTiltState) { + Serv.infos.VerTiltState = cmd2.VerTiltState; } - if(Serv.actions.slider) { - if(Serv.actions.slider.configuration && Serv.actions.slider.configuration.maxValue && parseInt(Serv.actions.slider.configuration.maxValue)) { - Serv.maxValue = parseInt(Serv.actions.slider.configuration.maxValue); - } - if(Serv.actions.slider.configuration && Serv.actions.slider.configuration.minValue && parseInt(Serv.actions.slider.configuration.minValue)) { - Serv.minValue = parseInt(Serv.actions.slider.configuration.minValue); - } + }); + if(Serv.actions.up && !Serv.actions.down) {this.log('warn','Pas de type générique "Action/Volet Bouton Descendre"');} + if(!Serv.actions.up && Serv.actions.down) {this.log('warn','Pas de type générique "Action/Volet Bouton Monter"');} + if(!Serv.actions.up && !Serv.actions.down) {this.log('warn','Pas de type générique "Action/Volet Bouton Descendre" et "Action/Volet Bouton Monter"');} + if(!Serv.actions.up && !Serv.actions.down && !Serv.actions.slider) {this.log('warn','Pas de type générique "Action/Volet Bouton Slider" et "Action/Volet Bouton Monter" et "Action/Volet Bouton Descendre"');} + if(Serv.actions.HorTiltSlider && !Serv.infos.HorTiltState) {this.log('warn','Pas de type générique "Info/Volet Etat Inclinaison Horizontale" malgré l\'action "Action/Volet Slider Inclinaison Horizontale"');} + if(Serv.actions.VerTiltSlider && !Serv.infos.VerTiltState) {this.log('warn','Pas de type générique "Info/Volet Etat Inclinaison Verticale" malgré l\'action "Action/Volet Slider Inclinaison Verticale"');} + if(!Serv.actions.HorTiltSlider && Serv.infos.HorTiltState) {this.log('warn','Pas de type générique "Action/Volet Slider Inclinaison Horizontale" malgré l\'état "Info/Volet Etat Inclinaison Horizontale"');} + if(!Serv.actions.VerTiltSlider && Serv.infos.VerTiltState) {this.log('warn','Pas de type générique "Action/Volet Slider Inclinaison Verticale" malgré l\'état "Info/Volet Etat Inclinaison Verticale"');} + Serv.minValue=0; + if(Serv.infos.state.subType == 'binary') { + Serv.maxValue=1; + // Serv.getCharacteristic(Characteristic.TargetPosition).setProps({minStep:1}); + } else { + Serv.maxValue=100; + } + if(Serv.actions.slider) { + if(Serv.actions.slider.configuration && Serv.actions.slider.configuration.maxValue && parseInt(Serv.actions.slider.configuration.maxValue)) { + Serv.maxValue = parseInt(Serv.actions.slider.configuration.maxValue); } - if(Serv.actions.HorTiltSlider) { - const props = {}; - if(Serv.actions.HorTiltSlider.configuration && Serv.actions.HorTiltSlider.configuration.maxValue && parseInt(Serv.actions.HorTiltSlider.configuration.maxValue)) { - props.maxValue = parseInt(Serv.actions.HorTiltSlider.configuration.maxValue); - } else { - props.maxValue = 90; - } - if(Serv.actions.HorTiltSlider.configuration && Serv.actions.HorTiltSlider.configuration.minValue && parseInt(Serv.actions.HorTiltSlider.configuration.minValue)) { - props.minValue = parseInt(Serv.actions.HorTiltSlider.configuration.minValue); - } else { - props.minValue = 0; - } - HBservice.characteristics.push(Characteristic.CurrentHorizontalTiltAngle); - Serv.addCharacteristic(Characteristic.CurrentHorizontalTiltAngle); - Serv.getCharacteristic(Characteristic.CurrentHorizontalTiltAngle).setProps(props); - - HBservice.characteristics.push(Characteristic.TargetHorizontalTiltAngle); - Serv.addCharacteristic(Characteristic.TargetHorizontalTiltAngle); - Serv.getCharacteristic(Characteristic.TargetHorizontalTiltAngle).setProps(props); - that.log('debug','Horizontal Slider props :'+JSON.stringify(props)+'/'+JSON.stringify(Serv.actions.HorTiltSlider.configuration)); + if(Serv.actions.slider.configuration && Serv.actions.slider.configuration.minValue && parseInt(Serv.actions.slider.configuration.minValue)) { + Serv.minValue = parseInt(Serv.actions.slider.configuration.minValue); } - - if(Serv.actions.VerTiltSlider) { - const props = {}; - if(Serv.actions.VerTiltSlider.configuration && Serv.actions.VerTiltSlider.configuration.maxValue && parseInt(Serv.actions.VerTiltSlider.configuration.maxValue)) { - props.maxValue = parseInt(Serv.actions.VerTiltSlider.configuration.maxValue); - } else { - props.maxValue = 90; - } - if(Serv.actions.VerTiltSlider.configuration && Serv.actions.VerTiltSlider.configuration.minValue && parseInt(Serv.actions.VerTiltSlider.configuration.minValue)) { - props.minValue = parseInt(Serv.actions.VerTiltSlider.configuration.minValue); - } else { - props.minValue = 0; - } - HBservice.characteristics.push(Characteristic.CurrentVerticalTiltAngle); - Serv.addCharacteristic(Characteristic.CurrentVerticalTiltAngle); - Serv.getCharacteristic(Characteristic.CurrentVerticalTiltAngle).setProps(props); - - HBservice.characteristics.push(Characteristic.TargetVerticalTiltAngle); - Serv.addCharacteristic(Characteristic.TargetVerticalTiltAngle); - Serv.getCharacteristic(Characteristic.TargetVerticalTiltAngle).setProps(props); - that.log('debug','Vertical Slider props :'+JSON.stringify(props)+'/'+JSON.stringify(Serv.actions.VerTiltSlider.configuration)); + } + if(Serv.actions.HorTiltSlider) { + const props = {}; + if(Serv.actions.HorTiltSlider.configuration && Serv.actions.HorTiltSlider.configuration.maxValue && parseInt(Serv.actions.HorTiltSlider.configuration.maxValue)) { + props.maxValue = parseInt(Serv.actions.HorTiltSlider.configuration.maxValue); + } else { + props.maxValue = 90; + } + if(Serv.actions.HorTiltSlider.configuration && Serv.actions.HorTiltSlider.configuration.minValue && parseInt(Serv.actions.HorTiltSlider.configuration.minValue)) { + props.minValue = parseInt(Serv.actions.HorTiltSlider.configuration.minValue); + } else { + props.minValue = 0; } + HBservice.characteristics.push(Characteristic.CurrentHorizontalTiltAngle); + Serv.addCharacteristic(Characteristic.CurrentHorizontalTiltAngle); + Serv.getCharacteristic(Characteristic.CurrentHorizontalTiltAngle).setProps(props); - // add Active, Tampered and Defect Characteristics if needed - HBservice=that.createStatusCharact(HBservice,eqServicesCopy); + HBservice.characteristics.push(Characteristic.TargetHorizontalTiltAngle); + Serv.addCharacteristic(Characteristic.TargetHorizontalTiltAngle); + Serv.getCharacteristic(Characteristic.TargetHorizontalTiltAngle).setProps(props); + this.log('debug','Horizontal Slider props :'+JSON.stringify(props)+'/'+JSON.stringify(Serv.actions.HorTiltSlider.configuration)); + } + + if(Serv.actions.VerTiltSlider) { + const props = {}; + if(Serv.actions.VerTiltSlider.configuration && Serv.actions.VerTiltSlider.configuration.maxValue && parseInt(Serv.actions.VerTiltSlider.configuration.maxValue)) { + props.maxValue = parseInt(Serv.actions.VerTiltSlider.configuration.maxValue); + } else { + props.maxValue = 90; + } + if(Serv.actions.VerTiltSlider.configuration && Serv.actions.VerTiltSlider.configuration.minValue && parseInt(Serv.actions.VerTiltSlider.configuration.minValue)) { + props.minValue = parseInt(Serv.actions.VerTiltSlider.configuration.minValue); + } else { + props.minValue = 0; + } + HBservice.characteristics.push(Characteristic.CurrentVerticalTiltAngle); + Serv.addCharacteristic(Characteristic.CurrentVerticalTiltAngle); + Serv.getCharacteristic(Characteristic.CurrentVerticalTiltAngle).setProps(props); - Serv.cmd_id = Serv.infos.state.id; - Serv.eqID = eqLogic.id; - Serv.subtype = Serv.subtype || ''; - Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; - - HBservices.push(HBservice); + HBservice.characteristics.push(Characteristic.TargetVerticalTiltAngle); + Serv.addCharacteristic(Characteristic.TargetVerticalTiltAngle); + Serv.getCharacteristic(Characteristic.TargetVerticalTiltAngle).setProps(props); + this.log('debug','Vertical Slider props :'+JSON.stringify(props)+'/'+JSON.stringify(Serv.actions.VerTiltSlider.configuration)); } + + // add Active, Tampered and Defect Characteristics if needed + HBservice=this.createStatusCharact(HBservice,eqServicesCopy); + + Serv.cmd_id = Serv.infos.state.id; + Serv.eqID = eqLogic.id; + Serv.subtype = Serv.subtype || ''; + Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; + + HBservices.push(HBservice); }); if(!HBservice) { - that.log('warn','Pas de type générique "Info/Volet Etat" ou "Info/Volet Etat Fermeture" on regarde s\'il y a uniquement les boutons...'); - eqLogic.services.flap.forEach(function(cmd) { + this.log('warn','Pas de type générique "Info/Volet Etat" ou "Info/Volet Etat Fermeture" on regarde s\'il y a uniquement les boutons...'); + eqLogic.services.flap.forEach((cmd) => { if (cmd.up) { const SwitchName=cmd.up.name; HBservice = { @@ -652,15 +695,14 @@ JeedomPlatform.prototype.AccessoireCreateHomebridge = function(eqLogic) { Serv.getCharacteristic(Characteristic.ConfiguredName).setValue(SwitchName); // add Active, Tampered and Defect Characteristics if needed - HBservice=that.createStatusCharact(HBservice,eqServicesCopy); + HBservice=this.createStatusCharact(HBservice,eqServicesCopy); Serv.cmd_id = cmd.up.id; Serv.eqID = eqLogic.id; Serv.subtype = Serv.subtype || ''; Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; HBservices.push(HBservice); - } - if (cmd.down) { + } else if (cmd.down) { const SwitchName=cmd.down.name; HBservice = { controlService : new Service.Switch(SwitchName), @@ -679,15 +721,14 @@ JeedomPlatform.prototype.AccessoireCreateHomebridge = function(eqLogic) { Serv.getCharacteristic(Characteristic.ConfiguredName).setValue(SwitchName); // add Active, Tampered and Defect Characteristics if needed - HBservice=that.createStatusCharact(HBservice,eqServicesCopy); + HBservice=this.createStatusCharact(HBservice,eqServicesCopy); Serv.cmd_id = cmd.down.id; Serv.eqID = eqLogic.id; Serv.subtype = Serv.subtype || ''; Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; HBservices.push(HBservice); - } - if (cmd.stop) { + } else if (cmd.stop) { const SwitchName=cmd.stop.name; HBservice = { controlService : new Service.Switch(SwitchName), @@ -706,7 +747,7 @@ JeedomPlatform.prototype.AccessoireCreateHomebridge = function(eqLogic) { Serv.getCharacteristic(Characteristic.ConfiguredName).setValue(SwitchName); // add Active, Tampered and Defect Characteristics if needed - HBservice=that.createStatusCharact(HBservice,eqServicesCopy); + HBservice=this.createStatusCharact(HBservice,eqServicesCopy); Serv.cmd_id = cmd.stop.id; Serv.eqID = eqLogic.id; @@ -716,7 +757,7 @@ JeedomPlatform.prototype.AccessoireCreateHomebridge = function(eqLogic) { } }); if(!HBservice) { - that.log('warn','Pas de type générique "Action/Volet Bouton Monter" ou "Action/Volet Bouton Descendre" ou "Action/Volet Bouton Stop"'); + this.log('warn','Pas de type générique "Action/Volet Bouton Monter" ou "Action/Volet Bouton Descendre" ou "Action/Volet Bouton Stop"'); } else { HBservice = null; } @@ -725,1346 +766,1316 @@ JeedomPlatform.prototype.AccessoireCreateHomebridge = function(eqLogic) { } } if (eqLogic.services.windowMoto) { - eqLogic.services.windowMoto.forEach(function(cmd) { - if (cmd.state) { - HBservice = { - controlService : new Service.Window(eqLogic.name), - characteristics : [Characteristic.CurrentPosition, Characteristic.TargetPosition, Characteristic.PositionState], - }; - const Serv = HBservice.controlService; - Serv.eqLogic=eqLogic; - Serv.actions={}; - Serv.infos={}; - Serv.infos.state=cmd.state; - - eqServicesCopy.windowMoto.forEach(function(cmd2) { - if (cmd2.up) { - Serv.actions.up = cmd2.up; - } else if (cmd2.down) { - Serv.actions.down = cmd2.down; - } else if (cmd2.slider) { - Serv.actions.slider = cmd2.slider; - } - }); - Serv.maxValue = 100; // if not set in Jeedom it's 100 - Serv.minValue = 0; // if not set in Jeedom it's 0 - if(Serv.actions.up && !Serv.actions.down) {that.log('warn','Pas de type générique "Action/Fenêtre Motorisée Descendre"');} - if(!Serv.actions.up && Serv.actions.down) {that.log('warn','Pas de type générique "Action/Fenêtre Motorisée Monter"');} - if(!Serv.actions.up && !Serv.actions.down) {that.log('warn','Pas de type générique "Action/Fenêtre Motorisée Descendre" et "Action/Fenêtre Motorisée Monter"');} - if(!Serv.actions.up && !Serv.actions.down && !Serv.actions.slider) {that.log('warn','Pas de type générique "Action/Fenêtre Motorisée Slider" et "Action/Fenêtre Motorisée Monter" et "Action/Fenêtre Motorisée Descendre"');} - if(Serv.actions.slider) { - if(Serv.actions.slider.configuration && Serv.actions.slider.configuration.maxValue && parseInt(Serv.actions.slider.configuration.maxValue)) { - Serv.maxValue = parseInt(Serv.actions.slider.configuration.maxValue); - } - if(Serv.actions.slider.configuration && Serv.actions.slider.configuration.minValue && parseInt(Serv.actions.slider.configuration.minValue)) { - Serv.minValue = parseInt(Serv.actions.slider.configuration.minValue); - } + eqLogic.services.windowMoto.forEach((cmd) => { + if (!cmd.state) {return;} + HBservice = { + controlService : new Service.Window(eqLogic.name), + characteristics : [Characteristic.CurrentPosition, Characteristic.TargetPosition, Characteristic.PositionState], + }; + const Serv = HBservice.controlService; + Serv.eqLogic=eqLogic; + Serv.actions={}; + Serv.infos={}; + Serv.infos.state=cmd.state; + + eqServicesCopy.windowMoto.forEach((cmd2) => { + if (cmd2.up) { + Serv.actions.up = cmd2.up; + } else if (cmd2.down) { + Serv.actions.down = cmd2.down; + } else if (cmd2.slider) { + Serv.actions.slider = cmd2.slider; } - // add Active, Tampered and Defect Characteristics if needed - HBservice=that.createStatusCharact(HBservice,eqServicesCopy); - - Serv.cmd_id = cmd.state.id; - Serv.eqID = eqLogic.id; - Serv.subtype = Serv.subtype || ''; - Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; + }); + Serv.maxValue = 100; // if not set in Jeedom it's 100 + Serv.minValue = 0; // if not set in Jeedom it's 0 + if(Serv.actions.up && !Serv.actions.down) {this.log('warn','Pas de type générique "Action/Fenêtre Motorisée Descendre"');} + if(!Serv.actions.up && Serv.actions.down) {this.log('warn','Pas de type générique "Action/Fenêtre Motorisée Monter"');} + if(!Serv.actions.up && !Serv.actions.down) {this.log('warn','Pas de type générique "Action/Fenêtre Motorisée Descendre" et "Action/Fenêtre Motorisée Monter"');} + if(!Serv.actions.up && !Serv.actions.down && !Serv.actions.slider) {this.log('warn','Pas de type générique "Action/Fenêtre Motorisée Slider" et "Action/Fenêtre Motorisée Monter" et "Action/Fenêtre Motorisée Descendre"');} + if(Serv.actions.slider) { + if(Serv.actions.slider.configuration && Serv.actions.slider.configuration.maxValue && parseInt(Serv.actions.slider.configuration.maxValue)) { + Serv.maxValue = parseInt(Serv.actions.slider.configuration.maxValue); + } + if(Serv.actions.slider.configuration && Serv.actions.slider.configuration.minValue && parseInt(Serv.actions.slider.configuration.minValue)) { + Serv.minValue = parseInt(Serv.actions.slider.configuration.minValue); + } + } + // add Active, Tampered and Defect Characteristics if needed + HBservice=this.createStatusCharact(HBservice,eqServicesCopy); + + Serv.cmd_id = cmd.state.id; + Serv.eqID = eqLogic.id; + Serv.subtype = Serv.subtype || ''; + Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; - HBservices.push(HBservice); - } + HBservices.push(HBservice); }); if(!HBservice) { - that.log('warn','Pas de type générique "Info/Fenêtre Motorisée Etat"'); + this.log('warn','Pas de type générique "Info/Fenêtre Motorisée Etat"'); } else { HBservice = null; } } if (eqLogic.services.energy) { - eqLogic.services.energy.forEach(function(cmd) { - if (cmd.state) { - HBservice = { - controlService : new Service.Outlet(eqLogic.name), - characteristics : [Characteristic.On, Characteristic.OutletInUse], - }; - const Serv = HBservice.controlService; - Serv.eqLogic=eqLogic; - Serv.actions={}; - Serv.infos={}; - Serv.infos.state=cmd.state; - eqServicesCopy.energy.forEach(function(cmd2) { - if (cmd2.on) { - Serv.actions.on = cmd2.on; - } else if (cmd2.off) { - Serv.actions.off = cmd2.off; - } else if (cmd2.inuse) { - Serv.infos.inuse = cmd2.inuse; - } - }); - if(!Serv.actions.on) {that.log('warn','Pas de type générique "Action/Prise Bouton On"');} - if(!Serv.actions.off) {that.log('warn','Pas de type générique "Action/Prise Bouton Off"');} - // Test for AdminOnlyAccess, state need to have OwnerOnly attribute to True ou 1 - if(Serv.infos.state.OwnerOnly) {Serv.getCharacteristic(Characteristic.On).setProps({adminOnlyAccess: [Access.WRITE]});} - // add Active, Tampered and Defect Characteristics if needed - HBservice=that.createStatusCharact(HBservice,eqServicesCopy); - - Serv.cmd_id = cmd.state.id; - Serv.eqID = eqLogic.id; - Serv.subtype = Serv.subtype || ''; - Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; - HBservices.push(HBservice); - } + eqLogic.services.energy.forEach((cmd) => { + if (!cmd.state) {return;} + HBservice = { + controlService : new Service.Outlet(eqLogic.name), + characteristics : [Characteristic.On, Characteristic.OutletInUse], + }; + const Serv = HBservice.controlService; + Serv.eqLogic=eqLogic; + Serv.actions={}; + Serv.infos={}; + Serv.infos.state=cmd.state; + eqServicesCopy.energy.forEach((cmd2) => { + if (cmd2.on) { + Serv.actions.on = cmd2.on; + } else if (cmd2.off) { + Serv.actions.off = cmd2.off; + } else if (cmd2.inuse) { + Serv.infos.inuse = cmd2.inuse; + } + }); + if(!Serv.actions.on) {this.log('warn','Pas de type générique "Action/Prise Bouton On"');} + if(!Serv.actions.off) {this.log('warn','Pas de type générique "Action/Prise Bouton Off"');} + // Test for AdminOnlyAccess, state need to have OwnerOnly attribute to True ou 1 + if(Serv.infos.state.OwnerOnly) {Serv.getCharacteristic(Characteristic.On).setProps({adminOnlyAccess: [Access.WRITE]});} + // add Active, Tampered and Defect Characteristics if needed + HBservice=this.createStatusCharact(HBservice,eqServicesCopy); + + Serv.cmd_id = cmd.state.id; + Serv.eqID = eqLogic.id; + Serv.subtype = Serv.subtype || ''; + Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; + HBservices.push(HBservice); }); if(!HBservice) { - that.log('warn','Pas de type générique "Info/Prise Etat"'); + this.log('warn','Pas de type générique "Info/Prise Etat"'); } else { HBservice = null; } } if (eqLogic.services.faucet) { - eqLogic.services.faucet.forEach(function(cmd) { - if (cmd.state) { - HBservice = { - controlService : new Service.Valve(eqLogic.name), - characteristics : [Characteristic.Active,Characteristic.InUse,Characteristic.ValveType], - }; - const Serv = HBservice.controlService; - Serv.eqLogic=eqLogic; - Serv.actions={}; - Serv.infos={}; - Serv.infos.state=cmd.state; - Serv.getCharacteristic(Characteristic.ValveType).setValue(Characteristic.ValveType.WATER_FAUCET); - Serv.ValveType=Characteristic.ValveType.WATER_FAUCET; - eqServicesCopy.faucet.forEach(function(cmd2) { - if (cmd2.on) { - Serv.actions.on = cmd2.on; - } else if (cmd2.off) { - Serv.actions.off = cmd2.off; - } - }); - if(!Serv.actions.on) {that.log('warn','Pas de type générique "Action/Robinet Bouton On"');} - if(!Serv.actions.off) {that.log('warn','Pas de type générique "Action/Robinet Bouton Off"');} - - // add Active, Tampered and Defect Characteristics if needed - HBservice=that.createStatusCharact(HBservice,eqServicesCopy); - - Serv.cmd_id = cmd.state.id; - Serv.eqID = eqLogic.id; - Serv.subtype = Serv.subtype || ''; - Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; - HBservices.push(HBservice); - } + eqLogic.services.faucet.forEach((cmd) => { + if (!cmd.state) {return;} + HBservice = { + controlService : new Service.Valve(eqLogic.name), + characteristics : [Characteristic.Active,Characteristic.InUse,Characteristic.ValveType], + }; + const Serv = HBservice.controlService; + Serv.eqLogic=eqLogic; + Serv.actions={}; + Serv.infos={}; + Serv.infos.state=cmd.state; + Serv.getCharacteristic(Characteristic.ValveType).setValue(Characteristic.ValveType.WATER_FAUCET); + Serv.ValveType=Characteristic.ValveType.WATER_FAUCET; + eqServicesCopy.faucet.forEach((cmd2) => { + if (cmd2.on) { + Serv.actions.on = cmd2.on; + } else if (cmd2.off) { + Serv.actions.off = cmd2.off; + } + }); + if(!Serv.actions.on) {this.log('warn','Pas de type générique "Action/Robinet Bouton On"');} + if(!Serv.actions.off) {this.log('warn','Pas de type générique "Action/Robinet Bouton Off"');} + + // add Active, Tampered and Defect Characteristics if needed + HBservice=this.createStatusCharact(HBservice,eqServicesCopy); + + Serv.cmd_id = cmd.state.id; + Serv.eqID = eqLogic.id; + Serv.subtype = Serv.subtype || ''; + Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; + HBservices.push(HBservice); }); if(!HBservice) { - that.log('warn','Pas de type générique "Info/Robinet Etat"'); + this.log('warn','Pas de type générique "Info/Robinet Etat"'); } else { HBservice = null; } } if (eqLogic.services.irrigation) { - eqLogic.services.irrigation.forEach(function(cmd) { - if (cmd.state) { - HBservice = { - controlService : new Service.Valve(eqLogic.name), - characteristics : [Characteristic.Active,Characteristic.InUse,Characteristic.ValveType], - }; - const Serv = HBservice.controlService; - Serv.eqLogic=eqLogic; - Serv.actions={}; - Serv.infos={}; - Serv.infos.state=cmd.state; - Serv.getCharacteristic(Characteristic.ValveType).setValue(Characteristic.ValveType.IRRIGATION); - Serv.ValveType=Characteristic.ValveType.IRRIGATION; - eqServicesCopy.irrigation.forEach(function(cmd2) { - if (cmd2.on) { - Serv.actions.on = cmd2.on; - } else if (cmd2.off) { - Serv.actions.off = cmd2.off; - } - }); - if(!Serv.actions.on) {that.log('warn','Pas de type générique "Action/Irrigation Bouton On"');} - if(!Serv.actions.off) {that.log('warn','Pas de type générique "Action/Irrigation Bouton Off"');} - - // add Active, Tampered and Defect Characteristics if needed - HBservice=that.createStatusCharact(HBservice,eqServicesCopy); - - Serv.cmd_id = cmd.state.id; - Serv.eqID = eqLogic.id; - Serv.subtype = Serv.subtype || ''; - Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; - HBservices.push(HBservice); - } + eqLogic.services.irrigation.forEach((cmd) => { + if (!cmd.state) {return;} + HBservice = { + controlService : new Service.Valve(eqLogic.name), + characteristics : [Characteristic.Active,Characteristic.InUse,Characteristic.ValveType], + }; + const Serv = HBservice.controlService; + Serv.eqLogic=eqLogic; + Serv.actions={}; + Serv.infos={}; + Serv.infos.state=cmd.state; + Serv.getCharacteristic(Characteristic.ValveType).setValue(Characteristic.ValveType.IRRIGATION); + Serv.ValveType=Characteristic.ValveType.IRRIGATION; + eqServicesCopy.irrigation.forEach((cmd2) => { + if (cmd2.on) { + Serv.actions.on = cmd2.on; + } else if (cmd2.off) { + Serv.actions.off = cmd2.off; + } + }); + if(!Serv.actions.on) {this.log('warn','Pas de type générique "Action/Irrigation Bouton On"');} + if(!Serv.actions.off) {this.log('warn','Pas de type générique "Action/Irrigation Bouton Off"');} + + // add Active, Tampered and Defect Characteristics if needed + HBservice=this.createStatusCharact(HBservice,eqServicesCopy); + + Serv.cmd_id = cmd.state.id; + Serv.eqID = eqLogic.id; + Serv.subtype = Serv.subtype || ''; + Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; + HBservices.push(HBservice); }); if(!HBservice) { - that.log('warn','Pas de type générique "Info/Irrigation Etat"'); + this.log('warn','Pas de type générique "Info/Irrigation Etat"'); } else { HBservice = null; } } if (eqLogic.services.valve) { - eqLogic.services.valve.forEach(function(cmd) { - if (cmd.state) { - HBservice = { - controlService : new Service.Valve(eqLogic.name), - characteristics : [Characteristic.Active,Characteristic.InUse,Characteristic.ValveType], - }; - const Serv = HBservice.controlService; - Serv.eqLogic=eqLogic; - Serv.actions={}; - Serv.infos={}; - Serv.infos.state=cmd.state; - Serv.getCharacteristic(Characteristic.ValveType).setValue(Characteristic.ValveType.GENERIC_VALVE); - Serv.ValveType=Characteristic.ValveType.GENERIC_VALVE; - eqServicesCopy.valve.forEach(function(cmd2) { - if (cmd2.on) { - Serv.actions.on = cmd2.on; - } else if (cmd2.off) { - Serv.actions.off = cmd2.off; - } else if (cmd2.setDuration) { - Serv.actions.setDuration = cmd2.setDuration; - } else if (cmd2.remainingDuration) { - Serv.infos.remainingDuration = cmd2.remainingDuration; - } - }); - if(!Serv.actions.on) {that.log('warn','Pas de type générique "Action/Valve générique Bouton On"');} - if(!Serv.actions.off) {that.log('warn','Pas de type générique "Action/Valve générique Bouton Off"');} - - if(Serv.actions.setDuration) { - HBservice.characteristics.push(Characteristic.SetDuration); - Serv.addOptionalCharacteristic(Characteristic.SetDuration); + eqLogic.services.valve.forEach((cmd) => { + if (!cmd.state) {return;} + HBservice = { + controlService : new Service.Valve(eqLogic.name), + characteristics : [Characteristic.Active,Characteristic.InUse,Characteristic.ValveType], + }; + const Serv = HBservice.controlService; + Serv.eqLogic=eqLogic; + Serv.actions={}; + Serv.infos={}; + Serv.infos.state=cmd.state; + Serv.getCharacteristic(Characteristic.ValveType).setValue(Characteristic.ValveType.GENERIC_VALVE); + Serv.ValveType=Characteristic.ValveType.GENERIC_VALVE; + eqServicesCopy.valve.forEach((cmd2) => { + if (cmd2.on) { + Serv.actions.on = cmd2.on; + } else if (cmd2.off) { + Serv.actions.off = cmd2.off; + } else if (cmd2.setDuration) { + Serv.actions.setDuration = cmd2.setDuration; + } else if (cmd2.remainingDuration) { + Serv.infos.remainingDuration = cmd2.remainingDuration; } - if(Serv.infos.remainingDuration) { - HBservice.characteristics.push(Characteristic.RemainingDuration); - Serv.addOptionalCharacteristic(Characteristic.RemainingDuration); - } - - // add Active, Tampered and Defect Characteristics if needed - HBservice=that.createStatusCharact(HBservice,eqServicesCopy); - - Serv.cmd_id = cmd.state.id; - Serv.eqID = eqLogic.id; - Serv.subtype = Serv.subtype || ''; - Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; - HBservices.push(HBservice); + }); + if(!Serv.actions.on) {this.log('warn','Pas de type générique "Action/Valve générique Bouton On"');} + if(!Serv.actions.off) {this.log('warn','Pas de type générique "Action/Valve générique Bouton Off"');} + + if(Serv.actions.setDuration) { + HBservice.characteristics.push(Characteristic.SetDuration); + Serv.addOptionalCharacteristic(Characteristic.SetDuration); } + if(Serv.infos.remainingDuration) { + HBservice.characteristics.push(Characteristic.RemainingDuration); + Serv.addOptionalCharacteristic(Characteristic.RemainingDuration); + } + + // add Active, Tampered and Defect Characteristics if needed + HBservice=this.createStatusCharact(HBservice,eqServicesCopy); + + Serv.cmd_id = cmd.state.id; + Serv.eqID = eqLogic.id; + Serv.subtype = Serv.subtype || ''; + Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; + HBservices.push(HBservice); }); if(!HBservice) { - that.log('warn','Pas de type générique "Info/Valve générique Etat"'); + this.log('warn','Pas de type générique "Info/Valve générique Etat"'); } else { HBservice = null; } } if (eqLogic.services.fan) { - eqLogic.services.fan.forEach(function(cmd) { - if (cmd.state) { - let FanType="Switch"; - let maxPower; - HBservice = { - controlService : new Service.Fan(eqLogic.name), - characteristics : [Characteristic.On], - }; - const Serv = HBservice.controlService; - Serv.eqLogic=eqLogic; - Serv.actions={}; - Serv.infos={}; - Serv.infos.state=cmd.state; - - eqServicesCopy.fan.forEach(function(cmd2) { - if (cmd2.on) { - Serv.actions.on=cmd2.on; - } else if (cmd2.off) { - Serv.actions.off=cmd2.off; - } else if (cmd2.slider) { - Serv.actions.slider=cmd2.slider; - } - }); - if (Serv.actions.on && !Serv.actions.off) {that.log('warn','Pas de type générique "Action/Ventilateur OFF"');} - if (!Serv.actions.on && Serv.actions.off) {that.log('warn','Pas de type générique "Action/Ventilateur ON"');} - if (!Serv.actions.on && !Serv.actions.off) {that.log('warn','Pas de type générique "Action/Ventilateur ON" et "Action/Ventilateur OFF"');} - - if(Serv.actions.slider) { - if(Serv.actions.slider.configuration && Serv.actions.slider.configuration.maxValue && parseInt(Serv.actions.slider.configuration.maxValue)) { - maxPower = parseInt(Serv.actions.slider.configuration.maxValue); - } else { - maxPower = 100; // if not set in Jeedom it's 100 - } - FanType += "_Slider"; - HBservice.characteristics.push(Characteristic.RotationSpeed); - Serv.addCharacteristic(Characteristic.RotationSpeed); + eqLogic.services.fan.forEach((cmd) => { + if (!cmd.state) {return;} + let FanType="Switch"; + let maxPower; + HBservice = { + controlService : new Service.Fan(eqLogic.name), + characteristics : [Characteristic.On], + }; + const Serv = HBservice.controlService; + Serv.eqLogic=eqLogic; + Serv.actions={}; + Serv.infos={}; + Serv.infos.state=cmd.state; + + eqServicesCopy.fan.forEach((cmd2) => { + if (cmd2.on) { + Serv.actions.on=cmd2.on; + } else if (cmd2.off) { + Serv.actions.off=cmd2.off; + } else if (cmd2.slider) { + Serv.actions.slider=cmd2.slider; + } + }); + if (Serv.actions.on && !Serv.actions.off) {this.log('warn','Pas de type générique "Action/Ventilateur OFF"');} + if (!Serv.actions.on && Serv.actions.off) {this.log('warn','Pas de type générique "Action/Ventilateur ON"');} + if (!Serv.actions.on && !Serv.actions.off) {this.log('warn','Pas de type générique "Action/Ventilateur ON" et "Action/Ventilateur OFF"');} + + if(Serv.actions.slider) { + if(Serv.actions.slider.configuration && Serv.actions.slider.configuration.maxValue && parseInt(Serv.actions.slider.configuration.maxValue)) { + maxPower = parseInt(Serv.actions.slider.configuration.maxValue); } else { - that.log('info','Le ventilateur n\'a pas de variateur'); + maxPower = 100; // if not set in Jeedom it's 100 } - - // add Active, Tampered and Defect Characteristics if needed - HBservice=that.createStatusCharact(HBservice,eqServicesCopy); - - that.log('info','Le ventilateur est du type :',FanType+((maxPower)?','+maxPower:'')); - Serv.FanType = FanType; - Serv.maxPower = maxPower; - Serv.cmd_id = cmd.state.id; - Serv.eqID = eqLogic.id; - Serv.subtype = Serv.subtype || ''; - Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; - HBservices.push(HBservice); + FanType += "_Slider"; + HBservice.characteristics.push(Characteristic.RotationSpeed); + Serv.addCharacteristic(Characteristic.RotationSpeed); + } else { + this.log('info','Le ventilateur n\'a pas de variateur'); } + + // add Active, Tampered and Defect Characteristics if needed + HBservice=this.createStatusCharact(HBservice,eqServicesCopy); + + this.log('info','Le ventilateur est du type :',FanType+((maxPower)?','+maxPower:'')); + Serv.FanType = FanType; + Serv.maxPower = maxPower; + Serv.cmd_id = cmd.state.id; + Serv.eqID = eqLogic.id; + Serv.subtype = Serv.subtype || ''; + Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; + HBservices.push(HBservice); }); if(!HBservice) { - that.log('warn','Pas de type générique "Info/Ventilateur Etat"'); + this.log('warn','Pas de type générique "Info/Ventilateur Etat"'); } else { HBservice = null; } } if (eqLogic.services.Switch) { - eqLogic.services.Switch.forEach(function(cmd) { - if (cmd.state) { - let SwitchName = eqLogic.name; - if(cmd.state.generic_type == 'CAMERA_RECORD_STATE' || (cmd.state.generic_type == 'SWITCH_STATE' && eqLogic.numSwitches>1)) { - that.log('debug',"Switchs multiples dans même équipement, il y en a "+eqLogic.numSwitches); - SwitchName=cmd.state.name; - } - HBservice = { - controlService : new Service.Switch(SwitchName), - characteristics : [Characteristic.On], - }; - const Serv = HBservice.controlService; - if(cmd.state.generic_type == 'CAMERA_RECORD_STATE' || (cmd.state.generic_type == 'SWITCH_STATE' && eqLogic.numSwitches>1)) { - that.log('debug',"Nom du switch (multi) : "+SwitchName); - Serv.getCharacteristic(Characteristic.On).displayName = SwitchName; - - Serv.ConfiguredName=SwitchName; - HBservice.characteristics.push(Characteristic.ConfiguredName); - Serv.addCharacteristic(Characteristic.ConfiguredName); - Serv.getCharacteristic(Characteristic.ConfiguredName).setValue(SwitchName); - } - Serv.eqLogic=eqLogic; - Serv.actions={}; - Serv.infos={}; - Serv.infos.state=cmd.state; - eqServicesCopy.Switch.forEach(function(cmd2) { - if (cmd2.on) { - if(Serv.infos.state.generic_type == 'SWITCH_STATE' && eqLogic.numSwitches>1) { - if(cmd2.on.value == cmd.state.id) { - Serv.actions.on = cmd2.on; - } - } else { + eqLogic.services.Switch.forEach((cmd) => { + if (!cmd.state) {return;} + let SwitchName = eqLogic.name; + if(cmd.state.generic_type == 'CAMERA_RECORD_STATE' || (cmd.state.generic_type == 'SWITCH_STATE' && eqLogic.numSwitches>1)) { + this.log('debug',"Switchs multiples dans même équipement, il y en a "+eqLogic.numSwitches); + SwitchName=cmd.state.name; + } + HBservice = { + controlService : new Service.Switch(SwitchName), + characteristics : [Characteristic.On], + }; + const Serv = HBservice.controlService; + if(cmd.state.generic_type == 'CAMERA_RECORD_STATE' || (cmd.state.generic_type == 'SWITCH_STATE' && eqLogic.numSwitches>1)) { + this.log('debug',"Nom du switch (multi) : "+SwitchName); + Serv.getCharacteristic(Characteristic.On).displayName = SwitchName; + + Serv.ConfiguredName=SwitchName; + HBservice.characteristics.push(Characteristic.ConfiguredName); + Serv.addCharacteristic(Characteristic.ConfiguredName); + Serv.getCharacteristic(Characteristic.ConfiguredName).setValue(SwitchName); + } + Serv.eqLogic=eqLogic; + Serv.actions={}; + Serv.infos={}; + Serv.infos.state=cmd.state; + eqServicesCopy.Switch.forEach((cmd2) => { + if (cmd2.on) { + if(Serv.infos.state.generic_type == 'SWITCH_STATE' && eqLogic.numSwitches>1) { + if(cmd2.on.value == cmd.state.id) { Serv.actions.on = cmd2.on; } - } else if (cmd2.off) { - if(Serv.infos.state.generic_type == 'SWITCH_STATE' && eqLogic.numSwitches>1) { - if(cmd2.off.value == cmd.state.id) { - Serv.actions.off = cmd2.off; - } - } else { + } else { + Serv.actions.on = cmd2.on; + } + } else if (cmd2.off) { + if(Serv.infos.state.generic_type == 'SWITCH_STATE' && eqLogic.numSwitches>1) { + if(cmd2.off.value == cmd.state.id) { Serv.actions.off = cmd2.off; } + } else { + Serv.actions.off = cmd2.off; } - }); - if(!Serv.actions.on) {that.log('warn','Pas de type générique "Action/Interrupteur Bouton On"');} - if(!Serv.actions.off) {that.log('warn','Pas de type générique "Action/Interrupteur Bouton Off"');} - - // add Active, Tampered and Defect Characteristics if needed - HBservice=that.createStatusCharact(HBservice,eqServicesCopy); - - Serv.cmd_id = cmd.state.id; - Serv.eqID = eqLogic.id; - Serv.subtype = Serv.subtype || ''; - Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; - - if(that.fakegato && !eqLogic.hasLogging) { - // HBservice.characteristics.push(Characteristic.Sensitivity,Characteristic.Duration,Characteristic.LastActivation); + } + }); + if(!Serv.actions.on) {this.log('warn','Pas de type générique "Action/Interrupteur Bouton On"');} + if(!Serv.actions.off) {this.log('warn','Pas de type générique "Action/Interrupteur Bouton Off"');} + + // add Active, Tampered and Defect Characteristics if needed + HBservice=this.createStatusCharact(HBservice,eqServicesCopy); + + Serv.cmd_id = cmd.state.id; + Serv.eqID = eqLogic.id; + Serv.subtype = Serv.subtype || ''; + Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; + + if(this.fakegato && !eqLogic.hasLogging) { + // HBservice.characteristics.push(Characteristic.Sensitivity,Characteristic.Duration,Characteristic.LastActivation); - // eqLogic.loggingService = {type:"motion", options:{storage:'googleDrive',folder:'fakegato',keyPath:'/home/pi/.homebridge/'},subtype:Serv.eqID+'-history',cmd_id:Serv.eqID}; - eqLogic.loggingService = {type:"switch", options:{storage:'fs',path:that.pathHomebridgeConf},subtype:Serv.eqID+'-history',cmd_id:Serv.eqID}; + // eqLogic.loggingService = {type:"motion", options:{storage:'googleDrive',folder:'fakegato',keyPath:'/home/pi/.homebridge/'},subtype:Serv.eqID+'-history',cmd_id:Serv.eqID}; + eqLogic.loggingService = {type:"switch", options:{storage:'fs',path:this.pathHomebridgeConf},subtype:Serv.eqID+'-history',cmd_id:Serv.eqID}; - eqLogic.hasLogging=true; - } - - HBservices.push(HBservice); + eqLogic.hasLogging=true; } + + HBservices.push(HBservice); }); if(!HBservice) { - that.log('warn','Pas de type générique "Info/Interrupteur Etat"'); + this.log('warn','Pas de type générique "Info/Interrupteur Etat"'); } else { HBservice = null; } } if (eqLogic.services.Push) { - eqLogic.services.Push.forEach(function(cmd) { - if (cmd.Push && cmd.Push.subType == 'other') { - const SwitchName=cmd.Push.name; - HBservice = { - controlService : new Service.Switch(SwitchName), - characteristics : [Characteristic.On,Characteristic.ConfiguredName], - }; - const Serv = HBservice.controlService; - Serv.eqLogic=eqLogic; - Serv.actions={}; - Serv.infos={}; - Serv.actions.Push = cmd.Push; - Serv.getCharacteristic(Characteristic.On).displayName = SwitchName; - - Serv.ConfiguredName=SwitchName; - Serv.getCharacteristic(Characteristic.ConfiguredName).setValue(SwitchName); - - // add Active, Tampered and Defect Characteristics if needed - HBservice=that.createStatusCharact(HBservice,eqServicesCopy); - - Serv.cmd_id = cmd.Push.id; - Serv.eqID = eqLogic.id; - Serv.subtype = Serv.subtype || ''; - Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; - HBservices.push(HBservice); - } + eqLogic.services.Push.forEach((cmd) => { + if (!cmd.Push || cmd.Push.subType != 'other') {return;} + const SwitchName=cmd.Push.name; + HBservice = { + controlService : new Service.Switch(SwitchName), + characteristics : [Characteristic.On,Characteristic.ConfiguredName], + }; + const Serv = HBservice.controlService; + Serv.eqLogic=eqLogic; + Serv.actions={}; + Serv.infos={}; + Serv.actions.Push = cmd.Push; + Serv.getCharacteristic(Characteristic.On).displayName = SwitchName; + + Serv.ConfiguredName=SwitchName; + Serv.getCharacteristic(Characteristic.ConfiguredName).setValue(SwitchName); + + // add Active, Tampered and Defect Characteristics if needed + HBservice=this.createStatusCharact(HBservice,eqServicesCopy); + + Serv.cmd_id = cmd.Push.id; + Serv.eqID = eqLogic.id; + Serv.subtype = Serv.subtype || ''; + Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; + HBservices.push(HBservice); }); if(!HBservice) { - that.log('warn','La Commande Action associée doit être du type "Autre"'); + this.log('warn','La Commande Action associée doit être du type "Autre"'); } else { HBservice = null; } } if (eqLogic.services.power || (eqLogic.services.power && eqLogic.services.consumption)) { - eqLogic.services.power.forEach(function(cmd) { - if (cmd.power) { - HBservice = { - controlService : new Service.PowerMonitor(eqLogic.name), - characteristics : [Characteristic.CurrentPowerConsumption, Characteristic.TotalPowerConsumption], - }; - const Serv = HBservice.controlService; - Serv.eqLogic=eqLogic; - Serv.actions={}; - Serv.infos={}; - Serv.infos.power=cmd.power; - // add Active, Tampered and Defect Characteristics if needed - HBservice=that.createStatusCharact(HBservice,eqServicesCopy); - - if(eqServicesCopy.consumption) { - eqServicesCopy.consumption.forEach(function(cmd2) { - if (cmd2.consumption) { - Serv.infos.consumption=cmd2.consumption; - } - }); - } - - Serv.cmd_id = cmd.power.id; - Serv.eqID = eqLogic.id; - Serv.subtype = Serv.subtype || ''; - Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; - if(that.fakegato && !eqLogic.hasLogging) { - // HBservice.characteristics.push(Characteristic.ResetTotal); - eqLogic.loggingService = {type:"energy", options:{storage:'fs',path:that.pathHomebridgeConf},subtype:Serv.eqID+'-history',cmd_id:Serv.eqID}; + eqLogic.services.power.forEach((cmd) => { + if (!cmd.power) {return;} + HBservice = { + controlService : new Service.PowerMonitor(eqLogic.name), + characteristics : [Characteristic.CurrentPowerConsumption, Characteristic.TotalPowerConsumption], + }; + const Serv = HBservice.controlService; + Serv.eqLogic=eqLogic; + Serv.actions={}; + Serv.infos={}; + Serv.infos.power=cmd.power; + // add Active, Tampered and Defect Characteristics if needed + HBservice=this.createStatusCharact(HBservice,eqServicesCopy); + + if(eqServicesCopy.consumption) { + eqServicesCopy.consumption.forEach((cmd2) => { + if (cmd2.consumption) { + Serv.infos.consumption=cmd2.consumption; + } + }); + } + + Serv.cmd_id = cmd.power.id; + Serv.eqID = eqLogic.id; + Serv.subtype = Serv.subtype || ''; + Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; + if(this.fakegato && !eqLogic.hasLogging) { + // HBservice.characteristics.push(Characteristic.ResetTotal); + eqLogic.loggingService = {type:"energy", options:{storage:'fs',path:this.pathHomebridgeConf},subtype:Serv.eqID+'-history',cmd_id:Serv.eqID}; - eqLogic.hasLogging=true; - } - HBservices.push(HBservice); - HBservice = null; + eqLogic.hasLogging=true; } + HBservices.push(HBservice); + HBservice = null; }); } if (eqLogic.services.battery) { - eqLogic.services.battery.forEach(function(cmd) { - if (cmd.battery) { - HBservice = { - controlService : new Service.BatteryService(eqLogic.name), - characteristics : [Characteristic.BatteryLevel,Characteristic.ChargingState,Characteristic.StatusLowBattery], - }; - const Serv = HBservice.controlService; - Serv.eqLogic=eqLogic; - Serv.actions={}; - Serv.infos={}; - Serv.infos.battery=cmd.battery; - Serv.infos.batteryCharging=cmd.batteryCharging || {id:'NOT'}; - eqServicesCopy.battery.forEach(function(cmd2) { - if (cmd2.batteryCharging) { - Serv.infos.batteryCharging=cmd2.batteryCharging; - } else { - Serv.infos.batteryCharging={id:'NOT'}; - } - }); - Serv.cmd_id = cmd.battery.id; - Serv.eqID = eqLogic.id; - Serv.subtype = Serv.subtype || ''; - Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; - HBservices.push(HBservice); - HBservice = null; - } + eqLogic.services.battery.forEach((cmd) => { + if (!cmd.battery) {return;} + HBservice = { + controlService : new Service.BatteryService(eqLogic.name), + characteristics : [Characteristic.BatteryLevel,Characteristic.ChargingState,Characteristic.StatusLowBattery], + }; + const Serv = HBservice.controlService; + Serv.eqLogic=eqLogic; + Serv.actions={}; + Serv.infos={}; + Serv.infos.battery=cmd.battery; + Serv.infos.batteryCharging=cmd.batteryCharging || {id:'NOT'}; + eqServicesCopy.battery.forEach((cmd2) => { + if (cmd2.batteryCharging) { + Serv.infos.batteryCharging=cmd2.batteryCharging; + } else { + Serv.infos.batteryCharging={id:'NOT'}; + } + }); + Serv.cmd_id = cmd.battery.id; + Serv.eqID = eqLogic.id; + Serv.subtype = Serv.subtype || ''; + Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; + HBservices.push(HBservice); + HBservice = null; }); } if (eqLogic.services.Noise) { - eqLogic.services.Noise.forEach(function(cmd) { - if (cmd.Noise) { - HBservice = { - controlService : new Service.NoiseSensor(eqLogic.name), - characteristics : [Characteristic.NoiseLevel,Characteristic.NoiseQuality], - }; - const Serv = HBservice.controlService; - Serv.eqLogic=eqLogic; - Serv.actions={}; - Serv.infos={}; - Serv.infos.Noise=cmd.Noise; - - if(cmd.Noise.subType=='numeric') { - Serv.levelNum=[]; - Serv.levelNum[Characteristic.NoiseQuality.SILENT]=50; - Serv.levelNum[Characteristic.NoiseQuality.CALM]=65; - Serv.levelNum[Characteristic.NoiseQuality.LIGHTLYNOISY]=70; - Serv.levelNum[Characteristic.NoiseQuality.NOISY]=80; - Serv.levelNum[Characteristic.NoiseQuality.TOONOISY]=100; - } else { - Serv.levelTxt=[]; - Serv.levelTxt[Characteristic.NoiseQuality.SILENT]="Silencieux"; - Serv.levelTxt[Characteristic.NoiseQuality.CALM]="Calme"; - Serv.levelTxt[Characteristic.NoiseQuality.LIGHTLYNOISY]="Légèrement Bruyant"; - Serv.levelTxt[Characteristic.NoiseQuality.NOISY]="Bruyant"; - Serv.levelTxt[Characteristic.NoiseQuality.TOONOISY]="Trop Bruyant"; - } - - Serv.cmd_id = cmd.Noise.id; - Serv.eqID = eqLogic.id; - Serv.subtype = 'Noise'; - Serv.subtype = Serv.subtype || ''; - Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; - const uniteNoise = Serv.infos.Noise.unite ? Serv.infos.Noise.unite : ''; - if(uniteNoise) { - const propsNoise = {}; - propsNoise.unit=uniteNoise; - Serv.getCharacteristic(Characteristic.NoiseLevel).setProps(propsNoise); - } - - HBservices.push(HBservice); - HBservice = null; + eqLogic.services.Noise.forEach((cmd) => { + if (!cmd.Noise) {return;} + HBservice = { + controlService : new Service.NoiseSensor(eqLogic.name), + characteristics : [Characteristic.NoiseLevel,Characteristic.NoiseQuality], + }; + const Serv = HBservice.controlService; + Serv.eqLogic=eqLogic; + Serv.actions={}; + Serv.infos={}; + Serv.infos.Noise=cmd.Noise; + + if(cmd.Noise.subType=='numeric') { + Serv.levelNum=[]; + Serv.levelNum[Characteristic.NoiseQuality.SILENT]=50; + Serv.levelNum[Characteristic.NoiseQuality.CALM]=65; + Serv.levelNum[Characteristic.NoiseQuality.LIGHTLYNOISY]=70; + Serv.levelNum[Characteristic.NoiseQuality.NOISY]=80; + Serv.levelNum[Characteristic.NoiseQuality.TOONOISY]=100; + } else { + Serv.levelTxt=[]; + Serv.levelTxt[Characteristic.NoiseQuality.SILENT]="Silencieux"; + Serv.levelTxt[Characteristic.NoiseQuality.CALM]="Calme"; + Serv.levelTxt[Characteristic.NoiseQuality.LIGHTLYNOISY]="Légèrement Bruyant"; + Serv.levelTxt[Characteristic.NoiseQuality.NOISY]="Bruyant"; + Serv.levelTxt[Characteristic.NoiseQuality.TOONOISY]="Trop Bruyant"; } + + Serv.cmd_id = cmd.Noise.id; + Serv.eqID = eqLogic.id; + Serv.subtype = 'Noise'; + Serv.subtype = Serv.subtype || ''; + Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; + const uniteNoise = Serv.infos.Noise.unite ? Serv.infos.Noise.unite : ''; + if(uniteNoise) { + const propsNoise = {}; + propsNoise.unit=uniteNoise; + Serv.getCharacteristic(Characteristic.NoiseLevel).setProps(propsNoise); + } + + HBservices.push(HBservice); + HBservice = null; }); } if (eqLogic.services.CO) { - eqLogic.services.CO.forEach(function(cmd) { - if (cmd.CO) { - HBservice = { - controlService : new Service.CarbonMonoxideSensor(eqLogic.name), - characteristics : [Characteristic.CarbonMonoxideDetected], - }; - const Serv = HBservice.controlService; - Serv.eqLogic=eqLogic; - Serv.actions={}; - Serv.infos={}; - Serv.infos.CO=cmd.CO; - - Serv.cmd_id = cmd.CO.id; - Serv.eqID = eqLogic.id; - Serv.subtype = 'CO'; - Serv.subtype = Serv.subtype || ''; - Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; - - HBservices.push(HBservice); - HBservice = null; - } + eqLogic.services.CO.forEach((cmd) => { + if (!cmd.CO) {return;} + HBservice = { + controlService : new Service.CarbonMonoxideSensor(eqLogic.name), + characteristics : [Characteristic.CarbonMonoxideDetected], + }; + const Serv = HBservice.controlService; + Serv.eqLogic=eqLogic; + Serv.actions={}; + Serv.infos={}; + Serv.infos.CO=cmd.CO; + + Serv.cmd_id = cmd.CO.id; + Serv.eqID = eqLogic.id; + Serv.subtype = 'CO'; + Serv.subtype = Serv.subtype || ''; + Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; + + HBservices.push(HBservice); + HBservice = null; }); } if (eqLogic.services.CO2) { - eqLogic.services.CO2.forEach(function(cmd) { - if (cmd.CO2) { - HBservice = { - controlService : new Service.AirQualitySensor(eqLogic.name), - characteristics : [Characteristic.AirQuality,Characteristic.CarbonDioxideLevel,Characteristic.CarbonDioxideDetected], - }; - const Serv = HBservice.controlService; - Serv.eqLogic=eqLogic; - Serv.actions={}; - Serv.infos={}; - Serv.infos.CO2=cmd.CO2; - - if(cmd.CO2.subType=='numeric') { - Serv.levelNum=[]; - Serv.levelNum[Characteristic.AirQuality.EXCELLENT]=900;// 700 - Serv.levelNum[Characteristic.AirQuality.GOOD]=1150;// 1100 - Serv.levelNum[Characteristic.AirQuality.FAIR]=1400;// 1600 - Serv.levelNum[Characteristic.AirQuality.INFERIOR]=1600;// 2100 - Serv.levelNum[Characteristic.AirQuality.POOR]=100000; - } else { - Serv.levelTxt=[]; - Serv.levelTxt[Characteristic.AirQuality.EXCELLENT]="Excellent"; - Serv.levelTxt[Characteristic.AirQuality.GOOD]="Bon"; - Serv.levelTxt[Characteristic.AirQuality.FAIR]="Moyen"; - Serv.levelTxt[Characteristic.AirQuality.INFERIOR]="Inférieur"; - Serv.levelTxt[Characteristic.AirQuality.POOR]="Faible"; - } - - Serv.cmd_id = cmd.CO2.id; - Serv.eqID = eqLogic.id; - Serv.subtype = 'CO2'; - Serv.subtype = Serv.subtype || ''; - Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; - const uniteCO2 = Serv.infos.CO2.unite ? Serv.infos.CO2.unite : ''; - if(uniteCO2) { - const propsCO2 = {}; - propsCO2.unit=uniteCO2; - Serv.getCharacteristic(Characteristic.CarbonDioxideLevel).setProps(propsCO2); - } - - if(that.fakegato && !eqLogic.hasLogging) { - HBservice.characteristics.push(Characteristic.PPM); - Serv.addCharacteristic(Characteristic.PPM); - const unite = Serv.infos.CO2.unite ? Serv.infos.CO2.unite : ''; - if(unite) { - const props = {}; - props.unit=unite; - Serv.getCharacteristic(Characteristic.PPM).setProps(props); - } - HBservice.characteristics.push(Characteristic.AQExtraCharacteristic); - Serv.addCharacteristic(Characteristic.AQExtraCharacteristic); - - eqLogic.loggingService ={type:"room", options:{storage:'fs',path:that.pathHomebridgeConf},subtype:Serv.eqID+'-history',cmd_id:Serv.eqID}; - eqLogic.hasLogging=true; + eqLogic.services.CO2.forEach((cmd) => { + if (!cmd.CO2) {return;} + HBservice = { + controlService : new Service.AirQualitySensor(eqLogic.name), + characteristics : [Characteristic.AirQuality,Characteristic.CarbonDioxideLevel,Characteristic.CarbonDioxideDetected], + }; + const Serv = HBservice.controlService; + Serv.eqLogic=eqLogic; + Serv.actions={}; + Serv.infos={}; + Serv.infos.CO2=cmd.CO2; + + if(cmd.CO2.subType=='numeric') { + Serv.levelNum=[]; + Serv.levelNum[Characteristic.AirQuality.EXCELLENT]=900;// 700 + Serv.levelNum[Characteristic.AirQuality.GOOD]=1150;// 1100 + Serv.levelNum[Characteristic.AirQuality.FAIR]=1400;// 1600 + Serv.levelNum[Characteristic.AirQuality.INFERIOR]=1600;// 2100 + Serv.levelNum[Characteristic.AirQuality.POOR]=100000; + } else { + Serv.levelTxt=[]; + Serv.levelTxt[Characteristic.AirQuality.EXCELLENT]="Excellent"; + Serv.levelTxt[Characteristic.AirQuality.GOOD]="Bon"; + Serv.levelTxt[Characteristic.AirQuality.FAIR]="Moyen"; + Serv.levelTxt[Characteristic.AirQuality.INFERIOR]="Inférieur"; + Serv.levelTxt[Characteristic.AirQuality.POOR]="Faible"; + } + + Serv.cmd_id = cmd.CO2.id; + Serv.eqID = eqLogic.id; + Serv.subtype = 'CO2'; + Serv.subtype = Serv.subtype || ''; + Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; + const uniteCO2 = Serv.infos.CO2.unite ? Serv.infos.CO2.unite : ''; + if(uniteCO2) { + const propsCO2 = {}; + propsCO2.unit=uniteCO2; + Serv.getCharacteristic(Characteristic.CarbonDioxideLevel).setProps(propsCO2); + } + + if(this.fakegato && !eqLogic.hasLogging) { + HBservice.characteristics.push(Characteristic.PPM); + Serv.addCharacteristic(Characteristic.PPM); + const unite = Serv.infos.CO2.unite ? Serv.infos.CO2.unite : ''; + if(unite) { + const props = {}; + props.unit=unite; + Serv.getCharacteristic(Characteristic.PPM).setProps(props); } - - HBservices.push(HBservice); - HBservice = null; + HBservice.characteristics.push(Characteristic.AQExtraCharacteristic); + Serv.addCharacteristic(Characteristic.AQExtraCharacteristic); + + eqLogic.loggingService ={type:"room", options:{storage:'fs',path:this.pathHomebridgeConf},subtype:Serv.eqID+'-history',cmd_id:Serv.eqID}; + eqLogic.hasLogging=true; } + + HBservices.push(HBservice); + HBservice = null; }); } if (eqLogic.services.AirQualityCustom) { - eqLogic.services.AirQualityCustom.forEach(function(cmd) { - if (cmd.Index) { - HBservice = { - controlService : new Service.AirQualitySensor(eqLogic.name), - characteristics : [Characteristic.AirQuality], - }; - const Serv = HBservice.controlService; - Serv.eqLogic=eqLogic; - Serv.actions={}; - Serv.infos={}; - Serv.infos.Index=cmd.Index; - - if(eqLogic.customizedValues && cmd.Index.subType=='numeric') { - Serv.levelNum=[]; - if(eqLogic.customizedValues.EXCELLENT && eqLogic.customizedValues.EXCELLENT != "NOT") { - Serv.levelNum[Characteristic.AirQuality.EXCELLENT] = parseInt(eqLogic.customizedValues.EXCELLENT); - } else { - that.log('warn',"Pas de config de la valeur 'Excellent', on la défini sur 50"); - Serv.levelNum[Characteristic.AirQuality.EXCELLENT]=50; - } - if(eqLogic.customizedValues.GOOD && eqLogic.customizedValues.GOOD != "NOT") { - Serv.levelNum[Characteristic.AirQuality.GOOD] = parseInt(eqLogic.customizedValues.GOOD); - } else { - that.log('warn',"Pas de config de la valeur 'Bon', on la défini sur 100"); - Serv.levelNum[Characteristic.AirQuality.GOOD]=100; - } - if(eqLogic.customizedValues.FAIR && eqLogic.customizedValues.FAIR != "NOT") { - Serv.levelNum[Characteristic.AirQuality.FAIR] = parseInt(eqLogic.customizedValues.FAIR); - } else { - that.log('warn',"Pas de config de la valeur 'Moyen', on la défini sur 150"); - Serv.levelNum[Characteristic.AirQuality.FAIR]=150; - } - if(eqLogic.customizedValues.INFERIOR && eqLogic.customizedValues.INFERIOR != "NOT") { - Serv.levelNum[Characteristic.AirQuality.INFERIOR] = parseInt(eqLogic.customizedValues.INFERIOR); - } else { - that.log('warn',"Pas de config de la valeur 'Inférieur', on la défini sur 200"); - Serv.levelNum[Characteristic.AirQuality.INFERIOR]=200; - } - if(eqLogic.customizedValues.POOR && eqLogic.customizedValues.POOR != "NOT") { - Serv.levelNum[Characteristic.AirQuality.POOR] = parseInt(eqLogic.customizedValues.POOR); - } else { - that.log('warn',"Pas de config de la valeur 'Faible', on la défini sur 1000"); - Serv.levelNum[Characteristic.AirQuality.POOR]=1000; - } - } else if(that.myPlugin == "homebridge") { - that.log('warn',"Pas de config numérique des valeurs que qualité d'air"); + eqLogic.services.AirQualityCustom.forEach((cmd) => { + if (!cmd.Index) {return;} + HBservice = { + controlService : new Service.AirQualitySensor(eqLogic.name), + characteristics : [Characteristic.AirQuality], + }; + const Serv = HBservice.controlService; + Serv.eqLogic=eqLogic; + Serv.actions={}; + Serv.infos={}; + Serv.infos.Index=cmd.Index; + + if(eqLogic.customizedValues && cmd.Index.subType=='numeric') { + Serv.levelNum=[]; + if(eqLogic.customizedValues.EXCELLENT && eqLogic.customizedValues.EXCELLENT != "NOT") { + Serv.levelNum[Characteristic.AirQuality.EXCELLENT] = parseInt(eqLogic.customizedValues.EXCELLENT); + } else { + this.log('warn',"Pas de config de la valeur 'Excellent', on la défini sur 50"); + Serv.levelNum[Characteristic.AirQuality.EXCELLENT]=50; } + if(eqLogic.customizedValues.GOOD && eqLogic.customizedValues.GOOD != "NOT") { + Serv.levelNum[Characteristic.AirQuality.GOOD] = parseInt(eqLogic.customizedValues.GOOD); + } else { + this.log('warn',"Pas de config de la valeur 'Bon', on la défini sur 100"); + Serv.levelNum[Characteristic.AirQuality.GOOD]=100; + } + if(eqLogic.customizedValues.FAIR && eqLogic.customizedValues.FAIR != "NOT") { + Serv.levelNum[Characteristic.AirQuality.FAIR] = parseInt(eqLogic.customizedValues.FAIR); + } else { + this.log('warn',"Pas de config de la valeur 'Moyen', on la défini sur 150"); + Serv.levelNum[Characteristic.AirQuality.FAIR]=150; + } + if(eqLogic.customizedValues.INFERIOR && eqLogic.customizedValues.INFERIOR != "NOT") { + Serv.levelNum[Characteristic.AirQuality.INFERIOR] = parseInt(eqLogic.customizedValues.INFERIOR); + } else { + this.log('warn',"Pas de config de la valeur 'Inférieur', on la défini sur 200"); + Serv.levelNum[Characteristic.AirQuality.INFERIOR]=200; + } + if(eqLogic.customizedValues.POOR && eqLogic.customizedValues.POOR != "NOT") { + Serv.levelNum[Characteristic.AirQuality.POOR] = parseInt(eqLogic.customizedValues.POOR); + } else { + this.log('warn',"Pas de config de la valeur 'Faible', on la défini sur 1000"); + Serv.levelNum[Characteristic.AirQuality.POOR]=1000; + } + } else if(this.myPlugin == "homebridge") { + this.log('warn',"Pas de config numérique des valeurs que qualité d'air"); + } - - Serv.cmd_id = cmd.Index.id; - Serv.eqID = eqLogic.id; - Serv.subtype = 'AirQualityCustom'; - Serv.subtype = Serv.subtype || ''; - Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; - - if(that.fakegato && !eqLogic.hasLogging) { - HBservice.characteristics.push(Characteristic.VOCDensity); - Serv.addCharacteristic(Characteristic.VOCDensity); - const unite = Serv.infos.Index.unite ? Serv.infos.Index.unite : ''; - if(unite) { - const props = {}; - props.unit=unite; - if(Serv.levelNum) {props.maxValue=parseInt(Serv.levelNum[Characteristic.AirQuality.POOR]*4.57);} - Serv.getCharacteristic(Characteristic.VOCDensity).setProps(props); - } - HBservice.characteristics.push(Characteristic.AQExtraCharacteristic); - Serv.addCharacteristic(Characteristic.AQExtraCharacteristic); - - eqLogic.loggingService ={type:"room2", options:{storage:'fs',path:that.pathHomebridgeConf},subtype:Serv.eqID+'-history',cmd_id:Serv.eqID}; - eqLogic.hasLogging=true; + + Serv.cmd_id = cmd.Index.id; + Serv.eqID = eqLogic.id; + Serv.subtype = 'AirQualityCustom'; + Serv.subtype = Serv.subtype || ''; + Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; + + if(this.fakegato && !eqLogic.hasLogging) { + HBservice.characteristics.push(Characteristic.VOCDensity); + Serv.addCharacteristic(Characteristic.VOCDensity); + const unite = Serv.infos.Index.unite ? Serv.infos.Index.unite : ''; + if(unite) { + const props = {}; + props.unit=unite; + if(Serv.levelNum) {props.maxValue=parseInt(Serv.levelNum[Characteristic.AirQuality.POOR]*4.57);} + Serv.getCharacteristic(Characteristic.VOCDensity).setProps(props); } - - HBservices.push(HBservice); - HBservice = null; + HBservice.characteristics.push(Characteristic.AQExtraCharacteristic); + Serv.addCharacteristic(Characteristic.AQExtraCharacteristic); + + eqLogic.loggingService ={type:"room2", options:{storage:'fs',path:this.pathHomebridgeConf},subtype:Serv.eqID+'-history',cmd_id:Serv.eqID}; + eqLogic.hasLogging=true; } + + HBservices.push(HBservice); + HBservice = null; }); } if (eqLogic.services.AirQuality) { - eqLogic.services.AirQuality.forEach(function(cmd) { - if (cmd.Index) { - HBservice = { - controlService : new Service.AirQualitySensor(eqLogic.name), - characteristics : [Characteristic.AirQuality], - }; - const Serv = HBservice.controlService; - Serv.eqLogic=eqLogic; - Serv.actions={}; - Serv.infos={}; - Serv.infos.Index=cmd.Index; - eqServicesCopy.AirQuality.forEach(function(cmd2) { - if (cmd2.PM25) { - Serv.infos.PM25= cmd2.PM25; - } - }); - // if there is a PM2.5 density, display it - if(Serv.infos.PM25) { - HBservice.characteristics.push(Characteristic.PM2_5Density); - Serv.addCharacteristic(Characteristic.PM2_5Density); - } - // AQI Generic - HBservice.characteristics.push(Characteristic.AQI); - Serv.addCharacteristic(Characteristic.AQI); - Serv.getCharacteristic(Characteristic.AQI).displayName = cmd.Index.name; - - if(cmd.Index.subType=='numeric') { - Serv.levelNum=[]; - Serv.levelNum[Characteristic.AirQuality.EXCELLENT]=50; - Serv.levelNum[Characteristic.AirQuality.GOOD]=100; - Serv.levelNum[Characteristic.AirQuality.FAIR]=150; - Serv.levelNum[Characteristic.AirQuality.INFERIOR]=200; - Serv.levelNum[Characteristic.AirQuality.POOR]=1000; - } else { - Serv.levelTxt=[]; - Serv.levelTxt[Characteristic.AirQuality.EXCELLENT]="Excellent"; - Serv.levelTxt[Characteristic.AirQuality.GOOD]="Bon"; - Serv.levelTxt[Characteristic.AirQuality.FAIR]="Moyen"; - Serv.levelTxt[Characteristic.AirQuality.INFERIOR]="Inférieur"; - Serv.levelTxt[Characteristic.AirQuality.POOR]="Faible"; - } - Serv.cmd_id = cmd.Index.id; - Serv.eqID = eqLogic.id; - Serv.subtype = 'AQI'; - Serv.subtype = Serv.subtype || ''; - Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; - HBservices.push(HBservice); - HBservice = null; - } + eqLogic.services.AirQuality.forEach((cmd) => { + if (!cmd.Index) {return;} + HBservice = { + controlService : new Service.AirQualitySensor(eqLogic.name), + characteristics : [Characteristic.AirQuality], + }; + const Serv = HBservice.controlService; + Serv.eqLogic=eqLogic; + Serv.actions={}; + Serv.infos={}; + Serv.infos.Index=cmd.Index; + eqServicesCopy.AirQuality.forEach((cmd2) => { + if (cmd2.PM25) { + Serv.infos.PM25= cmd2.PM25; + } + }); + // if there is a PM2.5 density, display it + if(Serv.infos.PM25) { + HBservice.characteristics.push(Characteristic.PM2_5Density); + Serv.addCharacteristic(Characteristic.PM2_5Density); + } + // AQI Generic + HBservice.characteristics.push(Characteristic.AQI); + Serv.addCharacteristic(Characteristic.AQI); + Serv.getCharacteristic(Characteristic.AQI).displayName = cmd.Index.name; + + if(cmd.Index.subType=='numeric') { + Serv.levelNum=[]; + Serv.levelNum[Characteristic.AirQuality.EXCELLENT]=50; + Serv.levelNum[Characteristic.AirQuality.GOOD]=100; + Serv.levelNum[Characteristic.AirQuality.FAIR]=150; + Serv.levelNum[Characteristic.AirQuality.INFERIOR]=200; + Serv.levelNum[Characteristic.AirQuality.POOR]=1000; + } else { + Serv.levelTxt=[]; + Serv.levelTxt[Characteristic.AirQuality.EXCELLENT]="Excellent"; + Serv.levelTxt[Characteristic.AirQuality.GOOD]="Bon"; + Serv.levelTxt[Characteristic.AirQuality.FAIR]="Moyen"; + Serv.levelTxt[Characteristic.AirQuality.INFERIOR]="Inférieur"; + Serv.levelTxt[Characteristic.AirQuality.POOR]="Faible"; + } + Serv.cmd_id = cmd.Index.id; + Serv.eqID = eqLogic.id; + Serv.subtype = 'AQI'; + Serv.subtype = Serv.subtype || ''; + Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; + HBservices.push(HBservice); + HBservice = null; }); } if (eqLogic.services.presence) { - eqLogic.services.presence.forEach(function(cmd) { - if (cmd.presence) { - let SensorName=eqLogic.name; - if(eqLogic.numDetector>1) { - that.log('debug',"Detecteurs multiples dans même équipement, il y en a "+eqLogic.numDetector); - SensorName=cmd.presence.name; - } - HBservice = { - controlService : new Service.MotionSensor(SensorName), - characteristics : [Characteristic.MotionDetected], - }; - const Serv = HBservice.controlService; - if(eqLogic.numDetector>1) { - that.log('debug',"Nom du détecteur (multi) : "+SensorName); - Serv.getCharacteristic(Characteristic.MotionDetected).displayName = SensorName; - - Serv.ConfiguredName=SensorName; - HBservice.characteristics.push(Characteristic.ConfiguredName); - Serv.addCharacteristic(Characteristic.ConfiguredName); - Serv.getCharacteristic(Characteristic.ConfiguredName).setValue(SensorName); - } - Serv.eqLogic=eqLogic; - Serv.actions={}; - Serv.infos={}; - Serv.infos.presence=cmd.presence; - Serv.invertBinary=0; - if(cmd.presence.display && cmd.presence.display.invertBinary != undefined) { - Serv.invertBinary=cmd.presence.display.invertBinary; - } - // add Active, Tampered and Defect Characteristics if needed - HBservice=that.createStatusCharact(HBservice,eqServicesCopy); - - Serv.cmd_id = cmd.presence.id; - Serv.eqID = eqLogic.id; - Serv.subtype = Serv.subtype || ''; - Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; + eqLogic.services.presence.forEach((cmd) => { + if (!cmd.presence) {return;} + let SensorName=eqLogic.name; + if(eqLogic.numDetector>1) { + this.log('debug',"Detecteurs multiples dans même équipement, il y en a "+eqLogic.numDetector); + SensorName=cmd.presence.name; + } + HBservice = { + controlService : new Service.MotionSensor(SensorName), + characteristics : [Characteristic.MotionDetected], + }; + const Serv = HBservice.controlService; + if(eqLogic.numDetector>1) { + this.log('debug',"Nom du détecteur (multi) : "+SensorName); + Serv.getCharacteristic(Characteristic.MotionDetected).displayName = SensorName; - if(that.fakegato && !eqLogic.hasLogging) { - HBservice.characteristics.push(Characteristic.Sensitivity,Characteristic.Duration,Characteristic.LastActivation); - Serv.addOptionalCharacteristic(Characteristic.Sensitivity); - Serv.addOptionalCharacteristic(Characteristic.Duration); - Serv.addOptionalCharacteristic(Characteristic.LastActivation); + Serv.ConfiguredName=SensorName; + HBservice.characteristics.push(Characteristic.ConfiguredName); + Serv.addCharacteristic(Characteristic.ConfiguredName); + Serv.getCharacteristic(Characteristic.ConfiguredName).setValue(SensorName); + } + Serv.eqLogic=eqLogic; + Serv.actions={}; + Serv.infos={}; + Serv.infos.presence=cmd.presence; + Serv.invertBinary=0; + if(cmd.presence.display && cmd.presence.display.invertBinary != undefined) { + Serv.invertBinary=cmd.presence.display.invertBinary; + } + // add Active, Tampered and Defect Characteristics if needed + HBservice=this.createStatusCharact(HBservice,eqServicesCopy); + + Serv.cmd_id = cmd.presence.id; + Serv.eqID = eqLogic.id; + Serv.subtype = Serv.subtype || ''; + Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; + + if(this.fakegato && !eqLogic.hasLogging) { + HBservice.characteristics.push(Characteristic.Sensitivity,Characteristic.Duration,Characteristic.LastActivation); + Serv.addOptionalCharacteristic(Characteristic.Sensitivity); + Serv.addOptionalCharacteristic(Characteristic.Duration); + Serv.addOptionalCharacteristic(Characteristic.LastActivation); - // eqLogic.loggingService = {type:"motion", options:{storage:'googleDrive',folder:'fakegato',keyPath:'/home/pi/.homebridge/'},subtype:Serv.eqID+'-history',cmd_id:Serv.eqID}; - eqLogic.loggingService = {type:"motion", options:{storage:'fs',path:that.pathHomebridgeConf},subtype:Serv.eqID+'-history',cmd_id:Serv.eqID}; + // eqLogic.loggingService = {type:"motion", options:{storage:'googleDrive',folder:'fakegato',keyPath:'/home/pi/.homebridge/'},subtype:Serv.eqID+'-history',cmd_id:Serv.eqID}; + eqLogic.loggingService = {type:"motion", options:{storage:'fs',path:this.pathHomebridgeConf},subtype:Serv.eqID+'-history',cmd_id:Serv.eqID}; - eqLogic.hasLogging=true; - } - - HBservices.push(HBservice); - HBservice = null; + eqLogic.hasLogging=true; } + + HBservices.push(HBservice); + HBservice = null; }); } if (eqLogic.services.occupancy) { - eqLogic.services.occupancy.forEach(function(cmd) { - if (cmd.occupancy) { - let SensorName=eqLogic.name; - if(eqLogic.numDetector>1) { - that.log('debug',"Detecteurs occupancy multiples dans même équipement, il y en a "+eqLogic.numDetector); - SensorName=cmd.occupancy.name; - } - HBservice = { - controlService : new Service.OccupancySensor(SensorName), - characteristics : [Characteristic.OccupancyDetected], - }; - const Serv = HBservice.controlService; - if(eqLogic.numDetector>1) { - that.log('debug',"Nom du détecteur (multi) : "+SensorName); - Serv.getCharacteristic(Characteristic.OccupancyDetected).displayName = SensorName; - - Serv.ConfiguredName=SensorName; - HBservice.characteristics.push(Characteristic.ConfiguredName); - Serv.addCharacteristic(Characteristic.ConfiguredName); - Serv.getCharacteristic(Characteristic.ConfiguredName).setValue(SensorName); - } - Serv.eqLogic=eqLogic; - Serv.actions={}; - Serv.infos={}; - Serv.infos.occupancy=cmd.occupancy; - Serv.invertBinary=0; - if(cmd.occupancy.display && cmd.occupancy.display.invertBinary != undefined) { - Serv.invertBinary=cmd.occupancy.display.invertBinary; - } - // add Active, Tampered and Defect Characteristics if needed - HBservice=that.createStatusCharact(HBservice,eqServicesCopy); - - Serv.cmd_id = cmd.occupancy.id; - Serv.eqID = eqLogic.id; - Serv.subtype = Serv.subtype || ''; - Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; - HBservices.push(HBservice); - HBservice = null; - } + eqLogic.services.occupancy.forEach((cmd) => { + if (!cmd.occupancy) {return;} + let SensorName=eqLogic.name; + if(eqLogic.numDetector>1) { + this.log('debug',"Detecteurs occupancy multiples dans même équipement, il y en a "+eqLogic.numDetector); + SensorName=cmd.occupancy.name; + } + HBservice = { + controlService : new Service.OccupancySensor(SensorName), + characteristics : [Characteristic.OccupancyDetected], + }; + const Serv = HBservice.controlService; + if(eqLogic.numDetector>1) { + this.log('debug',"Nom du détecteur (multi) : "+SensorName); + Serv.getCharacteristic(Characteristic.OccupancyDetected).displayName = SensorName; + + Serv.ConfiguredName=SensorName; + HBservice.characteristics.push(Characteristic.ConfiguredName); + Serv.addCharacteristic(Characteristic.ConfiguredName); + Serv.getCharacteristic(Characteristic.ConfiguredName).setValue(SensorName); + } + Serv.eqLogic=eqLogic; + Serv.actions={}; + Serv.infos={}; + Serv.infos.occupancy=cmd.occupancy; + Serv.invertBinary=0; + if(cmd.occupancy.display && cmd.occupancy.display.invertBinary != undefined) { + Serv.invertBinary=cmd.occupancy.display.invertBinary; + } + // add Active, Tampered and Defect Characteristics if needed + HBservice=this.createStatusCharact(HBservice,eqServicesCopy); + + Serv.cmd_id = cmd.occupancy.id; + Serv.eqID = eqLogic.id; + Serv.subtype = Serv.subtype || ''; + Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; + HBservices.push(HBservice); + HBservice = null; }); } if (eqLogic.services.generic) { - eqLogic.services.generic.forEach(function(cmd) { - if (cmd.state) { - HBservice = { - controlService : new Service.CustomService(cmd.state.name), - characteristics : [], - }; - const Serv = HBservice.controlService; - Serv.eqLogic=eqLogic; - Serv.actions={}; - Serv.infos={}; - Serv.infos.state=cmd.state; - // add Active, Tampered and Defect Characteristics if needed - HBservice=that.createStatusCharact(HBservice,eqServicesCopy); + eqLogic.services.generic.forEach((cmd) => { + if (!cmd.state) {return;} + HBservice = { + controlService : new Service.CustomService(cmd.state.name), + characteristics : [], + }; + const Serv = HBservice.controlService; + Serv.eqLogic=eqLogic; + Serv.actions={}; + Serv.infos={}; + Serv.infos.state=cmd.state; + // add Active, Tampered and Defect Characteristics if needed + HBservice=this.createStatusCharact(HBservice,eqServicesCopy); + + var props = {}; + var unite = ''; + if(cmd.state.subType=="numeric") { + this.log('debug','Le générique',cmd.state.name,'est un numérique'); + // test if default value is Float or Int ? + var CharactToSet=Characteristic.GenericFLOAT; + var NumericGenericType='float'; + if(cmd.state.currentValue.toString().indexOf('.') == -1) { + CharactToSet=Characteristic.GenericINT; + NumericGenericType='int'; + } + this.log('debug','Sur base de sa valeur actuelle',cmd.state.currentValue,', on determine un type :',NumericGenericType); + HBservice.characteristics.push(CharactToSet); + Serv.addCharacteristic(CharactToSet); + Serv.getCharacteristic(CharactToSet).displayName = cmd.state.name; - var props = {}; - var unite = ''; - if(cmd.state.subType=="numeric") { - that.log('debug','Le générique',cmd.state.name,'est un numérique'); - // test if default value is Float or Int ? - var CharactToSet=Characteristic.GenericFLOAT; - var NumericGenericType='float'; - if(cmd.state.currentValue.toString().indexOf('.') == -1) { - CharactToSet=Characteristic.GenericINT; - NumericGenericType='int'; - } - that.log('debug','Sur base de sa valeur actuelle',cmd.state.currentValue,', on determine un type :',NumericGenericType); - HBservice.characteristics.push(CharactToSet); - Serv.addCharacteristic(CharactToSet); - Serv.getCharacteristic(CharactToSet).displayName = cmd.state.name; - - unite = cmd.state.unite ? cmd.state.unite : ''; - if(unite) {props.unit=unite;} - if(cmd.state.configuration) { - if(NumericGenericType=='float'){ - if(cmd.state.configuration.maxValue != null && cmd.state.configuration.maxValue != undefined && cmd.state.configuration.maxValue != "") {props.maxValue = parseFloat(cmd.state.configuration.maxValue);} - if(cmd.state.configuration.minValue != null && cmd.state.configuration.minValue != undefined && cmd.state.configuration.minValue != "") {props.minValue = parseFloat(cmd.state.configuration.minValue);} - } else if (NumericGenericType=='int'){ - if(cmd.state.configuration.maxValue != null && cmd.state.configuration.maxValue != undefined && cmd.state.configuration.maxValue != "") {props.maxValue = parseInt(cmd.state.configuration.maxValue);} - if(cmd.state.configuration.minValue != null && cmd.state.configuration.minValue != undefined && cmd.state.configuration.minValue != "") {props.minValue = parseInt(cmd.state.configuration.minValue);} - } - } - if(Object.keys(props).length !== 0) { - that.log('debug','On lui set les props suivants :',props); - Serv.getCharacteristic(CharactToSet).setProps(props); - } - } else if (cmd.state.subType=="binary") { - that.log('debug','Le générique',cmd.state.name,'est un booléen'); - HBservice.characteristics.push(Characteristic.GenericBOOL); - Serv.addCharacteristic(Characteristic.GenericBOOL); - Serv.getCharacteristic(Characteristic.GenericBOOL).displayName = cmd.state.name; - } else if (cmd.state.subType=="string" || cmd.state.subType=="other") { - that.log('debug','Le générique',cmd.state.name,'est une chaîne'); - HBservice.characteristics.push(Characteristic.GenericSTRING); - Serv.addCharacteristic(Characteristic.GenericSTRING); - Serv.getCharacteristic(Characteristic.GenericSTRING).displayName = cmd.state.name; - - unite = cmd.state.unite ? cmd.state.unite : ''; - if(unite) {props.unit=unite;} - if(Object.keys(props).length !== 0) { - that.log('debug','On lui set les props suivants :',props); - Serv.getCharacteristic(Characteristic.GenericSTRING).setProps(props); - } - } - Serv.cmd_id = cmd.state.id; - Serv.eqID = eqLogic.id; - Serv.subtype = Serv.subtype || ''; - Serv.subtype = eqLogic.id + '-' + Serv.cmd_id +'-' + Serv.subtype; - HBservices.push(HBservice); - HBservice = null; - } + unite = cmd.state.unite ? cmd.state.unite : ''; + if(unite) {props.unit=unite;} + if(cmd.state.configuration) { + if(NumericGenericType=='float'){ + if(cmd.state.configuration.maxValue != null && cmd.state.configuration.maxValue != undefined && cmd.state.configuration.maxValue != "") {props.maxValue = parseFloat(cmd.state.configuration.maxValue);} + if(cmd.state.configuration.minValue != null && cmd.state.configuration.minValue != undefined && cmd.state.configuration.minValue != "") {props.minValue = parseFloat(cmd.state.configuration.minValue);} + } else if (NumericGenericType=='int'){ + if(cmd.state.configuration.maxValue != null && cmd.state.configuration.maxValue != undefined && cmd.state.configuration.maxValue != "") {props.maxValue = parseInt(cmd.state.configuration.maxValue);} + if(cmd.state.configuration.minValue != null && cmd.state.configuration.minValue != undefined && cmd.state.configuration.minValue != "") {props.minValue = parseInt(cmd.state.configuration.minValue);} + } + } + if(Object.keys(props).length !== 0) { + this.log('debug','On lui set les props suivants :',props); + Serv.getCharacteristic(CharactToSet).setProps(props); + } + } else if (cmd.state.subType=="binary") { + this.log('debug','Le générique',cmd.state.name,'est un booléen'); + HBservice.characteristics.push(Characteristic.GenericBOOL); + Serv.addCharacteristic(Characteristic.GenericBOOL); + Serv.getCharacteristic(Characteristic.GenericBOOL).displayName = cmd.state.name; + } else if (cmd.state.subType=="string" || cmd.state.subType=="other") { + this.log('debug','Le générique',cmd.state.name,'est une chaîne'); + HBservice.characteristics.push(Characteristic.GenericSTRING); + Serv.addCharacteristic(Characteristic.GenericSTRING); + Serv.getCharacteristic(Characteristic.GenericSTRING).displayName = cmd.state.name; + + unite = cmd.state.unite ? cmd.state.unite : ''; + if(unite) {props.unit=unite;} + if(Object.keys(props).length !== 0) { + this.log('debug','On lui set les props suivants :',props); + Serv.getCharacteristic(Characteristic.GenericSTRING).setProps(props); + } + } + Serv.cmd_id = cmd.state.id; + Serv.eqID = eqLogic.id; + Serv.subtype = Serv.subtype || ''; + Serv.subtype = eqLogic.id + '-' + Serv.cmd_id +'-' + Serv.subtype; + HBservices.push(HBservice); + HBservice = null; }); } if (eqLogic.services.uv) { - eqLogic.services.uv.forEach(function(cmd) { - if (cmd.uv) { - HBservice = { - controlService : new Service.WeatherService(eqLogic.name), - characteristics : [Characteristic.UVIndex], - }; - const Serv = HBservice.controlService; - Serv.eqLogic=eqLogic; - Serv.actions={}; - Serv.infos={}; - Serv.infos.uv=cmd.uv; - Serv.cmd_id = cmd.uv.id; - Serv.eqID = eqLogic.id; - Serv.subtype = Serv.subtype || ''; - Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; - HBservices.push(HBservice); - HBservice = null; - } + eqLogic.services.uv.forEach((cmd) => { + if (!cmd.uv) {return;} + HBservice = { + controlService : new Service.WeatherService(eqLogic.name), + characteristics : [Characteristic.UVIndex], + }; + const Serv = HBservice.controlService; + Serv.eqLogic=eqLogic; + Serv.actions={}; + Serv.infos={}; + Serv.infos.uv=cmd.uv; + Serv.cmd_id = cmd.uv.id; + Serv.eqID = eqLogic.id; + Serv.subtype = Serv.subtype || ''; + Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; + HBservices.push(HBservice); + HBservice = null; }); } if (eqLogic.services.speaker) { - eqLogic.services.speaker.forEach(function(cmd) { - if (cmd.volume) { - HBservice = { - controlService : new Service.Speaker(eqLogic.name), - characteristics : [Characteristic.Mute,Characteristic.Volume], - }; - const Serv = HBservice.controlService; - Serv.eqLogic=eqLogic; - Serv.actions={}; - Serv.infos={}; - Serv.infos.volume=cmd.volume; - eqServicesCopy.speaker.forEach(function(cmd2) { - if (cmd2.mute_toggle) { - Serv.actions.mute_toggle = cmd2.mute_toggle; - } else if (cmd2.mute_on) { - Serv.actions.mute_on = cmd2.mute_on; - } else if (cmd2.mute_off) { - Serv.actions.mute_off = cmd2.mute_off; - } else if (cmd2.set_volume) { - Serv.actions.set_volume = cmd2.set_volume; - } else if (cmd2.mute) { - Serv.infos.mute=cmd2.mute; - } - }); - if(!Serv.actions.set_volume) {that.log('warn','Pas de type générique "Action/Haut-Parleur Volume"');} - if(!Serv.actions.mute_toggle && !Serv.actions.mute_on && Serv.actions.mute_off) {that.log('warn','Pas de type générique "Action/Haut-Parleur Mute"');} - if(!Serv.actions.mute_toggle && Serv.actions.mute_on && !Serv.actions.mute_off) {that.log('warn','Pas de type générique "Action/Haut-Parleur UnMute"');} - if(!Serv.actions.mute_toggle && !Serv.actions.mute_on && !Serv.actions.mute_off) {that.log('warn','Pas de type générique "Action/Haut-Parleur Toggle Mute" / "Action/Haut-Parleur Mute" / "Action/Haut-Parleur UnMute"');} - Serv.cmd_id = cmd.volume.id; - Serv.eqID = eqLogic.id; - Serv.subtype = Serv.subtype || ''; - Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; - HBservices.push(HBservice); - } + eqLogic.services.speaker.forEach((cmd) => { + if (!cmd.volume) {return;} + HBservice = { + controlService : new Service.Speaker(eqLogic.name), + characteristics : [Characteristic.Mute,Characteristic.Volume], + }; + const Serv = HBservice.controlService; + Serv.eqLogic=eqLogic; + Serv.actions={}; + Serv.infos={}; + Serv.infos.volume=cmd.volume; + eqServicesCopy.speaker.forEach((cmd2) => { + if (cmd2.mute_toggle) { + Serv.actions.mute_toggle = cmd2.mute_toggle; + } else if (cmd2.mute_on) { + Serv.actions.mute_on = cmd2.mute_on; + } else if (cmd2.mute_off) { + Serv.actions.mute_off = cmd2.mute_off; + } else if (cmd2.set_volume) { + Serv.actions.set_volume = cmd2.set_volume; + } else if (cmd2.mute) { + Serv.infos.mute=cmd2.mute; + } + }); + if(!Serv.actions.set_volume) {this.log('warn','Pas de type générique "Action/Haut-Parleur Volume"');} + if(!Serv.actions.mute_toggle && !Serv.actions.mute_on && Serv.actions.mute_off) {this.log('warn','Pas de type générique "Action/Haut-Parleur Mute"');} + if(!Serv.actions.mute_toggle && Serv.actions.mute_on && !Serv.actions.mute_off) {this.log('warn','Pas de type générique "Action/Haut-Parleur UnMute"');} + if(!Serv.actions.mute_toggle && !Serv.actions.mute_on && !Serv.actions.mute_off) {this.log('warn','Pas de type générique "Action/Haut-Parleur Toggle Mute" / "Action/Haut-Parleur Mute" / "Action/Haut-Parleur UnMute"');} + Serv.cmd_id = cmd.volume.id; + Serv.eqID = eqLogic.id; + Serv.subtype = Serv.subtype || ''; + Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; + HBservices.push(HBservice); }); if(!HBservice) { - that.log('warn','Pas de type générique "Info/Haut-Parleur Volume"'); + this.log('warn','Pas de type générique "Info/Haut-Parleur Volume"'); } else { HBservice = null; } } if (eqLogic.services.temperature) { - eqLogic.services.temperature.forEach(function(cmd) { - if (cmd.temperature) { - HBservice = { - controlService : new Service.TemperatureSensor(eqLogic.name), - characteristics : [Characteristic.CurrentTemperature], - }; - const Serv = HBservice.controlService; - Serv.eqLogic=eqLogic; - Serv.actions={}; - Serv.infos={}; - Serv.infos.temperature=cmd.temperature; - - HBservice.characteristics.push(Characteristic.TemperatureDisplayUnits); - Serv.addOptionalCharacteristic(Characteristic.TemperatureDisplayUnits); - Serv.getCharacteristic(Characteristic.TemperatureDisplayUnits).updateValue(Characteristic.TemperatureDisplayUnits.CELSIUS); - - // add Active, Tampered and Defect Characteristics if needed - HBservice=that.createStatusCharact(HBservice,eqServicesCopy); - - Serv.cmd_id = cmd.temperature.id; - Serv.eqID = eqLogic.id; - Serv.subtype = Serv.subtype || ''; - Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; - if(that.fakegato && !eqLogic.hasLogging) { - eqLogic.loggingService ={type:"weather", options:{storage:'fs',path:that.pathHomebridgeConf},subtype:Serv.eqID+'-history',cmd_id:Serv.eqID}; - eqLogic.hasLogging=true; - } - - HBservices.push(HBservice); - HBservice = null; - } - }); - - } - if (eqLogic.services.humidity) { - eqLogic.services.humidity.forEach(function(cmd) { - if (cmd.humidity) { - HBservice = { - controlService : new Service.HumiditySensor(eqLogic.name), - characteristics : [Characteristic.CurrentRelativeHumidity], - }; - const Serv = HBservice.controlService; - Serv.eqLogic=eqLogic; - Serv.actions={}; - Serv.infos={}; - Serv.infos.humidity=cmd.humidity; - // add Active, Tampered and Defect Characteristics if needed - HBservice=that.createStatusCharact(HBservice,eqServicesCopy); - - Serv.cmd_id = cmd.humidity.id; - Serv.eqID = eqLogic.id; - Serv.subtype = Serv.subtype || ''; - Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; - - if(that.fakegato && !eqLogic.hasLogging) { - eqLogic.loggingService = {type:"weather", options:{storage:'fs',path:that.pathHomebridgeConf},subtype:Serv.eqID+'-history',cmd_id:Serv.eqID}; - eqLogic.hasLogging=true; - } - - HBservices.push(HBservice); - HBservice = null; + eqLogic.services.temperature.forEach((cmd) => { + if (!cmd.temperature) {return;} + HBservice = { + controlService : new Service.TemperatureSensor(eqLogic.name), + characteristics : [Characteristic.CurrentTemperature], + }; + const Serv = HBservice.controlService; + Serv.eqLogic=eqLogic; + Serv.actions={}; + Serv.infos={}; + Serv.infos.temperature=cmd.temperature; + + HBservice.characteristics.push(Characteristic.TemperatureDisplayUnits); + Serv.addOptionalCharacteristic(Characteristic.TemperatureDisplayUnits); + Serv.getCharacteristic(Characteristic.TemperatureDisplayUnits).updateValue(Characteristic.TemperatureDisplayUnits.CELSIUS); + + // add Active, Tampered and Defect Characteristics if needed + HBservice=this.createStatusCharact(HBservice,eqServicesCopy); + + Serv.cmd_id = cmd.temperature.id; + Serv.eqID = eqLogic.id; + Serv.subtype = Serv.subtype || ''; + Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; + if(this.fakegato && !eqLogic.hasLogging) { + eqLogic.loggingService ={type:"weather", options:{storage:'fs',path:this.pathHomebridgeConf},subtype:Serv.eqID+'-history',cmd_id:Serv.eqID}; + eqLogic.hasLogging=true; } - }); - } - if (eqLogic.services.pressure) { - eqLogic.services.pressure.forEach(function(cmd) { - if (cmd.pressure) { - HBservice = { - controlService : new Service.PressureSensor(eqLogic.name), - characteristics : [Characteristic.AirPressure], - }; - const Serv = HBservice.controlService; - Serv.eqLogic=eqLogic; - Serv.actions={}; - Serv.infos={}; - Serv.infos.pressure=cmd.pressure; - Serv.cmd_id = cmd.pressure.id; - Serv.eqID = eqLogic.id; - Serv.subtype = Serv.subtype || ''; - Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; - - if(that.fakegato && !eqLogic.hasLogging) { - eqLogic.loggingService = {type:"weather", options:{storage:'fs',path:that.pathHomebridgeConf},subtype:Serv.eqID+'-history',cmd_id:Serv.eqID}; - eqLogic.hasLogging=true; - } - - HBservices.push(HBservice); - HBservice = null; + + HBservices.push(HBservice); + HBservice = null; + }); + + } + if (eqLogic.services.humidity) { + eqLogic.services.humidity.forEach((cmd) => { + if (!cmd.humidity) {return;} + HBservice = { + controlService : new Service.HumiditySensor(eqLogic.name), + characteristics : [Characteristic.CurrentRelativeHumidity], + }; + const Serv = HBservice.controlService; + Serv.eqLogic=eqLogic; + Serv.actions={}; + Serv.infos={}; + Serv.infos.humidity=cmd.humidity; + // add Active, Tampered and Defect Characteristics if needed + HBservice=this.createStatusCharact(HBservice,eqServicesCopy); + + Serv.cmd_id = cmd.humidity.id; + Serv.eqID = eqLogic.id; + Serv.subtype = Serv.subtype || ''; + Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; + + if(this.fakegato && !eqLogic.hasLogging) { + eqLogic.loggingService = {type:"weather", options:{storage:'fs',path:this.pathHomebridgeConf},subtype:Serv.eqID+'-history',cmd_id:Serv.eqID}; + eqLogic.hasLogging=true; + } + + HBservices.push(HBservice); + HBservice = null; + }); + } + if (eqLogic.services.pressure) { + eqLogic.services.pressure.forEach((cmd) => { + if (!cmd.pressure) {return;} + HBservice = { + controlService : new Service.PressureSensor(eqLogic.name), + characteristics : [Characteristic.AirPressure], + }; + const Serv = HBservice.controlService; + Serv.eqLogic=eqLogic; + Serv.actions={}; + Serv.infos={}; + Serv.infos.pressure=cmd.pressure; + Serv.cmd_id = cmd.pressure.id; + Serv.eqID = eqLogic.id; + Serv.subtype = Serv.subtype || ''; + Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; + + if(this.fakegato && !eqLogic.hasLogging) { + eqLogic.loggingService = {type:"weather", options:{storage:'fs',path:this.pathHomebridgeConf},subtype:Serv.eqID+'-history',cmd_id:Serv.eqID}; + eqLogic.hasLogging=true; } + + HBservices.push(HBservice); + HBservice = null; }); } if (eqLogic.services.smoke) { - eqLogic.services.smoke.forEach(function(cmd) { - if (cmd.smoke) { - HBservice = { - controlService : new Service.SmokeSensor(eqLogic.name), - characteristics : [Characteristic.SmokeDetected], - }; - const Serv = HBservice.controlService; - Serv.eqLogic=eqLogic; - Serv.actions={}; - Serv.infos={}; - Serv.infos.smoke=cmd.smoke; - Serv.invertBinary=0; - if(cmd.smoke.display && cmd.smoke.display.invertBinary != undefined) { - Serv.invertBinary=cmd.smoke.display.invertBinary; - } - // add Active, Tampered and Defect Characteristics if needed - HBservice=that.createStatusCharact(HBservice,eqServicesCopy); - - Serv.cmd_id = cmd.smoke.id; - Serv.eqID = eqLogic.id; - Serv.subtype = Serv.subtype || ''; - Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; - HBservices.push(HBservice); - HBservice = null; - } + eqLogic.services.smoke.forEach((cmd) => { + if (!cmd.smoke) {return;} + HBservice = { + controlService : new Service.SmokeSensor(eqLogic.name), + characteristics : [Characteristic.SmokeDetected], + }; + const Serv = HBservice.controlService; + Serv.eqLogic=eqLogic; + Serv.actions={}; + Serv.infos={}; + Serv.infos.smoke=cmd.smoke; + Serv.invertBinary=0; + if(cmd.smoke.display && cmd.smoke.display.invertBinary != undefined) { + Serv.invertBinary=cmd.smoke.display.invertBinary; + } + // add Active, Tampered and Defect Characteristics if needed + HBservice=this.createStatusCharact(HBservice,eqServicesCopy); + + Serv.cmd_id = cmd.smoke.id; + Serv.eqID = eqLogic.id; + Serv.subtype = Serv.subtype || ''; + Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; + HBservices.push(HBservice); + HBservice = null; }); } if (eqLogic.services.flood) { - eqLogic.services.flood.forEach(function(cmd) { - if (cmd.flood) { - HBservice = { - controlService : new Service.LeakSensor(eqLogic.name), - characteristics : [Characteristic.LeakDetected], - }; - const Serv = HBservice.controlService; - Serv.eqLogic=eqLogic; - Serv.actions={}; - Serv.infos={}; - Serv.infos.flood=cmd.flood; - Serv.invertBinary=0; - if(cmd.flood.display && cmd.flood.display.invertBinary != undefined) { - Serv.invertBinary=cmd.flood.display.invertBinary; - } - // add Active, Tampered and Defect Characteristics if needed - HBservice=that.createStatusCharact(HBservice,eqServicesCopy); - - Serv.cmd_id = cmd.flood.id; - Serv.eqID = eqLogic.id; - Serv.subtype = Serv.subtype || ''; - Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; - HBservices.push(HBservice); - HBservice = null; - } + eqLogic.services.flood.forEach((cmd) => { + if (!cmd.flood) {return;} + HBservice = { + controlService : new Service.LeakSensor(eqLogic.name), + characteristics : [Characteristic.LeakDetected], + }; + const Serv = HBservice.controlService; + Serv.eqLogic=eqLogic; + Serv.actions={}; + Serv.infos={}; + Serv.infos.flood=cmd.flood; + Serv.invertBinary=0; + if(cmd.flood.display && cmd.flood.display.invertBinary != undefined) { + Serv.invertBinary=cmd.flood.display.invertBinary; + } + // add Active, Tampered and Defect Characteristics if needed + HBservice=this.createStatusCharact(HBservice,eqServicesCopy); + + Serv.cmd_id = cmd.flood.id; + Serv.eqID = eqLogic.id; + Serv.subtype = Serv.subtype || ''; + Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; + HBservices.push(HBservice); + HBservice = null; }); } if (eqLogic.services.opening) { - eqLogic.services.opening.forEach(function(cmd) { - if (cmd.opening) { - HBservice = { - controlService : new Service.ContactSensor(eqLogic.name), - characteristics : [Characteristic.ContactSensorState], - }; - const Serv = HBservice.controlService; - Serv.eqLogic=eqLogic; - Serv.actions={}; - Serv.infos={}; - Serv.infos.opening=cmd.opening; - Serv.invertBinary=0; - if(cmd.opening.display && cmd.opening.display.invertBinary != undefined) { - Serv.invertBinary=cmd.opening.display.invertBinary; - } - // add Active, Tampered and Defect Characteristics if needed - HBservice=that.createStatusCharact(HBservice,eqServicesCopy); - - Serv.cmd_id = cmd.opening.id; - Serv.eqID = eqLogic.id; - Serv.subtype = Serv.subtype || ''; - Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; - - if(that.fakegato && !eqLogic.hasLogging) { - // Serv.eqLogic.numberOpened = 0; - HBservice.characteristics.push(Characteristic.TimesOpened,Characteristic.Char118,Characteristic.Char119,Characteristic.ResetTotal,Characteristic.LastActivation); - Serv.addOptionalCharacteristic(Characteristic.TimesOpened); - Serv.addOptionalCharacteristic(Characteristic.Char118); - Serv.addOptionalCharacteristic(Characteristic.Char119); - Serv.addOptionalCharacteristic(Characteristic.ResetTotal); - Serv.addOptionalCharacteristic(Characteristic.LastActivation); - - eqLogic.loggingService = {type:"door", options:{storage:'fs',path:that.pathHomebridgeConf},subtype:Serv.eqID+'-history',cmd_id:Serv.eqID}; - eqLogic.hasLogging=true; - } - - HBservices.push(HBservice); - HBservice = null; + eqLogic.services.opening.forEach((cmd) => { + if (!cmd.opening) {return;} + HBservice = { + controlService : new Service.ContactSensor(eqLogic.name), + characteristics : [Characteristic.ContactSensorState], + }; + const Serv = HBservice.controlService; + Serv.eqLogic=eqLogic; + Serv.actions={}; + Serv.infos={}; + Serv.infos.opening=cmd.opening; + Serv.invertBinary=0; + if(cmd.opening.display && cmd.opening.display.invertBinary != undefined) { + Serv.invertBinary=cmd.opening.display.invertBinary; + } + // add Active, Tampered and Defect Characteristics if needed + HBservice=this.createStatusCharact(HBservice,eqServicesCopy); + + Serv.cmd_id = cmd.opening.id; + Serv.eqID = eqLogic.id; + Serv.subtype = Serv.subtype || ''; + Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; + + if(this.fakegato && !eqLogic.hasLogging) { + // Serv.eqLogic.numberOpened = 0; + HBservice.characteristics.push(Characteristic.TimesOpened,Characteristic.Char118,Characteristic.Char119,Characteristic.ResetTotal,Characteristic.LastActivation); + Serv.addOptionalCharacteristic(Characteristic.TimesOpened); + Serv.addOptionalCharacteristic(Characteristic.Char118); + Serv.addOptionalCharacteristic(Characteristic.Char119); + Serv.addOptionalCharacteristic(Characteristic.ResetTotal); + Serv.addOptionalCharacteristic(Characteristic.LastActivation); + + eqLogic.loggingService = {type:"door", options:{storage:'fs',path:this.pathHomebridgeConf},subtype:Serv.eqID+'-history',cmd_id:Serv.eqID}; + eqLogic.hasLogging=true; } + + HBservices.push(HBservice); + HBservice = null; }); } if (eqLogic.services.brightness) { - eqLogic.services.brightness.forEach(function(cmd) { - if (cmd.brightness) { - HBservice = { - controlService : new Service.LightSensor(eqLogic.name), - characteristics : [Characteristic.CurrentAmbientLightLevel], - }; - const Serv = HBservice.controlService; - Serv.eqLogic=eqLogic; - Serv.actions={}; - Serv.infos={}; - Serv.infos.brightness=cmd.brightness; - // add Active, Tampered and Defect Characteristics if needed - HBservice=that.createStatusCharact(HBservice,eqServicesCopy); - - Serv.cmd_id = cmd.brightness.id; - Serv.eqID = eqLogic.id; - Serv.subtype = Serv.subtype || ''; - Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; - /* if(that.fakegato && !eqLogic.hasLogging) { - // HBservice.characteristics.push(Characteristic.Sensitivity,Characteristic.Duration,Characteristic.LastActivation); + eqLogic.services.brightness.forEach((cmd) => { + if (!cmd.brightness) {return;} + HBservice = { + controlService : new Service.LightSensor(eqLogic.name), + characteristics : [Characteristic.CurrentAmbientLightLevel], + }; + const Serv = HBservice.controlService; + Serv.eqLogic=eqLogic; + Serv.actions={}; + Serv.infos={}; + Serv.infos.brightness=cmd.brightness; + // add Active, Tampered and Defect Characteristics if needed + HBservice=this.createStatusCharact(HBservice,eqServicesCopy); + + Serv.cmd_id = cmd.brightness.id; + Serv.eqID = eqLogic.id; + Serv.subtype = Serv.subtype || ''; + Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; + if(this.fakegato && !eqLogic.hasLogging) { + // HBservice.characteristics.push(Characteristic.Sensitivity,Characteristic.Duration,Characteristic.LastActivation); - // eqLogic.loggingService = {type:"motion", options:{storage:'googleDrive',folder:'fakegato',keyPath:'/home/pi/.homebridge/'},subtype:Serv.eqID+'-history',cmd_id:Serv.eqID}; - eqLogic.loggingService = {type:"custom", options:{storage:'fs',path:that.pathHomebridgeConf},subtype:Serv.eqID+'-history',cmd_id:Serv.eqID}; + // eqLogic.loggingService = {type:"motion", options:{storage:'googleDrive',folder:'fakegato',keyPath:'/home/pi/.homebridge/'},subtype:Serv.eqID+'-history',cmd_id:Serv.eqID}; + eqLogic.loggingService = {type:"custom", options:{storage:'fs',path:this.pathHomebridgeConf},subtype:Serv.eqID+'-history',cmd_id:Serv.eqID}; - eqLogic.hasLogging=true; - } */ - HBservices.push(HBservice); - HBservice = null; + eqLogic.hasLogging=true; } + HBservices.push(HBservice); + HBservice = null; }); } if (eqLogic.services.GarageDoor) { - eqLogic.services.GarageDoor.forEach(function(cmd) { - if (cmd.state) { - HBservice = { - controlService : new Service.GarageDoorOpener(eqLogic.name), - characteristics : [Characteristic.CurrentDoorState, Characteristic.TargetDoorState], - }; - const Serv = HBservice.controlService; - Serv.eqLogic=eqLogic; - Serv.actions={}; - Serv.infos={}; - Serv.infos.state=cmd.state; - eqServicesCopy.GarageDoor.forEach(function(cmd2) { - if (cmd2.on) { - Serv.actions.on = cmd2.on; - } else if (cmd2.off) { - Serv.actions.off = cmd2.off; - } else if (cmd2.toggle) { - Serv.actions.toggle = cmd2.toggle; - } - }); - if(!Serv.actions.toggle && !Serv.actions.on && Serv.actions.off) {that.log('warn','Pas de type générique "Action/Portail ou garage bouton d\'ouverture"');} - if(!Serv.actions.toggle && Serv.actions.on && !Serv.actions.off) {that.log('warn','Pas de type générique "Action/Portail ou garage bouton de fermeture"');} - if(!Serv.actions.toggle && !Serv.actions.on && !Serv.actions.off) {that.log('warn','Pas de type générique ""Action/Portail ou garage bouton toggle" / "Action/Portail ou garage bouton d\'ouverture" / "Action/Portail ou garage bouton de fermeture"');} - - if(eqLogic.customizedValues) { - Serv.customizedValues = eqLogic.customizedValues; + eqLogic.services.GarageDoor.forEach((cmd) => { + if (!cmd.state) {return;} + HBservice = { + controlService : new Service.GarageDoorOpener(eqLogic.name), + characteristics : [Characteristic.CurrentDoorState, Characteristic.TargetDoorState], + }; + const Serv = HBservice.controlService; + Serv.eqLogic=eqLogic; + Serv.actions={}; + Serv.infos={}; + Serv.infos.state=cmd.state; + eqServicesCopy.GarageDoor.forEach((cmd2) => { + if (cmd2.on) { + Serv.actions.on = cmd2.on; + } else if (cmd2.off) { + Serv.actions.off = cmd2.off; + } else if (cmd2.toggle) { + Serv.actions.toggle = cmd2.toggle; } - - // add Active, Tampered and Defect Characteristics if needed - HBservice=that.createStatusCharact(HBservice,eqServicesCopy); - - Serv.cmd_id = cmd.state.id; - Serv.eqID = eqLogic.id; - Serv.subtype = Serv.subtype || ''; - Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; - HBservices.push(HBservice); + }); + if(!Serv.actions.toggle && !Serv.actions.on && Serv.actions.off) {this.log('warn','Pas de type générique "Action/Portail ou garage bouton d\'ouverture"');} + if(!Serv.actions.toggle && Serv.actions.on && !Serv.actions.off) {this.log('warn','Pas de type générique "Action/Portail ou garage bouton de fermeture"');} + if(!Serv.actions.toggle && !Serv.actions.on && !Serv.actions.off) {this.log('warn','Pas de type générique ""Action/Portail ou garage bouton toggle" / "Action/Portail ou garage bouton d\'ouverture" / "Action/Portail ou garage bouton de fermeture"');} + + if(eqLogic.customizedValues) { + Serv.customizedValues = eqLogic.customizedValues; } + + // add Active, Tampered and Defect Characteristics if needed + HBservice=this.createStatusCharact(HBservice,eqServicesCopy); + + Serv.cmd_id = cmd.state.id; + Serv.eqID = eqLogic.id; + Serv.subtype = Serv.subtype || ''; + Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; + HBservices.push(HBservice); }); if(!HBservice) { - that.log('warn','Pas de type générique "Info/Garage état ouvrant" ou "Info/Portail état ouvrant"'); + this.log('warn','Pas de type générique "Info/Garage état ouvrant" ou "Info/Portail état ouvrant"'); } else { HBservice = null; } } if (eqLogic.services.lock) { - eqLogic.services.lock.forEach(function(cmd) { - if (cmd.state) { - HBservice = { - controlService : new Service.LockMechanism(eqLogic.name), - characteristics : [Characteristic.LockCurrentState, Characteristic.LockTargetState], - }; - const Serv = HBservice.controlService; - Serv.eqLogic=eqLogic; - Serv.actions={}; - Serv.infos={}; - Serv.infos.state=cmd.state; - eqServicesCopy.lock.forEach(function(cmd2) { - if (cmd2.on) { - Serv.actions.on = cmd2.on; - } else if (cmd2.off) { - Serv.actions.off = cmd2.off; - } - }); - if(!Serv.actions.on) {that.log('warn','Pas de type générique "Action/Serrure Bouton Ouvrir"');} - // if(!Serv.actions.off) {that.log('warn','Pas de type générique "Action/Serrure Bouton Fermer"');} - - // add Active, Tampered and Defect Characteristics if needed - HBservice=that.createStatusCharact(HBservice,eqServicesCopy); - - Serv.cmd_id = cmd.state.id; - Serv.eqID = eqLogic.id; - Serv.subtype = Serv.subtype || ''; - Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; - HBservices.push(HBservice); - } + eqLogic.services.lock.forEach((cmd) => { + if (!cmd.state) {return;} + HBservice = { + controlService : new Service.LockMechanism(eqLogic.name), + characteristics : [Characteristic.LockCurrentState, Characteristic.LockTargetState], + }; + const Serv = HBservice.controlService; + Serv.eqLogic=eqLogic; + Serv.actions={}; + Serv.infos={}; + Serv.infos.state=cmd.state; + eqServicesCopy.lock.forEach((cmd2) => { + if (cmd2.on) { + Serv.actions.on = cmd2.on; + } else if (cmd2.off) { + Serv.actions.off = cmd2.off; + } + }); + if(!Serv.actions.on) {this.log('warn','Pas de type générique "Action/Serrure Bouton Ouvrir"');} + // if(!Serv.actions.off) {this.log('warn','Pas de type générique "Action/Serrure Bouton Fermer"');} + + // add Active, Tampered and Defect Characteristics if needed + HBservice=this.createStatusCharact(HBservice,eqServicesCopy); + + Serv.cmd_id = cmd.state.id; + Serv.eqID = eqLogic.id; + Serv.subtype = Serv.subtype || ''; + Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; + HBservices.push(HBservice); }); if(!HBservice) { - that.log('warn','Pas de type générique "Info/Serrure Etat"'); + this.log('warn','Pas de type générique "Info/Serrure Etat"'); } else { HBservice = null; } } if (eqLogic.services.StatelessSwitch) { - eqLogic.services.StatelessSwitch.forEach(function(cmd) { - if(cmd.eventType) { - let buttonSingle,buttonDouble,buttonLong; - - if(cmd.eventType.customizedValues.SINGLE) { - buttonSingle = cmd.eventType.customizedValues.SINGLE.split(';'); - } else { - buttonSingle = [""]; - } - if(cmd.eventType.customizedValues.DOUBLE) { - buttonDouble = cmd.eventType.customizedValues.DOUBLE.split(';'); - } else { - buttonDouble = [""]; - } - if(cmd.eventType.customizedValues.LONG) { - buttonLong = cmd.eventType.customizedValues.LONG.split(';'); - } else { - buttonLong = [""]; - } - const maxValues = Math.max(buttonSingle.length,buttonDouble.length,buttonLong.length); - - if(buttonSingle.length === buttonDouble.length && buttonDouble.length === buttonLong.length) { - - for(let b = 0;b { + if (!cmd.eventType) {return;} + let buttonSingle,buttonDouble,buttonLong; + + if(cmd.eventType.customizedValues.SINGLE) { + buttonSingle = cmd.eventType.customizedValues.SINGLE.split(';'); + } else { + buttonSingle = [""]; + } + if(cmd.eventType.customizedValues.DOUBLE) { + buttonDouble = cmd.eventType.customizedValues.DOUBLE.split(';'); + } else { + buttonDouble = [""]; + } + if(cmd.eventType.customizedValues.LONG) { + buttonLong = cmd.eventType.customizedValues.LONG.split(';'); + } else { + buttonLong = [""]; + } + const maxValues = Math.max(buttonSingle.length,buttonDouble.length,buttonLong.length); + + if(buttonSingle.length === buttonDouble.length && buttonDouble.length === buttonLong.length) { + + for(let b = 0;b { if(cmd.Single || cmd.Double || cmd.Long) { let Label = ""; if(cmd.Single) {Label = "Simple";} @@ -2115,7 +2126,7 @@ JeedomPlatform.prototype.AccessoireCreateHomebridge = function(eqLogic) { Serv.cmd_id += Serv.infos.Long.id; break; } - that.log('debug','ValidValues 0 Mono',values); + this.log('debug','ValidValues 0 Mono',values); Serv.getCharacteristic(Characteristic.ProgrammableSwitchEvent).setProps({validValues:values}); @@ -2171,7 +2182,7 @@ JeedomPlatform.prototype.AccessoireCreateHomebridge = function(eqLogic) { Serv.infos.Long=cmdType.Long; Serv.cmd_id += Serv.infos.Long.id; } - that.log('debug','ValidValues '+b+' Mono',values); + this.log('debug','ValidValues '+b+' Mono',values); Serv.getCharacteristic(Characteristic.ProgrammableSwitchEvent).setProps({validValues:values}); @@ -2206,7 +2217,7 @@ JeedomPlatform.prototype.AccessoireCreateHomebridge = function(eqLogic) { } if (eqLogic.services.weather) { - eqLogic.services.weather.forEach(function(cmd) { + eqLogic.services.weather.forEach((cmd) => { if(cmd.temperature) { HBservice = { controlService : new Service.TemperatureSensor(eqLogic.name), @@ -2224,7 +2235,7 @@ JeedomPlatform.prototype.AccessoireCreateHomebridge = function(eqLogic) { Serv.getCharacteristic(Characteristic.TemperatureDisplayUnits).updateValue(Characteristic.TemperatureDisplayUnits.CELSIUS); // add Active, Tampered and Defect Characteristics if needed - HBservice=that.createStatusCharact(HBservice,eqServicesCopy); + HBservice=this.createStatusCharact(HBservice,eqServicesCopy); Serv.cmd_id = cmd.temperature.id; Serv.eqID = eqLogic.id; @@ -2232,8 +2243,8 @@ JeedomPlatform.prototype.AccessoireCreateHomebridge = function(eqLogic) { Serv.subtype = Serv.subtype || ''; Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; - if(that.fakegato && !eqLogic.hasLogging) { - eqLogic.loggingService ={type:"weather", options:{storage:'fs',path:that.pathHomebridgeConf},subtype:Serv.eqID+'-history',cmd_id:Serv.eqID}; + if(this.fakegato && !eqLogic.hasLogging) { + eqLogic.loggingService ={type:"weather", options:{storage:'fs',path:this.pathHomebridgeConf},subtype:Serv.eqID+'-history',cmd_id:Serv.eqID}; eqLogic.hasLogging=true; } @@ -2257,8 +2268,8 @@ JeedomPlatform.prototype.AccessoireCreateHomebridge = function(eqLogic) { Serv.subtype = Serv.subtype || ''; Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; - if(that.fakegato && !eqLogic.hasLogging) { - eqLogic.loggingService ={type:"weather", options:{storage:'fs',path:that.pathHomebridgeConf},subtype:Serv.eqID+'-history',cmd_id:Serv.eqID}; + if(this.fakegato && !eqLogic.hasLogging) { + eqLogic.loggingService ={type:"weather", options:{storage:'fs',path:this.pathHomebridgeConf},subtype:Serv.eqID+'-history',cmd_id:Serv.eqID}; eqLogic.hasLogging=true; } @@ -2282,8 +2293,8 @@ JeedomPlatform.prototype.AccessoireCreateHomebridge = function(eqLogic) { Serv.subtype = Serv.subtype || ''; Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; - if(that.fakegato && !eqLogic.hasLogging) { - eqLogic.loggingService ={type:"weather", options:{storage:'fs',path:that.pathHomebridgeConf},subtype:Serv.eqID+'-history',cmd_id:Serv.eqID}; + if(this.fakegato && !eqLogic.hasLogging) { + eqLogic.loggingService ={type:"weather", options:{storage:'fs',path:this.pathHomebridgeConf},subtype:Serv.eqID+'-history',cmd_id:Serv.eqID}; eqLogic.hasLogging=true; } @@ -2301,7 +2312,7 @@ JeedomPlatform.prototype.AccessoireCreateHomebridge = function(eqLogic) { Serv.infos={}; Serv.infos.condition=cmd.condition; - eqServicesCopy.weather.forEach(function(cmd2) { + eqServicesCopy.weather.forEach((cmd2) => { if (cmd2.wind_speed) { Serv.infos.wind_speed=cmd2.wind_speed; HBservice.characteristics.push(Characteristic.WindSpeed); @@ -2349,436 +2360,430 @@ JeedomPlatform.prototype.AccessoireCreateHomebridge = function(eqLogic) { } else if (cmd2.temperature_min) { Serv.infos.temperature_min=cmd2.temperature_min; HBservice.characteristics.push(Characteristic.MinimumTemperature); - Serv.addCharacteristic(Characteristic.MinimumTemperature); - Serv.getCharacteristic(Characteristic.MinimumTemperature).displayName = cmd2.temperature_min.name; - } - }); - - Serv.cmd_id = cmd.condition.id; - Serv.eqID = eqLogic.id; - Serv.subtype = Serv.cmd_id; - Serv.subtype = Serv.subtype || ''; - Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; - - HBservices.push(HBservice); - HBservice = null; - } - }); - } - if (eqLogic.services.thermostat) { - eqLogic.services.thermostat.forEach(function(cmd) { - if(cmd.setpoint) { - HBservice = { - controlService : new Service.Thermostat(eqLogic.name), - characteristics : [Characteristic.CurrentTemperature, Characteristic.TargetTemperature, Characteristic.CurrentHeatingCoolingState, Characteristic.TargetHeatingCoolingState], - }; - const Serv = HBservice.controlService; - Serv.eqLogic=eqLogic; - Serv.actions={}; - Serv.infos={}; - Serv.infos.setpoint=cmd.setpoint; - Serv.thermo={}; - - HBservice.characteristics.push(Characteristic.TemperatureDisplayUnits); - Serv.addOptionalCharacteristic(Characteristic.TemperatureDisplayUnits); - Serv.getCharacteristic(Characteristic.TemperatureDisplayUnits).updateValue(Characteristic.TemperatureDisplayUnits.CELSIUS); - - eqServicesCopy.thermostat.forEach(function(cmd2) { - if (cmd2.state_name) { - Serv.infos.state_name=cmd2.state_name; - } else if (cmd2.lock) { - Serv.infos.lock=cmd2.lock; - HBservice.characteristics.push(Characteristic.LockPhysicalControls); - Serv.addCharacteristic(Characteristic.LockPhysicalControls); - Serv.getCharacteristic(Characteristic.LockPhysicalControls).displayName = cmd2.lock.name; - } else if (cmd2.mode) { - Serv.infos.mode=cmd2.mode; - } else if (cmd2.temperature) { - Serv.infos.temperature=cmd2.temperature; - } else if (cmd2.state) { - Serv.infos.state=cmd2.state; - } else if (cmd2.set_lock) { - Serv.actions.set_lock=cmd2.set_lock; - } else if (cmd2.set_unlock) { - Serv.actions.set_unlock=cmd2.set_unlock; - } else if (cmd2.set_setpoint) { - Serv.actions.set_setpoint=cmd2.set_setpoint; - } - }); - - var props = {}; - if(Serv.actions.set_setpoint && Serv.actions.set_setpoint.configuration && Serv.actions.set_setpoint.configuration.minValue && parseInt(Serv.actions.set_setpoint.configuration.minValue)) { - props.minValue = parseInt(Serv.actions.set_setpoint.configuration.minValue); - } - if(Serv.actions.set_setpoint && Serv.actions.set_setpoint.configuration && Serv.actions.set_setpoint.configuration.maxValue && parseInt(Serv.actions.set_setpoint.configuration.maxValue)) { - props.maxValue = parseInt(Serv.actions.set_setpoint.configuration.maxValue); - } - if(props.minValue && props.maxValue) { - Serv.getCharacteristic(Characteristic.TargetTemperature).setProps(props); - } - // add Active, Tampered and Defect Characteristics if needed - HBservice=that.createStatusCharact(HBservice,eqServicesCopy); - - props = {}; - props.validValues=[0]; - if(eqLogic.thermoModes) { - if(eqLogic.thermoModes.Chauf && eqLogic.thermoModes.Chauf != "NOT") { - Serv.thermo.chauf = {}; - const splitted = eqLogic.thermoModes.Chauf.split('|'); - Serv.thermo.chauf.mode_label = splitted[1]; - Serv.thermo.chauf.mode_id = splitted[0]; - props.validValues.push(1); - } else { - that.log('warn','Pas de config du mode Chauffage'); - } - if(eqLogic.thermoModes.Clim && eqLogic.thermoModes.Clim != "NOT") { - Serv.thermo.clim = {}; - const splitted = eqLogic.thermoModes.Clim.split('|'); - Serv.thermo.clim.mode_label = splitted[1]; - Serv.thermo.clim.mode_id = splitted[0]; - props.validValues.push(2); - } else { - that.log('warn','Pas de config du mode Climatisation'); - } - if(eqLogic.thermoModes.Off && eqLogic.thermoModes.Off != "NOT") { - Serv.thermo.off = {}; - const splitted = eqLogic.thermoModes.Off.split('|'); - Serv.thermo.off.mode_label = splitted[1]; - Serv.thermo.off.mode_id = splitted[0]; - } - } else if(that.myPlugin == "homebridge") { - that.log('warn','Pas de config des modes du thermostat'); - } - // Serv.getCharacteristic(Characteristic.CurrentHeatingCoolingState).setProps(props); - props.validValues.push(3); - Serv.getCharacteristic(Characteristic.TargetHeatingCoolingState).setProps(props); - Serv.cmd_id = cmd.setpoint.id; - Serv.eqID = eqLogic.id; - Serv.subtype = Serv.subtype || ''; - Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; - if(that.fakegato && !eqLogic.hasLogging) { - eqLogic.loggingService ={type:"thermo", options:{storage:'fs',path:that.pathHomebridgeConf},subtype:Serv.eqID+'-history',cmd_id:Serv.eqID}; - eqLogic.hasLogging=true; - } - HBservices.push(HBservice); - HBservice = null; - } - }); - } - if (eqLogic.services.thermostatHC) { - eqLogic.services.thermostatHC.forEach(function(cmd) { - if(cmd.setpointH) { - HBservice = { - controlService : new Service.HeaterCooler(eqLogic.name), - characteristics : [Characteristic.CurrentTemperature, Characteristic.CoolingThresholdTemperature, Characteristic.HeatingThresholdTemperature, Characteristic.CurrentHeatingCoolingState, Characteristic.TargetHeatingCoolingState], - }; - const Serv = HBservice.controlService; - Serv.eqLogic=eqLogic; - Serv.actions={}; - Serv.infos={}; - Serv.infos.setpointH=cmd.setpointH; - Serv.thermoHC={}; - - HBservice.characteristics.push(Characteristic.TemperatureDisplayUnits); - Serv.addOptionalCharacteristic(Characteristic.TemperatureDisplayUnits); - Serv.getCharacteristic(Characteristic.TemperatureDisplayUnits).updateValue(Characteristic.TemperatureDisplayUnits.CELSIUS); - - eqServicesCopy.thermostatHC.forEach(function(cmd2) { - if (cmd2.setpointC) { - Serv.infos.setpointC=cmd2.setpointC; - } else if (cmd2.state_name) { - Serv.infos.state_name=cmd2.state_name; - } else if (cmd2.lock) { - Serv.infos.lock=cmd2.lock; - HBservice.characteristics.push(Characteristic.LockPhysicalControls); - Serv.addCharacteristic(Characteristic.LockPhysicalControls); - Serv.getCharacteristic(Characteristic.LockPhysicalControls).displayName = cmd2.lock.name; - } else if (cmd2.mode) { - Serv.infos.mode=cmd2.mode; - } else if (cmd2.temperature) { - Serv.infos.temperature=cmd2.temperature; - } else if (cmd2.state) { - Serv.infos.state=cmd2.state; - } else if (cmd2.set_lock) { - Serv.actions.set_lock=cmd2.set_lock; - } else if (cmd2.set_unlock) { - Serv.actions.set_unlock=cmd2.set_unlock; - } else if (cmd2.set_setpointH) { - Serv.actions.set_setpointH=cmd2.set_setpointH; - } else if (cmd2.set_setpointC) { - Serv.actions.set_setpointC=cmd2.set_setpointC; + Serv.addCharacteristic(Characteristic.MinimumTemperature); + Serv.getCharacteristic(Characteristic.MinimumTemperature).displayName = cmd2.temperature_min.name; } }); - var props = {}; - if(Serv.actions.set_setpointH && Serv.actions.set_setpointH.configuration && Serv.actions.set_setpointH.configuration.minValue && parseInt(Serv.actions.set_setpointH.configuration.minValue)) { - props.minValue = parseInt(Serv.actions.set_setpointH.configuration.minValue); - } - if(Serv.actions.set_setpointH && Serv.actions.set_setpointH.configuration && Serv.actions.set_setpointH.configuration.maxValue && parseInt(Serv.actions.set_setpointH.configuration.maxValue)) { - props.maxValue = parseInt(Serv.actions.set_setpointH.configuration.maxValue); - } - if(props.minValue && props.maxValue) { - Serv.getCharacteristic(Characteristic.HeatingThresholdTemperature).setProps(props); - } - props = {}; - if(Serv.actions.set_setpointC && Serv.actions.set_setpointC.configuration && Serv.actions.set_setpointC.configuration.minValue && parseInt(Serv.actions.set_setpointC.configuration.minValue)) { - props.minValue = parseInt(Serv.actions.set_setpointC.configuration.minValue); - } - if(Serv.actions.set_setpointC && Serv.actions.set_setpointC.configuration && Serv.actions.set_setpointC.configuration.maxValue && parseInt(Serv.actions.set_setpointC.configuration.maxValue)) { - props.maxValue = parseInt(Serv.actions.set_setpointC.configuration.maxValue); - } - if(props.minValue && props.maxValue) { - Serv.getCharacteristic(Characteristic.CoolingThresholdTemperature).setProps(props); - } - // add Active, Tampered and Defect Characteristics if needed - HBservice=that.createStatusCharact(HBservice,eqServicesCopy); - - props = {}; - props.validValues=[0]; - if(eqLogic.thermoModes) { - if(eqLogic.thermoModes.Chauf && eqLogic.thermoModes.Chauf != "NOT") { - Serv.thermoHC.chauf = {}; - const splitted = eqLogic.thermoModes.Chauf.split('|'); - Serv.thermoHC.chauf.mode_label = splitted[1]; - Serv.thermoHC.chauf.mode_id = splitted[0]; - props.validValues.push(1); - } else { - that.log('warn','Pas de config du mode Chauffage'); - } - if(eqLogic.thermoModes.Clim && eqLogic.thermoModes.Clim != "NOT") { - Serv.thermoHC.clim = {}; - const splitted = eqLogic.thermoModes.Clim.split('|'); - Serv.thermoHC.clim.mode_label = splitted[1]; - Serv.thermoHC.clim.mode_id = splitted[0]; - props.validValues.push(2); - } else { - that.log('warn','Pas de config du mode Climatisation'); - } - if(eqLogic.thermoModes.Off && eqLogic.thermoModes.Off != "NOT") { - Serv.thermoHC.off = {}; - const splitted = eqLogic.thermoModes.Off.split('|'); - Serv.thermoHC.off.mode_label = splitted[1]; - Serv.thermoHC.off.mode_id = splitted[0]; - } - } - else if(that.myPlugin == "homebridge") { - that.log('warn','Pas de config des modes du thermostatHC'); - } - // Serv.getCharacteristic(Characteristic.CurrentHeatingCoolingState).setProps(props); - props.validValues.push(3); - Serv.getCharacteristic(Characteristic.TargetHeatingCoolingState).setProps(props); - Serv.cmd_id = cmd.setpointH.id; + Serv.cmd_id = cmd.condition.id; Serv.eqID = eqLogic.id; + Serv.subtype = Serv.cmd_id; Serv.subtype = Serv.subtype || ''; Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; + HBservices.push(HBservice); HBservice = null; } }); + } + if (eqLogic.services.thermostat) { + eqLogic.services.thermostat.forEach((cmd) => { + if (!cmd.setpoint) {return;} + HBservice = { + controlService : new Service.Thermostat(eqLogic.name), + characteristics : [Characteristic.CurrentTemperature, Characteristic.TargetTemperature, Characteristic.CurrentHeatingCoolingState, Characteristic.TargetHeatingCoolingState], + }; + const Serv = HBservice.controlService; + Serv.eqLogic=eqLogic; + Serv.actions={}; + Serv.infos={}; + Serv.infos.setpoint=cmd.setpoint; + Serv.thermo={}; + + HBservice.characteristics.push(Characteristic.TemperatureDisplayUnits); + Serv.addOptionalCharacteristic(Characteristic.TemperatureDisplayUnits); + Serv.getCharacteristic(Characteristic.TemperatureDisplayUnits).updateValue(Characteristic.TemperatureDisplayUnits.CELSIUS); + + eqServicesCopy.thermostat.forEach((cmd2) => { + if (cmd2.state_name) { + Serv.infos.state_name=cmd2.state_name; + } else if (cmd2.lock) { + Serv.infos.lock=cmd2.lock; + HBservice.characteristics.push(Characteristic.LockPhysicalControls); + Serv.addCharacteristic(Characteristic.LockPhysicalControls); + Serv.getCharacteristic(Characteristic.LockPhysicalControls).displayName = cmd2.lock.name; + } else if (cmd2.mode) { + Serv.infos.mode=cmd2.mode; + } else if (cmd2.temperature) { + Serv.infos.temperature=cmd2.temperature; + } else if (cmd2.state) { + Serv.infos.state=cmd2.state; + } else if (cmd2.set_lock) { + Serv.actions.set_lock=cmd2.set_lock; + } else if (cmd2.set_unlock) { + Serv.actions.set_unlock=cmd2.set_unlock; + } else if (cmd2.set_setpoint) { + Serv.actions.set_setpoint=cmd2.set_setpoint; + } + }); + + var props = {}; + if(Serv.actions.set_setpoint && Serv.actions.set_setpoint.configuration && Serv.actions.set_setpoint.configuration.minValue && parseInt(Serv.actions.set_setpoint.configuration.minValue)) { + props.minValue = parseInt(Serv.actions.set_setpoint.configuration.minValue); + } + if(Serv.actions.set_setpoint && Serv.actions.set_setpoint.configuration && Serv.actions.set_setpoint.configuration.maxValue && parseInt(Serv.actions.set_setpoint.configuration.maxValue)) { + props.maxValue = parseInt(Serv.actions.set_setpoint.configuration.maxValue); + } + if(props.minValue && props.maxValue) { + Serv.getCharacteristic(Characteristic.TargetTemperature).setProps(props); + } + // add Active, Tampered and Defect Characteristics if needed + HBservice=this.createStatusCharact(HBservice,eqServicesCopy); + + props = {}; + props.validValues=[0]; + if(eqLogic.thermoModes) { + if(eqLogic.thermoModes.Chauf && eqLogic.thermoModes.Chauf != "NOT") { + Serv.thermo.chauf = {}; + const splitted = eqLogic.thermoModes.Chauf.split('|'); + Serv.thermo.chauf.mode_label = splitted[1]; + Serv.thermo.chauf.mode_id = splitted[0]; + props.validValues.push(1); + } else { + this.log('warn','Pas de config du mode Chauffage'); + } + if(eqLogic.thermoModes.Clim && eqLogic.thermoModes.Clim != "NOT") { + Serv.thermo.clim = {}; + const splitted = eqLogic.thermoModes.Clim.split('|'); + Serv.thermo.clim.mode_label = splitted[1]; + Serv.thermo.clim.mode_id = splitted[0]; + props.validValues.push(2); + } else { + this.log('warn','Pas de config du mode Climatisation'); + } + if(eqLogic.thermoModes.Off && eqLogic.thermoModes.Off != "NOT") { + Serv.thermo.off = {}; + const splitted = eqLogic.thermoModes.Off.split('|'); + Serv.thermo.off.mode_label = splitted[1]; + Serv.thermo.off.mode_id = splitted[0]; + } + } else if(this.myPlugin == "homebridge") { + this.log('warn','Pas de config des modes du thermostat'); + } + // Serv.getCharacteristic(Characteristic.CurrentHeatingCoolingState).setProps(props); + props.validValues.push(3); + Serv.getCharacteristic(Characteristic.TargetHeatingCoolingState).setProps(props); + Serv.cmd_id = cmd.setpoint.id; + Serv.eqID = eqLogic.id; + Serv.subtype = Serv.subtype || ''; + Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; + if(this.fakegato && !eqLogic.hasLogging) { + eqLogic.loggingService ={type:"thermo", options:{storage:'fs',path:this.pathHomebridgeConf},subtype:Serv.eqID+'-history',cmd_id:Serv.eqID}; + eqLogic.hasLogging=true; + } + HBservices.push(HBservice); + HBservice = null; + }); + } + if (eqLogic.services.thermostatHC) { + eqLogic.services.thermostatHC.forEach((cmd) => { + if (!cmd.setpointH) {return;} + HBservice = { + controlService : new Service.HeaterCooler(eqLogic.name), + characteristics : [Characteristic.CurrentTemperature, Characteristic.CoolingThresholdTemperature, Characteristic.HeatingThresholdTemperature, Characteristic.CurrentHeatingCoolingState, Characteristic.TargetHeatingCoolingState], + }; + const Serv = HBservice.controlService; + Serv.eqLogic=eqLogic; + Serv.actions={}; + Serv.infos={}; + Serv.infos.setpointH=cmd.setpointH; + Serv.thermoHC={}; + + HBservice.characteristics.push(Characteristic.TemperatureDisplayUnits); + Serv.addOptionalCharacteristic(Characteristic.TemperatureDisplayUnits); + Serv.getCharacteristic(Characteristic.TemperatureDisplayUnits).updateValue(Characteristic.TemperatureDisplayUnits.CELSIUS); + + eqServicesCopy.thermostatHC.forEach((cmd2) => { + if (cmd2.setpointC) { + Serv.infos.setpointC=cmd2.setpointC; + } else if (cmd2.state_name) { + Serv.infos.state_name=cmd2.state_name; + } else if (cmd2.lock) { + Serv.infos.lock=cmd2.lock; + HBservice.characteristics.push(Characteristic.LockPhysicalControls); + Serv.addCharacteristic(Characteristic.LockPhysicalControls); + Serv.getCharacteristic(Characteristic.LockPhysicalControls).displayName = cmd2.lock.name; + } else if (cmd2.mode) { + Serv.infos.mode=cmd2.mode; + } else if (cmd2.temperature) { + Serv.infos.temperature=cmd2.temperature; + } else if (cmd2.state) { + Serv.infos.state=cmd2.state; + } else if (cmd2.set_lock) { + Serv.actions.set_lock=cmd2.set_lock; + } else if (cmd2.set_unlock) { + Serv.actions.set_unlock=cmd2.set_unlock; + } else if (cmd2.set_setpointH) { + Serv.actions.set_setpointH=cmd2.set_setpointH; + } else if (cmd2.set_setpointC) { + Serv.actions.set_setpointC=cmd2.set_setpointC; + } + }); + + var props = {}; + if(Serv.actions.set_setpointH && Serv.actions.set_setpointH.configuration && Serv.actions.set_setpointH.configuration.minValue && parseInt(Serv.actions.set_setpointH.configuration.minValue)) { + props.minValue = parseInt(Serv.actions.set_setpointH.configuration.minValue); + } + if(Serv.actions.set_setpointH && Serv.actions.set_setpointH.configuration && Serv.actions.set_setpointH.configuration.maxValue && parseInt(Serv.actions.set_setpointH.configuration.maxValue)) { + props.maxValue = parseInt(Serv.actions.set_setpointH.configuration.maxValue); + } + if(props.minValue && props.maxValue) { + Serv.getCharacteristic(Characteristic.HeatingThresholdTemperature).setProps(props); + } + props = {}; + if(Serv.actions.set_setpointC && Serv.actions.set_setpointC.configuration && Serv.actions.set_setpointC.configuration.minValue && parseInt(Serv.actions.set_setpointC.configuration.minValue)) { + props.minValue = parseInt(Serv.actions.set_setpointC.configuration.minValue); + } + if(Serv.actions.set_setpointC && Serv.actions.set_setpointC.configuration && Serv.actions.set_setpointC.configuration.maxValue && parseInt(Serv.actions.set_setpointC.configuration.maxValue)) { + props.maxValue = parseInt(Serv.actions.set_setpointC.configuration.maxValue); + } + if(props.minValue && props.maxValue) { + Serv.getCharacteristic(Characteristic.CoolingThresholdTemperature).setProps(props); + } + // add Active, Tampered and Defect Characteristics if needed + HBservice=this.createStatusCharact(HBservice,eqServicesCopy); + + props = {}; + props.validValues=[0]; + if(eqLogic.thermoModes) { + if(eqLogic.thermoModes.Chauf && eqLogic.thermoModes.Chauf != "NOT") { + Serv.thermoHC.chauf = {}; + const splitted = eqLogic.thermoModes.Chauf.split('|'); + Serv.thermoHC.chauf.mode_label = splitted[1]; + Serv.thermoHC.chauf.mode_id = splitted[0]; + props.validValues.push(1); + } else { + this.log('warn','Pas de config du mode Chauffage'); + } + if(eqLogic.thermoModes.Clim && eqLogic.thermoModes.Clim != "NOT") { + Serv.thermoHC.clim = {}; + const splitted = eqLogic.thermoModes.Clim.split('|'); + Serv.thermoHC.clim.mode_label = splitted[1]; + Serv.thermoHC.clim.mode_id = splitted[0]; + props.validValues.push(2); + } else { + this.log('warn','Pas de config du mode Climatisation'); + } + if(eqLogic.thermoModes.Off && eqLogic.thermoModes.Off != "NOT") { + Serv.thermoHC.off = {}; + const splitted = eqLogic.thermoModes.Off.split('|'); + Serv.thermoHC.off.mode_label = splitted[1]; + Serv.thermoHC.off.mode_id = splitted[0]; + } + } + else if(this.myPlugin == "homebridge") { + this.log('warn','Pas de config des modes du thermostatHC'); + } + // Serv.getCharacteristic(Characteristic.CurrentHeatingCoolingState).setProps(props); + props.validValues.push(3); + Serv.getCharacteristic(Characteristic.TargetHeatingCoolingState).setProps(props); + Serv.cmd_id = cmd.setpointH.id; + Serv.eqID = eqLogic.id; + Serv.subtype = Serv.subtype || ''; + Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; + HBservices.push(HBservice); + HBservice = null; + }); } if (eqLogic.services.mode) { let modeState=null; - eqLogic.services.mode.forEach(function(cmd) { - if(cmd.state) { - HBservice = { - controlService : new Service.CustomService(eqLogic.name), - characteristics : [Characteristic.GenericSTRING], - }; - const Serv = HBservice.controlService; - - Serv.addCharacteristic(Characteristic.GenericSTRING); - Serv.getCharacteristic(Characteristic.GenericSTRING).displayName = cmd.state.name; - - Serv.eqLogic=eqLogic; - Serv.actions={}; - Serv.infos={}; - Serv.infos.state=cmd.state; - modeState=cmd.state; - Serv.cmd_id = cmd.state.id; - Serv.eqID = eqLogic.id; - Serv.subtype = Serv.subtype || ''; - Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; - HBservices.push(HBservice); - HBservice = null; - } + eqLogic.services.mode.forEach((cmd) => { + if (!cmd.state) {return;} + HBservice = { + controlService : new Service.CustomService(eqLogic.name), + characteristics : [Characteristic.GenericSTRING], + }; + const Serv = HBservice.controlService; + + Serv.addCharacteristic(Characteristic.GenericSTRING); + Serv.getCharacteristic(Characteristic.GenericSTRING).displayName = cmd.state.name; + + Serv.eqLogic=eqLogic; + Serv.actions={}; + Serv.infos={}; + Serv.infos.state=cmd.state; + modeState=cmd.state; + Serv.cmd_id = cmd.state.id; + Serv.eqID = eqLogic.id; + Serv.subtype = Serv.subtype || ''; + Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; + HBservices.push(HBservice); + HBservice = null; }); if(modeState) { var set_state_previous = null; - eqLogic.services.mode.forEach(function(cmd) { - if (cmd.set_state) { - cmd.set_state.forEach(function(set_action) { - var ModeName = ""; - if(set_action.name.toLowerCase().includes('mode') || set_action.name.toLowerCase().includes('modo')) { - ModeName = set_action.name; - } else { - ModeName = "Mode "+set_action.name; - } - HBservice = { - controlService : new Service.Switch(ModeName), - characteristics : [Characteristic.On,Characteristic.ConfiguredName], - }; - const Serv = HBservice.controlService; - Serv.modeSwitch=set_action.name; - Serv.eqLogic=eqLogic; - Serv.actions={}; - Serv.infos={}; - Serv.infos.state=modeState; - - Serv.ConfiguredName=ModeName; - Serv.getCharacteristic(Characteristic.ConfiguredName).setValue(ModeName); - - if(!set_state_previous) { - eqServicesCopy.mode.forEach(function(cmd2) { - if (cmd2.set_state_previous) { - Serv.actions.set_state_previous=cmd2.set_state_previous; - set_state_previous=cmd2.set_state_previous; - } - }); - } else { - Serv.actions.set_state_previous=set_state_previous; - } - - Serv.cmd_id = modeState.id; - Serv.eqID = eqLogic.id; - Serv.subtype = set_action.id || ''; - Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; - - const set_state_name = set_action.name; - Serv.actions[set_state_name]={"set_state":set_action}; - - HBservices.push(HBservice); - HBservice = null; - }); - } + eqLogic.services.mode.forEach((cmd) => { + if (!cmd.set_state) {return;} + cmd.set_state.forEach((set_action) => { + var ModeName = ""; + if(set_action.name.toLowerCase().includes('mode') || set_action.name.toLowerCase().includes('modo')) { + ModeName = set_action.name; + } else { + ModeName = "Mode "+set_action.name; + } + HBservice = { + controlService : new Service.Switch(ModeName), + characteristics : [Characteristic.On,Characteristic.ConfiguredName], + }; + const Serv = HBservice.controlService; + Serv.modeSwitch=set_action.name; + Serv.eqLogic=eqLogic; + Serv.actions={}; + Serv.infos={}; + Serv.infos.state=modeState; + + Serv.ConfiguredName=ModeName; + Serv.getCharacteristic(Characteristic.ConfiguredName).setValue(ModeName); + + if(!set_state_previous) { + eqServicesCopy.mode.forEach((cmd2) => { + if (cmd2.set_state_previous) { + Serv.actions.set_state_previous=cmd2.set_state_previous; + set_state_previous=cmd2.set_state_previous; + } + }); + } else { + Serv.actions.set_state_previous=set_state_previous; + } + + Serv.cmd_id = modeState.id; + Serv.eqID = eqLogic.id; + Serv.subtype = set_action.id || ''; + Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; + + const set_state_name = set_action.name; + Serv.actions[set_state_name]={"set_state":set_action}; + + HBservices.push(HBservice); + HBservice = null; + }); }); } else { - that.log('warn','Vous utilisez le type générique Mode en dehors du plugin Mode !'); + this.log('warn','Vous utilisez le type générique Mode en dehors du plugin Mode !'); } } if (eqLogic.services.siren) { - eqLogic.services.siren.forEach(function(cmd) { - if(cmd.state) { - HBservice = { - controlService : new Service.SecuritySystem(eqLogic.name), - characteristics : [Characteristic.SecuritySystemCurrentState, Characteristic.SecuritySystemTargetState], - }; - const Serv = HBservice.controlService; - Serv.eqLogic=eqLogic; - Serv.actions={}; - Serv.infos={}; - Serv.infos.state=cmd.state; - Serv.siren=true; - - eqServicesCopy.siren.forEach(function(cmd2) { - if (cmd2.on) { - Serv.actions.on=cmd2.on; - } else if (cmd2.off) { - Serv.actions.off=cmd2.off; - } - }); - - // add Active, Tampered and Defect Characteristics if needed - HBservice=that.createStatusCharact(HBservice,eqServicesCopy); - - // Serv.getCharacteristic(Characteristic.SecuritySystemCurrentState).setProps({validValues:[3,4]}); - Serv.getCharacteristic(Characteristic.SecuritySystemTargetState).setProps({validValues:[3]}); - Serv.cmd_id = cmd.state.id; - Serv.eqID = eqLogic.id; - Serv.subtype = Serv.subtype || ''; - Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; - HBservices.push(HBservice); - HBservice = null; - } + eqLogic.services.siren.forEach((cmd) => { + if (!cmd.state) {return;} + HBservice = { + controlService : new Service.SecuritySystem(eqLogic.name), + characteristics : [Characteristic.SecuritySystemCurrentState, Characteristic.SecuritySystemTargetState], + }; + const Serv = HBservice.controlService; + Serv.eqLogic=eqLogic; + Serv.actions={}; + Serv.infos={}; + Serv.infos.state=cmd.state; + Serv.siren=true; + + eqServicesCopy.siren.forEach((cmd2) => { + if (cmd2.on) { + Serv.actions.on=cmd2.on; + } else if (cmd2.off) { + Serv.actions.off=cmd2.off; + } + }); + + // add Active, Tampered and Defect Characteristics if needed + HBservice=this.createStatusCharact(HBservice,eqServicesCopy); + + // Serv.getCharacteristic(Characteristic.SecuritySystemCurrentState).setProps({validValues:[3,4]}); + Serv.getCharacteristic(Characteristic.SecuritySystemTargetState).setProps({validValues:[3]}); + Serv.cmd_id = cmd.state.id; + Serv.eqID = eqLogic.id; + Serv.subtype = Serv.subtype || ''; + Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; + HBservices.push(HBservice); + HBservice = null; }); } if (eqLogic.services.alarm) { - eqLogic.services.alarm.forEach(function(cmd) { - if(cmd.enable_state) { - HBservice = { - controlService : new Service.SecuritySystem(eqLogic.name), - characteristics : [Characteristic.SecuritySystemCurrentState, Characteristic.SecuritySystemTargetState], - }; - const Serv = HBservice.controlService; - Serv.eqLogic=eqLogic; - Serv.actions={}; - Serv.infos={}; - Serv.infos.enable_state=cmd.enable_state; - Serv.alarm={}; - eqServicesCopy.alarm.forEach(function(cmd2) { - if (cmd2.state) { - Serv.infos.state=cmd2.state; - } else if (cmd2.mode) { - Serv.infos.mode=cmd2.mode; - } - }); - - // add Active, Tampered and Defect Characteristics if needed - HBservice=that.createStatusCharact(HBservice,eqServicesCopy); - - var props = {}; - props.validValues=[]; - Serv.hasAlarmModes=false; - if(eqLogic.alarmModes) { - if(eqLogic.alarmModes.SetModePresent && eqLogic.alarmModes.SetModePresent != "NOT") { - Serv.alarm.present = {}; - const splitted = eqLogic.alarmModes.SetModePresent.split('|'); - Serv.alarm.present.mode_label = splitted[1]; - Serv.alarm.present.mode_id = splitted[0]; - props.validValues.push(Characteristic.SecuritySystemTargetState.STAY_ARM); - Serv.hasAlarmModes=true; - } else { - that.log('warn','Pas de config du mode Domicile/Présence'); - } - if(eqLogic.alarmModes.SetModeAbsent && eqLogic.alarmModes.SetModeAbsent != "NOT") { - Serv.alarm.away = {}; - const splitted = eqLogic.alarmModes.SetModeAbsent.split('|'); - Serv.alarm.away.mode_label = splitted[1]; - Serv.alarm.away.mode_id = splitted[0]; - props.validValues.push(Characteristic.SecuritySystemTargetState.AWAY_ARM); - Serv.hasAlarmModes=true; - } else { - that.log('warn','Pas de config du mode À distance/Absence'); - } - if(eqLogic.alarmModes.SetModeNuit && eqLogic.alarmModes.SetModeNuit != "NOT") { - Serv.alarm.night = {}; - const splitted = eqLogic.alarmModes.SetModeNuit.split('|'); - Serv.alarm.night.mode_label = splitted[1]; - Serv.alarm.night.mode_id = splitted[0]; - props.validValues.push(Characteristic.SecuritySystemTargetState.NIGHT_ARM); - Serv.hasAlarmModes=true; - } else { - that.log('warn','Pas de config du mode Nuit'); - } + eqLogic.services.alarm.forEach((cmd) => { + if (!cmd.enable_state) {return;} + HBservice = { + controlService : new Service.SecuritySystem(eqLogic.name), + characteristics : [Characteristic.SecuritySystemCurrentState, Characteristic.SecuritySystemTargetState], + }; + const Serv = HBservice.controlService; + Serv.eqLogic=eqLogic; + Serv.actions={}; + Serv.infos={}; + Serv.infos.enable_state=cmd.enable_state; + Serv.alarm={}; + eqServicesCopy.alarm.forEach((cmd2) => { + if (cmd2.state) { + Serv.infos.state=cmd2.state; + } else if (cmd2.mode) { + Serv.infos.mode=cmd2.mode; } - if(that.myPlugin == "homebridge" && !Serv.hasAlarmModes) { + }); + + // add Active, Tampered and Defect Characteristics if needed + HBservice=this.createStatusCharact(HBservice,eqServicesCopy); + + var props = {}; + props.validValues=[]; + Serv.hasAlarmModes=false; + if(eqLogic.alarmModes) { + if(eqLogic.alarmModes.SetModePresent && eqLogic.alarmModes.SetModePresent != "NOT") { + Serv.alarm.present = {}; + const splitted = eqLogic.alarmModes.SetModePresent.split('|'); + Serv.alarm.present.mode_label = splitted[1]; + Serv.alarm.present.mode_id = splitted[0]; + props.validValues.push(Characteristic.SecuritySystemTargetState.STAY_ARM); + Serv.hasAlarmModes=true; + } else { + this.log('warn','Pas de config du mode Domicile/Présence'); + } + if(eqLogic.alarmModes.SetModeAbsent && eqLogic.alarmModes.SetModeAbsent != "NOT") { + Serv.alarm.away = {}; + const splitted = eqLogic.alarmModes.SetModeAbsent.split('|'); + Serv.alarm.away.mode_label = splitted[1]; + Serv.alarm.away.mode_id = splitted[0]; props.validValues.push(Characteristic.SecuritySystemTargetState.AWAY_ARM); - that.log('warn','Pas de config des modes de l\'alarme'); + Serv.hasAlarmModes=true; + } else { + this.log('warn','Pas de config du mode À distance/Absence'); + } + if(eqLogic.alarmModes.SetModeNuit && eqLogic.alarmModes.SetModeNuit != "NOT") { + Serv.alarm.night = {}; + const splitted = eqLogic.alarmModes.SetModeNuit.split('|'); + Serv.alarm.night.mode_label = splitted[1]; + Serv.alarm.night.mode_id = splitted[0]; + props.validValues.push(Characteristic.SecuritySystemTargetState.NIGHT_ARM); + Serv.hasAlarmModes=true; + } else { + this.log('warn','Pas de config du mode Nuit'); } - props.validValues.push(Characteristic.SecuritySystemTargetState.DISARM); - Serv.getCharacteristic(Characteristic.SecuritySystemTargetState).setProps(props); - Serv.cmd_id = cmd.enable_state.id; - Serv.eqID = eqLogic.id; - Serv.subtype = Serv.subtype || ''; - Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; - HBservices.push(HBservice); - HBservice = null; } + if(this.myPlugin == "homebridge" && !Serv.hasAlarmModes) { + props.validValues.push(Characteristic.SecuritySystemTargetState.AWAY_ARM); + this.log('warn','Pas de config des modes de l\'alarme'); + } + props.validValues.push(Characteristic.SecuritySystemTargetState.DISARM); + Serv.getCharacteristic(Characteristic.SecuritySystemTargetState).setProps(props); + Serv.cmd_id = cmd.enable_state.id; + Serv.eqID = eqLogic.id; + Serv.subtype = Serv.subtype || ''; + Serv.subtype = eqLogic.id + '-' + Serv.cmd_id + '-' + Serv.subtype; + HBservices.push(HBservice); + HBservice = null; }); } if (HBservices.length != 0) { - if (DEV_DEBUG) {that.log('debug','HBservices : '+JSON.stringify(HBservices));} - createdAccessory = that.createAccessory(HBservices, eqLogic); - that.addAccessory(createdAccessory); + if (DEV_DEBUG) {this.log('debug','HBservices : '+JSON.stringify(HBservices));} + createdAccessory = this.createAccessory(HBservices, eqLogic); + this.addAccessory(createdAccessory); HBservices = []; } else { - that.log('│ Accessoire sans Type Générique d\'Etat'); - createdAccessory = that.createAccessory([], eqLogic); // create a cached lookalike object for unregistering it - that.delAccessory(createdAccessory); + this.log('│ Accessoire sans Type Générique d\'Etat'); + createdAccessory = this.createAccessory([], eqLogic); // create a cached lookalike object for unregistering it + this.delAccessory(createdAccessory); } - that.log('└─────────'); + this.log('└─────────'); } catch(e){ this.log('error','Erreur de la fonction AccessoireCreateHomebridge :',e); @@ -2873,14 +2878,12 @@ JeedomPlatform.prototype.createAccessory = function(HBservices, eqLogic) { // -- jeedomAccessory : JeedomBridgedAccessory to delete // -- silence : flag for logging or not // -- Return : nothing -JeedomPlatform.prototype.delAccessory = function(jeedomAccessory,silence) { - var existingAccessory; +JeedomPlatform.prototype.delAccessory = function(jeedomAccessory,silence=false) { + let existingAccessory; try{ - silence = silence || false; if (!jeedomAccessory) { return; } - if(!silence) {this.log('debug',' Vérification d\'existance de l\'accessoire dans le cache Homebridge...');} existingAccessory = this.existingAccessory(jeedomAccessory.UUID,silence); if(existingAccessory) @@ -2909,14 +2912,12 @@ JeedomPlatform.prototype.delAccessory = function(jeedomAccessory,silence) { // -- jeedomAccessory : JeedomBridgedAccessory to add // -- Return : nothing JeedomPlatform.prototype.addAccessory = function(jeedomAccessory) { - var HBAccessory,numberOpened,lastAct; + let HBAccessory; try{ - if (!jeedomAccessory) { - return; - } + if (!jeedomAccessory) {return;} let isNewAccessory = false; const services2Add = jeedomAccessory.services_add; - this.log('debug',' Vérification d\'existance de l\'accessoire dans le cache Homebridge...'); + this.log('debug'," Vérification d'existance de l'accessoire dans le cache Homebridge..."); HBAccessory = this.existingAccessory(jeedomAccessory.UUID); if (!HBAccessory) { this.log('│ Nouvel accessoire (' + jeedomAccessory.name + ')'); @@ -2925,6 +2926,7 @@ JeedomPlatform.prototype.addAccessory = function(jeedomAccessory) { jeedomAccessory.initAccessory(HBAccessory); this.accessories[jeedomAccessory.UUID] = HBAccessory; } + let numberOpened,lastAct; if(this.fakegato) { numberOpened = HBAccessory.context && HBAccessory.context.eqLogic && HBAccessory.context.eqLogic.numberOpened || 0; lastAct = HBAccessory.context && HBAccessory.context.eqLogic && HBAccessory.context.eqLogic.lastAct || 0; @@ -2981,10 +2983,10 @@ JeedomPlatform.prototype.addAccessory = function(jeedomAccessory) { this.log('│ OK : Mise à jour de l\'accessoire (' + jeedomAccessory.name + ')'); this.api.updatePlatformAccessories([HBAccessory]); } - HBAccessory.on('identify', function(paired, callback) { + HBAccessory.on('identify', (paired, callback) => { this.log(HBAccessory.displayName, "->Identifié!!!"); if(typeof callback === 'function') {callback();} - }.bind(this)); + }); HBAccessory.reviewed = true; } catch(e){ @@ -3002,15 +3004,12 @@ JeedomPlatform.prototype.addAccessory = function(jeedomAccessory) { // -- UUID : UUID to find // -- silence : flag for logging or not // -- Return : nothing -JeedomPlatform.prototype.existingAccessory = function(UUID,silence) { +JeedomPlatform.prototype.existingAccessory = function(UUID,silence=false) { try{ - silence = silence || false; - for (const a in this.accessories) { - if (this.accessories.hasOwnProperty(a)) { - if (this.accessories[a].UUID == UUID) { - if(!silence) {this.log('debug',' Accessoire déjà existant dans le cache Homebridge');} - return this.accessories[a]; - } + for (const key of Object.keys(this.accessories)) { + if (this.accessories[key].UUID == UUID) { + if(!silence) {this.log('debug',' Accessoire déjà existant dans le cache Homebridge');} + return this.accessories[key]; } } if(!silence) {this.log('debug',' Accessoire non existant dans le cache Homebridge');} @@ -3071,15 +3070,9 @@ JeedomPlatform.prototype.configureAccessory = function(accessory) { // -- Return : nothing JeedomPlatform.prototype.bindCharacteristicEvents = function(characteristic, service) { try{ - var readOnly = true; - for (var i = 0; i < characteristic.props.perms.length; i++) { - if (characteristic.props.perms[i] == 'pw') { - readOnly = false; - } - } - this.subscribeUpdate(service, characteristic); - if (!readOnly) { - characteristic.on('set', function(value, callback, context) { + /* if (characteristic.UUID != Characteristic.PositionState.UUID) { */this.updateSubscriptions.push({service, characteristic});// } + if (characteristic.props.perms.includes('pw')) { + characteristic.on('set', (value, callback, context) => { if (context !== 'fromJeedom' && context !== 'fromSetValue') { // from Homekit this.log('info','[Commande d\'Homekit]','Nom:'+characteristic.displayName+'('+characteristic.UUID+'):'+characteristic.value+'->'+value,'\t\t\t\t\t|||characteristic:'+JSON.stringify(characteristic)); this.setAccessoryValue(value,characteristic,service); @@ -3087,9 +3080,9 @@ JeedomPlatform.prototype.bindCharacteristicEvents = function(characteristic, ser this.log('info','[Commande de Jeedom]','Nom:'+characteristic.displayName+'('+characteristic.UUID+'):'+value,'\t\t\t\t\t|||context:'+JSON.stringify(context),'characteristic:'+JSON.stringify(characteristic)); } callback(); - }.bind(this)); + }); } - characteristic.on('get', function(callback) { + characteristic.on('get', (callback) => { let returnValue = this.getAccessoryValue(characteristic, service); if(returnValue !== undefined && returnValue !== 'no_response') { returnValue = sanitizeValue(returnValue,characteristic); @@ -3100,12 +3093,12 @@ JeedomPlatform.prototype.bindCharacteristicEvents = function(characteristic, ser } else { callback(); } - }.bind(this)); + }); if (this.fakegato) { - characteristic.on('change', function(_callback) { + characteristic.on('change', (_callback) => { this.changeAccessoryValue(characteristic, service); - }.bind(this)); + }); } } catch(e){ @@ -3124,8 +3117,6 @@ JeedomPlatform.prototype.bindCharacteristicEvents = function(characteristic, ser // -- Return : nothing JeedomPlatform.prototype.setAccessoryValue = function(value, characteristic, service) { try{ - const that = this; - var action,rgb,cmdId; switch (characteristic.UUID) { case Characteristic.ConfiguredName.UUID : @@ -3142,10 +3133,10 @@ JeedomPlatform.prototype.setAccessoryValue = function(value, characteristic, ser action = 'stop'; cmdId = service.cmd_id; - that.jeedomClient.executeScenarioAction(cmdId, action).then(function(response) { - that.log('info','[Commande Scenario envoyée à Jeedom]','cmdId:' + cmdId,'action:' + action,'response:'+JSON.stringify(response)); - }).catch(function(err) { - that.log('error','Erreur à l\'envoi de la commande Scenario ' + action + ' vers ' + cmdId , err); + this.jeedomClient.executeScenarioAction(cmdId, action).then((response) => { + this.log('info','[Commande Scenario envoyée à Jeedom]','cmdId:' + cmdId,'action:' + action,'response:'+JSON.stringify(response)); + }).catch((err) => { + this.log('error','Erreur à l\'envoi de la commande Scenario ' + action + ' vers ' + cmdId , err); if(err && err.stack) { console.error(err.stack); } }); } else { @@ -3153,27 +3144,27 @@ JeedomPlatform.prototype.setAccessoryValue = function(value, characteristic, ser action = 'run'; cmdId = service.cmd_id; - that.jeedomClient.executeScenarioAction(cmdId, action).then(function(response) { - that.log('info','[Commande Scenario envoyée à Jeedom]','cmdId:' + cmdId,'action:' + action,'response:'+JSON.stringify(response)); - }).catch(function(err) { - that.log('error','Erreur à l\'envoi de la commande Scenario ' + action + ' vers ' + cmdId , err); + this.jeedomClient.executeScenarioAction(cmdId, action).then((response) => { + this.log('info','[Commande Scenario envoyée à Jeedom]','cmdId:' + cmdId,'action:' + action,'response:'+JSON.stringify(response)); + }).catch((err) => { + this.log('error','Erreur à l\'envoi de la commande Scenario ' + action + ' vers ' + cmdId , err); if(err && err.stack) { console.error(err.stack); } }); } } else if (service.actions.Push){ if(value == 1) { this.command('Pushed', null, service); - setTimeout(function() { + setTimeout(() => { characteristic.updateValue(sanitizeValue(false,characteristic), undefined, 'fromSetValue'); }, 100); } } else if (service.modeSwitch) { // modes plugin if(value == 0) {// turnOff // execute set mode Previous - that.log('debug','info about previous mode',service); + this.log('debug','info about previous mode',service); this.command('modeSetPrevious', null, service); } else {// turnOn - that.log('debug','info about mode',service); + this.log('debug','info about mode',service); this.command('modeSet', null, service); } } else { @@ -3203,7 +3194,7 @@ JeedomPlatform.prototype.setAccessoryValue = function(value, characteristic, ser } else { value = characteristic.value; } - setTimeout(function() { + setTimeout(() => { characteristic.updateValue(sanitizeValue(value,characteristic), undefined, 'fromSetValue'); }, 100); break; @@ -3214,7 +3205,7 @@ JeedomPlatform.prototype.setAccessoryValue = function(value, characteristic, ser } else { value = characteristic.value; } - setTimeout(function() { + setTimeout(() => { characteristic.updateValue(sanitizeValue(value,characteristic), undefined, 'fromSetValue'); }, 100); break; @@ -3225,7 +3216,7 @@ JeedomPlatform.prototype.setAccessoryValue = function(value, characteristic, ser } else { value = characteristic.value; } - setTimeout(function() { + setTimeout(() => { characteristic.updateValue(sanitizeValue(value,characteristic), undefined, 'fromSetValue'); }, 100); break; @@ -3265,65 +3256,118 @@ JeedomPlatform.prototype.setAccessoryValue = function(value, characteristic, ser this.command('SetAlarmMode', value, service); } break; - case Characteristic.CurrentPosition.UUID: case Characteristic.TargetPosition.UUID: - case Characteristic.PositionState.UUID: // could be Service.Window or Service.Door too so we check + value=parseInt(value); if (service.UUID == Service.WindowCovering.UUID) { if(service.FlapType=="Closing") { // flap in percent Closing (100% = closed / 0% = open) if(service.actions.down && service.actions.up) { if (service.actions.slider) { - if (parseInt(value) === service.minValue) { - action = 'flapUp'; - } else if (parseInt(value) === service.maxValue) { + if (value === 0) { + service.Moving=Characteristic.PositionState.DECREASING; + service.TargetValue=0; action = 'flapDown'; + this.log('debug','---------set Blinds action:',action,' soit ',service.TargetValue,'/',100,' : ',positionStateLabel(service.Moving)); + } else if (value === 100) { + service.Moving=Characteristic.PositionState.INCREASING; + service.TargetValue=100; + action = 'flapUp'; + this.log('debug','---------set Blinds action:',action,' soit ',service.TargetValue,'/',100,' : ',positionStateLabel(service.Moving)); } else { action = 'setValue'; const oldValue = value; - value = 100 - parseInt(value);// invert percentage + value = 100 - value;// invert percentage value = Math.round(((value / 100)*(service.maxValue-service.minValue))+service.minValue); // transform from percentage to scale - this.log('debug','---------set Inverted Blinds Value:',oldValue,'% soit ',value,'/',service.maxValue); + if(value > service.infos.state.currentValue) { + service.Moving=Characteristic.PositionState.DECREASING; + } else if (value != service.infos.state.currentValue) { + service.Moving=Characteristic.PositionState.INCREASING; + } else { + service.Moving=Characteristic.PositionState.STOPPED; + } + service.TargetValue=oldValue; + this.log('debug','---------set Inverted Blinds Value:',oldValue,'% soit ',value,'/',service.maxValue,' : ',positionStateLabel(service.Moving)); } } - else if (parseInt(value) < ((service.maxValue-service.minValue)/2)) { - action = 'flapUp'; - } else { + else if (value < 50) { + service.Moving=Characteristic.PositionState.DECREASING; + service.TargetValue=0; action = 'flapDown'; + this.log('debug','---------set Blinds action:',action,' soit ',service.TargetValue,'/',100,' : ',positionStateLabel(service.Moving)); + } else { + service.Moving=Characteristic.PositionState.INCREASING; + service.TargetValue=100; + action = 'flapUp'; + this.log('debug','---------set Blinds action:',action,' soit ',service.TargetValue,'/',100,' : ',positionStateLabel(service.Moving)); } } else if (service.actions.slider) { action = 'setValue'; const oldValue = value; - value = 100 - parseInt(value);// invert percentage + value = 100 - value;// invert percentage value = Math.round(((value / 100)*(service.maxValue-service.minValue))+service.minValue); // transform from percentage to scale - this.log('debug','---------set Inverted Blinds Value:',oldValue,'% soit ',value,'/',service.maxValue); + if(value > service.infos.state.currentValue) { + service.Moving=Characteristic.PositionState.DECREASING; + } else if (value != service.infos.state.currentValue) { + service.Moving=Characteristic.PositionState.INCREASING; + } else { + service.Moving=Characteristic.PositionState.STOPPED; + } + service.TargetValue=oldValue; + this.log('debug','---------set Inverted Blinds Value:',oldValue,'% soit ',value,'/',service.maxValue,' : ',positionStateLabel(service.Moving)); } } else if (service.FlapType=="Opening") { // flap in percent Opening (100% = open / 0% = closed) if(service.actions.down && service.actions.up) { if (service.actions.slider) { - if (parseInt(value) === service.minValue) { + if (value === 0) { + service.Moving=Characteristic.PositionState.DECREASING; + service.TargetValue=0; action = 'flapDown'; - } else if (parseInt(value) === service.maxValue) { + this.log('debug','---------set Blinds action:',action,' soit ',service.TargetValue,'/',100,' : ',positionStateLabel(service.Moving)); + } else if (value === 100) { + service.Moving=Characteristic.PositionState.INCREASING; + service.TargetValue=100; action = 'flapUp'; + this.log('debug','---------set Blinds action:',action,' soit ',service.TargetValue,'/',100,' : ',positionStateLabel(service.Moving)); } else { action = 'setValue'; - value = parseInt(value); const oldValue = value; value = Math.round(((value / 100)*(service.maxValue-service.minValue))+service.minValue);// transform from percentage to scale - this.log('debug','---------set Blinds Value:',oldValue,'% soit ',value,'/',service.maxValue); + if(value > service.infos.state.currentValue) { + service.Moving=Characteristic.PositionState.INCREASING; + } else if (value != service.infos.state.currentValue) { + service.Moving=Characteristic.PositionState.DECREASING; + } else { + service.Moving=Characteristic.PositionState.STOPPED; + } + service.TargetValue=oldValue; + this.log('debug','---------set Blinds Value:',oldValue,'% soit ',value,'/',service.maxValue,' : ',positionStateLabel(service.Moving)); } } - else if (parseInt(value) < ((service.maxValue-service.minValue)/2)) { + else if (value < 50) { + service.Moving=Characteristic.PositionState.DECREASING; + service.TargetValue=0; action = 'flapDown'; + this.log('debug','---------set Blinds action:',action,' soit ',service.TargetValue,'/',100,' : ',positionStateLabel(service.Moving)); } else { + service.Moving=Characteristic.PositionState.INCREASING; + service.TargetValue=100; action = 'flapUp'; + this.log('debug','---------set Blinds action:',action,' soit ',service.TargetValue,'/',100,' : ',positionStateLabel(service.Moving)); } } else if (service.actions.slider) { action = 'setValue'; - value = parseInt(value); const oldValue = value; value = Math.round(((value / 100)*(service.maxValue-service.minValue))+service.minValue);// transform from percentage to scale - this.log('debug','---------set Blinds Value:',oldValue,'% soit ',value,'/',service.maxValue); + if(value > service.infos.state.currentValue) { + service.Moving=Characteristic.PositionState.INCREASING; + } else if (value != service.infos.state.currentValue) { + service.Moving=Characteristic.PositionState.DECREASING; + } else { + service.Moving=Characteristic.PositionState.STOPPED; + } + service.TargetValue=oldValue; + this.log('debug','---------set Blinds Value:',oldValue,'% soit ',value,'/',service.maxValue,' : ',positionStateLabel(service.Moving)); } } @@ -3333,30 +3377,54 @@ JeedomPlatform.prototype.setAccessoryValue = function(value, characteristic, ser if (service.UUID == Service.Window.UUID) { if(service.actions.down && service.actions.up) { if (service.actions.slider) { - if (parseInt(value) === service.minValue) { + if (value === 0) { + service.Moving=Characteristic.PositionState.DECREASING; + service.TargetValue=0; action = 'windowDown'; - } else if (parseInt(value) === service.maxValue) { + this.log('debug','---------set WindowMoto action:',action,' soit ',service.TargetValue,'/',100,' : ',positionStateLabel(service.Moving)); + } else if (value === 100) { + service.Moving=Characteristic.PositionState.INCREASING; + service.TargetValue=100; action = 'windowUp'; + this.log('debug','---------set WindowMoto action:',action,' soit ',service.TargetValue,'/',100,' : ',positionStateLabel(service.Moving)); } else { action = 'setValue'; - value = parseInt(value); const oldValue = value; value = Math.round(((value / 100)*(service.maxValue-service.minValue))+service.minValue); - this.log('debug','---------set WindowMoto Value:',oldValue,'% soit ',value,'/',service.maxValue); + if(value > service.infos.state) { + service.Moving=Characteristic.PositionState.INCREASING; + } else if (value != service.infos.state) { + service.Moving=Characteristic.PositionState.DECREASING; + } + service.TargetValue=oldValue; + this.log('debug','---------set WindowMoto Value:',oldValue,'% soit ',value,'/',service.maxValue,' : ',positionStateLabel(service.Moving)); } } - else if (parseInt(value) < ((service.maxValue-service.minValue)/2)) { + else if (value < 50) { + service.Moving=Characteristic.PositionState.DECREASING; + service.TargetValue=0; action = 'windowDown'; + this.log('debug','---------set WindowMoto action:',action,' soit ',service.TargetValue,'/',100,' : ',positionStateLabel(service.Moving)); } else { + service.Moving=Characteristic.PositionState.INCREASING; + service.TargetValue=100; action = 'windowUp'; + this.log('debug','---------set WindowMoto action:',action,' soit ',service.TargetValue,'/',100,' : ',positionStateLabel(service.Moving)); } } else if (service.actions.slider) { action = 'setValue'; - value = parseInt(value); const oldValue = value; value = Math.round(((value / 100)*(service.maxValue-service.minValue))+service.minValue); - this.log('debug','---------set WindowMoto Value:',oldValue,'% soit ',value,'/',service.maxValue); + if(value > service.infos.state) { + service.Moving=Characteristic.PositionState.INCREASING; + } else if (value != service.infos.state) { + service.Moving=Characteristic.PositionState.DECREASING; + } else { + service.Moving=Characteristic.PositionState.STOPPED; + } + service.TargetValue=oldValue; + this.log('debug','---------set WindowMoto Value:',oldValue,'% soit ',value,'/',service.maxValue,' : ',positionStateLabel(service.Moving)); } this.command(action, value, service); @@ -3443,36 +3511,32 @@ JeedomPlatform.prototype.setAccessoryValue = function(value, characteristic, ser } }; -JeedomPlatform.prototype.findAccessoryByService = function(service) { - for (const acc in this.accessories) { - if (this.accessories.hasOwnProperty(acc)) { - for(const ser in this.accessories[acc].services) { - if (this.accessories[acc].services.hasOwnProperty(ser)) { - if(this.accessories[acc].services[ser].cmd_id && this.accessories[acc].services[ser].cmd_id.toString() == service.cmd_id.toString()) { - return this.accessories[acc]; - } - } - } - } - } +JeedomPlatform.prototype.findAccessoryByService = function(serviceToFind) { + const targetCmdId = serviceToFind.cmd_id.toString(); + for (const accessory of Object.values(this.accessories)) { + for (const service of Object.values(accessory.services)) { + if (service.cmd_id && service.cmd_id.toString() === targetCmdId) { + return accessory; + } + } + } }; JeedomPlatform.prototype.changeAccessoryValue = function(characteristic, service) { - const that = this; - const cmdList = that.jeedomClient.getDeviceCmdFromCache(service.eqID); + const cmdList = this.jeedomClient.getDeviceCmdFromCache(service.eqID); switch (characteristic.UUID) { case Characteristic.ContactSensorState.UUID : for (const cmd of cmdList) { if ((cmd.generic_type == 'OPENING' || cmd.generic_type == 'OPENING_WINDOW') && cmd.id == service.cmd_id) { - if(that.fakegato) { + if(this.fakegato) { const realValue = parseInt(service.invertBinary)==0 ? toBool(cmd.currentValue) : !toBool(cmd.currentValue); // invertBinary ? if(realValue === false) { service.eqLogic.numberOpened++; } service.eqLogic.lastAct=Math.round(new Date().valueOf() / 1000)-service.eqLogic.loggingService.getInitialTime(); - that.api.updatePlatformAccessories([this.findAccessoryByService(service)]); + this.api.updatePlatformAccessories([this.findAccessoryByService(service)]); } break; } @@ -3481,9 +3545,9 @@ JeedomPlatform.prototype.changeAccessoryValue = function(characteristic, service case Characteristic.MotionDetected.UUID : for (const cmd of cmdList) { if (cmd.generic_type == 'PRESENCE' && cmd.id == service.cmd_id) { - if(that.fakegato) { + if(this.fakegato) { service.eqLogic.lastAct=Math.round(new Date().valueOf() / 1000)-service.eqLogic.loggingService.getInitialTime(); - that.api.updatePlatformAccessories([this.findAccessoryByService(service)]); + this.api.updatePlatformAccessories([this.findAccessoryByService(service)]); } break; } @@ -3500,8 +3564,6 @@ JeedomPlatform.prototype.changeAccessoryValue = function(characteristic, service // -- Return : nothing JeedomPlatform.prototype.getAccessoryValue = function(characteristic, service, info=null) { try{ - const that = this; - let customizedValues={}; if(service.customizedValues) { customizedValues=service.customizedValues; @@ -3511,7 +3573,7 @@ JeedomPlatform.prototype.getAccessoryValue = function(characteristic, service, i let returnValue = 0; let HRreturnValue; - const cmdList = that.jeedomClient.getDeviceCmdFromCache(service.eqID); + const cmdList = this.jeedomClient.getDeviceCmdFromCache(service.eqID); let targetValueToTest,currentValueToTest; let hsv,mode_PRESENT,mode_AWAY,mode_NIGHT,mode_CLIM,mode_CHAUF; @@ -3527,7 +3589,7 @@ JeedomPlatform.prototype.getAccessoryValue = function(characteristic, service, i break; case Characteristic.On.UUID : if(service.infos.scenario) { - const scenario = that.jeedomClient.getScenarioPropertiesFromCache(service.infos.scenario.id); + const scenario = this.jeedomClient.getScenarioPropertiesFromCache(service.infos.scenario.id); switch(scenario.state) { case 'stop': returnValue = false; @@ -3536,7 +3598,7 @@ JeedomPlatform.prototype.getAccessoryValue = function(characteristic, service, i returnValue = true; break; } - if(that.fakegato && service.eqLogic && service.eqLogic.hasLogging) { + if(this.fakegato && service.eqLogic && service.eqLogic.hasLogging) { service.eqLogic.loggingService.addEntry({ time: Math.round(new Date().valueOf() / 1000), status: ((returnValue)?1:0), @@ -3595,7 +3657,7 @@ JeedomPlatform.prototype.getAccessoryValue = function(characteristic, service, i break; } else if ((cmd.generic_type == "SWITCH_STATE" || cmd.generic_type == "CAMERA_RECORD_STATE") && cmd.id == service.cmd_id) { returnValue = cmd.currentValue; - if(that.fakegato && service.eqLogic && service.eqLogic.hasLogging) { + if(this.fakegato && service.eqLogic && service.eqLogic.hasLogging) { service.eqLogic.loggingService.addEntry({ time: Math.round(new Date().valueOf() / 1000), status: ((returnValue)?1:0), @@ -3634,11 +3696,11 @@ JeedomPlatform.prototype.getAccessoryValue = function(characteristic, service, i break; // Generics case Characteristic.TimesOpened.UUID : - that.log('info','Demande du nombre d\'ouverture de la porte',service.eqLogic.numberOpened); + this.log('info','Demande du nombre d\'ouverture de la porte',service.eqLogic.numberOpened); returnValue = service.eqLogic.numberOpened; break; case Characteristic.LastActivation.UUID : - that.log('info','Demande de la dernière activation',service.eqLogic.lastAct); + this.log('info','Demande de la dernière activation',service.eqLogic.lastAct); returnValue = service.eqLogic.lastAct; break; case Characteristic.ServiceLabelIndex.UUID : @@ -3709,7 +3771,7 @@ JeedomPlatform.prototype.getAccessoryValue = function(characteristic, service, i for (const cmd of cmdList) { if (cmd.generic_type == 'CO2' && cmd.id == service.cmd_id) { returnValue = parseInt(cmd.currentValue); - if(that.fakegato && service.eqLogic && service.eqLogic.hasLogging) { + if(this.fakegato && service.eqLogic && service.eqLogic.hasLogging) { service.eqLogic.loggingService.addEntry({ time: Math.round(new Date().valueOf() / 1000), ppm: returnValue, @@ -3726,7 +3788,7 @@ JeedomPlatform.prototype.getAccessoryValue = function(characteristic, service, i if(service.infos.Index && service.infos.Index.unite && service.infos.Index.unite.toLowerCase() == 'ppb') { // unit should be µg/m3 if it's ppb, multiply it by 4.57 returnValue = parseInt(returnValue*4.57); } - if(that.fakegato && service.eqLogic && service.eqLogic.hasLogging) { + if(this.fakegato && service.eqLogic && service.eqLogic.hasLogging) { service.eqLogic.loggingService.addEntry({ time: Math.round(new Date().valueOf() / 1000), voc: returnValue, @@ -3798,7 +3860,7 @@ JeedomPlatform.prototype.getAccessoryValue = function(characteristic, service, i } else { returnValue = Characteristic.ContactSensorState.CONTACT_DETECTED; } - if(that.fakegato && service.eqLogic && service.eqLogic.hasLogging) { + if(this.fakegato && service.eqLogic && service.eqLogic.hasLogging) { /* if(returnValue === Characteristic.ContactSensorState.CONTACT_NOT_DETECTED) { service.eqLogic.numberOpened++; } */ @@ -3816,12 +3878,12 @@ JeedomPlatform.prototype.getAccessoryValue = function(characteristic, service, i for (const cmd of cmdList) { if (cmd.generic_type == 'BRIGHTNESS' && cmd.id == service.cmd_id) { returnValue = cmd.currentValue; - /* if(that.fakegato && service.eqLogic && service.eqLogic.hasLogging) { + if(this.fakegato && service.eqLogic && service.eqLogic.hasLogging) { service.eqLogic.loggingService.addEntry({ time: Math.round(new Date().valueOf() / 1000), lux: returnValue, }); - } */ + } break; } } @@ -3834,13 +3896,13 @@ JeedomPlatform.prototype.getAccessoryValue = function(characteristic, service, i (cmd.generic_type == 'WEATHER_TEMPERATURE' && cmd.id == service.infos.temperature.id)) { returnValue = cmd.currentValue; - if(that.fakegato && service.eqLogic && service.eqLogic.hasLogging) { + if(this.fakegato && service.eqLogic && service.eqLogic.hasLogging) { if (cmd.generic_type == 'TEMPERATURE' || cmd.generic_type == 'WEATHER_TEMPERATURE') { service.eqLogic.loggingService.addEntry({ time: Math.round(new Date().valueOf() / 1000), temp: returnValue, }); - } else if (cmd.generic_type == 'THERMOSTAT_TEMPERATURE' || cmd.generic_type == 'THERMOSTAT_HC_TEMPERATURE') { + } else if (cmd.generic_type == 'THERMOSTAT_TEMPERATURE') { service.eqLogic.loggingService.addEntry({ time: Math.round(new Date().valueOf() / 1000), currentTemp: returnValue, @@ -3860,7 +3922,7 @@ JeedomPlatform.prototype.getAccessoryValue = function(characteristic, service, i (cmd.generic_type == 'WEATHER_HUMIDITY' && cmd.id == service.infos.humidity.id)) { returnValue = cmd.currentValue; - if(that.fakegato && service.eqLogic && service.eqLogic.hasLogging) { + if(this.fakegato && service.eqLogic && service.eqLogic.hasLogging) { service.eqLogic.loggingService.addEntry({ time: Math.round(new Date().valueOf() / 1000), humidity: returnValue, @@ -3876,7 +3938,7 @@ JeedomPlatform.prototype.getAccessoryValue = function(characteristic, service, i (cmd.generic_type == 'WEATHER_PRESSURE' && cmd.id == service.infos.pressure.id)) { returnValue = cmd.currentValue; - if(that.fakegato && service.eqLogic && service.eqLogic.hasLogging) { + if(this.fakegato && service.eqLogic && service.eqLogic.hasLogging) { service.eqLogic.loggingService.addEntry({ time: Math.round(new Date().valueOf() / 1000), pressure: returnValue, @@ -3958,7 +4020,7 @@ JeedomPlatform.prototype.getAccessoryValue = function(characteristic, service, i if (cmd.generic_type == 'PRESENCE' && cmd.id == service.cmd_id) { // returnValue = parseInt(service.invertBinary)==0 ? !toBool(cmd.currentValue) : toBool(cmd.currentValue); // invertBinary ? returnValue = toBool(cmd.currentValue); - if(that.fakegato && service.eqLogic && service.eqLogic.hasLogging) { + if(this.fakegato && service.eqLogic && service.eqLogic.hasLogging) { service.eqLogic.loggingService.addEntry({ time: Math.round(new Date().valueOf() / 1000), status: returnValue?1:0, @@ -4022,8 +4084,8 @@ JeedomPlatform.prototype.getAccessoryValue = function(characteristic, service, i if(maxJeedom) { returnValue = Math.round((returnValue / maxJeedom)*100); } - if (DEV_DEBUG) {that.log('debug','---------update Power(refresh):',returnValue,'% soit',cmd.currentValue,' / ',maxJeedom);} - // that.log('debug','------------PowerVentilo jeedom :',cmd.currentValue,'soit en homekit :',returnValue); + if (DEV_DEBUG) {this.log('debug','---------update Power(refresh):',returnValue,'% soit',cmd.currentValue,' / ',maxJeedom);} + // this.log('debug','------------PowerVentilo jeedom :',cmd.currentValue,'soit en homekit :',returnValue); break; } } @@ -4074,7 +4136,7 @@ JeedomPlatform.prototype.getAccessoryValue = function(characteristic, service, i break; } } - hsv = that.updateHomeKitColorFromJeedom(returnValue, service); + hsv = this.updateHomeKitColorFromJeedom(returnValue, service); returnValue = Math.round(hsv.h); break; case Characteristic.Saturation.UUID : @@ -4084,7 +4146,7 @@ JeedomPlatform.prototype.getAccessoryValue = function(characteristic, service, i break; } } - hsv = that.updateHomeKitColorFromJeedom(returnValue, service); + hsv = this.updateHomeKitColorFromJeedom(returnValue, service); returnValue = Math.round(hsv.s); break; case Characteristic.ColorTemperature.UUID : @@ -4108,8 +4170,8 @@ JeedomPlatform.prototype.getAccessoryValue = function(characteristic, service, i if(maxJeedom != 0) { returnValue = Math.round((returnValue / maxJeedom)*100); } - if (DEV_DEBUG) {that.log('debug','---------update Bright(refresh):',returnValue,'% soit',cmd.currentValue,' / ',maxJeedom);} - // that.log('debug','------------Brightness jeedom :',cmd.currentValue,'soit en homekit :',returnValue); + if (DEV_DEBUG) {this.log('debug','---------update Bright(refresh):',returnValue,'% soit',cmd.currentValue,' / ',maxJeedom);} + // this.log('debug','------------Brightness jeedom :',cmd.currentValue,'soit en homekit :',returnValue); break; } else if (cmd.generic_type == 'LIGHT_BRIGHTNESS' && cmd.id == service.infos.brightness.id) { const maxJeedom = parseInt(service.maxBright) || 100; @@ -4117,8 +4179,8 @@ JeedomPlatform.prototype.getAccessoryValue = function(characteristic, service, i if(maxJeedom != 0) { returnValue = Math.round((returnValue / maxJeedom)*100); } - if (DEV_DEBUG) {that.log('debug','---------update Bright(refresh):',returnValue,'% soit',cmd.currentValue,' / ',maxJeedom);} - // that.log('debug','------------Brightness jeedom :',cmd.currentValue,'soit en homekit :',returnValue); + if (DEV_DEBUG) {this.log('debug','---------update Bright(refresh):',returnValue,'% soit',cmd.currentValue,' / ',maxJeedom);} + // this.log('debug','------------Brightness jeedom :',cmd.currentValue,'soit en homekit :',returnValue); break; } } @@ -4133,34 +4195,34 @@ JeedomPlatform.prototype.getAccessoryValue = function(characteristic, service, i } for (const cmd of cmdList) { if (cmd.generic_type == 'SIREN_STATE') { - if (DEV_DEBUG) {that.log('debug',"Siren_state T=",cmd.currentValue);} + if (DEV_DEBUG) {this.log('debug',"Siren_state T=",cmd.currentValue);} returnValue = Characteristic.SecuritySystemTargetState.DISARM; break; } if(!service.hasAlarmModes) { if (cmd.generic_type == 'ALARM_ENABLE_STATE' && cmd.currentValue == 1) { - if (DEV_DEBUG) {that.log('debug',"Alarm_enable_state T=",cmd.currentValue,"NO MODES");} + if (DEV_DEBUG) {this.log('debug',"Alarm_enable_state T=",cmd.currentValue,"NO MODES");} returnValue = Characteristic.SecuritySystemTargetState.AWAY_ARM; break; } else if (cmd.generic_type == 'ALARM_ENABLE_STATE' && cmd.currentValue == 0) { - if (DEV_DEBUG) {that.log('debug',"Alarm_enable_state T=",cmd.currentValue,"NO MODES");} + if (DEV_DEBUG) {this.log('debug',"Alarm_enable_state T=",cmd.currentValue,"NO MODES");} returnValue = Characteristic.SecuritySystemTargetState.DISARM; break; } } else { if (cmd.generic_type == 'ALARM_ENABLE_STATE' && cmd.currentValue == 0) { - if (DEV_DEBUG) {that.log('debug',"Alarm_enable_state T=",cmd.currentValue);} + if (DEV_DEBUG) {this.log('debug',"Alarm_enable_state T=",cmd.currentValue);} returnValue = Characteristic.SecuritySystemTargetState.DISARM; break; } if (cmd.generic_type == 'ALARM_ENABLE_STATE' && cmd.currentValue == 1) { // if there is mode and alarm is enabled, will continue the search for mode instead ! - if (DEV_DEBUG) {that.log('debug',"Alarm_enable_state T=",cmd.currentValue,'return undefined');} + if (DEV_DEBUG) {this.log('debug',"Alarm_enable_state T=",cmd.currentValue,'return undefined');} returnValue = undefined; continue; } if (cmd.generic_type == 'ALARM_MODE') { - if (DEV_DEBUG) {that.log('debug',"alarm_mode T=",cmd.currentValue);} + if (DEV_DEBUG) {this.log('debug',"alarm_mode T=",cmd.currentValue);} if(service.alarm.present && service.alarm.present.mode_label != undefined) { mode_PRESENT=service.alarm.present.mode_label?.toLowerCase(); @@ -4173,23 +4235,23 @@ JeedomPlatform.prototype.getAccessoryValue = function(characteristic, service, i } switch (cmd.currentValue?.toLowerCase()) { case undefined: - if (DEV_DEBUG) {that.log('debug',"renvoie absent T via undefined",Characteristic.SecuritySystemTargetState.AWAY_ARM);} + if (DEV_DEBUG) {this.log('debug',"renvoie absent T via undefined",Characteristic.SecuritySystemTargetState.AWAY_ARM);} returnValue = Characteristic.SecuritySystemTargetState.AWAY_ARM; break; default: // back compatibility - if (DEV_DEBUG) {that.log('debug',"renvoie absent T via default",Characteristic.SecuritySystemTargetState.AWAY_ARM);} + if (DEV_DEBUG) {this.log('debug',"renvoie absent T via default",Characteristic.SecuritySystemTargetState.AWAY_ARM);} returnValue = Characteristic.SecuritySystemTargetState.AWAY_ARM; break; case mode_PRESENT: - if (DEV_DEBUG) {that.log('debug',"renvoie present T",Characteristic.SecuritySystemTargetState.STAY_ARM);} + if (DEV_DEBUG) {this.log('debug',"renvoie present T",Characteristic.SecuritySystemTargetState.STAY_ARM);} returnValue = Characteristic.SecuritySystemTargetState.STAY_ARM; break; case mode_AWAY: - if (DEV_DEBUG) {that.log('debug',"renvoie absent T",Characteristic.SecuritySystemTargetState.AWAY_ARM);} + if (DEV_DEBUG) {this.log('debug',"renvoie absent T",Characteristic.SecuritySystemTargetState.AWAY_ARM);} returnValue = Characteristic.SecuritySystemTargetState.AWAY_ARM; break; case mode_NIGHT: - if (DEV_DEBUG) {that.log('debug',"renvoie nuit T",Characteristic.SecuritySystemTargetState.NIGHT_ARM);} + if (DEV_DEBUG) {this.log('debug',"renvoie nuit T",Characteristic.SecuritySystemTargetState.NIGHT_ARM);} returnValue = Characteristic.SecuritySystemTargetState.NIGHT_ARM; break; } @@ -4209,56 +4271,56 @@ JeedomPlatform.prototype.getAccessoryValue = function(characteristic, service, i for (const cmd of cmdList) { if (cmd.generic_type == 'SIREN_STATE') { if (cmd.currentValue == 1) { - if (DEV_DEBUG) {that.log('debug',"Siren_State C=",cmd.currentValue);} + if (DEV_DEBUG) {this.log('debug',"Siren_State C=",cmd.currentValue);} returnValue = Characteristic.SecuritySystemCurrentState.ALARM_TRIGGERED; break; } else if (cmd.currentValue == 0) { - if (DEV_DEBUG) {that.log('debug',"Siren_state C=",cmd.currentValue);} + if (DEV_DEBUG) {this.log('debug',"Siren_state C=",cmd.currentValue);} returnValue = Characteristic.SecuritySystemCurrentState.DISARMED; break; } else { - if (DEV_DEBUG) {that.log('debug',"Siren_state C IMPOSSIBLE =",cmd.currentValue);} + if (DEV_DEBUG) {this.log('debug',"Siren_state C IMPOSSIBLE =",cmd.currentValue);} returnValue = Characteristic.SecuritySystemCurrentState.DISARMED; break; } } if (cmd.generic_type == 'ALARM_STATE') { if(cmd.currentValue == 1) { - if (DEV_DEBUG) {that.log('debug',"Alarm_State C=",cmd.currentValue);} + if (DEV_DEBUG) {this.log('debug',"Alarm_State C=",cmd.currentValue);} returnValue = Characteristic.SecuritySystemCurrentState.ALARM_TRIGGERED; break; } else { continue; } } if (!service.hasAlarmModes) { if (cmd.generic_type == 'ALARM_ENABLE_STATE' && cmd.currentValue == 1) { - if (DEV_DEBUG) {that.log('debug',"Alarm_enable_state C=",cmd.currentValue,"NO MODES");} + if (DEV_DEBUG) {this.log('debug',"Alarm_enable_state C=",cmd.currentValue,"NO MODES");} returnValue = Characteristic.SecuritySystemCurrentState.AWAY_ARM; break; } else if (cmd.generic_type == 'ALARM_ENABLE_STATE' && cmd.currentValue == 0) { - if (DEV_DEBUG) {that.log('debug',"Alarm_enable_state C=",cmd.currentValue,"NO MODES");} + if (DEV_DEBUG) {this.log('debug',"Alarm_enable_state C=",cmd.currentValue,"NO MODES");} returnValue = Characteristic.SecuritySystemCurrentState.DISARMED; break; } } else { if (cmd.generic_type == 'ALARM_ENABLE_STATE' && cmd.currentValue == 0) { - if (DEV_DEBUG) {that.log('debug',"Alarm_enable_state C=",cmd.currentValue);} + if (DEV_DEBUG) {this.log('debug',"Alarm_enable_state C=",cmd.currentValue);} returnValue = Characteristic.SecuritySystemCurrentState.DISARMED; break; } if (cmd.generic_type == 'ALARM_ENABLE_STATE' && cmd.currentValue == 1) { // if there is mode and alarm is enabled, will continue the search for mode instead ! - if (DEV_DEBUG) {that.log('debug',"Alarm_enable_state C=",cmd.currentValue,'return undefined');} + if (DEV_DEBUG) {this.log('debug',"Alarm_enable_state C=",cmd.currentValue,'return undefined');} returnValue = undefined; if(info && info.generic_type == 'ALARM_ENABLE_STATE') { - if (DEV_DEBUG) {that.log('debug',"And break");} + if (DEV_DEBUG) {this.log('debug',"And break");} break; } else { - if (DEV_DEBUG) {that.log('debug',"And continue");} + if (DEV_DEBUG) {this.log('debug',"And continue");} continue; } } if (cmd.generic_type == 'ALARM_MODE') { - if (DEV_DEBUG) {that.log('debug',"alarm_mode C=",cmd.currentValue?.toLowerCase());} + if (DEV_DEBUG) {this.log('debug',"alarm_mode C=",cmd.currentValue?.toLowerCase());} if(service.alarm.present && service.alarm.present.mode_label != undefined) { mode_PRESENT=service.alarm.present.mode_label?.toLowerCase(); @@ -4271,23 +4333,23 @@ JeedomPlatform.prototype.getAccessoryValue = function(characteristic, service, i } switch (cmd.currentValue?.toLowerCase()) { case undefined: - if (DEV_DEBUG) {that.log('debug',"renvoie absent C via undefined",Characteristic.SecuritySystemCurrentState.AWAY_ARM);} + if (DEV_DEBUG) {this.log('debug',"renvoie absent C via undefined",Characteristic.SecuritySystemCurrentState.AWAY_ARM);} returnValue = Characteristic.SecuritySystemCurrentState.AWAY_ARM; break; default: // back compatibility - if (DEV_DEBUG) {that.log('debug',"renvoie absent C via default",Characteristic.SecuritySystemCurrentState.AWAY_ARM);} + if (DEV_DEBUG) {this.log('debug',"renvoie absent C via default",Characteristic.SecuritySystemCurrentState.AWAY_ARM);} returnValue = Characteristic.SecuritySystemCurrentState.AWAY_ARM; break; case mode_PRESENT: - if (DEV_DEBUG) {that.log('debug',"renvoie present C",Characteristic.SecuritySystemCurrentState.STAY_ARM);} + if (DEV_DEBUG) {this.log('debug',"renvoie present C",Characteristic.SecuritySystemCurrentState.STAY_ARM);} returnValue = Characteristic.SecuritySystemCurrentState.STAY_ARM; break; case mode_AWAY: - if (DEV_DEBUG) {that.log('debug',"renvoie absent C",Characteristic.SecuritySystemCurrentState.AWAY_ARM);} + if (DEV_DEBUG) {this.log('debug',"renvoie absent C",Characteristic.SecuritySystemCurrentState.AWAY_ARM);} returnValue = Characteristic.SecuritySystemCurrentState.AWAY_ARM; break; case mode_NIGHT: - if (DEV_DEBUG) {that.log('debug',"renvoie nuit C",Characteristic.SecuritySystemCurrentState.NIGHT_ARM);} + if (DEV_DEBUG) {this.log('debug',"renvoie nuit C",Characteristic.SecuritySystemCurrentState.NIGHT_ARM);} returnValue = Characteristic.SecuritySystemCurrentState.NIGHT_ARM; break; } @@ -4302,7 +4364,7 @@ JeedomPlatform.prototype.getAccessoryValue = function(characteristic, service, i for (const cmd of cmdList) { if (cmd.generic_type == 'THERMOSTAT_STATE_NAME' || cmd.generic_type == 'THERMOSTAT_HC_STATE_NAME') { if(cmd.currentValue != undefined && cmd.currentValue != null) { - that.log('debug','----Current State Thermo :',cmd.currentValue.toString().toLowerCase()); + this.log('debug','----Current State Thermo :',cmd.currentValue.toString().toLowerCase()); switch(cmd.currentValue.toString().toLowerCase()) { default: case 'off' : // EN @@ -4365,7 +4427,7 @@ JeedomPlatform.prototype.getAccessoryValue = function(characteristic, service, i if(service.thermo.chauf && service.thermo.chauf.mode_label !== undefined) { mode_CHAUF=service.thermo.chauf.mode_label.toString().toLowerCase(); } - that.log('debug','TargetThermo :',mode_CLIM,mode_CHAUF,':',cmd.currentValue.toString().toLowerCase()); + this.log('debug','TargetThermo :',mode_CLIM,mode_CHAUF,':',cmd.currentValue.toString().toLowerCase()); switch(cmd.currentValue.toString().toLowerCase()) { case 'off' : // EN case 'stopped' : // EN @@ -4392,6 +4454,8 @@ JeedomPlatform.prototype.getAccessoryValue = function(characteristic, service, i case 'ninguna': // ES case 'ohne': // DE case 'nemhum': // PT + case 'manuel': // Plugin Boiler + case 'manual': // Plugin Boiler returnValue = Characteristic.TargetHeatingCoolingState.AUTO; break; } @@ -4404,7 +4468,7 @@ JeedomPlatform.prototype.getAccessoryValue = function(characteristic, service, i if(service.thermoHC.chauf && service.thermoHC.chauf.mode_label !== undefined) { mode_CHAUF=service.thermoHC.chauf.mode_label.toString().toLowerCase(); } - that.log('debug','TargetThermo :',mode_CLIM,mode_CHAUF,':',cmd.currentValue.toString().toLowerCase()); + this.log('debug','TargetThermo :',mode_CLIM,mode_CHAUF,':',cmd.currentValue.toString().toLowerCase()); switch(cmd.currentValue.toString().toLowerCase()) { case 'off' : // EN case 'stopped' : // EN @@ -4442,7 +4506,7 @@ JeedomPlatform.prototype.getAccessoryValue = function(characteristic, service, i for (const cmd of cmdList) { if (cmd.generic_type == 'THERMOSTAT_SETPOINT') { returnValue = cmd.currentValue; - if(that.fakegato && service.eqLogic && service.eqLogic.hasLogging) { + if(this.fakegato && service.eqLogic && service.eqLogic.hasLogging) { service.eqLogic.loggingService.addEntry({ time: Math.round(new Date().valueOf() / 1000), setTemp : returnValue, @@ -4500,7 +4564,7 @@ JeedomPlatform.prototype.getAccessoryValue = function(characteristic, service, i } if (DEV_DEBUG) { console.log(customizedValues); - that.log('debug','Target Garage/Barrier Homekit: '+returnValue+' soit en Jeedom:'+cmd.currentValue+" ("+HRreturnValue+")"); + this.log('debug','Target Garage/Barrier Homekit: '+returnValue+' soit en Jeedom:'+cmd.currentValue+" ("+HRreturnValue+")"); } break; } @@ -4537,7 +4601,7 @@ JeedomPlatform.prototype.getAccessoryValue = function(characteristic, service, i } if (DEV_DEBUG) { console.log(customizedValues); - that.log('debug','Etat Garage/Barrier Homekit: '+returnValue+' soit en Jeedom:'+cmd.currentValue+" ("+HRreturnValue+")"); + this.log('debug','Etat Garage/Barrier Homekit: '+returnValue+' soit en Jeedom:'+cmd.currentValue+" ("+HRreturnValue+")"); } break; } @@ -4545,46 +4609,76 @@ JeedomPlatform.prototype.getAccessoryValue = function(characteristic, service, i break; // Flaps & windowMoto case Characteristic.CurrentPosition.UUID : - case Characteristic.TargetPosition.UUID : for (const cmd of cmdList) { if (cmd.generic_type == 'FLAP_STATE' && cmd.id == service.cmd_id) { returnValue = parseInt(cmd.currentValue); returnValue = Math.round(((returnValue-service.minValue) / (service.maxValue-service.minValue))*100); - + if(service.maxValue == 100) { returnValue = returnValue > (service.maxValue-5) ? service.maxValue : returnValue; // >95% is 100% in home (flaps need yearly tunning) } - that.log('debug','---------update Blinds Value(refresh):',returnValue,'% soit',cmd.currentValue,' / ',service.maxValue); + + if(returnValue === service.TargetValue) {service.Moving=Characteristic.PositionState.STOPPED;} + else if (service.TargetValue !== undefined && service.Moving===Characteristic.PositionState.STOPPED) {service.TargetValue=undefined;} + this.log('debug','---------update Blinds Value(refresh):',returnValue,'% soit',cmd.currentValue,' / ',service.maxValue,' : ',positionStateLabel(service.Moving)); break; } if (cmd.generic_type == 'FLAP_STATE_CLOSING' && cmd.id == service.cmd_id) { returnValue = parseInt(cmd.currentValue); returnValue = Math.round(((returnValue-service.minValue) / (service.maxValue-service.minValue))*100); + if(service.maxValue == 100) { returnValue = returnValue > (service.maxValue-5) ? service.maxValue : returnValue; // >95% is 100% in home (flaps need yearly tunning) } returnValue = 100-returnValue; // invert percentage - that.log('debug','---------update Inverted Blinds Value(refresh):',returnValue,'% soit',cmd.currentValue,' / ',service.maxValue); + + if(returnValue === service.TargetValue) {service.Moving=Characteristic.PositionState.STOPPED;} + else if (service.TargetValue !== undefined && service.Moving===Characteristic.PositionState.STOPPED) {service.TargetValue=undefined;} + this.log('debug','---------update Inverted Blinds Value(refresh):',returnValue,'% soit',cmd.currentValue,' / ',service.maxValue,' : ',positionStateLabel(service.Moving)); break; } if (cmd.generic_type == 'WINDOW_STATE' && cmd.id == service.cmd_id) { returnValue = parseInt(cmd.currentValue); returnValue = Math.round(((returnValue-service.minValue) / (service.maxValue-service.minValue))*100); - that.log('debug','---------update WindowMoto Value(refresh):',returnValue,'% soit',cmd.currentValue,' / ',service.maxValue); + if(returnValue === service.TargetValue) {service.Moving=Characteristic.PositionState.STOPPED;} + else if (service.TargetValue !== undefined && service.Moving===Characteristic.PositionState.STOPPED) {service.TargetValue=undefined;} + this.log('debug','---------update WindowMoto Value(refresh):',returnValue,'% soit',cmd.currentValue,' / ',service.maxValue,' : ',positionStateLabel(service.Moving)); break; } } break; + case Characteristic.TargetPosition.UUID : + if(service.TargetValue === undefined) { + returnValue = parseInt(service.infos.state.currentValue); + returnValue = Math.round(((returnValue-service.minValue) / (service.maxValue-service.minValue))*100); + + if(service.maxValue == 100) { + returnValue = returnValue > (service.maxValue-5) ? service.maxValue : returnValue; // >95% is 100% in home (flaps need yearly tunning) + } + if(service.FlapType=="Closing" && service.Moving!==Characteristic.PositionState.STOPPED) { + this.log('debug','---------update TargetPosition(Closing)before:',returnValue,'%'); + returnValue=100-returnValue; + } + } else { + returnValue = service.TargetValue; + } + this.log('debug','---------update TargetPosition(refresh):',returnValue,'%'); + break; case Characteristic.PositionState.UUID : - returnValue = Characteristic.PositionState.STOPPED; + if('Moving' in service) { + returnValue = service.Moving; + } else { + returnValue = Characteristic.PositionState.STOPPED; + } + this.log('debug','---------update PositionState(refresh):',positionStateLabel(returnValue)); break; case Characteristic.CurrentHorizontalTiltAngle.UUID : case Characteristic.TargetHorizontalTiltAngle.UUID : for (const cmd of cmdList) { if (cmd.generic_type == 'FLAP_HOR_TILT_STATE') { returnValue = parseInt(cmd.currentValue); - that.log('debug','---------update Blinds HorTilt Value(refresh):',returnValue); + this.log('debug','---------update Blinds HorTilt Value(refresh):',returnValue); break; } } @@ -4594,7 +4688,7 @@ JeedomPlatform.prototype.getAccessoryValue = function(characteristic, service, i for (const cmd of cmdList) { if (cmd.generic_type == 'FLAP_VER_TILT_STATE') { returnValue = parseInt(cmd.currentValue); - that.log('debug','---------update Blinds VerTilt Value(refresh):',returnValue); + this.log('debug','---------update Blinds VerTilt Value(refresh):',returnValue); break; } } @@ -4605,7 +4699,7 @@ JeedomPlatform.prototype.getAccessoryValue = function(characteristic, service, i if (cmd.generic_type == 'LOCK_STATE') { service.target=cmd.currentValue; if(cmd.eqType == 'nuki' || (cmd.eqType == 'jeelink' && cmd.real_eqType && cmd.real_eqType == 'nuki')) { - if (DEV_DEBUG) {that.log('debug','LockCurrentState (nuki) : ',cmd.currentValue);} + if (DEV_DEBUG) {this.log('debug','LockCurrentState (nuki) : ',cmd.currentValue);} switch(parseInt(cmd.currentValue)) { case 0 : returnValue=Characteristic.LockCurrentState.SECURED; @@ -4621,10 +4715,10 @@ JeedomPlatform.prototype.getAccessoryValue = function(characteristic, service, i break; } // } else if(cmd.eqType == 'thekeys' || (cmd.eqType == 'jeelink' && cmd.real_eqType && cmd.real_eqType == 'thekeys')) { - // if (DEV_DEBUG) that.log('debug','LockCurrentState (thekeys) : ',cmd.currentValue); + // if (DEV_DEBUG) this.log('debug','LockCurrentState (thekeys) : ',cmd.currentValue); // returnValue = toBool(cmd.currentValue) === false ? Characteristic.LockCurrentState.SECURED : Characteristic.LockCurrentState.UNSECURED; } else { - if (DEV_DEBUG) {that.log('debug','LockCurrentState : ',cmd.currentValue);} + if (DEV_DEBUG) {this.log('debug','LockCurrentState : ',cmd.currentValue);} returnValue = toBool(cmd.currentValue) === true ? Characteristic.LockCurrentState.SECURED : Characteristic.LockCurrentState.UNSECURED; } } @@ -4638,13 +4732,13 @@ JeedomPlatform.prototype.getAccessoryValue = function(characteristic, service, i else {service.target=targetVal;} if(cmd.eqType == 'nuki' || (cmd.eqType == 'jeelink' && cmd.real_eqType && cmd.real_eqType == 'nuki')) { - if (DEV_DEBUG) {that.log('debug','LockTargetState (nuki) : ',cmd.currentValue,'service.target : ',service.target);} + if (DEV_DEBUG) {this.log('debug','LockTargetState (nuki) : ',cmd.currentValue,'service.target : ',service.target);} returnValue = toBool(targetVal) === false ? Characteristic.LockTargetState.SECURED : Characteristic.LockTargetState.UNSECURED; // } else if(cmd.eqType == 'thekeys' || (cmd.eqType == 'jeelink' && cmd.real_eqType && cmd.real_eqType == 'thekeys')) { - // if (DEV_DEBUG) {that.log('debug','LockTargetState (thekeys) : ',cmd.currentValue);} + // if (DEV_DEBUG) {this.log('debug','LockTargetState (thekeys) : ',cmd.currentValue);} // returnValue = toBool(cmd.currentValue) === false ? Characteristic.LockTargetState.SECURED : Characteristic.LockTargetState.UNSECURED; } else { - if (DEV_DEBUG) {that.log('debug','LockTargetState : ',cmd.currentValue,'service.target : ',service.target);} + if (DEV_DEBUG) {this.log('debug','LockTargetState : ',cmd.currentValue,'service.target : ',service.target);} returnValue = toBool(targetVal) === true ? Characteristic.LockTargetState.SECURED : Characteristic.LockTargetState.UNSECURED; } } @@ -4767,7 +4861,7 @@ JeedomPlatform.prototype.getAccessoryValue = function(characteristic, service, i if(service.infos.power && service.infos.power.unite && service.infos.power.unite.toLowerCase() == 'kw') { returnValue = Math.round(cmd.currentValue*1000); } - if(that.fakegato && service.eqLogic && service.eqLogic.hasLogging) { + if(this.fakegato && service.eqLogic && service.eqLogic.hasLogging) { service.eqLogic.loggingService.addEntry({ time: Math.round(new Date().valueOf() / 1000), power: returnValue, @@ -4853,7 +4947,7 @@ JeedomPlatform.prototype.getAccessoryValue = function(characteristic, service, i } } } - that.log('debug','**********GetState ProgrammableSwitchEvent: '+returnValue); + this.log('debug','**********GetState ProgrammableSwitchEvent: '+returnValue); break; case Characteristic.OutletInUse.UUID : for (const cmd of cmdList) { @@ -4890,6 +4984,14 @@ JeedomPlatform.prototype.getAccessoryValue = function(characteristic, service, i } }; +function positionStateLabel(ps) { + if(ps == Characteristic.PositionState.DECREASING) { + return "DECREASING"; + } else if (ps == Characteristic.PositionState.INCREASING) { + return "INCREASING"; + } + return "STOPPED"; +} // -- sanitizeValue // -- Desc : limit the value to the min and max characteristic + round the float to the same precision than the minStep @@ -4985,9 +5087,7 @@ function toBool(val) { // -- Return : nothing JeedomPlatform.prototype.command = function(action, value, service) { try{ - const that = this; - - const cmdList = that.jeedomClient.getDeviceCmdFromCache(service.eqID); + const cmdList = this.jeedomClient.getDeviceCmdFromCache(service.eqID); var cmdId = service.cmd_id; let found=false; @@ -5088,7 +5188,7 @@ JeedomPlatform.prototype.command = function(action, value, service) { } found = true; cmdFound=cmd.generic_type; - needToTemporize=500; + needToTemporize=0; } break; case 'FLAP_HOR_TILT_SLIDER' : @@ -5118,7 +5218,7 @@ JeedomPlatform.prototype.command = function(action, value, service) { // brightness up to 100% in homekit, in Jeedom (Zwave) up to 99 max. Convert to Zwave found = true; cmdFound=cmd.generic_type; - needToTemporize=500; + needToTemporize=0; } break; case 'GB_OPEN' : @@ -5377,7 +5477,7 @@ JeedomPlatform.prototype.command = function(action, value, service) { break; case 'ALARM_RELEASED' : if(action == 'SetAlarmMode' && value == Characteristic.SecuritySystemTargetState.DISARM) { - that.log('debug',"ALARM_RELEASED","setAlarmMode=",value,cmd.id); + this.log('debug',"ALARM_RELEASED","setAlarmMode=",value,cmd.id); cmdId = cmd.id; cmdFound=cmd.generic_type; found = true; @@ -5385,26 +5485,26 @@ JeedomPlatform.prototype.command = function(action, value, service) { break; case 'ALARM_SET_MODE' : if(action == 'SetAlarmMode' && service.hasAlarmModes) { - that.log('debug',"ALARM_SET_MODE","SetAlarmMode=",action,value); + this.log('debug',"ALARM_SET_MODE","SetAlarmMode=",action,value); cmdFound=cmd.generic_type; if(value == Characteristic.SecuritySystemTargetState.NIGHT_ARM && id_NIGHT != undefined) { cmdId = id_NIGHT; - that.log('debug',"set nuit"); + this.log('debug',"set nuit"); found = true; } else if(value == Characteristic.SecuritySystemTargetState.AWAY_ARM && id_AWAY != undefined) { cmdId = id_AWAY; - that.log('debug',"set absent"); + this.log('debug',"set absent"); found = true; } else if(value == Characteristic.SecuritySystemTargetState.STAY_ARM && id_PRESENT != undefined) { cmdId = id_PRESENT; - that.log('debug',"set present"); + this.log('debug',"set present"); found = true; } } break; case 'ALARM_ARMED' : if(action == 'SetAlarmMode' && value != Characteristic.SecuritySystemTargetState.DISARM && !service.hasAlarmModes) { - that.log('debug',"ALARM_ARMED","SetAlarmMode=",action,cmd.id); + this.log('debug',"ALARM_ARMED","SetAlarmMode=",action,cmd.id); cmdFound=cmd.generic_type; cmdId = cmd.id; found = true; @@ -5444,20 +5544,20 @@ JeedomPlatform.prototype.command = function(action, value, service) { if(action == 'TargetHeatingCoolingState') { if(value == Characteristic.TargetHeatingCoolingState.OFF && id_OFF != undefined) { cmdId = id_OFF; - that.log('debug',"set OFF"); + this.log('debug',"set OFF"); found = true; } else if(value == Characteristic.TargetHeatingCoolingState.HEAT && id_CHAUF != undefined) { cmdId = id_CHAUF; - that.log('debug',"set CHAUF"); + this.log('debug',"set CHAUF"); found = true; } else if(value == Characteristic.TargetHeatingCoolingState.COOL && id_CLIM != undefined) { cmdId = id_CLIM; - that.log('debug',"set CLIM"); + this.log('debug',"set CLIM"); found = true; } else if(value == Characteristic.TargetHeatingCoolingState.AUTO) { cmdId = service.actions.set_setpoint.id; value = service.infos.setpoint.currentValue; - that.log('debug','set AUTO',value); + this.log('debug','set AUTO',value); found = true; } } @@ -5466,20 +5566,20 @@ JeedomPlatform.prototype.command = function(action, value, service) { if(action == 'TargetHeatingCoolingState') { if(value == Characteristic.TargetHeatingCoolingState.OFF && id_OFF != undefined) { cmdId = id_OFF_HC; - that.log('debug',"set OFF"); + this.log('debug',"set OFF"); found = true; } else if(value == Characteristic.TargetHeatingCoolingState.HEAT && id_CHAUF != undefined) { cmdId = id_CHAUF_HC; - that.log('debug',"set CHAUF"); + this.log('debug',"set CHAUF"); found = true; } else if(value == Characteristic.TargetHeatingCoolingState.COOL && id_CLIM != undefined) { cmdId = id_CLIM_HC; - that.log('debug',"set CLIM"); + this.log('debug',"set CLIM"); found = true; } else if(value == Characteristic.TargetHeatingCoolingState.AUTO) { cmdId = service.actions.set_setpointH.id; value = service.infos.setpointH.currentValue; - that.log('debug','set AUTO',value); + this.log('debug','set AUTO',value); found = true; } } @@ -5490,43 +5590,43 @@ JeedomPlatform.prototype.command = function(action, value, service) { if(needToTemporize===0 && needToTemporizeSec===0) { if(cmdFound=="LIGHT_ON") { - if(that.settingLight) { + if(this.settingLight) { if(service.ignoreOnCommandOnBrightnessChange) { return; } } } - that.jeedomClient.executeDeviceAction(cmdId, action, value).then(function(response) { - that.log('info','[Commande envoyée à Jeedom]','cmdId:' + cmdId,'action:' + action,'value: '+value,'generic:'+cmdFound,'response:'+JSON.stringify(response)); - }).catch(function(err) { - that.log('error','Erreur à l\'envoi de la commande ' + action + ' vers ' + service.cmd_id , err); + this.jeedomClient.executeDeviceAction(cmdId, action, value).then((response) => { + this.log('info','[Commande envoyée à Jeedom]','cmdId:' + cmdId,'action:' + action,'value: '+value,'generic:'+cmdFound,'response:'+JSON.stringify(response)); + }).catch((err) => { + this.log('error','Erreur à l\'envoi de la commande ' + action + ' vers ' + service.cmd_id , err); if(err && err.stack) { console.error(err.stack); } }); } else if(needToTemporize) { if(service.temporizator) {clearTimeout(service.temporizator);} - service.temporizator = setTimeout(function(){ - if(cmdFound=="LIGHT_SLIDER") {that.settingLight=false;} - if(cmdFound=="FAN_SLIDER" || cmdFound=="FAN_SPEED") {that.settingFan=false;} + service.temporizator = setTimeout(() => { + if(cmdFound=="LIGHT_SLIDER") {this.settingLight=false;} + if(cmdFound=="FAN_SLIDER" || cmdFound=="FAN_SPEED") {this.settingFan=false;} - that.jeedomClient.executeDeviceAction(cmdId, action, value).then(function(response) { - that.log('info','[Commande T envoyée à Jeedom]','cmdId:' + cmdId,'action:' + action,'value: '+value,'response:'+JSON.stringify(response)); - }).catch(function(err) { - that.log('error','Erreur à l\'envoi de la commande ' + action + ' vers ' + service.cmd_id , err); + this.jeedomClient.executeDeviceAction(cmdId, action, value).then((response) => { + this.log('info','[Commande T envoyée à Jeedom]','cmdId:' + cmdId,'action:' + action,'value: '+value,'response:'+JSON.stringify(response)); + }).catch((err) => { + this.log('error','Erreur à l\'envoi de la commande ' + action + ' vers ' + service.cmd_id , err); if(err && err.stack) { console.error(err.stack); } }); },needToTemporize); } else if(needToTemporizeSec) { if(service.temporizatorSec) {clearTimeout(service.temporizatorSec);} - service.temporizatorSec = setTimeout(function(){ + service.temporizatorSec = setTimeout(() => { if(cmdFound=="LIGHT_ON") { - if(that.settingLight) { + if(this.settingLight) { if(!service.ignoreOnCommandOnBrightnessChange) { - // if(cmdFound=="LIGHT_ON" && service.infos && service.infos.state_bool && service.infos.state_bool.id) that.jeedomClient.updateModelInfo(service.infos.state_bool.id,true); - setTimeout(function(){ - that.jeedomClient.executeDeviceAction(cmdId, action, value).then(function(response) { - that.log('info','[Commande ON LATE envoyée à Jeedom]','cmdId:' + cmdId,'action:' + action,'value: '+value,'response:'+JSON.stringify(response)); - }).catch(function(err) { - that.log('error','Erreur à l\'envoi de la commande ' + action + ' vers ' + service.cmd_id , err); + // if(cmdFound=="LIGHT_ON" && service.infos && service.infos.state_bool && service.infos.state_bool.id) this.jeedomClient.updateModelInfo(service.infos.state_bool.id,true); + setTimeout(() => { + this.jeedomClient.executeDeviceAction(cmdId, action, value).then((response) => { + this.log('info','[Commande ON LATE envoyée à Jeedom]','cmdId:' + cmdId,'action:' + action,'value: '+value,'response:'+JSON.stringify(response)); + }).catch((err) => { + this.log('error','Erreur à l\'envoi de la commande ' + action + ' vers ' + service.cmd_id , err); if(err && err.stack) { console.error(err.stack); } }); },1000); @@ -5535,10 +5635,10 @@ JeedomPlatform.prototype.command = function(action, value, service) { } } - that.jeedomClient.executeDeviceAction(cmdId, action, value).then(function(response) { - that.log('info','[Commande T envoyée à Jeedom]','cmdId:' + cmdId,'action:' + action,'value: '+value,'response:'+JSON.stringify(response)); - }).catch(function(err) { - that.log('error','Erreur à l\'envoi de la commande ' + action + ' vers ' + service.cmd_id , err); + this.jeedomClient.executeDeviceAction(cmdId, action, value).then((response) => { + this.log('info','[Commande T envoyée à Jeedom]','cmdId:' + cmdId,'action:' + action,'value: '+value,'response:'+JSON.stringify(response)); + }).catch((err) => { + this.log('error','Erreur à l\'envoi de la commande ' + action + ' vers ' + service.cmd_id , err); if(err && err.stack) { console.error(err.stack); } }); @@ -5551,129 +5651,103 @@ JeedomPlatform.prototype.command = function(action, value, service) { } }; -// -- subscribeUpdate -// -- Desc : Populate the subscriptions to the characteristic. if the value is changed, the characteristic will be updated -// -- Params -- -// -- service : service containing the characteristic to subscribe to -// -- characteristic : characteristic to subscribe to -// -- Return : nothing -JeedomPlatform.prototype.subscribeUpdate = function(service, characteristic) { - try{ - if (characteristic.UUID == Characteristic.PositionState.UUID) { - return; - } - this.updateSubscriptions.push({ - 'service' : service, - 'characteristic' : characteristic, - }); - } - catch(e){ - this.log('error','Erreur de la fonction subscribeUpdate :',e); - console.error(e.stack); - hasError=true; - } -}; - // -- startPollingUpdate // -- Desc : Get the last status from Jeedom and act on it (update model and subscribers) // -- Params -- // -- Return : nothing JeedomPlatform.prototype.startPollingUpdate = function() { - const that = this; - if(that.pollingUpdateRunning) {return;} - that.pollingUpdateRunning = true; - that.jeedomClient.refreshStates().then(function(updates) { - that.lastPoll = updates.datetime; + if(this.pollingUpdateRunning) {return;} + this.pollingUpdateRunning = true; + this.jeedomClient.refreshStates().then((updates) => { + this.lastPoll = updates.datetime; if (updates.result) { - updates.result.map(function(update) { + updates.result.map((update) => { if (update.name == 'cmd::update' && update.option.value != undefined && update.option.cmd_id) { - if(that.jeedomClient.updateModelInfo(update.option.cmd_id,update.option.value)){ // Update cachedModel - that.updateSubscribers(update);// Update subscribers + if(this.jeedomClient.updateModelInfo(update.option.cmd_id,update.option.value)){ // Update cachedModel + this.updateSubscribers(update);// Update subscribers } } else if(update.name == 'scenario::update' && update.option.state != undefined && update.option.scenario_id) { - that.jeedomClient.updateModelScenario(update.option.scenario_id,update.option.state); // Update cachedModel - that.updateSubscribers(update);// Update subscribers + if(this.jeedomClient.updateModelScenario(update.option.scenario_id,update.option.state)){ // Update cachedModel + this.updateSubscribers(update);// Update subscribers + } } else if(DEV_DEBUG && update.name == 'eqLogic::update' && update.option.eqLogic_id) { - const cacheState = that.jeedomClient.getDevicePropertiesFromCache(update.option.eqLogic_id); - that.jeedomClient.getDeviceProperties(update.option.eqLogic_id).then(function(eqLogic){ + const cacheState = this.jeedomClient.getDevicePropertiesFromCache(update.option.eqLogic_id); + this.jeedomClient.getDeviceProperties(update.option.eqLogic_id).then((eqLogic) => { if(cacheState && eqLogic && cacheState.isEnable != eqLogic.isEnable) { - that.log('debug',"Changing Enable in",update.option.eqLogic_id,'from',cacheState.isEnable,'to',eqLogic.isEnable); - that.jeedomClient.updateModelEq(update.option.eqLogic_id,eqLogic); + this.log('debug',"Changing Enable in",update.option.eqLogic_id,'from',cacheState.isEnable,'to',eqLogic.isEnable); + this.jeedomClient.updateModelEq(update.option.eqLogic_id,eqLogic); } + }).catch((e) => { + this.log('error','Erreur :',e); }); - that.log('debug','[Reçu Type non géré]',update.name+' contenu: '+JSON.stringify(update).replace("\n","")); + this.log('debug','[Reçu Type non géré]',update.name+' contenu: '+JSON.stringify(update).replace("\n","")); } else if(DEV_DEBUG) { - that.log('debug','[Reçu Type non géré]',update.name+' ou contenu invalide: '+JSON.stringify(update).replace("\n","")); + this.log('debug','[Reçu Type non géré]',update.name+' ou contenu invalide: '+JSON.stringify(update).replace("\n","")); } }); } - }).then(function(){ - that.pollingUpdateRunning = false; - that.pollingID = setTimeout(function(){ /* that.log('debug','==RESTART POLLING=='); */that.startPollingUpdate(); }, that.pollerPeriod * 1000); - }).catch(function(err) { - that.log('error','Erreur de récupération des évènements de mise à jour: ', err); + }).then(() => { + this.pollingUpdateRunning = false; + this.pollingID = setImmediate(() => this.startPollingUpdate()); + }).catch((err) => { + this.log('error','Erreur de récupération des évènements de mise à jour: ', err); if(err && err.stack) { console.error(err.stack); } - that.pollingUpdateRunning = false; - that.pollingID = setTimeout(function(){ that.log('debug','!!RESTART POLLING AFTER ERROR!!');that.startPollingUpdate(); }, that.pollerPeriod * 2 * 1000); + this.pollingUpdateRunning = false; + this.pollingID = setTimeout(() => { this.log('debug','!!RESTART POLLING AFTER ERROR!!');this.startPollingUpdate(); }, this.pollerPeriod * 2 * 1000); }); }; // -- updateSubscribers -// -- Desc : update subcribers populated by the subscribeUpdate method +// -- Desc : update subcribers in updateSubscriptions array // -- Params -- // -- update : the update received from Jeedom // -- Return : nothing JeedomPlatform.prototype.updateSubscribers = function(update) { - const that = this; - var subCharact,subService,updateID; - for (let i = 0; i < that.updateSubscriptions.length; i++) { - subCharact = that.updateSubscriptions[i].characteristic; - subService = that.updateSubscriptions[i].service; - - if(update.option.scenario_id) { - updateID = update.option.scenario_id; - } else if(update.option.cmd_id) { - updateID = update.option.cmd_id; - } + const updateID = update.option.scenario_id || update.option.cmd_id; + for (let i = 0; i < this.updateSubscriptions.length; i++) { + const {characteristic: subCharact, service: subService} = this.updateSubscriptions[i]; - // that.log('debug',"update :",updateID,JSON.stringify(subService.infos),JSON.stringify(subService.statusArr),subCharact.UUID); + // this.log('debug',"update :",updateID,JSON.stringify(subService.infos),JSON.stringify(subService.statusArr),subCharact.UUID); const infoFound = findMyID(subService.infos,updateID); const statusFound = findMyID(subService.statusArr,updateID); - if(infoFound != -1 || statusFound != -1) { - let returnValue = that.getAccessoryValue(subCharact, subService, ((infoFound!=-1)?infoFound:statusFound)); - if(returnValue !== undefined && returnValue !== 'no_response') { + if(infoFound !== -1 || statusFound !== -1) { + let returnValue = this.getAccessoryValue(subCharact, subService, (infoFound !== -1?infoFound:statusFound)); + + if (returnValue === 'no_response') { + subCharact.updateValue(new Error('no_response'), undefined, 'fromJeedom'); + } else if(returnValue !== undefined) { returnValue = sanitizeValue(returnValue,subCharact); - if(infoFound != -1 && infoFound.generic_type=="LIGHT_STATE") { // if it's a LIGHT_STATE - if(!that.settingLight) { // and it's not currently being modified - that.log('info','[Commande envoyée à HomeKit]','Cause de modif: "'+((infoFound && infoFound.name)?infoFound.name+'" ('+updateID+')':'')+((statusFound && statusFound.name)?statusFound.name+'" ('+updateID+')':''),"Envoi valeur:",returnValue,'dans',subCharact.displayName); + const logMessage = 'Cause de modif: "' + (infoFound && infoFound.name ? infoFound.name + '" (' + updateID + ')' : '') + (statusFound && statusFound.name ? statusFound.name + '" (' + updateID + ')' : '') + ' Envoi valeur:' + returnValue + ' dans ' + subCharact.displayName; + if(infoFound !== -1 && infoFound.generic_type=="LIGHT_STATE") { // if it's a LIGHT_STATE + if(!this.settingLight) { // and it's not currently being modified + this.log('info','[Commande envoyée à HomeKit]',logMessage); subCharact.updateValue(returnValue, undefined, 'fromJeedom'); - } else if(DEV_DEBUG) {that.log('debug','//Commande NON envoyée à HomeKit','Cause de modif: "'+((infoFound && infoFound.name)?infoFound.name+'" ('+updateID+')':'')+((statusFound && statusFound.name)?statusFound.name+'" ('+updateID+')':''),"Envoi valeur:",returnValue,'dans',subCharact.displayName);} - } else if(infoFound != -1 && (infoFound.generic_type=="FAN_STATE" || infoFound.generic_type=="FAN_SPEED_STATE")) { // if it's a FAN_STATE - if(!that.settingFan) { // and it's not currently being modified - that.log('info','[Commande envoyée à HomeKit]','Cause de modif: "'+((infoFound && infoFound.name)?infoFound.name+'" ('+updateID+')':'')+((statusFound && statusFound.name)?statusFound.name+'" ('+updateID+')':''),"Envoi valeur:",returnValue,'dans',subCharact.displayName); + } else if(DEV_DEBUG) {this.log('debug','//Commande NON envoyée à HomeKit',logMessage);} + } else if(infoFound !== -1 && (infoFound.generic_type=="FAN_STATE" || infoFound.generic_type=="FAN_SPEED_STATE")) { // if it's a FAN_STATE + if(!this.settingFan) { // and it's not currently being modified + this.log('info','[Commande envoyée à HomeKit]',logMessage); subCharact.updateValue(returnValue, undefined, 'fromJeedom'); - } else if(DEV_DEBUG) {that.log('debug','//Commande NON envoyée à HomeKit','Cause de modif: "'+((infoFound && infoFound.name)?infoFound.name+'" ('+updateID+')':'')+((statusFound && statusFound.name)?statusFound.name+'" ('+updateID+')':''),"Envoi valeur:",returnValue,'dans',subCharact.displayName);} + } else if(DEV_DEBUG) {this.log('debug','//Commande NON envoyée à HomeKit',logMessage);} } else { - that.log('info','[Commande envoyée à HomeKit]','Cause de modif: "'+((infoFound && infoFound.name)?infoFound.name+'" ('+updateID+')':'')+((statusFound && statusFound.name)?statusFound.name+'" ('+updateID+')':''),"Envoi valeur:",returnValue,'dans',subCharact.displayName); + this.log('info','[Commande envoyée à HomeKit]',logMessage); subCharact.updateValue(returnValue, undefined, 'fromJeedom'); } - } else if (returnValue === 'no_response') { - subCharact.updateValue(new Error('no_response'), undefined, 'fromJeedom'); - } else { return; } + } else {return;} } } }; + // -- updateJeedomColorFromHomeKit // -- Desc : convert HSV value (Homebridge) to html value (Jeedom) // -- Params -- @@ -5731,31 +5805,12 @@ JeedomPlatform.prototype.updateHomeKitColorFromJeedom = function(color, service) // -- service : service to set color to // -- Return : nothing JeedomPlatform.prototype.syncColorCharacteristics = function(rgb, service) { - /* switch (--service.countColorCharacteristics) { - case -1: - service.countColorCharacteristics = 2; */ - const that = this; - clearTimeout(service.timeoutIdColorCharacteristics); - service.timeoutIdColorCharacteristics = setTimeout(function() { - // if (service.countColorCharacteristics < 2) - // return; + service.timeoutIdColorCharacteristics = setTimeout(() => { const rgbColor = rgbToHex(rgb.r, rgb.g, rgb.b); - if (DEV_DEBUG) {that.log('debug',"---------setRGB : ",rgbColor);} - that.command('setRGB', rgbColor, service); - // service.countColorCharacteristics = 0; - // service.timeoutIdColorCharacteristics = 0; + if (DEV_DEBUG) {this.log('debug',"---------setRGB : ",rgbColor);} + this.command('setRGB', rgbColor, service); }, 500); - /* break; - case 0: - var rgbColor = rgbToHex(rgb.r, rgb.g, rgb.b); - this.command('setRGB', rgbColor, service); - service.countColorCharacteristics = 0; - service.timeoutIdColorCharacteristics = 0; - break; - default: - break; - } */ }; // -- RegisterCustomCharacteristics @@ -6308,9 +6363,9 @@ JeedomBridgedAccessory.prototype.initAccessory = function(newAccessory) { // -- services : services to be added // -- Return : nothing JeedomBridgedAccessory.prototype.addServices = function(newAccessory,services,cachedValues) { - var service; + let service; try { - var cachedValue, characteristic; + let cachedValue, characteristic; for (var s = 0; s < services.length; s++) { service = services[s]; @@ -6356,24 +6411,20 @@ JeedomBridgedAccessory.prototype.addServices = function(newAccessory,services,ca // -- accessory : accessory to delete the services from // -- Return : nothing JeedomBridgedAccessory.prototype.delServices = function(accessory) { - var service; + let service; try { - const serviceList=[]; - const cachedValues=[]; - for(var t=0; t< accessory.services.length;t++) { - if(accessory.services[t].UUID != Service.AccessoryInformation.UUID && - accessory.services[t].UUID != Service.BridgingState.UUID) { - serviceList.push(accessory.services[t]); - } - } - for(service of serviceList){ // dont work in one loop or with temp object :( - this.log('debug',' Suppression service :'+service.displayName+' subtype:'+service.subtype+' UUID:'+service.UUID); - for (const c of service.characteristics) { - this.log('debug',' Caractéristique :'+c.displayName+' valeur cache:'+c.value); - cachedValues[service.subtype+c.displayName]=c.value; - } + const cachedValues = []; + const serviceList = accessory.services.filter((svc) => svc.UUID !== Service.AccessoryInformation.UUID && svc.UUID !== Service.BridgingState.UUID); + + serviceList.forEach((svc) => { + service=svc; + this.log('debug', ' Suppression service :' + service.displayName + ' subtype:' + service.subtype + ' UUID:' + service.UUID); + service.characteristics.forEach((c) => { + this.log('debug', ' Caractéristique :' + c.displayName + ' valeur cache:' + c.value); + cachedValues[service.subtype + c.displayName] = c.value; + }); accessory.removeService(service); - } + }); return cachedValues; } catch(e){ @@ -6417,7 +6468,7 @@ function hexToB(h) { // -- h : html color string // -- Return : numeric value of html color function cutHex(h) { - return (h.charAt(0) == '#') ? h.substring(1, 7) : h; + return h.charAt(0) === '#' ? h.substring(1, 7) : h; } // -- rgbToHex @@ -6437,12 +6488,7 @@ function rgbToHex(R, G, B) { // -- n : number // -- Return : hex value function toHex(n) { - n = parseInt(n, 10); - if (isNaN(n)) { - return '00'; - } - n = Math.max(0, Math.min(n, 255)); - return '0123456789ABCDEF'.charAt((n - n % 16) / 16) + '0123456789ABCDEF'.charAt(n % 16); + return parseInt(n,10).toString(16).padStart(2, '0'); } // -- HSVtoRGB @@ -6557,10 +6603,10 @@ function RGBtoHSV(r, g, b) { // -- id : id to find // -- Return : Object found function findMyID(obj,id) { - for(const o in obj) { - // if( obj.hasOwnProperty( o ) && obj[o] && obj[o].id && parseInt(obj[o].id) && parseInt(id) && parseInt(obj[o].id)==parseInt(id)) { - if( obj.hasOwnProperty( o ) && obj[o] && obj[o].id && obj[o].id==id) { - return obj[o]; + if (!obj) {return -1;} + for(const key in obj) { + if( obj.hasOwnProperty(key) && obj[key] && obj[key].id==id) { + return obj[key]; } } return -1; diff --git a/lib/jeedom-api.js b/lib/jeedom-api.js index 1b6a32f0..38d1ecff 100755 --- a/lib/jeedom-api.js +++ b/lib/jeedom-api.js @@ -13,11 +13,12 @@ * You should have received a copy of the GNU General Public License * along with Jeedom. If not, see . */ -/* jshint esversion: 6,node: true */ +/* jshint esversion: 11,node: true */ 'use strict'; - -var request = require('request'); +const axios = require('axios'); +const async = require('async'); var DEV_DEBUG; +var USE_QUEUES; function JeedomClient(url, apikey, Plateform, myPlugin) { this.apikey = apikey; @@ -26,190 +27,158 @@ function JeedomClient(url, apikey, Plateform, myPlugin) { this.Plateform = Plateform; this.log = this.Plateform.log; this.myPlugin = myPlugin || "mobile"; - this.sess_id = ""; DEV_DEBUG = Plateform.DEV_DEBUG || false; + USE_QUEUES = Plateform.USE_QUEUES || 1; // 0 = NO, or 1 or 2 etc for the concurrent tasks + this.queue = async.queue((task, callback) => { + if(task.type==='cmd') { + this._executeDeviceAction(task.ID, task.action, task.param) + .then((result) => callback(null, result)) + .catch((err) => callback(err, null)); + } else if(task.type==='scenario') { + this._executeScenarioAction(task.ID, task.action) + .then((result) => callback(null, result)) + .catch((err) => callback(err, null)); + } + }, ((USE_QUEUES===0)?1:USE_QUEUES)); } -JeedomClient.prototype.getModel = function() { - var that = this; +JeedomClient.prototype.changeQueueSys = function(newVal = 1) { + USE_QUEUES = newVal; + this.queue.concurrency = ((USE_QUEUES===0)?1:USE_QUEUES); +}; - return new Promise(function(resolve, reject) { - var url = that.url; - var request_id = Math.floor(Math.random() * 1000); - request.post(url, { - json : true, - gzip : true, - form : { - request : '{"jsonrpc":"2.0","id":"'+request_id+'","method":"sync_homebridge","params":{"plugin":"'+that.myPlugin+'","apikey":"' + that.apikey + '","session":true,"sess_id":"'+ that.sess_id +'"}}', - }, - }, function(err, response, json) { - // that.log(JSON.stringify(response).replace('\n','')); - if (!err && response.statusCode == 200) { - if(!json) {reject("JSON reçu de Jeedom invalide, vérifiez le log API de Jeedom, reçu :"+JSON.stringify(response));} - if(!json.result && json.error) { - reject(json.error); - } else { - if(json.sess_id !== undefined) { - that.sess_id = json.sess_id; - } else { - that.sess_id = ""; - } - that._cachedModel=json.result; - resolve(that._cachedModel); - } - - } else { - reject(err); - } - }); +JeedomClient.prototype.getModel = function() { + return axios.post(this.url, + { + jsonrpc:"2.0", + id:(Math.floor(Math.random() * 1000)), + method:"sync_homebridge", + params:{ + plugin:this.myPlugin, + apikey:this.apikey, + }, + }).then((result) => { + if(!result.data) {return Promise.reject("JSON reçu de Jeedom invalide, vérifiez le log API de Jeedom, reçu :"+JSON.stringify(result));} + if(!result.data.result && result.data.error) { + return Promise.reject(result.data.error.message); + } else { + this._cachedModel=result.data.result; + return this._cachedModel; + } }); }; JeedomClient.prototype.getDevicePropertiesFromCache = function(ID) { - var that = this; - for (var e in that._cachedModel.eqLogics) { - if (that._cachedModel.eqLogics.hasOwnProperty(e)) { - var eqLogic = that._cachedModel.eqLogics[e]; - if(eqLogic.id == ID) { - return eqLogic; - } + for (const e in this._cachedModel.eqLogics) { + if(this._cachedModel.eqLogics[e].id == ID) { + return this._cachedModel.eqLogics[e]; } } return null; }; JeedomClient.prototype.getDeviceProperties = function(ID) { - var that = this; - var p = new Promise(function(resolve, reject) { - var url = that.url; - var request_id = Math.floor(Math.random() * 1000); - request.post(url, { - json : true, - form : { - request : '{"jsonrpc":"2.0","id":"'+request_id+'","method":"getEql","params":{"plugin":"'+that.myPlugin+'","apikey":"' + that.apikey + '","id":"' + ID + '","session":true,"sess_id":"'+ that.sess_id +'"}}', - }, - }, function(err, response, json) { - if (!err && response.statusCode == 200) { - if(!json.result && json.error) { - reject(json.error); - } else { - if(json.sess_id !== undefined) { - that.sess_id = json.sess_id; - } else { - that.sess_id = ""; - } - resolve(json.result); - } - } else { - reject(err); - } - }); + return axios.post(this.url, + { + jsonrpc:"2.0", + id:(Math.floor(Math.random() * 1000)), + method:"getEql", + params:{ + plugin:this.myPlugin, + apikey:this.apikey, + id:ID, + }, + }).then((result) => { + if(!result.data) {return Promise.reject("JSON reçu de Jeedom invalide, vérifiez le log API de Jeedom, reçu :"+JSON.stringify(result));} + if(!result.data.result && result.data.error) { + return Promise.reject(result.data.error.message); + } else if(result.data.result != 'ok') { + return result.data.result; + } else { + return Promise.reject("EqLogic "+ID+" n'existe pas ou pas envoyé à homebridge"); + } }); - return p; + }; -JeedomClient.prototype.getDeviceCmdFromCache = function(ID) { - var that = this; - var clist = []; - for (var c in that._cachedModel.cmds) { - if (that._cachedModel.cmds.hasOwnProperty(c)) { - var cmd = that._cachedModel.cmds[c]; - if(cmd.eqLogic_id == ID) { - clist.push(cmd); - } +JeedomClient.prototype.daemonIsReady = function(port) { + return axios.post(this.url, + { + jsonrpc:"2.0", + id:(Math.floor(Math.random() * 1000)), + method:"daemonIsReady", + params:{ + plugin:this.myPlugin, + apikey:this.apikey, + port:port, + }, + }).then((result) => { + if(!result.data) {return Promise.reject("JSON reçu de Jeedom invalide, vérifiez le log API de Jeedom, reçu :"+JSON.stringify(result));} + if(!result.data.result && result.data.error) { + return Promise.reject(result.data.error.message); + } else if(result.data.result == true) { + return result.data.result; + } else { + return Promise.reject("Jeedom n'a pas compris l'envoi du port"); } + }); + +}; + +JeedomClient.prototype.getDeviceCmdFromCache = function(ID) { + const clist = []; + for (const c in this._cachedModel.cmds) { + if (this._cachedModel.cmds[c].eqLogic_id == ID) { + clist.push(this._cachedModel.cmds[c]); + } } return clist; }; JeedomClient.prototype.getScenarioPropertiesFromCache = function(ID) { - var that = this; - for (var s in that._cachedModel.scenarios) { - if (that._cachedModel.scenarios.hasOwnProperty(s)) { - var scenario = that._cachedModel.scenarios[s]; - if(scenario.id == ID) { - return scenario; - } + for (const s in this._cachedModel.scenarios) { + if(this._cachedModel.scenarios[s].id == ID) { + return this._cachedModel.scenarios[s]; } } return null; }; -JeedomClient.prototype.getScenarioProperties = function(ID) { - var that = this; - var p = new Promise(function(resolve, reject) { - var url = that.url; - var request_id = Math.floor(Math.random() * 1000); - request.post(url, { - json : true, - form : { - request : '{"jsonrpc":"2.0","id":"'+request_id+'","method":"scenario::byId","params":{"apikey":"' + that.apikey + '","id":"' + ID + '","session":true,"sess_id":"'+ that.sess_id +'"}}', - }, - }, function(err, response, json) { - if (!err && response.statusCode == 200) { - if(!json.result && json.error) { - reject(json.error); - } else { - if(json.sess_id !== undefined) { - that.sess_id = json.sess_id; - } else { - that.sess_id = ""; - } - resolve(json.result); - } - } else { - reject(err); - } - }); - }); - return p; -}; - JeedomClient.prototype.updateModelScenario = function(ID,state) { - var that = this; - for (var s in that._cachedModel.scenarios) { - if (that._cachedModel.scenarios.hasOwnProperty(s)) { - var scenario_cached = that._cachedModel.scenarios[s]; - if(scenario_cached.id == ID) { - that.log('debug','[[Modification Cache Jeedom scenarios: '+scenario_cached.name+'> State de '+scenario_cached.state+' vers '+state+' dans ' + JSON.stringify(scenario_cached).replace('\n','')); - that._cachedModel.scenarios[s].state=state; - return that._cachedModel.scenarios[s]; - } - } + for (const s in this._cachedModel.scenarios) { + if(this._cachedModel.scenarios[s].id == ID) { + this.log('debug','[[Modification Cache Jeedom scenarios: '+this._cachedModel.scenarios[s].name+'> State de '+this._cachedModel.scenarios[s].state+' vers '+state+' dans ' + JSON.stringify(this._cachedModel.scenarios[s]).replace('\n','')); + this._cachedModel.scenarios[s].state=state; + return this._cachedModel.scenarios[s]; + } } - that.log('debug','Scénario pas trouvée dans le cache jeedom (Nouveau Scénario, redémarrez le démon Homebridge pour prendre en compte): '+ID); + this.log('debug','Scénario pas trouvée dans le cache jeedom (Nouveau Scénario, redémarrez le démon Homebridge pour prendre en compte): '+ID); return null; }; JeedomClient.prototype.updateModelEq = function(ID,eqLogic) { - var that = this; - for (var e in that._cachedModel.eqLogics) { - if (that._cachedModel.eqLogics.hasOwnProperty(e)) { - var eqLogic_cached = that._cachedModel.eqLogics[e]; - if(eqLogic_cached.id == ID) { - that.log('info','[[Modification Cache Jeedom eqLogic: '+eqLogic_cached.name+'>'+eqLogic.name+' Enable de '+eqLogic_cached.isEnable+' vers '+eqLogic.isEnable+' dans ' + JSON.stringify(eqLogic).replace('\n','')); - that._cachedModel.eqLogics[e].isEnable=eqLogic.isEnable; - return eqLogic; - } - } + for (const e in this._cachedModel.eqLogics) { + if(this._cachedModel.eqLogics[e].id == ID) { + this.log('info','[[Modification Cache Jeedom eqLogic: '+this._cachedModel.eqLogics[e].name+'>'+eqLogic.name+' Enable de '+this._cachedModel.eqLogics[e].isEnable+' vers '+eqLogic.isEnable+' dans ' + JSON.stringify(eqLogic).replace('\n','')); + this._cachedModel.eqLogics[e].isEnable=eqLogic.isEnable; + return eqLogic; + } } if(DEV_DEBUG) { - that.log('debug','Eqlogic pas trouvée dans le cache jeedom (non visible ou pas envoyé à homebridge): '+ID); + this.log('debug','Eqlogic pas trouvée dans le cache jeedom (non visible ou pas envoyé à homebridge): '+ID); } return null; }; JeedomClient.prototype.updateModelInfo = function(ID,value,internal=false) { - var that = this; - var eq; - for (var c in that._cachedModel.cmds) { - if (that._cachedModel.cmds.hasOwnProperty(c)) { - var cmd = that._cachedModel.cmds[c]; + for (const c in this._cachedModel.cmds) { + const cmd = this._cachedModel.cmds[c]; + let eq; if(cmd.id == ID && cmd.type=='info') { - eq = that.getDevicePropertiesFromCache(cmd.eqLogic_id); - if(!internal) { that.log('info','[Maj reçue de Jeedom] commande:'+ID+' value:'+value); } - else { that.log('info','[Maj interne] commande:'+ID+' value:'+value); } - that.log('info','[[Modification Cache Jeedom: '+eq.name+'>'+cmd.name+'('+cmd.generic_type+') de '+cmd.currentValue+' vers '+value+' dans ' + JSON.stringify(cmd).replace('\n','')); + eq = this.getDevicePropertiesFromCache(cmd.eqLogic_id); + if(!internal) {this.log('info','[Maj reçue de Jeedom] commande:'+ID+' value:'+value);} + else {this.log('info','[Maj interne] commande:'+ID+' value:'+value);} + this.log('info','[[Modification Cache Jeedom: '+eq.name+'>'+cmd.name+'('+cmd.generic_type+') de '+cmd.currentValue+' vers '+value+' dans ' + JSON.stringify(cmd).replace('\n','')); if(cmd.generic_type == 'ALARM_STATE') { if(cmd.currentValue != value) { cmd.currentValue=value; @@ -223,1419 +192,361 @@ JeedomClient.prototype.updateModelInfo = function(ID,value,internal=false) { } } else if (cmd.id == ID) { if(DEV_DEBUG) { - eq = that.getDevicePropertiesFromCache(cmd.eqLogic_id); - that.log('debug','[Maj reçue de Jeedom] commande:'+ID+' value:'+value); - that.log('debug','[[Pas une commande INFO ('+cmd.type+') '+eq.name+'>'+cmd.name+'('+cmd.generic_type+') '+value+' dans ' + JSON.stringify(cmd).replace('\n','')); + eq = this.getDevicePropertiesFromCache(cmd.eqLogic_id); + this.log('debug','[Maj reçue de Jeedom] commande:'+ID+' value:'+value); + this.log('debug','[[Pas une commande INFO ('+cmd.type+') '+eq.name+'>'+cmd.name+'('+cmd.generic_type+') '+value+' dans ' + JSON.stringify(cmd).replace('\n','')); } return false; } - } } if(DEV_DEBUG) { - that.log('debug','[Maj reçue de Jeedom] commande:'+ID+' value:'+value); - that.log('debug','Commande pas trouvée dans le cache jeedom (non visible ou pas envoyé à homebridge): '+ID); + this.log('debug','[Maj reçue de Jeedom] commande:'+ID+' value:'+value); + this.log('debug','Commande pas trouvée dans le cache jeedom (non visible ou pas envoyé à homebridge): '+ID); } return false; }; -JeedomClient.prototype.ParseGenericType = function(EqLogic, cmds) { - var result_cmd = {}; - result_cmd = EqLogic; - result_cmd.services = {}; - result_cmd.numSwitches=0; - result_cmd.numDetector=0; - for (var i in cmds) { - if (isset(cmds[i].generic_type)) { - if (cmds[i].generic_type) { - switch(cmds[i].generic_type) { - case 'SHOCK' : - case 'RAIN_CURRENT' : - case 'RAIN_TOTAL' : - case 'WIND_SPEED' : - case 'WIND_DIRECTION' : - case 'GENERIC_INFO': - if (!result_cmd.services.generic) { - result_cmd.services.generic = []; - } - if (!result_cmd.services.generic[i]) { - result_cmd.services.generic[i] = {}; - } - result_cmd.services.generic[i].state = cmds[i]; - break; - /** *************** MODE ***********************/ - case 'MODE_STATE' : - if (!result_cmd.services.mode) { - result_cmd.services.mode = []; - } - if (!result_cmd.services.mode[i]) { - result_cmd.services.mode[i] = {}; - } - result_cmd.services.mode[i].state = cmds[i]; - break; - case 'MODE_SET_STATE' : - if(cmds[i].logicalId=="returnPreviousMode") { - if (!result_cmd.services.mode) { - result_cmd.services.mode = []; - } - if (!result_cmd.services.mode[i]) { - result_cmd.services.mode[i] = {}; - } - result_cmd.services.mode[i].set_state_previous = cmds[i]; - } else { - if (!result_cmd.services.mode) { - result_cmd.services.mode = []; - } - if (!result_cmd.services.mode[i]) { - result_cmd.services.mode[i] = {}; - } - if (!result_cmd.services.mode[i].set_state) { - result_cmd.services.mode[i].set_state = []; - } - result_cmd.services.mode[i].set_state.push(cmds[i]); - } - break; - /** *************** LIGHT ***********************/ - case 'LIGHT_STATE' : - if (!result_cmd.services.light) { - result_cmd.services.light = []; - } - if (!result_cmd.services.light[i]) { - result_cmd.services.light[i] = {}; - } - result_cmd.services.light[i].state = cmds[i]; - break; - case 'LIGHT_BRIGHTNESS' : - if (!result_cmd.services.light) { - result_cmd.services.light = []; - } - if (!result_cmd.services.light[i]) { - result_cmd.services.light[i] = {}; - } - result_cmd.services.light[i].brightness = cmds[i]; - break; - case 'LIGHT_STATE_BOOL' : - if (!result_cmd.services.light) { - result_cmd.services.light = []; - } - if (!result_cmd.services.light[i]) { - result_cmd.services.light[i] = {}; - } - result_cmd.services.light[i].state_bool = cmds[i]; - break; - case 'LIGHT_ON' : - if (!result_cmd.services.light) { - result_cmd.services.light = []; - } - if (!result_cmd.services.light[i]) { - result_cmd.services.light[i] = {}; - } - result_cmd.services.light[i].on = cmds[i]; - break; - case 'LIGHT_OFF' : - if (!result_cmd.services.light) { - result_cmd.services.light = []; - } - if (!result_cmd.services.light[i]) { - result_cmd.services.light[i] = {}; - } - result_cmd.services.light[i].off = cmds[i]; - break; - case 'LIGHT_SLIDER' : - if (!result_cmd.services.light) { - result_cmd.services.light = []; - } - if (!result_cmd.services.light[i]) { - result_cmd.services.light[i] = {}; - } - result_cmd.services.light[i].slider = cmds[i]; - break; - case 'LIGHT_COLOR' : - if (!result_cmd.services.light) { - result_cmd.services.light = []; - } - if (!result_cmd.services.light[i]) { - result_cmd.services.light[i] = {}; - } - result_cmd.services.light[i].color = cmds[i]; - break; - case 'LIGHT_COLOR_TEMP' : - if (!result_cmd.services.light) { - result_cmd.services.light = []; - } - if (!result_cmd.services.light[i]) { - result_cmd.services.light[i] = {}; - } - result_cmd.services.light[i].color_temp = cmds[i]; - break; - case 'LIGHT_SET_COLOR' : - if (!result_cmd.services.light) { - result_cmd.services.light = []; - } - if (!result_cmd.services.light[i]) { - result_cmd.services.light[i] = {}; - } - result_cmd.services.light[i].setcolor = cmds[i]; - break; - case 'LIGHT_SET_COLOR_TEMP' : - if (!result_cmd.services.light) { - result_cmd.services.light = []; - } - if (!result_cmd.services.light[i]) { - result_cmd.services.light[i] = {}; - } - result_cmd.services.light[i].setcolor_temp = cmds[i]; - break; - /** *************** WEATHER ***********************/ - case 'WEATHER_TEMPERATURE' : - if (!result_cmd.services.weather) { - result_cmd.services.weather = []; - } - if (!result_cmd.services.weather[i]) { - result_cmd.services.weather[i] = {}; - } - result_cmd.services.weather[i].temperature = cmds[i]; - break; - case 'WEATHER_HUMIDITY' : - if (!result_cmd.services.weather) { - result_cmd.services.weather = []; - } - if (!result_cmd.services.weather[i]) { - result_cmd.services.weather[i] = {}; - } - result_cmd.services.weather[i].humidity = cmds[i]; - break; - case 'WEATHER_PRESSURE' : - if (!result_cmd.services.weather) { - result_cmd.services.weather = []; - } - if (!result_cmd.services.weather[i]) { - result_cmd.services.weather[i] = {}; - } - result_cmd.services.weather[i].pressure = cmds[i]; - break; - case 'WEATHER_WIND_SPEED' : - if (!result_cmd.services.weather) { - result_cmd.services.weather = []; - } - if (!result_cmd.services.weather[i]) { - result_cmd.services.weather[i] = {}; - } - result_cmd.services.weather[i].wind_speed = cmds[i]; - break; - case 'WEATHER_WIND_DIRECTION' : - if (!result_cmd.services.weather) { - result_cmd.services.weather = []; - } - if (!result_cmd.services.weather[i]) { - result_cmd.services.weather[i] = {}; - } - result_cmd.services.weather[i].wind_direction = cmds[i]; - break; - case 'WEATHER_CONDITION' : - if (!result_cmd.services.weather) { - result_cmd.services.weather = []; - } - if (!result_cmd.services.weather[i]) { - result_cmd.services.weather[i] = {}; - } - result_cmd.services.weather[i].condition = cmds[i]; - break; - case 'WEATHER_UVINDEX' : - if (!result_cmd.services.weather) { - result_cmd.services.weather = []; - } - if (!result_cmd.services.weather[i]) { - result_cmd.services.weather[i] = {}; - } - result_cmd.services.weather[i].UVIndex = cmds[i]; - break; - case 'WEATHER_VISIBILITY' : - if (!result_cmd.services.weather) { - result_cmd.services.weather = []; - } - if (!result_cmd.services.weather[i]) { - result_cmd.services.weather[i] = {}; - } - result_cmd.services.weather[i].visibility = cmds[i]; - break; - case 'WEATHER_RAIN' : - if (!result_cmd.services.weather) { - result_cmd.services.weather = []; - } - if (!result_cmd.services.weather[i]) { - result_cmd.services.weather[i] = {}; - } - result_cmd.services.weather[i].rain = cmds[i]; - break; - case 'WEATHER_SNOW' : - if (!result_cmd.services.weather) { - result_cmd.services.weather = []; - } - if (!result_cmd.services.weather[i]) { - result_cmd.services.weather[i] = {}; - } - result_cmd.services.weather[i].snow = cmds[i]; - break; - case 'WEATHER_TEMPERATURE_MIN' : - if (!result_cmd.services.weather) { - result_cmd.services.weather = []; - } - if (!result_cmd.services.weather[i]) { - result_cmd.services.weather[i] = {}; - } - result_cmd.services.weather[i].temperature_min = cmds[i]; - break; - /** *************** SIREN ***********************/ - case 'SIREN_STATE' : - if (!result_cmd.services.siren) { - result_cmd.services.siren = []; - } - if (!result_cmd.services.siren[i]) { - result_cmd.services.siren[i] = {}; - } - result_cmd.services.siren[i].state = cmds[i]; - break; - /* case 'SIREN_ON' : - if (!result_cmd.services.siren) { - result_cmd.services.siren = []; - } - if (!result_cmd.services.siren[i]) { - result_cmd.services.siren[i] = {}; - } - result_cmd.services.siren[i].on = cmds[i]; - break; - case 'SIREN_OFF' : - if (!result_cmd.services.siren) { - result_cmd.services.siren = []; - } - if (!result_cmd.services.siren[i]) { - result_cmd.services.siren[i] = {}; - } - result_cmd.services.siren[i].off = cmds[i]; - break; */ - /** *************** ENERGY ***********************/ - case 'ENERGY_STATE' : - if (!result_cmd.services.energy) { - result_cmd.services.energy = []; - } - if (!result_cmd.services.energy[i]) { - result_cmd.services.energy[i] = {}; - } - result_cmd.services.energy[i].state = cmds[i]; - break; - case 'ENERGY_ON' : - if (!result_cmd.services.energy) { - result_cmd.services.energy = []; - } - if (!result_cmd.services.energy[i]) { - result_cmd.services.energy[i] = {}; - } - result_cmd.services.energy[i].on = cmds[i]; - break; - case 'ENERGY_OFF' : - if (!result_cmd.services.energy) { - result_cmd.services.energy = []; - } - if (!result_cmd.services.energy[i]) { - result_cmd.services.energy[i] = {}; - } - result_cmd.services.energy[i].off = cmds[i]; - break; - case 'ENERGY_INUSE' : - if (!result_cmd.services.energy) { - result_cmd.services.energy = []; - } - if (!result_cmd.services.energy[i]) { - result_cmd.services.energy[i] = {}; - } - result_cmd.services.energy[i].inuse = cmds[i]; - break; - /** *************** VALVES ***********************/ - case 'FAUCET_STATE' : - if (!result_cmd.services.faucet) { - result_cmd.services.faucet = []; - } - if (!result_cmd.services.faucet[i]) { - result_cmd.services.faucet[i] = {}; - } - result_cmd.services.faucet[i].state = cmds[i]; - break; - case 'FAUCET_ON' : - if (!result_cmd.services.faucet) { - result_cmd.services.faucet = []; - } - if (!result_cmd.services.faucet[i]) { - result_cmd.services.faucet[i] = {}; - } - result_cmd.services.faucet[i].on = cmds[i]; - break; - case 'FAUCET_OFF' : - if (!result_cmd.services.faucet) { - result_cmd.services.faucet = []; - } - if (!result_cmd.services.faucet[i]) { - result_cmd.services.faucet[i] = {}; - } - result_cmd.services.faucet[i].off = cmds[i]; - break; - case 'IRRIG_STATE' : - if (!result_cmd.services.irrigation) { - result_cmd.services.irrigation = []; - } - if (!result_cmd.services.irrigation[i]) { - result_cmd.services.irrigation[i] = {}; - } - result_cmd.services.irrigation[i].state = cmds[i]; - break; - case 'IRRIG_ON' : - if (!result_cmd.services.irrigation) { - result_cmd.services.irrigation = []; - } - if (!result_cmd.services.irrigation[i]) { - result_cmd.services.irrigation[i] = {}; - } - result_cmd.services.irrigation[i].on = cmds[i]; - break; - case 'IRRIG_OFF' : - if (!result_cmd.services.irrigation) { - result_cmd.services.irrigation = []; - } - if (!result_cmd.services.irrigation[i]) { - result_cmd.services.irrigation[i] = {}; - } - result_cmd.services.irrigation[i].off = cmds[i]; - break; - case 'VALVE_STATE' : - if (!result_cmd.services.valve) { - result_cmd.services.valve = []; - } - if (!result_cmd.services.valve[i]) { - result_cmd.services.valve[i] = {}; - } - result_cmd.services.valve[i].state = cmds[i]; - break; - case 'VALVE_ON' : - if (!result_cmd.services.valve) { - result_cmd.services.valve = []; - } - if (!result_cmd.services.valve[i]) { - result_cmd.services.valve[i] = {}; - } - result_cmd.services.valve[i].on = cmds[i]; - break; - case 'VALVE_OFF' : - if (!result_cmd.services.valve) { - result_cmd.services.valve = []; - } - if (!result_cmd.services.valve[i]) { - result_cmd.services.valve[i] = {}; - } - result_cmd.services.valve[i].off = cmds[i]; - break; - case 'VALVE_SET_DURATION' : - if (!result_cmd.services.valve) { - result_cmd.services.valve = []; - } - if (!result_cmd.services.valve[i]) { - result_cmd.services.valve[i] = {}; - } - result_cmd.services.valve[i].setDuration = cmds[i]; - break; - case 'VALVE_REMAINING_DURATION' : - if (!result_cmd.services.valve) { - result_cmd.services.valve = []; - } - if (!result_cmd.services.valve[i]) { - result_cmd.services.valve[i] = {}; - } - result_cmd.services.valve[i].remainingDuration = cmds[i]; - break; - /** *************** FAN ***********************/ - case 'FAN_STATE' : - case 'FAN_SPEED_STATE' : - if (!result_cmd.services.fan) { - result_cmd.services.fan = []; - } - if (!result_cmd.services.fan[i]) { - result_cmd.services.fan[i] = {}; - } - result_cmd.services.fan[i].state = cmds[i]; - break; - case 'FAN_ON' : - if (!result_cmd.services.fan) { - result_cmd.services.fan = []; - } - if (!result_cmd.services.fan[i]) { - result_cmd.services.fan[i] = {}; - } - result_cmd.services.fan[i].on = cmds[i]; - break; - case 'FAN_OFF' : - if (!result_cmd.services.fan) { - result_cmd.services.fan = []; - } - if (!result_cmd.services.fan[i]) { - result_cmd.services.fan[i] = {}; - } - result_cmd.services.fan[i].off = cmds[i]; - break; - case 'FAN_SLIDER' : - case 'FAN_SPEED' : - if (!result_cmd.services.fan) { - result_cmd.services.fan = []; - } - if (!result_cmd.services.fan[i]) { - result_cmd.services.fan[i] = {}; - } - result_cmd.services.fan[i].slider = cmds[i]; - break; - /** *************** SWITCH ***********************/ - case 'SWITCH_STATE' : - case 'CAMERA_RECORD_STATE' : - if (!result_cmd.services.Switch) { - result_cmd.services.Switch = []; - } - if (!result_cmd.services.Switch[i]) { - result_cmd.services.Switch[i] = {}; - } - result_cmd.services.Switch[i].state = cmds[i]; - result_cmd.numSwitches++; - break; - case 'SWITCH_ON' : - case 'CAMERA_RECORD' : - if (!result_cmd.services.Switch) { - result_cmd.services.Switch = []; - } - if (!result_cmd.services.Switch[i]) { - result_cmd.services.Switch[i] = {}; - } - result_cmd.services.Switch[i].on = cmds[i]; - break; - case 'SWITCH_OFF' : - case 'CAMERA_STOP' : - if (!result_cmd.services.Switch) { - result_cmd.services.Switch = []; - } - if (!result_cmd.services.Switch[i]) { - result_cmd.services.Switch[i] = {}; - } - result_cmd.services.Switch[i].off = cmds[i]; - break; - /** *************** SWITCH ***********************/ - case 'GENERIC_ACTION' : - if(cmds[i].subType=="other") { - if (!result_cmd.services.Push) { - result_cmd.services.Push = []; - } - if (!result_cmd.services.Push[i]) { - result_cmd.services.Push[i] = {}; - } - result_cmd.services.Push[i].Push = cmds[i]; - } - break; - case 'PUSH_BUTTON' : - case 'CAMERA_UP' : - case 'CAMERA_DOWN' : - case 'CAMERA_LEFT' : - case 'CAMERA_RIGHT' : - case 'CAMERA_ZOOM' : - case 'CAMERA_DEZOOM' : - case 'CAMERA_PRESET' : - if (!result_cmd.services.Push) { - result_cmd.services.Push = []; - } - if (!result_cmd.services.Push[i]) { - result_cmd.services.Push[i] = {}; - } - result_cmd.services.Push[i].Push = cmds[i]; - break; - /** *************** BARRIER/GARAGE**************/ - case "BARRIER_STATE" : - case "GARAGE_STATE" : - if (!result_cmd.services.GarageDoor) { - result_cmd.services.GarageDoor = []; - } - if (!result_cmd.services.GarageDoor[i]) { - result_cmd.services.GarageDoor[i] = {}; - } - result_cmd.services.GarageDoor[i].state = cmds[i]; - break; - case "GB_OPEN" : // should not be used - if (!result_cmd.services.GarageDoor) { - result_cmd.services.GarageDoor = []; - } - if (!result_cmd.services.GarageDoor[i]) { - result_cmd.services.GarageDoor[i] = {}; - } - result_cmd.services.GarageDoor[i].on = cmds[i]; - break; - case "GB_CLOSE" : // should not be used - if (!result_cmd.services.GarageDoor) { - result_cmd.services.GarageDoor = []; - } - if (!result_cmd.services.GarageDoor[i]) { - result_cmd.services.GarageDoor[i] = {}; - } - result_cmd.services.GarageDoor[i].off = cmds[i]; - break; - case "GB_TOGGLE" : - if (!result_cmd.services.GarageDoor) { - result_cmd.services.GarageDoor = []; - } - if (!result_cmd.services.GarageDoor[i]) { - result_cmd.services.GarageDoor[i] = {}; - } - result_cmd.services.GarageDoor[i].toggle = cmds[i]; - break; - /** *************** LOCK ***********************/ - case 'LOCK_STATE' : - if (!result_cmd.services.lock) { - result_cmd.services.lock = []; - } - if (!result_cmd.services.lock[i]) { - result_cmd.services.lock[i] = {}; - } - result_cmd.services.lock[i].state = cmds[i]; - break; - case 'LOCK_OPEN' : - if (!result_cmd.services.lock) { - result_cmd.services.lock = []; - } - if (!result_cmd.services.lock[i]) { - result_cmd.services.lock[i] = {}; - } - result_cmd.services.lock[i].on = cmds[i]; - break; - case 'LOCK_CLOSE' : - if (!result_cmd.services.lock) { - result_cmd.services.lock = []; - } - if (!result_cmd.services.lock[i]) { - result_cmd.services.lock[i] = {}; - } - result_cmd.services.lock[i].off = cmds[i]; - break; - /** *************** StatelessSwitch ******************/ - case 'SWITCH_STATELESS_ALLINONE' : - if (!result_cmd.services.StatelessSwitch) { - result_cmd.services.StatelessSwitch = []; - } - if (!result_cmd.services.StatelessSwitch[i]) { - result_cmd.services.StatelessSwitch[i] = {}; - } - result_cmd.services.StatelessSwitch[i].eventType = cmds[i]; - break; - case 'SWITCH_STATELESS_SINGLE' : - if (!result_cmd.services.StatelessSwitchMono) { - result_cmd.services.StatelessSwitchMono = []; - } - if (!result_cmd.services.StatelessSwitchMono[i]) { - result_cmd.services.StatelessSwitchMono[i] = {}; - } - result_cmd.services.StatelessSwitchMono[i].Single = cmds[i]; - break; - case 'SWITCH_STATELESS_DOUBLE' : - if (!result_cmd.services.StatelessSwitchMono) { - result_cmd.services.StatelessSwitchMono = []; - } - if (!result_cmd.services.StatelessSwitchMono[i]) { - result_cmd.services.StatelessSwitchMono[i] = {}; - } - result_cmd.services.StatelessSwitchMono[i].Double = cmds[i]; - break; - case 'SWITCH_STATELESS_LONG' : - if (!result_cmd.services.StatelessSwitchMono) { - result_cmd.services.StatelessSwitchMono = []; - } - if (!result_cmd.services.StatelessSwitchMono[i]) { - result_cmd.services.StatelessSwitchMono[i] = {}; - } - result_cmd.services.StatelessSwitchMono[i].Long = cmds[i]; - break; - /** *************** FLAP ***********************/ - case 'FLAP_STATE' : - if (!result_cmd.services.flap) { - result_cmd.services.flap = []; - } - if (!result_cmd.services.flap[i]) { - result_cmd.services.flap[i] = {}; - } - result_cmd.services.flap[i].state = cmds[i]; - break; - case 'FLAP_STATE_CLOSING' : - if (!result_cmd.services.flap) { - result_cmd.services.flap = []; - } - if (!result_cmd.services.flap[i]) { - result_cmd.services.flap[i] = {}; - } - result_cmd.services.flap[i].stateClosing = cmds[i]; - break; - case 'FLAP_UP' : - if (!result_cmd.services.flap) { - result_cmd.services.flap = []; - } - if (!result_cmd.services.flap[i]) { - result_cmd.services.flap[i] = {}; - } - result_cmd.services.flap[i].up = cmds[i]; - break; - case 'FLAP_DOWN' : - if (!result_cmd.services.flap) { - result_cmd.services.flap = []; - } - if (!result_cmd.services.flap[i]) { - result_cmd.services.flap[i] = {}; - } - result_cmd.services.flap[i].down = cmds[i]; - break; - case 'FLAP_SLIDER' : - if (!result_cmd.services.flap) { - result_cmd.services.flap = []; - } - if (!result_cmd.services.flap[i]) { - result_cmd.services.flap[i] = {}; - } - result_cmd.services.flap[i].slider = cmds[i]; - break; - case 'FLAP_STOP' : - if (!result_cmd.services.flap) { - result_cmd.services.flap = []; - } - if (!result_cmd.services.flap[i]) { - result_cmd.services.flap[i] = {}; - } - result_cmd.services.flap[i].stop = cmds[i]; - break; - case 'FLAP_HOR_TILT_STATE' : - if (!result_cmd.services.flap) { - result_cmd.services.flap = []; - } - if (!result_cmd.services.flap[i]) { - result_cmd.services.flap[i] = {}; - } - result_cmd.services.flap[i].HorTiltState = cmds[i]; - break; - case 'FLAP_HOR_TILT_SLIDER' : - if (!result_cmd.services.flap) { - result_cmd.services.flap = []; - } - if (!result_cmd.services.flap[i]) { - result_cmd.services.flap[i] = {}; - } - result_cmd.services.flap[i].HorTiltSlider = cmds[i]; - break; - case 'FLAP_VER_TILT_STATE' : - if (!result_cmd.services.flap) { - result_cmd.services.flap = []; - } - if (!result_cmd.services.flap[i]) { - result_cmd.services.flap[i] = {}; - } - result_cmd.services.flap[i].VerTiltState = cmds[i]; - break; - case 'FLAP_VER_TILT_SLIDER' : - if (!result_cmd.services.flap) { - result_cmd.services.flap = []; - } - if (!result_cmd.services.flap[i]) { - result_cmd.services.flap[i] = {}; - } - result_cmd.services.flap[i].VerTiltSlider = cmds[i]; - break; - /** *************** WINDOW ***********************/ - case 'WINDOW_STATE' : - if (!result_cmd.services.windowMoto) { - result_cmd.services.windowMoto = []; - } - if (!result_cmd.services.windowMoto[i]) { - result_cmd.services.windowMoto[i] = {}; - } - result_cmd.services.windowMoto[i].state = cmds[i]; - break; - case 'WINDOW_UP' : - if (!result_cmd.services.windowMoto) { - result_cmd.services.windowMoto = []; - } - if (!result_cmd.services.windowMoto[i]) { - result_cmd.services.windowMoto[i] = {}; - } - result_cmd.services.windowMoto[i].up = cmds[i]; - break; - case 'WINDOW_DOWN' : - if (!result_cmd.services.windowMoto) { - result_cmd.services.windowMoto = []; - } - if (!result_cmd.services.windowMoto[i]) { - result_cmd.services.windowMoto[i] = {}; - } - result_cmd.services.windowMoto[i].down = cmds[i]; - break; - case 'WINDOW_SLIDER' : - if (!result_cmd.services.windowMoto) { - result_cmd.services.windowMoto = []; - } - if (!result_cmd.services.windowMoto[i]) { - result_cmd.services.windowMoto[i] = {}; - } - result_cmd.services.windowMoto[i].slider = cmds[i]; - break; - /** ************* THERMOSTAT ***********************/ - case 'THERMOSTAT_STATE' : - if (!result_cmd.services.thermostat) { - result_cmd.services.thermostat = []; - } - if (!result_cmd.services.thermostat[i]) { - result_cmd.services.thermostat[i] = {}; - } - result_cmd.services.thermostat[i].state = cmds[i]; - break; - case 'THERMOSTAT_STATE_NAME' : - if (!result_cmd.services.thermostat) { - result_cmd.services.thermostat = []; - } - if (!result_cmd.services.thermostat[i]) { - result_cmd.services.thermostat[i] = {}; - } - result_cmd.services.thermostat[i].state_name = cmds[i]; - break; - case 'THERMOSTAT_TEMPERATURE' : - if (!result_cmd.services.thermostat) { - result_cmd.services.thermostat = []; - } - if (!result_cmd.services.thermostat[i]) { - result_cmd.services.thermostat[i] = {}; - } - result_cmd.services.thermostat[i].temperature = cmds[i]; - break; - case 'THERMOSTAT_SET_SETPOINT' : - if (!result_cmd.services.thermostat) { - result_cmd.services.thermostat = []; - } - if (!result_cmd.services.thermostat[i]) { - result_cmd.services.thermostat[i] = {}; - } - result_cmd.services.thermostat[i].set_setpoint = cmds[i]; - break; - case 'THERMOSTAT_SETPOINT' : - if (!result_cmd.services.thermostat) { - result_cmd.services.thermostat = []; - } - if (!result_cmd.services.thermostat[i]) { - result_cmd.services.thermostat[i] = {}; - } - result_cmd.services.thermostat[i].setpoint = cmds[i]; - break; - case 'THERMOSTAT_SET_MODE' : - if (!result_cmd.services.thermostat) { - result_cmd.services.thermostat = []; - } - if (!result_cmd.services.thermostat[i]) { - result_cmd.services.thermostat[i] = {}; - } - result_cmd.services.thermostat[i].set_mode = cmds[i]; - break; - case 'THERMOSTAT_MODE' : - if (!result_cmd.services.thermostat) { - result_cmd.services.thermostat = []; - } - if (!result_cmd.services.thermostat[i]) { - result_cmd.services.thermostat[i] = {}; - } - result_cmd.services.thermostat[i].mode = cmds[i]; - break; - case 'THERMOSTAT_LOCK' : - if (!result_cmd.services.thermostat) { - result_cmd.services.thermostat = []; - } - if (!result_cmd.services.thermostat[i]) { - result_cmd.services.thermostat[i] = {}; - } - result_cmd.services.thermostat[i].lock = cmds[i]; - break; - case 'THERMOSTAT_SET_LOCK' : - if (!result_cmd.services.thermostat) { - result_cmd.services.thermostat = []; - } - if (!result_cmd.services.thermostat[i]) { - result_cmd.services.thermostat[i] = {}; - } - result_cmd.services.thermostat[i].set_lock = cmds[i]; - break; - case 'THERMOSTAT_SET_UNLOCK' : - if (!result_cmd.services.thermostat) { - result_cmd.services.thermostat = []; - } - if (!result_cmd.services.thermostat[i]) { - result_cmd.services.thermostat[i] = {}; - } - result_cmd.services.thermostat[i].set_unlock = cmds[i]; - break; - case 'THERMOSTAT_TEMPERATURE_OUTDOOR' : - if (!result_cmd.services.thermostat) { - result_cmd.services.thermostat = []; - } - if (!result_cmd.services.thermostat[i]) { - result_cmd.services.thermostat[i] = {}; - } - result_cmd.services.thermostat[i].temperature_outdoor = cmds[i]; - break; - /** ************* THERMOSTAT_HC ***********************/ - case 'THERMOSTAT_HC_STATE' : - if (!result_cmd.services.thermostatHC) { - result_cmd.services.thermostatHC = []; - } - if (!result_cmd.services.thermostatHC[i]) { - result_cmd.services.thermostatHC[i] = {}; - } - result_cmd.services.thermostatHC[i].state = cmds[i]; - break; - case 'THERMOSTAT_HC_STATE_NAME' : - if (!result_cmd.services.thermostatHC) { - result_cmd.services.thermostatHC = []; - } - if (!result_cmd.services.thermostatHC[i]) { - result_cmd.services.thermostatHC[i] = {}; - } - result_cmd.services.thermostatHC[i].state_name = cmds[i]; - break; - case 'THERMOSTAT_HC_TEMPERATURE' : - if (!result_cmd.services.thermostatHC) { - result_cmd.services.thermostatHC = []; - } - if (!result_cmd.services.thermostatHC[i]) { - result_cmd.services.thermostatHC[i] = {}; - } - result_cmd.services.thermostatHC[i].temperature = cmds[i]; - break; - case 'THERMOSTAT_HC_SET_SETPOINT_H' : - if (!result_cmd.services.thermostatHC) { - result_cmd.services.thermostatHC = []; - } - if (!result_cmd.services.thermostatHC[i]) { - result_cmd.services.thermostatHC[i] = {}; - } - result_cmd.services.thermostatHC[i].set_setpointH = cmds[i]; - break; - case 'THERMOSTAT_HC_SET_SETPOINT_C' : - if (!result_cmd.services.thermostatHC) { - result_cmd.services.thermostatHC = []; - } - if (!result_cmd.services.thermostatHC[i]) { - result_cmd.services.thermostatHC[i] = {}; - } - result_cmd.services.thermostatHC[i].set_setpointC = cmds[i]; - break; - case 'THERMOSTAT_HC_SETPOINT_H' : - if (!result_cmd.services.thermostatHC) { - result_cmd.services.thermostatHC = []; - } - if (!result_cmd.services.thermostatHC[i]) { - result_cmd.services.thermostatHC[i] = {}; - } - result_cmd.services.thermostatHC[i].setpointH = cmds[i]; - break; - case 'THERMOSTAT_HC_SETPOINT_C' : - if (!result_cmd.services.thermostatHC) { - result_cmd.services.thermostatHC = []; - } - if (!result_cmd.services.thermostatHC[i]) { - result_cmd.services.thermostatHC[i] = {}; - } - result_cmd.services.thermostatHC[i].setpointC = cmds[i]; - break; - case 'THERMOSTAT_HC_SET_MODE' : - if (!result_cmd.services.thermostatHC) { - result_cmd.services.thermostatHC = []; - } - if (!result_cmd.services.thermostatHC[i]) { - result_cmd.services.thermostatHC[i] = {}; - } - result_cmd.services.thermostatHC[i].set_mode = cmds[i]; - break; - case 'THERMOSTAT_HC_MODE' : - if (!result_cmd.services.thermostatHC) { - result_cmd.services.thermostatHC = []; - } - if (!result_cmd.services.thermostatHC[i]) { - result_cmd.services.thermostatHC[i] = {}; - } - result_cmd.services.thermostatHC[i].mode = cmds[i]; - break; - case 'THERMOSTAT_HC_LOCK' : - if (!result_cmd.services.thermostatHC) { - result_cmd.services.thermostatHC = []; - } - if (!result_cmd.services.thermostatHC[i]) { - result_cmd.services.thermostatHC[i] = {}; - } - result_cmd.services.thermostatHC[i].lock = cmds[i]; - break; - case 'THERMOSTAT_HC_SET_LOCK' : - if (!result_cmd.services.thermostatHC) { - result_cmd.services.thermostatHC = []; - } - if (!result_cmd.services.thermostatHC[i]) { - result_cmd.services.thermostatHC[i] = {}; - } - result_cmd.services.thermostatHC[i].set_lock = cmds[i]; - break; - case 'THERMOSTAT_HC_SET_UNLOCK' : - if (!result_cmd.services.thermostatHC) { - result_cmd.services.thermostatHC = []; - } - if (!result_cmd.services.thermostatHC[i]) { - result_cmd.services.thermostatHC[i] = {}; - } - result_cmd.services.thermostatHC[i].set_unlock = cmds[i]; - break; - /** ************* ALARME ***********************/ - case 'ALARM_STATE' : - if (!result_cmd.services.alarm) { - result_cmd.services.alarm = []; - } - if (!result_cmd.services.alarm[i]) { - result_cmd.services.alarm[i] = {}; - } - result_cmd.services.alarm[i].state = cmds[i]; - break; - case 'ALARM_MODE' : - if (!result_cmd.services.alarm) { - result_cmd.services.alarm = []; - } - if (!result_cmd.services.alarm[i]) { - result_cmd.services.alarm[i] = {}; - } - result_cmd.services.alarm[i].mode = cmds[i]; - break; - case 'ALARM_ENABLE_STATE' : - if (!result_cmd.services.alarm) { - result_cmd.services.alarm = []; - } - if (!result_cmd.services.alarm[i]) { - result_cmd.services.alarm[i] = {}; - } - result_cmd.services.alarm[i].enable_state = cmds[i]; - break; - case 'ALARM_ARMED' : - if (!result_cmd.services.alarm) { - result_cmd.services.alarm = []; - } - if (!result_cmd.services.alarm[i]) { - result_cmd.services.alarm[i] = {}; - } - result_cmd.services.alarm[i].armed = cmds[i]; - break; - case 'ALARM_RELEASED' : - if (!result_cmd.services.alarm) { - result_cmd.services.alarm = []; - } - if (!result_cmd.services.alarm[i]) { - result_cmd.services.alarm[i] = {}; - } - result_cmd.services.alarm[i].released = cmds[i]; - break; - case 'ALARM_SET_MODE' : - if (!result_cmd.services.alarm) { - result_cmd.services.alarm = []; - } - if (!result_cmd.services.alarm[i]) { - result_cmd.services.alarm[i] = {}; - } - result_cmd.services.alarm[i].set_mode = cmds[i]; - break; - /** *************** GENERIC ***********************/ - case 'AIRQUALITY_INDEX' : - if (!result_cmd.services.AirQuality) { - result_cmd.services.AirQuality = []; - } - if (!result_cmd.services.AirQuality[i]) { - result_cmd.services.AirQuality[i] = {}; - } - result_cmd.services.AirQuality[i].Index = cmds[i]; - break; - case 'AIRQUALITY_PM25' : - if (!result_cmd.services.AirQuality) { - result_cmd.services.AirQuality = []; - } - if (!result_cmd.services.AirQuality[i]) { - result_cmd.services.AirQuality[i] = {}; - } - result_cmd.services.AirQuality[i].PM25 = cmds[i]; - break; - case 'AIRQUALITY_CUSTOM' : - if (!result_cmd.services.AirQualityCustom) { - result_cmd.services.AirQualityCustom = []; - } - if (!result_cmd.services.AirQualityCustom[i]) { - result_cmd.services.AirQualityCustom[i] = {}; - } - result_cmd.services.AirQualityCustom[i].Index = cmds[i]; - break; - case 'NOISE' : - if (!result_cmd.services.Noise) { - result_cmd.services.Noise = []; - } - if (!result_cmd.services.Noise[i]) { - result_cmd.services.Noise[i] = {}; - } - result_cmd.services.Noise[i].Noise = cmds[i]; - break; - case 'CO2' : - if (!result_cmd.services.CO2) { - result_cmd.services.CO2 = []; - } - if (!result_cmd.services.CO2[i]) { - result_cmd.services.CO2[i] = {}; - } - result_cmd.services.CO2[i].CO2 = cmds[i]; - break; - case 'CO' : - if (!result_cmd.services.CO) { - result_cmd.services.CO = []; - } - if (!result_cmd.services.CO[i]) { - result_cmd.services.CO[i] = {}; - } - result_cmd.services.CO[i].CO = cmds[i]; - break; - case 'OPENING_WINDOW' : - case 'OPENING' : - if (!result_cmd.services.opening) { - result_cmd.services.opening = []; - } - if (!result_cmd.services.opening[i]) { - result_cmd.services.opening[i] = {}; - } - result_cmd.services.opening[i].opening = cmds[i]; - break; - case 'BATTERY' : - if (!result_cmd.services.battery) { - result_cmd.services.battery = []; - } - if (!result_cmd.services.battery[i]) { - result_cmd.services.battery[i] = {}; - } - result_cmd.services.battery[i].battery = cmds[i]; - break; - case 'BATTERY_CHARGING' : // not existing yet - if (!result_cmd.services.battery) { - result_cmd.services.battery = []; - } - if (!result_cmd.services.battery[i]) { - result_cmd.services.battery[i] = {}; - } - result_cmd.services.battery[i].batteryCharging = cmds[i]; - break; - case 'DEFECT' : - if (!result_cmd.services.defect) { - result_cmd.services.defect = []; - } - if (!result_cmd.services.defect[i]) { - result_cmd.services.defect[i] = {}; - } - result_cmd.services.defect[i].defect = cmds[i]; - break; - case 'PRESENCE' : - if (!result_cmd.services.presence) { - result_cmd.services.presence = []; - } - if (!result_cmd.services.presence[i]) { - result_cmd.services.presence[i] = {}; - } - result_cmd.services.presence[i].presence = cmds[i]; - result_cmd.numDetector++; - break; - case 'OCCUPANCY' : - if (!result_cmd.services.occupancy) { - result_cmd.services.occupancy = []; - } - if (!result_cmd.services.occupancy[i]) { - result_cmd.services.occupancy[i] = {}; - } - result_cmd.services.occupancy[i].occupancy = cmds[i]; - result_cmd.numDetector++; - break; - case 'TEMPERATURE' : - if (!result_cmd.services.temperature) { - result_cmd.services.temperature = []; - } - if (!result_cmd.services.temperature[i]) { - result_cmd.services.temperature[i] = {}; - } - result_cmd.services.temperature[i].temperature = cmds[i]; - break; - case 'BRIGHTNESS' : - if (!result_cmd.services.brightness) { - result_cmd.services.brightness = []; - } - if (!result_cmd.services.brightness[i]) { - result_cmd.services.brightness[i] = {}; - } - result_cmd.services.brightness[i].brightness = cmds[i]; - break; - case 'SMOKE' : - if (!result_cmd.services.smoke) { - result_cmd.services.smoke = []; - } - if (!result_cmd.services.smoke[i]) { - result_cmd.services.smoke[i] = {}; - } - result_cmd.services.smoke[i].smoke = cmds[i]; - break; - case 'UV' : // via custom - if (!result_cmd.services.uv) { - result_cmd.services.uv = []; - } - if (!result_cmd.services.uv[i]) { - result_cmd.services.uv[i] = {}; - } - result_cmd.services.uv[i].uv = cmds[i]; - break; - case 'HUMIDITY' : - if (!result_cmd.services.humidity) { - result_cmd.services.humidity = []; - } - if (!result_cmd.services.humidity[i]) { - result_cmd.services.humidity[i] = {}; - } - result_cmd.services.humidity[i].humidity = cmds[i]; - break; - case 'SABOTAGE' : - if (!result_cmd.services.sabotage) { - result_cmd.services.sabotage = []; - } - if (!result_cmd.services.sabotage[i]) { - result_cmd.services.sabotage[i] = {}; - } - result_cmd.services.sabotage[i].sabotage = cmds[i]; - break; - case 'FLOOD' : - case 'WATER_LEAK' : - if (!result_cmd.services.flood) { - result_cmd.services.flood = []; - } - if (!result_cmd.services.flood[i]) { - result_cmd.services.flood[i] = {}; - } - result_cmd.services.flood[i].flood = cmds[i]; - break; - case 'POWER' : // via custom - if (!result_cmd.services.power) { - result_cmd.services.power = []; - } - if (!result_cmd.services.power[i]) { - result_cmd.services.power[i] = {}; - } - result_cmd.services.power[i].power = cmds[i]; - break; - case 'CONSUMPTION' : // via custom - if (!result_cmd.services.consumption) { - result_cmd.services.consumption = []; - } - if (!result_cmd.services.consumption[i]) { - result_cmd.services.consumption[i] = {}; - } - result_cmd.services.consumption[i].consumption = cmds[i]; - break; - case 'ACTIVE' : - if (!result_cmd.services.status_active) { - result_cmd.services.status_active = []; - } - if (!result_cmd.services.status_active[i]) { - result_cmd.services.status_active[i] = {}; - } - result_cmd.services.status_active[i].status_active = cmds[i]; - break; - case 'SPEAKER_VOLUME' : - case 'VOLUME' : - if (!result_cmd.services.speaker) { - result_cmd.services.speaker = []; - } - if (!result_cmd.services.speaker[i]) { - result_cmd.services.speaker[i] = {}; - } - result_cmd.services.speaker[i].volume = cmds[i]; - break; - case 'SPEAKER_SET_VOLUME' : - case 'SET_VOLUME' : - if (!result_cmd.services.speaker) { - result_cmd.services.speaker = []; - } - if (!result_cmd.services.speaker[i]) { - result_cmd.services.speaker[i] = {}; - } - result_cmd.services.speaker[i].set_volume = cmds[i]; - break; - case 'SPEAKER_MUTE' : - if (!result_cmd.services.speaker) { - result_cmd.services.speaker = []; - } - if (!result_cmd.services.speaker[i]) { - result_cmd.services.speaker[i] = {}; - } - result_cmd.services.speaker[i].mute = cmds[i]; - break; - case 'SPEAKER_MUTE_TOGGLE' : - if (!result_cmd.services.speaker) { - result_cmd.services.speaker = []; - } - if (!result_cmd.services.speaker[i]) { - result_cmd.services.speaker[i] = {}; - } - result_cmd.services.speaker[i].mute_toggle = cmds[i]; - break; - case 'SPEAKER_MUTE_ON' : - if (!result_cmd.services.speaker) { - result_cmd.services.speaker = []; - } - if (!result_cmd.services.speaker[i]) { - result_cmd.services.speaker[i] = {}; - } - result_cmd.services.speaker[i].mute_on = cmds[i]; - break; - case 'SPEAKER_MUTE_OFF' : - if (!result_cmd.services.speaker) { - result_cmd.services.speaker = []; - } - if (!result_cmd.services.speaker[i]) { - result_cmd.services.speaker[i] = {}; - } - result_cmd.services.speaker[i].mute_off = cmds[i]; - break; - case 'PRESSURE' : - if (!result_cmd.services.pressure) { - result_cmd.services.pressure = []; - } - if (!result_cmd.services.pressure[i]) { - result_cmd.services.pressure[i] = {}; - } - result_cmd.services.pressure[i].pressure = cmds[i]; - break; - } - } - } - } - return result_cmd; +JeedomClient.prototype.executeDeviceAction = function(ID, action, param) { + if(USE_QUEUES === 0) {return this._executeDeviceAction(ID, action, param);} + return new Promise((resolve, reject) => { + this.queue.push({ID, action, param, type:'cmd'}, (err, result) => { + if (err) {reject(err);} + else {resolve(result);} + }); + }); }; -JeedomClient.prototype.executeDeviceAction = function(ID, action, param) { - var that = this; - var options = ',"options":{}'; +JeedomClient.prototype._executeDeviceAction = function(ID, action, param) { + var options = {}; // console.log('params : ' + param); if (param != null) { if (action == 'setRGB') { - options = ',"options":{"color":"' + param + '"}'; + options = {color:param}; } else if (action == 'GBtoggleSelect') { - options = ',"options":{"select":"' + param + '"}'; - } else if (!isNaN(parseInt(param))) { - options = ',"options":{"slider":' + parseInt(param) + '}'; + options = {select:param}; + } else if (!isNaN(parseInt(param)) && parseInt(param) == param) { + options = {slider:parseInt(param)}; + } else if (!isNaN(parseFloat(param)) && parseFloat(param) == param) { + options = {slider:parseFloat(param)}; } } - return new Promise(function(resolve, reject) { - var url = that.url; - var request_id = Math.floor(Math.random() * 1000); - request.post(url, { - json : true, - form : { - request : '{"jsonrpc":"2.0","id":"'+request_id+'","method":"cmd::execCmd","params":{"apikey":"' + that.apikey + '","id":"' + ID + '"' + options + ',"session":true,"sess_id":"'+ that.sess_id +'"}}', - }, - }, function(err, response, json) { - if (!err && (response.statusCode == 200 || response.statusCode == 202)){ - if(!json.result && json.error) { - reject(json.error); - } else { - if(json.sess_id !== undefined) { - that.sess_id = json.sess_id; - } else { - that.sess_id = ""; - } - resolve(json.result); - } - } else { - reject(err); - } - }); + return axios.post(this.url, + { + jsonrpc:"2.0", + id:(Math.floor(Math.random() * 1000)), + method:"cmd::execCmd", + params:{ + apikey:this.apikey, + id:ID, + options:options, + }, + }).then((result) => { + if(!result.data) {return Promise.reject("JSON reçu de Jeedom invalide, vérifiez le log API de Jeedom, reçu :"+JSON.stringify(result));} + if(!result.data.result && result.data.error) { + return Promise.reject(result.data.error.message); + } else { + return result.data.result; + } }); }; JeedomClient.prototype.executeScenarioAction = function(ID, action) { - var that = this; - - return new Promise(function(resolve, reject) { - var url = that.url; - var request_id = Math.floor(Math.random() * 1000); - request.post(url, { - json : true, - form : { - request : '{"jsonrpc":"2.0","id":"'+request_id+'","method":"scenario::changeState","params":{"apikey":"' + that.apikey + '","id":"' + ID + '","state":"' + action + '","session":true,"sess_id":"'+ that.sess_id +'"}}', - }, - }, function(err, response, json) { - if (!err && (response.statusCode == 200 || response.statusCode == 202)) { - if(!json.result && json.error) { - reject(json.error); - } else { - if(json.sess_id !== undefined) { - that.sess_id = json.sess_id; - } else { - that.sess_id = ""; - } - resolve(json.result); - } - } else { - reject(err); - } + if(USE_QUEUES === 0) {return this._executeScenarioAction(ID, action);} + return new Promise((resolve, reject) => { + this.queue.push({ID, action, type:'scenario'}, (err, result) => { + if (err) {reject(err);} + else {resolve(result);} }); }); }; +JeedomClient.prototype._executeScenarioAction = function(ID, action) { + return axios.post(this.url, + { + jsonrpc:"2.0", + id:(Math.floor(Math.random() * 1000)), + method:"scenario::changeState", + params:{ + apikey:this.apikey, + id:ID, + state:action, + }, + }).then((result) => { + if(!result.data) {return Promise.reject("JSON reçu de Jeedom invalide, vérifiez le log API de Jeedom, reçu :"+JSON.stringify(result));} + if(!result.data.result && result.data.error) { + return Promise.reject(result.data.error.message); + } else { + return result.data.result; + } + }); +}; + JeedomClient.prototype.refreshStates = function() { - var that = this; - return new Promise(function(resolve, reject) { - var url = that.url; - var request_id = Math.floor(Math.random() * 1000); - request.post(url, { - timeout : 70000, - json : true, - form : { - request : '{"jsonrpc":"2.0","id":"'+request_id+'","method":"event::changes","params":{"apikey":"' + that.apikey + '","longPolling":"30","datetime" : "' + that.Plateform.lastPoll + '","filter":"homebridge","session":true,"sess_id":"'+ that.sess_id +'"}}', - }, - }, function(err, response, json) { - if (!err && response.statusCode == 200) { - if(!json.result && json.error) { - reject(json.error); + return axios.post(this.url, + { + jsonrpc:"2.0", + id:(Math.floor(Math.random() * 1000)), + method:"event::changes", + params:{ + apikey:this.apikey, + longPolling:30, + datetime:this.Plateform.lastPoll, + filter:"homebridge", + }, + },{ + timeout: 70000, + }).then((result) => { + if(!result.data) {return Promise.reject("JSON reçu de Jeedom invalide, vérifiez le log API de Jeedom, reçu :"+JSON.stringify(result));} + if(!result.data.result && result.data.error) { + return Promise.reject(result.data.error.message); + } else { + return result.data.result; + } + }); +}; + +function initServ(result_cmd, value, serviceType, property, isPush = false) { + result_cmd.services[serviceType] ??= []; + const service = {}; + if (isPush) { + service[property] ??= []; + service[property].push(value); + } else { + service[property] = value; + } + result_cmd.services[serviceType].push(service); +} + +JeedomClient.prototype.ParseGenericType = function(EqLogic, cmds) { + const result_cmd = {...EqLogic, services: {}, numSwitches: 0, numDetector: 0}; + cmds.forEach((cmd) => { + if (cmd.generic_type !== null) { + + if(cmd.generic_type === 'MODE_SET_STATE') { + if(cmd.logicalId === "returnPreviousMode") { + initServ(result_cmd,cmd,'mode','set_state_previous'); } else { - if(json.sess_id !== undefined) { - that.sess_id = json.sess_id; - } else { - that.sess_id = ""; - } - resolve(json.result); + initServ(result_cmd,cmd,'mode','set_state',true); + } + return; + } else if(cmd.generic_type === 'GENERIC_ACTION') { + if(cmd.subType=="other") { + initServ(result_cmd,cmd,'Push','Push'); } - } else { - reject(err); + return; } - }); + + const serviceInfo = genTypesMapping[cmd.generic_type]; + if(!serviceInfo) {return;} + initServ(result_cmd, cmd, serviceInfo.serviceType, serviceInfo.property, serviceInfo.isPush || false); + + if(cmd.generic_type === 'PRESENCE') { + result_cmd.numDetector++; + } else if(cmd.generic_type === 'OCCUPANCY') { + result_cmd.numDetector++; + } else if(cmd.generic_type === 'SWITCH_STATE' || cmd.generic_type === 'CAMERA_RECORD_STATE') { + result_cmd.numSwitches++; + } + } }); + return result_cmd; }; -function isset() { - var a = arguments, l = a.length, i = 0; +const genTypesMapping = { + // *************** MODE *********************** + 'MODE_STATE': {serviceType: 'mode', property: 'state'}, + + // *************** LIGHT *********************** + 'LIGHT_STATE': {serviceType: 'light', property: 'state'}, + 'LIGHT_BRIGHTNESS': {serviceType: 'light', property: 'brightness'}, + 'LIGHT_STATE_BOOL': {serviceType: 'light', property: 'state_bool'}, + 'LIGHT_ON': {serviceType: 'light', property: 'on'}, + 'LIGHT_OFF': {serviceType: 'light', property: 'off'}, + 'LIGHT_SLIDER': {serviceType: 'light', property: 'slider'}, + 'LIGHT_COLOR': {serviceType: 'light', property: 'color'}, + 'LIGHT_COLOR_TEMP': {serviceType: 'light', property: 'color_temp'}, + 'LIGHT_SET_COLOR': {serviceType: 'light', property: 'setcolor'}, + 'LIGHT_SET_COLOR_TEMP': {serviceType: 'light', property: 'setcolor_temp'}, + + // *************** WEATHER *********************** + 'WEATHER_TEMPERATURE': {serviceType: 'weather', property: 'temperature'}, + 'WEATHER_HUMIDITY': {serviceType: 'weather', property: 'humidity'}, + 'WEATHER_PRESSURE': {serviceType: 'weather', property: 'pressure'}, + 'WEATHER_WIND_SPEED': {serviceType: 'weather', property: 'wind_speed'}, + 'WEATHER_WIND_DIRECTION': {serviceType: 'weather', property: 'wind_direction'}, + 'WEATHER_CONDITION': {serviceType: 'weather', property: 'condition'}, + 'WEATHER_UVINDEX': {serviceType: 'weather', property: 'UVIndex'}, + 'WEATHER_VISIBILITY': {serviceType: 'weather', property: 'visibility'}, + 'WEATHER_RAIN': {serviceType: 'weather', property: 'rain'}, + 'WEATHER_SNOW': {serviceType: 'weather', property: 'snow'}, + 'WEATHER_TEMPERATURE_MIN': {serviceType: 'weather', property: 'temperature_min'}, + + // *************** SIREN *********************** + 'SIREN_STATE': {serviceType: 'siren', property: 'state'}, + // 'SIREN_ON': {serviceType: 'siren', property: 'on'}, + // 'SIREN_OFF': {serviceType: 'siren', property: 'off'}, + + // *************** ENERGY *********************** + 'ENERGY_STATE': {serviceType: 'energy', property: 'state'}, + 'ENERGY_ON': {serviceType: 'energy', property: 'on'}, + 'ENERGY_OFF': {serviceType: 'energy', property: 'off'}, + 'ENERGY_INUSE': {serviceType: 'energy', property: 'inuse'}, + + // *************** VALVES *********************** + 'FAUCET_STATE': {serviceType: 'faucet', property: 'state'}, + 'FAUCET_ON': {serviceType: 'faucet', property: 'on'}, + 'FAUCET_OFF': {serviceType: 'faucet', property: 'off'}, + 'IRRIG_STATE': {serviceType: 'irrigation', property: 'state'}, + 'IRRIG_ON': {serviceType: 'irrigation', property: 'on'}, + 'IRRIG_OFF': {serviceType: 'irrigation', property: 'off'}, + 'VALVE_STATE': {serviceType: 'valve', property: 'state'}, + 'VALVE_ON': {serviceType: 'valve', property: 'on'}, + 'VALVE_OFF': {serviceType: 'valve', property: 'off'}, + 'VALVE_SET_DURATION': {serviceType: 'valve', property: 'setDuration'}, + 'VALVE_REMAINING_DURATION': {serviceType: 'valve', property: 'remainingDuration'}, + + // *************** FAN *********************** + 'FAN_STATE': {serviceType: 'fan', property: 'state'}, + 'FAN_SPEED_STATE': {serviceType: 'fan', property: 'state'}, + 'FAN_ON': {serviceType: 'fan', property: 'on'}, + 'FAN_OFF': {serviceType: 'fan', property: 'off'}, + 'FAN_SLIDER': {serviceType: 'fan', property: 'slider'}, + 'FAN_SPEED': {serviceType: 'fan', property: 'slider'}, + + // *************** SWITCH *********************** + 'SWITCH_STATE': {serviceType: 'Switch', property: 'state'}, + 'SWITCH_ON': {serviceType: 'Switch', property: 'on'}, + 'SWITCH_OFF': {serviceType: 'Switch', property: 'off'}, + 'CAMERA_RECORD_STATE': {serviceType: 'Switch', property: 'state'}, + 'CAMERA_RECORD': {serviceType: 'Switch', property: 'on'}, + 'CAMERA_STOP': {serviceType: 'Switch', property: 'off'}, + + // *************** PUSH *********************** + 'PUSH_BUTTON': {serviceType: 'Push', property: 'Push'}, + 'CAMERA_UP': {serviceType: 'Push', property: 'Push'}, + 'CAMERA_DOWN': {serviceType: 'Push', property: 'Push'}, + 'CAMERA_LEFT': {serviceType: 'Push', property: 'Push'}, + 'CAMERA_RIGHT': {serviceType: 'Push', property: 'Push'}, + 'CAMERA_ZOOM': {serviceType: 'Push', property: 'Push'}, + 'CAMERA_DEZOOM':{serviceType: 'Push', property: 'Push'}, + 'CAMERA_PRESET':{serviceType: 'Push', property: 'Push'}, + + // *************** BARRIER/GARAGE************** + 'BARRIER_STATE': {serviceType: 'GarageDoor', property: 'state'}, + 'GARAGE_STATE': {serviceType: 'GarageDoor', property: 'state'}, + 'GB_OPEN': {serviceType: 'GarageDoor', property: 'on'}, // should not be used + 'GB_CLOSE': {serviceType: 'GarageDoor', property: 'off'}, // should not be used + 'GB_TOGGLE': {serviceType: 'GarageDoor', property: 'toggle'}, + + // *************** LOCK *********************** + 'LOCK_STATE': {serviceType: 'lock', property: 'state'}, + 'LOCK_OPEN': {serviceType: 'lock', property: 'on'}, + 'LOCK_CLOSE': {serviceType: 'lock', property: 'off'}, + + // *************** StatelessSwitch ****************** + 'SWITCH_STATELESS_ALLINONE': {serviceType: 'StatelessSwitch', property: 'eventType'}, + 'SWITCH_STATELESS_SINGLE': {serviceType: 'StatelessSwitchMono', property: 'Single'}, + 'SWITCH_STATELESS_DOUBLE': {serviceType: 'StatelessSwitchMono', property: 'Double'}, + 'SWITCH_STATELESS_LONG': {serviceType: 'StatelessSwitchMono', property: 'Long'}, + + // *************** FLAP *********************** + 'FLAP_STATE': {serviceType: 'flap', property: 'state'}, + 'FLAP_STATE_CLOSING': {serviceType: 'flap', property: 'stateClosing'}, + 'FLAP_UP': {serviceType: 'flap', property: 'up'}, + 'FLAP_DOWN': {serviceType: 'flap', property: 'down'}, + 'FLAP_SLIDER': {serviceType: 'flap', property: 'slider'}, + 'FLAP_STOP': {serviceType: 'flap', property: 'stop'}, + 'FLAP_HOR_TILT_STATE': {serviceType: 'flap', property: 'HorTiltState'}, + 'FLAP_HOR_TILT_SLIDER': {serviceType: 'flap', property: 'HorTiltSlider'}, + 'FLAP_VER_TILT_STATE': {serviceType: 'flap', property: 'VerTiltState'}, + 'FLAP_VER_TILT_SLIDER': {serviceType: 'flap', property: 'VerTiltSlider'}, + + // *************** WINDOW *********************** + 'WINDOW_STATE': {serviceType: 'windowMoto', property: 'state'}, + 'WINDOW_UP': {serviceType: 'windowMoto', property: 'up'}, + 'WINDOW_DOWN': {serviceType: 'windowMoto', property: 'down'}, + 'WINDOW_SLIDER':{serviceType: 'windowMoto', property: 'slider'}, + + // ************* THERMOSTAT *********************** + 'THERMOSTAT_STATE': {serviceType: 'thermostat', property: 'state'}, + 'THERMOSTAT_STATE_NAME': {serviceType: 'thermostat', property: 'state_name'}, + 'THERMOSTAT_TEMPERATURE': {serviceType: 'thermostat', property: 'temperature'}, + 'THERMOSTAT_SET_SETPOINT': {serviceType: 'thermostat', property: 'set_setpoint'}, + 'THERMOSTAT_SETPOINT': {serviceType: 'thermostat', property: 'setpoint'}, + 'THERMOSTAT_SET_MODE': {serviceType: 'thermostat', property: 'set_mode'}, + 'THERMOSTAT_MODE': {serviceType: 'thermostat', property: 'mode'}, + 'THERMOSTAT_LOCK': {serviceType: 'thermostat', property: 'lock'}, + 'THERMOSTAT_SET_LOCK': {serviceType: 'thermostat', property: 'set_lock'}, + 'THERMOSTAT_SET_UNLOCK': {serviceType: 'thermostat', property: 'set_unlock'}, + 'THERMOSTAT_TEMPERATURE_OUTDOOR': {serviceType: 'thermostat', property: 'temperature_outdoor'}, - if (l === 0) { - throw new Error('Empty isset'); - } + // ************* THERMOSTAT_HC *********************** + 'THERMOSTAT_HC_STATE': {serviceType: 'thermostatHC', property: 'state'}, + 'THERMOSTAT_HC_STATE_NAME': {serviceType: 'thermostatHC', property: 'state_name'}, + 'THERMOSTAT_HC_TEMPERATURE': {serviceType: 'thermostatHC', property: 'temperature'}, + 'THERMOSTAT_HC_SET_SETPOINT_H': {serviceType: 'thermostatHC', property: 'set_setpointH'}, + 'THERMOSTAT_HC_SET_SETPOINT_C': {serviceType: 'thermostatHC', property: 'set_setpointC'}, + 'THERMOSTAT_HC_SETPOINT_H': {serviceType: 'thermostatHC', property: 'setpointH'}, + 'THERMOSTAT_HC_SETPOINT_C': {serviceType: 'thermostatHC', property: 'setpointC'}, + 'THERMOSTAT_HC_SET_MODE': {serviceType: 'thermostatHC', property: 'set_mode'}, + 'THERMOSTAT_HC_MODE': {serviceType: 'thermostatHC', property: 'mode'}, + 'THERMOSTAT_HC_LOCK': {serviceType: 'thermostatHC', property: 'lock'}, + 'THERMOSTAT_HC_SET_LOCK': {serviceType: 'thermostatHC', property: 'set_lock'}, + 'THERMOSTAT_HC_SET_UNLOCK': {serviceType: 'thermostatHC', property: 'set_unlock'}, - while (i !== l) { - if (!a[i]) { - return false; - } - i++; - } - return true; -} + // ************* ALARME *********************** + 'ALARM_STATE': {serviceType: 'alarm', property: 'state'}, + 'ALARM_MODE': {serviceType: 'alarm', property: 'mode'}, + 'ALARM_ENABLE_STATE': {serviceType: 'alarm', property: 'enable_state'}, + 'ALARM_ARMED': {serviceType: 'alarm', property: 'armed'}, + 'ALARM_RELEASED': {serviceType: 'alarm', property: 'released'}, + 'ALARM_SET_MODE': {serviceType: 'alarm', property: 'set_mode'}, + + // ************* SPEAKER *********************** + 'SPEAKER_VOLUME': {serviceType: 'speaker', property: 'volume'}, + 'VOLUME': {serviceType: 'speaker', property: 'volume'}, + 'SPEAKER_SET_VOLUME': {serviceType: 'speaker', property: 'set_volume'}, + 'SET_VOLUME': {serviceType: 'speaker', property: 'set_volume'}, + 'SPEAKER_MUTE': {serviceType: 'speaker', property: 'mute'}, + 'SPEAKER_MUTE_TOGGLE': {serviceType: 'speaker', property: 'mute_toggle'}, + 'SPEAKER_MUTE_ON': {serviceType: 'speaker', property: 'mute_on'}, + 'SPEAKER_MUTE_OFF': {serviceType: 'speaker', property: 'mute_off'}, + + // *************** GENERIC *********************** + 'AIRQUALITY_INDEX': {serviceType: 'AirQuality', property: 'Index'}, + 'AIRQUALITY_PM25': {serviceType: 'AirQuality', property: 'PM25'}, + 'AIRQUALITY_CUSTOM': {serviceType: 'AirQualityCustom', property: 'Index'}, + 'NOISE': {serviceType: 'Noise', property: 'Noise'}, + 'CO2': {serviceType: 'CO2', property: 'CO2'}, + 'CO': {serviceType: 'CO', property: 'CO'}, + 'OPENING_WINDOW': {serviceType: 'opening', property: 'opening'}, + 'OPENING': {serviceType: 'opening', property: 'opening'}, + 'BATTERY': {serviceType: 'battery', property: 'battery'}, + 'BATTERY_CHARGING': {serviceType: 'battery', property: 'batteryCharging'}, // not existing yet + 'DEFECT': {serviceType: 'defect', property: 'defect'}, + 'PRESENCE': {serviceType: 'presence', property: 'presence'}, + 'OCCUPANCY': {serviceType: 'occupancy', property: 'occupancy'}, + 'TEMPERATURE': {serviceType: 'temperature', property: 'temperature'}, + 'BRIGHTNESS': {serviceType: 'brightness', property: 'brightness'}, + 'SMOKE': {serviceType: 'smoke', property: 'smoke'}, + 'UV': {serviceType: 'uv', property: 'uv'}, // via custom + 'HUMIDITY': {serviceType: 'humidity', property: 'humidity'}, + 'SABOTAGE': {serviceType: 'sabotage', property: 'sabotage'}, + 'FLOOD': {serviceType: 'flood', property: 'flood'}, + 'WATER_LEAK': {serviceType: 'flood', property: 'flood'}, + 'POWER': {serviceType: 'power', property: 'power'}, // via custom + 'CONSUMPTION': {serviceType: 'consumption', property: 'consumption'}, // via custom + 'ACTIVE': {serviceType: 'status_active', property: 'status_active'}, + 'PRESSURE': {serviceType: 'pressure', property: 'pressure'}, + 'SHOCK': {serviceType: 'generic', property: 'state'}, + 'RAIN_CURRENT': {serviceType: 'generic', property: 'state'}, + 'RAIN_TOTAL': {serviceType: 'generic', property: 'state'}, + 'WIND_SPEED': {serviceType: 'generic', property: 'state'}, + 'WIND_DIRECTION': {serviceType: 'generic', property: 'state'}, + 'GENERIC_INFO': {serviceType: 'generic', property: 'state'}, +}; -module.exports.createClient = function(url, apikey, Plateform,myPlugin) { +module.exports.createClient = function(url, apikey, Plateform, myPlugin) { return new JeedomClient(url, apikey, Plateform,myPlugin); }; diff --git a/lib/myLogger.js b/lib/myLogger.js index 5e3aa78f..4df98f6d 100644 --- a/lib/myLogger.js +++ b/lib/myLogger.js @@ -41,7 +41,7 @@ var loggerCache = {}; function myLogger(debugLevel,logger,creationLogPath) { this.logger = logger; this.debugLevel= debugLevel; - this.allowedLevel = ['debug','info','warn','error']; + this.allowedLevel = ['debug','info','warn','error','conf']; this.creationLogPath = creationLogPath; this.creationPassed = false; fs.writeFileSync(this.creationLogPath+startLog, '['+(new Date().toISOString())+"] ---Début du log de création---\n"); @@ -49,10 +49,10 @@ function myLogger(debugLevel,logger,creationLogPath) { msg = util.format.apply(util, Array.prototype.slice.call(arguments, 1)); if(msg) { - if(this.allowedLevel.indexOf(level) !== -1) { + if(this.allowedLevel.indexOf(level.toLowerCase()) !== -1) { msg="["+level.toUpperCase()+"] "+msg; } else { - msg=level+' '+msg; + msg=level.toLowerCase()+' '+msg; } } else { msg=level; @@ -75,6 +75,9 @@ function myLogger(debugLevel,logger,creationLogPath) { this.logger(msg); msg=null; }; + this.changeLevel = (newDebugLevel) => { + this.debugLevel=newDebugLevel; + }; } myLogger.createMyLogger = function(debugLevel,logger,creationLogPath) { @@ -84,6 +87,7 @@ myLogger.createMyLogger = function(debugLevel,logger,creationLogPath) { var ml = new myLogger(debugLevel,logger,creationLogPath); var log = ml.log.bind(ml); log.log = ml.log; + log.changeLevel = ml.changeLevel.bind(ml); loggerCache[debugLevel] = log; } return loggerCache[debugLevel]; diff --git a/package.json b/package.json index d5cd8fa2..5f1fb9f1 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "@nebz/homebridge-jeedom", - "version": "v1.6.1", - "cust_serial": "0009", + "version": "v1.7.0", + "cust_serial": "0024", "description": "Homebridge plugin for Jeedom ", "main": "index.js", "private":true, @@ -25,13 +25,15 @@ "Siri" ], "dependencies": { - "request": ">=2.88.2", + "async": "3.2.5", + "axios": "1.6.7", + "express": "4.18.2", "fakegato-history": "NebzHB/fakegato-history#master" }, "devDependencies": { - "@babel/core": ">=7.23.2", - "@babel/eslint-parser": "^7.22.15", - "eslint": "^8.52.0" + "@babel/core": ">=7.23.9", + "@babel/eslint-parser": "^7.23.10", + "eslint": "^8.56.0" }, "author": "Nebz ", "license": "GPL-2.0",