Hue motion sensors + remotes: custom component

Sorry for the late reply, been away for a few days. In the hue labs I see that the status does get updated and this is what the logs say:
2019-01-19 12:17:53 DEBUG (MainThread) [homeassistant.core] Bus:Handling <Event state_changed[L]: entity_id=device_tracker.hue_samsung_sm_g960f, old_state=None, new_state=<state device_tracker.hue_samsung_sm_g960f=home; source_type=gps, latitude=xxxxxxx, longitude=xxxxxx, gps_accuracy=0, last_updated=2019-01-19T11:30:45+01:00, unique_id=L_02_Qp4iU, friendly_name=Samsung SM-G960F, hidden=True @ 2019-01-19T12:17:53.080576+01:00>>

2019-01-20 10:44:32 DEBUG (MainThread) [custom_components.device_tracker.hue] Hue Geofence Samsung SM-G960F: home ({‘last_updated’: datetime.datetime(2019, 1, 20, 4, 46, 49, tzinfo=<DstTzInfo ‘Europe/Amsterdam’ CET+1:00:00 STD>), ‘unique_id’: ‘xxxxxxxxxxx’})

So it does seem to get updated, but I don’t see the component on the main dashboard.

there’s another thing I have been looking for since forever, trying to sync the Hue setup and App with HA. the settings for the accessories, more specifically the motion sensors scheduling rules.
It would really be of great added value, if we could template these in our HA automations. AS it stands now, we have to hard code these Day and night times (and the action) manually in the automations. Would be really really cool if we could use a template for that.

Trying to read the API, one can browse down to /rules, and for one a sensor find this:

http://192.168.1.212/api/api/rules/20

{"name":"MotionSensor 48.night-dark-on","owner":"redacted owner","created":"2019-01-20T12:58:29","lasttriggered":"none","timestriggered":0,"status":"enabled","recycle":true,"conditions":[{"address":"/config/localtime","operator":"in","value":"T22:00:00/T07:00:00"},{"address":"/sensors/48/state/presence","operator":"eq","value":"true"},{"address":"/sensors/49/state/dark","operator":"eq","value":"true"},{"address":"/sensors/49/state/dark","operator":"dx"},{"address":"/sensors/50/state/status","operator":"lt","value":"1"}],"actions":[{"address":"/groups/2/action","method":"PUT","body":{"scene":"fHEB6SwiIIlSXMt"}},{"address":"/sensors/50/state","method":"PUT","body":{"status":1}}]}

I am especially interested in the value":"T22:00:00/T07:00:00 and would like to use these times.

of course my top question would be if you could have a look and see if these could be added to the properties of the motion sensors, and as a consequence have them available for templating of off the binary_sensors now created.

If not, please would you help me create a command line sensor like this which I use for several lights testing for reachability:

- platform: command_line
  name: Driveway reachable
  command: !secret driveway_command
  value_template: >
    {{value_json.state.reachable}}

driveway_command: curl -X GET http://192.168.1.212/api/ID/lights/13/

I can seem to get to the value with the times from http://192.168.1.212/api/API/rules/20

please let me invite @pnbruckner for this too, since you have helped me before in going down in these nested listed templates…

Sorry, this topic is too long to read to try to figure out exactly what you’re asking my help with. Is it simply to extract “T22:00:00/T07:00:00” from the JSON you show if that JSON was obtained via a command_line sensor using curl?

If so, I’d suggest using jq in the command to extract the JSON element. E.g.:

- platform: command_line
  name: blah
  command: curl http://192.168.1.21/api/API/rules/20 | jq '.conditions[]|select(.address == "/config/localtime")|.value'

yess! that’s what I am after. Thanks for helping!.preferably even in 2 separate sensors showing the morning and night time

wouldn’t this need the

  value_template: >
    {{value_json.state.value}}  ?

Getting there:

using these templates to derive from your json sensor:

34

I can create sensor.master_bedroom_schedule_morning and sensor.master_bedroom_schedule_evening

Would this allow for using these in my automations and substitute the current hard coded time:

  - alias: 'Weekend Switch Off Masterbedroom motion sensor'
    id: 'Weekend Switch Off Masterbedroom motion sensor'
#    initial_state: 'on'
    trigger:
      platform: time
      at: '07:00:00' # the time set in the Hue app, which has only day setting, and doesn't recognize weekend
    condition:
      - condition: template
        value_template: >
          {{ is_state ('sensor.activity_selection', 'Slapen')}}
      - condition: template
        value_template: >
          {{is_state('binary_sensor.workday_sensor','off') or 
            is_states('input_boolean.home_mode_vacation','on')}}
    action:
      - service: switch.turn_off
        entity_id: switch.master_bedroom_motion_sensor_switch

