better hue integration?

Moderator: leecollings

prein
Posts: 10
Joined: Thursday 26 November 2015 11:25
Target OS: Raspberry Pi / ODroid
Domoticz version:
Contact:

better hue integration?

Post by prein »

When I am changing my philips light bulbs using other software than domoticz (for instance via Hue app or via Hue Tap) I can see that the status of the light bulbs change in domoticz. That is good!
However, I can't use it in scripts. It seems that only the GUI of Domoticz is updated, but not the real (database) values.

for example:
hue was turned off using hue-tap. shows off in domoticz, but when I ask for the status in LUA script it still says: on. This means I am unable to make scripts based on the status of the hue lights.

so for an alternative solution I created a dummy switch with a lua time event that triggers when the hue light last seen info is updated. But altough the last seen information is updated on the screen, the information I get from LUA still is the old information.

The workaround for this is that I have a lua time event that polls the status of my light bulb directly from the hue bridge, updating a dummy sensor. But it has to run every minute, since there is no reliable information within Domoticz that can be used when scripting.

Is this a bug and will this be changed?
User avatar
bbqkees
Posts: 407
Joined: Sunday 17 August 2014 21:01
Target OS: Linux
Domoticz version: 4.1x
Location: The Netherlands
Contact:

Re: better hue integration?

Post by bbqkees »

Can you post your script?
Bosch / Nefit / Buderus / Junkers / Worcester / Sieger EMS bus Wi-Fi MQTT Gateway and interface boards: https://bbqkees-electronics.nl/
prein
Posts: 10
Joined: Thursday 26 November 2015 11:25
Target OS: Raspberry Pi / ODroid
Domoticz version:
Contact:

Re: better hue integration?

Post by prein »

Note that I have commented out the if statement that checks for the device update. Meaning it now runs every minute.
Code is very rough, full of dirty comments and unneccesary print commands... sorry for that :)


replace: $$APIUSERKEY$$ with your philips hue user ID

note that the hue bulb I am checking is named: Betty
The Dummy switch is named: Hue Status
In the Hue bridge, I am calling light number 2

