#templates-archived
1 messages Β· Page 17 of 1
Just if those sensors are "unavailable" or "unknown" that I want the sensor to be off
all of them
if any are "unavailable" or "unknown" then the sensor state should be off
{{ expand(['sensor.collingwood_short_text_0', 'sensor.outside_home_feels_like_temperature', 'sensor.outside_min_temp', 'sensor.collingwood_temp_max_0', 'sensor.collingwood_rain_chance_0', 'sensor.melbourne_pollen_count', 'sensor.collingwood_uv_category_0'])|selectattr('state', 'in', ['unavailable', 'unknown'])|list|length == 0 }}
still shows as unavailable
put it in
-> Templates and debug
UndefinedError: str object has no element ('unavailable', 'unknown')
oh, I missed a comma
Ah yes! That worked. Thank you π
Is there a way to wildcard match these results?
{{ states('sensor.openweathermap_weather') in [ 'scattered clouds' ] }}
there are many weather conditions that involve clouds, so instead of listing them all, is it possible to just wildcard "cloud" ?
will that work the same for multiple conditions? like:
{{ states('sensor.openweathermap_weather') in [ 'cloud', 'snow', 'rain' ] }}
you flipped it around again
yeah, i know. will it work for all 3 of those if i flip it around?
so i can only do 1 at a time?
was hoping to have a one-liner
i want to check for cloud,snow,rain. but wanted them to be more of a wildcard because results could equal: cloudy, snowy, rainy, etc
{{ 'blah'|regex_search('foo|bar|blah') }}
oh regex. hm
{{ states('sensor.openweathermap_weather') | regex_search('cloud|snow|rain') }}
like that? π
try it
does regex_search ignore caps? sometimes it might be Snow instead of snow
{{ 'Bar'|lower|regex_search('foo|bar|blah') }} -> True
oo i like that
thanks. ive been trying to get this figured out for a week lol
basically when weather condition changes, it will announce it to the house
{{ states('sensor.openweathermap_weather') | lower | regex_search('thunderstorm|drizzle|rain|snow|sleet|mist|smoke|haze|sand|dust|fog|ash|squalls|tornado|hurricane') }}
i think this is it, thanks
is anyone able to see why this template sensor would be unavailable?:
- platform: time
at: "05:00:00"
id: 5am
- platform: state
entity_id: sensor.outside_home_temperature
sensor:
- name: "Outside Min Temp"
unique_id: outside_min_temp
availability: "{{ states('sensor.outside_home_temperature') | is_number and states('sensor.outside_home_feels_like_temperature') | is_number }}"
unit_of_measurement: "Β°C"
device_class: temperature
state: >
{{ iif (trigger.id == '5am' or
states('sensor.outside_home_feels_like_temperature') | float < states('sensor.outside_min_temp') | float, states('sensor.outside_home_feels_like_temperature'), states('sensor.outside_min_temp')) }}"```
sensor.outside_home_temperature = 12.9
sensor.outside_home_feels_like_temperature = 7.7
at 5am it triggered and the state was 8.1
but now its Unavailable
put the availability template in
-> Templates
I tried that and it says "True"
in logs it says:
Error rendering state template for sensor.outside_min_temp: ValueError: Template error: float got invalid input 'unknown' when rendering template '{{ iif (trigger.id == '5am' or states('sensor.outside_home_feels_like_temperature') | float < states('sensor.outside_min_temp') | float, states('sensor.outside_home_feels_like_temperature'), states('sensor.outside_min_temp')) }}"' but no default was specified
which is normal since the sensor is unavailable but I am just not sure why it would be
well, there ya go
states('sensor.outside_min_temp') isn't in your availability template
I changed it: availability: "{{ states('sensor.outside_home_temperature') | is_number and states('sensor.outside_home_feels_like_temperature') | is_number and states('sensor.outside_min_temp') | is_number }}"
it's still going to be "unavailable"
now the state is "unknown" how can I have that it always shows the last known state
- name: "Outside Min Temp"
unique_id: outside_min_temp
unit_of_measurement: "Β°C"
device_class: temperature
state: >
{% set available = states('sensor.outside_home_temperature') | is_number and states('sensor.outside_home_feels_like_temperature') | is_number and states('sensor.outside_min_temp') | is_number %}
{{ this.state if not available else iif (trigger.id == '5am' or
states('sensor.outside_home_feels_like_temperature') | float < states('sensor.outside_min_temp') | float, states('sensor.outside_home_feels_like_temperature'), states('sensor.outside_min_temp')) }}
I tried that without the extra " on the end - do I have to wait for the trigger again?
the state of sensor.outside_home_feels_like_temperature just change and so did sensor.outside_home_temperature but sensor still showing as Unavailable
should I delete " availability: "{{ states('sensor.outside_home_temperature') | is_number and states('sensor.outside_home_feels_like_temperature') | is_number and states('sensor.outside_min_temp') | is_number }}""
yes, note that I removed it
ah yes - sorry I just copied the state section
I'll give it a few minutes for my states to change π
how do I force a state change?
strange - I set it to 20 and then it dropped to "1"
let me try again
when I reload the template entities it goes to 1
I'll put it back to 20 and see what happens when my sensors change with the weather outside - I'll be back in 15 mins
seems to be working - unsure why it drops to "1" when I reload
thanks for your help!
are conditions for equal to "==" or "="
tests are always "=="
TY
is there a better way to do:
- name: "Collingwood Cloudy"
availability: "{{ not is_state('sensor.collingwood_extended_text_0', 'unavailable') and not is_state('sensor.collingwood_short_text_0', 'unavailable') }}"
state: >
{{ 'cloudy' in states('sensor.collingwood_extended_text_0') or
'Cloudy' in states('sensor.collingwood_extended_text_0') or
'cloudy' in states('sensor.collingwood_short_text_0') or
'Cloudy' in states('sensor.collingwood_short_text_0') }}
I've also noticed in the history of the state that even though the binary sensor is "on" it still triggers on - is there a way to stop that so it only triggers if it goes off to on
Something like this: #templates-archived message
I'm running into a hurdle here. I have this line:
calculated_adjustment: "{{ states(target_temperature) | float - actual_temperature }}"
but I'd like to alter the end of it by adding an arbitrary 2 to it, so whatever numerical answer it comes out with, just simply add 2 to it. I assumed I needed | + 2 after actual_temperature but it doesn't seem to take...?
works great! state: > {{ states('sensor.collingwood_extended_text_0')|regex_search('cloudy') or states('sensor.collingwood_short_text_0')|regex_search('cloudy') }}
how about my issue with it changing to state on even though its already on? just trying to clean up my history
is it something like:
states('sensor.collingwood_extended_text_0')|regex_search('cloudy') or states('sensor.collingwood_short_text_0')|regex_search('cloudy'),
'off') }}```
you missed the |lower part that actually addresses the issue you had
what you did doesn't solve your problem
If it's triggering when the state doesn't change, then an attribute must be changing. There's nothing you can do about that with a template sensor, unfortunately
like this?
{{ states('sensor.collingwood_extended_text_0') | lower |regex_search('cloudy') or
states('sensor.collingwood_short_text_0') | lower |regex_search('cloudy') }}```
are there any unintended consequences I'm not thinking of if I take [snipped]...........float + calculated_adjustment ) * 2 ) | round ) / 2 }}" and instead of / 2 (which is of course a whole number) do something like / 1.9? The end result of this is a setpoint that's fed to my furnace thermostat. In one example, the output was 66.7, but my thermostat display just ends up saying 67 (only displays two digits). Perhaps that's fine?
if I divide by 1.9 it gets me more in line with where I want to be as far as the final number/answer, but couldn't help but to feel as though perhaps HA won't like that for some reason
So sensors dont save their state when restarting HA, what would be the best template to put into a template sensor created just for this, to "detect" restarts, iow only restarts trigger it?
Add a unique_id
What do you mean by adding a unique_id?
Eh?
?
So I just searched for these sensors that did not restore like a week, two ago, but couldnt find them just yet (i think they are normal sensors: history-stats) but that doesnt matter because I used this story to more easily explain what I need atm (sorry)
What I need atm is a sensor that triggers only on restarts
Will try that unique_id later when I find those problematic ones
So I think I found them, if I remember correctly its not that they kinda do not restore, the sensor they are counting becomes briefly unavailable and that triggers an On state as another cycle (=doesnt restore or merge it with the previous cycle)
Thats by design and I think unresolvable and so its a case closed for me
Atm I only need this
You could also do this:
{{ 'cloudy' in [ 'sensor.collingwood_extended_text_0', 'sensor.collingwood_short_text_0' ] | map('states') | map('lower') | join(',') }}
I need help. I trying to import this https://community.home-assistant.io/t/engine-heater-automation/132528. But this {{ strptime(((as_timestamp('1970-01-01 ' ~ states('sensor.car_heater_departure_time')) - (states('sensor.car_heater_run_time')|float *3600))|timestamp_local), '%Y-%m-%d %H:%M:%S').strftime("%H:%M") }} doesn't work. Tried in jinja and got "ValueError: Template error: strptime got invalid input '1970-01-01T14:23:00+01:00' when rendering template '{## Imitate available variables: ##}" thankful for any help.
do you have all those entities that the template requires? If yes, what are the entity_id's and what are the states?
I imported it as a package and all entities seems to be there. When I change input_number.car_heater_3h_before_temp over 10C sensor.car_heater_start_time change to never else unaviable.
input_boolean.car_heater_enable = off
input_boolean.car_heater_weekday = on
input_number.car_heater_3h_before_temp = 12.5
input_number.car_heater_hour = 19.0
input_number.car_heater_minutes = 0.0
sensor.car_heater_3h_before_start_time = unavailable
sensor.car_heater_departure_time = 19:00
sensor.car_heater_run_time = 0
sensor.car_heater_start_time = Never
that's just a bad template, use this instead:
{% set t = states('input_number.car_heater_hour') ~ ':' ~ states('input_number.car_heater_minutes') %}
{% set t = (today_at(t) - timedelta(hours=3)) or now() %}
{{ t.strftime("%H:%M") }}
TBH that whole package is crap
Oh, I see. I will try it out thank you so much. I was looking at this first. But service_template is deprecated? https://community.home-assistant.io/t/car-engine-heater-for-nordic-and-other-cold-climates/239311
it's deprecated, but you can still use it
the guy who wrote that package didn't know templates very well, or automations for that matter. It just happens to work. That's my opinion, take it with a grain of salt.
if it works for you, by all means, use it. But it's not optimized at all
well, looking at the date, it looks like he didn't have many options
so it's just old
Ok, thank you @mighty ledge . I will search for a replacement if I don't find anything I try to make this work with your suggestion.
@fading oriole I converted your message into a file since it's above 15 lines :+1:
@fading oriole are you sure you got the clamps going in the correct direction?
as for your template, rename the value fields to state and delete the state: {{ value }} line.
They aren't, but I'm not an electrician and would rather not touch it
well, you shouldn't be getting negative numbers from your values, that typically indicates the clamp is going in the wrong direction
they aren't in the correct direct, I wasn't clear enough with my response. They are definitely the wrong way around
anyways, back to your templates, you need to the beginning from
template:
sensor:
to
template:
- sensor:
all you have to do is unclamp them, spin, and clamp them
FYI, if they are going the wrong direction, the values aren't going to be correct at all
so negating the values won't help
Even if it can measure both ways? Didn't think it would be a problem cause it also measures power going from solar to the grid
if these are clamps that go on a wire, yes the direction matters
it depends on how they were wired
if you're trying to just get the return and it's installed correctly, then yes, negate the values
I will look further into it, thanks a lot for the help π
You may want to ask this in energy as I'm not an expert, you might get better answers there.
personally, I always thought that the circuit would be set up in away that you wouldn't be measuring the load vs the return on the same clamp.
it's possible you have a different setup
what is the correct way to accomplish this:
{% set camera = amcrest2 %}
https://hass.domain.com/local/alerts/"{{ states('sensor.{{camera}}_alert_image') }}"
ah, the dreaded nested template
yes
first, you're not actually assigning a string as I assume you think you are
well, thats just in template debugger
looks pretty random
the var is getting set properly and passed to the script but isnt getting resolved in the notify data section
Sorry to bother you again. With that I got ValueError: could not convert str to datetime: '19.0:0.0' I see there's to many zeros but don't know how to get rid of it.
{% set camera = 'amcrest2' %}
https://hass.domain.com/local/alerts/%22%7B%7B {{ states('sensor.' ~ camera ~ '_alert_image') }}
not sure what you're trying to do, but that's the idea
message: "{{ camera }} Alert"
data:
entity_id: "https://hass.domain.com/local/alerts/{{ states(sensor.{{camera}}_alert_image) }}"
thanks, i'll try that out
add | int after each states('')
That worked. Thanks again π
Thank you, I did have to update to image: from entity_id: but the template changes you suggested worked perfectly
Why can I add a template sensor to my energy dashboard? I don't understand, It has the good state_class and a valid unit? It does not show in the energy list for the gas sensor...
state_class: total_increasing
unit_of_measurement: kWh
device_class: energy
icon: mdi:fire
friendly_name: sensor.total_gas_energy
you're doing something wrong, based on what you have there, you're confusing the legacy and new template format. But I can't relaly tell if you are doing that because you didn't actually post what you have for your template sensor.
@meager sparrow I converted your message into a file since it's above 15 lines :+1:
no, you cannot create entities that way
I know repeat (from scripts )isn't the way to do this, but wondered if it was possible any other way
Okay, thanks Rob!
Writing them all out as in the first example is the cleanest (only) way I can do this then?
Ideally wanted them to have a defined-once set of other params i.e. min_temp max_temp etc
I could do that with variables I guess
You could use YAML anchors to reduce the repetition
Like this: ?
@meager sparrow I converted your message into a file since it's above 15 lines :+1:
That has some of the right characters in it...
I see a few errors, can't edit post π
I'll have a play, but thanks for sharing the concept
The docs say that a for_each loop in a script can iterate over a list returned from a template, but there are@no examples of how to return a list from a template. Any ideas?
I can give a lot of examples of a template returning a list
But it might be easier if you give some more insight in what you would need
Iβve figured it out now. It seems that a string formatted like a JavaScript list equates to a list.
Iβm pretty much there with my mission now- I want to set each light that is on in a group to 20% of its current brightness - not 20% overall
formatted like a python or JSON list
repeat:
for_each: "{{ states.light | selectattr('attributes.brightness', 'defined') | map(attribute='entity_id') | list }}"
sequence:
- service: light.turn_on
target:
entity_id: "{{ repeat.item }}"
data:
brightness: "{{ state_attr(repeat.item, 'brightness') * 0.2 | round(0) }}"
Interesting. Hereβs what I came up with:
alias: Hall to 20%
sequence:
- repeat:
for_each: >-
[{% for entity_id in states.light.hall.attributes.entity_id -%} '{{
entity_id }}'{% if not loop.last %}, {% endif %}{%- endfor %}]
sequence:
- if:
- "{{ is_state(repeat.item, 'on') }}"
then:
- service: light.turn_on
data:
entity_id: "{{ repeat.item }}"
brightness: "{{ (state_attr(repeat.item,'brightness') * 0.2) | int }}"
mode: single
light.hall is a light group with a few lights in it
my version was using all lights, you seem to have a light group you want to apply it to, use this then:
repeat:
for_each: "{{ expand('light.hall') | selectattr('attributes.brightness', 'defined') | map(attribute='entity_id') | list }}"
I selected on all lights which have a brightness attribute, that also means they are on, as otherwise the attribute doesn't exist
I need to read more on the templating stuff. Your version seems neater than mine.
It also filters out lights which are unavailable
Become a real Jinja2 Ninja! Don't worry my Genin, we are here to help! You can find general Jinja docs at https://jinja.palletsprojects.com/en/3.1.x/templates/, Home Assistant extensions at https://www.home-assistant.io/docs/configuration/templating/, and trigger variables at https://www.home-assistant.io/docs/automation/templating/
This channel is for support with Jinja templates. Some custom Lovelace cards support other types of templates, such as those written in JavaScript, and #frontend-archived is the right channel for that.
Please use http://pastie.org/, https://dpaste.org/, or https://paste.debian.net/ to share code or logs
Here are some links to start with
The expand function returns the entire state object, the map filter takes only the entity_id out of that
I'm off to bed now, but if you have further questions others can help here
Youβve been very helpful, thank you.
Is there a way to have an easy template where if a smart light switch toggles on or off a smart globe will also toggle to the same as the switch?
trigger:
- platform: state
entity_id: switch.smart_switch
to:
- "on"
- "off"
action:
- service: light.turn_{{ trigger.to_state.state }}
target:
entity_id: light.smart_bulb
hi. i create(d) sensors for (almost) every national team that takes part in Qatar WC through a custom integration. I have an automation notifying me every time a team scores, but i have to change at every game the name of the sensor. can i make my automation to read every sensor and notify me when an attribute changes and for what team ? http://pastie.org/p/11nfdmSG3yYt0Ww8o3Ry8C
you can just add all sensors in the entity_id field
entity_id:
- sensor.mex
- sensor.qat
- sensor.ned
- etc
true. but when mex will play ned...basically from sensor.mex i will get 1-0 if mexic scores....and sensor.ned will get...hopefully 0-1
sometimes simple things are not obvious for me. thank you π
Just use one trigger then
not both
you do need some adjustments in your template though`
@marble jackal I converted your message into a file since it's above 15 lines :+1:
thank you
the only thing is that you don't know who scored
so you also don't know who is winning π
:))))
what kind of further information is in that sensor?
you can probably add some relevant information to that message
there is team_abbr
also opponent_Abbr
i can have... in the match {{ trigger.to_state.attributes.team_abbr }} - {{
trigger.to_state.attributes.opponent_abbr }}
the score is {{ trigger.to_state.attributes.team_score }} - {{
trigger.to_state.attributes.opponent_score }}
?
yes, that will work
the only thing is that you can have ARG - KSA then, when the match is officially KSA - ARG
no
it won't be doubled, because you onlyl use the team score as trigger
not also the oponent score
host and opponent are provided by the integration....hope will be the official ksa-arg
thank you for the effort
With your current template, the team which scores will be mentioned first. If ARG scores, it will be ARG - KSA
@glossy viper
alias: WC3
description: ""
trigger:
- platform: state
entity_id:
- sensor.mex
- sensor.ned
- sensor.qat
-
attribute: team_score
action:
- service: notify.whatsapp
data:
title: S-a marcat in meci
message: >-
{% set match = trigger.to_state.attributes.event_name | replace('@', '-') %}
{% set host = match.split(' - ')[0] %}
{% set team = trigger.to_state.attributes.team_abbr %}
{% set score = [ trigger.to_state.attributes.team_score, trigger.to_state.attributes.opponent_score ] %}
In the match {{ match }} the score is {{ score | join(' - ') if team == host else score | reverse | join(' - ') }}
You're a template legend haha
Thanks!
Hey guys, is it possible to get a list of all areas in templates?
it's totally okay
{{ states | map(attribute='entity_id') | map('area_name') | reject('none') | unique | sort }}
ah okay you get all states and iterate trough them to get the area and unique the list to remove dupes. Thought about this but got afraid about the performance because this seems to be very expensive everytime, right?
yep
I guess this would be a great addition for HA if this would get a native implementation
@woven vine you can put it in the attribute of a trigger based template sensor with the HA start event as the trigger
then it's performed once when your system starts, and you can use the attribute in your templates
add the template reloaded event as a second trigger so you can easily update the data after you added/changed an area
unless there is an area updated event you can use
hey ive a basic Question. i want do send me time Difference to my Phone. Currently i send only the time. Is there a Calculation in Notifier Possible
=now-abfahrtszeit
start time attribute is in hh:mm
Part of the Automation
service: notify.mobile_app_iphone_12 data: title: π You canΒ΄t reach the current Bus. DonΒ΄t worry the next one comes soon! message: "Next start Timeπ : {{ state_attr('sensor.oebb_journey_2_2', 'startTime') }}"
Maybe someone can help me how the calculation would work
so it will look something like {{ state_attr('sensor.oebb_journey_2_2', 'startTime') }}" - now but i dont know exactly how π Maybe someone knows
It's just math
{{ (now() + timedelta(minutes=2)) - now() }}
you might need to do this:
{{ today_at(state_attr('sensor.oebb_journey_2_2', 'startTime')) - now() }}
yeah i know its very simple but i stuggle π with writing im still learning
@inner mesa that works in the Template Dev Tools in general but not as Notifier
so i need a new Template i cant do that directly in the notifier
I'm not following
you were using this:
message: "Next start Time:clock3: : {{ state_attr('sensor.oebb_journey_2_2', 'startTime') }}"
so use this:
message: "Next start Time:clock3: : {{ today_at(state_attr('sensor.oebb_journey_2_2', 'startTime')) - now() }}"
it's just a different template
sorry it works like charm @inner mesa is there any possibilitys to get away after mm:ss
{% set upcoming = "11:00" %}
{% set diff2 = today_at(upcoming) - now() %}
{{ "%s:%s"|format(diff2.seconds//3600, diff2.seconds%60) }}
-> 0:38
Im pulling a date out of an IMAP integration and it shows up as
{{ (state_attr('sensor.aaronautomation_mail','date')) }}
with the result being "Tue, 22 Nov 2022 10:58:18 -0800 (PST)" . is there a way to convert this to local? im in EST and its in PST for some reason
{% set date = "Tue, 22 Nov 2022 10:58:18 -0800 (PST)" %}
{% set dt = strptime(date[:date.rindex(' ')], "%a, %d %b %Y %H:%M:%S %z")|as_local %}
{{ dt }}
You're welcome to play around to get what you need: https://www.programiz.com/python-programming/datetime/strptime
{{ states('sensor.openweathermap_wind_speed') | float * (2.23694) }}
output = 5.010745600000001
is there a way to round this number to say...1 decimal place?
surprisingly, round(1)
wth, hang on lol
There are great docs in the channel topic
{{ states('sensor.openweathermap_wind_speed') | float * (2.23694) | round(2) }}
like this?
No, that's rounding 2.34694
move the ( in front of the 2, 54 characters to the left
You had both too many parens and also not enough π
a lot of this is learning the formatting of how to write it, not so much what needs to be done. i can figure out most things, but not sure how to format it in the yaml way
It's not yaml, it's jinja
How can I use the light.turn_on service to set the HS color to it's current color +30 %360? (plus thirty, modulo 360 since HS color can be 0-360)
With saturation remaining as is?
service: light.turn_on
target:
entity_id: light.your_light
data:
hs_color:
- "{{ [ 360, state_attr('light.your_light', 'hs_color')[0] + 30] | min }}"
- "{{ state_attr('light.your_light', 'hs_color')[1] }}"
This will only work when the light is on though , otherwise the attribute is not available
That's the plan. Thanks!
hi. i try to simplify the way i store air conditioner active time. is there a simplier way to store the hours that it was on ? i did this http://pastie.org/p/5QtflbCKFPyV87HkGeDwns but sometimes the value is stored as 0 although my air run π¦
Im adding _(component.sensor.state.duration.{{states(config.entity)}}) to state: into a custom lovelace card and it aint changing 9.31 to "duration"
Its just _(component.sensor.state.duration.9.31) in entitys state
What am I missing?
I can't figure out what you're taking about
custom:template-entity-row can make custom secondary-info and also state
But state is kinda decoupled from "gui translation of values"
So we need to do this: https://developers.home-assistant.io/blog/2020/04/23/frontend-translations/
While I added to some _(component.sensor.state.battery.{{states(config.entity)}}) and other _(component.sensor.state.window.{{states(config.entity)}}) they both work
Only duration does not atm :/
_(component.sensor.state.duration.{{states(config.entity)}})
I tried doing _(component.sensor.state.duration.['{{states(config.entity)}}']) because digit is first but it just outputs _(component.sensor.state.duration.['9.31'])
Should I ask template questions related to mushrom template card here or front-end?
Mushroom uses jinja, right?
Nm, it's definitely a card specific question
I'm feeling a bit ridiculous not finding a filter.
Want to find a minimum value of a list of objects.
{{ state_attr('weather.tomorrow_io_home_nowcast', 'forecast') Is a big old list of objects ```{'datetime': '2022-11-23T02:06:00+00:00', 'condition': 'cloudy', 'precipitation_probability': 0, 'wind_bearing': 289.13, 'temperature': 0.4, 'wind_speed': 8.32, 'precipitation': 0.0}
I just want to filter on `temperature`
selectattr will match all with temperature in it but I really just want to make it a list of temperature and | min to get the minimum
You seem to be missing map(attribute='temperature')
ah I was trying map('temperature') at one piont
just not attribute='temperature'
{{ state_attr('weather.tomorrow_io_home_nowcast', 'forecast') | map(attribute='temperature')|list|min}}
Beautiful thanks
Spent way to long on that...
A template that will show the content playing on a media_player?
Or extrapolate the source?
Inside the conditions of an automation, I want to use the following template which is checking whether the 'UNKNOWN' keyword is present in the state of sensor or not.
If yes then I have to trigger an action, but this condition is not working
condition: state
entity_id: sensor.main_door_lock
state: >-
Β Β Β Β {{'UNKNOWN' in states('sensor.main_door_lock')}}
Am I doing anything wrong here
service: mqtt.publish
data:
Β topic: alerts
Β payload_template: >- Β Β
Β Β Β {% if "UNKNOWN" in states("sensor.main_door_lock") %}
Β Β Β Β Β Β Β {{ "Unknown user is trying to open the door" }}
This is also not working
It is producing error that template value should be a string
does your doorlock sensor actually have the state 'UNKNOWN' in all caps? That's not a typical state. States are typically lowercase.
That template is missing the endif for the if statement. Also, you don't need the {{ "" }} around your output string.
Hi all,
Is it possible to directly use an OR statement if you loop through a domain?
For instance, I want to loop through all my lights with a linkquality defined or a raw_state defined.
Like this:
{{ states.light
| selectattr('attributes.linkquality', 'defined') OR selectattr('attributes.raw_state', 'defined')
| selectattr('state', 'eq', 'on')
| map(attribute='name') | join('\n')
}}
This is not working (of course), but I'd like to do something like this instead of adding a for loop after I filled a namespace with values. I hope you get what I mean.
hmmm, not possible
Thanks I was afraid so...
gotta make 2 collections and add them
I should go the for loop route then I guess
no need
Thank you!
It's indeed for a message π
π
You are using a state conditon, you should be using a template condition
this might be automation, though I am fighting to find the easiest template .... given https://pastebin.com/PXd7EQks what would be the most effective template to calculate the time between switch.turn_on and switch.turn_off in the action? So I can notify: "switch has been on for xx::xx min:sec"
ofc I also want to notify the kWh it used during that time, but that is phase 2b... π
trying to use the last_triggered (set when the condition block passes) and the last_changed of the switch seems to be my choice now..though that wont survive a restart I am afraid
still, this is what I ws looking at:```
{{(states.switch.opentherm_dhw_comfort_mode.last_changed|as_timestamp -
state_attr('automation.zonneboiler_schakelen','last_triggered')|as_timestamp)|timestamp_custom("%H:%M:%S")}}
or, using the this variable: {{(states.switch.opentherm_dhw_comfort_mode.last_changed|as_timestamp - this.attributes.last_triggered|as_timestamp |timestamp_custom("%H:%M:%S")}}
but its completely wrong...
since I manually triggered it the notification was not correct, but look at this template that is closer: it adds 1 hour
heck, I forgot ,False. sorry
that's why I avoid as_timestamp π
as_datetime, all day
no need for as_timestamp... at all
{{ states.switch.opentherm_dhw_comfort_mode.last_changed - this.attributes.last_triggered | as_datetime }}
that gives me the TypeError: float() argument must be a string or a real number, not 'datetime.timedelta' when I use the verbose automation entity
{{(states.switch.opentherm_dhw_comfort_mode.last_changed -
state_attr('automation.zonneboiler_schakelen','last_triggered'))
|as_datetime}}```
state_attr('automation.zonneboiler_schakelen','last_triggered')
|as_datetime}}```
that is a pretty confusing error message, though π
still throws the same error
not sure how that's possible becaues that's returning a timedelta
the error must be coming from something else
odd, just remove the as_datetime, apparently it's already a datetime
I wonder what the heck the code is doing there
right! that returns 0:13:03.495317
i don't know, as_datetime and as_local need an overhaul IMO to add error trapping
the as_stimestamp one won't be correct past 24 hours btw
well, I hope it will never get to that ...;-)
it should only max to 30 min or so
but to get it to be correct, what do I need? I cant leave it like this anyways, because of all the micro seconds
why not?
make it a duration sensor, set the units to seconds
how it will have hh:mm:ss in the UI
this is for my notification.... it should report in HH:MM:SS max
will only ever be MM:SS though
(...).seconds | timestamp_custom("%M:%S")
thx! yes thats very nice. btw, why is that first subtraction returning 1970... does it calculate all the way back to the beginning +13 min and 3 secs ..
because you're using as_timestamp
0 in seconds is 1970
when you subtract 2 times, you get close to zero
In the beginning...
yes, thats was what I tried to say.. in the beginning
hehe
cool. I wont do that again. this is much better
thanks!
Sorry, I needed to be on my computer to reply. Here is my templates.yaml, included in my configuration file : - sensor: - name: gas_volume unit_of_measurement: "mΒ³" state: > {{ state_attr('sensor.gazpar', 'daily')[0]['end_index_m3'] | float(0) }} icon: mdi:fire device_class: gas state_class: total_increasing - name: gas_energy unit_of_measurement: "kWh" state: > {{ states('sensor.gazpar') | float(0) }} icon: mdi:fire device_class: energy state_class: total_increasing
That should be working and you should be able to add them in the dashboard config
as long as you put that in teh template section
Both sensors are in the state tab of the dev tools. And are working. But I can't add them in the energy dashboard. The gas_volume is in the list of the available sensor for the energy panel but I can't save it when selected, the save button is gray. The gas_energy is not in the list...
ask in #energy-archived as it should be working π
You might want to add false
{{ 3600 | timestamp_custom('%H:%M', false) }} returns 01:00
{{ 3600 | timestamp_custom('%H:%M') }} returns 02:00 (because of the local timezone we are both in)
Is there a way to get an entity's icon via template if it isn't an attribute? Or alternatively, perhaps there's a way I can have the default icon show up as an attribute? It only seems to show up if you set it manually which I don't want to
nope
Bummer
thx Martijn, will do. Still, seems to me we should be able to measure the time spent on the action (endtime-begintime) of an automation in a more default way, than spelling out some actual entities and calculating their last_changed/triggered
@green scaffold I converted your message into a file since it's above 15 lines :+1:
This is for a history_stats sensor. I need the start time to always be 24 hours before now, ending with now. how would I write it?
start: "{{ now() - 24 }}"
end: "{{ now() }}"
{{ now() - timedelta(hours=24) }}
thats great, cheers
or timedelta(days=1)
you need to provide exactly two of start,end and duration. So in your usage you could do 24h duration ending now.
what if I need a percentage? I see a type: ratio there but it kind of confused me cos in the example, the time from the start time is said to be divided by the period length but in my case it would be shifting constantly
basically what percentage of the last 24 hours has the switch been on
that's just a bit of maths in your template. for example:
{{ (states('sensor.pool_filter_duration_24h_to_2am') | float * 100 / 24) | round(1) }}
oh, sorry, you want the history_stats sensor in percentage.
That's just it though, the duration won't be til 2am , the start and the endpoint will always be shifting
your period is always 24h though isnt it?
Start will be now minus 24h, and end will be now. And yes, a percentage is what I'm going for
for a history_stats sensor you provide two of start, end and duration. Home assistant works out the one you didn't provide. So even if you provide start and end, and even if those expressions vary, it still works. However, you use is simple. You want a rolling 24h up to now. so you specify the duration and the end, liek this:
- platform: history_stats name: example sensor entity_id: <your entity> state: "on" type: ratio duration: "24:00:00" end: "{{ now() }}"
here, end is now() and duration is 24h, so HA works out the start time, and since type is ratio, the output is a percentage.
Oh that makes sense
You said it before but it's just now that it clicked for me. Thanks for taking the time
no worries
So it will divide the 24 by 24?
yes. internally, it's doing [entity on time] * 100 / [sensor duration]
But won't that yield 1?
Sure I'll just pop it in see how it goes thanks a lot. Otherwise I can just do with the hours, as is
you can add lots of these sensors all targetting the same entity. so, to experiement and prove it to yourself, add one in hours, one ratio, oen with 24h duration, one with an hour duration etc. look at the state values in developer tools. you'll seen see how it works.
Is there any way to iterate through a bunch of entity_ids based on some criteria, other than forming a group? My entities are dates, thus I cannot put them into a group.
what are you actually trying to do?
I'd like to switch on heating in several rooms, based on an occupancy table. This table contains date:time information that I converted to date sensors. I'd like to regularly iterate through the sensors to see when to switch on heating.
You can put any entity in an old school group
Can you please explain what an old school group is? In the docs I see only binary sensors, covers, switches etc but no arbitrary entities.
Just scroll to the bottom of that page, there is a section on old school style groups
Looks great! Can I use the expand filter on it the same way as with the new groups?
Yep
Hi, I want to create a template that subtracts the time from the alarm time. I've found the following script, but that sets the time to one hour before at today. As my alarms are mostly set at night, I want the script to run the following day 1 hour before the alarm. I've already tried tomorrow_at but that doesn't seem to exist. How can I do that?
- name: "1uurvoorwekker"
state: "{{ today_at(states('input_datetime.smartsleep')) - timedelta(minutes=60) }}```
Do you have any info on whether it stays that way or will eventually be deprecated?
The documentation is quite fuzzy wrt its future.
it will stay
There is no alternative for dynamic groups, so this will not be removed
Great, thanks a lot!
i think what you say you want isn't quite right. you're trying to find the next occurence of a particular time of day, which might be later on today (hence today_at would work) or it might be tomorrow, if today's alarm has already passed. You therefore need an if block to see if today's alarm is in the past, or not. It can be done with IIF:
{{ today_at("10:15") if now() < today_at("10:15") else today_at("10:15") + timedelta(hours=24) }}
substitute the string time for the state of your input.
I don't really see the issue, let's say it's 23:00, and you set your alarm at 8:00
At that moment the sensor will indeed show 7:00 today, which is one day early. However, after midnight, the sensor state will change to 7:00 on that new day, and it will be correct
If you use it in a time trigger, the trigger will only look at the time part anyway
hi I would like to trigger on an event related to some entity_id, when the parent_id in the context is not null. I understand this parameter takes limited templates. How would I do this? I guess the below won't work
- platform: event
event_type: "state_changed"
event_data:
entity_id: cover.blind_gabinet
context:
parent_id: "{{ not null}}"
What on earth is a parent id?
when states are changed by automations they have a parent_id, when they are changed by users/external they are null. I would like to trigger when another automation triggered the change
You have to make that a condition, context isnβt valid in the trigger
But if I want it to be null or somethign else specific, it works perfectly well in the trigger.
this works perfectly:
trigger:
- platform: event
event_type: "state_changed"
event_data:
entity_id: cover.blind_gabinet
context:
parent_id: null
variables:
act: "off"
switch: input_boolean.blind_sunscreener_gabinet_auto
So, it needs to be a condition
The docs say "Itβs also possible to use limited templates in the event_type, event_data and context options."
Check the note π
now I understand what that means. ok π
that is interesting. i've wondered before how if you have an automation that will turn off the lights in 10 minutes etc, if someone manually controls a light (via app, switch, anything), you'd want to cancel that delayed action; this could be a way of doing it? i.e. any state change without a parent_id cancels the running automtaion
I'm exactly trying to do that -- swtich off automatic tiling on blinds when someone's touched the physical buttons
Itβs been on my list of things I want to add to all triggers, but not use the ids and use the actual entities
I have time at Christmas break to look at it
I've been reworking a number of my automations recently to use explicit states (or combinations) instead of trigger IDs and it's been a nice improvement
well i've just tried the above and it works perfectly
how do you mean?
https://hastebin.com/uhiyobafah.yaml
It's a simple enough automation
So how is that an improvement? You end up repeating a load of the trigger logic in conditions in actions? (Genuine question, Iβm learning here)
Instead of saying "if trigger id "temperature went above 5Β°C" and the tank is not full, , then do X, I just check the logic for any trigger
I could have #templates-archived triggers that only turn to on when the temperature is above 5, and when the tank is not full, but this keeps it simple.
I have to say, most of my automations have started looking like this, and if you add an extra entity to the trigger, the conditions need to be rewritten. so I suggested a condition trigger, which would trigger when a bunch of conditions become true. A kind of newbie template trigger.
I am trying to create a sensor to QC if all my lights in a group are in 'sync' for use in node red after automations. I currently have this in my sensors.yaml: http://pastie.org/p/37Ny0NMbIanBKbpaVdNlNW
This basically filters to group and in TWO templates counts unique brightness and RGB values, hopefully each yielding '1'. The third function AGAIN checks if both are congruent, also hopefully ending in '1'. If 'aggregate' = '1', then no prob, if >1 then there is more than one unique value for something, re-run automation etc.
This is clunky and not the most efficient way to gather this info I feel, plus it clutters up my sensors.yaml. Is there a more accurate way to combine these all into one, or better yet report back the specific problem light in a given group for a more direct error correction post storing the result?
successfully set my car up to schedule preconditioning for 30 minutes before work IF I have it the next day, it runs at 10pm via an automation, let me know your thoughts!
https://paste.helpch.at/ovunayexej.yaml
I could've done the enabled bit with a condition that lead to hard-coded false and departure time 0, but wanted to see what I can do with templates and kind of use them a bit
and I already had the work done for the departure, so π€·ββοΈ
okay so that just creates a sensor that's populated with the triggering entity at the time
Hi all - quick question:
Have a template sensor with state: {{state_attr('sensor.bin_days', 'nextbindate') }} which gives a value of 2022-11-26T07:00:00, but when I set device_class: timestamp (after all, this is an ISO8601 format date string), the state becomes "unknown. Am I being particularly stupid here?
Ah, solved it myself - a timestamp needs an explicit timezone (even if +00:00) on the end. Sorted.
Hello, how can I filter the on/off from binary_sensor.phone1_bluetooth_state=on; icon=mdi:bluetooth ? When I try state.sensor it says undefined
{{state.binary_sensor.phone1_bluetooth_state}} is my understanding of how this works since it's not an attribute
so this is where I am
no, that's not right
that I am sure about. can you give me a pointer how to make this work please?
that's just retrieving the state of an entity, though. it's not what you originally asked
I want to determine if bluetooth is on or off basically
alright, then see that link
and build an automation to listen for a change
then you don't need a template at all
sorry for being unclear
that's just a state trigger
well I want a notification to say the state as well, sorry for beeing incomplete as well
that still doesn't mean you need a template
ok, what would be the best way todo it then?
perhaps just start over
done
what exactly are you trying to do?
I press an aqara button to say "Papa still asleep" if bluetooth is off
the aqara buttin triggering an echo notification
wow, that's quite far afield from the original question π
I got the aqara button to work
I got the echo part to work
just need to figure out the bluetooth on/off part
that part is easy. use a state condition with that entity
well I want todo part of the work as well π
hah, that is indeed much easier i GUESS
thank you sir
sensor:
- name: 'Marantz Kamer Volume'
state_topic: "marantz/state/0/volume"
value_template: "{{ float(state) / 0.6 }}"```
I'm trying to divide a value coming from an MQTT sensor by 0.6, but I cannot figure out what the correct term to use for `state` is. I also tried `value`, but that doesn't work either. I've looked at https://www.home-assistant.io/integrations/sensor.mqtt/#examples but that mentions JSON attributes, which I believe is not what I want
What are you getting from that topic?
Any thoughts on this? Been stuck for a few days on this one. Appreciate any help.
a value like 0.08 or 0.32
If I get 0.60 I want to turn it into 1.00
Then just 'value'
and is the float() neccesary?
Maybe, maybe not. Won't hurt
huh that works, thanks! no idea why it didnt work before π
is this the new syntax? - platform: template sensors:
Can someone correct my syntax here, I want a printout to be true when none of this is met
{{ state_attr('calendar.shift_pattern', 'message') != "First Day" or "Second Day"}}
{{ state_attr('calendar.shift_pattern', 'message') not in ['First Day', 'Second Day'] }}
Thanks that worked
Thanks! I wonder why the visual studio code HA plug-in still uses this π
It understands both
I created an old-style group via yaml containing entities with timestamps and try to expand it in a template, but it gives me back an empty list. Could you give me a hint why it does not work?
The group is empty would be my guess
No, I checked it in the developer tools.
{{ expand('group.next_arrivals')}} is empty all the time.
States in Developer Tools shows the group nicely, with all its members.
What does {{ state_attr('group.next_arrivals', 'entity_id') }} show in 
UndefinedError: 'homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'temperature'
It looks it is messed up somehow, I need to see where temperature comes from.
The members of the group all have device_class: timestamp
Do I need to specify device class for the group as well?
That can't be the result from what I asked to to test above
Sorry, my mistake, I had too many templates in Developer Tools. After cleaning up it nicely shows all member entity_ids, separated by commas.
How shall I proceed from here?
If that works, expand should work as well
I might do something silly but it just does not expand. Can you recommend something else to check on?
Did you try with only {{ expand('group.next_arrivals') }} in the template editor?
Just to avoid confusion
You can try this as well {{ expand(state_attr('group.next_arrivals', 'entity_id')) }}
Yes, I've been trying all these in the template editor. I just tried both versions to no avail. Could I have bumped into a bug perhaps?
I have another group containing binary sensors (mqtt generated), and the expand works there just fine. The problematic group contains date sensors also created by mqtt.
Hi all - quick question for your thoughts. I have an on/off "switch" that is operated by two buttons (let's say "start" and "stop"), which I've configured up on a template switch. The thing is that it can take a long time (up to 5 minutes) from switching it "on" before the device confirms back its status as "on". Unfortunately, the template switch appears to time out and return to the "off" position after 10s or so, which leaves a somewhat ambiguous state until the device reports back, and the switch moves correctly to "on" some period later. Any thoughts on a better way to do this?
I'm updating a template I've been using for a while now but ran into an issue. The new datetime format contains microtime (.000) which seams to throw my rejectattr('startsAt', 'lt', now()) off for some reason. I get this error now:
TypeError: '<' not supported between instances of 'str' and 'datetime.datetime'
I've verified that the datetime string can be parsed by Date('2022-11-26T00:00:00.000+01:00')
What is wrong and any idea how to resolve it?
New data:
today:
- total: 2.9208
startsAt: '2022-11-26T00:00:00.000+01:00'
Old data:
- start: '2022-11-26T00:00:00+01:00'
end: '2022-11-26T01:00:00+01:00'
value: 2.81
i have a mqtt sensor that needs to report the battery percentage out of this message:
{
"id": 0,
"battery": {
"V": 6.23,
"percent": 100
},
"external": {
"present": false
}
}
normally i would use something like:
value_template: "{{ value_json.battery }}"
how do i get info from one layer deeper in the json? so i can use percent as the value for my mqtt sensor
value_json.battery.percent
You are comparing a string to a datetime, which is not possible
try rejectattr('startsAt', 'lt', now(). isoformat())
You are an absolute genius β€οΈ
Maybe also know how I could re-write this | map(attribute='total') to return:
[
[
startsAt: '2022-11-26T01:00:00+01:00'
value: 2.81
]
]
Well map will select a value to return. So, you'll have to skip the map
Without seeing the whole template and some data it's hard to say what you could do instead
I'm thinking if I've overcomplicated this for no reason. I have an ApexCharts chart with the electricity price and now I want to add an boolean line indicating if I've had the heater on or off (which I control from a binary sensor)
But at least it would have to be:
[
{
startsAt: '2022-11-26T01:00:00+01:00',
value: 2.81
}
]
Or similar.
I have this graph: https://imgur.com/a/k4xnEWc
And now I want another data series in there which should only be 0 or 1 showing if my heater will be triggered or not
Could that be achieved in any easier way than creating a new time series with date and value (0/1)?
So you want dots on the graph where the heater is on?
And the heater data?
@proud cradle I converted your message into a file since it's above 15 lines :+1:
The heater is controlled from the binary template_sensor I posted in the previous message.
I've tried to reproduce this by creating a group with all entities with device_class: timestamp
expand() works just fine on this group
@marble jackal thanks for the help!
I'm also gonna try to create another group of timestamp sensors to try with...
Can someone explain how I write this if else clause in Jinja/template?
https://pastebin.com/3b7WA4zE
I want to generate a new array (time series) but I don't know how I can do that.
I'm not sure what kind of values you expect in this array. But you need to use a namespace
{% set ns = namespace(vars = []) %}
{% for item in heater %}
{% if item.value < threshold %}
{% set ns.vars = ns.vars + [ 'whale'] %}
{% else %}
{% set ns.vars = ns.vars + [ 'petunis'] %}
{% endif %}
{% endfor %}
{{ ns.vars }}
Turned out like this, almost there π https://imgur.com/a/wIkNwDW
How do I get rid of the Undefined?
Don't share images of code
Please use a code share site to share code or logs, for example:
- http://pastie.org/ (select YAML for the language)
- https://dpaste.org/ (select YAML for 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.
how could I make a template to detect when a timestamp is older / not updated within the last 5 hours? This is what the time stamp format looks like; 2022-11-26T18:05:58+00:00
{{ "2022-11-26T18:05:58+00:00"|as_datetime|as_local < now() - timedelta(hours=5) }}
How could I incorporate the time stamp from the sensor named sensor.litterbotz_last_seen?
is there a simple way in jinja to convert seconds to a HH:MM:SS timestamp?
{{states.('sensor.litterbotz_last_seen')|as_datetime|as_local < now() - timedelta(hours=5) }}
Is that the correct syntax for pulling the sensor state?
{{ states('sensor.litterbotz_last_seen')|as_local < now() - timedelta(hours=5) }} I think
my lord that was all over the place
not sure if you still need as_datetime if it's a timestamp already
Returns with error; AttributeError: 'str' object has no attribute 'tzinfo'
{{states('sensor.litterbotz_last_seen')|as_datetime|as_local < now() - timedelta(hours=5) }} just no .
Thank you for helping. I'll give it a shot, I feel like I'm working on half my brain lol new born at home and loosing sleep.
oh boy definitely a lot to handle π
That does indeed seem to work. Thank you so much!
π no problem!
{{ seconds | timestamp_custom('%H:%M:%S', false) }}
thanks I'll give it a shot
looks like timestamp_custom('%X', false) does it too, guess my missing piece was the false bool thanks again
Without it the time is converted to local time
So eg 3600 as a timestamp will be 1:00 on 1st of January 1970
Without the false that will be converted to your local time, and the that time will be used
What do I need to change to make this template sensor to work as a list of values?
When I run it I get an error that the state length is too long.
Sensor
https://pastebin.com/SKzH3TVp
Template output (values - this is what I want in the sensor (to use in ApexCharts))
https://pastebin.com/uBa9xfvP
Put it in an attribute, states are limited to 255 characters and are always strings, so it won't be a list
I google that but didn't see how?
btw you are sometimes using state_attr() which is good, but also sometimes states.sensor.whatever.attributes.attribute which should be avoided
Got it, thanks.
Look at this, I'm almost there now π
https://imgur.com/a/KDA3fut
Hello
After 18pm, stock max value. After midnight go to zero and start pushing value sensor after 6am
This is the right approach?
Hey, I'm trying to configure a total_increasing template sensor that shows the time my cats slept, e.g 05h 24min
This is an increasing value which resets every night at 00:00
I was wondering how should I configure it so that it can show properly in the history stats as well as in grafana, and I wanted to know if there's a way to make this sensor only update its existing value in the database for that day instead of adding a new one(not sure if that's what total_increasing already does)
I.e should I make it hh:mm, <hours>h <minutes>m? Or is there no way for me to display both hours and minutes and I'd have to e.g have it just in minutes?
Thanks for your time!
On a second look total_increasing might not be the right type
how do i set the temperature of the climate.huiskamer entity to the input temperature from the climate.master_therm_keuken entity. the value_template attribute for temperature is wrong but how do i make it so it uses the an input value rather than a constant float number?
@green scaffold I converted your message into a file since it's above 15 lines :+1:
someone mentioned that a value_template only accepts floats, how can i use the input temperature from the master_therm_keuken to change the temp attribute of another thermostat not in config, i am desperate for a solution
state_attr not states_attr?
Anyone know how I would make this a conditional boolean true/false?
{{ states.light | selectattr('entity_id', 'in', area_entities(area)) | selectattr('attributes.color_temp_kelvin', 'defined') }}
That's not going to work how it's currently structured but the goal is to check if the attribute colo_temp_kelvin is defined
Doesn't solvd
{{ states.light | selectattr('entity_id', 'in', area_entities(area)) | selectattr('attributes.color_temp_kelvin', 'defined') | list | count > 0 }}
(I want to check if the last time the value changed was X seconds ago, so i need to be able to check the timestamp of when it last changed to be able to compare it against now())
For a heat pump that has four states (heat, cool, hot water and off), I have connected an energy meter (kWh, increasing).
How would you split the energy count over those four states? So, I want to know how much energy is used for hot water, and for heating etc.
I found the problem, the sensors in the group had one character different than the name of the sensors themselves. The state_attr listed them correctly according to the group definition but the entities it referenced were mistyped by one char. Thanks a lot and sorry for being dumb.
I have a simple template sensor called electricity_price and every time I restart HA I get an error saying "Entity id already exists - ignoring: sensor.electricity_price"
What is causing this?
electricity_price:
friendly_name: 'Electricity price incl. grid fee and tax'
unit_of_measurement: 'SEK/kWh'
device_class: energy
availability_template: >
{{ states('sensor.electricity_price_osthammar') }}
value_template: >
{{ (states('sensor.electricity_price_osthammar') | float + 0.755) }}
You seem to have two of these legacy template sensor formats, both starting with electricity_price
So besides this one above, you seem to have another one
How to check if all lights are turned off with map function but to exclude some lights? I need in combination fo the same thing for media_players entity
Hello, when working with now() in a template, is there a value for both hour and time combined or do I need to create this on my own? I basically want to check if it's before or after 7:30
Compare against today_at('07:30')
thank you sir
hi help me with binary sensor please
{{ state_attr ('switch.kitchen_button_left','state_left')
or state_attr ('switch.kitchen_button_left','state_right') = ON
}}
how write this ?
{{ 'ON' in [state_attr ('switch.kitchen_button_left','state_left'), state_attr ('switch.kitchen_button_left','state_right')] }}
{{ is_state_attr ('switch.kitchen_button_left','state_left', 'ON') or is_state_attr ('switch.kitchen_button_left','state_right', 'ON') }}
Or that
oh ) thanks
is there a way to get the timestamp of when a value changed? as in, i updated
input_number.servicenow_aaron_s_active_timeout
manually, and i want to check the last time it changed. the logbook has the time, but is there a way to retrieve that info?
Changed to 0.0 triggered by service input_number.set_value
7:29:45 AM - 5 minutes ago - Aaron
yes, with the last_changed property
so, states.input_number.servicenow_aaron_s_active_timeout.last_changed
{{ expand(states.sensor) | selectattr('device_class', 'eq', 'power' ) | list | count }}
I am trying get a value of all my energy sensors
How should I do it right?
First of all, you don't need expand here
And you as it is an attribute you are checking for, you need to use attributes.device_class
And you first need to check if it exists on each sensor, because there are probably sensors without a device_class
{{ states.sensor | selectattr('attributes.device_class', 'defined') | selectattr('attributes.device_class', 'eq', 'power') | list | count }}
Thanks!
π
Hi, Is it possible to round a value from a template sensor?
Become a real Jinja2 Ninja! Don't worry my Genin, we are here to help! You can find general Jinja docs at https://jinja.palletsprojects.com/en/3.1.x/templates/, Home Assistant extensions at https://www.home-assistant.io/docs/configuration/templating/, and trigger variables at https://www.home-assistant.io/docs/automation/templating/
This channel is for support with Jinja templates. Some custom Lovelace cards support other types of templates, such as those written in JavaScript, and #frontend-archived is the right channel for that.
Please use http://pastie.org/, https://dpaste.org/, or https://paste.debian.net/ to share code or logs
is it possible to access templates from inside Webpage Cards?
When used as a template trigger - Will this work as expected? {{ now() == today_at(states('input_datetime.birthday_message_time')) }}
just use a time trigger: https://www.home-assistant.io/docs/automation/trigger/#input-datetime
Hmmm... Not sure if it will work in this partiular use case. I'm using the trigger.entity_id in the automation. I think I got a work around using this:```
{{ is_state('sensor.birthday_test_person', '0') and now().strftime("%H:%M:%S") == states('input_datetime.birthday_message_time') }}
Not sure if this is the correct forum, but I believe this will be done using templates, hence starting here. I want to add a condition to an automation which tests the state(contents) of a sensor, before proceeding. The sensor gets updated, by an automation when a fault is reported by the automation and harvests the reference number to update the sensor. The sensor have four possible states: unavailable/unknown, None, "Your reference for the incident at <<address>> is XX of XX/XX/20XX" OR "Your call Ref XXX of XX/XX/20XX for an incident at <<address>> has been allocated". I would like to not proceed with the automation is the sensor does not have the value of one of the last two possible states. Any pointers/suggestions would be much appreciated. Thank you!
I thought of using a template sensor, with this template. And if the value is > 0 the automation may continue. But sure there might be a prettier more elegant solution.```
{% set x = states('sensor.faultreport') %}
{{ x | regex_findall(find='<<address>>', ignorecase=True) |list |count}}
That seems way too complicated. Why can't you just use input_datetime.birthday_message_time?
I have a singular input_datetime, to dermine when the message will be sent - e.g 09:00. This particular application uses the trigger ID to derive the name and contact details af the person in question, to the them a message for their birthday. I can probably change the naming conventions on the input_datetime to match the mappings in the automation and still work.
Will it be possible to trigger on a wildcard? E.gβββ
Trigger:
Platform: time
Entity_id: input_datetime.birthday_person_1
β¦
βββ
To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks.
```yaml
example: here
```
Don't forget you can edit your post rather than repeatedly posting the same thing.
you don't have a wildcard there, but you can just add multiple triggers
I would like to select all my Shelly devices of a specific type (like the following example: all Shelly 1PM units) This info is available as additional info of the Device, but not as an attribute. Is it nevertheless possible to use this to filter out all the Shellies of this type?
Look into device_attr
I am trying to get a list of all media_player entities. I tried this but I'm not sure how to get the var device into a list not str
{% set device_list = states.media_player|selectattr('domain','eq','media_player')|map(attribute='entity_id')|list %}
{% set data = namespace(entities=[]) %}
{% for device in device_list %}
{%- set data.entities = data.entities + (device) -%}
{% endfor %}
{{ data.entities | list }}
This is my error: TypeError: can only concatenate list (not "str") to list
nvm: After I typed it out, I realised its all extra. Its already a list. π€¦
Now I need to filter out the "unavailable" devices.
{% set device_list = states.media_player|rejectattr('state','eq','unavailable')|map(attribute='entity_id')|list %}
After some rest, you are right, This can work perfectly - I was using input_datetime with just a time value and had my head so far down the rabbit hole I could not see the simplicity. Thank you!
for this to work (although you indeed don't need it at all) you need to use [device] instead of (device) in {%- set data.entities = data.entities + (device) -%}
hey Fes and @mighty ledge - I am revisiting this one. I have this sensor set up, however it does not change. it only ever triggers the automation it relates to at 10pm, but of course then never changes the input_select to change the actual tariff, no idea where it is going wrong in the template though....
replied to the old one so you had a point of reference in time π
it wont change the terrif
why not?
because templates only update themselves?
template sensor - https://hastebin.com/yuretiqalo.csharp
utility_meter - https://hastebin.com/yariqofine.properties
automation - https://hastebin.com/kuqivafica.yaml
it is meant to trigger the automation no?
when its state changes to anything other than unavailable or unknown
does the template sensor change?
i don't think it does
and is the entity_id sensor.tariff_price, because based on the conig it would be sensor.electricity_tariff
that's not the right sensor
and based on the name of your sensor, your entity_id in the automation should be sensor.electricity_tariff not sensor.tariff_price
oh i'm slow this morning
π€£
that one is actually returning the price, not the description
that link doesn't work
seems to be the same sensor, if there is a graph it has a numeric state
omg
you can't plot peak, off-peak and shoulder in a graph
ah
well, not in a line graph
can you please use the states page instead
BTW your config of the template sensor is not the correct one, the one you linked to to start this conversation is the right one
so, if I were to just change the entity in the automation trigger, it should work?
developer tools -> states. Type tariff in the entity_id field
in the automation?
because of the off-peak vs offpeak?
rest looked the same to me
I don't see anything wrong after confirming that your entity_id was correct
the template sensor should update once per minute on the minute, and you should see it changing states
any way to test it here and now, rather than waiting until 7am?
remove the unit_of_measurement to see the text states not the graph
nope, the summer period peak check should end at 20:00 not at 22:00
the offpeak was actually correct
ahhh yep
this is the correct config, I also removed the unit_of_measurement as it makes no sense on this sensor
the spacing of the template is to the left a bit, that ok?
it's indented 2 spaces compared to state: which is correct, yours was indented a bit too far to the right
ahhh right
also, i gave it the name Electricity Tariff, why would it not appear as sensor.electricity_tariff ? Instead it is sensor.tariff_price
because it already had that name before you renamed it in the config, and as it has a unique_id the enity_id was already stored in the storage
its messy... sigh
renamed it in the UI, the entity ID
so now its just sensor.electricity_tariff
now, how can I test this?
you have to wait
i guess its time to go to bed then π
if you got rid of the unit_of_measurement, you can now see the state changes in history
yep, did that. thanks a lot
i don't know why i had it in there tbh
thanks legends, you guys are a wealth of knowledge
I'm a bit hungover, so i'm a weth of knowledge
probably missing more than a couple of letters π€£
You might want to change the template to this though:
{% set n = now() %}
{% set summer = [ 11, 12, 1, 2, 3] %}
{% set winter = [ 6, 7, 8 ] %}
{% if today_at('07:00') < n < today_at('22:00') %}
{% if (now().month in summer and today_at('14:00') < n < today_at('20:00'))
or (now().month in winter and today_at('17:00') < n < today_at('22:00'))
%}
peak
{% else %}
shoulder
{% endif %}
{% else %}
offpeak
{% endif %}
It was complaining that I can't define a variable called now (well it didn't say that, took me some time to figure out why it errored)
Wonder if he will see this before going to bed, otherwise he will have to wait longer to see if it works
i did
π
i just changed it, now sensor.tariff_price is back. should I use a new UID?
if you change the unique_id it will use the name as entity_id
Not sure if this is the correct forum, but I believe this will be done using templates, hence starting here. I want to add a condition to an automation which tests the state(contents) of a sensor, before proceeding. The sensor gets updated, by an automation when a fault is reported by the automation and harvests the reference number to update the sensor. The sensor have four possible states: unavailable/unknown, None, "Your reference for the incident at <<address>> is XX of XX/XX/20XX" OR "Your call Ref XXX of XX/XX/20XX for an incident at <<address>> has been allocated". I would like to not proceed with the automation is the sensor does not have the value of one of the last two possible states. Any pointers/suggestions would be much appreciated. Thank you!
nice
I thought of using a template sensor, with this template. And if the value is > 0 the automation may continue. But sure there might be a prettier more elegant solution.```
{% set x = states('sensor.faultreport') %}
{{ x | regex_findall(find='<<address>>', ignorecase=True) |list |count}}
dude its monday...
π€·ββοΈ my team didn't play, was just there for the good times
thats the spirit. is it playoffs yet?
no they don't start til jan
far from it
i thought the superbowl was in jan
bills played on thursday
or is that valentines day?
Thank you, duly noted, I'm sure it will come in handy for something.
@little forge I converted your message into a file since it's above 15 lines :+1:
@little forge yep, and I think the only thing you need to do is add .state in your template
ah thanks Fes, misread the docs. scene selector β
As my message is too long i pasted it... Please read it and help me...
https://pastebin.com/xWeW83Lu
@hardy swallow I converted your message into a file since it's above 15 lines :+1:
Use {% if state_attr('sensor.skyq_schedule', 'skyq_scheduled_start') is not none %}
@hardy swallow is_state_attr will always return false when none, making that always pass
use what fes said
Just a quick one: rejectattr('state', 'gt', switchontime) . Switchontime is datetime format, and state is string, thus I cannot compare them. How to convert the string into datetime inline?
Thanks, i'll try it...
skyq_schedule.isoformat() if that is also the format of the state
Otherwise use .strftime() to match it
https://strftime.org for the building blocks
Sure, thanks! Will that work inline?
A, maybe stupid, question: If i change the template inside configuration.yaml am i forced to restart HA to have the changes effect?
Yes, the they are in the same format.
yes or just restart template sensors
How to do this?
ah, ok, already did it, but it seems have no effect
Yes,
the error would now we different if you're getting an error
Did you save the file? I sometimes make that mistake
Ok the reload worked, but the markdown card related to this template is not shown. May i post this card here to trace the error?
Sorry, I'm lost a bit, could you please help me with a oneliner on how to convert the state string into dateformat inline?
No, you need to convert the datetime to a string
rejectattr('state', 'gt', switchontime.isoformat())
Oh, I thought the state was in str and my object was in datetime.
Yes, that is correct
.isoformat() converts a datetime object to a string in the ISO datetime format
All right, so I cannot compare objects, but strings in the same format?
Sure
Thanks.... when at home i'll post it...
You can compare a string to a string, and a datetime to a datetime. But not a string to a datetime
My first idea was to convert the string to datetime. But I did not know how to applystrptime() on 'state' within rejectattr.
You can't, that's why I suggested to convert the datetime object you are comparing it to to a string
I got it, thanks a lot!!!!
The markdown is the following:
{% set recordings = state_attr('sensor.sky_q_schedule', 'skyq_recordings') %}
{% if recordings is sequence and recordings|length > 0 and recordings[0].skyq_recording_title is defined %}
**Recording Now:** {{ recordings[0].skyq_recording_title }}
{{as_timestamp (recordings[0].skyq_recording_start) | timestamp_custom('**Started:** %H:%M') }}
{{as_timestamp (recordings[0].skyq_recording_end) | timestamp_custom('**Ends:** %H:%M') }}
{% else %}
**Actually Not Recording**
{% endif %}
**Next Recording:** {{state_attr ('sensor.sky_q_schedule', 'skyq_scheduled_title')}}
{{ as_timestamp(state_attr('sensor.sky_q_schedule', 'skyq_scheduled_start')) | timestamp_custom('Starts: %A %dth %H:%M') }}
{{ as_timestamp(state_attr('sensor.sky_q_schedule', 'skyq_scheduled_end')) | timestamp_custom('Ends: %A %dth %H:%M') }}
**Disk Capacity Remaining:** {{states ('sensor.sky_q_used_storage')}}Gb ( {{state_attr ('sensor.sky_q_used_storage', 'skyq_storage_percent')}}% )
```
and i get the following error:
ValueError: Template error: as_timestamp got invalid input 'None' when rendering template
'{% set recordings = state_attr('sensor.sky_q_schedule', 'skyq_recordings') %}
{% if recordings is sequence and recordings|length > 0 and recordings[0].skyq_recording_title is defined %}
**Recording Now:** {{ recordings[0].skyq_recording_title }}
{{as_timestamp (recordings[0].skyq_recording_start) | timestamp_custom('**Started:** %H:%M') }}
{{as_timestamp (recordings[0].skyq_recording_end) | timestamp_custom('**Ends:** %H:%M') }}
{% else %}
**Actually Not Recording**
{% endif %}
**Next Recording:** {{state_attr ('sensor.sky_q_schedule', 'skyq_scheduled_title')}}
{{ as_timestamp(state_attr('sensor.sky_q_schedule', 'skyq_scheduled_start')) | timestamp_custom('Starts: %A %dth %H:%M') }}
{{ as_timestamp(state_attr('sensor.sky_q_schedule', 'skyq_scheduled_end')) | timestamp_custom('Ends: %A %dth %H:%M') }}
**Disk Capacity Remaining:** {{states ('sensor.sky_q_used_storage')}}Gb ( {{state_attr ('sensor.sky_q_used_storage', 'skyq_storage_percent')}}% )'
but no default was specified
```
You have to make the same changes that you made above. add if statements around all the attributes you're getting.
Thanks, for understanding better, please put one example and i will do the rest
Your own template sensor is the example
ok i must put the if statement in every state_attr?
yep
hmmm...... i'll try also if i am not so able with templates... π¦
I have no idea what you're saying
did you copy those templates or did you create them?
if you created them, you should have no problem with this.
Oh, i copied....
ok, thanks
{{ 'happy' if petro == 'moved to HA Container' else 'sad' }}
sad

