Hello,
First of all, I’m pretty new with HA.
I’m trying to make a button for my Lovelace board that will increase or decrease the brightness of a light. I’m using the entity-button for that.
Here is the code in my ui-lovelace.yaml
- type: entity-button
name: Floor light Increase
icon: mdi:plus-box
tap_action:
action: call-service
service: script.increase_light_brightness
service_data:
light_id: 'light.floor'
entity: light.floor
In my scripts.yaml :
increase_light_brightness:
alias: 'Increase Light Brightness'
sequence:
- service: light.turn_on
data_template:
entity_id: '{{light_id}}'
brightness: '{{states.XXX.attributes.brightness + 10}}'
Instead of the XXX in the last line of code, I would need to reference light_id instead so it makes the script more dynamic but I wasn’t able to find a way to do it. Anyone could help me on this.
Thanks
Try:
brightness: "{{state_attr(light_id, 'brightness') + 10}}"
But be careful. The brightness variable cannot be larger than 255. So you might be better off with something like this:
brightness: >
{% set newb = state_attr(light_id, 'brightness') + 10 %}
{{ newb if newb <= 255 else 255 }}
1 Like
Thanks @pnbruckner, it works great. Only thing is it is not working if the light is turned off - any idea about it ?
Also, where can I find some documentation about the syntax you’re using (I mean when you use > , {, %)
Oh, ok. Well, that’s easy to deal with. Try this:
brightness: >
{% set newb = state_attr(light_id, 'brightness')|int + 10 %}
{{ newb if newb <= 255 else 255 }}
When a light is off it doesn’t have a brightness attribute. In that case the state_attr function returns None. You can’t add 10 to None. So, adding the int filter causes anything that isn’t a number, or string representation of a number, (such as None) to result in the value of 0
.
BTW, after looking at the code again, it looks like brightness can accept numbers outside the range of 0 to 255. Numbers outside this range are “clamped” to 0 or 255. So, in theory, you could just use:
brightness: "{{ state_attr(light_id, 'brightness')|int + 10 }}"
1 Like
Thank you @pnbruckner - that works perfectly well!
1 Like