Furthermore I had to implement some plugins, taken from the Wiki (create the directories if they don't exist):
Secondly, you need to install the socket and luacolor libraries on your machine, I have attached gzipped tar files for the Raspberry Pi to this forum post, as there is no packaged versions available. Download the two attached files, placing usrlocalsharelua5p2.tar.gz in directory /usr/local/share/lua/5.2/ and extracting the file with sudo tar -xvf usrlocalsharelua5p2.tar.gz, then put usrlocalliblua5p2.tar.gz in /usr/local/lib/lua/5.2/ and extract all the files with sudo tar -xvf usrlocalliblua5p2.tar.gz.
socket and luacolor from: http://www.domoticz.com/forum/viewtopic ... 638#p22638
LUA Json library from: http://regex.info/blog/lua/json (place in /usr/local/share/lua/5.2/)

Code: Select all

t1 = os.time()
s = otherdevices_lastupdate['Betty']
year = string.sub(s, 1, 4)
month = string.sub(s, 6, 7)
day = string.sub(s, 9, 10)
hour = string.sub(s, 12, 13)
minutes = string.sub(s, 15, 16)
seconds = string.sub(s, 18, 19)
 
commandArray = {}
print(s) 
t2 = os.time{year=year, month=month, day=day, hour=hour, min=minutes, sec=seconds}
difference = (os.difftime (t1, t2))
--if (difference > 10 and difference < 70) then
    
	base_url =  'http://192.168.1.57/api/$$APIUSERKEY$$/'
	domoticz_url = '192.168.1.58:8080'
 
   -- Only store the pattern if the light is already on
   
      -- Only load libaries now
      io = require('io')
      http = require('socket.http')
      ltn12 = require('ltn12')
      colors = require('luacolors')
      json = require('json')
 
      function hueit(device, operation, mode)
      -- Sends commands to Philips Hue bridge and returns JSON
      --     device is the device specific url i.e. /lights/1/state
      --     operation is the message body i.e. {"on":true, "sat":255, "bri":255,"hue":10000}
      --     mode is 'GET', 'PUT' or 'POST'
         local t = {}
         local url = base_url .. device
         local req_body = operation
         print(url)
         print(req_body)
         local headers = {
            ["Content-Type"] = "application/json";
            ["Content-Length"] = #req_body;
          }
          client, code, headers, status = http.request{url=url, headers=headers, source=ltn12.source.string(req_body), sink = ltn12.sink.table(t), method=mode}
         print(status)
         return t
      end
 
      function processJSON(t)
         print(table.concat(t))
         obj, pos, err = json:decode(table.concat(t),1,nil)
         if err then
            print ("Error:", err)
         else
            for i = 1,1 do
               state=obj.state
				onvalue = state.on
				print('nu komt ie')
				print(tostring(onvalue))
			end
         end
		 if onvalue then
		 commandArray['Hue Status']='On'
		 print('switching dummy on')
		 else
		 commandArray['Hue Status']='Off'
		 print('switching dummy off')
		 end
         return
      end
 
      device = 'lights/2/'
      mode = 'GET'
      params = ''
      t = hueit(device, params, mode)
      processJSON(t)
   
--end 
 
return commandArray
User avatar
bbqkees
Posts: 407
Joined: Sunday 17 August 2014 21:01
Target OS: Linux
Domoticz version: 4.1x
Location: The Netherlands
Contact:

Re: better hue integration?

Post by bbqkees »

I meant the code you used in the first place which did not work.

You have to keep in mind that 'on' is not really defined for dimmers, it is f.i. '"Set Level, Level: 43 %".
When off it is "Off, Level: 32 %".

There was something with dimmer als LUA, not sure what really works.
Bosch / Nefit / Buderus / Junkers / Worcester / Sieger EMS bus Wi-Fi MQTT Gateway and interface boards: https://bbqkees-electronics.nl/
prein
Posts: 10
Joined: Thursday 26 November 2015 11:25
Target OS: Raspberry Pi / ODroid
Domoticz version:
Contact:

Re: better hue integration?

Post by prein »

I tried:

if(devicechanged[]) --> never executes (of course in device script)

Code: Select all

commandArray =  {}
base_url =  'http://192.168.1.57/api/&&APIUSERKEY&&/'
domoticz_url = '192.168.1.58:8080'
 
if(devicechanged['Betty']) then
   -- Only store the pattern if the light is already on
   
      -- Only load libaries now
      io = require('io')
      http = require('socket.http')
      ltn12 = require('ltn12')
      colors = require('luacolors')
      json = require('json')
 
      function hueit(device, operation, mode)
      -- Sends commands to Philips Hue bridge and returns JSON
      --     device is the device specific url i.e. /lights/1/state
      --     operation is the message body i.e. {"on":true, "sat":255, "bri":255,"hue":10000}
      --     mode is 'GET', 'PUT' or 'POST'
         local t = {}
         local url = base_url .. device
         local req_body = operation
         print(url)
         print(req_body)
         local headers = {
            ["Content-Type"] = "application/json";
            ["Content-Length"] = #req_body;
          }
          client, code, headers, status = http.request{url=url, headers=headers, source=ltn12.source.string(req_body), sink = ltn12.sink.table(t), method=mode}
         print(status)
         return t
      end
 
      function processJSON(t)
         print(table.concat(t))
         obj, pos, err = json:decode(table.concat(t),1,nil)
         if err then
            print ("ErrorRein:", err)
         else
            for i = 1,1 do
               if i == 1 then
                  stuff = ''
				  else
                  stuff = stuff ..'|'
				end
               state=obj.state
               stuff = stuff .. state.bri ..'|'.. state.hue ..'|'.. state.sat ..'|'.. state.xy[1] ..'|'.. state.xy[2] ..'|'.. state.ct
				onvalue = state.on
				print('nu komt ie')
				print(tostring(onvalue))
				--print('state')
				--print(table.concat(state))
			end
         end
         --print('length of encode '..#stuff)
         --noscenes = uservariables["NoHue1Scenes"]
         --print('noscenes '..noscenes)
         --noscenes = noscenes + 1
         --commandArray['Variable:NoHue1Scenes'] = tostring(noscenes)
         --t={}
         --url = domoticz_url..'/json.htm?type=command&param=saveuservariable&vname=Hue1Scene'..noscenes..'&vtype=2&vvalue='..stuff
         --commandArray['OpenURL'] = url
		 if onvalue then
		 commandArray['Hue Status']='On'
		 print('switching dummy on')
		 else
		 commandArray['Hue Status']='Off'
		 print('switching dummy off')
		 end
         return
      end
 
      device = 'lights/2/'
      mode = 'GET'
      params = ''
      t = hueit(device, params, mode)
      processJSON(t)
   
end
 
return commandArray

otherdevices['Betty'] will allways give the same result (on/off/dimmed, nothing changes) : --> LUA: Set Level
otherdevices_svalues['Betty'] will also always give the same result: --> LUA: 210;13199 (these values also never change, not when on, off, only with different colour)
User avatar
bbqkees
Posts: 407
Joined: Sunday 17 August 2014 21:01
Target OS: Linux
Domoticz version: 4.1x
Location: The Netherlands
Contact:

Re: better hue integration?

Post by bbqkees »

I will try to reproduce the problem.
What version of Domoticz are you using?
Bosch / Nefit / Buderus / Junkers / Worcester / Sieger EMS bus Wi-Fi MQTT Gateway and interface boards: https://bbqkees-electronics.nl/
prein
Posts: 10
Joined: Thursday 26 November 2015 11:25
Target OS: Raspberry Pi / ODroid
Domoticz version:
Contact:

Re: better hue integration?

Post by prein »

thanks! using latest stable version: v2.3530
Derik
Posts: 1602
Joined: Friday 18 October 2013 23:33
Target OS: Raspberry Pi / ODroid
Domoticz version: BETA
Location: Arnhem/Nijmegen Nederland
Contact:

Re: better hue integration?

Post by Derik »

I do have/use this script...
When i use a button of my remote i activate this script.[ with a dummy button, and place the adres to my script ]
Always the good color etc..
After a other device i click a button on my remote, works simple..

Code: Select all

#!/bin/sh
curl -H "Accept: application/json" -X PUT --data '{"on": true,"bri": 500,"hue": 13088,"sat": 212,"xy": [0.5128,0.4147],"ct": 467,"alert": "none","effect": "none","colormode": "xy","reachable": true}' http://192.168.5.36/api/newdeveloper/lights/4/state
I get this code with the developer api from Hue.
Xu4: Beta Extreme antenna RFXcomE,WU Fi Ping ip P1 Gen5 PVOutput Harmony HUE SolarmanPv OTG Winddelen Alive ESP Buienradar MySensors WOL Winddelen counting RPi: Beta SMAspot RFlinkTest Domoticz ...Different backups
prein
Posts: 10
Joined: Thursday 26 November 2015 11:25
Target OS: Raspberry Pi / ODroid
Domoticz version:
Contact:

Re: better hue integration?

Post by prein »

I have got this kind of integration as well. The problem is that when I switch lights using non-Domoticz Apps, like Philips Hue app or Hue-TAP, I would like the status in Domoticz to be changed. The status changes, but it seems only visual, not in the database. This makes it unable to use the state of the hue lights in scripts. (like, if hue is turned off, also turn off other lights). I got this working, but I have to check the status in the hue bridge every minute, I want it to work without the workaround.
Kjakan
Posts: 14
Joined: Wednesday 11 March 2015 14:03
Target OS: Linux
Domoticz version: 2024.2
Location: Norway
Contact:

Re: better hue integration?

Post by Kjakan »

prein wrote:I have got this kind of integration as well. The problem is that when I switch lights using non-Domoticz Apps, like Philips Hue app or Hue-TAP, I would like the status in Domoticz to be changed. The status changes, but it seems only visual, not in the database. This makes it unable to use the state of the hue lights in scripts. (like, if hue is turned off, also turn off other lights). I got this working, but I have to check the status in the hue bridge every minute, I want it to work without the workaround.
I have the same problem. Hoping for better Philips Hue support in Domoticz in the future.

Now i'm using a script with Curl that gives me true/false whenever a hue bulb is on/off in scripts.
irisdc
Posts: 1
Joined: Tuesday 22 December 2015 16:53
Target OS: Raspberry Pi / ODroid
Domoticz version:
Contact:

Re: better hue integration?

Post by irisdc »

I have exactly the same problem as I would like to have real-time information about the a Hue light triggered by a physical switch. Will this be foreseen? Thanks in advance.
MaXa
Posts: 6
Joined: Saturday 15 August 2015 9:10
Target OS: Linux
Domoticz version:
Contact:

Re: better hue integration?

Post by MaXa »

Very interesting topic. Stumbled upon the same issue this evening. I bought the Philips HUE light with the Wireless light dimmer remote combi. Since the dimmer is not detected directly in Domoticz due to protocol limitations of HUE, I do not have the ability to switch my other lights or hardware with it (like Applamp lights) over Domoticz. My idea was the almost the same like you guys. I Have a bunch of sleeping room ligths Applamp (milight) together with the Philips HUE light in this room. My idea was to switch all lights with this Philips Dimmer switch and link the Milights directly to the Philips HUE lamp with a Blockly event or LUA script. Somehting like: If milight off then set Milight off. However, this doesn't respond in LUA and in Blockly. Only when I switch the Philips HUE light directly over the Domoticz interface, the other lights switch off as well. Turn Philips HUE off with HUE switch, doesn't trigger any activitity. Seems like something is completely ignored when switching lights from external sources besides Domoticz. Will do further investigation...
wmn79
Posts: 27
Joined: Monday 13 April 2015 23:19
Target OS: NAS (Synology & others)
Domoticz version: 3.5033
Location: Amsterdam, The Netherlands
Contact:

Re: better hue integration?

Post by wmn79 »

Kjakan wrote:
prein wrote:I have got this kind of integration as well. The problem is that when I switch lights using non-Domoticz Apps, like Philips Hue app or Hue-TAP, I would like the status in Domoticz to be changed. The status changes, but it seems only visual, not in the database. This makes it unable to use the state of the hue lights in scripts. (like, if hue is turned off, also turn off other lights). I got this working, but I have to check the status in the hue bridge every minute, I want it to work without the workaround.
I have the same problem. Hoping for better Philips Hue support in Domoticz in the future.

Now i'm using a script with Curl that gives me true/false whenever a hue bulb is on/off in scripts.
I have the same issue here, I want to use the states in Lua scripts but the status is not updated. I have changed one of my Hue Lights to an off/on switch instead of dimmer but that status gets only updated if I use the Domoticz interface. If my Domoticz scene (which is using a bash script to turn the correct Hue scene on) is turned on the status in Domoticz does not get updated. So the "last seen" of the switch displays correct, but the log of the switch doesn't display all changes. Also if you want to use the values in events or scripts it does not work as expected. See these topics:
viewtopic.php?f=6&t=5541&p=66686&hilit= ... vel#p66686
viewtopic.php?f=6&t=8745&p=64448&hilit= ... vel#p64448

So better Philips Hue support in Domoticz would be highly appreciated! In the mean time I will try to figure something out based on the suggestions in this topic.

@Kjakan: can you share the script you use with Curl?
rgroothuis
Posts: 347
Joined: Friday 03 April 2015 17:09
Target OS: Raspberry Pi / ODroid
Domoticz version:
Contact:

Re: better hue integration?

Post by rgroothuis »

+1 for better support. I've the same problems with my Hue bridge. Published on a different thread already.
Kjakan
Posts: 14
Joined: Wednesday 11 March 2015 14:03
Target OS: Linux
Domoticz version: 2024.2
Location: Norway
Contact:

Re: better hue integration?

Post by Kjakan »

wmn79 wrote:@Kjakan: can you share the script you use with Curl?
Sure. I'm still learning lua and programming so it could be better ways to do this.

You need to download dkjson.lua from http://dkolf.de/src/dkjson-lua.fsl/home and put it in "/usr/local/lib/lua/5.2" folder.

Code: Select all

local HueBridgeIP = "192.168.XX.XX"
local HueBridgeAPI = "XXXXXXX"

-- Function for checking Philips Hue On/Off state
function GetHueState(light_id)
	local json = require ("dkjson")
	local tmpfile = '/tmp/hueLight_'..light_id..'.txt'
	os.execute('curl -s http://'..HueBridgeIP..'/api/'..HueBridgeAPI..'/lights/'..light_id..' > '..tmpfile)
	local file = io.open(tmpfile)
	local content = file:read()
	local obj, pos, err = json.decode (content, 1, nil)
		if err then
			print ("Error:", err)
		else
			hue_state=(obj.state.on)
		end
	file:close()
	os.execute('rm -f '..tmpfile..'')
	--print (content)
	return (hue_state)
end

commandArray = {}

local hue_light1 = GetHueState(1) -- Get state from hue bulb id 1
local hue_light2 = GetHueState(2) -- Get state from hue bulb id 2
		
if hue_light1 == false then
	print("Hue light 1 is Off")
elseif hue_light1 == true then
	print("Hue light 1 is On")
end

if hue_light2 == false then
	print("Hue light 2 is Off")
elseif hue_light2 == true then
	print("Hue light 2 is On")
end

return commandArray
Change hue bridge IP and hue bridge API.
This example will get true/false state from Hue lights with id 1 and 2.
wmn79
Posts: 27
Joined: Monday 13 April 2015 23:19
Target OS: NAS (Synology & others)
Domoticz version: 3.5033
Location: Amsterdam, The Netherlands
Contact:

Re: better hue integration?

Post by wmn79 »

Kjakan wrote:
wmn79 wrote:@Kjakan: can you share the script you use with Curl?
Sure. I'm still learning lua and programming so it could be better ways to do this.
....
Thanks! I used your example and altered it a bit. I do the check only on one light, when it is off but the state (switchlog/otherdevices table) in Domoticz is not correct it gives the same command again through the script. This seems to work for how I want to use it. Below is the script I use now:

Code: Select all

-- ~/domoticz/scripts/lua/script_time_HueState.lua

    local HueBridgeIP = "192.168.x.x"
    local HueBridgeAPI = "username"

    -- Function for checking Philips Hue On/Off state
    function GetHueState(light_id)
       local json = require ("dkjson")
       local tmpfile = '/tmp/hueLight_'..light_id..'.txt'
       os.execute('curl -s http://'..HueBridgeIP..'/api/'..HueBridgeAPI..'/lights/'..light_id..' > '..tmpfile)
       local file = io.open(tmpfile)
       local content = file:read()
       local obj, pos, err = json.decode (content, 1, nil)
          if err then
             print ("Error:", err)
          else
             hue_state=(obj.state.on)
          end
       file:close()
       os.execute('rm -f '..tmpfile..'')
       --print (content)
       return (hue_state)
    end

    commandArray = {}

    local hue_light1 = GetHueState(5) -- Get state from hue bulb id 5
          
    if hue_light1 == false then
       print("Hue light 1 is Off")
	   if otherdevices['Hue Staande Lamp']== 'On' then 
		  commandArray['Hue Staande Lamp']='Off'
	   end
    elseif hue_light1 == true then
       print("Hue light 1 is On")
	   if otherdevices['Hue Staande Lamp']== 'Off' then 
		  commandArray['Hue Staande Lamp']='On'
	   end
    end

    return commandArray
	
kneh1
Posts: 1
Joined: Friday 01 January 2016 11:22
Target OS: Raspberry Pi / ODroid
Domoticz version:
Contact:

Re: better hue integration?

Post by kneh1 »

I had the same HUE update problem in Domoticz.
As a workaround I created a simple shell script to update the status of HUE lamps in Domoticz (similar as the lua scripts from previous posts).
I tested the script on a Raspberry pi.

Code: Select all

#!/bin/bash
# 
# Replace <ip hue bridge> with the ip address or hostname of your HUE bridge
# Replace <username> with the username that corresponds with your HUE bridge
# Replace <ip domoticz> with the ip address or hostname of your Domoticz system
#
# MYARR contains the HUE light numbers (used in the Philips HUE app) that correspond with the IDX numbers (used in Domoticz) in the form [HUE_LIGHT_NR]=IDX_NR
# For me, HUE light 1 corresponds with IDX 38, HUE light 2 corresponds with IDX 39 etc.
#
declare -A MYARR=( [1]=38 [2]=39 [5]=42 [6]=43 [7]=44 )
for i in ${!MYARR[@]}; do
  HUE_PROPS=$(curl --silent "http://<ip hue bridge>/api/<username>/lights/$i")
  grep '{\"state\": {\"on\":false' > /dev/null 2>&1 <<< "$HUE_PROPS"
  if [ $? -eq 0 ]; then
    curl --silent --output /dev/null "http://<ip domoticz>:8080/json.htm?type=command&param=switchlight&idx=${MYARR[$i]}&switchcmd=Off"
  fi
  grep '{\"state\": {\"on\":true' > /dev/null 2>&1 <<< "$HUE_PROPS"
  if [ $? -eq 0 ]; then
    curl --silent --output /dev/null "http://<ip domoticz>:8080/json.htm?type=command&param=switchlight&idx=${MYARR[$i]}&switchcmd=On"
  fi
done
Save above script somewhere on your filesystem (e.g. /home/pi/crontab/updateHueState.sh)
Make the script executable using the command chmod +x /home/pi/crontab/updateHueState.sh
You can easily test the script. Use your HUE tap or the Philips HUE app to turn one or more HUE light on, and execute the updateHueState.sh to update the status in Domoticz accordingly.

Calling the script each minute can be done by calling it from a cronjob. You can create such a cronjob by editing your cronjob file using he command cronjob -e
Add the following line:
* * * * * /home/pi/crontab/updateHueState.sh
This will call your script each minute.
RichardBokker
Posts: 39
Joined: Thursday 09 April 2015 20:57
Target OS: Raspberry Pi / ODroid
Domoticz version: 3.9317
Location: Netherlands
Contact:

Re: better hue integration?

Post by RichardBokker »

I had running my hue lights a couple of months, but suddenly it was not working anymore? on/Off with hue app works fine.

I had this, with a bash script:

On code:

Code: Select all

curl -s -H "Accept: application/json" -X PUT --data '{"on":true, "sat":153, "bri":122,"hue":7294}' http://192.168.1.161/api/newdeveloper/lights/1/state ;
Off code:

Code: Select all

curl -s -H "Accept: application/json" -X PUT --data '{"on":false}' http://192.168.1.161/api/newdeveloper/lights/1/state ;
API debug console give the following result on url: api/newdeveloper/lights/1/state

Code: Select all

[
    {
        "error": {
            "type": 3,
            "address": "/lights/1/state",
            "description": "resource, /lights/1/state, not available"
        }
    }
Anyone a idea to make it working again?
Bikey
Posts: 331
Joined: Sunday 22 February 2015 12:19
Target OS: Linux
Domoticz version: 2020.x
Location: Netherlands
Contact:

Re: better hue integration?

Post by Bikey »

I think you now must a bridge generated user-key instead if the name.
See: http://www.developers.meethue.com/docum ... ng-started

Currently it is possible to create your own usernames in the bridge (e.g. “newdeveloper”), however, this option will be removed in future bridge versions, so we need to use the randomly generated username that the bridge creates for you.
RichardBokker
Posts: 39
Joined: Thursday 09 April 2015 20:57
Target OS: Raspberry Pi / ODroid
Domoticz version: 3.9317
Location: Netherlands
Contact:

Re: better hue integration?

Post by RichardBokker »

Thnx, that did the trick. Scripts are working now when i run them directly from Putty.

But the dummy switch what activates the on and off switch is not working, scripts seems not to be activated.. hmmz.
Post Reply

Who is online

Users browsing this forum: No registered users and 1 guest