Skip to content
  • Home
  • Aktuell
  • Tags
  • 0 Ungelesen 0
  • Kategorien
  • Unreplied
  • Beliebt
  • GitHub
  • Docu
  • Hilfe
Skins
  • Light
  • Brite
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Standard: (Kein Skin)
  • Kein Skin
Einklappen
ioBroker Logo

Community Forum

donate donate
  1. ioBroker Community Home
  2. Deutsch
  3. Skripten / Logik
  4. Hue Push API für Hue Adapter

NEWS

  • UPDATE 31.10.: Amazon Alexa - ioBroker Skill läuft aus ?
    apollon77A
    apollon77
    48
    3
    8.7k

  • Monatsrückblick – September 2025
    BluefoxB
    Bluefox
    13
    1
    2.2k

  • Neues Video "KI im Smart Home" - ioBroker plus n8n
    BluefoxB
    Bluefox
    16
    1
    3.1k

Hue Push API für Hue Adapter

Geplant Angeheftet Gesperrt Verschoben Skripten / Logik
164 Beiträge 46 Kommentatoren 37.5k Aufrufe 57 Watching
  • Älteste zuerst
  • Neuste zuerst
  • Meiste Stimmen
Antworten
  • In einem neuen Thema antworten
Anmelden zum Antworten
Dieses Thema wurde gelöscht. Nur Nutzer mit entsprechenden Rechten können es sehen.
  • M MCU

    @murdockus
    Script aus Post 12 neuladen (wurde geändert!): https://forum.iobroker.net/topic/47391/hue-push-api-für-hue-adapter/12

    d6ee0351-9313-4241-a73f-2a7ed759f133-image.png

    In der javascript Instanz: hue-push-client eintragen:

    b015d4a1-ef44-4b98-a8d3-56a185e15df7-image.png

    Script in ein neues javascript Objekt kopieren.
    c9186b86-8ee4-47c5-b5fd-0ac6390829bd-image.png

    Die Definitionen im Script ändern: IP, TOKEN, INSTANCE.
    Und dann das Script starten.

    M Offline
    M Offline
    Murdockus
    schrieb am zuletzt editiert von
    #29

    @mcu
    Danke ! Klappt perfekt und auf anhieb ! Jetzt kann ich endlich mein Hue Wall Switch Modul in Iobroker benutzen ! :tada:

    A sentinelS 2 Antworten Letzte Antwort
    0
    • P Pman

      Bisher hat Philips die Push API nicht offiziell released und sie wird noch nicht vom Hue-Adapter unterstützt. Dieses Skript baut eine Verbindung zur Bridge auf und aktualisiert entsprechende States "live", ich empfehle das polling im Adapter zu deaktivieren. Welche Datenpunkte aktualisiert werden kann man in der UPDATEMAP nachlesen.
      Weitere Hinweise siehe Skript.
      Update
      1.1.0 hue-extended support
      1.1.1 ZGPSwitch support
      1.1.2 bekannte push calls ignorieren um weniger log zu erzeugen
      1.1.3 Zone support (only on)

      /**
      * Version: 1.1.3 (HUE + HUE-EXTENDED)
      * Anleitung: 
      *  - npm-Modul im Javascript-Adapter hinzufügen (Adaptereinstellung): hue-push-client 
      *  - IP: IP der Bridge eintragen
      *  - TOKEN: gültigen User für die Bridge eintragen (z.B. aus der Hue Adapter Konfiguration)
      *  - INSTANCE: korrekte Instanz eingeben, meist hue.0 oder hue-extended.0
      **/
      const IP = '<bridge ip>';
      const TOKEN = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
      const INSTANCE = 'hue.0';
      
      /**
      * DO NOT EDIT BELOW
      **/
      const UPDATEMAP_HUE = {
          //lights
          'lights.status.status': {stateName: 'reachable', convert: (val) => {return val === 'connected' ? true : false;}, validTypes: ['Extended color light', 'Color temperature light', 'Dimmable light', 'On/Off plug-in unit'], after: (stateId, value) => {updateHueState(stateId.substring(0, stateId.lastIndexOf('.'))  + '.on', value)}},
          'lights.on.on': {stateName: 'on', validTypes: ['Extended color light', 'Color temperature light', 'Dimmable light', 'On/Off plug-in unit']},
          'lights.dimming.brightness': {stateName: 'level', convert: (val) => {return Math.ceil(val)}, validTypes: ['Extended color light', 'Color temperature light', 'Dimmable light'], after: (stateId, value) => {updateRGBHue(stateId.substring(0, stateId.lastIndexOf('.')))}},
          'lights.color_temperature.mirek': {stateName: 'ct', convert: (val) => {return Math.round(1000000/val)}, validTypes: ['Extended color light', 'Color temperature light']},
          'lights.color.xy': {stateName: 'xy', convert: (val) => {return val.x + ',' + val.y}, validTypes: ['Extended color light'], after: (stateId, value) => {updateRGBHue(stateId.substring(0, stateId.lastIndexOf('.')))}},
      
          //groups
          'groups.on.on': {stateName: 'on', validTypes: ['Room', 'LightGroup', 'Zone']},
      
          //sensors
          'sensors.motion.motion': {stateName: 'presence', validTypes: ['ZLLPresence']},
          'sensors.light.light_level':  {stateName: 'lightlevel', convert: (val) => {return Math.round(val)}, validTypes: ['ZLLLightLevel']},
          'sensors.temperature.temperature': {stateName: 'temperature', convert: (val) => {return Number.parseFloat(val.toPrecision(4))}, validTypes: ['ZLLTemperature']},
          'sensors.power_state.battery_level': {stateName: 'battery', convert: (val) => {return Math.round(val)}, validTypes: ['ZLLPresence', 'ZLLLightLevel', 'ZLLTemperature', 'ZLLSwitch']},
          //buttons
          'sensors.button.last_event': {stateName: 'buttonevent', convert: (val) => {return ((UUIDs[this.idv2] && UUIDs[this.idv2].metadata) ? UUIDs[this.idv2].metadata.control_id : 0) * 1000 + (val === 'repeat' ? 1 : 0) + (val === 'short_release' ? 2 : 0) + (val === 'long_release' ? 3 : 0)}, validTypes: ['ZLLSwitch', 'ZGPSwitch']},
      
          //ignore
          'lights.owner.rid':{},
          'lights.owner.rtype':{},
          'sensors.owner.rid':{},
          'sensors.owner.rtype':{},
          'sensors.power_state.battery_state': {},
      };
      
      const UPDATEMAP_HUE_EXTENDED = {
          //lights
          'lights.status.status': {stateName: 'state.reachable', convert: (val) => {return val === 'connected' ? true : false;}, validTypes: ['Extended color light', 'Color temperature light', 'Dimmable light', 'On/Off plug-in unit']},
          'lights.on.on': {stateName: 'action.on', validTypes: ['Extended color light', 'Color temperature light', 'Dimmable light', 'On/Off plug-in unit']},  
          'lights.dimming.brightness': {stateName: 'action.level', convert: (val) => {return Math.ceil(val)}, validTypes: ['Extended color light', 'Color temperature light', 'Dimmable light'], after: (stateId, value) => {updateRGBHueExtended(stateId.substring(0, stateId.lastIndexOf('.')))}},
          'lights.color_temperature.mirek': {stateName: 'action.colorTemperature', convert: (val) => {return Math.round(1000000/val)}, validTypes: ['Extended color light', 'Color temperature light']},
          'lights.color.xy': {stateName: 'action.xy', convert: (val) => {return val.x + ',' + val.y}, validTypes: ['Extended color light'], after: (stateId, value) => {updateRGBHueExtended(stateId.substring(0, stateId.lastIndexOf('.')))}},
        
          //groups
          'groups.on.on': {stateName: 'state.any_on', validTypes: ['Room', 'LightGroup', 'Zone']},
      
          //sensors
          'sensors.motion.motion': {stateName: 'state.presence', convert: (val) => {return val.toString()}, validTypes: ['ZLLPresence']},
          'sensors.light.light_level':  {stateName: 'state.lightlevel', convert: (val) => {return Math.round(val).toString()}, validTypes: ['ZLLLightLevel']},
          'sensors.temperature.temperature': {stateName: 'state.temperature', convert: (val) => {return Number.parseFloat(val.toPrecision(4))}, validTypes: ['ZLLTemperature']},
          'sensors.power_state.battery_level': {stateName: 'config.battery', convert: (val) => {return Math.round(val)}, validTypes: ['ZLLPresence', 'ZLLLightLevel', 'ZLLTemperature', 'ZLLSwitch']},
          //buttons
          'sensors.button.last_event': {stateName: 'state.buttonevent', convert: (val) => {return ((UUIDs[this.idv2] && UUIDs[this.idv2].metadata) ? UUIDs[this.idv2].metadata.control_id : 0) * 1000 + (val === 'short_release' ? 2 : 0) + (val === 'long_release' ? 3 : 0)}, validTypes: ['ZLLSwitch', 'ZGPSwitch']},
      
          //ignore
          'lights.owner.rid':{},
          'lights.owner.rtype':{},
          'sensors.owner.rid':{},
          'sensors.owner.rtype':{},
          'sensors.power_state.battery_state': {},
      };
      
      //select UPDATEMAP for hue or hue-extended
      const UPDATEMAP = INSTANCE.toLowerCase().includes('extended') ? UPDATEMAP_HUE_EXTENDED : UPDATEMAP_HUE;
      const findState = INSTANCE.toLowerCase().includes('extended') ? findStateHueExtended : findStateHue;
      
      //connect to event stream
      const HuePushClient = require('hue-push-client');
      const client = new HuePushClient({ip: IP, user: TOKEN});
      client.addEventListener('open', function () {
          log('connected');
      });
      client.addEventListener('close', function () {
          log('disconnected', 'warn');
      });
      client.addEventListener('error', function (e) {
          log('connection error: ' + e.message, 'warn');
      });
      client.addEventListener('message', function (packet) {
          parsePacket(packet);
      });
      
      //get resouce ids (required to identify buttons)
      let UUIDs = {};
      async function getUUIDs() {
          try {
              UUIDs = await client.uuids();
          } catch (e) {
              log(e, 'warn');
          }
      };
      getUUIDs();
      
      
      // close connection if script is stopped
      onStop(function (callback) {
          client.close();
          callback();
      }, 2000);
      
      function parsePacket (packet) {
          log('RECEIVED PACKET: ' + "\n" + JSON.stringify(packet), 'debug');
          try {
              if (!packet.data) {
                  log('packet has no data: ' + JSON.stringify(packet), 'warn');
                  return;
              }
              for (let message of JSON.parse(packet.data)) {
                  if (message.type !== 'update') {
                      log ('unknown message type: ' + JSON.stringify(message), 'warn');
                      continue;
                  }
                  if (typeof message.data !== 'object') {
                      log ('message contains no data: '  + JSON.stringify(message), 'warn');
                      continue;
                  }
                  for (let update of message.data) {
                      parseUpdate(update);
                  }
              }
          } catch (e) {
              log('could not read packet: ' + JSON.stringify(packet), 'warn');
              log(e.message, 'warn');
              return;
          }
      }
      
      function parseUpdate(update) {
          log('PARSING UPDATE: ' + "\n" + JSON.stringify(update), 'debug');
      
          if (!update.id_v1) return;
          const [resource, idv1] = update.id_v1.split('/').filter(Boolean);
          const idv2 = update.id;
      
          //remove id, id_v1, type
          delete  update.id;
          delete  update.id_v1;
          delete  update.type;
      
          //status to object as other updates are objects
          if (update.status) {
              update.status = {status: update.status};
          }
      
          processUpdate(resource, idv1, idv2, update);
      }
      
      let IdCache = [];
      function processUpdate(resource, resourceId, idv2, data) {
          this.resource = resource;
          this.resourceId = resourceId;
          this.idv2 = idv2;
          this.data = data;
      
          log('PROCESSING UPDATE: ' + 'resource ' + resource + "\n" + JSON.stringify(data), 'debug');
          //check for values to data
          for (let action in data) {
              if (typeof data[action] !== 'object') {continue;}
      
              //check if update invalid and delete _valid entries
              for (let endpoint in data[action]) {
                  if (endpoint.substr(-6) === '_valid') {
                      if (!data[action][endpoint]) {
                          log('skipping invalid value' + resource + '.' + action + '.' + endpoint, 'debug');
                          return;
                      } else {
                          delete data[action][endpoint];
                      }
                  } 
              }
              //find hue adapter states to update and set new values
              for (let endpoint in data[action]) {
                  if (UPDATEMAP[resource + '.' + action + '.' + endpoint]) {    
                      log('found UPDATEMAP for ' + resource + '.' + action + '.' + endpoint, 'debug');
                      let updateValue = data[action][endpoint];
                      //convert value?
                      if (typeof UPDATEMAP[resource + '.' + action + '.' + endpoint].convert === 'function') {
                          let updateValueOld = updateValue;
                          updateValue = UPDATEMAP[resource + '.' + action + '.' + endpoint].convert.call(this, updateValue);
                          log('converted ' + resource + '.' + action + '.' + endpoint + ' from ' + updateValueOld + ' to ' + updateValue, 'debug');
                      }
                      let stateName = UPDATEMAP[resource + '.' + action + '.' + endpoint].stateName;
                      
                      //check if state id is cached
                      if (!IdCache[resource + '.' + resourceId + '.' + stateName]) {
                          findState(resource, resourceId, stateName, action, endpoint, () => {
                              updateHueState(IdCache[resource + '.' + resourceId + '.' + stateName], updateValue, UPDATEMAP[resource + '.' + action + '.' + endpoint].after);
                          });
                      } else {
                          log('found cache entry for ' + resource + '.' + resourceId + '.' + stateName + ': ' + IdCache[resource + '.' + resourceId + '.' + stateName], 'debug');
                          updateHueState(IdCache[resource + '.' + resourceId + '.' + stateName], updateValue, UPDATEMAP[resource + '.' + action + '.' + endpoint].after);
                      }
      
                  } else {
                      log('missing update instructions for ' + resource + '.' + action + '.' + endpoint);
                      log(JSON.stringify(data));
                  }
              }
          }
      }
      
      async function findStateHue(resource, resourceId, stateName, action, endpoint, callback) {
          log('searching for object with id ' + resourceId + ' and stateName ' + stateName, 'debug');
          $(INSTANCE + '.*' + '.' + stateName).each(function (stateId, i) {  //better way to find matching objects?
              getObject(stateId, (err, obj) => {
                  if (!err) {
                      if (obj.native && obj.native.id && obj.native.id == resourceId) {
                          log('found ' + stateId + ', checking parent for matching type...', 'debug');
                          //get parent object and check type
                          let parentId = stateId.substring(0, stateId.lastIndexOf('.'));
                          getObject(parentId, (err2, obj2) => {
                              if (!err2) {
                                  if (obj2.native && obj2.native.type && UPDATEMAP[resource + '.' + action + '.' + endpoint].validTypes.indexOf(obj2.native.type) !== -1 && !IdCache[resource + '.' + resourceId + '.' + stateName]) {
                                      log('found matching type for ' + parentId + ': ' + obj2.native.type, 'debug');
                                      log('save cache entry "' + resource + '.' + resourceId + '.' + stateName + '":' + stateId, 'debug');
                                      IdCache[resource + '.' + resourceId + '.' + stateName] = stateId;
                                      callback();
                                  }
                              } else {
                                  log('could not find obj: ' + stateId, 'warn');
                              }
                          });    
                      }
                  } else {
                      log('could not find obj: ' + stateId, 'warn');
                  }
              });
          });
      }
      
      async function findStateHueExtended(resource, resourceId, stateName, action, endpoint, callback) {
          log('searching for object with id ' + resourceId + ' and stateName ' + stateName, 'debug');
          $(INSTANCE + '.' + resource + '.*' + '.uid').each(async (stateId, i) => {  //better way to find matching objects?
              const deviceId = await getStateAsync(stateId);
              //check if device id matches
              if (deviceId.val !== resourceId) {
                  return;
              }
              const device = stateId.substr(0,stateId.length-4);
              //make sure final object exists
              const stateExists = await existsObjectAsync(device + '.' + stateName);
              if (!stateExists) {
                  return;
              }
              //check if type is valid and save cache entry
              const deviceType = await getStateAsync(device + '.type');
              if (UPDATEMAP[resource + '.' + action + '.' + endpoint].validTypes.indexOf(deviceType.val) !== -1 && !IdCache[resource + '.' + resourceId + '.' + stateName]) {
                  log('found matching type for ' + resourceId + ': ' + deviceType.val, 'debug');
                  log('save cache entry "' + resource + '.' + resourceId + '.' + stateName + '":' + device + '.' + stateName, 'debug');
                  IdCache[resource + '.' + resourceId + '.' + stateName] = device + '.' + stateName;
                  callback();                    
              }
          });
      }
      
      function updateHueState(stateId, value, after) {
          log('set ' + stateId + ' to ' + value + ' (' + typeof value + ')', 'debug');
          setStateDelayed(stateId, value, true, 50, true, () => {
              if (typeof after === 'function') {
                  log ('running  function after change of ' + stateId, 'debug');
                  after(stateId, value);
              }
          });
      } 
      
      
      //helpers
      async function updateRGBHue(stateId) {
          let xyState = await getStateAsync(stateId + '.xy');
          if (!xyState) return;
          let xy = xyState.val.replace('[', '').replace(']', '').split(',');
          let levelState = await getStateAsync(stateId + '.level');
          let level = levelState.val / 100;
          //let onState = await getStateAsync(stateId + '.on');
          //if (onState.val === false) level = 0;
          let rgb = HelperXYBtoRGB(xy[0], xy[1], level);
      
          updateHueState(stateId + '.r', Math.round(rgb.Red * 255));
          updateHueState(stateId + '.g', Math.round(rgb.Green * 255));
          updateHueState(stateId + '.b', Math.round(rgb.Blue * 255));
      }
      
      async function updateRGBHueExtended(stateId) {
          let xyState = await getStateAsync(stateId + '.xy');
          if (!xyState) return;
          let xy = xyState.val.replace('[', '').replace(']', '').split(',');
          let levelState = await getStateAsync(stateId + '.level');
          let level = levelState.val / 100;
          let rgb = HelperXYBtoRGB(xy[0], xy[1], level);
          updateHueState(stateId + '.rgb', Math.round(rgb.Red * 255) + ',' + Math.round(rgb.Green * 255) + ',' + Math.round(rgb.Blue * 255));
      }
      
      function HelperXYBtoRGB (x, y, Brightness) { // Source: https://github.com/PhilipsHue/PhilipsHueSDK-iOS-OSX/blob/master/ApplicationDesignNotes/RGB%20to%20xy%20Color%20conversion.md
          if (Brightness <= 0) {
              return {Red: 0, Green: 0, Blue: 0};
          }
          Brightness = Brightness || 1.0; // Default full brightness
          const z = 1.0 - x - y;
          const Y = Brightness;
          const X = (Y / y) * x;
          const Z = (Y / y) * z;
          // XYZ to RGB [M]-1 for Wide RGB D65, http://www.developers.meethue.com/documentation/color-conversions-rgb-xy
          let Red = X * 1.656492 - Y * 0.354851 - Z * 0.255038;
          let Green = -X * 0.707196 + Y * 1.655397 + Z * 0.036152;
          let Blue = X * 0.051713 - Y * 0.121364 + Z * 1.011530;
          // Limit RGB on [0..1]
          if (Red > Blue && Red > Green && Red > 1.0) { // Red is too big
              Green = Green / Red;
              Blue = Blue / Red;
              Red = 1.0;
          }
          if (Red < 0) {
              Red = 0;
          }
          if (Green > Blue && Green > Red && Green > 1.0) { // Green is too big
              Red = Red / Green;
              Blue = Blue / Green;
              Green = 1.0;
          }
          if (Green < 0) {
              Green = 0;
          }
          if (Blue > Red && Blue > Green && Blue > 1.0) { // Blue is too big
              Red = Red / Blue;
              Green = Green / Blue;
              Blue = 1.0;
          }
          if (Blue < 0) {
              Blue = 0;
          }
          // Apply reverse gamma correction
          if (Red <= 0.0031308) {
              Red = Red * 12.92;
          } else {
              Red = 1.055 * Math.pow(Red, (1.0 / 2.4)) - 0.055;
          }
          if (Green <= 0.0031308) {
              Green = Green * 12.92;
          } else {
              Green = 1.055 * Math.pow(Green, (1.0 / 2.4)) - 0.055;
          }
          if (Blue <= 0.0031308) {
              Blue = Blue * 12.92;
          } else {
              Blue = 1.055 * Math.pow(Blue, (1.0 / 2.4)) - 0.055;
          }
          // Limit RGB on [0..1]
          if (Red > Blue && Red > Green && Red > 1.0) { // Red is too big
              Green = Green / Red;
              Blue = Blue / Red;
              Red = 1.0;
          }
          if (Red < 0) {
              Red = 0;
          }
          if (Green > Blue && Green > Red && Green > 1.0) { // Green is too big
              Red = Red / Green;
              Blue = Blue / Green;
              Green = 1.0;
          }
          if (Green < 0) {
              Green = 0;
          }
          if (Blue > Red && Blue > Green && Blue > 1.0) { // Blue is too big
              Red = Red / Blue;
              Green = Green / Blue;
              Blue = 1.0;
          }
          if (Blue < 0) {
              Blue = 0;
          }
          return {Red: Red, Green: Green, Blue: Blue};
      };
      
      
      S Online
      S Online
      Solardach
      schrieb am zuletzt editiert von
      #30

      @pman Ich bin ganz zufällig hier drauf gekommen.
      Endlich funktionieren meine HUE Bewegungsmelder ohne Zeit Verzögerung.
      Einbindung des Skripts verlief problemlos und funktioniert Perfekt.

      Vielen Dank !!

      1 Antwort Letzte Antwort
      0
      • M Murdockus

        @mcu
        Danke ! Klappt perfekt und auf anhieb ! Jetzt kann ich endlich mein Hue Wall Switch Modul in Iobroker benutzen ! :tada:

        A Offline
        A Offline
        aleks-83
        schrieb am zuletzt editiert von
        #31

        @murdockus
        Könntest du mir bitte mal einen Screenshot machen welche Datenpunkte ein Wall Switch erstellt und füttert?
        Das würde mir sehr helfen.

        = Dell Optiplex Micro - 10GB RAM - 200GB SSD - Debian VM =
        = Node.js v20.18.3 = NPM 10.2.3 = JS Controller 7.0.6 =

        Ubiquiti UAP-AC-LR - UAP-AC-Lite - Synology DS716+II - Fritz!Box 7490
        Glasfaser 400

        1 Antwort Letzte Antwort
        0
        • P Pman

          Bisher hat Philips die Push API nicht offiziell released und sie wird noch nicht vom Hue-Adapter unterstützt. Dieses Skript baut eine Verbindung zur Bridge auf und aktualisiert entsprechende States "live", ich empfehle das polling im Adapter zu deaktivieren. Welche Datenpunkte aktualisiert werden kann man in der UPDATEMAP nachlesen.
          Weitere Hinweise siehe Skript.
          Update
          1.1.0 hue-extended support
          1.1.1 ZGPSwitch support
          1.1.2 bekannte push calls ignorieren um weniger log zu erzeugen
          1.1.3 Zone support (only on)

          /**
          * Version: 1.1.3 (HUE + HUE-EXTENDED)
          * Anleitung: 
          *  - npm-Modul im Javascript-Adapter hinzufügen (Adaptereinstellung): hue-push-client 
          *  - IP: IP der Bridge eintragen
          *  - TOKEN: gültigen User für die Bridge eintragen (z.B. aus der Hue Adapter Konfiguration)
          *  - INSTANCE: korrekte Instanz eingeben, meist hue.0 oder hue-extended.0
          **/
          const IP = '<bridge ip>';
          const TOKEN = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
          const INSTANCE = 'hue.0';
          
          /**
          * DO NOT EDIT BELOW
          **/
          const UPDATEMAP_HUE = {
              //lights
              'lights.status.status': {stateName: 'reachable', convert: (val) => {return val === 'connected' ? true : false;}, validTypes: ['Extended color light', 'Color temperature light', 'Dimmable light', 'On/Off plug-in unit'], after: (stateId, value) => {updateHueState(stateId.substring(0, stateId.lastIndexOf('.'))  + '.on', value)}},
              'lights.on.on': {stateName: 'on', validTypes: ['Extended color light', 'Color temperature light', 'Dimmable light', 'On/Off plug-in unit']},
              'lights.dimming.brightness': {stateName: 'level', convert: (val) => {return Math.ceil(val)}, validTypes: ['Extended color light', 'Color temperature light', 'Dimmable light'], after: (stateId, value) => {updateRGBHue(stateId.substring(0, stateId.lastIndexOf('.')))}},
              'lights.color_temperature.mirek': {stateName: 'ct', convert: (val) => {return Math.round(1000000/val)}, validTypes: ['Extended color light', 'Color temperature light']},
              'lights.color.xy': {stateName: 'xy', convert: (val) => {return val.x + ',' + val.y}, validTypes: ['Extended color light'], after: (stateId, value) => {updateRGBHue(stateId.substring(0, stateId.lastIndexOf('.')))}},
          
              //groups
              'groups.on.on': {stateName: 'on', validTypes: ['Room', 'LightGroup', 'Zone']},
          
              //sensors
              'sensors.motion.motion': {stateName: 'presence', validTypes: ['ZLLPresence']},
              'sensors.light.light_level':  {stateName: 'lightlevel', convert: (val) => {return Math.round(val)}, validTypes: ['ZLLLightLevel']},
              'sensors.temperature.temperature': {stateName: 'temperature', convert: (val) => {return Number.parseFloat(val.toPrecision(4))}, validTypes: ['ZLLTemperature']},
              'sensors.power_state.battery_level': {stateName: 'battery', convert: (val) => {return Math.round(val)}, validTypes: ['ZLLPresence', 'ZLLLightLevel', 'ZLLTemperature', 'ZLLSwitch']},
              //buttons
              'sensors.button.last_event': {stateName: 'buttonevent', convert: (val) => {return ((UUIDs[this.idv2] && UUIDs[this.idv2].metadata) ? UUIDs[this.idv2].metadata.control_id : 0) * 1000 + (val === 'repeat' ? 1 : 0) + (val === 'short_release' ? 2 : 0) + (val === 'long_release' ? 3 : 0)}, validTypes: ['ZLLSwitch', 'ZGPSwitch']},
          
              //ignore
              'lights.owner.rid':{},
              'lights.owner.rtype':{},
              'sensors.owner.rid':{},
              'sensors.owner.rtype':{},
              'sensors.power_state.battery_state': {},
          };
          
          const UPDATEMAP_HUE_EXTENDED = {
              //lights
              'lights.status.status': {stateName: 'state.reachable', convert: (val) => {return val === 'connected' ? true : false;}, validTypes: ['Extended color light', 'Color temperature light', 'Dimmable light', 'On/Off plug-in unit']},
              'lights.on.on': {stateName: 'action.on', validTypes: ['Extended color light', 'Color temperature light', 'Dimmable light', 'On/Off plug-in unit']},  
              'lights.dimming.brightness': {stateName: 'action.level', convert: (val) => {return Math.ceil(val)}, validTypes: ['Extended color light', 'Color temperature light', 'Dimmable light'], after: (stateId, value) => {updateRGBHueExtended(stateId.substring(0, stateId.lastIndexOf('.')))}},
              'lights.color_temperature.mirek': {stateName: 'action.colorTemperature', convert: (val) => {return Math.round(1000000/val)}, validTypes: ['Extended color light', 'Color temperature light']},
              'lights.color.xy': {stateName: 'action.xy', convert: (val) => {return val.x + ',' + val.y}, validTypes: ['Extended color light'], after: (stateId, value) => {updateRGBHueExtended(stateId.substring(0, stateId.lastIndexOf('.')))}},
            
              //groups
              'groups.on.on': {stateName: 'state.any_on', validTypes: ['Room', 'LightGroup', 'Zone']},
          
              //sensors
              'sensors.motion.motion': {stateName: 'state.presence', convert: (val) => {return val.toString()}, validTypes: ['ZLLPresence']},
              'sensors.light.light_level':  {stateName: 'state.lightlevel', convert: (val) => {return Math.round(val).toString()}, validTypes: ['ZLLLightLevel']},
              'sensors.temperature.temperature': {stateName: 'state.temperature', convert: (val) => {return Number.parseFloat(val.toPrecision(4))}, validTypes: ['ZLLTemperature']},
              'sensors.power_state.battery_level': {stateName: 'config.battery', convert: (val) => {return Math.round(val)}, validTypes: ['ZLLPresence', 'ZLLLightLevel', 'ZLLTemperature', 'ZLLSwitch']},
              //buttons
              'sensors.button.last_event': {stateName: 'state.buttonevent', convert: (val) => {return ((UUIDs[this.idv2] && UUIDs[this.idv2].metadata) ? UUIDs[this.idv2].metadata.control_id : 0) * 1000 + (val === 'short_release' ? 2 : 0) + (val === 'long_release' ? 3 : 0)}, validTypes: ['ZLLSwitch', 'ZGPSwitch']},
          
              //ignore
              'lights.owner.rid':{},
              'lights.owner.rtype':{},
              'sensors.owner.rid':{},
              'sensors.owner.rtype':{},
              'sensors.power_state.battery_state': {},
          };
          
          //select UPDATEMAP for hue or hue-extended
          const UPDATEMAP = INSTANCE.toLowerCase().includes('extended') ? UPDATEMAP_HUE_EXTENDED : UPDATEMAP_HUE;
          const findState = INSTANCE.toLowerCase().includes('extended') ? findStateHueExtended : findStateHue;
          
          //connect to event stream
          const HuePushClient = require('hue-push-client');
          const client = new HuePushClient({ip: IP, user: TOKEN});
          client.addEventListener('open', function () {
              log('connected');
          });
          client.addEventListener('close', function () {
              log('disconnected', 'warn');
          });
          client.addEventListener('error', function (e) {
              log('connection error: ' + e.message, 'warn');
          });
          client.addEventListener('message', function (packet) {
              parsePacket(packet);
          });
          
          //get resouce ids (required to identify buttons)
          let UUIDs = {};
          async function getUUIDs() {
              try {
                  UUIDs = await client.uuids();
              } catch (e) {
                  log(e, 'warn');
              }
          };
          getUUIDs();
          
          
          // close connection if script is stopped
          onStop(function (callback) {
              client.close();
              callback();
          }, 2000);
          
          function parsePacket (packet) {
              log('RECEIVED PACKET: ' + "\n" + JSON.stringify(packet), 'debug');
              try {
                  if (!packet.data) {
                      log('packet has no data: ' + JSON.stringify(packet), 'warn');
                      return;
                  }
                  for (let message of JSON.parse(packet.data)) {
                      if (message.type !== 'update') {
                          log ('unknown message type: ' + JSON.stringify(message), 'warn');
                          continue;
                      }
                      if (typeof message.data !== 'object') {
                          log ('message contains no data: '  + JSON.stringify(message), 'warn');
                          continue;
                      }
                      for (let update of message.data) {
                          parseUpdate(update);
                      }
                  }
              } catch (e) {
                  log('could not read packet: ' + JSON.stringify(packet), 'warn');
                  log(e.message, 'warn');
                  return;
              }
          }
          
          function parseUpdate(update) {
              log('PARSING UPDATE: ' + "\n" + JSON.stringify(update), 'debug');
          
              if (!update.id_v1) return;
              const [resource, idv1] = update.id_v1.split('/').filter(Boolean);
              const idv2 = update.id;
          
              //remove id, id_v1, type
              delete  update.id;
              delete  update.id_v1;
              delete  update.type;
          
              //status to object as other updates are objects
              if (update.status) {
                  update.status = {status: update.status};
              }
          
              processUpdate(resource, idv1, idv2, update);
          }
          
          let IdCache = [];
          function processUpdate(resource, resourceId, idv2, data) {
              this.resource = resource;
              this.resourceId = resourceId;
              this.idv2 = idv2;
              this.data = data;
          
              log('PROCESSING UPDATE: ' + 'resource ' + resource + "\n" + JSON.stringify(data), 'debug');
              //check for values to data
              for (let action in data) {
                  if (typeof data[action] !== 'object') {continue;}
          
                  //check if update invalid and delete _valid entries
                  for (let endpoint in data[action]) {
                      if (endpoint.substr(-6) === '_valid') {
                          if (!data[action][endpoint]) {
                              log('skipping invalid value' + resource + '.' + action + '.' + endpoint, 'debug');
                              return;
                          } else {
                              delete data[action][endpoint];
                          }
                      } 
                  }
                  //find hue adapter states to update and set new values
                  for (let endpoint in data[action]) {
                      if (UPDATEMAP[resource + '.' + action + '.' + endpoint]) {    
                          log('found UPDATEMAP for ' + resource + '.' + action + '.' + endpoint, 'debug');
                          let updateValue = data[action][endpoint];
                          //convert value?
                          if (typeof UPDATEMAP[resource + '.' + action + '.' + endpoint].convert === 'function') {
                              let updateValueOld = updateValue;
                              updateValue = UPDATEMAP[resource + '.' + action + '.' + endpoint].convert.call(this, updateValue);
                              log('converted ' + resource + '.' + action + '.' + endpoint + ' from ' + updateValueOld + ' to ' + updateValue, 'debug');
                          }
                          let stateName = UPDATEMAP[resource + '.' + action + '.' + endpoint].stateName;
                          
                          //check if state id is cached
                          if (!IdCache[resource + '.' + resourceId + '.' + stateName]) {
                              findState(resource, resourceId, stateName, action, endpoint, () => {
                                  updateHueState(IdCache[resource + '.' + resourceId + '.' + stateName], updateValue, UPDATEMAP[resource + '.' + action + '.' + endpoint].after);
                              });
                          } else {
                              log('found cache entry for ' + resource + '.' + resourceId + '.' + stateName + ': ' + IdCache[resource + '.' + resourceId + '.' + stateName], 'debug');
                              updateHueState(IdCache[resource + '.' + resourceId + '.' + stateName], updateValue, UPDATEMAP[resource + '.' + action + '.' + endpoint].after);
                          }
          
                      } else {
                          log('missing update instructions for ' + resource + '.' + action + '.' + endpoint);
                          log(JSON.stringify(data));
                      }
                  }
              }
          }
          
          async function findStateHue(resource, resourceId, stateName, action, endpoint, callback) {
              log('searching for object with id ' + resourceId + ' and stateName ' + stateName, 'debug');
              $(INSTANCE + '.*' + '.' + stateName).each(function (stateId, i) {  //better way to find matching objects?
                  getObject(stateId, (err, obj) => {
                      if (!err) {
                          if (obj.native && obj.native.id && obj.native.id == resourceId) {
                              log('found ' + stateId + ', checking parent for matching type...', 'debug');
                              //get parent object and check type
                              let parentId = stateId.substring(0, stateId.lastIndexOf('.'));
                              getObject(parentId, (err2, obj2) => {
                                  if (!err2) {
                                      if (obj2.native && obj2.native.type && UPDATEMAP[resource + '.' + action + '.' + endpoint].validTypes.indexOf(obj2.native.type) !== -1 && !IdCache[resource + '.' + resourceId + '.' + stateName]) {
                                          log('found matching type for ' + parentId + ': ' + obj2.native.type, 'debug');
                                          log('save cache entry "' + resource + '.' + resourceId + '.' + stateName + '":' + stateId, 'debug');
                                          IdCache[resource + '.' + resourceId + '.' + stateName] = stateId;
                                          callback();
                                      }
                                  } else {
                                      log('could not find obj: ' + stateId, 'warn');
                                  }
                              });    
                          }
                      } else {
                          log('could not find obj: ' + stateId, 'warn');
                      }
                  });
              });
          }
          
          async function findStateHueExtended(resource, resourceId, stateName, action, endpoint, callback) {
              log('searching for object with id ' + resourceId + ' and stateName ' + stateName, 'debug');
              $(INSTANCE + '.' + resource + '.*' + '.uid').each(async (stateId, i) => {  //better way to find matching objects?
                  const deviceId = await getStateAsync(stateId);
                  //check if device id matches
                  if (deviceId.val !== resourceId) {
                      return;
                  }
                  const device = stateId.substr(0,stateId.length-4);
                  //make sure final object exists
                  const stateExists = await existsObjectAsync(device + '.' + stateName);
                  if (!stateExists) {
                      return;
                  }
                  //check if type is valid and save cache entry
                  const deviceType = await getStateAsync(device + '.type');
                  if (UPDATEMAP[resource + '.' + action + '.' + endpoint].validTypes.indexOf(deviceType.val) !== -1 && !IdCache[resource + '.' + resourceId + '.' + stateName]) {
                      log('found matching type for ' + resourceId + ': ' + deviceType.val, 'debug');
                      log('save cache entry "' + resource + '.' + resourceId + '.' + stateName + '":' + device + '.' + stateName, 'debug');
                      IdCache[resource + '.' + resourceId + '.' + stateName] = device + '.' + stateName;
                      callback();                    
                  }
              });
          }
          
          function updateHueState(stateId, value, after) {
              log('set ' + stateId + ' to ' + value + ' (' + typeof value + ')', 'debug');
              setStateDelayed(stateId, value, true, 50, true, () => {
                  if (typeof after === 'function') {
                      log ('running  function after change of ' + stateId, 'debug');
                      after(stateId, value);
                  }
              });
          } 
          
          
          //helpers
          async function updateRGBHue(stateId) {
              let xyState = await getStateAsync(stateId + '.xy');
              if (!xyState) return;
              let xy = xyState.val.replace('[', '').replace(']', '').split(',');
              let levelState = await getStateAsync(stateId + '.level');
              let level = levelState.val / 100;
              //let onState = await getStateAsync(stateId + '.on');
              //if (onState.val === false) level = 0;
              let rgb = HelperXYBtoRGB(xy[0], xy[1], level);
          
              updateHueState(stateId + '.r', Math.round(rgb.Red * 255));
              updateHueState(stateId + '.g', Math.round(rgb.Green * 255));
              updateHueState(stateId + '.b', Math.round(rgb.Blue * 255));
          }
          
          async function updateRGBHueExtended(stateId) {
              let xyState = await getStateAsync(stateId + '.xy');
              if (!xyState) return;
              let xy = xyState.val.replace('[', '').replace(']', '').split(',');
              let levelState = await getStateAsync(stateId + '.level');
              let level = levelState.val / 100;
              let rgb = HelperXYBtoRGB(xy[0], xy[1], level);
              updateHueState(stateId + '.rgb', Math.round(rgb.Red * 255) + ',' + Math.round(rgb.Green * 255) + ',' + Math.round(rgb.Blue * 255));
          }
          
          function HelperXYBtoRGB (x, y, Brightness) { // Source: https://github.com/PhilipsHue/PhilipsHueSDK-iOS-OSX/blob/master/ApplicationDesignNotes/RGB%20to%20xy%20Color%20conversion.md
              if (Brightness <= 0) {
                  return {Red: 0, Green: 0, Blue: 0};
              }
              Brightness = Brightness || 1.0; // Default full brightness
              const z = 1.0 - x - y;
              const Y = Brightness;
              const X = (Y / y) * x;
              const Z = (Y / y) * z;
              // XYZ to RGB [M]-1 for Wide RGB D65, http://www.developers.meethue.com/documentation/color-conversions-rgb-xy
              let Red = X * 1.656492 - Y * 0.354851 - Z * 0.255038;
              let Green = -X * 0.707196 + Y * 1.655397 + Z * 0.036152;
              let Blue = X * 0.051713 - Y * 0.121364 + Z * 1.011530;
              // Limit RGB on [0..1]
              if (Red > Blue && Red > Green && Red > 1.0) { // Red is too big
                  Green = Green / Red;
                  Blue = Blue / Red;
                  Red = 1.0;
              }
              if (Red < 0) {
                  Red = 0;
              }
              if (Green > Blue && Green > Red && Green > 1.0) { // Green is too big
                  Red = Red / Green;
                  Blue = Blue / Green;
                  Green = 1.0;
              }
              if (Green < 0) {
                  Green = 0;
              }
              if (Blue > Red && Blue > Green && Blue > 1.0) { // Blue is too big
                  Red = Red / Blue;
                  Green = Green / Blue;
                  Blue = 1.0;
              }
              if (Blue < 0) {
                  Blue = 0;
              }
              // Apply reverse gamma correction
              if (Red <= 0.0031308) {
                  Red = Red * 12.92;
              } else {
                  Red = 1.055 * Math.pow(Red, (1.0 / 2.4)) - 0.055;
              }
              if (Green <= 0.0031308) {
                  Green = Green * 12.92;
              } else {
                  Green = 1.055 * Math.pow(Green, (1.0 / 2.4)) - 0.055;
              }
              if (Blue <= 0.0031308) {
                  Blue = Blue * 12.92;
              } else {
                  Blue = 1.055 * Math.pow(Blue, (1.0 / 2.4)) - 0.055;
              }
              // Limit RGB on [0..1]
              if (Red > Blue && Red > Green && Red > 1.0) { // Red is too big
                  Green = Green / Red;
                  Blue = Blue / Red;
                  Red = 1.0;
              }
              if (Red < 0) {
                  Red = 0;
              }
              if (Green > Blue && Green > Red && Green > 1.0) { // Green is too big
                  Red = Red / Green;
                  Blue = Blue / Green;
                  Green = 1.0;
              }
              if (Green < 0) {
                  Green = 0;
              }
              if (Blue > Red && Blue > Green && Blue > 1.0) { // Blue is too big
                  Red = Red / Blue;
                  Green = Green / Blue;
                  Blue = 1.0;
              }
              if (Blue < 0) {
                  Blue = 0;
              }
              return {Red: Red, Green: Green, Blue: Blue};
          };
          
          
          H Offline
          H Offline
          Hitcher
          schrieb am zuletzt editiert von
          #32

          @pman Mann, das ist einfach nur Megahilfreich! Vielen Dank dafür !!
          Frage:
          Ich habe den Hue und den Hue-Extended am laufen..

          Muss ich das Script dann 2x nutzen? Also 1x mit User und Instanz für HUE und 1x für den Extended?

          ? 1 Antwort Letzte Antwort
          0
          • H Hitcher

            @pman Mann, das ist einfach nur Megahilfreich! Vielen Dank dafür !!
            Frage:
            Ich habe den Hue und den Hue-Extended am laufen..

            Muss ich das Script dann 2x nutzen? Also 1x mit User und Instanz für HUE und 1x für den Extended?

            ? Offline
            ? Offline
            Ein ehemaliger Benutzer
            schrieb am zuletzt editiert von
            #33

            @hitcher said in Hue Push API für Hue Adapter:

            Muss ich das Script dann 2x nutzen? Also 1x mit User und Instanz für HUE und 1x für den Extended?

            Ich denke mal das du das so machen kannst.

            cashC 1 Antwort Letzte Antwort
            0
            • ? Ein ehemaliger Benutzer

              @hitcher said in Hue Push API für Hue Adapter:

              Muss ich das Script dann 2x nutzen? Also 1x mit User und Instanz für HUE und 1x für den Extended?

              Ich denke mal das du das so machen kannst.

              cashC Offline
              cashC Offline
              cash
              Most Active
              schrieb am zuletzt editiert von
              #34

              Ich scheitere leider. Beim Script Start bekomme ich:

              
              javascript.0
              2021-10-10 15:22:38.443	info	script.js.Allgemein.Lichtsteuerung.Hue_Bridge_Push: connected
              
              javascript.0
              2021-10-10 15:22:37.515	info	script.js.Allgemein.Lichtsteuerung.Hue_Bridge_Push: registered 0 subscriptions and 0 schedules
              
              javascript.0
              2021-10-10 15:22:37.479	info	Start javascript script.js.Allgemein.Lichtsteuerung.Hue_Bridge_Push
              

              scheint also alles gut zu sein. Im Javascript habe ich entsprechend hue-push-client eingetragen. Leider kommt kein Update bei den Objekten an wenn ich per Hue-App etwas schalte. Wo könnte mein Problem liegen? Nutze ioBroker in einem Docker.

              cashC 1 Antwort Letzte Antwort
              0
              • cashC cash

                Ich scheitere leider. Beim Script Start bekomme ich:

                
                javascript.0
                2021-10-10 15:22:38.443	info	script.js.Allgemein.Lichtsteuerung.Hue_Bridge_Push: connected
                
                javascript.0
                2021-10-10 15:22:37.515	info	script.js.Allgemein.Lichtsteuerung.Hue_Bridge_Push: registered 0 subscriptions and 0 schedules
                
                javascript.0
                2021-10-10 15:22:37.479	info	Start javascript script.js.Allgemein.Lichtsteuerung.Hue_Bridge_Push
                

                scheint also alles gut zu sein. Im Javascript habe ich entsprechend hue-push-client eingetragen. Leider kommt kein Update bei den Objekten an wenn ich per Hue-App etwas schalte. Wo könnte mein Problem liegen? Nutze ioBroker in einem Docker.

                cashC Offline
                cashC Offline
                cash
                Most Active
                schrieb am zuletzt editiert von
                #35

                ok irgend etwas macht das Script schon. Nur wenn ich per App Licht ein oder ausschalte passiert nichts…

                
                javascript.0
                2021-10-10 16:52:22.298	info	script.js.Allgemein.Lichtsteuerung.Hue_Bridge_Push: {"power_state":{"battery_level":83,"battery_state":"normal"}}
                
                javascript.0
                2021-10-10 16:52:22.294	info	script.js.Allgemein.Lichtsteuerung.Hue_Bridge_Push: missing update instructions for sensors.power_state.battery_state
                
                
                cashC 1 Antwort Letzte Antwort
                0
                • cashC cash

                  ok irgend etwas macht das Script schon. Nur wenn ich per App Licht ein oder ausschalte passiert nichts…

                  
                  javascript.0
                  2021-10-10 16:52:22.298	info	script.js.Allgemein.Lichtsteuerung.Hue_Bridge_Push: {"power_state":{"battery_level":83,"battery_state":"normal"}}
                  
                  javascript.0
                  2021-10-10 16:52:22.294	info	script.js.Allgemein.Lichtsteuerung.Hue_Bridge_Push: missing update instructions for sensors.power_state.battery_state
                  
                  
                  cashC Offline
                  cashC Offline
                  cash
                  Most Active
                  schrieb am zuletzt editiert von
                  #36

                  Lösung gefunden. Es funktioniert schon nur nicht komplett.

                  Ich habe einen Raum hue_Badezimmer im Raum gibt es nur eine Lampe Deckenleuchte Badezimmer. Schalte ich nun in der App den Raum erkennt das Script das Licht und schaltet die Lampe Deckenleuchte Badezimmer den on-Datenpunkt auf true. Nur der on-Datenpunkt vom Raum hue_Badezimmer bleibt auf false.

                  Ist das generell so oder nur ein Problem bei mir?

                  Bei meinen Tests habe ich immer nur auf den Raum geschaut.

                  P 1 Antwort Letzte Antwort
                  0
                  • P Pman

                    Bisher hat Philips die Push API nicht offiziell released und sie wird noch nicht vom Hue-Adapter unterstützt. Dieses Skript baut eine Verbindung zur Bridge auf und aktualisiert entsprechende States "live", ich empfehle das polling im Adapter zu deaktivieren. Welche Datenpunkte aktualisiert werden kann man in der UPDATEMAP nachlesen.
                    Weitere Hinweise siehe Skript.
                    Update
                    1.1.0 hue-extended support
                    1.1.1 ZGPSwitch support
                    1.1.2 bekannte push calls ignorieren um weniger log zu erzeugen
                    1.1.3 Zone support (only on)

                    /**
                    * Version: 1.1.3 (HUE + HUE-EXTENDED)
                    * Anleitung: 
                    *  - npm-Modul im Javascript-Adapter hinzufügen (Adaptereinstellung): hue-push-client 
                    *  - IP: IP der Bridge eintragen
                    *  - TOKEN: gültigen User für die Bridge eintragen (z.B. aus der Hue Adapter Konfiguration)
                    *  - INSTANCE: korrekte Instanz eingeben, meist hue.0 oder hue-extended.0
                    **/
                    const IP = '<bridge ip>';
                    const TOKEN = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
                    const INSTANCE = 'hue.0';
                    
                    /**
                    * DO NOT EDIT BELOW
                    **/
                    const UPDATEMAP_HUE = {
                        //lights
                        'lights.status.status': {stateName: 'reachable', convert: (val) => {return val === 'connected' ? true : false;}, validTypes: ['Extended color light', 'Color temperature light', 'Dimmable light', 'On/Off plug-in unit'], after: (stateId, value) => {updateHueState(stateId.substring(0, stateId.lastIndexOf('.'))  + '.on', value)}},
                        'lights.on.on': {stateName: 'on', validTypes: ['Extended color light', 'Color temperature light', 'Dimmable light', 'On/Off plug-in unit']},
                        'lights.dimming.brightness': {stateName: 'level', convert: (val) => {return Math.ceil(val)}, validTypes: ['Extended color light', 'Color temperature light', 'Dimmable light'], after: (stateId, value) => {updateRGBHue(stateId.substring(0, stateId.lastIndexOf('.')))}},
                        'lights.color_temperature.mirek': {stateName: 'ct', convert: (val) => {return Math.round(1000000/val)}, validTypes: ['Extended color light', 'Color temperature light']},
                        'lights.color.xy': {stateName: 'xy', convert: (val) => {return val.x + ',' + val.y}, validTypes: ['Extended color light'], after: (stateId, value) => {updateRGBHue(stateId.substring(0, stateId.lastIndexOf('.')))}},
                    
                        //groups
                        'groups.on.on': {stateName: 'on', validTypes: ['Room', 'LightGroup', 'Zone']},
                    
                        //sensors
                        'sensors.motion.motion': {stateName: 'presence', validTypes: ['ZLLPresence']},
                        'sensors.light.light_level':  {stateName: 'lightlevel', convert: (val) => {return Math.round(val)}, validTypes: ['ZLLLightLevel']},
                        'sensors.temperature.temperature': {stateName: 'temperature', convert: (val) => {return Number.parseFloat(val.toPrecision(4))}, validTypes: ['ZLLTemperature']},
                        'sensors.power_state.battery_level': {stateName: 'battery', convert: (val) => {return Math.round(val)}, validTypes: ['ZLLPresence', 'ZLLLightLevel', 'ZLLTemperature', 'ZLLSwitch']},
                        //buttons
                        'sensors.button.last_event': {stateName: 'buttonevent', convert: (val) => {return ((UUIDs[this.idv2] && UUIDs[this.idv2].metadata) ? UUIDs[this.idv2].metadata.control_id : 0) * 1000 + (val === 'repeat' ? 1 : 0) + (val === 'short_release' ? 2 : 0) + (val === 'long_release' ? 3 : 0)}, validTypes: ['ZLLSwitch', 'ZGPSwitch']},
                    
                        //ignore
                        'lights.owner.rid':{},
                        'lights.owner.rtype':{},
                        'sensors.owner.rid':{},
                        'sensors.owner.rtype':{},
                        'sensors.power_state.battery_state': {},
                    };
                    
                    const UPDATEMAP_HUE_EXTENDED = {
                        //lights
                        'lights.status.status': {stateName: 'state.reachable', convert: (val) => {return val === 'connected' ? true : false;}, validTypes: ['Extended color light', 'Color temperature light', 'Dimmable light', 'On/Off plug-in unit']},
                        'lights.on.on': {stateName: 'action.on', validTypes: ['Extended color light', 'Color temperature light', 'Dimmable light', 'On/Off plug-in unit']},  
                        'lights.dimming.brightness': {stateName: 'action.level', convert: (val) => {return Math.ceil(val)}, validTypes: ['Extended color light', 'Color temperature light', 'Dimmable light'], after: (stateId, value) => {updateRGBHueExtended(stateId.substring(0, stateId.lastIndexOf('.')))}},
                        'lights.color_temperature.mirek': {stateName: 'action.colorTemperature', convert: (val) => {return Math.round(1000000/val)}, validTypes: ['Extended color light', 'Color temperature light']},
                        'lights.color.xy': {stateName: 'action.xy', convert: (val) => {return val.x + ',' + val.y}, validTypes: ['Extended color light'], after: (stateId, value) => {updateRGBHueExtended(stateId.substring(0, stateId.lastIndexOf('.')))}},
                      
                        //groups
                        'groups.on.on': {stateName: 'state.any_on', validTypes: ['Room', 'LightGroup', 'Zone']},
                    
                        //sensors
                        'sensors.motion.motion': {stateName: 'state.presence', convert: (val) => {return val.toString()}, validTypes: ['ZLLPresence']},
                        'sensors.light.light_level':  {stateName: 'state.lightlevel', convert: (val) => {return Math.round(val).toString()}, validTypes: ['ZLLLightLevel']},
                        'sensors.temperature.temperature': {stateName: 'state.temperature', convert: (val) => {return Number.parseFloat(val.toPrecision(4))}, validTypes: ['ZLLTemperature']},
                        'sensors.power_state.battery_level': {stateName: 'config.battery', convert: (val) => {return Math.round(val)}, validTypes: ['ZLLPresence', 'ZLLLightLevel', 'ZLLTemperature', 'ZLLSwitch']},
                        //buttons
                        'sensors.button.last_event': {stateName: 'state.buttonevent', convert: (val) => {return ((UUIDs[this.idv2] && UUIDs[this.idv2].metadata) ? UUIDs[this.idv2].metadata.control_id : 0) * 1000 + (val === 'short_release' ? 2 : 0) + (val === 'long_release' ? 3 : 0)}, validTypes: ['ZLLSwitch', 'ZGPSwitch']},
                    
                        //ignore
                        'lights.owner.rid':{},
                        'lights.owner.rtype':{},
                        'sensors.owner.rid':{},
                        'sensors.owner.rtype':{},
                        'sensors.power_state.battery_state': {},
                    };
                    
                    //select UPDATEMAP for hue or hue-extended
                    const UPDATEMAP = INSTANCE.toLowerCase().includes('extended') ? UPDATEMAP_HUE_EXTENDED : UPDATEMAP_HUE;
                    const findState = INSTANCE.toLowerCase().includes('extended') ? findStateHueExtended : findStateHue;
                    
                    //connect to event stream
                    const HuePushClient = require('hue-push-client');
                    const client = new HuePushClient({ip: IP, user: TOKEN});
                    client.addEventListener('open', function () {
                        log('connected');
                    });
                    client.addEventListener('close', function () {
                        log('disconnected', 'warn');
                    });
                    client.addEventListener('error', function (e) {
                        log('connection error: ' + e.message, 'warn');
                    });
                    client.addEventListener('message', function (packet) {
                        parsePacket(packet);
                    });
                    
                    //get resouce ids (required to identify buttons)
                    let UUIDs = {};
                    async function getUUIDs() {
                        try {
                            UUIDs = await client.uuids();
                        } catch (e) {
                            log(e, 'warn');
                        }
                    };
                    getUUIDs();
                    
                    
                    // close connection if script is stopped
                    onStop(function (callback) {
                        client.close();
                        callback();
                    }, 2000);
                    
                    function parsePacket (packet) {
                        log('RECEIVED PACKET: ' + "\n" + JSON.stringify(packet), 'debug');
                        try {
                            if (!packet.data) {
                                log('packet has no data: ' + JSON.stringify(packet), 'warn');
                                return;
                            }
                            for (let message of JSON.parse(packet.data)) {
                                if (message.type !== 'update') {
                                    log ('unknown message type: ' + JSON.stringify(message), 'warn');
                                    continue;
                                }
                                if (typeof message.data !== 'object') {
                                    log ('message contains no data: '  + JSON.stringify(message), 'warn');
                                    continue;
                                }
                                for (let update of message.data) {
                                    parseUpdate(update);
                                }
                            }
                        } catch (e) {
                            log('could not read packet: ' + JSON.stringify(packet), 'warn');
                            log(e.message, 'warn');
                            return;
                        }
                    }
                    
                    function parseUpdate(update) {
                        log('PARSING UPDATE: ' + "\n" + JSON.stringify(update), 'debug');
                    
                        if (!update.id_v1) return;
                        const [resource, idv1] = update.id_v1.split('/').filter(Boolean);
                        const idv2 = update.id;
                    
                        //remove id, id_v1, type
                        delete  update.id;
                        delete  update.id_v1;
                        delete  update.type;
                    
                        //status to object as other updates are objects
                        if (update.status) {
                            update.status = {status: update.status};
                        }
                    
                        processUpdate(resource, idv1, idv2, update);
                    }
                    
                    let IdCache = [];
                    function processUpdate(resource, resourceId, idv2, data) {
                        this.resource = resource;
                        this.resourceId = resourceId;
                        this.idv2 = idv2;
                        this.data = data;
                    
                        log('PROCESSING UPDATE: ' + 'resource ' + resource + "\n" + JSON.stringify(data), 'debug');
                        //check for values to data
                        for (let action in data) {
                            if (typeof data[action] !== 'object') {continue;}
                    
                            //check if update invalid and delete _valid entries
                            for (let endpoint in data[action]) {
                                if (endpoint.substr(-6) === '_valid') {
                                    if (!data[action][endpoint]) {
                                        log('skipping invalid value' + resource + '.' + action + '.' + endpoint, 'debug');
                                        return;
                                    } else {
                                        delete data[action][endpoint];
                                    }
                                } 
                            }
                            //find hue adapter states to update and set new values
                            for (let endpoint in data[action]) {
                                if (UPDATEMAP[resource + '.' + action + '.' + endpoint]) {    
                                    log('found UPDATEMAP for ' + resource + '.' + action + '.' + endpoint, 'debug');
                                    let updateValue = data[action][endpoint];
                                    //convert value?
                                    if (typeof UPDATEMAP[resource + '.' + action + '.' + endpoint].convert === 'function') {
                                        let updateValueOld = updateValue;
                                        updateValue = UPDATEMAP[resource + '.' + action + '.' + endpoint].convert.call(this, updateValue);
                                        log('converted ' + resource + '.' + action + '.' + endpoint + ' from ' + updateValueOld + ' to ' + updateValue, 'debug');
                                    }
                                    let stateName = UPDATEMAP[resource + '.' + action + '.' + endpoint].stateName;
                                    
                                    //check if state id is cached
                                    if (!IdCache[resource + '.' + resourceId + '.' + stateName]) {
                                        findState(resource, resourceId, stateName, action, endpoint, () => {
                                            updateHueState(IdCache[resource + '.' + resourceId + '.' + stateName], updateValue, UPDATEMAP[resource + '.' + action + '.' + endpoint].after);
                                        });
                                    } else {
                                        log('found cache entry for ' + resource + '.' + resourceId + '.' + stateName + ': ' + IdCache[resource + '.' + resourceId + '.' + stateName], 'debug');
                                        updateHueState(IdCache[resource + '.' + resourceId + '.' + stateName], updateValue, UPDATEMAP[resource + '.' + action + '.' + endpoint].after);
                                    }
                    
                                } else {
                                    log('missing update instructions for ' + resource + '.' + action + '.' + endpoint);
                                    log(JSON.stringify(data));
                                }
                            }
                        }
                    }
                    
                    async function findStateHue(resource, resourceId, stateName, action, endpoint, callback) {
                        log('searching for object with id ' + resourceId + ' and stateName ' + stateName, 'debug');
                        $(INSTANCE + '.*' + '.' + stateName).each(function (stateId, i) {  //better way to find matching objects?
                            getObject(stateId, (err, obj) => {
                                if (!err) {
                                    if (obj.native && obj.native.id && obj.native.id == resourceId) {
                                        log('found ' + stateId + ', checking parent for matching type...', 'debug');
                                        //get parent object and check type
                                        let parentId = stateId.substring(0, stateId.lastIndexOf('.'));
                                        getObject(parentId, (err2, obj2) => {
                                            if (!err2) {
                                                if (obj2.native && obj2.native.type && UPDATEMAP[resource + '.' + action + '.' + endpoint].validTypes.indexOf(obj2.native.type) !== -1 && !IdCache[resource + '.' + resourceId + '.' + stateName]) {
                                                    log('found matching type for ' + parentId + ': ' + obj2.native.type, 'debug');
                                                    log('save cache entry "' + resource + '.' + resourceId + '.' + stateName + '":' + stateId, 'debug');
                                                    IdCache[resource + '.' + resourceId + '.' + stateName] = stateId;
                                                    callback();
                                                }
                                            } else {
                                                log('could not find obj: ' + stateId, 'warn');
                                            }
                                        });    
                                    }
                                } else {
                                    log('could not find obj: ' + stateId, 'warn');
                                }
                            });
                        });
                    }
                    
                    async function findStateHueExtended(resource, resourceId, stateName, action, endpoint, callback) {
                        log('searching for object with id ' + resourceId + ' and stateName ' + stateName, 'debug');
                        $(INSTANCE + '.' + resource + '.*' + '.uid').each(async (stateId, i) => {  //better way to find matching objects?
                            const deviceId = await getStateAsync(stateId);
                            //check if device id matches
                            if (deviceId.val !== resourceId) {
                                return;
                            }
                            const device = stateId.substr(0,stateId.length-4);
                            //make sure final object exists
                            const stateExists = await existsObjectAsync(device + '.' + stateName);
                            if (!stateExists) {
                                return;
                            }
                            //check if type is valid and save cache entry
                            const deviceType = await getStateAsync(device + '.type');
                            if (UPDATEMAP[resource + '.' + action + '.' + endpoint].validTypes.indexOf(deviceType.val) !== -1 && !IdCache[resource + '.' + resourceId + '.' + stateName]) {
                                log('found matching type for ' + resourceId + ': ' + deviceType.val, 'debug');
                                log('save cache entry "' + resource + '.' + resourceId + '.' + stateName + '":' + device + '.' + stateName, 'debug');
                                IdCache[resource + '.' + resourceId + '.' + stateName] = device + '.' + stateName;
                                callback();                    
                            }
                        });
                    }
                    
                    function updateHueState(stateId, value, after) {
                        log('set ' + stateId + ' to ' + value + ' (' + typeof value + ')', 'debug');
                        setStateDelayed(stateId, value, true, 50, true, () => {
                            if (typeof after === 'function') {
                                log ('running  function after change of ' + stateId, 'debug');
                                after(stateId, value);
                            }
                        });
                    } 
                    
                    
                    //helpers
                    async function updateRGBHue(stateId) {
                        let xyState = await getStateAsync(stateId + '.xy');
                        if (!xyState) return;
                        let xy = xyState.val.replace('[', '').replace(']', '').split(',');
                        let levelState = await getStateAsync(stateId + '.level');
                        let level = levelState.val / 100;
                        //let onState = await getStateAsync(stateId + '.on');
                        //if (onState.val === false) level = 0;
                        let rgb = HelperXYBtoRGB(xy[0], xy[1], level);
                    
                        updateHueState(stateId + '.r', Math.round(rgb.Red * 255));
                        updateHueState(stateId + '.g', Math.round(rgb.Green * 255));
                        updateHueState(stateId + '.b', Math.round(rgb.Blue * 255));
                    }
                    
                    async function updateRGBHueExtended(stateId) {
                        let xyState = await getStateAsync(stateId + '.xy');
                        if (!xyState) return;
                        let xy = xyState.val.replace('[', '').replace(']', '').split(',');
                        let levelState = await getStateAsync(stateId + '.level');
                        let level = levelState.val / 100;
                        let rgb = HelperXYBtoRGB(xy[0], xy[1], level);
                        updateHueState(stateId + '.rgb', Math.round(rgb.Red * 255) + ',' + Math.round(rgb.Green * 255) + ',' + Math.round(rgb.Blue * 255));
                    }
                    
                    function HelperXYBtoRGB (x, y, Brightness) { // Source: https://github.com/PhilipsHue/PhilipsHueSDK-iOS-OSX/blob/master/ApplicationDesignNotes/RGB%20to%20xy%20Color%20conversion.md
                        if (Brightness <= 0) {
                            return {Red: 0, Green: 0, Blue: 0};
                        }
                        Brightness = Brightness || 1.0; // Default full brightness
                        const z = 1.0 - x - y;
                        const Y = Brightness;
                        const X = (Y / y) * x;
                        const Z = (Y / y) * z;
                        // XYZ to RGB [M]-1 for Wide RGB D65, http://www.developers.meethue.com/documentation/color-conversions-rgb-xy
                        let Red = X * 1.656492 - Y * 0.354851 - Z * 0.255038;
                        let Green = -X * 0.707196 + Y * 1.655397 + Z * 0.036152;
                        let Blue = X * 0.051713 - Y * 0.121364 + Z * 1.011530;
                        // Limit RGB on [0..1]
                        if (Red > Blue && Red > Green && Red > 1.0) { // Red is too big
                            Green = Green / Red;
                            Blue = Blue / Red;
                            Red = 1.0;
                        }
                        if (Red < 0) {
                            Red = 0;
                        }
                        if (Green > Blue && Green > Red && Green > 1.0) { // Green is too big
                            Red = Red / Green;
                            Blue = Blue / Green;
                            Green = 1.0;
                        }
                        if (Green < 0) {
                            Green = 0;
                        }
                        if (Blue > Red && Blue > Green && Blue > 1.0) { // Blue is too big
                            Red = Red / Blue;
                            Green = Green / Blue;
                            Blue = 1.0;
                        }
                        if (Blue < 0) {
                            Blue = 0;
                        }
                        // Apply reverse gamma correction
                        if (Red <= 0.0031308) {
                            Red = Red * 12.92;
                        } else {
                            Red = 1.055 * Math.pow(Red, (1.0 / 2.4)) - 0.055;
                        }
                        if (Green <= 0.0031308) {
                            Green = Green * 12.92;
                        } else {
                            Green = 1.055 * Math.pow(Green, (1.0 / 2.4)) - 0.055;
                        }
                        if (Blue <= 0.0031308) {
                            Blue = Blue * 12.92;
                        } else {
                            Blue = 1.055 * Math.pow(Blue, (1.0 / 2.4)) - 0.055;
                        }
                        // Limit RGB on [0..1]
                        if (Red > Blue && Red > Green && Red > 1.0) { // Red is too big
                            Green = Green / Red;
                            Blue = Blue / Red;
                            Red = 1.0;
                        }
                        if (Red < 0) {
                            Red = 0;
                        }
                        if (Green > Blue && Green > Red && Green > 1.0) { // Green is too big
                            Red = Red / Green;
                            Blue = Blue / Green;
                            Green = 1.0;
                        }
                        if (Green < 0) {
                            Green = 0;
                        }
                        if (Blue > Red && Blue > Green && Blue > 1.0) { // Blue is too big
                            Red = Red / Blue;
                            Green = Green / Blue;
                            Blue = 1.0;
                        }
                        if (Blue < 0) {
                            Blue = 0;
                        }
                        return {Red: Red, Green: Green, Blue: Blue};
                    };
                    
                    
                    S Nicht stören
                    S Nicht stören
                    stenmic
                    schrieb am zuletzt editiert von
                    #37

                    @pman erstmal danke für dein Skript.
                    Jedoch habe ich ein Problem mit meiner "Bloom Tischleuchte".
                    Bei ihr werden die Datenpunkte z.B. on - true/false einfach nicht aktualisiert.
                    Alle anderen Leuchten funktionieren.

                    hat jemand eine idee.

                    1 Antwort Letzte Antwort
                    0
                    • P Pman

                      Neue Version (siehe start Post), ich habe gleich noch Versucht das Skript kompatibel mit dem hue-extended Adapter zu machen, ist aber weitestgehend ungetestet.
                      Wichtig: benötigt nun das modul "hue-push-client" statt "eventsource".

                      T Offline
                      T Offline
                      TaylorTrifft
                      schrieb am zuletzt editiert von TaylorTrifft
                      #38

                      @pman Moin, nutze dein Script mit dem Hue-extended Adapter, funktioniert alles , allerdings zeigt es mir fehler im Script an weist du evtl eine Lösung? Den Hue-push-client habe ich in JS installiert.
                      Ich habe dir mal die Fehler als JPG angehängt, vielleicht weist du ja auf anhieb was falsch ist, danke dass du das Script geschrieben hast.

                      Einmal bei idv2 und der hue-push-client werden mir jewweiwls als fehler angezeigt, mit * markiert

                      'sensors.button.last_event': {stateName: 'buttonevent', convert: (val) => {return ((UUIDs[this.*idv2*] && UUIDs[this.idv2].metadata) ? UUIDs[this.idv2].metadata.control_id : 0) * 1000 + (val === 'repeat' ? 1 : 0) + (val === 'short_release' ? 2 : 0) + (val === 'long_release' ? 3 : 0)}, validTypes: ['ZLLSwitch']},
                      
                      und
                      const HuePushClient = require(*'hue-push-client'*);
                      
                      arteckA 1 Antwort Letzte Antwort
                      0
                      • T TaylorTrifft

                        @pman Moin, nutze dein Script mit dem Hue-extended Adapter, funktioniert alles , allerdings zeigt es mir fehler im Script an weist du evtl eine Lösung? Den Hue-push-client habe ich in JS installiert.
                        Ich habe dir mal die Fehler als JPG angehängt, vielleicht weist du ja auf anhieb was falsch ist, danke dass du das Script geschrieben hast.

                        Einmal bei idv2 und der hue-push-client werden mir jewweiwls als fehler angezeigt, mit * markiert

                        'sensors.button.last_event': {stateName: 'buttonevent', convert: (val) => {return ((UUIDs[this.*idv2*] && UUIDs[this.idv2].metadata) ? UUIDs[this.idv2].metadata.control_id : 0) * 1000 + (val === 'repeat' ? 1 : 0) + (val === 'short_release' ? 2 : 0) + (val === 'long_release' ? 3 : 0)}, validTypes: ['ZLLSwitch']},
                        
                        und
                        const HuePushClient = require(*'hue-push-client'*);
                        
                        arteckA Offline
                        arteckA Offline
                        arteck
                        Developer Most Active
                        schrieb am zuletzt editiert von arteck
                        #39

                        @taylortrifft bitte keine Bilder vom source..kopier es doch hier rein.. und nutze den code tag

                        c4a8b750-c0db-4965-a4d8-2a05620e3bfb-grafik.png
                        und Fehler welcher Fehler.. wo ist das LOG

                        zigbee hab ich, zwave auch, nuc's genauso und HA auch

                        T 1 Antwort Letzte Antwort
                        0
                        • arteckA arteck

                          @taylortrifft bitte keine Bilder vom source..kopier es doch hier rein.. und nutze den code tag

                          c4a8b750-c0db-4965-a4d8-2a05620e3bfb-grafik.png
                          und Fehler welcher Fehler.. wo ist das LOG

                          T Offline
                          T Offline
                          TaylorTrifft
                          schrieb am zuletzt editiert von
                          #40

                          @arteck Danke geändert.

                          1 Antwort Letzte Antwort
                          0
                          • B Offline
                            B Offline
                            blackeagle998
                            schrieb am zuletzt editiert von
                            #41

                            @Pman
                            Hello und herzlichen Dank für das Skript, funktioniert wunderbar, bis auf folgende kleine Sache.
                            Ich verwende den hue-extended adapter und bekomme im LOG für diverse Lampen folgenden Fehler:

                            javascript.0   2021-10-25 20:19:05.820	warn	at processTimers (internal/timers.js:497:7)
                            javascript.0   2021-10-25 20:19:05.820	warn	at listOnTimeout (internal/timers.js:556:17)
                            javascript.0   2021-10-25 20:19:05.820	warn	at Timeout._onTimeout (/opt/iobroker/node_modules/iobroker.javascript/lib/sandbox.js:1485:29)
                            javascript.0   2021-10-25 20:19:05.819	warn	at Object.setState (/opt/iobroker/node_modules/iobroker.javascript/lib/sandbox.js:1427:20)
                            javascript.0   2021-10-25 20:19:05.818	warn	State "hue-extended.0.lights.022-bad_deckenlampe.state.on" not found
                            

                            Das Skript will auf einen Datenpunkt mit ".state.on" am Ende zugreifen, der müsste aber ".action.on" heißen.
                            Ich bin noch nicht ganz durchgestiegen, wo genau das im Skript herkommt bzw. was man ändern müsste.
                            Deswegen wäre ich dir dankbar, wenn du hierbei unterstützen könntest :-)

                            1 Antwort Letzte Antwort
                            1
                            • P Pman

                              Bisher hat Philips die Push API nicht offiziell released und sie wird noch nicht vom Hue-Adapter unterstützt. Dieses Skript baut eine Verbindung zur Bridge auf und aktualisiert entsprechende States "live", ich empfehle das polling im Adapter zu deaktivieren. Welche Datenpunkte aktualisiert werden kann man in der UPDATEMAP nachlesen.
                              Weitere Hinweise siehe Skript.
                              Update
                              1.1.0 hue-extended support
                              1.1.1 ZGPSwitch support
                              1.1.2 bekannte push calls ignorieren um weniger log zu erzeugen
                              1.1.3 Zone support (only on)

                              /**
                              * Version: 1.1.3 (HUE + HUE-EXTENDED)
                              * Anleitung: 
                              *  - npm-Modul im Javascript-Adapter hinzufügen (Adaptereinstellung): hue-push-client 
                              *  - IP: IP der Bridge eintragen
                              *  - TOKEN: gültigen User für die Bridge eintragen (z.B. aus der Hue Adapter Konfiguration)
                              *  - INSTANCE: korrekte Instanz eingeben, meist hue.0 oder hue-extended.0
                              **/
                              const IP = '<bridge ip>';
                              const TOKEN = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
                              const INSTANCE = 'hue.0';
                              
                              /**
                              * DO NOT EDIT BELOW
                              **/
                              const UPDATEMAP_HUE = {
                                  //lights
                                  'lights.status.status': {stateName: 'reachable', convert: (val) => {return val === 'connected' ? true : false;}, validTypes: ['Extended color light', 'Color temperature light', 'Dimmable light', 'On/Off plug-in unit'], after: (stateId, value) => {updateHueState(stateId.substring(0, stateId.lastIndexOf('.'))  + '.on', value)}},
                                  'lights.on.on': {stateName: 'on', validTypes: ['Extended color light', 'Color temperature light', 'Dimmable light', 'On/Off plug-in unit']},
                                  'lights.dimming.brightness': {stateName: 'level', convert: (val) => {return Math.ceil(val)}, validTypes: ['Extended color light', 'Color temperature light', 'Dimmable light'], after: (stateId, value) => {updateRGBHue(stateId.substring(0, stateId.lastIndexOf('.')))}},
                                  'lights.color_temperature.mirek': {stateName: 'ct', convert: (val) => {return Math.round(1000000/val)}, validTypes: ['Extended color light', 'Color temperature light']},
                                  'lights.color.xy': {stateName: 'xy', convert: (val) => {return val.x + ',' + val.y}, validTypes: ['Extended color light'], after: (stateId, value) => {updateRGBHue(stateId.substring(0, stateId.lastIndexOf('.')))}},
                              
                                  //groups
                                  'groups.on.on': {stateName: 'on', validTypes: ['Room', 'LightGroup', 'Zone']},
                              
                                  //sensors
                                  'sensors.motion.motion': {stateName: 'presence', validTypes: ['ZLLPresence']},
                                  'sensors.light.light_level':  {stateName: 'lightlevel', convert: (val) => {return Math.round(val)}, validTypes: ['ZLLLightLevel']},
                                  'sensors.temperature.temperature': {stateName: 'temperature', convert: (val) => {return Number.parseFloat(val.toPrecision(4))}, validTypes: ['ZLLTemperature']},
                                  'sensors.power_state.battery_level': {stateName: 'battery', convert: (val) => {return Math.round(val)}, validTypes: ['ZLLPresence', 'ZLLLightLevel', 'ZLLTemperature', 'ZLLSwitch']},
                                  //buttons
                                  'sensors.button.last_event': {stateName: 'buttonevent', convert: (val) => {return ((UUIDs[this.idv2] && UUIDs[this.idv2].metadata) ? UUIDs[this.idv2].metadata.control_id : 0) * 1000 + (val === 'repeat' ? 1 : 0) + (val === 'short_release' ? 2 : 0) + (val === 'long_release' ? 3 : 0)}, validTypes: ['ZLLSwitch', 'ZGPSwitch']},
                              
                                  //ignore
                                  'lights.owner.rid':{},
                                  'lights.owner.rtype':{},
                                  'sensors.owner.rid':{},
                                  'sensors.owner.rtype':{},
                                  'sensors.power_state.battery_state': {},
                              };
                              
                              const UPDATEMAP_HUE_EXTENDED = {
                                  //lights
                                  'lights.status.status': {stateName: 'state.reachable', convert: (val) => {return val === 'connected' ? true : false;}, validTypes: ['Extended color light', 'Color temperature light', 'Dimmable light', 'On/Off plug-in unit']},
                                  'lights.on.on': {stateName: 'action.on', validTypes: ['Extended color light', 'Color temperature light', 'Dimmable light', 'On/Off plug-in unit']},  
                                  'lights.dimming.brightness': {stateName: 'action.level', convert: (val) => {return Math.ceil(val)}, validTypes: ['Extended color light', 'Color temperature light', 'Dimmable light'], after: (stateId, value) => {updateRGBHueExtended(stateId.substring(0, stateId.lastIndexOf('.')))}},
                                  'lights.color_temperature.mirek': {stateName: 'action.colorTemperature', convert: (val) => {return Math.round(1000000/val)}, validTypes: ['Extended color light', 'Color temperature light']},
                                  'lights.color.xy': {stateName: 'action.xy', convert: (val) => {return val.x + ',' + val.y}, validTypes: ['Extended color light'], after: (stateId, value) => {updateRGBHueExtended(stateId.substring(0, stateId.lastIndexOf('.')))}},
                                
                                  //groups
                                  'groups.on.on': {stateName: 'state.any_on', validTypes: ['Room', 'LightGroup', 'Zone']},
                              
                                  //sensors
                                  'sensors.motion.motion': {stateName: 'state.presence', convert: (val) => {return val.toString()}, validTypes: ['ZLLPresence']},
                                  'sensors.light.light_level':  {stateName: 'state.lightlevel', convert: (val) => {return Math.round(val).toString()}, validTypes: ['ZLLLightLevel']},
                                  'sensors.temperature.temperature': {stateName: 'state.temperature', convert: (val) => {return Number.parseFloat(val.toPrecision(4))}, validTypes: ['ZLLTemperature']},
                                  'sensors.power_state.battery_level': {stateName: 'config.battery', convert: (val) => {return Math.round(val)}, validTypes: ['ZLLPresence', 'ZLLLightLevel', 'ZLLTemperature', 'ZLLSwitch']},
                                  //buttons
                                  'sensors.button.last_event': {stateName: 'state.buttonevent', convert: (val) => {return ((UUIDs[this.idv2] && UUIDs[this.idv2].metadata) ? UUIDs[this.idv2].metadata.control_id : 0) * 1000 + (val === 'short_release' ? 2 : 0) + (val === 'long_release' ? 3 : 0)}, validTypes: ['ZLLSwitch', 'ZGPSwitch']},
                              
                                  //ignore
                                  'lights.owner.rid':{},
                                  'lights.owner.rtype':{},
                                  'sensors.owner.rid':{},
                                  'sensors.owner.rtype':{},
                                  'sensors.power_state.battery_state': {},
                              };
                              
                              //select UPDATEMAP for hue or hue-extended
                              const UPDATEMAP = INSTANCE.toLowerCase().includes('extended') ? UPDATEMAP_HUE_EXTENDED : UPDATEMAP_HUE;
                              const findState = INSTANCE.toLowerCase().includes('extended') ? findStateHueExtended : findStateHue;
                              
                              //connect to event stream
                              const HuePushClient = require('hue-push-client');
                              const client = new HuePushClient({ip: IP, user: TOKEN});
                              client.addEventListener('open', function () {
                                  log('connected');
                              });
                              client.addEventListener('close', function () {
                                  log('disconnected', 'warn');
                              });
                              client.addEventListener('error', function (e) {
                                  log('connection error: ' + e.message, 'warn');
                              });
                              client.addEventListener('message', function (packet) {
                                  parsePacket(packet);
                              });
                              
                              //get resouce ids (required to identify buttons)
                              let UUIDs = {};
                              async function getUUIDs() {
                                  try {
                                      UUIDs = await client.uuids();
                                  } catch (e) {
                                      log(e, 'warn');
                                  }
                              };
                              getUUIDs();
                              
                              
                              // close connection if script is stopped
                              onStop(function (callback) {
                                  client.close();
                                  callback();
                              }, 2000);
                              
                              function parsePacket (packet) {
                                  log('RECEIVED PACKET: ' + "\n" + JSON.stringify(packet), 'debug');
                                  try {
                                      if (!packet.data) {
                                          log('packet has no data: ' + JSON.stringify(packet), 'warn');
                                          return;
                                      }
                                      for (let message of JSON.parse(packet.data)) {
                                          if (message.type !== 'update') {
                                              log ('unknown message type: ' + JSON.stringify(message), 'warn');
                                              continue;
                                          }
                                          if (typeof message.data !== 'object') {
                                              log ('message contains no data: '  + JSON.stringify(message), 'warn');
                                              continue;
                                          }
                                          for (let update of message.data) {
                                              parseUpdate(update);
                                          }
                                      }
                                  } catch (e) {
                                      log('could not read packet: ' + JSON.stringify(packet), 'warn');
                                      log(e.message, 'warn');
                                      return;
                                  }
                              }
                              
                              function parseUpdate(update) {
                                  log('PARSING UPDATE: ' + "\n" + JSON.stringify(update), 'debug');
                              
                                  if (!update.id_v1) return;
                                  const [resource, idv1] = update.id_v1.split('/').filter(Boolean);
                                  const idv2 = update.id;
                              
                                  //remove id, id_v1, type
                                  delete  update.id;
                                  delete  update.id_v1;
                                  delete  update.type;
                              
                                  //status to object as other updates are objects
                                  if (update.status) {
                                      update.status = {status: update.status};
                                  }
                              
                                  processUpdate(resource, idv1, idv2, update);
                              }
                              
                              let IdCache = [];
                              function processUpdate(resource, resourceId, idv2, data) {
                                  this.resource = resource;
                                  this.resourceId = resourceId;
                                  this.idv2 = idv2;
                                  this.data = data;
                              
                                  log('PROCESSING UPDATE: ' + 'resource ' + resource + "\n" + JSON.stringify(data), 'debug');
                                  //check for values to data
                                  for (let action in data) {
                                      if (typeof data[action] !== 'object') {continue;}
                              
                                      //check if update invalid and delete _valid entries
                                      for (let endpoint in data[action]) {
                                          if (endpoint.substr(-6) === '_valid') {
                                              if (!data[action][endpoint]) {
                                                  log('skipping invalid value' + resource + '.' + action + '.' + endpoint, 'debug');
                                                  return;
                                              } else {
                                                  delete data[action][endpoint];
                                              }
                                          } 
                                      }
                                      //find hue adapter states to update and set new values
                                      for (let endpoint in data[action]) {
                                          if (UPDATEMAP[resource + '.' + action + '.' + endpoint]) {    
                                              log('found UPDATEMAP for ' + resource + '.' + action + '.' + endpoint, 'debug');
                                              let updateValue = data[action][endpoint];
                                              //convert value?
                                              if (typeof UPDATEMAP[resource + '.' + action + '.' + endpoint].convert === 'function') {
                                                  let updateValueOld = updateValue;
                                                  updateValue = UPDATEMAP[resource + '.' + action + '.' + endpoint].convert.call(this, updateValue);
                                                  log('converted ' + resource + '.' + action + '.' + endpoint + ' from ' + updateValueOld + ' to ' + updateValue, 'debug');
                                              }
                                              let stateName = UPDATEMAP[resource + '.' + action + '.' + endpoint].stateName;
                                              
                                              //check if state id is cached
                                              if (!IdCache[resource + '.' + resourceId + '.' + stateName]) {
                                                  findState(resource, resourceId, stateName, action, endpoint, () => {
                                                      updateHueState(IdCache[resource + '.' + resourceId + '.' + stateName], updateValue, UPDATEMAP[resource + '.' + action + '.' + endpoint].after);
                                                  });
                                              } else {
                                                  log('found cache entry for ' + resource + '.' + resourceId + '.' + stateName + ': ' + IdCache[resource + '.' + resourceId + '.' + stateName], 'debug');
                                                  updateHueState(IdCache[resource + '.' + resourceId + '.' + stateName], updateValue, UPDATEMAP[resource + '.' + action + '.' + endpoint].after);
                                              }
                              
                                          } else {
                                              log('missing update instructions for ' + resource + '.' + action + '.' + endpoint);
                                              log(JSON.stringify(data));
                                          }
                                      }
                                  }
                              }
                              
                              async function findStateHue(resource, resourceId, stateName, action, endpoint, callback) {
                                  log('searching for object with id ' + resourceId + ' and stateName ' + stateName, 'debug');
                                  $(INSTANCE + '.*' + '.' + stateName).each(function (stateId, i) {  //better way to find matching objects?
                                      getObject(stateId, (err, obj) => {
                                          if (!err) {
                                              if (obj.native && obj.native.id && obj.native.id == resourceId) {
                                                  log('found ' + stateId + ', checking parent for matching type...', 'debug');
                                                  //get parent object and check type
                                                  let parentId = stateId.substring(0, stateId.lastIndexOf('.'));
                                                  getObject(parentId, (err2, obj2) => {
                                                      if (!err2) {
                                                          if (obj2.native && obj2.native.type && UPDATEMAP[resource + '.' + action + '.' + endpoint].validTypes.indexOf(obj2.native.type) !== -1 && !IdCache[resource + '.' + resourceId + '.' + stateName]) {
                                                              log('found matching type for ' + parentId + ': ' + obj2.native.type, 'debug');
                                                              log('save cache entry "' + resource + '.' + resourceId + '.' + stateName + '":' + stateId, 'debug');
                                                              IdCache[resource + '.' + resourceId + '.' + stateName] = stateId;
                                                              callback();
                                                          }
                                                      } else {
                                                          log('could not find obj: ' + stateId, 'warn');
                                                      }
                                                  });    
                                              }
                                          } else {
                                              log('could not find obj: ' + stateId, 'warn');
                                          }
                                      });
                                  });
                              }
                              
                              async function findStateHueExtended(resource, resourceId, stateName, action, endpoint, callback) {
                                  log('searching for object with id ' + resourceId + ' and stateName ' + stateName, 'debug');
                                  $(INSTANCE + '.' + resource + '.*' + '.uid').each(async (stateId, i) => {  //better way to find matching objects?
                                      const deviceId = await getStateAsync(stateId);
                                      //check if device id matches
                                      if (deviceId.val !== resourceId) {
                                          return;
                                      }
                                      const device = stateId.substr(0,stateId.length-4);
                                      //make sure final object exists
                                      const stateExists = await existsObjectAsync(device + '.' + stateName);
                                      if (!stateExists) {
                                          return;
                                      }
                                      //check if type is valid and save cache entry
                                      const deviceType = await getStateAsync(device + '.type');
                                      if (UPDATEMAP[resource + '.' + action + '.' + endpoint].validTypes.indexOf(deviceType.val) !== -1 && !IdCache[resource + '.' + resourceId + '.' + stateName]) {
                                          log('found matching type for ' + resourceId + ': ' + deviceType.val, 'debug');
                                          log('save cache entry "' + resource + '.' + resourceId + '.' + stateName + '":' + device + '.' + stateName, 'debug');
                                          IdCache[resource + '.' + resourceId + '.' + stateName] = device + '.' + stateName;
                                          callback();                    
                                      }
                                  });
                              }
                              
                              function updateHueState(stateId, value, after) {
                                  log('set ' + stateId + ' to ' + value + ' (' + typeof value + ')', 'debug');
                                  setStateDelayed(stateId, value, true, 50, true, () => {
                                      if (typeof after === 'function') {
                                          log ('running  function after change of ' + stateId, 'debug');
                                          after(stateId, value);
                                      }
                                  });
                              } 
                              
                              
                              //helpers
                              async function updateRGBHue(stateId) {
                                  let xyState = await getStateAsync(stateId + '.xy');
                                  if (!xyState) return;
                                  let xy = xyState.val.replace('[', '').replace(']', '').split(',');
                                  let levelState = await getStateAsync(stateId + '.level');
                                  let level = levelState.val / 100;
                                  //let onState = await getStateAsync(stateId + '.on');
                                  //if (onState.val === false) level = 0;
                                  let rgb = HelperXYBtoRGB(xy[0], xy[1], level);
                              
                                  updateHueState(stateId + '.r', Math.round(rgb.Red * 255));
                                  updateHueState(stateId + '.g', Math.round(rgb.Green * 255));
                                  updateHueState(stateId + '.b', Math.round(rgb.Blue * 255));
                              }
                              
                              async function updateRGBHueExtended(stateId) {
                                  let xyState = await getStateAsync(stateId + '.xy');
                                  if (!xyState) return;
                                  let xy = xyState.val.replace('[', '').replace(']', '').split(',');
                                  let levelState = await getStateAsync(stateId + '.level');
                                  let level = levelState.val / 100;
                                  let rgb = HelperXYBtoRGB(xy[0], xy[1], level);
                                  updateHueState(stateId + '.rgb', Math.round(rgb.Red * 255) + ',' + Math.round(rgb.Green * 255) + ',' + Math.round(rgb.Blue * 255));
                              }
                              
                              function HelperXYBtoRGB (x, y, Brightness) { // Source: https://github.com/PhilipsHue/PhilipsHueSDK-iOS-OSX/blob/master/ApplicationDesignNotes/RGB%20to%20xy%20Color%20conversion.md
                                  if (Brightness <= 0) {
                                      return {Red: 0, Green: 0, Blue: 0};
                                  }
                                  Brightness = Brightness || 1.0; // Default full brightness
                                  const z = 1.0 - x - y;
                                  const Y = Brightness;
                                  const X = (Y / y) * x;
                                  const Z = (Y / y) * z;
                                  // XYZ to RGB [M]-1 for Wide RGB D65, http://www.developers.meethue.com/documentation/color-conversions-rgb-xy
                                  let Red = X * 1.656492 - Y * 0.354851 - Z * 0.255038;
                                  let Green = -X * 0.707196 + Y * 1.655397 + Z * 0.036152;
                                  let Blue = X * 0.051713 - Y * 0.121364 + Z * 1.011530;
                                  // Limit RGB on [0..1]
                                  if (Red > Blue && Red > Green && Red > 1.0) { // Red is too big
                                      Green = Green / Red;
                                      Blue = Blue / Red;
                                      Red = 1.0;
                                  }
                                  if (Red < 0) {
                                      Red = 0;
                                  }
                                  if (Green > Blue && Green > Red && Green > 1.0) { // Green is too big
                                      Red = Red / Green;
                                      Blue = Blue / Green;
                                      Green = 1.0;
                                  }
                                  if (Green < 0) {
                                      Green = 0;
                                  }
                                  if (Blue > Red && Blue > Green && Blue > 1.0) { // Blue is too big
                                      Red = Red / Blue;
                                      Green = Green / Blue;
                                      Blue = 1.0;
                                  }
                                  if (Blue < 0) {
                                      Blue = 0;
                                  }
                                  // Apply reverse gamma correction
                                  if (Red <= 0.0031308) {
                                      Red = Red * 12.92;
                                  } else {
                                      Red = 1.055 * Math.pow(Red, (1.0 / 2.4)) - 0.055;
                                  }
                                  if (Green <= 0.0031308) {
                                      Green = Green * 12.92;
                                  } else {
                                      Green = 1.055 * Math.pow(Green, (1.0 / 2.4)) - 0.055;
                                  }
                                  if (Blue <= 0.0031308) {
                                      Blue = Blue * 12.92;
                                  } else {
                                      Blue = 1.055 * Math.pow(Blue, (1.0 / 2.4)) - 0.055;
                                  }
                                  // Limit RGB on [0..1]
                                  if (Red > Blue && Red > Green && Red > 1.0) { // Red is too big
                                      Green = Green / Red;
                                      Blue = Blue / Red;
                                      Red = 1.0;
                                  }
                                  if (Red < 0) {
                                      Red = 0;
                                  }
                                  if (Green > Blue && Green > Red && Green > 1.0) { // Green is too big
                                      Red = Red / Green;
                                      Blue = Blue / Green;
                                      Green = 1.0;
                                  }
                                  if (Green < 0) {
                                      Green = 0;
                                  }
                                  if (Blue > Red && Blue > Green && Blue > 1.0) { // Blue is too big
                                      Red = Red / Blue;
                                      Green = Green / Blue;
                                      Blue = 1.0;
                                  }
                                  if (Blue < 0) {
                                      Blue = 0;
                                  }
                                  return {Red: Red, Green: Green, Blue: Blue};
                              };
                              
                              
                              S Offline
                              S Offline
                              senger1985
                              schrieb am zuletzt editiert von senger1985
                              #42

                              @pman erstmal vielen Dank, für das Script.
                              Es funktioniert super.

                              Nachdem ich heute einen zweiten Smart Button an meine Bridge angelernt habe und diesen in ein Script einbinden wollte, ist mir etwas aufgefallen und ich weiß nicht, woran es liegt.

                              Ich nutze eine zweite Instanz, des HUE-Adapters und habe diese dann deaktiviert, weil sonst die Aktionen, die über den Button ausgeführt werden sollen, doppelt ausgeführt werden.

                              Funktioniert auch wunderbar, bis auf, dass bei dem "alten" Button, mir der Wert "buttonevent", im tausender Bereich angegeben wird, bei dem "neuen" Button jedoch einstellig.
                              Es sind, wie oben schon geschrieben, beides Smart Button(dieser kleine runde Button).

                              EDIT: Hat sich erledigt.
                              Habe, wie oben empfohlen, das Polling, der zweiten instanz auf 0 gesetzt und lasse die Instanz jetzt aktiv und jetzt werden mir die Werte wie gewohnt, im tausender Bereich angezeigt und meine Scripte laufen, wie gewünscht.

                              1 Antwort Letzte Antwort
                              0
                              • P Pman

                                Bisher hat Philips die Push API nicht offiziell released und sie wird noch nicht vom Hue-Adapter unterstützt. Dieses Skript baut eine Verbindung zur Bridge auf und aktualisiert entsprechende States "live", ich empfehle das polling im Adapter zu deaktivieren. Welche Datenpunkte aktualisiert werden kann man in der UPDATEMAP nachlesen.
                                Weitere Hinweise siehe Skript.
                                Update
                                1.1.0 hue-extended support
                                1.1.1 ZGPSwitch support
                                1.1.2 bekannte push calls ignorieren um weniger log zu erzeugen
                                1.1.3 Zone support (only on)

                                /**
                                * Version: 1.1.3 (HUE + HUE-EXTENDED)
                                * Anleitung: 
                                *  - npm-Modul im Javascript-Adapter hinzufügen (Adaptereinstellung): hue-push-client 
                                *  - IP: IP der Bridge eintragen
                                *  - TOKEN: gültigen User für die Bridge eintragen (z.B. aus der Hue Adapter Konfiguration)
                                *  - INSTANCE: korrekte Instanz eingeben, meist hue.0 oder hue-extended.0
                                **/
                                const IP = '<bridge ip>';
                                const TOKEN = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
                                const INSTANCE = 'hue.0';
                                
                                /**
                                * DO NOT EDIT BELOW
                                **/
                                const UPDATEMAP_HUE = {
                                    //lights
                                    'lights.status.status': {stateName: 'reachable', convert: (val) => {return val === 'connected' ? true : false;}, validTypes: ['Extended color light', 'Color temperature light', 'Dimmable light', 'On/Off plug-in unit'], after: (stateId, value) => {updateHueState(stateId.substring(0, stateId.lastIndexOf('.'))  + '.on', value)}},
                                    'lights.on.on': {stateName: 'on', validTypes: ['Extended color light', 'Color temperature light', 'Dimmable light', 'On/Off plug-in unit']},
                                    'lights.dimming.brightness': {stateName: 'level', convert: (val) => {return Math.ceil(val)}, validTypes: ['Extended color light', 'Color temperature light', 'Dimmable light'], after: (stateId, value) => {updateRGBHue(stateId.substring(0, stateId.lastIndexOf('.')))}},
                                    'lights.color_temperature.mirek': {stateName: 'ct', convert: (val) => {return Math.round(1000000/val)}, validTypes: ['Extended color light', 'Color temperature light']},
                                    'lights.color.xy': {stateName: 'xy', convert: (val) => {return val.x + ',' + val.y}, validTypes: ['Extended color light'], after: (stateId, value) => {updateRGBHue(stateId.substring(0, stateId.lastIndexOf('.')))}},
                                
                                    //groups
                                    'groups.on.on': {stateName: 'on', validTypes: ['Room', 'LightGroup', 'Zone']},
                                
                                    //sensors
                                    'sensors.motion.motion': {stateName: 'presence', validTypes: ['ZLLPresence']},
                                    'sensors.light.light_level':  {stateName: 'lightlevel', convert: (val) => {return Math.round(val)}, validTypes: ['ZLLLightLevel']},
                                    'sensors.temperature.temperature': {stateName: 'temperature', convert: (val) => {return Number.parseFloat(val.toPrecision(4))}, validTypes: ['ZLLTemperature']},
                                    'sensors.power_state.battery_level': {stateName: 'battery', convert: (val) => {return Math.round(val)}, validTypes: ['ZLLPresence', 'ZLLLightLevel', 'ZLLTemperature', 'ZLLSwitch']},
                                    //buttons
                                    'sensors.button.last_event': {stateName: 'buttonevent', convert: (val) => {return ((UUIDs[this.idv2] && UUIDs[this.idv2].metadata) ? UUIDs[this.idv2].metadata.control_id : 0) * 1000 + (val === 'repeat' ? 1 : 0) + (val === 'short_release' ? 2 : 0) + (val === 'long_release' ? 3 : 0)}, validTypes: ['ZLLSwitch', 'ZGPSwitch']},
                                
                                    //ignore
                                    'lights.owner.rid':{},
                                    'lights.owner.rtype':{},
                                    'sensors.owner.rid':{},
                                    'sensors.owner.rtype':{},
                                    'sensors.power_state.battery_state': {},
                                };
                                
                                const UPDATEMAP_HUE_EXTENDED = {
                                    //lights
                                    'lights.status.status': {stateName: 'state.reachable', convert: (val) => {return val === 'connected' ? true : false;}, validTypes: ['Extended color light', 'Color temperature light', 'Dimmable light', 'On/Off plug-in unit']},
                                    'lights.on.on': {stateName: 'action.on', validTypes: ['Extended color light', 'Color temperature light', 'Dimmable light', 'On/Off plug-in unit']},  
                                    'lights.dimming.brightness': {stateName: 'action.level', convert: (val) => {return Math.ceil(val)}, validTypes: ['Extended color light', 'Color temperature light', 'Dimmable light'], after: (stateId, value) => {updateRGBHueExtended(stateId.substring(0, stateId.lastIndexOf('.')))}},
                                    'lights.color_temperature.mirek': {stateName: 'action.colorTemperature', convert: (val) => {return Math.round(1000000/val)}, validTypes: ['Extended color light', 'Color temperature light']},
                                    'lights.color.xy': {stateName: 'action.xy', convert: (val) => {return val.x + ',' + val.y}, validTypes: ['Extended color light'], after: (stateId, value) => {updateRGBHueExtended(stateId.substring(0, stateId.lastIndexOf('.')))}},
                                  
                                    //groups
                                    'groups.on.on': {stateName: 'state.any_on', validTypes: ['Room', 'LightGroup', 'Zone']},
                                
                                    //sensors
                                    'sensors.motion.motion': {stateName: 'state.presence', convert: (val) => {return val.toString()}, validTypes: ['ZLLPresence']},
                                    'sensors.light.light_level':  {stateName: 'state.lightlevel', convert: (val) => {return Math.round(val).toString()}, validTypes: ['ZLLLightLevel']},
                                    'sensors.temperature.temperature': {stateName: 'state.temperature', convert: (val) => {return Number.parseFloat(val.toPrecision(4))}, validTypes: ['ZLLTemperature']},
                                    'sensors.power_state.battery_level': {stateName: 'config.battery', convert: (val) => {return Math.round(val)}, validTypes: ['ZLLPresence', 'ZLLLightLevel', 'ZLLTemperature', 'ZLLSwitch']},
                                    //buttons
                                    'sensors.button.last_event': {stateName: 'state.buttonevent', convert: (val) => {return ((UUIDs[this.idv2] && UUIDs[this.idv2].metadata) ? UUIDs[this.idv2].metadata.control_id : 0) * 1000 + (val === 'short_release' ? 2 : 0) + (val === 'long_release' ? 3 : 0)}, validTypes: ['ZLLSwitch', 'ZGPSwitch']},
                                
                                    //ignore
                                    'lights.owner.rid':{},
                                    'lights.owner.rtype':{},
                                    'sensors.owner.rid':{},
                                    'sensors.owner.rtype':{},
                                    'sensors.power_state.battery_state': {},
                                };
                                
                                //select UPDATEMAP for hue or hue-extended
                                const UPDATEMAP = INSTANCE.toLowerCase().includes('extended') ? UPDATEMAP_HUE_EXTENDED : UPDATEMAP_HUE;
                                const findState = INSTANCE.toLowerCase().includes('extended') ? findStateHueExtended : findStateHue;
                                
                                //connect to event stream
                                const HuePushClient = require('hue-push-client');
                                const client = new HuePushClient({ip: IP, user: TOKEN});
                                client.addEventListener('open', function () {
                                    log('connected');
                                });
                                client.addEventListener('close', function () {
                                    log('disconnected', 'warn');
                                });
                                client.addEventListener('error', function (e) {
                                    log('connection error: ' + e.message, 'warn');
                                });
                                client.addEventListener('message', function (packet) {
                                    parsePacket(packet);
                                });
                                
                                //get resouce ids (required to identify buttons)
                                let UUIDs = {};
                                async function getUUIDs() {
                                    try {
                                        UUIDs = await client.uuids();
                                    } catch (e) {
                                        log(e, 'warn');
                                    }
                                };
                                getUUIDs();
                                
                                
                                // close connection if script is stopped
                                onStop(function (callback) {
                                    client.close();
                                    callback();
                                }, 2000);
                                
                                function parsePacket (packet) {
                                    log('RECEIVED PACKET: ' + "\n" + JSON.stringify(packet), 'debug');
                                    try {
                                        if (!packet.data) {
                                            log('packet has no data: ' + JSON.stringify(packet), 'warn');
                                            return;
                                        }
                                        for (let message of JSON.parse(packet.data)) {
                                            if (message.type !== 'update') {
                                                log ('unknown message type: ' + JSON.stringify(message), 'warn');
                                                continue;
                                            }
                                            if (typeof message.data !== 'object') {
                                                log ('message contains no data: '  + JSON.stringify(message), 'warn');
                                                continue;
                                            }
                                            for (let update of message.data) {
                                                parseUpdate(update);
                                            }
                                        }
                                    } catch (e) {
                                        log('could not read packet: ' + JSON.stringify(packet), 'warn');
                                        log(e.message, 'warn');
                                        return;
                                    }
                                }
                                
                                function parseUpdate(update) {
                                    log('PARSING UPDATE: ' + "\n" + JSON.stringify(update), 'debug');
                                
                                    if (!update.id_v1) return;
                                    const [resource, idv1] = update.id_v1.split('/').filter(Boolean);
                                    const idv2 = update.id;
                                
                                    //remove id, id_v1, type
                                    delete  update.id;
                                    delete  update.id_v1;
                                    delete  update.type;
                                
                                    //status to object as other updates are objects
                                    if (update.status) {
                                        update.status = {status: update.status};
                                    }
                                
                                    processUpdate(resource, idv1, idv2, update);
                                }
                                
                                let IdCache = [];
                                function processUpdate(resource, resourceId, idv2, data) {
                                    this.resource = resource;
                                    this.resourceId = resourceId;
                                    this.idv2 = idv2;
                                    this.data = data;
                                
                                    log('PROCESSING UPDATE: ' + 'resource ' + resource + "\n" + JSON.stringify(data), 'debug');
                                    //check for values to data
                                    for (let action in data) {
                                        if (typeof data[action] !== 'object') {continue;}
                                
                                        //check if update invalid and delete _valid entries
                                        for (let endpoint in data[action]) {
                                            if (endpoint.substr(-6) === '_valid') {
                                                if (!data[action][endpoint]) {
                                                    log('skipping invalid value' + resource + '.' + action + '.' + endpoint, 'debug');
                                                    return;
                                                } else {
                                                    delete data[action][endpoint];
                                                }
                                            } 
                                        }
                                        //find hue adapter states to update and set new values
                                        for (let endpoint in data[action]) {
                                            if (UPDATEMAP[resource + '.' + action + '.' + endpoint]) {    
                                                log('found UPDATEMAP for ' + resource + '.' + action + '.' + endpoint, 'debug');
                                                let updateValue = data[action][endpoint];
                                                //convert value?
                                                if (typeof UPDATEMAP[resource + '.' + action + '.' + endpoint].convert === 'function') {
                                                    let updateValueOld = updateValue;
                                                    updateValue = UPDATEMAP[resource + '.' + action + '.' + endpoint].convert.call(this, updateValue);
                                                    log('converted ' + resource + '.' + action + '.' + endpoint + ' from ' + updateValueOld + ' to ' + updateValue, 'debug');
                                                }
                                                let stateName = UPDATEMAP[resource + '.' + action + '.' + endpoint].stateName;
                                                
                                                //check if state id is cached
                                                if (!IdCache[resource + '.' + resourceId + '.' + stateName]) {
                                                    findState(resource, resourceId, stateName, action, endpoint, () => {
                                                        updateHueState(IdCache[resource + '.' + resourceId + '.' + stateName], updateValue, UPDATEMAP[resource + '.' + action + '.' + endpoint].after);
                                                    });
                                                } else {
                                                    log('found cache entry for ' + resource + '.' + resourceId + '.' + stateName + ': ' + IdCache[resource + '.' + resourceId + '.' + stateName], 'debug');
                                                    updateHueState(IdCache[resource + '.' + resourceId + '.' + stateName], updateValue, UPDATEMAP[resource + '.' + action + '.' + endpoint].after);
                                                }
                                
                                            } else {
                                                log('missing update instructions for ' + resource + '.' + action + '.' + endpoint);
                                                log(JSON.stringify(data));
                                            }
                                        }
                                    }
                                }
                                
                                async function findStateHue(resource, resourceId, stateName, action, endpoint, callback) {
                                    log('searching for object with id ' + resourceId + ' and stateName ' + stateName, 'debug');
                                    $(INSTANCE + '.*' + '.' + stateName).each(function (stateId, i) {  //better way to find matching objects?
                                        getObject(stateId, (err, obj) => {
                                            if (!err) {
                                                if (obj.native && obj.native.id && obj.native.id == resourceId) {
                                                    log('found ' + stateId + ', checking parent for matching type...', 'debug');
                                                    //get parent object and check type
                                                    let parentId = stateId.substring(0, stateId.lastIndexOf('.'));
                                                    getObject(parentId, (err2, obj2) => {
                                                        if (!err2) {
                                                            if (obj2.native && obj2.native.type && UPDATEMAP[resource + '.' + action + '.' + endpoint].validTypes.indexOf(obj2.native.type) !== -1 && !IdCache[resource + '.' + resourceId + '.' + stateName]) {
                                                                log('found matching type for ' + parentId + ': ' + obj2.native.type, 'debug');
                                                                log('save cache entry "' + resource + '.' + resourceId + '.' + stateName + '":' + stateId, 'debug');
                                                                IdCache[resource + '.' + resourceId + '.' + stateName] = stateId;
                                                                callback();
                                                            }
                                                        } else {
                                                            log('could not find obj: ' + stateId, 'warn');
                                                        }
                                                    });    
                                                }
                                            } else {
                                                log('could not find obj: ' + stateId, 'warn');
                                            }
                                        });
                                    });
                                }
                                
                                async function findStateHueExtended(resource, resourceId, stateName, action, endpoint, callback) {
                                    log('searching for object with id ' + resourceId + ' and stateName ' + stateName, 'debug');
                                    $(INSTANCE + '.' + resource + '.*' + '.uid').each(async (stateId, i) => {  //better way to find matching objects?
                                        const deviceId = await getStateAsync(stateId);
                                        //check if device id matches
                                        if (deviceId.val !== resourceId) {
                                            return;
                                        }
                                        const device = stateId.substr(0,stateId.length-4);
                                        //make sure final object exists
                                        const stateExists = await existsObjectAsync(device + '.' + stateName);
                                        if (!stateExists) {
                                            return;
                                        }
                                        //check if type is valid and save cache entry
                                        const deviceType = await getStateAsync(device + '.type');
                                        if (UPDATEMAP[resource + '.' + action + '.' + endpoint].validTypes.indexOf(deviceType.val) !== -1 && !IdCache[resource + '.' + resourceId + '.' + stateName]) {
                                            log('found matching type for ' + resourceId + ': ' + deviceType.val, 'debug');
                                            log('save cache entry "' + resource + '.' + resourceId + '.' + stateName + '":' + device + '.' + stateName, 'debug');
                                            IdCache[resource + '.' + resourceId + '.' + stateName] = device + '.' + stateName;
                                            callback();                    
                                        }
                                    });
                                }
                                
                                function updateHueState(stateId, value, after) {
                                    log('set ' + stateId + ' to ' + value + ' (' + typeof value + ')', 'debug');
                                    setStateDelayed(stateId, value, true, 50, true, () => {
                                        if (typeof after === 'function') {
                                            log ('running  function after change of ' + stateId, 'debug');
                                            after(stateId, value);
                                        }
                                    });
                                } 
                                
                                
                                //helpers
                                async function updateRGBHue(stateId) {
                                    let xyState = await getStateAsync(stateId + '.xy');
                                    if (!xyState) return;
                                    let xy = xyState.val.replace('[', '').replace(']', '').split(',');
                                    let levelState = await getStateAsync(stateId + '.level');
                                    let level = levelState.val / 100;
                                    //let onState = await getStateAsync(stateId + '.on');
                                    //if (onState.val === false) level = 0;
                                    let rgb = HelperXYBtoRGB(xy[0], xy[1], level);
                                
                                    updateHueState(stateId + '.r', Math.round(rgb.Red * 255));
                                    updateHueState(stateId + '.g', Math.round(rgb.Green * 255));
                                    updateHueState(stateId + '.b', Math.round(rgb.Blue * 255));
                                }
                                
                                async function updateRGBHueExtended(stateId) {
                                    let xyState = await getStateAsync(stateId + '.xy');
                                    if (!xyState) return;
                                    let xy = xyState.val.replace('[', '').replace(']', '').split(',');
                                    let levelState = await getStateAsync(stateId + '.level');
                                    let level = levelState.val / 100;
                                    let rgb = HelperXYBtoRGB(xy[0], xy[1], level);
                                    updateHueState(stateId + '.rgb', Math.round(rgb.Red * 255) + ',' + Math.round(rgb.Green * 255) + ',' + Math.round(rgb.Blue * 255));
                                }
                                
                                function HelperXYBtoRGB (x, y, Brightness) { // Source: https://github.com/PhilipsHue/PhilipsHueSDK-iOS-OSX/blob/master/ApplicationDesignNotes/RGB%20to%20xy%20Color%20conversion.md
                                    if (Brightness <= 0) {
                                        return {Red: 0, Green: 0, Blue: 0};
                                    }
                                    Brightness = Brightness || 1.0; // Default full brightness
                                    const z = 1.0 - x - y;
                                    const Y = Brightness;
                                    const X = (Y / y) * x;
                                    const Z = (Y / y) * z;
                                    // XYZ to RGB [M]-1 for Wide RGB D65, http://www.developers.meethue.com/documentation/color-conversions-rgb-xy
                                    let Red = X * 1.656492 - Y * 0.354851 - Z * 0.255038;
                                    let Green = -X * 0.707196 + Y * 1.655397 + Z * 0.036152;
                                    let Blue = X * 0.051713 - Y * 0.121364 + Z * 1.011530;
                                    // Limit RGB on [0..1]
                                    if (Red > Blue && Red > Green && Red > 1.0) { // Red is too big
                                        Green = Green / Red;
                                        Blue = Blue / Red;
                                        Red = 1.0;
                                    }
                                    if (Red < 0) {
                                        Red = 0;
                                    }
                                    if (Green > Blue && Green > Red && Green > 1.0) { // Green is too big
                                        Red = Red / Green;
                                        Blue = Blue / Green;
                                        Green = 1.0;
                                    }
                                    if (Green < 0) {
                                        Green = 0;
                                    }
                                    if (Blue > Red && Blue > Green && Blue > 1.0) { // Blue is too big
                                        Red = Red / Blue;
                                        Green = Green / Blue;
                                        Blue = 1.0;
                                    }
                                    if (Blue < 0) {
                                        Blue = 0;
                                    }
                                    // Apply reverse gamma correction
                                    if (Red <= 0.0031308) {
                                        Red = Red * 12.92;
                                    } else {
                                        Red = 1.055 * Math.pow(Red, (1.0 / 2.4)) - 0.055;
                                    }
                                    if (Green <= 0.0031308) {
                                        Green = Green * 12.92;
                                    } else {
                                        Green = 1.055 * Math.pow(Green, (1.0 / 2.4)) - 0.055;
                                    }
                                    if (Blue <= 0.0031308) {
                                        Blue = Blue * 12.92;
                                    } else {
                                        Blue = 1.055 * Math.pow(Blue, (1.0 / 2.4)) - 0.055;
                                    }
                                    // Limit RGB on [0..1]
                                    if (Red > Blue && Red > Green && Red > 1.0) { // Red is too big
                                        Green = Green / Red;
                                        Blue = Blue / Red;
                                        Red = 1.0;
                                    }
                                    if (Red < 0) {
                                        Red = 0;
                                    }
                                    if (Green > Blue && Green > Red && Green > 1.0) { // Green is too big
                                        Red = Red / Green;
                                        Blue = Blue / Green;
                                        Green = 1.0;
                                    }
                                    if (Green < 0) {
                                        Green = 0;
                                    }
                                    if (Blue > Red && Blue > Green && Blue > 1.0) { // Blue is too big
                                        Red = Red / Blue;
                                        Green = Green / Blue;
                                        Blue = 1.0;
                                    }
                                    if (Blue < 0) {
                                        Blue = 0;
                                    }
                                    return {Red: Red, Green: Green, Blue: Blue};
                                };
                                
                                
                                dslraserD Offline
                                dslraserD Offline
                                dslraser
                                Forum Testing Most Active
                                schrieb am zuletzt editiert von
                                #43

                                @pman
                                Kam heute per E-Mail. Ist das jetzt die neue API ?

                                @foxriver76
                                vielleicht auch für den HUE Adapter ?

                                B881A707-8EDB-4084-B7B7-271C7FD0BCF8.jpeg

                                M 1 Antwort Letzte Antwort
                                0
                                • dslraserD dslraser

                                  @pman
                                  Kam heute per E-Mail. Ist das jetzt die neue API ?

                                  @foxriver76
                                  vielleicht auch für den HUE Adapter ?

                                  B881A707-8EDB-4084-B7B7-271C7FD0BCF8.jpeg

                                  M Online
                                  M Online
                                  MCU
                                  schrieb am zuletzt editiert von MCU
                                  #44

                                  @pman Nach Update der HUE App kommen Meldungen im Log. Was muss man im Script umstellen? Danke.

                                  2021-11-20 18:27:27.915	info	script.js.HUE-EXTENDED.HUE-NEWAPI: {"motion":{"motion":true},"owner":{"rid":"f79557d0-3ec2-4658-8d11-3a6522e9cc29","rtype":"device"}}
                                  2021-11-20 18:27:27.915	info	script.js.HUE-EXTENDED.HUE-NEWAPI: missing update instructions for sensors.owner.rid
                                  2021-11-20 18:27:26.910	info	script.js.HUE-EXTENDED.HUE-NEWAPI: {"motion":{"motion":false},"owner":{"rid":"f79557d0-3ec2-4658-8d11-3a6522e9cc29","rtype":"device"}}
                                  2021-11-20 18:27:26.910	info	script.js.HUE-EXTENDED.HUE-NEWAPI: missing update instructions for sensors.owner.rtype
                                  

                                  Habe erstmal Leerobjekte ergänzt.

                                      Lights
                                      'lights.owner.rid':{},
                                      'lights.owner.rtype':{},
                                  
                                      Sensoren
                                      'sensors.owner.rid':{},
                                      'sensors.owner.rtype':{},
                                  

                                  NUC i7 64GB mit Proxmox ---- Jarvis Infos Aktualisierungen der Doku auf Instagram verfolgen -> mcuiobroker Instagram
                                  Wenn Euch mein Vorschlag geholfen hat, bitte rechts "^" klicken.

                                  F P 2 Antworten Letzte Antwort
                                  0
                                  • M MCU

                                    @pman Nach Update der HUE App kommen Meldungen im Log. Was muss man im Script umstellen? Danke.

                                    2021-11-20 18:27:27.915	info	script.js.HUE-EXTENDED.HUE-NEWAPI: {"motion":{"motion":true},"owner":{"rid":"f79557d0-3ec2-4658-8d11-3a6522e9cc29","rtype":"device"}}
                                    2021-11-20 18:27:27.915	info	script.js.HUE-EXTENDED.HUE-NEWAPI: missing update instructions for sensors.owner.rid
                                    2021-11-20 18:27:26.910	info	script.js.HUE-EXTENDED.HUE-NEWAPI: {"motion":{"motion":false},"owner":{"rid":"f79557d0-3ec2-4658-8d11-3a6522e9cc29","rtype":"device"}}
                                    2021-11-20 18:27:26.910	info	script.js.HUE-EXTENDED.HUE-NEWAPI: missing update instructions for sensors.owner.rtype
                                    

                                    Habe erstmal Leerobjekte ergänzt.

                                        Lights
                                        'lights.owner.rid':{},
                                        'lights.owner.rtype':{},
                                    
                                        Sensoren
                                        'sensors.owner.rid':{},
                                        'sensors.owner.rtype':{},
                                    
                                    F Offline
                                    F Offline
                                    Fuxsism
                                    schrieb am zuletzt editiert von
                                    #45

                                    Hallo Zusammen,

                                    steige hier auch einmal mit ein weil es so klingt als wäre dieses Skirpt genau das was ich brauche.
                                    Ich habe nämlich VIIIEEEL zu lange Verzögerungen zwischen meinen BWM.
                                    Diese werden durch das Skript behoben?

                                    Ich bin leider in dem Bereicht noch etwas unerfahren... wie bringe ich das denn dieses Skript ans laufen?
                                    Und ersetzt das meinen HUE Adapter? Oder läuft der parallel weiter?
                                    Vielleicht kann mit Jemand kurz sagen wie das geht?

                                    F 1 Antwort Letzte Antwort
                                    0
                                    • F Fuxsism

                                      Hallo Zusammen,

                                      steige hier auch einmal mit ein weil es so klingt als wäre dieses Skirpt genau das was ich brauche.
                                      Ich habe nämlich VIIIEEEL zu lange Verzögerungen zwischen meinen BWM.
                                      Diese werden durch das Skript behoben?

                                      Ich bin leider in dem Bereicht noch etwas unerfahren... wie bringe ich das denn dieses Skript ans laufen?
                                      Und ersetzt das meinen HUE Adapter? Oder läuft der parallel weiter?
                                      Vielleicht kann mit Jemand kurz sagen wie das geht?

                                      F Offline
                                      F Offline
                                      FlorianSHJ
                                      schrieb am zuletzt editiert von FlorianSHJ
                                      #46

                                      @fuxsism

                                      Zwei Schritte:

                                      1. Das Script von hier https://forum.iobroker.net/topic/47391/hue-push-api-für-hue-adapter/12 als Javascript in ioBroker > Scripte anlegen. In den Zeilen 9, 10, 11 noch entsprechend anpassen, also eigene IP der HUE-Bridge, Token des registrierten Nutzers und checken, ob die Datenpunkte des HUE-Adpaters unter hue.0. liegen. IP und Token findest Du im korrekt installierten HUE-Adapter. Danach Script einfach starten.

                                      2. Polling im HUE-Adapter deaktivieren, sonst kann es zu Problemen in den Updates kommen.

                                      Funktioniert mit den beiden im stable verfügbaren HUE-Adaptern für ioBroker.

                                      Viele Grüße
                                      Florian

                                      Smart starten und helfen: www.smarthomejetzt.de

                                      Synology DS718+ | ioBroker | Docker | Home Assistant | FHEM | HUE | Aqara/Xiaomi | Tasmota | WLED | Shelly | Tradfri | Homematic | Nuki | Roborock S5

                                      F 1 Antwort Letzte Antwort
                                      0
                                      • F FlorianSHJ

                                        @fuxsism

                                        Zwei Schritte:

                                        1. Das Script von hier https://forum.iobroker.net/topic/47391/hue-push-api-für-hue-adapter/12 als Javascript in ioBroker > Scripte anlegen. In den Zeilen 9, 10, 11 noch entsprechend anpassen, also eigene IP der HUE-Bridge, Token des registrierten Nutzers und checken, ob die Datenpunkte des HUE-Adpaters unter hue.0. liegen. IP und Token findest Du im korrekt installierten HUE-Adapter. Danach Script einfach starten.

                                        2. Polling im HUE-Adapter deaktivieren, sonst kann es zu Problemen in den Updates kommen.

                                        Funktioniert mit den beiden im stable verfügbaren HUE-Adaptern für ioBroker.

                                        Viele Grüße
                                        Florian

                                        F Offline
                                        F Offline
                                        Fuxsism
                                        schrieb am zuletzt editiert von
                                        #47

                                        @florianshj

                                        ich habe jetzt soeben versucht dieses Skript zu installieren.
                                        Das scheint aber irgendwie nicht zu gehen... bekomme da diese Fehlermeldung:

                                        script.js.Hue_PUSH: TypeScript compilation failed: 'lights.status.status': { stateName: 'reachable', convert: (val) => { return val === 'connected' ? true : false; }, validTypes: ['Extended color light', 'Color temperature light', 'Dimmable light', 'On/Off plug-in unit'], after: (stateId, value) => { updateHueState(stateId.substring(0, stateId.lastIndexOf('.')) + '.on', value); } }, ^ERROR: Expected 3 arguments, but got 2. 'sensors.button.last_event': { stateName: 'buttonevent', convert: (val) => { return ((UUIDs[this.idv2] && UUIDs[this.idv2].metadata) ? UUIDs[this.idv2].metadata.control_id : 0) * 1000 + (val === 'repeat' ? 1 : 0) + (val === 'short_release' ? 2 : 0) + (val === 'long_release' ? 3 : 0); }, validTypes: ['ZLLSwitch'] }, ^ERROR: Object is possibly 'undefined'. 'sensors.button.last_event': { stateName: 'buttonevent', convert: (val) => { return ((UUIDs[this.idv2] && UUIDs[this.idv2].metadata) ? UUIDs[this.idv2].metadata.control_id : 0) * 1000 + (val === 'repeat' ? 1 : 0) + (val === 'short_release' ? 2 : 0) + (val === 'long_release' ? 3 : 0); }, validTypes: ['ZLLSwitch'] }, ^ERROR: Object is possibly 'undefined'. 'sensors.button.last_event': { stateName: 'buttonevent', convert: (val) => { return ((UUIDs[this.idv2] && UUIDs[this.idv2].metadata) ? UUIDs[this.idv2].metadata.control_id : 0) * 1000 + (val === 'repeat' ? 1 : 0) + (val === 'short_release' ? 2 : 0) + (val === 'long_release' ? 3 : 0); }, validTypes: ['ZLLSwitch'] }, ^ERROR: Object is possibly 'undefined'. 'lights.status.status': { stateName: 'state.reachable', convert: (val) => { return val === 'connected' ? true : false; }, validTypes: ['Extended color light', 'Color temperature light', 'Dimmable light', 'On/Off plug-in unit'], after: (stateId, value) => { updateHueState(stateId.substring(0, stateId.lastIndexOf('.')) + '.on', value); } }, ^ERROR: Expected 3 arguments, but got 2. 'sensors.button.last_event': { stateName: 'state.buttonevent', convert: (val) => { return ((UUIDs[this.idv2] && UUIDs[this.idv2].metadata) ? UUIDs[this.idv2].metadata.control_id : 0) * 1000 + (val === 'short_release' ? 2 : 0) + (val === 'long_release' ? 3 : 0); }, validTypes: ['ZLLSwitch'] }, ^ERROR: Object is possibly 'undefined'. 'sensors.button.last_event': { stateName: 'state.buttonevent', convert: (val) => { return ((UUIDs[this.idv2] && UUIDs[this.idv2].metadata) ? UUIDs[this.idv2].metadata.control_id : 0) * 1000 + (val === 'short_release' ? 2 : 0) + (val === 'long_release' ? 3 : 0); }, validTypes: ['ZLLSwitch'] }, ^ERROR: Object is possibly 'undefined'. 'sensors.button.last_event': { stateName: 'state.buttonevent', convert: (val) => { return ((UUIDs[this.idv2] && UUIDs[this.idv2].metadata) ? UUIDs[this.idv2].metadata.control_id : 0) * 1000 + (val === 'short_release' ? 2 : 0) + (val === 'long_release' ? 3 : 0); }, validTypes: ['ZLLSwitch'] }, ^ERROR: Object is possibly 'undefined'. updateHueState(stateId + '.r', Math.round(rgb.Red * 255)); ^ERROR: Expected 3 arguments, but got 2. updateHueState(stateId + '.g', Math.round(rgb.Green * 255)); ^ERROR: Expected 3 arguments, but got 2. updateHueState(stateId + '.b', Math.round(rgb.Blue * 255)); ^ERROR: Expected 3 arguments, but got 2. updateHueState(stateId + '.rgb', Math.round(rgb.Red * 255) + ',' + Math.round(rgb.Green * 255) + ',' + Math.round(rgb.Blue * 255)); ^ERROR: Expected 3 arguments, but got 2.
                                        

                                        Und momentan laufen die BWM gar nicht...
                                        Kann mir Jemand helfen?

                                        F 1 Antwort Letzte Antwort
                                        0
                                        • F Fuxsism

                                          @florianshj

                                          ich habe jetzt soeben versucht dieses Skript zu installieren.
                                          Das scheint aber irgendwie nicht zu gehen... bekomme da diese Fehlermeldung:

                                          script.js.Hue_PUSH: TypeScript compilation failed: 'lights.status.status': { stateName: 'reachable', convert: (val) => { return val === 'connected' ? true : false; }, validTypes: ['Extended color light', 'Color temperature light', 'Dimmable light', 'On/Off plug-in unit'], after: (stateId, value) => { updateHueState(stateId.substring(0, stateId.lastIndexOf('.')) + '.on', value); } }, ^ERROR: Expected 3 arguments, but got 2. 'sensors.button.last_event': { stateName: 'buttonevent', convert: (val) => { return ((UUIDs[this.idv2] && UUIDs[this.idv2].metadata) ? UUIDs[this.idv2].metadata.control_id : 0) * 1000 + (val === 'repeat' ? 1 : 0) + (val === 'short_release' ? 2 : 0) + (val === 'long_release' ? 3 : 0); }, validTypes: ['ZLLSwitch'] }, ^ERROR: Object is possibly 'undefined'. 'sensors.button.last_event': { stateName: 'buttonevent', convert: (val) => { return ((UUIDs[this.idv2] && UUIDs[this.idv2].metadata) ? UUIDs[this.idv2].metadata.control_id : 0) * 1000 + (val === 'repeat' ? 1 : 0) + (val === 'short_release' ? 2 : 0) + (val === 'long_release' ? 3 : 0); }, validTypes: ['ZLLSwitch'] }, ^ERROR: Object is possibly 'undefined'. 'sensors.button.last_event': { stateName: 'buttonevent', convert: (val) => { return ((UUIDs[this.idv2] && UUIDs[this.idv2].metadata) ? UUIDs[this.idv2].metadata.control_id : 0) * 1000 + (val === 'repeat' ? 1 : 0) + (val === 'short_release' ? 2 : 0) + (val === 'long_release' ? 3 : 0); }, validTypes: ['ZLLSwitch'] }, ^ERROR: Object is possibly 'undefined'. 'lights.status.status': { stateName: 'state.reachable', convert: (val) => { return val === 'connected' ? true : false; }, validTypes: ['Extended color light', 'Color temperature light', 'Dimmable light', 'On/Off plug-in unit'], after: (stateId, value) => { updateHueState(stateId.substring(0, stateId.lastIndexOf('.')) + '.on', value); } }, ^ERROR: Expected 3 arguments, but got 2. 'sensors.button.last_event': { stateName: 'state.buttonevent', convert: (val) => { return ((UUIDs[this.idv2] && UUIDs[this.idv2].metadata) ? UUIDs[this.idv2].metadata.control_id : 0) * 1000 + (val === 'short_release' ? 2 : 0) + (val === 'long_release' ? 3 : 0); }, validTypes: ['ZLLSwitch'] }, ^ERROR: Object is possibly 'undefined'. 'sensors.button.last_event': { stateName: 'state.buttonevent', convert: (val) => { return ((UUIDs[this.idv2] && UUIDs[this.idv2].metadata) ? UUIDs[this.idv2].metadata.control_id : 0) * 1000 + (val === 'short_release' ? 2 : 0) + (val === 'long_release' ? 3 : 0); }, validTypes: ['ZLLSwitch'] }, ^ERROR: Object is possibly 'undefined'. 'sensors.button.last_event': { stateName: 'state.buttonevent', convert: (val) => { return ((UUIDs[this.idv2] && UUIDs[this.idv2].metadata) ? UUIDs[this.idv2].metadata.control_id : 0) * 1000 + (val === 'short_release' ? 2 : 0) + (val === 'long_release' ? 3 : 0); }, validTypes: ['ZLLSwitch'] }, ^ERROR: Object is possibly 'undefined'. updateHueState(stateId + '.r', Math.round(rgb.Red * 255)); ^ERROR: Expected 3 arguments, but got 2. updateHueState(stateId + '.g', Math.round(rgb.Green * 255)); ^ERROR: Expected 3 arguments, but got 2. updateHueState(stateId + '.b', Math.round(rgb.Blue * 255)); ^ERROR: Expected 3 arguments, but got 2. updateHueState(stateId + '.rgb', Math.round(rgb.Red * 255) + ',' + Math.round(rgb.Green * 255) + ',' + Math.round(rgb.Blue * 255)); ^ERROR: Expected 3 arguments, but got 2.
                                          

                                          Und momentan laufen die BWM gar nicht...
                                          Kann mir Jemand helfen?

                                          F Offline
                                          F Offline
                                          fastfoot
                                          schrieb am zuletzt editiert von fastfoot
                                          #48

                                          @fuxsism sagte in Hue Push API für Hue Adapter:

                                          Das scheint aber irgendwie nicht zu gehen...

                                          hast du das mit Typescript probiert?

                                          iobroker läuft unter Docker auf QNAP TS-451+
                                          SkriptRecovery: https://forum.iobroker.net/post/930558

                                          F 2 Antworten Letzte Antwort
                                          0
                                          Antworten
                                          • In einem neuen Thema antworten
                                          Anmelden zum Antworten
                                          • Älteste zuerst
                                          • Neuste zuerst
                                          • Meiste Stimmen


                                          Support us

                                          ioBroker
                                          Community Adapters
                                          Donate

                                          849

                                          Online

                                          32.4k

                                          Benutzer

                                          81.5k

                                          Themen

                                          1.3m

                                          Beiträge
                                          Community
                                          Impressum | Datenschutz-Bestimmungen | Nutzungsbedingungen | Einwilligungseinstellungen
                                          ioBroker Community 2014-2025
                                          logo
                                          • Anmelden

                                          • Du hast noch kein Konto? Registrieren

                                          • Anmelden oder registrieren, um zu suchen
                                          • Erster Beitrag
                                            Letzter Beitrag
                                          0
                                          • Home
                                          • Aktuell
                                          • Tags
                                          • Ungelesen 0
                                          • Kategorien
                                          • Unreplied
                                          • Beliebt
                                          • GitHub
                                          • Docu
                                          • Hilfe