#templates-archived
1 messages Β· Page 127 of 1
same way
{% set new_text = states('input_text.test').split("?") %}
{{ new_text[0] + " " + new_text[1] }}
noice
ok, when you split it, it removes the ? is there a way to do it without removing the question mark
just add it back π
damn...I ask, go try, figure it out and by the time I get back you have answered
I feel like this is a stupid question, but how can I call the status of a binary sensor in a template ? using "states" is coming back unknown when I know it has a value of off
not sure what my if statement should look like
(works fine with non binary sensors, the way I have it)
Please use https://paste.ubuntu.com/ to share code or logs. Please don't use Pastebin, since it can randomly add spaces to the main view.
{%- if states.binary_sensor.awake.state == on -%}
{% set status1 = states('sensor.binary_sensor.awake') %}
used that
and then {{status1}} and I get "unknown"
well, that's wrong π
sensor.binary_sensor isn't a thing
use what I gave you above
I think I called my sensor "binary_sensor.awake"
oh
i see
thx let me adjust
thank you
ugh driving me nuts π very much appreciated
the part to the left of the "." is the domain, and determines the type of the thing and what you can do with it. the part to the right is the "object_id", and is usually the name you provide or can specify
and if you have two "."s, you're in trouble π
you don't need all the "-"s, but it should be
something's not correct
if you're just looking for the boolean value, you can leave off the "if"
maybe I'm overcomplicating it
~share the whole thing
Please use https://paste.ubuntu.com/ to share code or logs. Please don't use Pastebin, since it can randomly add spaces to the main view.
if you only have an "if", you're missing the rest of it. but if you just want to use that expression as a boolean, you don't need the "if"
(keep in mind my brain works best with visual confirmation on each step so I tend to echo stuff just so I know it's functional)
Here's what I'm trying to do
I have 2 sensors
a value sensor tracking humidity and an awake (and a sleeping) sensor (binary)
I want a 3rd sensor to tell me if my value is within range
for example if it's daytime and humidity is between 2 values, then I am trying to set this "3rd" sensor to 'on'
you're describing an automation
you wouldn't use a template sensor ?
you could, but I guess I'm taking the next step and thinking that you want to do something with the output of that 3rd sensor
well I wanted to track that 3rd sensor with the history platform
ok
I'm monitoring some temp and humidity sensors, and tracking if I am within safe range and how often
I could use an automation and a "counter" but I figured that was sloppy and history would do a much better job
If I use an automation (or node red generated automation) would it imply any type of delay vs a template sensor?
so if I wanted to use an automation to determine the 3rd sensor
do I define it in my config.yaml and what platform would I use?
wait
you can use a template binary_sensor for that
as you had suggested earlier. if all you want to do is record and monitor the output
yea I just need to calculate if I'm in range and track how often
yeah but I can't use history stats until after a sensor has a value
well it will, won't it?
I am going to use history_stats to track the 3rd sensor but I have to calculate and populate the 3rd first
and?
the logic to use?
I thought I had it figured out but I'm spinning my wheels. I get the logic but not how to define it
{{ low_value < states("sensor.temp")|float < high_value }}
I feel like I'm hopeless where are you saying I should put that, in an automation?
in a template binary_sensor
this is the new format that I haven't used personally, but somethign like this:
template:
- binary_sensor:
- name: Temp Within Range
state: '{{ low_value < states("sensor.temp")|float < high_value }}'
should create binary_sensor.temp_within_range
so that does the first half? creates a sensor that tells me if its in range
but the range is conditional
based on day or night
(not in the real world, a separate status)
should i modify the lines to define if statements for that ?
template:
- binary_sensor:
- name: Temp Within Range
state: >-
{% if is_state('sun.sun', 'above_horizon') %}
{{ day_low_value < states("sensor.temp")|float < day_high_value }}
{% else %}
{{ night_low_value < states("sensor.temp")|float < night_high_value }}
{% endif %}
that's the demonstration one right
I just wrote that
oh ok
when I say day/night
i'm not talking about time of day
it's a status of my environment
you can put whatever you want in the "if" clause
I'm just showing you the syntax
thanks for your help rob I am going to go play around with this π
you can do "and" and "or" and parentheses and other stuff to further complicate it
np
{% if states('binary_sensor.awake') = 'on' %}
This is what I'm using
TemplateSyntaxError: expected token 'end of statement block', got '='
You used = instead of ==
I think I'm functional now:
{% set day_low_value = 53 %}
{% set day_high_value = 59 %}
{% set night_low_value = 51 %}
{% set night_high_value = 63 %}
{% if states('binary_sensor.awake') == 'on' %}
{{ day_low_value < states("sensor.tasmota_am2301_humidity")|float < day_high_value }}
{% else %}
{{ night_low_value < states("sensor.tasmota_am2301_humidity")|float < night_high_value }}
{% endif %}
Should work. You can play with the sensor value in
-> States
You may want <= for one of the limits
Or both. Or neither
ok works in dev tools template test
trying to add into my sensors-binary.yaml
- platform: template
name: humidity_correct
state: >-
{% set day_low_value = 68 %}
{% set day_high_value = 72 %}
{% set night_low_value = 53 %}
{% set night_high_value = 57 %}
{% if states('light.grow_light') == 'on' %}
{{ day_low_value < states("sensor.tasmota_am2301_humidity")|float < day_high_value }}
{% else %}
{{ night_low_value < states("sensor.tasmota_am2301_humidity")|float < night_high_value }}
{% endif %}
configuration checker says : Invalid config for [binary_sensor.template]: [name] is an invalid option for [binary_sensor.template]. Check: binary_sensor.template->name. (See ?, line ?).
You need to follow the docs; https://www.home-assistant.io/integrations/template/#legacy-sensor-configuration-format
Either use the new format I wrote above, or the legacy format you seem to be using
but where do i put your format above?
You have something in between now
inside a sensors yaml?
Just read the docs
See how they differ
Note thereβs no name: there
Which is what the error says
oh you're saying the new format does use name
The old format doesnβt
but I'm trying to use the old format but keeping your "name" entry
Docs
@low blaze are you using packages to split the config?
I made a few yamls yes to split up the config
maybe thats making the new format not work
yes
Itβs not
no?
Includes are not packages
I guess i don't know what a package is
I recommend spending some time with the docs
ah crap i just dropped in and didn't even really read
my bad yall
it is a bit annoying that name is for the new ones, but the old ones have friendly_name
the bigger annoyance for me is that the new format doesn't work with packages
@formal ember posted a code wall, it is moved here --> https://paste.ubuntu.com/p/BST4wNFCMT/
@formal ember posted a code wall, it is moved here --> https://paste.ubuntu.com/p/dnPNtmhBQw/
woops, it was under 15 lines, dunno why it did that
anyway, if anyone cares to take a look, its all here π
So the paste itself is line numbered π€
And try following this @formal ember
https://www.home-assistant.io/integrations/cover.template/#configuration
Looks like you have your first two lines reversed
And is it passing a cli config check?
yeah it passed
The UI config check or a cli config check?
UI, whats the cli one?
hmm which two are they?
https://www.home-assistant.io/docs/tools/check_config/
There is a bot message if I can find it. You are better off learning how to do a command line config check
Enable the "Configuration" section of the UI by adding config: to your configuration.yaml file, visit the docs page for more info.
you bewdy
Not that one
oh
Did you compare it to the docs?
Always run the configuration check command when you make changes. Don't trust the UI check - it misses some problems.
Really, as cover: is top-level in the docs
ah sorry, I am inside a cover.yaml file
cover.open_cover and cover.close_cover may have to replace switch
and i didn't have the !include in my config.yaml
sweet all has worked I think π
- platform: template
covers:
bedroom_blind:
device_class: blind
friendly_name: "Bedroom Blind"
value_template: "{{ is_state('cover.bedroom_rollerblind', 'closed') }}"
open_cover:
service: switch.turn_off
entity_id: cover.bedroom_rollerblind
close_cover:
service: switch.turn_on
entity_id: cover.bedroom_rollerblind
stop_cover:
service: switch.turn_{{ 'on' if is_state('cover.bedroom_rollerblind', 'off') else 'off' }}
entity_id: cover.bedroom_rollerblind```
there we go. now, how tf do I add in the icons to that one?! haha
read the docs
Yes, I think it is in that same link
icon_template: >-
{% if is_state('cover.bedroom_blind', 'open') %}
mdi:window-open
{% else %}
mdi:window-closed
{% endif %}```
so, it shows as Open if it is fully open, but closed if it is anything else
and on top of that, calling the service cover.close_cover to the new entity does nothing, matter of fact any service call does nothing
Well, what states do your blinds support? If there are other states, add them to the template.....closing comes to mind
But you can only do what your blinds support
And you still have your service defined as switch.turn_off
ah will take a look
should the service be that of cover.close_cover etc?
bedroom_blind:
device_class: blind
friendly_name: "Bedroom Blind"
value_template: "{{ is_state('cover.bedroom_rollerblind', 'closed') }}"
open_cover:
service: cover.open_cover
entity_id: cover.bedroom_rollerblind
close_cover:
service: cover.close_cover
entity_id: cover.bedroom_rollerblind
stop_cover:
service: cover.{{ 'open' if is_state('cover.bedroom_rollerblind', 'close') else 'close' }}_cover
entity_id: cover.bedroom_rollerblind```
trying this
right so https://pastebin.ubuntu.com/p/xbDrJ2PpMH/ gives me a slider like the normal cover entity to set the position, but I can only slide it to the extremes, as in 0 or 100. think i would need to put in a state attribute of the %?
I've noticed this as well.. now my configuration.yaml has an additional line π
so have done some reading. the finished product, although not 100% happy with it https://pastebin.ubuntu.com/p/YwS75tYbN8/
Sorted it out with the set_data_position, in particular the data field
Think thereβs a way to list the state attributes such as battery, link quality etc like the original one has?
I moved to a new house that has garbage every week and recycling every two weeks. I have been looking at examples on the forums for templates but can't get anything to work. I was hoping for a single automation with a template for the notification method that if week = odd then Garbage else Garbage and Recycling. Anyone have an example to go by?
{% if (not now().isocalendar()[1] % 2) %} Garbage Day {%else%} Garbage and Recycling Day {%endif%} Seems to work, can anyone check it. It returns Garbage and Recycling which is true for this week.
@dark sparrow posted a code wall, it is moved here --> https://paste.ubuntu.com/p/8WgsnXPTzt/
10 lines of text is a code wall π
Ah well. I'm trying to figure out the templating with a custom timestamp. it comes in as an integer, so the template functions don't seem to work with it. I could use a few more clues!
If I change to {% set data = { 'timestamp':'20210510141920' } %}, the time functions work. So is there a way to convert the data to a string value?
Found something that works, {{ strptime("{}".format(data.timestamp), "%Y%m%d%H%M%S").year }}
Hey guys I created this icon_template {% if is_state('sensor.alarm_state','Armed Home') %} mdi:shield-home {% elif is_state('sensor.alarm_state','Alarm Pendingg') %} mdi:timer {% elif is_state('sensor.alarm_state','Armed Away') %} mdi:shield-car {% elif is_state('sensor.alarm_state','Armed Nightt') %} mdi:lock-open {% elif is_state('sensor.alarm_state','Alarm Disarmed') %} mdi:shield-off {% elif is_state('sensor.alarm_state','Alarm Triggered') %} mdi:alarm-bell {% else %} mdi:lock-question {% endif %} , but now I want to have the different states show in a different colors without needing to create a new template. Is that possible
You can only color an icon using custom lovelace cards or integrations, meaning that it will always be a separate template
Can you .split between two characters and take what is in between them?
are you still trying to get the "?" back for your dad jokes?
there's only empty space between two characters
Lmao....naw but last night got me template motivated to clean some things up
(192.168.1.1)
Just pull out the ip
extract the part between the parens?
doesn't matter
Well...for my jinja knowledge it does π€£
does Jinja do slices?
it would be [1:-1]
So .slice
if the string is (dslkfjalskdjf)
sigh, changed it at the last sec
But there is more to the string than that
You can lazily split on the ( and then ) and take [-1][1]
Regexπ€’
or regex
regex is terrible in the HA jinja EVN
its been on my list to change but I always forget
regex_search or match returns indicies
my_string_var.split('(')[-1].split(')')[0]
But you canβt do something like .split(β(β:β)β)
lasiest way
Thatβs ugly
yep
But it errored
π€·πΌββοΈ
ah just cleaning up
Yes...just fart around in template editor till it works
Trying to template out illegal logins to replace IPs with known local devices
ah, in the long run you might need regex if you get some ( that don't have closing )
Because......kids
ah
{{message}} set by Ledeus I think is pretty standard
ah ok, yeah you should be good then
petro, so if I have door& window/motion/humidity/temp/smoke& co sensors, I would need to create a icon_color template for each item group?
any ideas why round isn't rounding? {{ states.sensor.upstairs_temperature.state | float | round(2) - states.sensor.downstairs_temperature.state | float | round(2) | abs | round(1) }} results in 5.200000000000003
ah wait, maybe I answered my own question. Order of operation issue... {{ (states.sensor.upstairs_temperature.state | float | round(2)) - (states.sensor.downstairs_temperature.state | float) | round(2) | abs | round(1) }}
Not just order of operations. The order matters but only because you're doing it after you've performed floating point math.
Floating point math gives weird precision in some cases.
Can a template God help this lowly peasant out? I have a template cover in order to invert the state of a cover, however it doesn't have any of the extra info that the original incorrect entity has, such as battery life, link quality etc. Is there a way to add these attributes to the template cover i have made?
Hi guys. Having trouble with a template in an automation. Here is the code:
https://www.codepile.net/pile/k5j0vDYv
The idea is notify through telegram which battery is low, for test purposes im using cover position and the message either doesn't arrive to telegram or gives me a blank space in the template
I tried trigger.name and trigger.friendly_name with no luck
Any idea?
I'd bet that the problem is the device trigger
Look at https://www.home-assistant.io/docs/automation/templating/ - device triggers aren't mentioned
Been doing some tests with a state trigger instead of device. Managed to use trigger.from_state.state. But trigger.entity_id not working
I also tried trigger.to_state.attributes.friendly_name and didnt work eithrr
Solved setting the optional argument "parse_mode" in telegram bot to html.
I focused too much in the template itself rather than the actual notifier
By extra info do you mean attributes? If so then no, there's no way to do that. Template covers don't have an attributes option like template sensors and binary sensors. That means the only way to add attributes to it is via customization and those are constant.
But you can just break those attributes out into template sensors
awesome, thats a shame but thanks for the clarification
literally just for OCD'ness when you tap on the cover in the UI and see all the related entities
hm yea that is nice
worth a feature request if you can't find an existing one. Template covers are part of the template platform so it could support those, just doesn't have that option right now
feature requests go on the forum in the feature request category
thanks mate
give it a tickle π
Will a wait_template have to go in the Action part of a automation? I'd like to have it before that...
It can be the first action, which fires as soon as the automation does... I'm not sure how it could be before that π
Ah, ok. Thanks. Problem I have is a sensor that isn't fully updated (after HA restart) when conditions are evaluated, so trying to wait until it is....
You can put the whole template inside an if-not-null kinda thing to prevent that.
That is interesting... How would I write something like that?
This is the template I want... wait_template: "{{ states('sensor.avg_illumination') | int > 0 }}"
This is the automation btw... https://paste.ubuntu.com/p/467hXYc7d5/
Ah I usually use templates in sensors... Not sure why that can't just be a condition?
You got me thinking! I'll try the wait template in the sensor definition... As I read it only scripts support it, but kinda hoping... π
Probably isn't that easy...
Hey guys, I'm working on a switch template which will run the scripts to turn on and off the curtain. However, it only manage to run the "turn on script" but the switch's state does not update to "on" state. How do I get it to update its states without feedback? I'm not using input boolean because I need the switch to be controlled in Alexa (https://community.home-assistant.io/t/alexa-toggle-input-boolean/39180/17?u=unitedgeek) . Here is my code. https://paste.ubuntu.com/p/CHZ7wYPyb7/ . Any suggestion and direction to go bout this ? Thanks!
got it. I use another input boolean to provide a fake feedback for the switch. When the switch template on, the input boolean also on. vice versa with off.
@shrewd vault posted a code wall, it is moved here --> https://paste.ubuntu.com/p/ZcgV6QNrXm/
Are the brackets on the HS values necessary? I can't see how your rest command works but it looks like brackets would only complicate things?
I have tried earlier in blueprints, I will try here since the problem I have is template related too...
What is wrong with this, I get unhashable type: 'list'...
action:
- condition:
- condition: template
value_template: "{{ trigger.payload_json.action }} == 'toggle'"
Moving == 'toggle' inside }} doesnt help either
I have tested the template using system_log.write, it returns True
You have double-nested conditions.
You need to make it something like:
action:
- condition: template
value_template: "{{ trigger.payload_json.action == 'toggle'}}"
What do you want to do with a condition within an action:? Either your condition should be in condition: and not in action, or it should be within a choose:
I grabbed it from an automation on the zigbee2mqtt website though there it was a trigger not an action
Conditions within sequences can actually be handy if you just want to interrupt the flow of an otherwise linear sequence.
@deft timber I left out the rest of the code for brevity
ok that fixed it thanks, I take it conditions is only if you are using multiple condition checks?
If you are anding/oring
@glacial oxide https://www.home-assistant.io/docs/scripts/conditions/
@nocturne chasm Yeah I have realised my errors now
Thanks
Is it possible to test the state of a target in a template?
Target?
The variable of a target selector
You can get the state of anything in HAss that has an entity
I donβt get blueprints so, you should ask over in #blueprints-archived
Yeah I have asked over there, I think the answer will be no and I will have use entities and groups
If itβs not in dev tools / states, you canβt get the state. I believe the target_selector is a drop down in blueprints though. Reference your question, loop through the state of the lights in your group
Thanks
so i am using the sense energy monitor integration, and I am trying to create some additional sensors to track From Grid and To Grid... is there a way when creating the template sensor to only update the state/value of the sensor conditionally, in my case "To Grid" I would only update the state/value when "From Grid" is negative. "From Grid" is calculated by subtracting. energy_production from energy_consumption
hi (:
I'm trying to do some automation templating is this the right channel to ask for help ?
yep
Hello
I'm trying to make a restful switch to enable/disable a rule in my firewall. The switch works but i i try to make a template to check if it it is enabled or disabled.
The switch configration looks like this: https://hastebin.com/imebunaqal.less
The output from the api call looks like this: https://hastebin.com/ufavedadaq.json
The value i want to use is status under the results section (or what you call it)
I have tried a template like this:
is_on_template: "{{ value_json.results.status == enable}}"
Any idea what i'm doing wrong?
quotes on enable
i give it a try
Worked!
the line ended up looking like this as there is an array:
is_on_template: '{{ value_json.results[0].status == "enable"}}'
is this not a valid template condition?
- condition: template
value_template: '{{ trigger.to_state == "on" }}'```
to_state represents a state object. You still need to read the right field from that object.
Hey, can i somehow use something like
{% set sensor = { "entity": "bla bla" } %}
for a is_state like:
if is_state({{ sensor.entity }}, "bla")
What are you trying to do?
that example gives me a error, and is_state("{{ sensor.entity }}" doesnt work, i couldnt find anything on google or the forum.
basically setting a var with a name, and 2 entites to use in a one lined, rather complex (for my liking) template string. i would have to replace the sensor entites like 6 or 7 times in a single line of that, and i need multiple
so i tried to just store it in a var that i only have to replace that for the other lines i need.
Show me the original that you're trying to make simpler.
{% if is_state("binary_sensor.rauchmelder_buro_alarm_smoke_2", "on") or is_state("binary_sensor.rauchmelder_buro_alarm_heat_2", "on")%}{{ states.binary_sensor.rauchmelder_buro_alarm_smoke_2.room_name}} | {{states.sensor.rauchmelder_buro_temperature_air_2.state}}Β°C |{% if is_state("binary_sensor.rauchmelder_buro_alarm_smoke_2", "on") %} SMOKE {% endif %}{% if is_state("binary_sensor.rauchmelder_buro_alarm_heat_2", "on") %}| HEAT {% endif %} {% endif %}
output is supposed to look something along those lines.
And you just want to remove the repetition of the entity ID's?
yeah kinda
i need like a total of 5-15 lines of that in a single template, that would be a mess to debug and change.
You're not going to get it much shorter. Most of your code is the logic and what you're trying to output.
You don't even repeat the same thing often. Even where you repeat a value, you'll use a line to set a variable just to save referencing it twice - that's not a saving.
yeah ok
is it technically possible tho?
bcz that line might get even more complicated, thats just the start so far
Everything is possible. I just don't think it's worth the time or effort here to bother.
I've started changing this, you should get the idea:
{% set smoke = states.binary_sensor.rauchmelder_buro_alarm_smoke_2 %}
{% set heat = states.binary_sensor.rauchmelder_buro_alarm_heat_2 %}
{% set air = states.binary_sensor.rauchmelder_buro_temperature_air_2 %}
{% if smoke.state == 'on' or heat.state == 'on' %}
{{ states.binary_sensor.rauchmelder_buro_alarm_smoke_2.room_name }} | {{states.sensor.rauchmelder_buro_temperature_air_2.state }}Β°C |{% if is_state("binary_sensor.rauchmelder_buro_alarm_smoke_2", "on") %} SMOKE {% endif %}
{% if is_state("binary_sensor.rauchmelder_buro_alarm_heat_2", "on") %}| HEAT {% endif %}
{% endif %}```
It adds 3 ugly lines at the beginning to save almost nothing.
maybe i could do a array with all the sensors, that would probably make it a lot smaller
π€
I have no idea why you'd want to do that. However you do it, you still have to both assign and access your variables. All you achieve by using variables is saving a few characters of typing (and only if you're actually repeating things).
when completely done i will have about 5-15 of these lines
And? You'll still have crap like this:
{% if smoke.state == 'on' or heat.state == 'on' %}
because you still need to access the right part of the state objects you assigned to your variables earlier on.
In some places you want the state, in others you want the room_name. Variables aren't the hail Mary you think they are in this case.
lol fair
hi Iβd like to create a condition template to check the MQTT trigger payload of an automation
If the key βRfRawβ in payload
If the key βDataβ in [RfRaw]
Then if the 2,conditions are met
If a sub string is in the [Data] string
If all 3 conditions are met run automation
You just need to think ahead a bit, you're not reusing things properly and that's making it ugly. Also, you're checking to see if smoke is on and heat is on... inside an if statement that already checks if smoke is on and if heat is on. You can't really see that because you aren't formatting the code in a readable fashion. Code isn't about being condense, it's about being readable.
{% set smoke = expand('binary_sensor.rauchmelder_buro_alarm_smoke_2') | first | default %}
{% set heat = is_state('binary_sensor.rauchmelder_buro_alarm_heat_2', 'on') %}
{% set air = states('binary_sensor.rauchmelder_buro_temperature_air_2') %}
{% if smoke.state == 'on' and heat %}
{{ smoke.room_name }} | {{ air }}Β°C | SMOKE | HEAT
{% endif %}
and if you want the 'least amount of lines...
{% set smoke = expand('binary_sensor.rauchmelder_buro_alarm_smoke_2') | first | default %}
{% if smoke.state == 'on' and is_state('binary_sensor.rauchmelder_buro_alarm_heat_2', 'on') %}
{{ smoke.room_name }} | {{ states('binary_sensor.rauchmelder_buro_temperature_air_2') }}Β°C | SMOKE | HEAT
{% endif %}
what have you tried? No one's going to write the code for you. They'll be willing to help fix your code.
Iβll send the code as soon as I get back home
So just as an Idea of what I'm trying to do
I have a Sonoff RF Bridge that suddenly just decided to not receive any RF codes
So my automatons stopped working ... I tried everything from resetting the bridge to re-flashing it
I then tried the new method of the Portisch Firmware with tasmota
At first nothing happened, when I triggered the PIR sensor the RF Bridge should've picked up the RF code coming from it
but when I entered the rfraw 177 command it started picking up the RF data
Now comes my current issue, the RF data picked up with the rfraw 177 always changes, except for a code in the middle
I want to write a template condition to check the MQTT trigger payload and see if there's an RfRaw key in there, then if there is it checks if that key has a Data key inside it
If there is Data key check if there's a certain string in that Data value
if there is return a value of True (:
- id: bathroom_motion_on
alias: Bathroom motion on
description: Set bathroom motion sensor state to on based on MQTT trigger
condition: "{{%if '28181818190908190909090819090908190908190818181909' in {{trigger.payload_json['RfRaw']['Data]}}%}}"
trigger:
- platform: mqtt
topic: tele/RF_Bridge/RESULT
action:
service: input_boolean.turn_on
data:
entity_id: input_boolean.bathroom_motion_detected
here's the code i've written so far
The problem is
1 idk how to do nested IFs in jinja2
2 how do I check if the keys Rfraw and Data in the payload
Nested if is not different from any if
Checking for keys usually takes the form of βkeyβ in dict
that's python syntax (:
does that work for jija as well ?
Yes
can you write an example please ^^
There are lots of jinja docs out there
yeah the official jinja doc confuses me tbh π
something like {{ 'key' in trigger.payload_json }}
Ok thanks I'll try it
thanks for helping (:
this is from a Google hit: https://stackoverflow.com/questions/27740153/check-if-key-exists-in-a-python-dict-in-jinja2-templates
Hm... I used to have this under sensor: in configurations.yaml just to round the digits. Can the same effect be achieved in a better way? Redefining a sensor seems odd?
# hallway_motion_temperature:
# friendly_name: 'Hallway - Motion Sensor'
# value_template: '{{ states("sensor.hallway_motion_temperature") | round(1) }}'
# icon_template: 'mdi:thermometer'
# unit_of_measurement: 'Β°C'
Better how?
Don't know. I just though that defining a second version of the same sensor made little sense, but if that is how to do it, then all good π
I was thinking of perhaps using customize.yaml, but don't see how
If you want it to display differently, some cards allow templates... but as soon as you're using it in two places, you're repeating yourself somewhere else instead.
The one I use now is the entity itself, but really want to round that value, so what I did wasn't wrong then?
If it works, it can't be wrong.
Bit weird to have a circular reference... personally, I would've called the new sensor something else.
It has a different name, or had when configured...
As mono said, you typically only care about precision when displaying the value, and many cards allow you to round there
Guess I'm using too simple cards then. I have only default ones, showing entities. Perhaps time to upgrade some of them. I haven't paid much attention to where I would find such cards. Is there an official GitHub or lots of different ones I need to search for?
Home Assistant Community Store is the successor to the old Custom Updater, and can do so much more - you should check it out. They even have a Discord server for issues with HACS itself.
Wow, perfect! π
@earnest schooner posted a code wall, it is moved here --> https://paste.ubuntu.com/p/cqF99k6222/
oops.. guess I posted a code wall :/
I'm having a really difficult time getting a customized entity that will show the state of the garage door. Can anybody point me in the first direction? This is what I have in my configuraiton.yaml
Use an mqtt binary sensor instead of an mqtt sensor. Then apply the device class garage_door.
This will not only give you open/closed states but changing open/closed garage door icons as well.
thanks
that worked, thank you. Templating makes me remember how much I hate yaml π
Is a template able to adjust the colour of the icon of a sensor depending on the state? i.e. a temperature one?
Cheers Rob, just found something about being able to do it via customize. will head to frontend if I get any more issues with it
is that a HACS thing?
I donβt know how itβs distributed anymore
hmm, just want to top my UI off after copying yours π although I did make some changes and it looks quite different
Mine is almost entirely custom button cards, which allow for color changes based on state
I'm struggling to think of how to sum the last 24 hours of rainfall from the openweathermap_rain sensor. It has the rain volume for the last hour
I use a statistics sensor for such things
max_age of 24hrs? what about sampling_size
of samples, so 24
Hey, I want to be able to see the state of a program running on my pc. For example, I would see that Google chrome's state is set to true
and how does that relate to this channel?
Aight thnx
I'm finally getting around to fixing some broken templates that the mqtt.publish service uses on a vacuum lovelace card to set the parameters for it. The error from the UI pops up quickly and seems to indicate my template needs to be sending a string. It is currently set to generate a json payload based on the state of an input_datetime set in the card. So with that background, here are my questions: ```
- The error that pops up in the browser does not appear in the logs. Is there a place I can go review those errors with a little more time?
- What was the general date of the changes in the templating system? I've been going through the last year's breaking changes because I remember one of the releases centering on template changes but haven't been able to find it yet.
- The docs say "It is strongly recommended to use 'states(sensor.temperature)'... In the dev tools, when I put my template in that form it doesn't work.
works: "start_time": "{{ states.input_datetime.vacuum_start_time.state }}"
doesn't work: "states('input_datetime.vacuum_start_time')"
What am I doing wrong here? And do I need to change this format?
Thank you.```
Any advice on what is wrong with this template within an mqtt switch? it's for a tasmota ifan03. The speed controls work, but using the on and off toggle, it doesnt show as on. ever. If i switch it on using the toggle, the button switches back to the off position.
{% if value_json.FanSpeed is defined %}
{% if value_json.FanSpeed == 0 -%}0{%- elif value_json.FanSpeed > 0 -%}4{%- endif %}
{% else %}
{% if states.fan.ceilingfan.state == 'off' -%}0{%- elif states.ceilingfan.state == 'on' -%}4{%- endif %}
{% endif %}
one of these? https://www.home-assistant.io/integrations/switch.mqtt/
Yes, my config is for a ceiling fan. my full config is here.
https://pastebin.ubuntu.com/p/r8YCncRSxX/
it is controlling the fan as expected, but doesnt seem to be showing corectly in HA.
in the command view on the fan when it is turned on, i can see:
20:38:58 MQT: stat/ifan1/RESULT = {"FanSpeed":1}
you're using the wrong values for payload_on and payload_off
your template is reporting 0 and 4, but these are your on/off definitions:
payload_off: '0'
payload_on: '1'
looks like you followed some of this, but not all of it: https://tasmota.github.io/docs/Home-Assistant/#fans
Everything about using Tasmota in Home Assistant
I've not seen that. I'll try and figure out where i've gone wrong from there.
thank you.
the payload when on can be anything from 1 to 4 does that make a difference?
you just need to be consistent in what you report and what you're checking
your logic sets it to 0 if it's 0 and 4 if it's greater than 0
so 4 just needs changing to 1 right?
the easiest thing to do is to follow the docs above and use this:
payload_on: '4'
you can use whatever you want, just be consistent
Thanks, I thought that the payload had something to do with reported state on the tasmota fen.
fan^
only if you don't specify state_value_template. if you do, then you're deciding how to interpret what it reports and how to indicate that to HA
ahhh, ok thank you. I assume that if i have retain: true in the config, it will keep the state after a HA restart is that correct?
it retains the state in the MQTT broker for HA to read when it restarts
great! Cheers.
got it sorted now. I found that using 4 meant that when i just pressed the toggle to put the fan into low speed mode, it didnt work, so changed all values to 1, and that is now working on the toggle and when the speed is set. Thank you.
supported_color_modes: - hs color_mode: unknown
in my template light entity. how to set color mode in yaml?
hello, I'm defining a MQTT Light, and I'm using unique ID, but it's not using that, can anyone help?
defining in yaml?
yes
unique_id: light_00_all
name: "Light all"
state_topic: "light/BBFF"
command_topic: "light/BBFF"
state_value_template: "{{ value_json.state }}"
payload_on: "On"
payload_off: "Off"```
and it gets light.light_all and not light.light_00_all
An ID that uniquely identifies this light. If two lights have the same unique ID, Home Assistant will raise an exception.```
unique_id != entity_id
can I set the entity_id?
I unerstand that
what I want is to "fix" the entity_id
derived from the name field
so I can change the name, and not change the entity_id...
which is derived from name so you're changing both
once they're in HA if you set unique_id you can customize the entity
I've just removed the unique_id from all devices π
feelsbadman
why my template_light
supported_color_modes: hs, color_mode: unknown 
I have this:
name: "Light 00 all"
unique_id: light_00_all
state_topic: "light/BBFF"
command_topic: "light/BBFF"
state_value_template: "{{ value_json.state }}"
payload_on: "On"
payload_off: "Off"```
and the entity it's light.light_all
why?
try
light:
- platform: mqtt
your_light_X:
name: .....
unique_id: ....
Visual code says "property your_light_x is not allowed"
I guess you want the entity id to be light.light_00_all?
This is a question for #integrations-archived, actually, but I think HA checks for entities which already has the same unique_id and will use that. Try changing the entity id from the UI.
Configuration
-> Entities
I have arround 80 entities... it's not pratical to do like that π
but I think it's an option... not pratical..
if I can choose on yaml it would be better...
I want to check if the temperature in one room is at least 5 celsius lower than another room inside an automation condition
how would I go about it? I know how to check if one number is bigger than the other, just not how to check if the difference is higher than 5
absolute value is your friend
{% set sensor2 = 5 %}
{{ (sensor1 - sensor2)|abs() }}```
that'll ensure you always have a positive number
so then you can do {{ (...)|abs() > 5 }}
I'm trying to use a cover template to tie together a binary sensor and a relay into an object to represent my garage door. State monitoring works fine, but when I click the UI element, the mqtt command never gets sent to the device. I've monitored the mqtt messages on the device itself, and listened to that topic from ha's mqtt broker. State works fine, but the command never gets sent. ideas?
`cover:
- platform: mqtt
name: "Garage Door"
unique_id: garage_door_opener
device_class: garage
state_topic: "tele/garagecontroller_0051BB/SENSOR"
command_topic: "cmnd/garage_controller_0051BB/power1"
value_template: "{{ value_json.Switch4 }}"
state_open: "OFF"
state_closed: "ON"
payload_open: "1"
payload_close: "1"`
ugh.. nevermind.. just figured it out. Needed to set the correct action, service, and target on the button card. /facepalm
how to reject a state and not an attribute instead of this rejectattr while mapping
| reject?
@native pilot posted a code wall, it is moved here --> https://paste.ubuntu.com/p/Tyq4rY85nk/
Tried to protect this template from division by zero but it still fail, why?
states are strings, so you need |float
reject('eq','state') ?
@fossil hearth When using Discord's new Reply feature it defaults to pinging the person you reply to, which can get frustrating for the target. Click @ ON to @ OFF to stop this - on the right side of the compose bar.
And if you read the docs, it'll tell you that you have to pass a test in. The docs also explain how tests work.
Ive lots of zigbee devices which all expose the battery level as different names (and some devices even report values which fluctuate due to temp). Anyone know of a generic template which can alert me to low battery level? I found an old template on HA forums, but couldn't get it working
I'm looking to make a template sensor that updates with the delta to next x weekday (say, days untill wednesday for example), I have no idea where to start apart from a time_pattern triggered sensor.
good afternoon guys,
I use this mqtt template sensor:
- platform: mqtt
name: "Room Humidity"
state_topic: "tele/Wemos2/SENSOR"
value_template: "{{ value_json['AM2301'].Humidity | float - 0 | round(1) }}"
unit_of_measurement: '%'
availability_topic: "tele/Wemos2/LWT"
payload_available: "Online"
payload_not_available: "Offline"
works fine, but it does not round up the decimals,
any clue how to do it ?
Thank you
Because you're rounding 0
corrects the value shown on lovelace, i.e. -10 will turn 50 to 40 and so on
left it there for future calibration
the prob is that a lot of times I have values like 50.9999666545 %
which is not very useful, 50% or even 50.9% would be fine
I get why you're rounding, but you have a pemdas problem but | go first
I dont understand you, what should I correct in my code?
Remember how you had to group things in grade school maths? Same thing here
and...
And I've given you enough hints to figure it out
in here: https://www.home-assistant.io/docs/configuration/templating/
it has the same thing: {{ (states('sensor.temperature') | float * 10) | round(2) }}
I dont see how is this different from what I posted above
There is one very key difference
which is?
I'm not going to hand hold you, you're going to need to work it out so you actually learn
added the 2 paranthesis, restarting HA...
Random fact: it's BODMAS/BIDMAS in the UK, depending on which school you went to π
Brackets, Orders, Division/Multiplication, Addition/Subtraction
The 'I' in the alternative version is for indices. π€·ββοΈ
Im from Greece, so we were taught them paranthesis, I had to look up what pemdas is
hey. I'm trying to create a binary sensor from an event, and I can see that we now have trigger based template sensors. how do I set the binary sensor based on data in the event though? the event type is too generic
Ok now !!!
Changed the code to:
value_template: "{{ (value_json['AM2301'].Humidity | float - 30.0) | round(1) }}"
restarted HA and it worked
Thank you @dreamy sinew
Dont know about code, Im from another field, but I am learning (painfully π )
Don't worry - figured it out by creating an event trigger in the UI, then viewing the resulting yaml π
hey guys I am trying to create a icon_color template icon_color: > {% if is_state('group.security_sensors', 'on') %} return 'rgb(0,255,0)' {% elif is_state('group.security_sensors', 'off') %} return 'rgb(0,0,255) {% else %} fas:alert {% endif %}, but I am getting this error Invalid config for [sensor.template]: [icon_color] is an invalid option for [sensor.template]. Check: sensor.template->sensors->doors->icon_color. I would like to have the icon change color based on the state of the sensor. Can anyone help me sort out what I am doing wrong?
Thereβs no βicon_color:β option for template sensors?
Hey guys! I'm having a pretty frustrating issue. I've been trying to get an automation working for months now, and just FINALLY discovered the problem. Some lights have the brightness attribute, while others don't. I have no way to explain this. They're exactly the same type of dimmer switches. Can anyone help me? I'll send the attribute lists of each
@pliant patrol posted a code wall, it is moved here --> https://paste.ubuntu.com/p/3H3tXgX9Dt/
That was like 12 lines but ok :p
As far as the bot is concerned, that's 21 lines.
I see, I assumed it would account for formatting syntax
The name "code wall" is missleading.
gotcha
You know what, I just realized the brightness attribute disappears when the light is turned off. Durr. So I still haven't found my issue.
Would someone be willing to help me out? I'm trying to template an InfluxDB query in configuration.yaml. The date-part should be evaluated and enclosed by single quotes. I've been trying different things, but can't seem to manage. https://pastebin.com/xnH27sK8
Can a template be created using y=mx+b ?
gonna need more context
I have a receiver that measures in (-) dB and the media player cards use 0-100. I'd like the media player card to reflect the same as the receiver. Easy to derive slope intercept from.
you can do math in a template
can the templates use variables?
Jinja is used by Home Assistant's template engine, see the Jinja Template Designer Documentation
need to fix that. here's the template docs
https://jinja.palletsprojects.com/en/3.0.x/templates/
you can do basically anything there
yeah lol. thanks
Can they run Crysis?
Can someone help me create a "time since last restart" template sensor using the uptime sensor? not sure where to start
there's a forum thread about it: https://community.home-assistant.io/t/uptime-in-days-hours-and-minutes/180916/4
how do I manage file splitting with template?
@brazen spear posted a code wall, it is moved here --> https://paste.ubuntu.com/p/nbDmpkQvYD/
you can't use the new template format in a package
So, I add template to configuration.yaml and include from there?
Are attribute_templates only calculated when the parent template sensor is evaluated based on the value_template or whenever any of those templates change?
That's more of a question for #integrations-archived but I believe it's when any of them change. It wouldn't make sense for attributes to only update when the state updates, otherwise you'd never get things like battery level updates for contact/motion sensors.
So.. Iβve been trying to do this myself for weeks but I need help: Iβve managed to get my Nest cameraβs showing in HomeKit using the integration but it doesnβt recognise the sensors (motion sensor, person sensor, or the doorbell). I understand that this is because they fire events rather than have sensor entities but, as I want homepod integration I need those. Decided to try to make a template sensor but Iβve never made one based on a trigger!? Iβll post what Iβve got so far but it might be embarrassingly badβ¦ would also welcome suggestions of any other methodsβ¦.
I made this by editing the trigger sensor off the template page.. but didnβt know what to put next. Also, I donβt know how to post this properly (Iβll go and find out now), so, as itβs only small, hope itβs ok to just c&p!
- trigger:
- platform: device
device_id: not sure if I need to censor this so have just in case
domain: nest
type: doorbell_chime
binary_sensor: - name: Doorbell Pressed
- platform: device
I think you might wanna take a different approach - use an input boolean rather than a template sensor to track states within HA, and use an automation with an event trigger to update those automations.
My use case is a little different - I have PIR sensors firing MQTT events, and the automation is handled by NodeRed, but tracking these with input booleans works great.
Thanks for the reply. I did this actually! I set up a select (options for doorbell: pressed, motion, sound, person, nothing) but itβs not very reliable and Iβm not sure how to make it reset? I told it to just go back to βnothingβ after 10 seconds because there doesnβt seem to be a trigger available for thisβ¦ but this is obviously quite inaccurate because the motion might still be there. It also limits the possibility of setting any βif motion is detected for more than ____ do ____β automations π
Is there not an event when the detection ends?
Perhaps.. sorry, Iβm still pretty newβ¦ I just know that the available triggers are just the detection βstatesβ
I'm no genius with HA myself so I'm not quite sure I know what you mean... I thought you were able to trigger off the events? (which aren't represented by a state in HA without this automation?)
I could be using the wrong word but I think theyβre βeventsβ. Basically, all I know about this integration is that it doesnβt have separate entities for the sensors as I expected (apparently this is by design) and that the only way HA seems to even recognise the sensors/button is if I set up an automation to triggered by βdeviceββ¦ and then I get the options motion detected, sound detected, person detected & doorbell pressed.
I tried to find something in the logbook but if I select the camera entity it says there are no entries. I understand thatβs because that is just the cameraβ¦ but is there a logbook for devices?
Hmm, yeah looking at the integration doco there's no mention of an end event.
You know how to see these in Dev Tools > Events right? That's where you'd see an end event, if it existed.
But someone else who actually has one would probably have way nicer advice π
Itβs not something Iβve used tbh, as far as I was aware that was for firing an eventβ¦ which I thought was to fake an eventβ¦ but yeah.. not used it π
Your attempts are much appreciated anyway!
It's both for firing and listening to events.
If you just type # in the listening field then click the button, you'll see everything, including the nest events (I think)
Wait, I'm getting totally confused with MQTT events, I think you just want nest_event in that box
In the βlisten to eventsβ bit?
Yup
So * (not # ) will show you everything for HA, nest_event should show you the Nest-specific ones. That's how I pull zha_event for my Conbee
Ah yes.. Thanks very much! I can see it change from motion to personβ¦ but when thereβs nothing it doesnβt seem to change at all
Hmm, does the proper Nest app show this in any way?
Could be a device limitation.
I just checked, they don't even sell Nests in Australia haha
I've previously used the legacy sensor templating to create entities from other entity attributes and states. I could then use a friendy_name_template to set the name based on the data.
I have started to use the new way of creating template sensors as described in https://www.home-assistant.io/integrations/template/
If I set the friendly_name under attributes in the new configuration, it doesn't affect the name of the new sensor entity. Am I doing this wrong or is the name not possible to update using a template using this new way of creating sensors from templates?
In templating / jinja is ther a way of converting a list like this ['item 1', 'item 2, ...] into a list like this:
- item 1
- item 2
- ...
What are you trying to do ? When a template is expecting a list to be returned, the template can return either
- item 1
- item 2
or [ "item 1", "item 2"] so I don't see the point of trying to convert one to another. The first representation is yaml, the second is jinja. But maybe I'm missing something?
It's purely for stylistic reasons. I was using an automation to output a list of entities that are currently unavailable or offline and then send that to myself in an email.
It's easier to read the list of entities in an email if it's in the YAML format rather than the bracketed format.
{% set l = ["item 1", "item 2"] %}
{% for item in l %}
{{"- "~item -}}
{% endfor %}
Thank you.
Or, shorter
- {{ l | join('\n- ')}}
Other than sending a notification, noβ¦ or at least I donβt think so. I guess Iβll give up and cry π
Trying to diagnose this new error message "Invalid config for [automation]: invalid template (TemplateSyntaxError: expected token 'end of statement block', got 'integer') for dictionary value @ data['action'][3]['data_template']. Got None. (See /home/homeassistant/homeassistant/configuration.yaml, line 4)." .... line 4 in configuration file is "group: !include groups.yaml", the next line is automations include.
The error message isn't really helping much.
It's the 4th action in one of your automations.
fyi this is kinda moot anyway, yaml accepts ['item', 'item2'] natively for lists and current HA versions will output it as a list type for yaml to consume
Hmm, I have about 70 automations and my automations file is 1600+ lines long ..
What was the last one you changed? Otherwise you'll have to do a binary search. Comment out half the automations, reload. If the error persists it's in the uncommented half, divide that in two with comments and try again. It will take you 7 tries to locate it at most.
what can be a reason I can filter an entity with regex on the template editor but once I create a template sensor I just get unknown ?
what can be a reason I can filter an entity with regex on the template editor but once I create a template sensor I just get unknown ?
Thanks, that was a useful approach. Found the error ... seems it decided it didn't like the leading zero in the comparison ... {% if now().hour < 07 %}
Yep. That will do it.
Regex has issues with the type of quotes. Can you show your expression?
False alarm. Damn typo π€¦ββοΈ
I remember that with the quotes. Needs to be reversed
took me ages the first time I played with regex
Thank you
how to sort mapping alphabetically ? |list | sort ?
output:
['S1', 'S2', 'S3', 'S4', 'S5', 'U10', 'U9']
Is it possible to format an entity output inside of the ui-lovelace.yaml . Something like entity: floor(sensor.temperature_1) ?
that would be a #frontend-archived question
oh, sorry, mixed them up. I'll ask there
so how to arrange so that U9 come first ? alpha-numerical sort ascending .. i checked the link.. its abit too much for me hehe...
it take 3 parameters ?
you don't. that's how it works for strings
ok ..
mixed #templates-archived and #automations-archived question but I ask here first: I try to send the last time a sensor updated to a retained mqtt topic. Is {{ ((as_timestamp(now()) - as_timestamp(states.sensor.esp32_03_temperature.last_changed)) / 60) | round(0) }} min the best solution for that?
As it will always be in the past you can use {{ relative_time(states.sensor.esp32_03_temperature.last_changed) }}
I just store the timestamp
Hm thanks
Apologies if this is the incorrect channel, I'm very green to HA and am struggling to understand if I've set something up incorrectly. I'm trying to extract the temperature from a weather object so that I can graph it together with my indoor temperature in a card on the lovelace interface. Googling suggested that my correct way to do this was to add a template to my configuration.yaml, and it does seem to properly create an entity with just the temperature, but when added to the history graph card it gets put as a new graph tracking 'degrees' instead of 'Β°F', despite it being set to Β°F in its config
I would share a couple screenshots, but I appear to be unable to post images
don't post images, post text
Please use https://paste.ubuntu.com/ to share code or logs. Please don't use Pastebin, since it can randomly add spaces to the main view.
specifically, the template definition
sensor:
- platform: template
sensors:
weather_temperature:
friendly_name: "Weather Temperature"
unit_of_measurement: 'Β°F'
device_class: 'temperature'
value_template: "{{ state_attr('weather.thermostat', 'temperature') }}"
maybe the unit_of_measurement and device_class are fighting each other. You can try to remove the device_class
I'm not sure where it's getting 'degrees' for the graph
I'll give that a try now
when I initially put in this template, the unit_of_measure was 'degrees', and I switched it to '
'Β°F' after seeing that it was showing up differently on the graph
but the change to Β°F never seemed to propagate. Would some dependent property have been written when I initially added the template and not updated when I changed my template in configuration.yaml?
No change after removing and restarting HA
When using Discord's new Reply feature it defaults to pinging the person you reply to, which can get frustrating for the target. Click @ ON to @ OFF to stop this - on the right side of the compose bar.
I'm not sure where it's getting "degrees", then
actually, it is possible that it's getting it from the recorded history of that entity with the old unit, as you suggested
that's probably what's happening
is there a way to clear that? or perhaps I need to make a new entity?
there's no straightforward way to remove the history for a single entity. removing the template definition, restarting and adding it again may help. Or reloading template entities in place of the restart
I'll give that a try, thank you
actually, there is this: https://www.home-assistant.io/integrations/recorder/#service-purge_entities
I wonder if that's recent π
Ha, 14 days ago: https://github.com/home-assistant/core/pull/48069
ahh, ok, I'll have to give that a try, as removing the template, restarting, adding the template, restarting left me where I started... probably picked the same data right back up from the DB
you might have to manually delete the entity from
-> Entities if it still shows up as "Restored" when you remove it from your configuration. eventually the old data will age out
If I'm understanding what you're suggesting correctly, manually removing the entity from there doesn't seem to be possible in the GUI; the checkbox I would use to select it to disable/remove an entity is greyed out, as it's read-only
the steps would be to remove it from your config, restart HA, see if it's still in
-> Entities, delete it if it is, add it back to your config
ahh, well I checked my entities after removing it from my config before and it didn't show up in entities anymore, so that didn't seem to do anything. I think I've puzzled out how to purge the weather_temperature entity, and there's not a second graph showing now... though there's no outdoor temp data either, but I wouldn't expect it to have anything until it polls some new data
you can use homeassistant.update_entity to force it
has the friendly_name config option been removed from the new template sensor config? Am i suppose to set it in the UI?
hi how to get last changed by name ... in template
in HA it says last changed to xx by yyyyyy ...
for what?
i need the last changed name of the person ( in the example that am trying is input_number)
log says for example: Changed to 9.0 by Linn
input_number.h8_mh this is my input number helper
i don't think that's stored on the state object
so can it be extracted by template ? :/
yeah i haven't seen it either anywhere , its only last changed and updated as in time ...
can it be detected in events ? so an automation can pick up and say who updated last and what maybe ?
aha
i have no idea ho to extract from context :/ but anyways if u can show me how to do it for an input_number.h8_mh as an example .. that would be great .. otherwise its fine i might be asking too much hehe thanks π
it won't be on the entity, it'll be in an event that fires
yes..
There are threads on the forum about extracting the user ID from the event
Didnβt realize you were waiting for me to write it for you, since you suggested it in the first place π
Thanks alot man am looking into it ! β€οΈ
Hello π Can someone please help me figure out why this simple code doesnt work? I'm just trying to apply a ratio to a sensor...
- platform: template
sensors:
ppfd_ubi:
value_template: '{{ ((states.sensor.light_ubi | float * 0.0014574)) | round(0) }}'
the sensor it creates only returns 0
Your syntax is wrong
i think that may be my bad copy paste job one sec, cant remember how to use the \ or //
unlikely. it's quite wrong
yep, still broken
i basically copied it from one of the home assistant tutorials and modified it, i know almost nothing about code :
{{ (states('sensor.light_ubi') | float * 0.0014574) | round(0) }}
ty β€οΈ
I see that kind of mistake a lot. states(xxx) is a function, you don't add filters in there
you'll need to change the quotes
remove the ' ' marks?
- platform: template
sensors:
ppfd_ubi:
value_template: "{{ (states('sensor.light_ubi') | float * 0.0014574) | round(0) }}"
Another way is states.sensor.light_ubi.state | float
but not recommended: https://www.home-assistant.io/docs/configuration/templating/#states
so I get to correct people all the time π
Didnβt know this, I though itβs more straight forward. thanks!
@swift hill posted a code wall, it is moved here --> https://paste.ubuntu.com/p/42HbHKCCXt/
Rule #6: Please do not post codewalls (text longer than 15 lines) - use sites such as https://paste.ubuntu.com/ (just not Pastebin).
Please take the time now to review all of the rules and references in #rules.
first, the templates should look like this:
value_template: "{{ state_attr('light.family_room_family_fan', 'brightness') | int < 130 }}"
it already returns a boolean
second, those triggers require a transition that makes that template true. simply being "true" isn't enough
third, it would help to have more detail on what's not working
@inner mesa Thanks for the reply. I thought that the template evaluating as TRUE would be enough to act as a trigger.
Home Assistant triggers all work on state changes
What do you mean by transition? Changing from one value to another? Because that's what I'm after.
you can trigger on any "brightness" change and then use a condition or template in the action to take instantaneous action based on the value
Any time the fan speed (brightness) moves above 130 or below 129, I want it to trigger.
Yeah, I think we're saying the same thing.
that template needs to start false and change to true for it to trigger
so what's not working?
Let me try your revised templating. Maybe that's the problem (though if it is, I don't understand why the template editor woudln't catch it). Hang on a sec while I try it out.
if might return "false" if it fails the "if" test and there's no "else" clause, but it's not great
Can anyone give me pointers on how to learn to get an automation for example to both turn a light on and off in a single automation?
@stark hare posted a code wall, it is moved here --> https://paste.ubuntu.com/p/wf9drK3Mb3/
If you have a MyQ garage door opener and want to add a sensor to display the status, I made a quick template for your to use. It's the link above this post.
hello gents. Can I ask you for your help. I have raindrop sensor , which is connected to my NodeMCU on analog input and return me value in V - 1.0V . I want to have string for example when it is 1.0 to have 100, when it is 0.45 to return me 45
Use the compensation integration.
okay
what's the best way to test a "trigger"?? I am having issues testing automations in the template editor
for example: {% if trigger %} FIRE ALARM!! {{ trigger.to_state.attributes.friendly_name}} reports {{trigger.to_state.state}} {% else
%} Unknown Fire Detector Alert {% endif %}
there would always be a trigger or the automation wouldn't fire
yes, however I am trying to test. what's the best way to test a "trigger" in the template editor
{% set trigger.to_state = states.domain.entity %}
Then add the rest in the template tester
interesting
where the domain.entity is the entity id of your thing
I've been attempting this: {% set trigger = 'sensor.time' %}
so {% set trigger.to_state = sensor.time %}
no, states.sensor.time
hmmm I'm getting "cannot assign attribute on non-namespace object"
oh, {% set trigger = {'to_state': states.sensor.time} %}
oh, so this is setting an attribute of a "fake" object to a real one?
simulating the trigger object with the bits you care about
How can I add the from_state also?
{'to_state': states.sensor.time, "from_state": ...}
@mighty ledge i'm not sure , that can understand this compensation. I did try on template but not any changes
1 canβt be compensated to both 4 and 100.
If the voltage is 1, what should the output be? 100?
Alright, then your second datapoint should be [0.77, 77]
i don't know how they can be
that is idea. In normal state is 1.00 v. if going down to 0.5 i have to recieve alaram
but it can drop from 1.00 to 0.45 as well
Just change the second datapoint in the configuration for compensation
To [0.77, 77]
It wasnβt working before because you gave it invalid data
And there were errors in your logs but you ignored or missed them
okay.
how can I use a template to parse this json data from a MQTT payload to see if error: true https://paste.ubuntu.com/p/pXcFyKTpkX/
value_json.state.flags.error is true
but how do I integrate that template into an automation?
under condition? use {% trigger.payload_json.state.flags.error == true %}
{% %} logic statements
{{ }} print statements
so can I just put that logic statement as a value template in the condition of the automation, or do I have to do it differently?
You need to output something
That something can be a {{ }} that returns a value like a boolean, or you have to use a string or {{ }} for each logic branch
What do I need to output?
I don't need it to output anything
I just need it to check if that condition is true in the json payload
and then do the actions if it is
If it's for a condition, a condition template must output a boolean.
If you just want the boolean above as the output, use {{ }} instead of {% %}
I just need it to check if that condition is true in the json payload
Then do that π
So I can just do {{ trigger.payload_json.state.flags.error }}
If thatβs a boolean (true/false), yes
Hey guys, so I made a helper input Boolean but itβs not letting me control it from Alexa
Are input Booleans able to do that?
Thanks
.
!
sorry, was writing something on top of my laptop
anyway I want to set up a template that takes the the time remaining from Octoprint and tells me when the print should be finished. I feel this should be possible, i just have no clue what the math for that is
i... was expecting something more complicated, thank you
{{ trigger.payload_json.device == "1P7U5" }}
i have this condition template for this.
it's an mqtt payload trigger for a value "1P7U5" - is there any way to include multiple OR values (ex: 2P7U5, 3P7U5) alongside that in the same one liner?
I have this simple template https://paste.ubuntu.com/p/75thPk3grh/. Works fine, but can it be made to return both a value and a string? Like ['30', 'on'], and if so, how would I access the map(?) in scripts/automations...
Youβre better off creating 2 template sensors or making the numerical value an attribute
Aha, ok. How would I go about creating an attribute then?
This info will be used to feed a runtime-scene, so would be practical to have all info in same sensor/place...
Hello, maybe I am not able to see the simple solution for what I want to achieve. I have a solar heated swimming pool with a couple of temperature sensors attached to it. I am interested in the efficiency of the system. Is there any way to show the temperature difference of sensor.temp1.now() vs sensor.temp1.oneHourBefore(). Any ideas on how to implement that?
statistic.change - great, thanks!
Is it possible to, from inside a sensor template, do similar calculations like what can be done in state triggers for things like time to/from a state? I am trying to self contain something totally within a template sensor but this seems like it might not be possible
Hi
@trim leaf If you define a trigger. See here: https://www.home-assistant.io/integrations/template/#trigger-based-template-sensors
so i created a list of scenes in helper
for lights to be set at specified colors
now I think I need to create a template?
i basically want to be able to use a philips hue dimmer switch, to cycle through the color scenes
can i make a template sensor which calculates the time a device was used on this day
Sounds like you want this https://www.home-assistant.io/integrations/history_stats/
the thats exactly what i need
can i also get the time since the device was turned on?
thx
Can anyone help with getting the syntax right to create a template (or template sensor) that returns a single value from a list in a sensor's attributes?
from a weather forecast, perhaps?
Precisely, sir
Hmm, is there a trick to searching? I had already done that and I don't get any results from #templates-archived...well, I do now. The two lines from you just now.
I've tried "from: RobD forecast" and get no results
my search was: from: RobC#5132 forecast
Ah, didn't realize you had to include the number. Should have.
once you start typing the name, it gives you a list with the IDs
Awesome, got it. I was beating my head against it trying various of {{ states.weather.station_daynight.attributes.forecast }} throwing index(n) or [n] in along with the list item I was trying to grab. I haven't used/seen state_attr before.
how do I reload templates without restarting the entire server?
pretty much this issue i guess
mine doesn't have it either: https://s.woet.me/cv3AcLF5uH.png
and now after a server restart it does
curious
You have to have at least one for the option to show up
Otherwise the platform isnβt loaded
how to make this work? when the json has a dash inside . DS18B20-988FEF has a "-"
my_test_json.sn.DS18B20-988FEF.Temperature
or .get('foo-bar') or |attribute('foo-bar')
Is there any documentation on things like selectattr or map?
I cant seem to find anything, and google searches are proving to not be very helpful
At the moment, I'm trying to join together a list of modified device trackers, changing their domain for their notification counterparts. I've got the list of device trackers, like so:
{{ states.device_tracker|rejectattr('entity_id','eq','device_tracker.silly_iphone_hub')|selectattr('state','eq','home')|map(attribute='entity_id')|join(',') }}
I'm getting output similar to: device_tracker.a,device_tracker.b but I am trying to transform that into notify.mobile_app_a,notify.mobile_app_b
Thoughts?
{%- set trackers = states.device_tracker|rejectattr('entity_id','eq','device_tracker.silly_iphone_hub')|selectattr('state','eq','home')|map(attribute='entity_id') -%}
{%- set ns = namespace(notify = []) -%}
{%- for tracker in trackers -%}
{%- set ns.notify = ns.notify + ['notify.mobile_app_{}'.format(tracker.split('.')[-1])] -%}
{%- endfor -%}
{{ ns.notify }}
@grand prism
np
loops get funky with namespacing issues, the ns = namespace() gets around that problem
Yeah, I was trying to get it to work with append a bit ago, but found a github issue where it is explained that it isnt possible by design
End result works a treat, thank you again!
data:
object_id: mobile_app_home
entities: >-
{% set list = namespace(notify=[]) -%}
{%- for item in states.device_tracker|rejectattr('entity_id','eq','device_tracker.silly_iphone_hub')|selectattr('state','eq','home') -%}
{%- set list.notify = list.notify + ['notify.mobile_app_' + item.entity_id.split('.')[1]] -%}
{%- endfor %}
{{ list.notify }}
np!
How can I use a variable that is passed to a script in an if statement? Basically, I want to have one script that I can call with different parameters to let it do different things. I tried both https://paste.ubuntu.com/p/rbGSZwQZJK/ and https://paste.ubuntu.com/p/tRyGJk9cy7/ but without success, I guess because the state of the attributes isn't actually set when you call the script. How could I make this work?
I called the scripts using this:
data:
parameter: "test"``` in the dev tools service panel btw
Youβre providing parameter as a string in the script. Remove the quotes around it to use it as as a variable
@oak quail
And value_template in the second one is missing the {{ }}
And then further down you used parameter properly π€·ββοΈ
I must say I'm a bit confused as to when to use ", ', or no quotes. Do you mean I need to remove the quotes around parameter in the is_state_attr('script.test_script', 'parameter', 'test') part, or around the parameter value in the service call? Because I tried both and they still don't seem to work
I also put "{{ }}" around the value_template like this, as I saw in the docs that single line templates must be surrounded by quotes https://paste.ubuntu.com/p/mrRgQwgP7K/. Could you confirm this is the correct syntax?
strings are surrounded by quotes, variables are not
no, you're still not consistent
alias: Test script
sequence:
- choose:
- conditions:
- condition: template
value_template: "{{ parameter == 'test' }}"
sequence:
- service: notify.persistent_notification
data:
title: Ja
message: "{{ parameter }}"
default:
- service: notify.persistent_notification
data:
message: Werkt niet
title: Nee
mode: single
icon: mdi:test-tube
both are attempting to use the variable parameter, but you referenced them in two different ways
actually, I have no idea what you're doing there
edited above. is that what you're after? the parameters you pass don't end up as attributes on the script, they're just variables
Okay basically, I'm trying to make a script that can get called with one variable, and depending on the value of that variable, different sequences are initiated. The code I have now is just to test out how to get this to work
ok, so does the above make sense?
gives me the error Message malformed: invalid template (TemplateSyntaxError: unexpected ')') for dictionary value @ data['sequence'][0]['choose'][0]['conditions'][0]['value_template']
oh, there's an extra paren
check
I'll try
That works, awesome!
Thanks a ton!
The reason I added the ' ' around parameter in the value template is because it says so on the docs https://www.home-assistant.io/docs/configuration/templating/#states. Is this information incorrect then? @inner mesa
what part of that? None of those are variables
that's the distinction
string vs. variable
Ahh okay then I think I don't really understand what variables are. Aren't they the same as attributes?
no
variables (anywhere, in any language) represent some value
attributes are specific to HA and are essentially additional data provided by an entity beyond the state
the use of "attributes" there is confusing in this context because those attributes aren't the same as HA attributes
Gotcha! Thanks again, I thought they were basically the same (also inside Home Assistant) so that's were the confusion came from
it kinda helps to have written an integration or at least looked at the code for one
Hahaha I don't have that luxury quite yet I think π
I have somw weird warning in my logs regarding rendering param input as template variable
Template variable warning: 'source' is undefined when rendering '{{ source }}'
here is my automation: https://paste.ubuntu.com/p/DKYp2YmM3D/
I think is maybe a problem here at value_template:
- conditions:
- condition: template
value_template: "{{ not is_state(speaker,'on') }}"
sequence:```
can I actually do like this? speaker is avariable that comes into a script as field param
Using what I learned today, and provided that speaker is indeed a variable, I think you could use value_template: "{{ speaker != 'on' }}"
What is the value of speaker?
Just an ordinary string
What is the value specifically?
That should be "{{ states(speaker) != 'on' }}"
You actually have to provide speaker and you can't rely on default to populate it without providing it to the script.
Hi, I have a rain sensor that is linked to the irrigation system, if for example today it rained more than 5mm the irrigation does not start, the problem is that the irrigation is activated at 5 in the morning, so it does not take into account the rain since at midnight it resets, so I am trying to create a sensor that before midnight does a check of the rain that has fallen and activates it if it exceeds 5mm, but which then remains unchanged, is it possible to do such a thing? Thank you
is there a way I can reference the entity_id in the action field entity_id property for an automation?
I need to grab the saturation for a light
- '{{state_attr("light.desk", "hs_color")[1]}}'
this works but I'd like to replace light.desk with a reference to the entity_id property so that I only need to change it there
doesn't look like that's an option, the only documentation I can find is for trigger properties
the issue is that I'm using a mqtt remote to control a HA light, so the trigger is not related to the light at all
I think I can assign the entity_id in the trigger tho, I'll test that
I'm trying to use an input_number in a scene to control brightness but it keeps telling me that it's expecting a float
entities:
group.lights:
entity_id:
- light.light_1
- light.light_2
order: 0
friendly_name: Lights
state: 'on'
brightness_pct: "{{states('input_number.brightness_low_power') | float}}"```
I've tried with "{{states('input_number.brightness_low_power') | int}}" and without piping it into int or float.
always complains.
Ok, I guess scene definitions don't support this kind of templating, never mind.
Yeah, templating is mostly reserved for script and automation services. There are a few places you can use templates in integration configuration, but they are explicitly documented as such.
I didn't realize, seemed like you could use it almost anywhere from the examples I've seen.
The only universal truths are if you have a service call in an automation/script, the service can be a template and anything in a data: block can be templated. Anything else requires a specific support
I'm confused about how timestamps work in HA. I live in Germany.
When I access a state object such as {{ states.device_tracker.dd.last_changed }} it returns 2021-06-12 13:39:42.516698+00:00.
However, when I request now() it spits out 2021-06-12 17:56:00.063892+02:00.
I get that both are compatible with each other in terms of calculation, but still: why?
Is something wrong with my setup?
Okay, so that's how it's intended to be.
I see, I could've noticed myself if I read properly lol. Thanks Rob!
Date/time stuff is my nemesis. I ask similar questions often and only manage by reading the docs and trying things
π
Just created this template for my doors, anyone know how to change the history colorbar to a history log (open and closed).
sensors:
custom_deuren_icon:
friendly_name: "mdi custom deuren"
value_template: >-
{% if is_state('binary_sensor.voordeur', 'on') and is_state('binary_sensor.achterdeur','on') %} Alle Deuren
{% elif is_state('binary_sensor.voordeur', 'on') %} Voordeur
{% elif is_state('binary_sensor.achterdeur', 'on') %} Achterdeur
{% elif is_state('binary_sensor.voordeur', 'off') and is_state('binary_sensor.achterdeur','off') %} Alle Deuren β
{% endif %}```
make a binary_sensor instead of a sensor
but you can't if you're returning strings like that
{{ expand('binary_sensor.voordeur', 'binary_sensor.achterdeur') | selectattr('state','eq','on') | list | length > 0 }}
that template will be on/off if any doors are open
Thanks Petro! The thing is i made a custom:button-card to show which doors are open. Because I want the Open/Closed states below the doorname i canβt use a template like that because it will show the state of the door instead of the name. So now I have a card that shows front door open, back door open or all doors open. π
{{ expand('binary_sensor.voordeur', 'binary_sensor.achterdeur') | selectattr('state','eq','on') | map(attribute='name') | list | join(',') }}
that'll be the list of names
any idea?
You could just use the statistics sensor to get the maximum rainfall in the last 24 hours. If you need help with that pop over to #integrations-archived
Thanks
I was thinking that the real time rain sensor updates every 60 sec if there are changes, otherwise it does not update, maybe a statistics sensor would not be accurate, I also have a sensor directly from the weather station that automatically accumulates the total rain, it would be maybe more opportunun to find a way to take a data at a specific time of this sensor, what do you recommend?
Why do you think it would be inaccurate? Use the total rain accumulated sensor with the statistics sensor configured for a max age of 24 hours. That way you can always get the maximum value (it is the max_value attribute of the statistics sensor) over the last 24 hours. Be careful with the sample size. What is the minimum update period of the accumulated rain total sensor?
Will adding Device_class: None to my template add a history log to a card (more-info)?
name: "Sun inside living room (Azimuth)"
upper: 180
lower: 80
entity_id: sensor.sun_azimuth
- platform: threshold
name: "Sun inside living room (Elevation)"
lower: 25
upper: 35
entity_id: sensor.sun_elevation```
What would be the best way to combine these two binary sensors into one?
hello. i'm looking to do an iteration loop in a script. i have a light that changes color based off of how many times you turn it off and on, and i'l like to automate that. i tried to create a script using the jinja tempate's {% for %} loop, but it errored on me: while scanning for the next token found character '%' that cannot start any token in ...
is it possible to perform a loop N number of times in a script?
Please use https://paste.ubuntu.com/ to share code or logs. Please don't use Pastebin, since it can randomly add spaces to the main view.
you can't do that with a template. you can with a repeat: loop
And of course, now you've explained more, see https://www.home-assistant.io/docs/scripts/#repeat-a-group-of-actions
sorry, @arctic sorrel. there's always more, isn't there? thanks for the link
It's why we have this bot message:
The XY problem is asking about your attempted solution rather than your actual problem.
This leads to enormous amounts of wasted time and energy, both on the part of people asking for help, and on the part of those providing help.
The problem occurs when people get stuck on what they believe is the solution and are unable to step back and explain the issue in full.
i wonder if sometimes the reason why people are so hesitant to give any extra details in chats like this is because they know they're going to be chastised for something
but thank you for the link. i can work with it
Taking 30 seconds to summarise your goals is rarely something you're going to get chastised for - unless you're in #the-water-cooler
Everywhere else you'll just get told there's a channel for that, maybe with overtones of how did you miss it
yeah. to be honest, i was more focused on picking the right channel to ask the question in. and i still missed it
i didn't see a #scripts, and #templates-archived didn't stand out to me
The channel topics... are worth a read π
i'm still learning, though. thanks for being patient.
Admittedly it can take a while to learn what's what, especially with such a complex application.
And then another release comes out and changes things π
yep. and i don't plan on scanning every channel and memorizing the topics
But there's no chastising so far... not until you make the same mistakes repeatedly.
i'm already in trouble with the wife for spending time trying to hack together a simple script to make our lives easier π
so i removed the {% for %} stanza and worked with the repeat. saved the file. tried to reload the 'scripts' from the server control page, and it's erroring with the same error on the same line. there is no "%" on that line. is it possibly cached now somewhere?
Always run the configuration check command when you make changes. Don't trust the UI check - it misses some problems.
Please use https://paste.ubuntu.com/ to share code or logs. Please don't use Pastebin, since it can randomly add spaces to the main view.
More a topic for #automations-archived though, if you're not using templates any more
heh. ok. thanks again
perhaps it might be templating afterall... it seems to be erroring on a line that is expanding a variable: Error loading /config/configuration.yaml: invalid key: "OrderedDict([('color', None)])" in "/config/scripts/colorsplash_lxg.yaml", line 166, column 0 (line 166 is line 53 in this paste): https://paste.ubuntu.com/p/8CpPYz6cX5/
i've copied the inovelli_led script and trying to make one for my new pool light
Quotes... you're missing quotes
gotcha. i cleared it up a bunch, quoted, and got it working. thanks again