#templates-archived
1 messages · Page 159 of 1
tadah..... you are completely right!
it should have been account-multiple-check currently....
so it's just saying that the key isn't there, and you're getting the default you specified
adding the int makes that happen 😉
exactly
thx!
have another challenge....
using the new This variable, I can not get it to work in an availability template
consider: attributes: id: mijn_mobiel availability: > {% set x = ['unavailable','unknown'] %} {{states('sensor.mijn_mobiel_connection_type') not in x and states('sensor.mijn_mobiel_ssid') not in x}}
which is the verbose template, and now use it with the this variable attributes: id: mijn_mobiel availability: > {% set x = ['unavailable','unknown'] %} {{states('sensor.' ~ this.attributes.get('id','Not yet set') ~ '_connection_type') not in x and states('sensor.' ~ this.attributes.get('id','Not yet set') ~ '_ssid') not in x}}
the replacement works fine in all other spots in the rest of that same template sensor, just not in the availability template
example: - unique_id: map_connection_mijn_mobiel name: > Mijn Mobiel: {{states('sensor.' ~ this.attributes.get('id','Not yet set') ~ '_connection_type')}} - {{states('sensor.' ~ this.attributes.get('id','Not yet set') ~ '_ssid')|replace('_',' ')}} icon: > {% if states('sensor.' ~ this.attributes.get('id','Not yet set') ~ '_ssid') != 'Not Connected' %} mdi:router-wireless {% else %} mdi:wifi-off {% endif %}
could be. the availability template determines whether the state is even evaluated, and could also impact whether the variables are set
I see. so this might actually be an unexpected result of a correct template.... preventing the full template to be even set. guess I need to ask Erik to have a look at that then.
it could be a completely consistent and expected result
yeah, thats what I meant.... technically speaking that is. In real life it is blocking a correct template
since the availability template determines whether the template is evaluated at all
thx Rob, have to get some sleep now, will take it to next week 😉
I'm really struggling with a lot of entities reporting unknown, particularly after restart. I've tried a few things like making a separate template that does something like this, but it just isn't working:
{% if is_state('sensor.original', 'unknown') %}
{{ states('sensor.masking') }}
{% else %}
{{ states('sensor.original') }}
{% endif %}
Does anyone have other tricks to prevent this? Can the new this var in templates help?
So I ran into this with my utility meter. Here is how I get around it:
{% set ft3 = (value | float) / 100 %}
{% if not is_state('sensor.gas_meter', 'unknown') %}
{% if (ft3 != 0) and (ft3 < 5) %}
{{ ft3 }}
{% elif (ft3 == 0) or ((((states('sensor.gas_meter') | float ) - ft3) | abs) > 100) %}
{{ states('sensor.gas_meter') }}
{% else %}
{{ ft3 }}
{% endif %}
{% else %}
{{ ft3 }}
{% endif %}
So it only updates if it is not unknown.
The rest is just sanity checking, because sometimes the radio picks up something wrong.
What about the unavailable or none states? A better test would be {% if not states('sensor.gas_meter')|is_number %} Also your first line will generate errors and (in a future release) stop the template from rendering if the value is non numeric. You need to supply a default, or check that the value is a number before attempting to apply the float filter.
Maybe this:```
{% if value|is_number %}
{% set ft3 = (value | float) / 100 %}
{% if (ft3 != 0) and (ft3 < 5) %}
{{ ft3 }}
{% elif (ft3 == 0) or ((((states('sensor.gas_meter') | float ) - ft3) | abs) > 100) %}
{{ states('sensor.gas_meter') }}
{% else %}
{{ ft3 }}
{% endif %}
{% else %}
{{ ft3 }}
{% endif %}
Can anyone point me in the right direction for putting my calendar date in a more palatable date format?
For example, it is stored as a state attribute:
start_time: 2022-06-12 09:00:00
how can I get that to display as something like "June 12th at 9am" or something similar?
Not sure if this is the correct channel, but how can I identify an entity which is part of a group and in that group it is set to not hide the individual entities in HA?
Basically: how can I identify a hidden entity? I do not see an attribute that stores this.
My use case is that I do not want to show hidden entities in the lovelace-auto-entities integration from Thomas Loven.
You can't, unfortunately
I want to show when my washing machine is running - I have an automation that runs when it turns on or off, based on power usage. I'm thinking of using a toggle helper, switch it on/off using the automation, and using a template binary sensor to show the state in the frontend. Is there an easier way?
So my binary_sensor template would be {{ states.input_boolean.washing_machine.state }}
Why not just use a a template binary_sensor itself based on the power usage?
What does the automaton do for you?
Ah, the automation has hysteresis to avoid false positives/negatives
And I expect to have to tune it, so why not have the variables in one place
Ok
You should review https://www.home-assistant.io/docs/configuration/templating/#states, including the warning box
That warning is useful, thanks!
If I'm not mistaken isn't this just what I have (except you have inversed logic to mine)? You are still using is_state() as the guard
For some reason pulling sensor.original affects the value that is set. Saying only update if not unknown worked better for me.
I'm also not sure how using something more specific would help in my situation like is_number or something. The state is still evaluating to unknown which means that the OLD value is evaluating to unknown during startup
Also, you don't need another storage for old or current if you only update the sensor if not unknown.
🤷♂️ Works for me. I tried your method prior to settling on what I'm using there.
How does that work? If I have a template that has a conditional statement where at the end it doesn't set anything? Like if there's just an if block with no else and condition ends up being false? Does it just not set a new value or does it set to none?
Or does it set it to empty string?
Possibly the latter, but unknown doesn't make it through.
I suppose I should try stripping out the final {{ ft3 }} in a test sensor and see what happens.
I'm particularly looking to keep it at the old value/not set it when the template is evaluated
Hello, I am again too stupid for this and request a hint. For my template rest switches I would like to add an icon per on/off state but I am lost where to add it.
I use rest sensors for the state as in
- platform: rest
name: lights_endpoint
json_attributes:
- item0
- item1
and switches´
switch:
- platform: template
switches:
gaestezimmer_licht:
value_template: "{{ state_attr('sensor.lights_endpoint', 'item0').sumstate.value.split(';')[0] == '1' }}"
unique_id: gaestezimmer_licht
turn_on:
turn_off:
where do I enter the icon defition? to the sensor? to the switch? to the template defition or each entity?
To the thing you want the icon to apply to. Is that the template switch?
yes
Then there
and I add it to each light?
The template switch
sorry I was unclear
do I add it to each entity under the template switch
or once for all entities
ok, that's what I tried and I followed the syntax mentioned in the examples here: https://www.home-assistant.io/integrations/template/ but it says icon is not a valid attribute
It's not
template:
- binary_sensor:
- name: Sun Up
state: >
{{ is_state("sun.sun", "above_horizon") }}
icon: >
{% if is_state("binary_sensor.sun_up", "on") %}
mdi:weather-sunset-up
{% else %}
mdi:weather-sunset-down
{% endif %}
- name: Sun Up
this is from the example page
That's a binary sensor
and what I am trying to adapt
You have a template switch
that is correct
thanks, I will try this.
I am happy to work with the right docs, it's hard to identify the correct ones though, at least for me. thank you very much for this pointer!
can I use icon color in this syntax or how do I differentiate lamp on / lamp off icons?
You can only specify icons
ok, what is the correct way to achieve a different on/off icon then? https://gist.github.com/thomasloven/01e03543364cf685eff969ad7980f5d7 only has one lightbulb icon
I must misunderstand how todo this the best practice way I guess
The logic above that you incorrectly put under icon: is fine
For the new this variable, would it be available in something like the value_template like the IMAP integration has? https://www.home-assistant.io/integrations/imap_email_content/
ok thanks, but I need different icons then for lightbuld on/off and the hass: list only has one lightbulb icon or am I missing sth?
thank you. I read a thread that there is no way to know which of those icons can be used in HA, is this true and I trial and error?
I have never found one that can’t be used in HAss. That is prob an old thread.
great to know, thank you very much
They're adding and changing icons regularly, so you have available whatever version is in the HA release you're using
ok, I got it working for the off state, it grabs the correct, icon, thanks. For the on state, I am not sure what to turn it to. I use value_template: "{{ state_attr('sensor.lights_endpoint', 'item8').sumstate.value.split(';')[0] == '1' }}" for the switch do determine on/off state, I tried to just grab the state of that switch entity but that didn't work. I tried also to include the same as in the value_template but that didn't work as well. what would be the correct approach?
so I was trying to use {% if is_state("switch.entityname", "on"
hah, i got it working with just the entity name!
I thought this was front end for some reason
got myself into a type issue once more.... considering https://www.home-assistant.io/integrations/zone/#state and eg states('zone.home') in the template dev tools says it's a number. yet - unique_id: family_home_united name: Family home united state: > {{states('zone.home') == '6'}} needs the number to be a string (or the |int filter on the state ) for the comparison to be correct... maybe a small edit on that page is in order?
Again, states are always strings.
You keep thinking that is_number returns the type, and it does not
It only indicates whether the input value can be evaluated as a number, not that it is an int or float type
I really hope that's clear
You Jerrold getting confused about exactly the same thing
yeah, I realize that. I was thinking it could be confusing to many others, so a note with what you say above would be enlightning
don't you agree though that when the editor explicitly returns 'Result type: number', a test is number would be expected to be True? I know it doesn't, and understand what you say. Yet what good does it do to state its a number, when it can not be used as a number type.
{{ 5.0 is float }}
{{ '5.0' is float }}
{{ states('input_number.test') is float }}
{{ states('input_number.test') is string }}
{{ states('input_number.test') }}
True
False
False
True
1.0
yep. and the editor shows Result type: number on those strings {{ states('input_number.test')}} 😉
Because they can be evaluated as numbers? 
I have been confused by that part and just ignore it
It's meaningless if you have more than one thing there
well, they cant can they? we need to explicitly cast them to |int before they can be evaluated as numbers
No, they can be evaluated as numbers, where 'foo' cannot
Are a number type and can be evaluated as a number are not the same thing
We're back here again: #templates-archived message
I guess I dont understand that after all then 😉 . All I am saying is I 'know' the output of any template is a string. And that we need to either quote the numbers (to make them strings) or cast the template to |int.
Going to bed
But 'TypeError: '<' not supported between instances of 'str' and 'int' tells us they can not be evaluated as numbers...
goodnight!
@floral shuttle it a matter of definition and interpretation, and I agree it can ben confusing. '5.5' CAN be evaluated as a number, but it IS NOT a number (and in that sense the naming of the is_number filter is confusing). It IS as string.
And you can not compare strings to numbers, even if the string only contains a numeric value.
sure. guess what I am looking for is what does 'CAN be evaluated as a number' really mean. where/how can it be evaluated as number? not in a template. In a numeric trigger probably.?
You can use strings in a numeric_state trigger, actually, the GUI puts quotes arond it. But in a template for a string to be treated as a number, you need to cast it either to int or float
I have a ESP32 bluetooth-gateway for some sensors connected with api to ha. When the esp32 it's offline all the sensors are unavailable, how can I keep the last value until it's back online?
Store it in a trigger based template sensor
Only in the template, when you use float or int. It’s a pre check you can use to verify that you can change the type without default being used. You’re getting confused because of the result type that is determined after the template is executed.
Everything in a template is executed as you see it. The result is always a string and that string is then thrown through a typing resolver. That’s when it gets assigned a type for the field the template is in. So if the returned value resolves to a number a number will be used. If it resolves to a list, a list will be used.
Do not confuse is_number with the ending result. Is_number purely checks to see if you can use int or float inside the template to covert your value to a number so you can use it as a number later inside the template. Float or int have no impact on the ending result type that’s resolved after the template is evaluated
{% if states('sensor.bedroom_battery_level') in ["unknown", "unavailable"] %}
{{states('sensor.bedroom_battery_level_fix')}}
{% else %}
{{states('sensor.bedroom_battery_level')}}
{% endif %}
what i'm doing wrong to keep the value on reboot for a ESP32?
What is the current state of the source sensor?
online - 72% batttery
okay, so does it work in
> templates?
nope, there's something I miss
What does this return in
>templates {{states('sensor.bedroom_battery_level')}}
right now unknown, i just reboot the esp32
73 value
if I restart the esp32, all values goes unavailable or unknown.
Does this work?
{% if states('sensor.bedroom_battery_level') | is_number %}
{{states('sensor.bedroom_battery_level')}}
{% else %}
{{states('sensor.bedroom_battery_level_fix')}}
{% endif %}
on reboot it's the same thing. I don't understand where the _fix should get the value
On reboot both are probably unavailable
on reboot of esp32 I mean.
Do you already have a working template sensor?
called sensor.bedroom_battery_level_fix
72
.share the complete template sensor
Please use a code share site to share code or logs, for example:
- https://dpaste.org/ (select YAML for the language)
- https://www.codepile.net/ (select YAML as the language)
- https://paste.debian.net/ (you guessed it, select YAML as the language)
Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.
it's working with this
now it keep the value on esp32 reboot
I would make it a trigger based template sensor, as of 2022.5 they keep their state after a reboot, so after HA reboot you will also have a state even if your ESP is not available
can you explain a bit? I want to make an thermostat for this and I want to keep the value on all restarts
But you need to use the new template format then, not the legacy format as you are using now
and the trigger to be when esp32 it's disconnected? I don't know if I understand the trigger based sensor
This will trigger on changes of the battery sensor, and then it will update the state of the template sensor
sorry, indentation is off
https://dpaste.org/vg1KB corrected version
with extra dynamic icon based on the battery percentage
and I need to remove the old sensor template yes?
Yes
Sorry for the late reply
and where should I add the block code? I tried on sensor folder and it says missing property sensors
I explicitly mentioned that in the first link (but not in the corrected version)
It is part of the template integration, not the sensor integration.
Add it in configuration.yaml, or create a similar include and folder for the template integration like you have now for the sensor integration
@mighty ledge thx. I note: It’s a pre check you can use to verify that you can change the type without default being used.
I also use it a lot in availlibility templates
Yep
that's my main usecase for it
and to filter states before casting all the states to a float
selectattr('state', 'is_number')
I add this line to configurations.yaml - template: !include_dir_merge_named template and made a directory template
in that folder I made a file bluetooth-gateway.yaml
and it's telling me property template is not allowed
Remove the first line with template: and use a different include type, as the template integration expects a list and not a dict
was missing a - in the line with name
@marble jackal thank you so much for your help. It's working now.
Looking for some help on an if value is in a range condition...
{% if states('sensor.energy_monitor_electricity_meter') | int < 500 %}
green
{% elif states('sensor.energy_monitor_electricity_meter') | int >= 500 and < 1000 %}
orange
{% else %}
red
{% endif %}
I understand I could just swap the elif and else around in this example, but I also want to use same template for a different thing with 4 options so it'd help if I can understand a way to check if its in a range? In this example above the and < 1000 is not permitted, but i hope it shows what I'm after?
what's the problem...
oh, nm
{% elif 500 <= states('sensor.energy_monitor_electricity_meter') | int < 1000 %}
ah that makes perfect sense! Thanks so much!
but technically you dont need that
you can have
{% elif states('sensor.energy_monitor_electricity_meter') | int < 1000 %}
and it will still work.
because the green will always catch less than 500, the elif will always catch whats between 500 and 1000
oh really, learnt two new things here then. I always assumed it had to only match one condition, not sure why but it does make sense that it stops once its matched one. Thanks so much @mighty ledge
if -> elif - else will always only have 1 resulting path.
regardless how many elif's there are
I now wonder how many templates I've made overly complicated due to this misunderstanding...!! Does the if statement work like this in all languages? jinja2 templating is the closest ive ever come to python or any other language.
every single language
really interesting! Not that I'm planning to learn to code any time soon. A bit of ha templating and yaml is enough for me!
I know how to grab the timestamp for a sensor's last change, but how do I get it for the last time a sensor changed to a specific state?
You would either need to create a trigger-based template sensor that returns the current time when your condition is met, or use an SQL sensor to search the database
yikes
The first is easy
so something like "if [binary sensor] goes to 'off', set sensor to [current time]" ?
If 'binary_sensor turns off' is the thing you care about
I think none actually worked for me (wasn't sure if it needed to be capitalized or not None), however I ended up changing the wait_for_trigger to a wait_until with a condition for # of loops, followed by a stop action.
Also fine, good that you got it working!
(so none or None - either work in general?)
I always use none, and that's clear here:
{{ state_attr('sensor.foobar', 'blah') }}
{{ state_attr('sensor.foobar', 'blah') is none }}
->
None
True
{{ state_attr('sensor.foobar', 'blah') is None }}
->
TemplateAssertionError: No test named 'None'.
it's confusing because what it displays and what you need to compare against aren't the same, both for None and True/False
and sometimes
-> Templates also says "null" where again "none" should be used for comparison
yeah. always confused about that. seems safer to use lowercase then?
not just safer, but required
i've also had issues when testing boolean attributes in an automation. 1 is determining if the entity attribute is actually a string or a boolean, and 2, if i type "true" in the UI, it becomes a string when i save it. I have to edit in YAML mode and remove the auto-added quotation marks
cool.
- sensor:
- name: Tariff Price
unit_of_measurement: Pkr/kWh
state: >
{% if is_state('utility_meter.daily_energy', 'offPeak') %}
{{ 18.010 }}
{% elif is_state('utility_meter.daily_energy', 'Peak') %}
{{ 24 }}
{% else %}
{{ 24 }}
{% endif %}
is this sensor correct?
peak rate is Pkr 24 and off-peak rate is 18
ran this in
->templates ```
template:
- sensor:
-
name: Tariff Price
unit_of_measurement: Pkr/kWh
state: >24
-
current time is in peak hours
You don't need to put those curly brackets around the numbers
And you also don't need the elif
Hello! I have a sensor template that tries to return a 2-element list. Basically, simplifying it to remove templating, I want to do: state: [1,1] But the automation code that reads that sensor using the states function in a {{ template }} doesn’t recognize it as a list with elements 0 and 1. Is a sensor template able to have a state that is a list?
Hey, I'm writing a blueprint for a 4 button remote, after inspecting zigbee events, for long press there are two events 'start' and 'stop', I have found existing blueprints that I can copy but they are for remotes that constantly emit 'hold' event, does anyone know of a blueprint that I can modify for my situation (with some sort of a 'start' and 'stop' event)
- sensor:
- name: Tariff Price
unique_id: 'Lesco_Tariff'
unit_of_measurement: Pkr/kWh
state: >
{% if is_state('utility_meter.daily_energy', 'offpeak') %}
{{ 18.010 }}
{% if is_state('utility_meter.daily_energy', 'Peak') %}
24.330
{% else %}
24.330
{% endif %}
like this?
resulted in ```
TemplateSyntaxError: Unexpected end of template. Jinja was looking for the following tags: 'elif' or 'else' or 'endif'. The innermost block that needs to be closed is 'if'.
No, like this:
state: >
{% if is_state('utility_meter.daily_energy', 'offpeak') %}
18.010
{% else %}
24.330
{% endif %}
states are always strings. You can attempt to convert it using | from_json but it won't work if it's not valid json.
full block will be ```
template:
- sensor:
- name: Tariff Price
unit_of_measurement: Pkr/kWh
state: >
{% if is_state('utility_meter.daily_energy', 'offpeak') %}
18.010
{% else %}
24.330
{% endif %}
- name: Tariff Price
Yes, you could even shorten it to this though:
template:
- sensor:
- name: Tariff Price
unit_of_measurement: Pkr/kWh
state: >
{{ 18.010 if is_state('utility_meter.daily_energy', 'offpeak') else 24.330 }}
Thank you. That makes sense to me. I’ll probably split it into 2 sensors.
Indentation is a bit off on this one, but I'm on mobile, so that's a bit tricky to fix
it is working though
👍🏼
checked in
-->templates
- sensor:
- name: Tariff Price
unit_of_measurement: Pkr/kWh
state: >
18.01
- name: Tariff Price
unique_id: 'Lesco_Tariff'
unit_of_measurement: Pkr/kWh
state: >
{{ 18.010 if is_state('utility_meter.daily_energy', 'offpeak') else 24.330 }}
``` I modified it to add unique id
I created another sensor to calculate the cost of plug energy usage ```template:
- sensor:
- name: MP off-peak cost
unit_of_measurement: Pkr
value_template: "{{ (states('sensor.mobile_plug_daily_usage') | float * 18.010 ) | round(2) }}"
friendly_name: Today's Offpeak Tariff Cost
- name: MP off-peak cost
No unique_id there? And you might also want to add an availability template there, to avoid it going to 0 when your source sensor is unavailable (and somewhere in the future it will run in error)
- sensor:
- name: MP off-peak cost
unit_of_measurement: 'Pkr'
device_class: monetary
unique_id: 'MP_offpeak_cost'
value_template: "{{ (states('sensor.mobile_plug_daily_usage') | float * 18.010 ) | round(2) }}"
friendly_name: Today's MP off-peak cost
availability: >
{{ states('sensor.mobile_plug_daily_usage') not in [ unknown, unavailable, none ]}}
is this fine?
No, you are mixing the new and legacy format now
value_template should be state, friendly_name should be removed, that is set after name already
And for your availability template you can use {{ states('sensor.your_sensor') | is_number }}
template:
- sensor:
- name: MP off-peak cost
unit_of_measurement: 'Pkr'
device_class: monetary
unique_id: 'MP_offpeak_cost'
state: "{{ (states('sensor.mobile_plug_daily_usage') | float * 18.010 ) | round(2) }}"
availability: >
{{ states('sensor.mobile_plug_daily_usage') not in [ 'unknown', 'unavailable', 'none' ]}}
instead of this 'unkown' and 'none' etc
Yes
And please stop posting the entire template sensor for each check, it is filling up the entire channel
Just put it in your config and try it out 👍🏼
Hello all,
I need a quick help with my sensor.
I need a sensor for Magic Areas that goes on at < 5 for example.
I have it, but after a few seconds it jumps back to off as soon as the light is on.
I have also searched, but so far nothing suitable found in the templates :/ can you help me? Maybe one or the other also uses Magic Areas?
So is how my Sensor currently Looks:
- binary_sensor:
- name: Dark Schlafzimmer
unique_id: dark_schlafzimmer
icon: mdi:brightness-6
state: >
{{ states('sensor.bewegungsmelder_schlafzimmer_illuminance')|float < 6 }}
- name: Dark Schlafzimmer
No idea what magic areas are, but as soon as you turn on a light in a room, the illuminance will increase, so your template will evaluate to false
That is exactly my problem, the sensor should not update immediately but e.g. every 15 minutes.
Is that possible somehow?
delay_off:?
but generally, using illuminance to manage a light where the sensor is next to the light is going to be problematic
Or a trigger based sensor based on a time pattern
Still curious what the heck a "Magic Area" is. Sounds like a Room of Requirement
Could anyone help me figure out what I'm doing wrong with this template? It is working in Dev Tools -> Template Editor, but it doesn't seem to work as a trigger:
value_template: >-
"{% if states('sensor.dryer_4_1min') | float >= 500 or
states('sensor.dryer_3_1min') | float >= 500 %} true {% endif %}"
for: '00:00:30'
id: dryer_started```
And here is what my template editor looks like where it works:
```{% if states('sensor.dryer_4_1min') | float >= 500 or
states('sensor.dryer_3_1min') | float >= 500 %}
Dryer running
{%- else -%}
Dryer not running
{%- endif %}```
Thanks in advance!
a) don't use quotes around multiline templates
b) it could be simpler:
{{ states('sensor.dryer_4_1min') | float >= 500 or states('sensor.dryer_3_1min') | float >= 500 }}
c) since you didn't have an "else" , it would just return nothing if it wasn't true
ahhh gotcha, thanks I'll make some modifications and see if it works!
Thanks for the help RobC, it's working now!
how do i convert absolute seconds to mm:ss
- name: intremain
value_template: "{{ value_json.intermissionInfo.intermissionTimeRemaining / 60 | int }}"
Simple math
well up there gives me the proper minutes but how do i format it?
I'm checking power usage to create a sensor with the state of my dumb video projector - on, off or transition. Rather than "transition" I would like show "starting up" or "shutting down" based on the previous state of on or off. Any tips?
- sensor:
- name: "Projector State"
state: >
{% if (states('sensor.projector_checker_current_consumption') | int < 1) %} off
{% elif (states('sensor.projector_checker_current_consumption') | int > 260) %} on
{% else %} transition
{% endif %}
value_template: >
{% set m = value_json.intermissionInfo.intermissionTimeRemaining / 60 | int %}
{% set h = (m / 60) | int %}
{% set m = m - h * 60 %}
{{ h }}:{{ 0 if m < 10 }}{{ m }}
This might work, assuming you are on 2022.5. Also removed some unneeded paranthesis
state: >
{% if states('sensor.projector_checker_current_consumption') | int < 1 %}
off
{% elif states('sensor.projector_checker_current_consumption') | int > 260 %}
on
{% elif this.get('state') == 'on' %}
shutting down
{% else %}
starting up
{% endif %}
Hey y'all...I've just started wanting to use a sensors.yaml file for sensors (I'm new to adding sensors in yaml). However, whenever I add a sensor in that new yaml file (I have it !included in config.yaml correctly) I get issues like: 'Missing property "state"' and 'Property scan_interval is not allowed.'
Why is this?
Returns null or unavailable during transition. I was unaware of "this.get". Is there any documentation about this I can read?
this.get('state') does the same as this.state, but this.state will run in error in case there is no state yet (so after reboot or template reload) and this.get('state') is forgiving, so it will just return none.
But it could be that the entire this object is missing after a reload. Maybe try this:
{% if states('sensor.projector_checker_current_consumption') | int < 1 %}
off
{% elif states('sensor.projector_checker_current_consumption') | int > 260 %}
on
{% elif this is undefined or this.state is undefined %}
unknown
{% elif this.state == 'on' %}
shutting down
{% else %}
starting up
{% endif %}```
What is the line you used to include the file? And what is the code of the sensor you tried to add?
Please use a code share site to share code or logs, for example:
- https://dpaste.org/ (select YAML for the language)
- https://www.codepile.net/ (select YAML as the language)
- https://paste.debian.net/ (you guessed it, select YAML as the language)
Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.
This is closer although never evaluates to "shutting down". Shows "starting up" whenever in transition regardless of initial state.
new attempt 🙂
{% if states('sensor.projector_checker_current_consumption') | int < 1 %}
off
{% elif states('sensor.projector_checker_current_consumption') | int > 260 %}
on
{% elif this is undefined or states(this.entity_id) not in [ 'on', 'off' ] %}
unknown
{% elif states(this.entity_id) == 'on' %}
shutting down
{% else %}
starting up
{% endif %}```
It's for a sensor that shows how many lights I have on + a sensor for monitoring my system + a sensor for a custom card for my dashboard to show available HA updates and current version etc
indentation of line 8 to 25 is wrong
What is the correct indentation?
And it seems like you are mixing the the sensor and template integration here
how did you include this file from your configuration.yaml?
Erm yeah it was suggested by someone else for me to use template: !include sensors.yaml in my config.yaml
well, only the first sensor is part of the template integration
there is also sensor integration, and a binary_sensor integration
They can not be mixed in one file (unless you are using packages)
Ohhh right
That makes sense 😄
Sooo I need to make different files for each type of sensor?
lines 67 and 106 are template binary_sensors which are written in the legacy format, and could be rewritten so they will work in this file
lines 7 to 65 are not template sensors, but sensors using a specific platform, and should end up in a different file
Right okay, yeah I am unsure how to re-write em
and if you are at least on 2022.4 you could remove those command line sensors, and create template sensors based on the update entities
Ok! So if I work that out (is it very hard? I am somewhat new to HA) the binary sensor I have in there rn will work
You could also use this format, but then you would need to create a separate file for this as well
configuration.yaml
template: !include template.yaml
sensor: !include sensor.yaml
binary_sensor: !include binary_sensor.yaml
I am very tempted just to do that because it's easier haha
How long would it take to re-do the sensors if I've never done it before/currently have zero clue how to? Probably a while or?
I'm also wondering what you are trying to achieve with these sensors.
This
Tbh for now because it's quicker and easier I'll just pop em on separate files
There is an update entity for core, os and supervisor, and also for all the add-ons
Why reinvent the wheel
Should probs have asked the question regarding that sensor in the Discord server for Minimalist UI 😅
Well, I would not advice to start using Minimalist when you are saying you are just a beginner
but anyway, here are the 3 files you can use to include using the includes above: https://dpaste.org/1BKbH, https://dpaste.org/4Pnrs, https://dpaste.org/CMLKZ
Haha yeah that makes a lot of sense...but I've already spent the past month learning how to make it all work and I actually have a fairly expansive dashboard working right now. I am finding it worth the effort learning it all 😄
I'm away from keyboard for now
No worries, thanks for your help!
I have one question with regards to templates (I believe - might be wrong category if I think about this the wrong way). I have a Synology surveillance station which has the "Home Mode" function, which is set-up to trigger recording or not of cameras. So far so good. I can see the Home Mode switch in HA and its state under DevTools. I now would like to have an input boolean that monitors this - not change it. The boolean is not supposed to be a button but just turn on when the state changes (or off). Trigger for the boolean therefore would be a state change, but how do I monitor this? A template sensor? Would someone have an example?
Template binary_sensor, the documents have examples of this exact thing.
(you don't need the icon template)
Transition state of projector
Thanks, the sensor works fine. How do I let it now trigger the boolean on/off in line with its state? Because an automation would again just capture change, not actual state
you don't need an input boolean, just use the binary sensor
that's the point of the binary_sensor
i.e. you now have a 'binary sensor' that is in sync with your switch and you can't turn it on or off
I knew there was a logic mistake in my attempts! Thanks a lot, works perfectly
Hi, why does this return zero (0) matches? Is there a better way of finding a substring in a string? {% set t = 'motion' %} {{ t|select('search', 'motion') |list|length }}
this is from a test in dev-tools. t is normally a variable I want to parse
oh, in the select statement?
Yes. It's iterating through the string
{{ t|select('search', ['motion']) |list|length }} gives me a TypeError: unhashable type: 'list'...
I have a stupid jinja problem. Jinja figures into most of my problems.
Trying to do an automation wherein telegram notifies me of which timer has finished. Telegram works fine. The reference to the entity_id of the timer that went off does not:
`alias: New Automation
description: ''
trigger:
- platform: event
event_type: timer.finished
condition: []
action:- service: telegram_bot.send_message
data_template:
message: hi {{ trigger.entity_id }}
mode: single
Also triedtrigger.event.data.entity_id `, which is what the documentation has suggested would be the correct answer.
Aha, that will be difficult, but if neccessary to get this working... Thanks 🙂
Update. This works:
` alias: New Automation
description: ''
trigger:
- platform: event
event_type: timer.finished
condition: []
action: - service: telegram_bot.send_message
data:
message: reowr {{ trigger.event.data.entity_id }}
mode: single
`
This also works:
`alias: New Automation
description: ''
trigger:
- platform: event
event_type: timer.finished
condition: []
action: - service: telegram_bot.send_message
data_template:
message: reowr {{ trigger.event.data.entity_id.split('.')[1].replace('_', ' ') }}
mode: single
`
I suspect that the virtual keyboard I was using on my smartphone threw an invalid character.
trigger.event.data.entity_id
Uh and discord just updated and showed me you already figured it out
Hi, how do I encode double quotes in a value template so that they are not converted to single quotes?
value_template: >-
{{
{
"ping": value_json.ping.latency,
"download": value_json.download.bandwidth,
"upload": value_json.upload.bandwidth
}
}}
Get's converted to 'ping':... that fails to be json parsed.
Thankyou Much much appreciated!
{{
{
"ping": value_json.ping.latency,
"download": value_json.download.bandwidth,
"upload": value_json.upload.bandwidth
}|tojson
}}```
Thx
- name: "Bathroom motion"
delay_off: "00:00:30"
state: >
{{ states('sensor.samsung_j3_ipcam_motion')|float > 0 }}```
trying to make this turn on whenever there's a state change regardless of value not just above 0
anyone know how?
This will trigger on every state change of the sensor, and then evaluate the template
Idunno, it stays on even after the motion stops
it's at 51 now, since 8 minutes ago
and the binary sensor still on
Yes, it is still above 0, so that would be correct
ok, but I'm trying to make it turn on whenever there's a state change regardless of value not just above 0
which would then make it turn off whenever there's a lack of state change for 30 secs
If you just want it to turn off of there has not been a state change in the last 30 seconds, you can use this:
- binary_sensor:
- name: "Bathroom motion"
delay_off: "00:00:30"
state: >
{{ (now() - states.sensor.samsung_j3_ipcam_motion.last_changed).seconds < 30 }}
thanks!
Sorry, other way around
Corrected now.
However, now() is only evaluated once a minute, so it will probably take longer than 30 seconds after a state change to turn off
Hi, my device_tracker template is not working anymore. Does someone know why?
{% for device in (states.device_tracker | selectattr('attributes.essid', 'eq', 'MYSSID') | list) -%}
{{ device.name }}
{% endfor %}
Error: UndefinedError: 'homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'essid'
Add a check if the attribute is defined
{% for device in (states.device_tracker | selectattr('attributes.essid', 'defined') | selectattr('attributes.essid', 'eq', 'MYSSID') | list) -%}
{{ device.name }}
{% endfor %}
so no way to trigger it faster to turn off?
Thank you!
You could make it trigger based and add a time pattern trigger with a 1 second pattern
that would be great! how to do that?
thank you!
upon reload of templates, the only 'default' issue I seem to have left is a get function in my Python scripts, based on a Ha core template:, which is - unique_id: utc_offset name: Utc offset state: > {{now().utcoffset().total_seconds()/3600}}. The Python uses: utc_offset = hass.states.get('sensor.utc_offset').state try: timeDifference = float(utc_offset) except: ValueError and throws the error when the template reloads...
can/should I default that like we do in HA? eg withutc_offset = hass.states.get('sensor.utc_offset',0).state I get get() takes 2 positional arguments but 3 were given
https://www.w3schools.com/python/ref_dictionary_get.asp default is None, meaning float(None) would indeed fail..
hass.states is not a dictionary and .get does not allow a second argument.
I think I've told you multiple times that you can't mix and match languages. Jinja is not python, jinja is not JS, python is not JS, etc
you actually have to look up the API and perform the code based on what the API tells you
yah I am aware of not mixing ofc, my mistake was the dictonary.. but, before I fix that, I tested the new This variable on the utc_offset for experiments sake just now, and it wont pass config.```
- unique_id: utc_offset
name: Utc offset
state: >
{{now().utcoffset().total_seconds()/3600}}
icon: >
mdi:numeric-{{this.state|default(0)|int|abs}}
icon: >
{% set offset = now().utcoffset().total_seconds()/3600 %}
mdi:numeric-{{offset|int|abs}}``` still complains about 'this is undefined when rendering etc'. The commented bit works fine.
even though I set a default on it. Cant use the availability with that, so how to proceed in this case?
even tried ```
icon: >
{% if this.state is defined %}
mdi:numeric-{{this.state|int|abs}}
{% endif %}
mdi:numeric-{{ this.state|int|abs if this is defined and this is not none and this.state | is_number else 'negative-1' }}
a yes, that was it. 'this' is the entity, which should be checked for none, not entity.state. thx. This: icon: > mdi:numeric-{{this.state|int|abs if this is defined}} seems to work too.
yeah but you'd wnat an icon when it's not, right?
and when the state is non-numeric
yep...
too bad we can not default the this.state directly, and have to resort to if's, its makes it way less attractive to use the self referencing This, certainly for these short templates. might as well simply repeat the state template
its also a bit of a mixed complexity, because ```
- unique_id: next_alarm
name: Next Alarm
state: >
{% set timestamp = states('sensor.next_alarm_timestamp')|int(default=0) %}
{% if timestamp %}
{{timestamp|timestamp_custom('%H:%M')}}
{% else %} Not set
{% endif %}
icon: >
{{iif(this.state == 'Not set','mdi:alarm-off','mdi:calendar-clock')}}
then you'd have all sorts of problems with a 'fake' state object. This is also how all state objects work everywhere. Inside triggers, inside events, etc.
this is a state object. So checking for the state object is standard
just like trigger.to_state and trigger.from_state
yes, I see that, thx. using midway mdi:numeric-{{this.state|int|abs if this is defined and this.state|is_number else 'negative-1'}} for now, to see if I run into more extreme exceptions to be guarded (the previous never caused any trouble so I hope this will suffice). btw, I tried it in an iif() but then even the if this is defined caused it to throw the error.
becuase you remove the if
iff(this is defined, ...
not
iff(if this is defined, ...
iif(...)
mdi:numeric-{{ iff(this is defined and this.state|is_number, this.state|int|abs, 'negative-1') }}
however, that might not work because it may try to resolve this.state|int|abs inside the iff
meaning you HAVE to use the pythonic if else
I'd wager that the resolution will happen, forcing you towards the pythonic if else
FWIW, I personally wouldn't switch to the iff, it's for beginners who can't read (if-passes) if () else (if-fails)
hehe. and youre right: Template variable error: 'this' is undefined when rendering 'mdi:numeric-{{iff(this is defined and this.state|is_number,this.state|int|abs,'negative-1')}}'
well that settles it, use the pythonic if-else
as it will not resolve the if-passes
https://www.home-assistant.io/docs/configuration/templating#time just above that says something along those lines, 'shortcut'
yeah, and you have to understand what it says, before you understand what is says....
having settled that (thank you btw) I am back to NameError: name 'timeDifference' is not defined for my Python scripts importing that Utc sensor.
right, and you're getting that because of the exact same issue, but in python
you're getting the state object, not checking it's existance, and then providing it the conversion with a bad value
utc_offset_obj = hass.states.get('sensor.utc_offset')
utc_offset = utc_offset_obj.state utc_offset_obj is not None else None
try:
timeDifference = float(utc_offset)
except ValueError as err:
timeDifference = 0.0
thx! was busy testing this utc_offset = hass.states.get('sensor.utc_offset').state if (utc_offset is not 'unavailable'): timeDifference = float(utc_offset) else: timeDifference = 0.0 which also prevents the error. tested for None first, but since it isn't none (which is the test for the state object) but 'unavailable' given it's the state.state, I hoped that would work.
now back to the course and find your solution
and, utc_offset = hass.states.get('sensor.utc_offset').state try: timeDifference = float(utc_offset) except ValueError as err: timeDifference = 0.0 works without error too.
I just realized it's remarkable these errors show up in the first place, upon reload of templates, since this python script only runs when this automation fires:```
- alias: Mode selection
id: mode_selection
trigger:
platform: state
entity_id: select.mode_selector
action:
service: python_script.summary_mode
``` Somehow theevent_template_reloadedtriggers that.
How do I get the current entity icon? For example a battery entity will change icon depending on the battery status, so I'm wondering how can I get the icon of an entity through template
I don't think you can. I think it's determined by the frontend based on the battery level, which you can access
But I have some custom components that show the icon of the entity, how are they doing it, javascript?
yes
damn that sucks
you can just make a template that gets the same icon
{% set level = 11 %}
{% set fullempty = {0:'-outline',100:''} %}
mdi:battery{{ fullempty.get((level // 10) * 10, '-' ~ (level // 10) * 10) }}
yep, just did that
What does // do? Is it like divide and int afterwards?
it's int division
tosses the remainder out
but, basically, yes it does what you asked
Ah good to know
I only know of it because of python 2. Basically back in the day if you divided 2 int's you'd get an int. If you wanted a float, you'd have to cast crap to a float or use the // to do float division. When they went to python 3, they inverted it. / was always a float and // was an int
Hey whats wrong here?
{{ now().month in [6, 7, 8] }}
It says: template value should be a string for dictionary value @ data['value_template']. Got None
When I test the condition within an automations
Check the pinned posts
Oh what did I miss?
Okay got it:D
the pinned message
Ty so I should be fine I guess
Hopefully this gets a fix because I really like the quick condition check within automations
Sorry for such a basic question, but Ive been struggling with this for like an hour... I'm trying to turn off a charger after a time once the level is greater than a input number: platform: numeric_state entity_id: sensor.nexus_battery_level for: '30' value_template: >- {% if states('sensor.nexus_battery_level') >= states('input_number.charger_high_percent') %}true{%endif%}
It needs an "above" or "below".... those blocks don't seem to support templates
States are strings
THis Should be a condition, not trigger?
and you have no "else"
RRRRRRrrrr {% if states('sensor.nexus_battery_level') >= states('input_number.charger_high_percent') %}true{%endif%}
yes, that's wrong
Wait, you need an else?
well, it has to evaluate to something
plus, you're using a numeric_state trigger and then providing a template
I doubt it
before I had hardcoded 80% in there, but now I am trying to update the automation with a helper
- platform: template
for: 30
value_template: "{{ states('sensor.nexus_battery_level')|float >= states('input_number.charger_high_percent')|float }}"
and this is a condition, right? But it still needs a trigger, or it'll never fire, correct?
or...
you haven't said
you could use a trigger for this
it will only trigger if it starts below the threshold that you've set and transitions above it, though
a better solution is this:
trigger:
platform: state
entity_id: sensor.nexus_battery_level
condition:
condition: numeric_state
entity_id: sensor.nexus_battery_level
above: input_number.charger_high_percent
you can't use a "for:" there, but I don't know if you really care
I wanted to stop potential thrashing so I just said for > 30 minutes.... 5 would even be fine I guess.
that was "30 seconds"
OH... dang
just increase the percentage
it's not going to "thrash", just add a condition to check that it's still on
Well, I think that would be fine, becuase I don't turn the charger back on until the "low" slider is passed
right
Ok, here's the whole thing, and it looks right:
description: ''
trigger:
platform: state
entity_id: sensor.nexus_battery_level
condition:
condition: numeric_state
entity_id: sensor.nexus_battery_level
above: input_number.charger_high_percent
action:
- service: switch.turn_off
target:
entity_id:
- switch.bath_charger
mode: single```
I didn't know you could just put the input_number in the above field...... I thought it needed a template
Hmmm.. I will test more. Thank you!
I think I made the mistake of looking for examples first, and getting in a rabbit hole
If you do want a time delay, I would suggest to create a binary_sensor and use a delay_on
I will keep that in mind! Thank you
Or a state trigger with a for using the binary_sensor
True, that's the direction I would have gone
is there a way to template state condition for:?
this is the rough idea of what I have:
template:
- binary_sensor:
- name: "time to check for update"
state: "{{ is_state('binary_sensor.check_update', 'off') for 24 hours }}"
the for 24 hours is where I can't find where to do that in a template. I searched but I didnt find where it says this point.
delay_on: should be able to do that
I guess if it was only based on time. I would want it to also be based on another trigger (besides time) and then have the delay on. If I understand correctly delay_on would ignore that. In an automation I guess I would use wait for trigger...
some times the sensor gets false triggers I want it to wait 24hrs after getting triggered to see if it held before changing the state of binary sensor.
I see, I didn't understand how it works. I still thought it wouldn't but I tried it and its good so its good, Thanks.
hi, I have a binary sensor that I need to have it check every second for a doods image processing entity if its above 0
- platform: time_pattern
hours: "*"
minutes: "*"
seconds: "*"
binary_sensor:
- name: "Chair motion"
delay_off: "00:00:30"
state: >
{{ states('sensor.image_processing.doods_theothergoat')|float > 0 }} ```
is the code right?
I would simplify the trigger to:
- platform: time_pattern
seconds: "/1"
and that will make the binary sensor trigger each second right?
yes
awesome cheers!
only it doesn't
the sensor shows up as Unknown
I'm thinkin it has to do with the way that the doods sensor is written
like the attributes and such
the binary sensor is told by the template to turn on if the doods is above 0
the doods sensor's state does show up as above 0 in the developer tab
It'll show up as unknown on first start
but maybe the binary sensor should look for a certain attribute? like 'person' for instance
yes that's what I thought too, so I started triggering the doods, and it still doesn't change
It'll only update on your trigger
it won't update based on dood changing
that's what happens when you use a trigger
so it disregards the template completely?
yes
wow
when trigger -> resolve template
makes sense
or no trigger, works off templates state changes
how can I make the binary sensor use the template AND check for the template every 1 sec
why do you need to check the template every 1 second
that makes no sense as the template will update live
cos the doods is my motion detection
yeah, but a binary sensor is binary
if it goes from 0 to 1 it'll be on, if it goes from 1 to 2, it won't be more on, it'll still be on
if it goes from 1 to 0 it'll be off
thats perfect
that's how it was initially 😄
and it didnt work
because maybe the thing with the attribute
no clue what you're saying
(from what I know, some sensors show different states in the development tab as opposed to what their actual states are)
different formatting, IDK
no...
ok rewind a bit:
there's a translated state for things that have known states. Like a binary sensor that's motion
a sensor does not have known states
and does not have any translations
known state is like 'on', or 'off'.
a sensor is just a value
that tracks
ok so it was like this:
- name: "Living Room motion"
delay_off: "00:00:30"
state: >
{{ states('sensor.image_processing.doods_thegoat')|float > 0 }}
yep, that will update when doods changes
then dudes wasn't changing
even though I was witnessing doods changing live
then you have the wrong entity id
hmm, I don't think so but doublechecking just to be sure
yeah you're right, the entity doesn't have the word "sensor" before it
or is that part of the template perhaps
not sure I folllow you
sorry, not that experienced with templates. I thought the entity name went after "sensor"
but that was just part of a sensor's name
not being experienced, I only swap out parts for other parts
image_processing.doods_thegoat
then that's why it's not working
thats great!
ok and just to be sure: this one won't check the template either, correct?
name: "Bathroom motion"
delay_off: "00:00:30"
state: >
{{ (now() - states.sensor.samsung_j3_ipcam_motion.last_changed) }}```
remove the - before binary_senosr and align it with trigger
so for this one I need it to turn on whenever that motion sensor changes state, and then off if there's no change state for 30secs
it needs to return on or off, true or false
remove the timepattern
what is supposed to signify on?
whenever there is a state change in the motion sensor (which sometimes remains stuck at random values)
so if it's stuck at 500 when I turn off the light, I need the next time there's any other number apart from 500 to show as on
like, whenever there's a state change from 'now'
You're going to have a tough time figuring that out
does the value change constantly when it detects motion?
you'll probably need to make a forum post, it's too complicated to come up with here and I'm about to head out
np
I'd like to use a time of day sensor but base the times on variables I have already created and set. How would I modify this example to use input_datetime.t1_wake as the time? ```
- platform: tod
name: Late Morning
after: "10:00"
before: "12:00"```
I don't think you can with that integration. You could do the equivalent with a template binary_sensor, though
thanks what would that look like?
Actually it doesn't have to be binary right?
I could just use a template sensor, I'd prefer that as I can give the value "Day" and "Night"
I'm gonna give it a go
have an idea
{{ states('input_datetime.xxx')|as_datetime <= now() <= states('input_datetime.yyy')|as_datetime }}
or something like that. you (and I) would need to play with it to get it right
ok let me play with that
do I need to enable the time and date function so that sensor.time exists or the above can do that without it
I think I've got it !
{{ states('input_datetime.t1_wake') <= states('sensor.time') <= states('input_datetime.t1_sleep') }}
so that works as long as am>pm isn't bridged
but not if say wake is 9pm and sleep is 4am, it fails
Got it (with help from the forums)
{% set slt1start = states('input_datetime.t1_wake') [0:5] %}
{% set slt1stop = states('input_datetime.t1_sleep') [0:5] %}
{{ (slt1start <= time < slt1stop) if (slt1start < slt1stop) else (slt1start <= time or time < slt1stop) }}
how do I reference the value in a value template?
@plucky heron easiest way is to define a variable for it at the start of your template and then reference it's name
you can see it above in the unrelated template i just added. First you set "time" equal to the value of anything you want, then you use simply "time" in your statements
the defined variables live only inside the single value_template so you do not need to worry about using specific labels they just need to be unique inside that one sensor
@inner mesa so I have it working with true/false, how can I modify that to output Day if true and Night if false?
Done.
{% set slt1start = states('input_datetime.t1_wake') [0:5] %}
{% set slt1stop = states('input_datetime.t1_sleep') [0:5] %}
{% if ((slt1start <= time < slt1stop) if (slt1start < slt1stop) else (slt1start <= time or time < slt1stop)) %}
Day
{% else %}
Night
{% endif %} ```
i have a mqtt switch, and the mqtt value for the state isn't on\off. i don't see the mqtt topic value in states(). how do i assign it to a variable?
{% set switchstate = states('switch.garage_motion) %}
you can test it in the template under developer tools by writing
{{ states('switch.garage_motion) }}
that will output on or off
so now you know what value you are setting your "switchstate" to
once you set it, you can put {{ switchstate }} on the next line and you will get a matching output as well
If I was playing around with templates I would use the following in that box
{% set switchstate = states('switch.garage_motion') %}
{{ switchstate }}```
result will be off, off
which lets you know your value is getting assigned to your variable, and then you can pull the variable, and now you can use simply switchstate in your if statements
when I am workign on long ones I'll add plain text labels around them like this ```This is the raw state [{{ states('switch.p1_ro_feeder') }}]
{% set switchstate = states('switch.p1_ro_feeder') %}
This is the output variable [{{ switchstate }}]
{% means a calculation or logical statement while {{ means output this value
'value' is the variable i was looking for. it has the mqtt topic data in it
value_template: "{{ value is search('motion=1', ignorecase=False) }}"
Guess it would have made it easier if you would have told you were talking about an MQTT topic 🙂
sensor isha:
- platform: rest
resource: https://dailyprayer.abdulrcs.repl.co/api/london
name: Isha
value_template: "{{ value_json.today.isha'a }}"
scan_interval: 20
im trying to get the isha'a in value template to work
but it wont
how do i put ' in a that
value_template: "{{ value_json.today.isha\'a }}"
``` should work AFAIK
@fluid horizon Always run the configuration check command when you make changes. Don't trust the UI check - it misses some problems.
- HAOS & Supervised use
ha core check - Container uses
dockercommands - Core requires you to activate the venv first
`
Configuration invalid!
Error loading /config/configuration.yaml: while scanning a double-quoted scalar
in "/config/configuration.yaml", line 54, column 21
found unknown escape character "'"
in "/config/configuration.yaml", line 54, column 47
`
Now use a code share site to share the YAML of what you've done
sensor isha:
- platform: rest
resource: https://dailyprayer.abdulrcs.repl.co/api/london
name: Isha
value_template: "{{ value_json.today.isha\'a }}"
scan_interval: 20
that won't work unless it's inside a string.
because it's the dot notation, you need all characters and no special characters.
value_template: "{{ value_json.today['isha\'a'] }}"
you can't create a function or macro with special characters and that rule is also applied to calling them. attrs of a dictionary are wierd like that. The safest way to get any attribute to avoid that stuff is xx.get('attr'), however it's not as nice as xx.attr or xx['attr']. All 3 of those methods work when you're dealing with a alpha-numeric key unless it steps on the toes of a function name. If it's non alpha-numeric or a function shares the same name, you have to use xx['attr'] or xx.get('attr').
Can a template be made to add an hour to the current hour
{{ now().strftime("%I:%M %p") }}
returns 07:08 am. If I wanted it to return 08 am as in current hour + 1 how would I do that?
Text to speech using it with Amazon Polly to say at 10am it will be x degrees outside
ok, and howare you getting that?
Rather than saying in 1 hour
didnt work for some reason
its giving me errors
I have everything set for knowing the temperature. It's just a matter of it would be cool to know the hour vs just saying in 1 hour, in 2 hours etc. Instead at 08 am, 09 am it will be x degrees outside.
not a mind reader, gonna have to post errors
sensor isha:
- platform: rest
resource: https://dailyprayer.abdulrcs.repl.co/api/london
name: Isha
value_template: "{{ value_json.today['isha\'a'] }}"
scan_interval: 20
Error loading /config/configuration.yaml: while scanning a double-quoted scalar
in "/config/configuration.yaml", line 53, column 21
found unknown escape character "'"
in "/config/configuration.yaml", line 53, column 48
@mighty ledge
Can you just explain how you're getting the in 1 hour?
oh wait
thats not ur code
hold on
i think thats something i did
wait nah its urs
@silent vector posted a code wall, it is moved here --> https://hastebin.com/rimugiseta
Thanks, can you post the results of state_attr('weather.home_hourly','forecast') as well
That doesn't make sense, it will pass validation. You can try this instead if you want but the result will be the same.
value_template: >
{{ value_json.today["isha'a"] }}
@silent vector posted a code wall, it is moved here --> https://hastebin.com/obonuwozoc
passes config check
but now wont display
are you sure that it's the correct name?
post the json
@silent vector haven't forgotten, hold a sec
No problem.
sensor isha:
- platform: rest
resource: https://dailyprayer.abdulrcs.repl.co/api/london
name: Isha
value_template: >
{{ value_json.today["isha'a"] }}
scan_interval: 20
api im using
@silent vector
<speak> {% if now().strftime('%H')|int < 12 %}
Good morning.
{% elif now().strftime('%H')|int >= 12 and now().strftime('%H')|int < 17 %}
Good afternoon.
{% else %}
Good evening.
{% endif %} It is {{ now().strftime("%I:%M %p") }}. The high today is {{ (state_attr('weather.home_hourly',
'forecast') | map(attribute="temperature") | list)[0:16] | max }}
degrees and the low is {{ (state_attr('weather.home_hourly', 'forecast')
| map(attribute="temperature") | list)[0:16] | min }} degrees. <break
time=".03s"/> It is currently {{state_attr('weather.home_hourly',
'temperature') }} degrees outside.
{% for hourly in state_attr('weather.home_hourly','forecast')[:2] %}
- <break time=".03s"/> at {{ (hourly.datetime | as_datetime | as_local).strftime("%I %p") }} it will be {{ hourly.temperature }} degrees outside.
{% endfor %} </speak>
ok, now look at your json, and look at what you're asking for. Is the key the same?
That is perfect thank you!
is "isha'a" the same as "Isha'a"?
How would I keep the logic with the addition of the loop to get the time that you gave me?
{% if
state_attr('weather.home_hourly','forecast')[0] .temperature | float(0)
- state_attr('weather.home_hourly', 'temperature') | float(0) > 3 %}
at 08 am it will be x degrees {% else %} {% endif %}
The for loop you gave also provides 2 times as an output
- <break time=".03s"/> at 08 AM it will be 58 degrees outside.
- <break time=".03s"/> at 09 AM it will be 60 degrees outside.
I assume it should only provide one? As I would only want to know the next hour, next 2 and next 3 but only if the conditions of each if is met at that time would I want to know the next 2 and 3. That's why I spaced them out in separate if statements so that if necessary it would say every hours temperature and If not only 1 or 2 or even 0 if the conditions aren't met.
what is the condition, that the templerature is greater than 3 degrees from the previous?
Yep that's it. the next hour, 2 hours from now and 3 hours out. Then I would want to know what the temperature is at that hour. If not nothing. To avoid. It will be 59 at 09 and 60 at 10 and 61 at 11 for example. Pretty small changes I would rather not waste the time hearing lol
This is the current output of the code I posted in the first hastebin
<speak>
Good morning.
It is 07:48 AM. The high today is 72 degrees and the low
is 58 degrees. <break
time=".03s"/> It is currently 52 degrees outside.
<break time=".03s"/> in 1 hour it will be 58 degrees
outside. </speak>
makes it a bit more complicated but
<speak> {% if now().strftime('%H')|int < 12 %}
Good morning.
{% elif now().strftime('%H')|int >= 12 and now().strftime('%H')|int < 17 %}
Good afternoon.
{% else %}
Good evening.
{% endif %} It is {{ now().strftime("%I:%M %p") }}. The high today is {{ (state_attr('weather.home_hourly',
'forecast') | map(attribute="temperature") | list)[0:16] | max }}
degrees and the low is {{ (state_attr('weather.home_hourly', 'forecast')
| map(attribute="temperature") | list)[0:16] | min }} degrees. <break
time=".03s"/> It is currently {{state_attr('weather.home_hourly',
'temperature') }} degrees outside.
{% set ns = namespace(previous=-300) %}
{% for hourly in state_attr('weather.home_hourly','forecast')[:3] %}
{% if hourly.temperatere - ns.previous > 3 %}
- <break time=".03s"/> at {{ (hourly.datetime | as_datetime | as_local).strftime("%I %p") }} it will be {{ hourly.temperature }} degrees outside.
{% endif %}
{% set ns.previous = hourly.temperature %}
{% endfor %} </speak>
actually
can optimze
<speak> {% if now().strftime('%H')|int < 12 %}
Good morning.
{% elif now().strftime('%H')|int >= 12 and now().strftime('%H')|int < 17 %}
Good afternoon.
{% else %}
Good evening.
{% endif %} It is {{ now().strftime("%I:%M %p") }}. The high today is {{ (state_attr('weather.home_hourly',
'forecast') | map(attribute="temperature") | list)[0:16] | max }}
degrees and the low is {{ (state_attr('weather.home_hourly', 'forecast')
| map(attribute="temperature") | list)[0:16] | min }} degrees. <break
time=".03s"/> It is currently {{state_attr('weather.home_hourly',
'temperature') }} degrees outside.
{% set ns = namespace(previous=-300) %}
- <break time=".03s"/> at {{ (hourly.datetime | as_datetime | as_local).strftime("%I %p") }} it will be {{ hourly.temperature }} degrees outside.
{% set ns.previous = hourly.temperature %}
{% endfor %} </speak>
What's the difference between the 2? This is slightly over my head as I haven't used for loops before.
it just moves the if statement in the for loop line
you can keep whichever one you want
unfortunately we need namespace in order to capture the previous result. Jinja has a scoping issue where you can't define variables inside a loop and expect it to update. You ahve to use namespace in order to do that.
either way, that should work as long as I didn't add any typos
Other than temperatere in the first one no typos it worked. Thanks again. This is addicting as I'm building out a full temperature briefing now. Next additions will be cloudy,sunny and precipitation.
Ah, you can put breaks in an amazon polly TTS, would be nice if that was also possible for Google Home
you can get that info from hourly variable inside the loop
hourly.condition
same with wind direction, etc
How would I add condition for example? And yes when I first used this with cloud say It was too fast and Polly is amazing. The breaks are customizeable and it can do a lot more.
I'm not sure what you mean? If you want the condition in text, just use {{ hourly.condition }} to get the word in the condition variable
I wasn't sure if it would mess up the loop. But yes that makes sense. The precipitation addition would be different as I wouldn't care if the precipitation was 0% only if above 60% chance so that would require additional logic vs condition is simply dropping an additional variable. What does the -300 do
it sets the previous temperature to -300 degrees
so the first hourly temperature will be output
Usually they are closer and not off by that much but thank you for the help I'll look for additional integrations with forecast and modify the template for that so it's more accurate.
- binary_sensor:
- name: "Outside heat"
delay_on: "1:12:00"
state: >
{{ state_attr('weather.home','temperature') > 25 }}
I wanna have this turn on only after there's been 36h of temp over 25
and the way it is now, it is on when I restart HA
right now there are 27 degrees outside
so Im guessing the delay on didnt trigger?
@mighty ledge you helped me out with a days_left sensor a while back but it's not updating everyday, except on restarts, any way of fixing this?
{% set n = today_at().date() %} {% set t = n.replace(day=8) %} {% set ns = namespace(dates = [ t.replace(year=n.year - 1, month=12), t.replace(year=n.year + 1, month=2) ]) %} {% for m in range(2, 14, 2) %} {% set ns.dates = ns.dates + [ t.replace(month=m) ] %} {% endfor %} {% set end = ns.dates | sort | select('>=', n) | first %} {% set start = ns.dates | sort | select('<=', n) | reverse | first %} {{ (end - n).days }}
you're supposed to use that with a time pattern trigger
i.e. add a trigger to your template sensor
1:12:00 is one hour and 12 minutes
guys I use this restapi to set target temperature on my TRVs
rest_command:
mihome_kitchentrv_set_15:
url: "https://mihome4u.co.uk/api/v1/subdevices/set_target_temperature"
payload: '{"id":14965,"temperature":15}'
method: POST
content_type: application/json
username: !secret mihome_username
password: !secret mihome_password
also have a sensor that can read set temp and current temp
- platform: rest
name: "MiHome KitchenTRV"
resource: 'https://mihome4u.co.uk/api/v1/subdevices/show'
method: POST
authentication: basic
username: !secret mihome_username
password: !secret mihome_password
payload: '{"id":149565}'
value_template: '{{ value_json.data.power_state }}'
json_attributes_path: "data"
json_attributes:
- label
- id
- device_id
- power_state
- startup_mode
- device_type
- remote_id
- voltage
- voltage_reported_at
- updated_at
- target_temperature
- last_temperature
headers:
Content-Type: application/json
force_update: true
scan_interval: 60
I would like to have it a bit smarter. Is there a way to make some template turn it into thermostat and when I set new value it will be automatically set to this restaip as "temperature:"
Please don' t use the edit post feature to circumvent the maximum post length rules.
Sheesh
sorry I am new to discord and keep pressing enter for new line without shift. Sorry.
Is it possible in a template switch to include an action if the condition fails?
friendly_name: "T1 Hummer"
value_template: "{{ states('switch.t1hum1') }}"
turn_on:
- condition: state
entity_id: input_boolean.enabler_t1_hum1
state: 'on'
- service: switch.turn_on
target:
entity_id: switch.t1hum1
turn_off:
- service: switch.turn_off
data:
entity_id: switch.t1hum1 ```
could i run a notify if it fails the condition?
Use a choose:?
just found that suggestion as I'm trying to research in parallel
that would let me have an anternate action
Or if/else
can you give an example of how you would add if/else to that template switch
where would it go ?
k will go look thanks Rob!
I've used plenty of if/else just not inside and respective with conditions
oh wait can i just write the turn_on: section like a template sensor?
just what I would use for a value template ?
Like a script, which it is
Template warning: 'int' got invalid input 'None' when rendering template
{{ state_attr('light.hallway', 'brightness')|int < (75*2.55)|int }}
{%else%}
{%if states('sensor.light_sensor_illuminance')|int > 350 %} {{state_attr('light.hallway', 'brightness') != 'None'}}
{%else%}
{{state_attr('light.hallway', 'brightness') |int < ((75-sqrt((((states('sensor.light_sensor_illuminance'))|int-2)/350))*75)*2.55)|round}}
{%endif%}
{%endif%}
{{state_attr('light.hallway', 'brightness') }}```
but no default was specified. Currently 'int' will return '0', however this template will fail to render in Home Assistant core 2022.6
what exactly does this warning mean
i dont really wanna mess with something i dont understand, but it looks there theres something i need to change
I can not find an example close enough to my current template switch sytax that shows me how to work the if/else into my switch, and with it being a template switch need to reboot home assistant every single time to test a guess, can you perhaps point me at an example I can work from ? (Sorry I'm not trying to have you do it for me just can't translate the examples)
or is there a way to just keep testing my code inside Developer Tools that way you can with a sensor?
You can reload template entities at runtime, you don't need to restart HA
thanks that helps
is there a way i can stop an entity from reporting its values so i can mess with it in the template editor
@orchid oxide you want to just have it report dummy data? you could make a helper that is input_number type and just use that as a place holder till you are done
Hi All, I am very new to HA, so I'm not sure if this is the correct forum of category for my questions. I have created some hardware that is publishing to mqtt in raw text data, not using json. I have added a sensor card to the dashboard but cannot get any connection to the mqtt broker. I add a sensor in config.yaml as below
sensor:
- platform: mqtt
name: "Tank 2"
unique_id: tank2_level
state_topic: "Bills_Mesh/master/tank2/level"
unit_of_measurement: "%"
value_template: "{{ state.value.level }}"
I suspect the value_template is not correct but can't find any examples to know what to use
Any help would be greatly appreciated
A lot of sensors seem to support a value_template. Is there a value_template I could use for any sensor that supports value_template that would prevent that sensor from ever being unknown or unavailable, most importantly EVEN AFTER A RESTART?
Scott this is something i saw in an example to fix non-numeric value when the value is unknown etc : value_template: "{{ states('sensor.pv_power') | float }}"
@atomic blade For a template sensor you can add an availability template, the best template for that will differ based on how many source entities you are using and what kind of states they can have (only numbers, or also other string values).
What is the simplest way to say greater than positive 3 or - 3. -3 would mean the temperature fell. Positive 3 it went up. Can that be done in the same statement?
{{ state_attr('weather.openweathermap','forecast')[0] .temperature | float(0)
- state_attr('weather.openweathermap', 'temperature') | float(0) < - 3 or < 3 }}
I didn't think that would work but I'm wondering if there's a way it could?
Don't to mean < -3 or > 3
Oh yeah that lol. That's what I have in the script I am using that just has > 3 as a condition. I quickly put that together and didn't think about the sign for the positive number.
{{ (state_attr('weather.openweathermap','forecast')[0].temperature - state_attr('weather.openweathermap', 'temperature')) | abs > 3 }} will do the trick
btw, these attributes are already stored as number, you don't need to convert them to float
Perfect and should I just get rid of float then? Int is not necessary either?
int is also not needed
Sounds good thank you
I've adjusted the template above
Perfect thank you.
I need some help creating an automation using a template to list the items in a for-each list. I have several scripts I need to traverse through and needs to be killed.
The scripts are in the format: script.vacuum_
https://www.home-assistant.io/docs/scripts/#for-each
An example to such a template would be very much appreciated.
@earnest cosmos No need for a for_each here
- service: script.turn_off
target:
entity_id: "{{ states.script | selectattr('state', 'eq', 'on') | map(attribute='entity_id') | select('match', '^script.vacuum_') | list }}"
Thank you, @marble jackal 👍🏻
Hi - I've got 2 sensors that I'm merging with a template and was wondering if there was a way to get the average value only if both sensors are responsing properly?
At the moment, if I pipe this to average - then if one sensor is offline, I only get half the value.
{{ (state_attr('binary_sensor.lounge_door_sensor_occupancy', 'temperature') | int, state_attr('binary_sensor.lounge_sofa_sensor_occupancy', 'temperature') | int) | min }}
how do you know if they are responding properly?
currently I don't - | int is converting the None to a 0, which results in the halved averages - previously it was just breaking the sensor completely
basically - if the sensor is misbehaving - the attribute doesn't exist
ok, that's what I wanted to know
normally I'd search for "filter" - but that means something different in template land, so I'm hitting a brick wall 😂
effectively, I want to pre-filter the list of sensor attributes with is_number or > 0 before I average it
{% set sensors = expand('binary_sensor.lounge_door_sensor_occupancy', 'binary_sensor.lounge_sofa_sensor_occupancy') %}
{% set temperatures = sensors | selectattr('attributes.temperature', 'defined') | selectattr('attributes.temperature', 'is_number') | map(attribute='attributes.temperature') | list %}
{{ temperature | average if temperatures | length == sensors | length else none }}
that will be unavailable if either temperature is unavailable
{{ expand('binary_sensor.lounge_door_sensor_occupancy', 'binary_sensor.lounge_sofa_sensor_occupancy') | selectattr('attributes.temperature', 'defined') | map(attribute='attributes.temperature') | list | average }} perfect
thanks
FYI, removing the is_number will cause this to potentially fail if temperature isn't populated
yeah I tweaked it further - but the important bit is you pointed me at expand / list
and map I guess
but that bit I kind of knew, just didn't know how to apply it here
min/max will do and/or logic on truthy values too it seems 🙂
yep
I've got 2 hue motion sensors that like to trip out occasionally - this should finally resolve that issue
they're secondary sensors just to add extra reliability to the detection, the irony being they're unreliable themselves 😂 now at least they won't take the entire automation down if they act up
That's sensors for you, I haven't found any that are 100% reliable
they all have issues somewhere
What does the availability of a sensor affect?
It will affect if your template sensor will return unavailable or will render the state for the value template
So you can for example check if your source sensor is available, if not, return unavailable for the template sensor as well
I'm wondering if this would help with issues I've had in the past with template sensors still rendering unknown even if I have what I thought were guards against it
If you give an example for one of the sensors for which you have issues, that might help in giving the best advice
Please use a code share site to share code or logs, for example:
- https://dpaste.org/ (select YAML for the language)
- https://www.codepile.net/ (select YAML as the language)
- https://paste.debian.net/ (you guessed it, select YAML as the language)
Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.
I've tried this and the template sensor would still render unknown sometimes, I believe after startup:
{% if is_state('sensor.base_sensor', 'unknown') %}
{{ states('sensor.this_template_sensor') }}
{% else %}
{{ states('sensor.base_sensor') }}
{% endif %}
Basically base_sensor would report unknown sometimes and I wanted to use the last value
So I tried making a template sensor (this_template_sensor) that would wrap base_sensor to protect it from reporting as unknown
And with recent HA updates where template sensors are supposed to report their last state on startup, I thought this would be bulletproof but it doesn't seem to be
As far as I know this only applies to trigger based template sensors
Oh ok that actually does sound familiar. I think that did fix a problem with another sensor I had. So is there any reliable way to protect a sensor from ever reporting as unknown
No, because not everything can be loaded at the same time during startup, and before your template sensor is loaded, it will report unknown
I think I'd be OK with it reporting unknown during startup, but I'd like it to eventually converge on using it's last value
I've added a template to configuration.yaml. Is there a way to reload the config without restarting HA completely. I can see several options for YAML configuration reloading under developer tools->YAML but wasn't sure which one would reload templates/sensors
yes, there's an option to reload template entities there
Thanks, is there a way to load the sensors? or if you could point me to some docs I can look it up.
template sensors are templates
if you had no template entities at all before, then you need to restart HA for that to show up
I think we need a larger image of that
is it possible to do a single line if else set?
something like this, but obivously im doing it wrong
{%set elevation = state_attr('sun.sun', 'elevation' - minelevation) if state_attr('sun.sun', 'elevation') > '-5' else -5 %}
this one gets me TemplateSyntaxError: Expected an expression, got 'end of print statement'
should be ('sun.sun', 'elevation' ) - minelevation
huh, didnt catch that, sorry. getting rid of quotes there makes it work
Hello, how can I make a binary sensor through templating to show how much light entity was on during one day?
If you want to show how much, a binary_sensor is not your best choice. They only indicate yes/no, on/off.
But if you describe your case a bit more, I'm sure there's some other sensor that can do what you want.
Another thing: I was about to update my old binary_sensor templates to the new format. It seems there's no "friendly_name" in the new template format.
I typically want my entities to have names in English, but friendly names in Swedish.
Is traditional customize the way to go then? I thought they wanted to move away from customizing?
I want for e ample to have just a number entity like: Toilet light today: 5h 36min
So…. Not a binary sensor
That's what history_stats can do for you
Not sure what I'm doing wrong here
{% if '{{ entity_id }}' == media_player.bedroom_speaker %}
media_player.bedroom_speaker {% elif '{{ entity_id }}' ==
media_player.family_room %} media_player.family_room {% else %} {%
endif %}
There's the possibility the entity_id is another one that I don't want to have the source changed for otherwise I would just use the variable entity_id. I'm attempting to only set the source if the entity_id is one of those 2. The variable works elsewhere in the script. I assume I just didn't do this template properly.
You're nesting templates
For more context.
- service: media_player.select_source
data:
source: TV
target:
entity_id: >-
{% if '{{ entity_id }}' == media_player.bedroom_speaker %}
media_player.bedroom_speaker {% elif '{{ entity_id }}' ==
media_player.family_room %} media_player.family_room {% else %} {%
endif %}
Welp can you assist me lol that's why I came here to untangle the mess.
Where does entity_id come from?
I'm passing it from a service call
alright
service: script.outside_temperature_tts
data:
entity_id: "media_player.bedroom_speaker"
- service: media_player.select_source
data:
source: TV
target:
entity_id: "{{ entity_id }}"
right?
Well yes but I'm trying to not set it for a specific entity Id. One of the speakers isn't connected to a tv so I'm trying to avoid telling it to set the source to tv by filtering out one of them.
Specifically media_player.master_bedroom
you can't not set it
you need to use a condition above that action to not run the action
you can't just leave it blank
I see. What would the condition be as it's a variable?
a template condition
I'll just delete the nonsense
Hi, I`m getting the "default warning" on my template and can't seem to figure out where/how to set the default value
- sensor:
- name: "Generator Energy Meter"
unit_of_measurement: "kWh"
device_class: energy
state_class: total_increasing
state : "{{ '%0.2f'|format(state_attr('sensor.generator_average_power','energy') | float / 1000 * (now().hour + now().minute/60)) }} "
- name: "Generator Energy Meter"
2022-05-14 18:52:44 WARNING (MainThread) [homeassistant.helpers.template] Template warning: 'float' got invalid input 'None' when rendering template '{{ '%0.2f'|format(state_attr('sensor.generator_average_power','energy') | float / 1000 * (now().hour + now().minute/60)) }}' but no default was specified. Currently 'float' will return '0', however this template will fail to render in Home Assistant core 2022.6
@silent vector posted a code wall, it is moved here --> https://hastebin.com/sikijupewu
Tried that but still gets a "None" from the state_attr function
I forgot the spaces, your spacing is correct? as in float(0) / 1000
Yes but still gets me
'Template warning: 'float' got invalid input 'None' when rendering template '{{ '%0.2f'|format(state_attr('sensor.generator_average_power','energy')|float / 1000* (now().hour + now().minute/60), 0) }}' but no default was specified. Currently 'float' will return '0', however this template will fail to render in Home Assistant core 2022.6'
I think it`s complaining about getting a "None" result from either format or state_attr but not sure where the default value should go
Did you reload templates that's not the same template
Or restart
Now that you updated it, it should show float(0) / 1000 and it doesn't
Oh well... I thought that using the "reload" template entities was actually doing the same thing. I did a restart and seems to have fixed it. So I had the right syntax at some point just the wrong way of implementing it.
Thanks for the guidance
Reload does reload them but sometimes a restart is necessary to clear the erorr.
What am I doing wrong here? {{ states.binary_sensor | selectattr('attributes.icon', 'eq', 'mdi:mailbox') | list | count }} there definitely is a binary sensor with that icon attribute. I get "UndefinedError: 'homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'icon'".
There was an earlier discussion about that. I think if you'll get it if you have entities that don't have that attribute
I don't know if it's new, but it sounded like maybe it is
I see some changes earlier this year where there was a move from MappingProxy to a new ReadOnlyDict type
You have to test that it's defined first
Yeah that will be it. Some sensors have device_classes instead of icons. How do I check if it is defined?
It seems to be new that a template runs in error because of undefined attributes
Any idea why this is resulting In a 0 value in trace?
'{{ state_attr("media_player.family_room", "volume_level") | float | round(2) }}'
Template editor results '0.4'
Trace
domain: input_number
service: set_value
service_data:
value: 0
entity_id:
- input_number.family_room_volume
target:
entity_id:
- input_number.family_room_volume
Does anyone know if it's possible to add a service call into an input_select ? My doorbell has selectable mp3 tunes , but I want to add a google TTS to it as well ?
https://pastebin.ubuntu.com/p/t5wJBfT8NR/
Was the player off at that time? The volume level can not be retrieved then, as the attribute doesn't exist
If a media_player is off (in
> states) it doesn't have the attribute volume_level
So even the template editor can not retrieve it then
But the template editor is retrieving it. I just checked again.
Check the state in developer tools
'{{ state_attr("media_player.family_room", "volume_level") | float | round(2) }}'
Returns
Result type: string
'0.4'
This template listens for the following state changed events:
Entity: media_player.family_room
Is it is idle it can retrieve it
It's paused
Then the attribute exists, but not when it's off
It's a sonos that's always on.
So it's weird why in trace it is setting 0 but the template evaluates the correct volume.
Well, Google Home speakers are well, but they do show as off in HA
I expect Sonos speakers to act the same
.share the entire script/automation
Please use a code share site to share code or logs, for example:
- https://dpaste.org/ (select YAML for the language)
- https://www.codepile.net/ (select YAML as the language)
- https://paste.debian.net/ (you guessed it, select YAML as the language)
Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.
You were helping me with a different part yesterday.
Trace
params:
domain: input_number
service: set_value
service_data:
value: 0
entity_id:
- input_number.family_room_volume
target:
entity_id:
- input_number.family_room_volume
I didn't know it existed. That stores volume and source?
It should, I don't own Sonos devices, so I never used it
Perfect thank you.
Not sure if it restores volume though, but it will resume what is playing
If it doesn't, you see nothing wrong with the template/script that should result in a 0 value?
Is it doesn't, you don't need to write the old volume to an input_number, you can use a variable in the automation
Which would be using the template by itself. volume: template?
- variables:
volume_old: '{{ state_attr(entity_id, "volume_level") |float | round(2) }}'
Ah, you are nesting templates, that is why it is not working
Corrected above
I see now. Thank you.
But still, the input_number is not needed :)
Yep I will use this and restore the volume value as volume_old
If sonos restore doesn't do volume*
I have a question about the alarm control panel template. I do all my automations in Node-RED. My template looks like this:
- platform: template
panels:
safe_alarm_panel:
value_template: "{{ states('alarm_control_panel.real_alarm_panel') }}"
disarm:
service: nodered.trigger
data:
entity_id: switch.safe_alarm_panel_disarm_switch
The problem is that I don't get the entered pin code with this service call so that I could check all kind of things (I have connected a Ring Keypad so that I can give sound/light messages).
How do I get the entered pin within this service call?
The nodered trigger works perfect. (It is a HACS integration) I use it for the communication between HA and NodeRed
The only problem is that I don't the extra information
What you posted above looks like a mix of a template trigger, a service call and setting variables. I have no clue what you are trying to achieve with it
What I say, I do all my automations in Node-RED. So there has to be something that triggers a switch in Node-RED. For this I use the HACS integration: https://github.com/zachowj/hass-node-red
So when I arm home / arm away / disarm there are 3 seperate switches triggered in Node-RED so that I know what the user has done so that I can start teh correct automation.
This all work perfectly only I need the entered code in the alarm panel in Node-RED. So that should be sent as data with the service call
You have to make an automation based on your alarm panel state
To the point: everything almost works with the combination of the Ring Keypad and the HA alarm control panel. But I'm know busy with playing the sound on the keypad when the wrong code is entered
Yes but to your original question, it’s not a service call it’s a template sensor. So if you want the info in your service call, you just need to use a variable from your trigger and send it through. If your automations are in nodered then you’d probably need to do this in node red
I now get some information in Node-RED but the code is not parsed.
What do I? The alarm is armed and then I entered a wrong code and pressed disarm on the template alarm panel.
Has the alarm control panel a "code" property?
disarm:
service: nodered.trigger
data_template:
entity_id: switch.safe_alarm_panel_disarm_switch
payload:
ccode: "{code}"
Last I remember, alarm codes were events
I could be wrong as I don’t use them. Either way, you need to look at all your items in the events tab and look for an event that might fit the bill
If it’s not events, it might be a built in trigger or a sensor. In both of those cases you’d need to search for that info
okay i will search for it
He was trying to create this, but I did not recognize it https://www.home-assistant.io/integrations/alarm_control_panel.template/
That is right. But unfortunately i think it is not possible to get the entered alarm code in this alarm control panel template.
Can I make a template that just allows a user to toggle it on and off. Which then runs a node red sequence?
So an input_boolean?
Yea. That’s sounds about right. Thank you.
is it possible to include plain text in a single line if-then template? im trying to turn this into one line, but i cant figure out the proper way to format it so that it recognizes that the text is part of the output
Cleaning ({{states('sensor.current_clean_duration')}} min)
{%else%}
{{states('vacuum.robot_vacuum')|title}}
{%endif%}```
@orchid oxide state: "{{ iif (is_state('vacuum.robot_vacuum', 'cleaning'), 'Cleaning (' ~ states('sensor.current_clean_duration') ~ ' min)', states('vacuum.robot_vacuum')|title) }}"
awesome thanks
how can I add another template sensor for the same platform?
There are examples in the docs for adding multiple template sensors
Pretty sure there's a section for exactly that
this page you mean? https://www.home-assistant.io/integrations/template
Yes
you mean like this?
template:
- sensor:
- name: test
state: "{{ iif (is_state('vacuum.taileater_2_0', 'cleaning'), 'Cleaning (' ~ states('sensor.aarlo_total_cameras') ~ ' min)', states('vacuum.taileater_2_0')|title) }}"
- name: Sun Angle
unit_of_measurement: "°"
state: "{{ '%+.1f'|format(state_attr('sun.sun', 'elevation')) }}"
ah my bad, I have a restful sensor in there
or if you're using the legacy format, the first example there: https://www.home-assistant.io/integrations/template/#legacy-sensor-configuration-format
and the doc says, this only works for a single sensor per endoint
yeah I tried it with above and didn't work, but it's not the format but the type of sensor
a rest sensor isn't a template sensor
ah my bad, I have it combined in a template with a template switch
based on the rest sensors on/off state
sorry for the inconience
I need to figure out a way to convert this
{{ states.binary_sensor | selectattr('state', 'eq', 'on') | selectattr('attributes.device_class', 'eq', 'door') | list | count }}
I am getting this error
UndefinedError: 'homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'device_class'
these are door sensors and this code was working fine until the last update
any ideas
I keep getting a log error because my NAS isn't on all the time. Is there a way to make a template sensor ignore if sensor.nas_status is "unavailable" ?
nas_uptime_minutes:
friendly_name: NAS Uptime
unit_of_measurement: "mins"
value_template: >
{{ ((as_timestamp(now()) - as_timestamp(states('sensor.nas_last_boot'))) // 60)| int }}```
An availability template
the error I am getting is:
TemplateError('TypeError: unsupported operand type(s) for -: 'float' and 'NoneType'') while processing template 'Template("{{ ((as_timestamp(now()) - as_timestamp(states('sensor.nas_last_boot'))) // 60)| int }}")' for attribute '_attr_native_value' in entity 'sensor.nas_uptime_minutes'
nas_uptime_minutes:
friendly_name: NAS Uptime
unit_of_measurement: "mins"
availability_template: >-
{%- if not is_state("sensor.nas_status", "unavailable") %}
true
{%- endif %}
value_template: >
{{ ((as_timestamp(now()) - as_timestamp(states('sensor.nas_last_boot'))) // 60)| int }}```
like that?
nas_uptime_minutes:
friendly_name: NAS Uptime
unit_of_measurement: "mins"
availability_template: >
{{ not is_state('sensor.nas_status', 'unavailable') }}
value_template: >
{{ ((as_timestamp(now()) - as_timestamp(states('sensor.nas_last_boot'))) // 60)| int }}
That's not what I wrote
how about now
Still not 🙂
Yes that looks like the same issue, I checked all the door sensors and all have device_class so not sure how I fix that.
I guess I don't understand the solution
Understand what it's doing and yes
Thanks
{{ states.door | selectattr('state', 'eq', 'on') | rejectattr('attributes.device_class','search','all')| list | count }}
I tried this but it only returns 0
I know there is one door open
I'm not aware of a "door" domain
you probably wanted states.binary_sensor or something else
You are right but then how can I be sure that it only counts the binary sensors with device_class door?
Oh I think I got it
will test it now 🙂
nope still doesn't work
@tidal sinew The problem with your initial template is that you are taking all binary_sensors, and then select on a device class, even for those which don't have a device class defined
So the solution is to select only those who have a device class defined first, Rob gave you a pointer in that direction
try this:
{{ states.binary_sensor | selectattr('attributes.device_class', 'defined') | selectattr('state', 'eq', 'on') | selectattr('attributes.device_class', 'eq', 'door') | list | count }}
Thank you let me try that now.
Yes works perfect, but I don't understand this part. selectattr('attributes.device_class', 'defined')
That part does what I described above
With states.binary_sensor you are getting the state objects of all binary sensors. The selectattr('attributes.device_class', 'defined') takes out of this complete list, all binary_sensors which have the attribute device_class defined
You were getting errors because you were trying to select on a device class on binary sensors which do not have a device class attribute
AHHHHH Ok I understand now, that makes total sense to me now. Thanks so much 🙂
hey, i have this for avg humidity in my apt.
{{ (float(states('sensor.living_room_humidity')) +
float(states('sensor.kitchen_humidity')) +
float(states('sensor.office_humidity')) +
float(states('sensor.master_bathroom_humidity')) +
float(states('sensor.guest_bathroom_humidity'))) / 5 | round(2) }}%
but when i try to show it on a graph, it doesn't show as a line, but a gauge....
i'm trying to figure out the sensor templates, but the docs for them are a little confusing.