It worked 
Thanks a lot guys for persevering with me
Trying to wrap my head around it, if I would like to update an input_datetime.XXX, which has a date and time value, using input_datetime.set_datetime, but would like to increment the year with one. E.g should it run now, the result would be 2023-11-28 09:00:00. The example below would set todays date if I'm correct. Any help will be appreciated... ```
- service: input_datetime.set_datetime
target:
entity_id: input_datetime.XXX
data:
date: "{{ now().strftime('%Y-%m-%d') }}"
Unfortunately, timedelta only takes days and weeks
better: {{ now().replace(year=now().year+1) }}
Hmmm... do I understand correctly, that I will then pass the year, month, and day individually to the data of the service call?
No
from my understanding:```
- service: input_datetime.set_datetime
target:
entity_id: input_datetime.XXX
data:
date: "{{ now().year + 1 }} {{ now().month }} {{ now().day }}"
Rendered it in the Dev Tools - For the date it works like a charm, but how do I prevent it from changing the time part of it or do I just have to specify it again?
ha - wait... date will only alter the date if I understand the docs correctly
Thank you! Much appreciated.... π
this keeps the time if just setting the date doesn't work:
{% set datetime = states('input_datetime.date_test')|as_datetime %}
{{ datetime.replace(year=datetime.year + 1) }}
->
2023-08-22 09:00:00
Thank you! Really appreciate your assistance...
I'm looking for a shortcut vs hours of typing. I have a bunch of sensors, which I can pull a list with a template. The naming convention is similiar to the new datetime objects. e.g Current: sensor.birthday_person_one and New: input_datetime.birthday_person_one. The current sensors have an attribute "date" of which the value I would like to set to the new input_datetime object. Now I'm sure a for loop should be able to do it, but its a bit beyond my reach... Can someone perhaps assist or point me towards an example I can learn/derive from?
I got the list of entities using:```
{{ states.sensor| selectattr('entity_id', 'search', 'birthday_') | map(attribute='entity_id') | list }}
how were you planning to set the attribute of a sensor?
where do the sensors come from?
The sensors were manually captured by me originally using the custom anniversary component. They have the correct dates. I thought if I could loop through them, extract the date attribute, and use the service call set_datetime to set the date to the the date time entity using replace (sensor --> input_datetime).
it's still not clear to me how you will be able to set an attribute of the sensors provided by that integration
sensors are read-only
I would like to read the attribute from the sensors, then use set_datetime to set the date on the datetime objects
The datetime objects are newly created, all with todays date
ok
The logic in my head runs something like this:```
For each sensor in birthday_Sensors
get date attribute from sensor
mangle entity_id from sensor.birthday_person_one to input_datetime.birthday_person_one
service call - set input_datetime using extracted date attribute.
end of loop
I hope it makes sense π
I was thinking of doing it in a script, because the service dev tools doent support teplates.
Where I'm currently stuck, is how do I get form the list to an array I can loop through?
standard Jinja syntax: ['person_1', 'person_2']
there's an easier example in the docs: https://www.home-assistant.io/docs/scripts/#for-each
Let me start fiddling there... thx!
Sorry for all the questions - Major learning curve here... This seems to create strings, so I'm unsure how to get the date attribute from there. {{ states.sensor| selectattr('entity_id', 'search', 'birthday_') | map(attribute='entity_id') | list }}
you're mapping the entity_id at the end, map the state instead
Thx! Let me try that... Appreciate the pointer! π
I probably am - but I'm learning a lot π€£
I just read everything, what's the actual endgoal here
why you trying to increment the year on a datetime
- Make a list of substrings like person_1, person_2
- Build a for_each loop that iterates through that list
- One
input_datetime.set_datetimeservice call in the loop with the entity constructed from'input_datetime.' ~ repeat.itemand thedatetime: "{{ state_attr('sensor.' ~ repeat.item, 'date') }}"
Yeah, that's what I would do, but why even have these input_datetimes... what's the point
you have the sensor already
the current sensors only have a date value, which means at midnight it becomes "active" for the day. Now not everyone will appreciate a happy birthday message at midnight, so I would like to fire it later in the day. I orignally foudna way of doing it with a template sensor, but that generated a lot of duplicate work. Rob then suggested date_time which makes a lot of sense as it has a date and time, and I can adjust it for different time zones which is awesome. So without manually recreating everything, I would like to transplant the data.
Thx! Let me quickly try that.
just make an automation that fires at a specific time in the day that checks the current date and notifies whoever's day is up
no reason for datetimes
Petro - The end use case is to fire happy birthday messages on a predetermined time using a single automation using mappings with the number/email based ont he trigger.id
what's the format of today?
er, the sensor
and what's the format of the sensor's name
the sensor does a count down - so it goes to '0' on the day
sensor name = sensor.birthday_name_surname
right, but the actual name of the sensor
well, ok, i'll just work with that
so the sensors count down to zero?
and how are you notifying people?
right, but how do you know what notify to call?
@paper hazel basically, can you post an example notification that you're using to send the happy birthday message
I'm almost done with the automation
I just need that piece
One day I will be that quick.... π
so you got the example notification?
@paper hazel
- alias: Notify Birthday
trigger:
- platform: time
at: "10:00"
variables:
config:
test_person: 2712345678@s.whatsapp.net
people: >
{{ states.sensor | selectattr('object_id', 'search', '^birthday_') | selectattr('state','eq','0') | map(attribute='object_id') | map('replace', 'birthday_', '') | list }}
items: >
{% set ns = namespace(ret = []) %}
{% for sensor in sensors if config.get(sensor, False) %}
{% set ns.ret = ns.ret + [ {'name': sensor | replace('_', ' ') | title, 'whatsapp': config[sensor] } ] %}
{% endfor %}
{{ ns.ret }}
condition:
- platform: template
value_template: "{{ items | length > 0 }}"
action:
- repeat:
for_each: "{{ items }}"
sequence:
- service: whatsapp.send_message
data:
clientId: default
to: "{{ repeat.item.whatsapp }}"
body:
text: "Happy birthday {{ repeat.item.name }}"
add your people to config
and you're done
change the time you want to notify at too
Wow!!!! 
I'm trying to learn and wrap my head around this - Could you perhaps explain the voodoo under items?
states.sensor | selectattr('object_id', 'search', '^birthday_') | selectattr('state','eq','0') -> filters all states down to entities starting with birthday with a zero state
| map(attribute='object_id') | map('replace', 'birthday_', '') | list -> maps the filtered list to just object_id's and replaces birthday_ with nothing
{% set ns = namespace(ret = []) %} -> creates an empty list
what does the (ret = []) do? or is that the empty list?
{% for sensor in sensors if config.get(sensor, False) %} -> iterates sensors and tries to get the whatsapp id out of the configuration. If that fails, it doesn't use that iteration
creating lists in jinja requires namespace, otherwise the list items don't persist each iteration of a for loop
{% set ns.ret = ns.ret + [ {'name': sensor | replace('_', ' ') | title, 'whatsapp': config[sensor] } ] %} adds 1 dictionary to the list with 2 attributes, name and whatsapp (the id).
{% endfor %}
{{ ns.ret }}
``` Ends the foor loop and outputs the resulting list
Is this just years of experience or pure genius - absolutely mind blown...
I have been butchering at this for about two evenings flopping around between various methods
π€·ββοΈ
Thank you so much for this, and for the time to explain it to me. It is really really appreciated and valued. Both you and Rob's asssitance have helped me tremendously with this and previous endeavours.
I just think βwhen I add a person in the future, how much work will I want to put into itβ
then I design around that
That being βfuture petro doesnβt want to do shitβ
Same here - but the lack of design skill sometimes makes designing the task longer than doing it manually π€£
Anything that need to happen more than once, must be automated...
@inner mesa & @mighty ledge Just want to thank you again for everything! This forum and the people here are just awesome! π
I added the automation, but gets an error on this condition:```
- platform: template
value_template: "{{ items | length > 0 }}"
Invalid config for [automation]: Unexpected value for condition: 'None'. Expected and, device, not, numeric_state, or, state, sun, template, time, trigger, zone @ data['condition'][2]. Got None. (See ?, line ?).
Had to re-enable the condition to lure out the correct whale... π
I can't see how that error is related to that condition
I was thinking of trying ```
{{ items | length | int > 0 }}
no
If I comment out the condition, it passes the check and on automation reload no errors and shows up
I guess "items" could be "None", rather than a list
Perhaps then ```
{{ items | count > 0 }}
items: >
{% set ns = namespace(ret = []) %}
{% for sensor in sensors if config.get(sensor, False) %}
{% set ns.ret = ns.ret + [ {'name': sensor | replace('_', ' ') | title, 'whatsapp': config[sensor] } ] %}
{% endfor %}
{{ ns.ret }}
ok, I see
added till first line after endfor
so somehow that's "None"
Hmmm... In Dev Tools I get UndefinedError: 'sensors' is undefined
right, where is "sensors" defined?
I looked for it, but could not find it, and not sure how or where to plug it in...
going to try this π€ ```
{% set ns = namespace(ret = []) %}
{% set sensors = states.sensor| selectattr('entity_id', 'search', 'birthday_') | map(attribute='entity_id') | list %}
{% for sensor in sensors if config.get(sensor, False) %}
{% set ns.ret = ns.ret + [ {'name': sensor | replace('_', ' ') | title, 'whatsapp': config[sensor] } ] %}
{% endfor %}
{{ ns.ret }}
he probably meant "people"
Hm... Think so, so then that will read for person in people?
My workaround did not work....
Will ask him tomorrow...
Its now 3:00am and I have to be up by 06:30am... time for some sleep...
Thx again! Have a good one!
just replace "sensors" with "people" in the for loop. nothing else needs to change
let me quickly try...
the variable "sensor" doesn't matter
It now reads like this, but the error still shows up {% for people in sensors if config.get(sensor, False) %}
you didn't do what i said
just replace "sensors" with "people" in the for loop. nothing else needs to change
you replaced "sensor" with "people", when I said that didn't matter
π€¦ββοΈ Let me go again... Sorry
consider what you're doing
you couldn't find a definition for "sensors", so that's what you're fixing
Error is still popping up```
{% for sensor in people if config.get(sensor, False) %}
in my completely fabricated example that works in my setup, it works fine
{% set config = {"captured_today_family_room": "2712345678@s.whatsapp.net", "captured_today_living_room":"foo"} %}
{% set people = states.sensor | selectattr('object_id', 'search', '^aarlo_') | selectattr('state','eq','0') | map(attribute='object_id') | map('replace', 'aarlo_', '') | list %}
{% set ns = namespace(ret = []) %}
{% for sensor in people if config.get(sensor, False) %}
{% set ns.ret = ns.ret + [ {'name': sensor | replace('_', ' ') | title, 'whatsapp': config[sensor] } ] %}
{% endfor %}
{{ ns.ret }}
->
[
{
"name": "Captured Today Family Room",
"whatsapp": "2712345678@s.whatsapp.net"
},
{
"name": "Captured Today Living Room",
"whatsapp": "foo"
}
]
so I conclude that there's something about your entities that isn't right
In this part - should the number be in brackets? variables: config: test_person: 2712345678@s.whatsapp.net
no, but it needs to be real
if you just have that, then you didn't follow petro's instructions
They are, and correspond with the sensors names
all I did was change the strings to search for to correspond to entities that I have that have a state of "0" and changes "sensors" to "people"
and changed the config to match those entities
boom
so you'll need to debug
start by printing the value of each variable
I will make them less, and see what it does then tomorrow. testting each variable
going to be something stupid on my side - pretty sure of it...
Thx!
BEfore I crawl off - When I change the array to same format as your for config, it works. so it must be something in there. Will scratch tomorrow and try and figure it out
Thx!
np. I provided the set of changes that I made above
Is there any way to combine multiple SNMP sensors into one?
hi,I defined a template binary_sensor to get an other sensor's last_changed time, code http://pastie.org/p/2f6oGsO0BoiMH7AknmLOgc
the state is updated realtime,but the attr is not
is there somewrong?
I think you can define a template sensor and reference the others snmp sensors attribute,I'm still learning it
Yes but for my use it will require creating multiple sensors, and then referencing it by another sensor. I want to avoid that and only define one sensor that pulls in from multiple SNMP data sources
I'd like to create an automation where in the action part I call a service and specify a set of entity_ids generated by a template. I could get so far that I have the list of entity_ids generated by a loop, but it does not seem to work. Do I need to pass on the set of entity_ids as a list?
{% for i in switchonentities %} input_number.setpoint_room_{{i.entity_id.split('_')[-4] }} {% endfor %}
target: entity_id: > {% set switchontime = now() + timedelta(minutes=(states.input_number.homerseklet_beallitas_kezdete.state | int + 4200)) %} {% set switchonentities = expand('group.kovetkezo_erkezesek') | rejectattr('state', 'eq', 'unknown') | rejectattr('state', 'gt', switchontime.isoformat()) %} {% for i in switchonentities %} input_number.setpoint_room_{{i.entity_id.split('_')[-4]}} {% endfor %}
This is how the whole target specification looks like.
Is the comma missing from the end of the entity_ids? How do I delete the comma from the end of the llist?
That's...a lot of code to read through
This is the line to generate the list of entity_ids: input_number.setpoint_room_{{i.entity_id.split('_')[-4]}}
No comma there
If I put a comma to the end in the loop, there will be one at the end:
{% for i in switchonentities %} input_number.setpoint_room_{{i.entity_id.split('_')[-4] }}, {% endfor %}
Then don't add one for loop.last
Ok, I'm gonna try it!
I'm pretty sure it could be done by constructing a list, but I can't do it on my phone
π
Good morning. I've a simple question, I've my climate valve that have only climate.room entity but don't a sensor entity. is it possible to create a sensor using entity history data?