to

  - alias: 'Weekend Switch Off Masterbedroom motion sensor'
    id: 'Weekend Switch Off Masterbedroom motion sensor'
#    initial_state: 'on'
    trigger:
      platform: time
      at: {{states('sensor('master_bedroom_schedule_morning')}}
    condition:
      - condition: template
        value_template: >
          {{ is_state ('sensor.activity_selection', 'Slapen')}}
      - condition: template
        value_template: >
          {{is_state('binary_sensor.workday_sensor','off') or 
            is_states('input_boolean.home_mode_vacation','on')}}
    action:
      - service: switch.turn_off
        entity_id: switch.master_bedroom_motion_sensor_switch

couldn’t these evening and morning sensors be created directly from the json? It would prevent creating extra intermediary sensors.

Hi @robmarkcole. Firstly thank you very much for this awesome component - It’s so very useful! Much appreciated. I’m trying to get long click to work on my remote. I can setup an automation that works easily enough. But the Hue app responds to “short” click beforehand. Is it your advice to not use the Hue app at all and set all those commands in Home Assistant.? And therefore have automations that respond only to short click or long click?

ok, update on my search for the schedule times, I got this far, thanks to @pnbruckner 's command_line sensor support :

49

using:

- platform: template
  sensors:
    master_bedroom_night:
      friendly_name: Master bedroom schedule night
      value_template: >
        {{states('sensor.master_bedroom_schedule')[2:-11]}}
    master_bedroom_day:
      friendly_name: Master bedroom schedule day
      value_template: >
        {{states('sensor.master_bedroom_schedule')[12:-1]}}

based on:

- platform: command_line
  name: Master bedroom schedule
  command: !secret master_bedroom_schedule

and secret:

master_bedroom_schedule: curl http://192.168.1.212/api/API/rules/20 | jq '.conditions[]|select(.address == "/config/localtime")|.value'

find the correct rules in the Hue api configuration…

I am not sure if and how I can use these times, which are strings still, but my goal is to have automatons trigger from them. So this looks very promising, thanks so far!

reason for this intermediary post is an issue though, several of the CC’s attributes are not created (though presence battery, on, and reachable are unaffected) and hence the template sensors create errors in the log:

16

and:

16 23 29

10

question for @robmarkcole and @yottatsa if this is to be expected? does my extra command_line sensor frustrate the CC? And if yes, could I prevent this is any way?
thanks for having a look!

just to be sure I tested 3 extra times, and can report it is consistent: each time I take out the |jq command line sensor, all attributes are there. use the |jq command line sensor and the attributes are gone.

maybe this way of pulling out the wanted data can be change into a

value_template: >
    {{value_json.state.value}}

after all, and that wouldn’t hurt the CC sensors creation?

EDIT 2

changed to _X GET and now it works fine!:

master_bedroom_schedule: curl -X GET http://192.168.1.212/api/API/rules/20 | jq ‘.conditions[]|select(.address == “/config/localtime”)|.value’

can’t find the documentation on the -X GET necessity but will find out later.

_UPDATE_3

seems still a bit flakey, template sensors don’t always get created, and are only created when the motion sensors is set to on. Dint understand this at all yet… somehow the command_line sensors interferes with the regular CC created sensors, and their template sensors.

Still progress made on the timings. I can now set a trigger using:

{{now().time().strftime("%H:%M") == states('sensor.master_bedroom_schedule_day') }} or
{{now().time().strftime("%H:%M") == states('sensor.master_bedroom_schedule_night')}}

since the Hue app doesn’t support seconds in the schedules, I took them out by means of:

- platform: template
  sensors:
    master_bedroom_schedule_night:
      friendly_name: Master bedroom schedule night
      value_template: >
        {{states('sensor.master_bedroom_schedule')[2:-14]}}
    master_bedroom_schedule_day:
      friendly_name: Master bedroom schedule day
      value_template: >
        {{states('sensor.master_bedroom_schedule')[12:-4]}}

resulting example automation:

  - alias: 'Weekend Switch Off Masterbedroom motion sensor'
    id: 'Weekend Switch Off Masterbedroom motion sensor'
#    initial_state: 'on'
    trigger:
#      platform: time
#      at: '07:00:00' # the time set in the Hue app, which has only day setting, and doesn't recognize weekend
      platform: template
      value_template: >
        {{now().time().strftime("%H:%M") == states('sensor.master_bedroom_schedule_day')}}
    condition:
      - condition: template
        value_template: >
          {{ is_state ('sensor.activity_selection', 'Slapen')}}
      - condition: template
        value_template: >
          {{is_state('binary_sensor.workday_sensor','off') or 
            is_states('input_boolean.home_mode_vacation','on')}}
    action:
      - service: switch.turn_off
        entity_id: switch.master_bedroom_motion_sensor_switch
        - condition: template
        value_template: >
          {{ is_state('input_boolean.notify_system', 'on')}}
      - service: notify.notify
        data_template:
          message: >
            {{as_timestamp(now()) | timestamp_custom("%X") }}: Day Off, enjoy a longer sleep.

hope to be able to do that with a better json command string, but since I don’t have that yet, this will do?

1 Like

First- many thanks to Robin - this is a great component. (I’m a newbie, and still learning my way around HA.) Should I be concerned that a scan interval of 0.1 secs will place a significant load on my Hue bridge, do you think? Or on my Pi?

If I wanted to drop, it, I’m guessing I’d do something like this?

binary_sensor:
  - platform: hue
      scan_interval: 0.2

your best bet would be to change line 23 in the CC:

SCAN_INTERVAL = timedelta(seconds=0.1)

set it to 1.0 if you need, motion sensors report when they have anything to report. I haven’t noticed any significant loss of responsiveness doing so, and for the other attributes this doesn’t matter at all.

that being said. with the latest CC I havent seen any of the timing issues we had before filling the logs each 0.1 second, so if you’re not experiencing issues, why change a running system.

I am having a problem with the hue remote sensor.
One remote is firing the last pressed button regularly. For example I get the payload 1_click every 5 or 10 minutes although the remote is not pressed. In Node-Red I am using an “events: state” node to catch state changes but this also fires regularly though no change.
Even stranger is that I do have a second hue remote which does not fire regularly in HA but only when pressed. :thinking: :exploding_head:
Does anyone have the same problem or at least any ideas?

EDIT: Problem solved. See below.

@ Rhandos
I can see you got it working with a new format, but your original format would have worked also, except for one thing.
You missed the sensor. in the template.

should be

Just thought I would mention. Probably a useless bit of information now, but it might help someone :slight_smile:

Has anyone explored reporting and controlling the motion sensitivity setting on the motion sensors? I have some sensors where I’d like to vary the level of sensitivity depending on various events (time of day, whose home, etc) and am wondering if there’s a recommended approach for this.

that could indeed be useful, but I am sorry to say I fear the same issue as with my quest for the schedule settings: whenever I enable that in the form of a command_line sensor, the sensor itself isnt working any longer as expected, needs to be switched on (while in the current setting using only the Hue CC, sensors reports their attributes, even when the motion sensor is switched Off)

see: Hue motion sensors + remotes: custom component - #691 by Mariusthvdb

but you could check the api, see what values are there for sensitivity, and probably set it with a Put command.

Thanks Marius for the reference. In my curl tests it seems like GET’ing and PUT’ing the sensitivity value works fine, without any issues gathering other attributes on the main sensor that you seem to have encountered with the schedules (but maybe they’ll pop up later?)

I thought about creating an input_select for each motion sensor, a sensor to GET each value, a shell_command to update the value (and map the input_select friendly name to the API value), automations to call the shell_command when the input_select changed, and automations to update the input_select when the sensor updated.

For one motion sensor this wouldn’t be too bad, but for multiple motion sensors it seems pretty hairy, especially since I’d need to hardcode the sensor ID# for each sensor, on top of managing the bridge IP and API key in a second place. It’d probably also cause a once-loop when the input_select change causes the sensor to update, which would cause the input_select automation to fire again.

In the end I don’t actually have much need for a selector UI to show/control the status, I just want to be able to know the status and change it with automation.
So for now I went with the below. Not super pretty but at least it’s brief.

rest_command:
  hue_command:
    url: 'http://HUE_BRIDGE_IP/api/APIKEY/{{ type }}/{{ id }}/{{ command }}'
    method: put
    payload: '{{ data }}'

- id: set_motion_sensitivity_to_medium
  trigger:
  ...
  action:
  - service: rest_command.hue_command
    data:
      command: config
      data: '{ "sensitivity":1 }'
      id: 7
      type: sensors


- id: set_motion_sensitivity_to_high
  trigger:
  ...
  action:
  - service: rest_command.hue_command
    data:
      command: config
      data: '{ "sensitivity":2 }'
      id: 7
      type: sensors

Left the rest_command.hue_command fairly generic in case I have other uses later. Also updated the hue CC binary_sensor to collect and display the ‘sensitivity’ attribute so I can view the current value on the existing binary_sensor badge.

For a manual update, I can do a service call to rest_command.hue_command from dev-service. The main thing is having to remember the right sensor id numbers.

np, and cool thinking!
I have several sensor testing the reachable of a few lights, and that works just fine without causing any issues.

Maybe its just the way I post the query to the sensors, that have them act up. Don’t know yet, and I have disabled it for now.

will be following you here though, cause I like the way we can play with the HUE api from within HA.

I think the thresholds could be added to the CC sensors, and it would probably be not very much extra effort to add that to it, and be very convenient to not have to do all the manual labor. adding to the CC might even be less tressful to the Hue system interaction. Maybe @robmarkcole and @yottatsa could read along with you?

Getting the current values would be a bi step forward, and leave you only to sort out changing that :wink:

btw, I always put all urls or resources in the secrets file, which is very nice and easy to copy then, only have to sort things out once, and no risk of sharing your config over the community …

Getting the current sensitivity value on the existing CC binary_sensor is of course trivial, just a quick 2-line change to enable it.

What would the thresholds do?

Thought about putting the URL in the secrets file (which I do for normal credentials fields) but wasn’t sure whether the template values would still be parsed, plus it would make the listed rest_command somewhat unhelpful. :smiley: But yeah, that’s a good suggestion. Ideal would be if I could use !secrets BLAH in the middle of a value, but haven’t seen any indications that that’s possible.

No it isn’t… Have stopped trying that, and added many full lines to the secrets file. It has the nice effect of compact configuration files, and easy to copy secrets.
I have 11 sensors…

please create a PR for this! if it is that simple, no reason not too? Maybe you’d be willing to see if the day and night times of the sensors would be just as easy? I’d really need those…

about the commands: couldn’t you use a variable for id too? that why you could

1- set sensitivity,
2- set id, and
3- hit execute.
somewhat like my set hue scene setup:

  hue_light_control:
    name: Hue Light Control
    icon: mdi:spotlight
    control: hidden
    entities:
      - input_select.hue_scenes
      - input_select.hue_groups
      - script.set_hue_scene

and script ( in your case rest command)

script:
  set_hue_scene:
    alias: Set Hue scene
    sequence:
      service: hue.hue_activate_scene
      data_template:
        group_name: >
          {{ states('input_select.hue_groups')}}
        scene_name: >
          {{ states('input_select.hue_scenes')}}

no need for automation and time to reconsider if you change your mind before executing :wink:

I do use a variable for the id, though as you point out using some input_select’s as an input field to a script would be easier than dropping the json into dev-service if one needed to do manual changes regularly. For me it’ll be 99% automations, but I might borrow your scene select for actually selecting hue scenes. :slight_smile: Thanks for the example!

I was hoping input_select’s had “friendly names” for the values, so I could pick map friendly names (“Hall”, “Garage”, “Living Room”, etc.) to the id numbers, which would populate the actual input_select state. That’d make it more worthwhile.

please create a PR for this! if it is that simple, no reason not too? Maybe you’d be willing to see if the day and night times of the sensors would be just as easy? I’d really need those…

Almost more of a configuration choice, but since you asked, I created a PR. It can count as my request to have it added.

Re: the day and night times, I don’t think it’s as simple as those seem to be setup as rules, whereas sensitivity is just another config attribute like “battery” or “reachable”, which is already read but instead currently discarded.

you’d be most welcome. have a look here how Ive done it, added scene Off and use it in a tiles setup both in regular ha and Lovelace:

15

1 Like

they’re not discarded are they, and fully templatable?:

38

would you be able to add the ‘tholddark’ of the ZLLLightLevel sensor too?

I have several scenarios I could use that for:

night scenes vs day scenes and automatically adjust lightlevel sensitivity

home/away modes are obvious: motion detection has to be more sensitive when out of the house

sleep/awake: dont want to have the lights go on when I turn around in bed.

btw, that what my quest for the day-night schedules is for, being able to automatically read and disable at those set times, or maybe even change them in the weekend to sleep out.

but, for now, please add the tholddark to the PR?