#templates-archived
1 messages · Page 32 of 1
Not sure but something like the following might work.
{{ (state_attr('sensor.gar_stations_search', 'stations) | selectattr('address.line1','eq', '7625 Sawmill Rd') | list | first) | selectattr('price.credit', 'eq', 'price')}}
how to use template: is_state('entity_id','comparative condition')
For example: is_state('entity_id', '!= off' )
I can use states('entity_id') != 'off' but I would like to learn more
how to compare with is_state
That's not what is_state is for. states is the correct function for this use case.
I don't believe it supports what you're asking for.
not is_state('entity_id', 'off')
Hi, i am trying to make a template Sensor which calculates my CO2 emission. Calculated with my power consumtion and 15.7g/kwh
This is my code but its not correct:
- name: "CO2"
unit_of_measurement: "g"
state: >
{{ states('sensor.plug_energy') * 15.7 | float(0) }}```
@maiden magnet you are converting 15.7 to a floating point number, which it already is
you need to convert the entity state to a floating point number, as all states are strings
so do i have to do it like this?
name: "CO2"
unit_of_measurement: "g"
value_template: '{{ states("sensor.plug_energy" | float )) * 15.7}}'```
this is also incorrect
Something like this
{{ states("sensor.plug_energy") | float * 15.7 }}
You should test this in the developer tools before writing it in the config: https://my.home-assistant.io/create-link/?redirect=developer_template
oh yes, this works in the template tools but how do i add it the the config correctly?
The same way as you had it but just with valid syntax
but this is not correct :(
platform: template
name: CO2
unit_of_measurement: 'g'
value_template: "{{ states('sensor.plug_energy') | float * 15.7 }}"
you can try template in Developer Tools
Check the examples here: https://www.home-assistant.io/integrations/template/
Something like this
template:
- sensor:
- name: "CO2"
state: "{{ states('sensor.plug_energy') | float * 15.7 }}"
unit_of_measurement: g
{{ states('sensor.broadlink_khai_temperature') | float * 15.7 }} is good
this is a mix of the old an new template format
what Impact posted is the new format, which should be placed directly in configuration.yaml
if you are using sensor.yaml you should use the old/legacy format
How to send images in Local with :
service: notify.hass_synchat
data:
message: teset
title: dsadsadsa
data:
file_url: /config/www/cam_captures/cam_bep_9.3.2023_15.46.png
that code don't run with file_url.
I change with https://hdjsahdjsdsadsadsdsa.png and run ok
that's not related to this channel
- sensor: - name: remaining_power unit_of_measurement: 'W' state: "{{ ( states('sensor.inverter_active_power') | float | round(1)) - ( states('sensor.smartdin_power_2') | float | round(2) - ( states('input_number.house_usage') | float | round(2)}}"
Returning this error Invalid config for [template]: invalid template (TemplateSyntaxError: unexpected '}', expected ')') for dictionary value @ data['sensor'][0]['state']. Got "{{ ( states('sensor.inverter_active_power') | float | round(1)) - ( states('sensor.smartdin_power_2') | float | round(2) - ( states('input_number.house_usage') | float | round(2)}}". (See /config/configuration.yaml, line 48).
Can someone give me a hand? even yamlchecker is showing this should be fine
I'm trying to make a sensor that does my solar panel production - ev charger usage - house usage
wheres this
you will also see errors from this sensor every time you reboot HA, as you are not using defaults for your float filters, or an availability template
I assume you can find those yourself, just check for every ( if there is a closing ) as well
Hello. So i have a template sensore that should reflect the status of my dryer.
It's working perfectly fine so far, the only problem is, that it also gets set to on, after i restart home assistant and therefore triggers all the automations.
Could someone point me in the right direction on how i could solve this problem?
- sensor:
- name: "Dryer Status"
unique_id: "dryer_status"
state: >
{% if (states('sensor.smart_socket_16a_5_power') | float > 1) or
(states('sensor.smart_socket_16a_5_power') | float < 1 and
now() < states.sensor.smart_socket_16a_5_power.last_updated + timedelta(minutes=5))
%}
{{ "on" }}
{% else %}
{{ "off" }}
{% endif %}
why are you creating a sensor, and not a binary_sensor (which uses the states on and off by default)
I was thinking of creating a third status called "running" or something similar, but i didn't get that to work yet
anyway, last_updated get's reset when you reboot HA, so that's why it will be always on after a reboot
Yeah, it makes sense to me why it happens, but i'll need a workaround now
Is there a sensor that reflects how long home assistant has been running for?
Maybe i could check if the last status change was after the restart, so that would turn the sensor to off by default
you can use the automation check state after restarted and set state to off
how will you use an automation to set the state of a sensor?
rebuild it to a trigger based template sensor
- trigger:
- platform: numeric_state
entity_id: sensor.smart_socket_16a_5_power
above: 1
id: "on"
- platform: numeric_state
entity_id: sensor.smart_socket_16a_5_power
below: 1
for:
minutes: 5
id: "off"
sensor:
- name: "Dryer Status"
unique_id: "dryer_status"
state: "{{ trigger.id }}"
icon: "{{ 'mdi:tumble-dryer' if this.state == 'on' else 'mdi:tumble-dryer-off' }}"
Ohh, that makes way more sense.
I haven't worked with trigger based template sensors yet, but based of of this it looks really simple.
I also change the icon with a condition currently
icon: >
{% if is_state("sensor.dryer_status", "On") %}
mdi:tumble-dryer
{% else %}
mdi:tumble-dryer-off
{% endif %}
Should i just leave like this or is there also a cleaner way to integrate that?
uhm, you were using the states on and off in your template, but you are checking for the stateOn
so the if statement will never be true
"On" or "on"
anyway, you can use this.state
Oh yeah, i changed it earlier and forgot about the icon state
I added icon template in the code above
That looks so much cleaner, thank you very much
{{ 'Yes' if is_state('light.kitchen', 'on') else 'No' }}
{{ 'mdi:tumble-dryer' if is_state('sensor.dryer_status', 'on') else 'mdi:tumble-dryer-off' }}
you mean like I already added here? <#templates-archived message> (but then using this.state so it will also work after an entity_id change)
Great if you want to help others though, so don't let me stop you!
try to format your code as code though 🙂
To format your text as code, enter three backticks on the first line, press Shift+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.
where is that code can add?
single backtick for one line code snippets
sorry? what do you mean
i mean, i want creat that sensor.
So where am i paste that code? Configuration.yaml?
it need template: above the current code block if you want to place it directly in configuration.yaml
unless you already have template: somewhere
thanks
is there a template to get the last time something was in a specific state?
I have {{ states.vacuum.roomba.last_changed < today_at('00:00') }} right now, but the state changes when I empty the bin (because it insists on "finding dock"), so I'd like to have the last time since it was in state "cleaning"
create a trigger based template sensor or an automation which stores it in a input_datetime
also note that last_changed will reset when you reboot HA
@compact robin I converted your message into a file since it's above 15 lines :+1:
oh, it doesn't use the database used for recorder/history? Good to know
Though for this usecase it's fine. I'll look into the trigger based template sensor, thx
I defined:
`template:
- sensor:
- unique_id: sensor.sun_height_percent
name: "Sonne aktuelle Höhe"
state_class: measurement
unit_of_measurement: "%"
state: >-
{{ (float(states.sun.sun.attributes.elevation) / float(69.82)) * 100}}
`
and expecte do see it as {{ states('sensor.sun_height_percent')}} in Developer - Template - or can use it on a lovelace as sensor.sun_height_percent, but it says 'unknown'
- unique_id: sensor.sun_height_percent
what did I wrong? how can I trace whats going on with this definition?
Let me try that
this will create sensor.sonne_aktuelle_hohe (not completely sure how it will slugify the umlaut)
thank you, so I totally misunderstood the unique_id
It did work, appreciated TheFees!
Back to utility_meter. I am able to get it working when using the Helper. I can see the history of a sensor. However if I add a similar part in configuration.yaml:
util_hourly_gas:
source: sensor.gas_consumption
name: Hourly Gas
cycle: hourly
It will not work. What goes wrong?
where did you put this?
To format your text as code, enter three backticks on the first line, press Shift+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.
In /config/configuration.yaml
do you already have other utility meters in there?
No, i see another component in group.yaml
meter_readings:
name: Meter readings
entities:
- sensor.energy_consumption_tarif_1
- sensor.energy_consumption_tarif_2
- sensor.energy_production_tarif_1
- sensor.energy_production_tarif_2
- sensor.gas_consumption
Is this the cause?
Is there a way to do a select attr and ignore case? | selectattr('foo','equalto',bar)
you ever figure out the dynamic dictionaries?
you
I figured I was thinking what? I don't see anyone talking about that. And I ended up going a different route. Honestly 50% of the time I ask Jinja questions now it's for work (Ansible).
lol
Now I'm wondering about a way to ignorecase with selectattr
But seriously thanks to you and thefes assisting me with home assistant is literally how I got this job
How would it be done?
map(attribute='foo') | map('lower') | select('==', 'bar')
but then you lose the base object
mapping lower will lower it
Ohhh
you can't really manipulate data on the left side of your generators
without changing the object
Oh interesting. I will test.
What do you do now for work?
I do infrastructure automation. Building vms, hp ilo physical servers.
Yep infrastructure as code with Ansible.
They use Jenkins as well. But I only work with Ansible.
Let's say I have a big dict setup like this https://dpaste.org/e0Ez8
If I want to search EPG-F5Prod but not be case sensitive and pull the related information in that list and make a list of the related bd, and subnet how would I?
You’d need a custom function for that to use generators
Otherwise, namespace
Any examples for using a namespace?
Namespace just allows you to keep memory with for loops and if statements
Any idea how I would formulate this?
Can someone explain to me how to create an upcoming event sensor for let's say birthdays
Just like this one
Upcoming_day: 15-03-2023
Upcoming_waste_types: papier
Hidden: false
friendly_name: Rd4 eerst volgende
Would anyone be able to help me out with a MQTT Fan Template issue? I have it about 90% working, just can't get the state topic figured out.
I'm trying to write a template that says whether or not Adaptive Lighting manual control is on for an Adaptive Lighting lighting group. test: {{ state_attr('switch.adaptive_lighting_adaptive_lighting_study', 'manual_control') }} shows test: [] when manual_control is empty/undefined/null (shows no value when I look at the attribute). The same template shows test: ['light.study'] when manual_control is enabled (it shows the entity that assumed manual control by changing more than 10%). I have tried an if statement for both state_attr('switch.adaptive_lighting_adaptive_lighting_study', 'manual_control') == '' and state_attr('switch.adaptive_lighting_adaptive_lighting_study', 'manual_control') == '''light.study''' and states.switch.adaptive_lighting_adaptive_lighting_study.manual_control is defined but they all yield as false. How do I check if it that attribute has content or not? If it has content, I want it to say "On", and if it does not (or is undefined?) then I want it to say "Off".
TL;DR: How do I tell if an attribute has content?
{% if states('switch.adaptive_lighting_adaptive_lighting_study', 'manual_control') is not none %} hello {% else %} bye {% endif %}
V0: >{{ state_attr('switch.adaptive_lighting_adaptive_lighting_study', 'manual_control') }}<
V1: {{ state_attr('switch.adaptive_lighting_adaptive_lighting_study', 'manual_control') }}
V2: {{ states('switch.adaptive_lighting_adaptive_lighting_study', 'manual_control') }}
V3: {{ is_state('switch.adaptive_lighting_adaptive_lighting_study', 'manual_control') }}
V4: {{ is_state_attr('switch.adaptive_lighting_adaptive_lighting_study', 'manual_control', '') }}
V5: {{ is_state_attr('switch.adaptive_lighting_adaptive_lighting_study', 'manual_control', '[]') }}
V6: {{ is_state_attr('switch.adaptive_lighting_adaptive_lighting_study', 'manual_control', '''[light.study]''') }}
V7: {{ is_state_attr('switch.adaptive_lighting_adaptive_lighting_study', 'manual_control', '''[''light.study'']''') }}
V7: {{ is_state_attr('switch.adaptive_lighting_adaptive_lighting_study', 'manual_control', 'light.study' ) }}```
All of these yield the same value, except for V0 and V1, which show as `V0: >[]< V1: []` when manual control is off, and as `V0: >['light.study']< V1: ['light.study']` when it is on.
{{ light in state_attr('switch.adaptive_lighting_adaptive_lighting_study', 'manual_control') }} shows False when manual_control is off/empty(?), but gives an error when manual_control is on as activated by light.strudy: UndefinedError: 'light' is undefined. This is the closest I've gotten so far.
{% if state_attr('switch.adaptive_lighting_adaptive_lighting_study', 'manual_control') == None %} false {% else %} false {% endif %}```
Both of those show 'false' no matter what.
my god its been like an HOUR of my life trying to deal with just figuring whether or not an attribute is empty or not. wtf am i doing wrong.
{{ []|length == 0 }} == True
i'm hearing you say to check the length of the attribute's return to see if it is zero?
{% if states('switch.adaptive_lighting_adaptive_lighting_study', 'manual_control')|length == 0 %}true{% else %}false{% endif %} returns 'false' regardless of the manual_control state
ahhh, you're right!
{% if state_attr('switch.adaptive_lighting_adaptive_lighting_study', 'manual_control')|length == 0 %}true{% else %}false{% endif %} works!
you just need {{ state_attr('switch.adaptive_lighting_adaptive_lighting_study', 'manual_control')|length == 0 }} BTW
that's it
omg this has been an hour and a half of my life, lol, THANK YOU, you have brought me so much relief here, thank you so much
I didn't realize it was returning a list. Lesson learned.
- sensor:
- name: rlinkLocationTracker
state: sensor.rlinkLocationLat
attributes:
latitude: sensor.rlinkLocationLat
longitude: sensor.rlinkLocationLong```
how can I use these sensors directly in a template?
if you format them as proper templates, yes
"{{ states('sensor.rlinkLocationLat') }}" for example
thanks will give it a shot
I wonder if it needs to be cast to floats, since the state will be a string.
yeah that may be possible because technically they are floats
it might work as is, just give it a try I guess
yeee it works
Appreciate the help homies
Now my motorcycle location tracker works, yay
You might also consider making a proper device tracker out of it.
Then it will do things like change its state based on zone.
ah thanks yeah ill probably do that
hey guys, is there a way to have a template do stuff based on logged in user? for example, on my phone's dash, i want to see my phone's battery, but on my wife's phone, i want to display her battery on the dash?
ah, not sure if this is the best way but i got it - i can use {{ user }} in templates, and i can set up some input text fields with the name of the possible users and the name of the phone in HA
Hello,
Im trying to template a service call to run a script. Im running a for each loop, during which, the script call is based on the loop iteration.
for_each:
- outdoor_led_1
- outdoor_led_2
- outdoor_led_3
sequence:
- variables:
iteration: repeat.index
- service: script.turn_on
entity_id: "{{ (script.number_generator_ ~ repeat.index) }}" #script.number_generator_3
ive tried various syntax changes inside the single line template without success. id appreciate ne help
Is there a template for iOS media player widget android seems to have one not iOS
You need to surround the 'script.xxx' part in quotes, since it's a string. Also, remove the parentheses
I have a question. I have a tuya led strip with RGBW lights (rgb leds and white leds). I connected the data pin to a esp8266 to use with WLED. Both entites (wled and tuya led strip) are in home assistant. How can I combile these into one light entity and make sure white lights turn off if i use RGB and the other way around.
Try to specify for which platform you intend to use it on. E.g. Apple Music, or Spotify of something else
i looked at template sensor docs and i dont understand it much (feel like 2 examples isn't enough)
template:
- binary_sensor:
- name: "Server Online Status"
i want to update my sensor using the api calls, what should I set as value? how would I call the sensor to update it externally? (curl is fine)
Seems like you really want an input_boolean
don't see input_boolean is docs...
Ok
can i have some link so i can read?
so i dont need template sensor? oh lemme look into
nice, is there a way i can automatically turn it off automatically after no updates?
Otherwise you can try this: DLNA Digital Media Renderer
Is there a way using templates to take something like this and extract the value of one thing (eg extract temperature):
{
"datetime": "2023-03-12T00:00:00+11:00",
"condition": "rainy",
"templow": null,
"precipitation_probability": 70,
"temperature": 27,
"precipitation": 7
}
Edit: I am silly and that was surprisingly easy to do a .[name of line]
Sonos but it shows up as a media player entity in home assistant
Foo.temperature or Foo["temperature"]
Yeah figured it out, turns out I'm just stupid, I've done that same stuff before and I thought I tried it, I just spelt it wrong
Lol aight, I just wanted to make sure you knew there was 2 ways to get items out of a dict in jinja
Ah yeah thanks! I probably could've guessed the [] way, but knowing me would've stuffed that up somehow 😄
hi
I got a sensor for the last time I fed the fish and I want to make an automation that will notify me whenever time has passed the 2 days and 3 hours (51 hours) of the last feeding time.
I assume I need a template condition/trigger to make it work, that's why I'm posting it here.
Thanks for helping!
Template:
http://pastie.org/p/1MYEOTtlyFPDOYbRN2G2Hg
The attribute of the sensor:
https://imgur.com/G0CujPx
is there a possibility to make 2 separate template sensors from one variable? to remove part of the attribute: {{state_attr("sensor.iphone_geocoded_location", "Location")}})
Please don't cross-post. I'd suggest using a new template sensor of {{ states('sensor.feed_record_timestamp') | as_datetime | as_local + timedelta(days=2, hours=3) }} with a device_class: timestamp using the time trigger: https://www.home-assistant.io/docs/automation/trigger/#time-trigger
I’m more talking about using the media player entity on an iOS widget
If you really want 2 sensors from 1 bit of data, you can. You could also put it into an array or different attributes of the same sensor, if you like
Yeah sorry, I though at first it wasn't related to this channel.
However, I prefer to use the current template instead of making a new one. Is there a way to implement that automation that will notify me? or It's impossible?
That above template would be in addition
So that you track the time you want to be notified
Your current one tracks when they were last fed and the above one tracks when you want to be notified
So I just put it on the automation as condition?
No
so I don't need any condition just to add that template as trigger and set on action the notification to my phone I assume?
Right, the trigger will only trigger at exactly 2 days and 3 hours after that current sensor
No condition is needed unless you need to filter it any further
If you keep pushing out that feeding date, you'll never be notified as you'll have fed them on time
By using device_class: timestamp you mean to do something like that?
http://pastie.org/p/0rCUNTi4JbpzqP6uTJZs0e
You need to create a new sensor w/ that template
Very similar to the one you already have
Is that OK?
http://pastie.org/p/1xicrrpYOtMvQNiWxWH84t
looks good
so now on the automation how do I use this sensor to make sure it will trigger when that sensor is detecting that past time over 51 hours
trigger:
- platform: time
at: sensor.feed_is_missing_timestamp
I wish I could do this, not having to define every light in a group 🙂
- service: light.turn_off
target: light.*
Maybe there is an other way?
- service: light.turn_off
entity_id: all
Or with entity_id: all nested under target:
Thank you, @buoyant pine . Wold nesting entity_id under target make any difference? Or why would i consider the two alternatives?
Wouldn't make a difference. In general, if the domain of the entity matches the domain of the service (or if you use all), you can just do what I showed above
No clue if that will be removed at some point. The method with target seems to be the official way these days
my problem i have to extract the data out of one attribute... in my case
i am getting this value (50.468755, 10.660919) and i want to save the tho coordinate numbers in separate sensor values
Well, you can get a list of those coords like {{ "(50.468755, 10.660919)"[1:-1].split(',') | map('float') | list }}, you could grab the first/last accordingly if you want to store them in different sensors
ohh, i am able to extract the first number but not the other
What do you mean
as there a way to convert dates like this 2023-03-11T16:26:36 and 2023-03-11T05:36:08.316Z to just YYYY-MM-DD? or even just take the first 10 characters from the string?
{{ now().date() }}
These dates may not be now, they are coming in json from webhooks
How do you want the output when you get a UTC date (as expressed in your second example)? You want it to be local to your HA instance or the date from the UTC timestamp
Local
{{ your_date_str | as_timestamp | timestamp_custom('%Y-%m-%d') }}
perfect thank you again!
How can I get a user_id to the friendly_name of said user with a template?
Or {{ as_datetime(your_date_str).date() }}
Can someone help me format the output of this code as a whole percentage? Right now I get “0.2345664355” and after searching, I have no idea how to accomplish this.
{% set original = states("sensor.ecu_current_power") | float %} {% set minimum = 0 %} {% set maximum = 5800 %} {% set adjusted = min(maximum, max(minimum, original)) %} {{ (adjusted - minimum) / (maximum - minimum) }}
do you mean just multiplying by 100 and rounding?
Yes, exactly. It’s for a Watch complication that truncates at four decimals so I need to express it as a percentage instead.
Thank you! How do I express it as a whole number (as in 19.67488 rounds up to 20)?
Thanks again. Sorry the noob question and appreciate the help. I’ll check out the docs.
Dear members, running in circles, can't see it anymore 😦
I believe the BP is a beginners level, still can't get it to work.
error " failed to generate automation from blueprint: Missing input weightdiff, weightsensor.
I know this is a BP, but was advised to try it here. Its the calculation in the Action which is the problem and probbaly around the ~ ~ Any hint very much appreciated !
Are you trying to create this blueprint, or do you want to use it?
{{ states(weightsensor) | float(0) - states(weightdiff) | float(0) < states(okoksensor) | float(0) < states(weightsensor) | float(0) + states(weightdiff) | float(0) }}
Guess this is what you are trying to do
You were turning everything into strings with the single quotes
hey peoples, another templating question. trying to set a time, but the types don't add up. any hint?
data:
time: "{{ (states('input_datetime.wake_up_time') - timedelta( minutes = 15 )).strftime(\"%H:%M\") }}"
target:
entity_id: input_datetime.wake_up_time_offset```
that makes total sense
You need to use as_datetime to convert the string to a datetime
And if you use single quotes inside your template, you don't need to escape them
still left with Error rendering data template: TypeError: unsupported operand type(s) for +: 'NoneType' and 'datetime.timedelta'
What do you have now?
data:
time: "{{ (states('input_datetime.wake_up_time')| as_datetime - timedelta( minutes = 15 )).strftime('%H:%M') }}"
target:
entity_id: input_datetime.wake_up_time_offset```
Is your input_datetime.wake_up_time time only?
darn. yes. should be too because it's daily
service: input_datetime.set_datetime
data:
time: "{{ (today_at(states('input_datetime.wake_up_time')) - timedelta( minutes = 15 )).strftime('%H:%M') }}"
target:
entity_id: input_datetime.wake_up_time_offset```
if i can use the wake_up_time with an offset was a trigger that would also work
lemme try your suggestion
perfect, thanks
now let's learn why this works 😛
Well, you need a datetime object if you want to subtract a timedelta
today_at converts a time only string to a datetime object
I'm trying to set the value of a template binary_sensor to the last known value during startup. I'm reading the Considerations::Startup section of the Template page and struggling to understand it. I think the answer to what I'm trying to do is there, but I'm not following what the page is saying. Could someone explain setting the initial value when the value is "unknown"? Or how to set the startup value to the last known value?
This is the page I'm reading: https://www.home-assistant.io/integrations/template/#considerations
@young lake What is the current code of your template binary sensor?
Anyone know how i can adjust this template so it can show day and days? So now it show minutes, hours and 1 day(s), 2 day(s) etc but i wan't to show minutes, hours, 1 day, 2 days, etc... https://paste.ubuntu.com/p/t4CSQX8Cwq/
you know this will reset when you reboot HA right? So after a reboot of HA core it will show like 10 seconds
Yep i know 🙂
But that would not have affected the online status of your Pi, as you are only rebooting core
Yeah i know but i think there is no other way around?
you actually have an uptime sensor so it seems
just use that?
what does that sensor return as value
sensor.raspberry_uptime
12 maart 2023 om 20:05
So it also resets wen Core is retarted.
I don't think it's possible to bypass this?
How did you configure that sensor
This is what I have, the first seems to be what you want, the second is when core was last rebooted
And you don't need templates to show it like this on your dashboard, HA does that automatically when you add a sensor with the right device class and a time in the past
It's the default uptime integration.
the default uptime integration indeed shows the uptime of HA (Core), not the uptime of your Pi
How can i show the Pi uptime? 🙂
specifically: type: last_boot
and if you then just add the sensor to your dashboard in an entities card, it will show it like above (in Dutch if your user language is set to Dutch)
I just rebooted because of an HACS update
Ok i had that last_boot sensor but it seems i removed that.
Because i want to show the uptime in a little chip card i use that template so it's smaller in text size...
I just want to figure out how i can show/seperate day and days
BTW why are your doing an integer division (using //) then convert that to a float, then round that, then convert it to an int? all these steps are redundant, because you already had an integer to start with
sorry, that's not right
but you only need to add | int
anyway, you can do this:
{% set sensor = 'sensor.last_boot' %}
{% set last_boot = as_datetime(states(sensor)) %}
{% set seconds = (now() - last_boot).total_seconds() %}
{% set days = seconds / ( 60 * 60 * 24 ) %}
{% set hours = seconds / 3600 %}
{% if days >= 1 %}
{{ days | int }} dag{{'en' if days | int > 1 }}
{% elif hours >= 1 %}
{{ hours | int }}u
{% else %}
{{ (seconds // 60) | int }}min
{% endif %}
Probably asking in wrong channel...again however cant really place my question anywere so i go here anyway... 🙂
I have a Switch which by using the Helpers i have changed to Lock entity.... Lock.unlock turns switch on and Lock.lock turns switch off... However Lock.open i would want to associate with something maybe a button entity or so is there a way i can use all three Lock commands
Sorry i had a conference call. Thanks for the template! So this can expose min, hour, day and days?
it will expose the largest of those
Ok perfect, thanks!
Largest in time that is
eeSolved
Merged for next release!
Nice
loop controls??
does it break things?
I'm waiting on a review to get today_at and relative time added to the minutely updates
it breaks things if you use the variables 'continue' or 'break'
which are pretty common words
I was thinking why that would be needed, but something like today_at('10:00') would stick to today until the next boot of HA or a template reload
not if you reboot HA?
well yes, if you reboot or reload
or use the update_entity function
but a template on it's own would not
yes, that's what I meant
technically it's a breaking change because you can't use it in limited templates anymore
I would expect in most cases you will compare it with now()
yeah, for relative time it's different, but there I would expect you will use it on an actual entity
but it wouldn't update if it was on the entity
it would always be zero in that case
I actually don't really know the difference between a limited template, and a normal template. The docs mention for most that they are not limited templates, but I'm not sure what defines a limited template
limited templates don't have access to the state machine
the hass object doesn't exist
so anything that talks to hass, won't work
but back to today_at, if you wanted to use the time difference between 10 am and your next calendar event, it would never update
unless you added now()
right
so, I just added it to the "now()" updates
same with relative_time
quick and dirty without changing logic
only breaks limited_templates
I probably should have omitted that change
so then it would get looked at by core
trying to think of a use case for those 2 in a limited template
there's always that someone
Many thanks TheFes !!! Will try it this evening.
I have a question. I have a tuya led strip with RGBW lights (rgb leds and white leds). I connected the data pin to a esp8266 to use with WLED. Both entites (wled and tuya led strip) are in home assistant. How can I combile these into one light entity and make sure white lights turn off if i use RGB and the other way around.
Thank you! I will do some research in that! Thanks for the help! ❤️ @marble jackal
@hexed laurel I converted your message into a file since it's above 15 lines :+1:
Can anyone help with above, I can't get the state to update in HA https://paste.ofcode.org/Q9GhiJC38wGVzvG2vgEc5g
The state is determined by the value_template field
I tried a few different things with no result. I don't think I understand it enough. The stat/Main_RF_Blaster/POWER is either POWER = ON or POWER = OFF
I got everything else working, but this is the death of me.
state_value_template: "{{ value == 'ON' }}"
unless the topic actually contains the phrase POWER = ON
in that case it would be
state_value_template: "{{ value == 'POWER = ON' }}"
Tried both, but nothing.
MQTT Explorer shows it as just ON/OFF value so
state_value_template: "{{ value == 'ON' }}" should be it
state = unknown 🥺
In MQTT Explorer I can see the value update in real time.
I have tele/Main_RF_Blaster/STATE as a topic too
It lists "POWER": "ON",
@hexed laurel I converted your message into a file since it's above 15 lines :+1:
You can use whatever you want as your state topic, tele/Main_RF_Blaster/STATE is the state topic, use that instead
state_value_template: "{{ value_json.POWER == 'ON' }}"
Hard restarted, state unknown 😖
🤷♂️ it should work just fine
I know, I've been slamming my head.
is your payload on and off really 1 and 0?
This is setup in Tasmota with a Blank Relay that does power on and off via a rule.
ok then
I'm running a D1 Mini to 433mhz transmitter via Tasmota.
state_value_template: "{{ '1' if value_json.POWER == 'ON' else '0' }}"
Aha!
So this works, and now I am noticing a problem via MQTT Explorer.
The state isn't updating...
I think it has something to do with my setup with the Blank Relay sending RF commands.
Personally, I'd use this setup instead
mqtt:
fan:
- name: "Bedroom Fan"
command_topic: "tele/Main_RF_Blaster/STATE"
command_template: "{{ 1 if value == 'ON' else 0 }}"
state_topic: "stat/Main_RF_Blaster/POWER"
state_value_template: "{{ value_json.POWER }}"
payload_on: "ON"
payload_off: "OFF"
preset_mode_command_topic: "cmnd/Main_RF_Blaster/RFSend"
preset_modes:
- "Speed 1"
- "Speed 2"
- "Speed 3"
- "Speed 4"
- "Speed 5"
- "Speed 6"
preset_mode_command_template: >
{% if value == 'Speed 1' %}
{"Data":"0x80930417","Bits":32,"Protocol":1,"Pulse":386}
{% elif value == 'Speed 2' %}
{"Data":"0x80930A19","Bits":32,"Protocol":1,"Pulse":386}
{% elif value == 'Speed 3' %}
{"Data":"0x8093081B","Bits":32,"Protocol":1,"Pulse":386}
{% elif value == 'Speed 4' %}
{"Data":"0x80930C1F","Bits":32,"Protocol":1,"Pulse":386}
{% elif value == 'Speed 5' %}
{"Data":"0x80930615","Bits":32,"Protocol":1,"Pulse":386}
{% elif value == 'Speed 6' %}
{"Data":"0x80930516","Bits":32,"Protocol":1,"Pulse":386}
{% else %}
{"Data":"0x80930112","Bits":32,"Protocol":1,"Pulse":386}
{% endif %}
I'd probably clean up the preset mode template too but it's not a big deal
That works perfectly for the status. Power command via HA now doesn't work.
Changed command topic to "cmnd/Main_RF_Blaster/POWER" seems to work now.
yeah, sorry, ment to put that in state_topic
Works with the stat, as the state doesnt update but stat/power does
something like this?
preset_mode_command_template: >
{% set data = {
'Speed 1': '0x80930417',
'Speed 2': '0x80930A19',
'Speed 3': '0x8093081B',
'Speed 4': '0x80930C1F',
'Speed 5': '0x8093061F',
'Speed 6': '0x80930615'
} %}
{{ dict(Data=data[value] | default('0x80930112'), Bits=32, Protocol=1, Pulse=386) | to_json }}
ya
That works great! Thank you both for all the help.
I added the same default as you did in your original version
Awesome thanks. I am working on trying to figure out why I am getting status unknow after reboot until I toggle it on/off now.
Fixed with PowerRetain 1 in Tasmota!
Thanks again @mighty ledge and @marble jackal I appreciate your time.
Hello Why this random template does not work in my case:
- service: media_player.play_media
data:
entity_id: media_player.heos
media_content_type: "favorite"
media_content_id: "{{ range(1, 6) | random }}"
The template's fine
It's most likely the service call
Yep, it doesn't allow numbers
@sonic nimbus ^
that won't fix it
is the id actually a number ranging from 1 to 5?
if it is, you have to template the whole data section
- service: media_player.play_media
data: >
{{ {'entity_id': 'media_player.heos', 'media_content_type': 'favorite', 'media_content_id': range(1,6) | random | string} }}
I see, but I want to include 1 and 6, so I have 1,2,3,4,5,6 favorites
then you want range(1,7)
anyways, you still have to template the whole data section
Ok, tnx, I will try
Is there a way to do startswith that's case insensitive?
{{ ('BaNaNa' | lower).startswith('ban') }}
Thank you. And if i wanted to check for starts with BaNanna- do x else if starts with BaNanna as in there's no - do x. The challenge is starts with would match both because it's truly there. But I care if it has the - and doesn't have - after BaNanna
{% set value= 'BaNaNa-Orange' %}
{% if (value | lower).startswith('banana-') %}
Do something
{% elif (value | lower).startswith('banana') %}
Do something else
{% else %}
Do nothing
{% endif %}
I figured out my issue I had that but I didn't have the case right.lol
hey, how does an event look when a button is pressed, so I can read it by event, which user triggered the event?
How would I do a search of a list for a matching a piece of a string. You can use'testfoo' is search('testfooey') and it will return true because testfoo matched. How would I do that with a list? You can't do is search on a list and in list is an exact match I couldn't do 'testfoo' in ['testfoobar','bar'] There would be more than the exact match and it would be cleaner to avoid listing every exact match.
still using this nex_alarm timestamp sensor, to build all of my other scripts/tts etc etc on. based on 4 input_datetimes, for weekday hour/minutes, and weekend hout/minutes....
was wondering if I could replace that with the new calendar feature, and maybe do away with all of those templates? Would it be better/simpler/easier?
to give you an idea, this is the Frontend for it
and some complex translations finally result in a completely Dutch sentence..... 😉
hey, how does an event look when a button is pressed, so I can read it by event, which user triggered the event?
like {{ ['foo', 'bar', 'barfoo']|regex_search('foo') }}?
You can use search on a list.
[ 'foo', 'bar', 'banana' ] | select('search', 'foo') | list
Awesome didn't know that
But if you just want true or false I would use what Rob suggested
anyways you still have to template the
Thank you!
So I'm trying to use the android template widget, have something saying someone's location (person.person in this situation does exist)
{{states('person.person')}}
How can I make it conditional so it will read out as normal except if it says not_home to change to Not Home (I gather some sort of conditional but am not 100% how to do it)
I feel like this can be written more concise but maybe something like this?
{{ 'Not Home' if states('person.person') == 'not_home' else states('person.person') }}
Can someone advise on my syntax here? I'm trying to output row['helper_id'] in an object i'm looping through but it's returning an error that indicates it's not reaching this object.
- if:
- condition: trigger
id: {{row['helper_id']}}
then:
- service: input_select.select_option
data_template:
entity_id: {{row['helper_id']}}
option: >
{% set options = state_attr(row['helper_id'],
'options') %}{% set current_index =
options.index(states(row['helper_id'])) %}{% set
next_index = (current_index + 1) % options|length %}{{
options[next_index] }}
Error: UndefinedError: 'None' has no attribute 'index'
It works well enough for me so thanks!!
I would do it like {{ states('person.person').replace('not_home', 'Not Home') }}
Or
{{ states('person.person').replace('_',' ').title() }}
``` if it doesn't only need to be Not Home that's treated that way
I have a question. I have a tuya led strip with RGBW lights (rgb leds and white leds). I connected the data pin to a esp8266 to use with WLED. Both entites (wled and tuya led strip) are in home assistant. How can I combile these into one light entity and make sure white lights turn off if i use RGB and the other way around. I cannot seem to get it working
What's the most pythonic/Jinjaest way to check if any forecast condition within the next 3 days (weather.home.forecast[0-3].condition) is a certain value?
Pretty sure this should do the job for telling me the # of days that are supposed to rain right? {{ state_attr('weather.home','forecast') | selectattr('precipitation','>',0) | list | count }}
Even better, found you can slice lists as you'd expect! {{ state_attr('weather.home','forecast')[0:3] | selectattr('precipitation','>',0) | list | count }}
@crimson lichen I converted your message into a file since it's above 15 lines :+1:
seems you already succeeded 😉
@crimson lichen why do you need this, to display it on a dashboard?
yep,
i copied and paste here 😄
{%- for a in states.sensor.lunar_exlab.attributes.items() %}
{{ a[0] }}: {{ a[1] }}
{%- endfor %}
Looking back at this, it's not as good as 'foosanta' is search('foo') because it would still work as long as it matches the characters whereas the regex_search can't have any more than the string itself.
Is there another way?
{{ ['foo', 'bar', 'barfoo']|regex_search('foo') }}
You have to use namespace if you want to 'lower' anything or regex. When you have a list like that, you have to use a generator too. Like | select('search', 'foo')
keep in mind that search doesn't exist in your environment
that's an HA only jinja test
but you're using ansible, so you have regex as a test
so you should be using that for pretty much every one of your "how do I select something and lower the case"
as regex has a built in kewarg called ignore case
Yeah regex is a test there and if only I could use a list with is search and yeah I learned about the ignorecase=true here.
You can
| select('search',...)
also
| select('regex', ...)
Got it {{ test | select('search','foo') | list | count > 0 }}
Is there a way to do a regex replace if there are more than 1 - between characters in a string so foo--bar becomes foo-bar foo--bar---foosanta becomes foo-bar-foosanta?
{% set value = 'foo-----bar--banana---------orange' %}
{{ value.split('-') | reject('eq', '') | join('-') }}
That worked thank you
Seems like anything is possible with Jinja
Hello
I want to template "inline_keyboard" item
in notify service
it's usually a list
e.g.
- ":bulb: Controllo luci:/cont, :bulb: Stato luci:/sta"
- ":window: Controllo tapparelle:/tap"
how can I make an if then else of this list?
- ":bulb: Disattiva Motion Detect:/mof"
{%- else -%}
- ":bulb: Attiva Motion Detect:/mon"
{%- endif -%}
like the above example...
{%- if is_state('binary_sensor.motion_detect_status', 'on') -%}
inline_keyboard[0]
{%- else -%}
inline_keyboard[1]
{%- endif -%}
something like that?
the first item of the list named inline_keyboard
as counting starts with 0
@mighty ledge https://github.com/home-assistant/core/pull/89011 another nice template feature merged, this makes hiding entities useful for people who rely on templates 🙂
Could you please explain me better your example?
How can I assign "💡 Disattiva Motion Detect:/mof" or "💡 Attiva Motion Detect:/mon" with if to inline_keyboard[0] ?
then to inline_keyboard[1] I need to assign another string
based on another different if
@marble jackal please help me 🙂
where does inline_keyboard come from?
data_template:
title: '👮 *Centrale'
message: Controlla la centrale
data:
inline_keyboard:
- "🔴 Zone A B C:/alè, ⚪ Zone A B:/all"
- "🟢 Disattivo allarme:/all, 🚨 Spengo sirena:/sir"
- "🚨 Accendo sirena:/sir, 🟡 Panico:/pan"
This is an example
so I send to telegram
6 buttons
2 per row
I want those buttons to be parametric
with templates
the problem is that
inline_keyboard is a list
in this case it has 3 items
You have to use namespace
No need
I found a way
{%- if states('binary_sensor.motion_detect_status') == "on" -%}
{%- set x = "💡 Disattiva Motion Detect:/motiondetectoff"-%}
{%- else -%}
{%- set x = "💡 Attiva Motion Detect:/motiondetecton" -%}
{%- endif -%}
{{ [x, x] | list }}
{% set ns = namespace(output=[]) %}
{%- if states('binary_sensor.motion_detect_status') == "on" -%}
{% set ns.output = ns.output + [":bulb: Disattiva Motion Detect:/mof"] %}
{% else %}
{% set ns.output = ns.output + [":bulb: Attiva Motion Detect:/mon"] %}
{% endif %}
{{ ns.output }}
no need, my example above works
also note that data_template has been depreciated for like 3 years now
Is there a limitation to where I can use Jinja in an automation template? It's not letting me save often times and when I switch to YAML it often discards all my work. I'm trying to generate a list of triggers and actions but I'm getting the feeling the validation is missing required elements in plain YAML?
If you're using templates you should be in yaml editor, the UI editor does not support templates except in very limited spots.
Otherwise I'd have to see exactly what you're typing and where to explain what is happening to you.
Yeah, often times it wont show me the save button though. So I switch to see if it does anything. But you're right. I'm doing that
Let me clean up my example. Thanks
@shell cape I converted your message into a file since it's above 15 lines :+1:
It's good to note it passes the template developer tool
yeah I don't think you can do this. an automation is in YAML. All this {%%} stuff is not yaml, it won't understand it. You can use templates in places that support templates, but even there they have to be quoted as strings, so that the yaml does not try to parse it
Automations do support templates right? But maybe not a structural level?
Certain fields may support templates, but as far as the YAML is concerned you're just passing a string to the field, to be later parsed as a template. You have to look at the documentation for a particular trigger, condition, or action to see which fields it has and which ones support templates.
Ah will check which fields allow that, thanks. Any suggestions to a different approach where i can set things up like this without repeating myself a lot?
trigger:
{% for row in data %} - device_id: {{row['device_id']}}
e.g. this you cannot do either
If I wanted to trigger off when one of multiple remotes was pressed, I would not use devices, but maybe create a group of remote entities, or look for event trigger with some subfields of the event matching some of the properties of my remotes.
you can't template the yaml structure of anything
you can only template in specific templateable fields
well, the data sections of a service call would be an exception
you're templating JSON tho
Yeah, i was about to say, I'm trying to workaround my lack of understanding of options to centralize this in a different way. I looked into groups but could not find one that allowed me to group the switches
you still can't template yaml structure
I would go to #automations-archived and formalize what you're trying to do as a question, you can get some ideas there.
e.g. yaml
xyz:
- 1
- 2
- 3
vs JSON
{"xyz": [1,2,3]}
The way I specify objects inside Jinja2 is fine, it works. But i just cant output it in a loop like this on a structural level.
When I do
{% set list = ['foodaddddd','bar'] %}
{% set test = 'barfoo' %}
{{ list | select('search',test) | list | count > 0 }}
It is false. Since it's not an exact match. Is there a way to do wildcard or something I would want that to be true because bar is in barfoo
Thanks so much for the insights
you'd want to do separate tests
for bar and foo
by rejecting things that don't have foo or bar in it
You gotta dream it up 😉
Seems challenging because it could be
{% set list = ['foodaddddd','hello'] %}
{% set test = 'hellosanta' %}
{{ list | select('search',test) | list | count > 0 }}
🤷♂️ not separating your test like that will lead to problems
how is the code supposed to know you just want to check hello and santa but not llos?
or osan
or hel
or nta
or just the letter t?
No idea that's why I'm asking if we can do partial matches lol.
that's what I'm saying, your logic is flawed
you gotta approach this differently
even if we had partial matches, it wouldn't work because of what I said above
That's why I come here when I'm stuck banging my head on the wall.
I have never done partial matches to have a clue of how to approach this
I'm not sure why you'd even want partial matches
More or less to avoid hard coding every possibility. By simply saying is foo in foo-bar or foobar
yes but you'll still have a list of partial strings
As in it found f but not foo? I'm just looking for true/false
you aren't going to want to check for every permutation of the partial
I mean if you expect a software to find partials from a string abcde, then you're going to get all partials
including single letter partials
so you're better off separating the string into the partials you want
explicitly
How should I approach that?
you have a number of ways, your current method or rejecting instead of selecting
What is the best way to take a | list and get it into a nice human-readable format with an Oxford comma?
| list | join(',')
Any pointers? I'm struggling on implementation of reject for example in this use case.
oh, I didn't know this approach 🙂
What rsplit?
{% set list = ['foodaddddd','bar'] %}
{% set test = 'barfoo' %}
{{ list | select('reject',test) | list | count > 0 }}
TemplateRuntimeError: No test named 'reject'.
🤦♂️
and you have to separate barfoo
using barfoo will never work for the reasons I mentioned above
aslo, word of advice, don't override the name list
same with all other functions/methods
yeah, but I usually start with a list, so you need to convert it to a comma seprated string first, and then split it again 🙂
so what would be more efficient?
{% set fruit = ['Banana', 'Orange', 'Grape', 'Lemon'] %}
{{' and '.join((fruit | join(', ')).rsplit(', ', 1))}}
{{ fruit[:-1] | join(', ') ~ ' and ' ~ fruit[-1] if fruit | count > 1 else fruit | join }}
Yeah I noticed that could be an issue.
{{ listtest | reject(test,'') | list | count > 0 }}
Returns an error
I'm struggling lol.
what test were you using for select? Hint: it wasn't test
I think you should take time and learn what a test is and what tests are available in ansible
I get the same error in home assistant too.
yes, because you aren't using the correct test
reject and select filters first argument is a test
the second argument is what you're testing
right, so why are you supplying the variable test?
Because how do I tell it what to reject?
{{ listtest | reject('search',test) | list | count > 0 }} no errors with this
You’re not thinking about your ending result
When rejecting are you looking for items or the absence of items
You’re rejecting items from the list that you want to find. So should you be checking for greater than 0?
You have to approach your problem differently, the whole problem, not just swapping out select for reject
{{ listtest | reject('search',test) | list | count != listtest | count }}
That looks like it could work
Not sure if that's a weird way of approaching it
Not sure if it fully solves it though. As it returns true for even 1 letter matching.
You have to add a reject for each one you want to find
Each letter?
Each word
you can do something like this:
{% set testlist = [ 'food', 'barcelona', 'banana'] %}
{% set searchlist = [ 'foo', 'bar'] %}
{{ testlist | reject('search', searchlist | join('|')) | list }}
it works, it returns [ 'banana' ]
yah but he's in ansible
yeah, I forgot 🙂
🤷♂️
Got it
Will test now
Both work surprisingly. 'regex' and 'search'.
Is it technically ok to ask these questions? They are Jinja questions and can be used in home assistant so I guess it's ok?
Anyway to prevent
{% set testlist = [ 'foo', 'santa', 'banana'] %}
{% set searchlist = [ 'f'] %}
{{ testlist | reject('search', searchlist | join('|')) | list | count != testlist | count}}
From being true.
Meaning not return true just because it marched a single letter. I guess it's impossible because of what I'm trying to do?
this is true becuase 2 is not equal to 3
you are rejecting foo becuase it contains an f
so there are 2 items left
2 != 3 returns true
Is there a way to reject only if it's more than 2 characters that match?
To avoid that?
why not just not use a single letter?
simply use 'foo'?
{% set testlist = [ 'fad', 'fkm', 'banana'] %}
{% set searchlist = [ 'foo'] %}
{{ testlist | reject('search', searchlist | join('|')) | list | count != testlist | count}}
I just wanted to make sure but yeah that makes sense this works it doesn't return true just because of the f
I have added a fan template to my configuration.yaml in order to be able to control the fan speed on my new GE zwave fan control switch. However, I'm not sure what the next step is. How can I create a lovelace card to be able to set the fan speeds?
I'm not aware if there are any default cards that have pretty fan controls. You could look for a custom fan card, or you can create a horizontal row of buttons, each one calling a different fan.set_percentage service.
This PR (https://github.com/home-assistant/frontend/pull/15819) leads me to believe that maybe something is coming soon, though could be a-ways out still. Actually I'm not even sure if this will be used for a lovelace card, so maybe it's nothing.
Hi, I don't know if this can be created with a light template - but I have a 4 button switch, which has LED behind every button which can get controlled by setting a zwave_js.set_value with a hex color. Would it be possible to be a reuseable template, which could be used on multiple entities, Or do I have to copy the whole template for each switch I have in my house? (its a ZDB5100) https://community.home-assistant.io/t/homeseer-hsm200-zwave-led-on-off-and-color-control/223242/42?u=lauer - this show an example for a similar approach.
Hi all. I got this https://github.com/djerik/wavinsentio-ha - But i need a helper to combine the air humidity. But i was told that it is a a thermostat (a climate in HA) so i need to create a template? 🙂
How can I determine if Google Assistant SDK (https://www.home-assistant.io/integrations/google_assistant_sdk) supports templates in the *command * and media_player fields? It seems not to...
anything under data: can be templated
Hmmm.... I get the following error```
Error executing script. Invalid data for call_service at pos 4: length of value must be at least 1 @ data['command'][0]
This is the yaml:
- service: google_assistant_sdk.send_text_command
data:
command: >-
{% if is_state('input_select.speaker_destination', 'Kitchen') %}
"Call Kitchen Speaker"
{% elif is_state('input_select.speaker_destination', 'Living Room') %}
"Call Living Room Speaker"
{% endif %}
media_player: >-
{% if is_state('input_select.speaker_source', 'Kitchen') %}
media_player.kitchen_speaker
{% elif is_state('input_select.speaker_source', 'Living Room') %}
media_player.living_room_speaker
{% endif %}
It looks like it wants a list
Thx! Will figure a work around
hello, on what order are the attributes set in the templates? Is there any pattern? I would like to know if it's safe to reference the same entity attributes, for example:
power: "{{ la la la something }}"
voltage: "{{ la la la another something}}"
amp: "{{ this.attributes.power / this.attributes.voltage }}"
you can't reference a value before the sensor has been created and its state established
the order they're evaluated in doesn't mean that any are immediately available in the state object
so basically, doing this or using the states(...) is the same, I just need to check if they are available and have a valid value...
?
you can't do what you're trying to do
this is refers to the state object before you update anything
ohh I see... so this will always be the state before the changes in progress?
yes
ok, tks @inner mesa
I kinda miss something like a try/catch in templates, sometimes the logic is just so big that matching all possible points of fail on the template (like is int, etc etc) is so mutch work... somthing like a try this and if fails the template just catch and return that..
ohhh so it's possible...
i'll check it out
I don't know if that's the current value or the last one, based on the |default()
you shouldn't need that if it's the current value
@inner mesa
I tested out the template
it works, it take the default stataus for some seconds then it syncs
the current value or the last value?
the current...
it updtes the attribute and some micro seconds afther the state to the same value
in your example, you were trying to refer to other attributes
my point is that your references are probably to the last update, not what you're doing right now
- sensor:
- name: test_self_ref
state: |+
{{ this.attributes.test | default('Value when missing') }} -
{{ now() }}
# not: "{{ state_attr('sensor.test', 'test') }}"
attributes:
test: "{{ now() }}"
attribute: test: 2023-03-15 01:25:00.121364+00:00
state: 2023-03-15 01:25:00.121364+00:00 - 2023-03-15 01:25:00.439643+00:00
I wanted to reference attributes on the same entity
from other attributes
yes... let me see
I'm not saying that it won't work, just that you haven't actually tested it
and further, I don't think your test above proves that it's taking the current value while you're defining the state
- sensor:
- name: test_self_ref
state: |+
{{ this.attributes.test | default('Value when missing') }} - {{ now() }}
# not: "{{ state_attr('sensor.test', 'test') }}"
attributes:
test: "{{ now() }}"
teste2: >
{{ this.attributes.test | default('Value when missing') }} - {{ now() }}
as you say, it updates later
teste2: 2023-03-15 01:28:00.248990+00:00 - 2023-03-15 01:28:00.561057+00:00
test: 2023-03-15 01:28:00.248990+00:00
friendly_name: test_self_ref
state: 2023-03-15 01:28:00.248990+00:00 - 2023-03-15 01:28:00.561057+00:00
it did the state and the other atribute on the same micro second... thats impressive
yes it's later... but for my use case thats good enough
The most typical case for this is defining the state in the context of the previous state, in which case this.state is the previous state until you finish setting the value. I suspect that you'll get a different answer to your sensor above if you flip the order of the attributes
it does evaluate them in order
I flipped the order and I have the same result... state and test2 with the same value
got an automation which logs Full data: {{trigger.event}} in a notification. I can probably use the automations last_triggered, or this.attributes.last_triggered, but for this purpose am trying to template that off off the event. Might even use the time_fired for that? Anyways, particular template reason is how to get to this timestamp: Full data: <Event system_log_event[L]: name=homeassistant.components.tradfri, message=['Keep-alive failed'], level=ERROR, source=('components/tradfri/__init__.py', 129), timestamp=1678838780.6360462, exception=, count=1, first_occurred=1678838780.6360462>
in the trigger.event
would that be as simple as trigger.event.data.timestamp? given the fact that these also work: Message: {{trigger.event.data.message[0]}}, Logger: {{trigger.event.data.name}}, Source: {{trigger.event.data.source}}, Level: {{trigger.event.data.level}}
yes it is 😉 ```
- service: persistent_notification.create
data:
title: >
{{trigger.event.data.timestamp|timestamp_custom('%X')}}: Tradfri reloaded
message: >
{{now().timestamp()|timestamp_custom('%X')}}: Ikea Tradfri integration was
hi, is there a possibility in an automation to read out who the trigger, in my case a button, has triggered, and how i can do it?
https://www.home-assistant.io/docs/automation/templating/ has the information you need, but we'd need to see the automation
Assuming a state trigger then https://www.home-assistant.io/docs/automation/templating/#state applies
me it would be enough to know how the event looks for a button when it is pressed, since you can read out who has triggered the event
You can take that from the context
There is no pattern. There's a loose heirarcy that starts with availability template, then state, then all others. HA is asynchronous so it should be in the order received by the yaml but it might not be at times. You can't rely on it. Especially if the attributes are built from different entities that update at a different rate.
i am sorry, I can't really do anything with the information so I've seen an attribute is "user_id" but where do I check that? I am overstretched
it's not particularly easy and every case is different
i.e. listen to tinkerer and post your automation.
my automation is not existing at the moment, the automation should deduct "money" from the respective user. So each user has a number and every time he presses the button should be deducted from his "account" a certain price
well we can't help without it
sorry
the context object in automations is different depending on the trigger
typically it's always in the same spot, but it's not for state triggers and event triggers. So we really need to see the automation
also, the only way you can get that information is if you have a person attached to a user and the person can log into HA
@glossy sleet I converted your message into a file since it's above 15 lines :+1:
I guess that's because of navigate: null
@maiden magnet I converted your message into a file since it's above 15 lines :+1:
does someone has an idea?
Yes, use the context. trigger.to_state.context.user_id should have the user id of the person who pressed the button
You have to use trigger.to_state.context.user_id If you want the persons name, then you'd use "{{ states.person | selectattr('attributes.user_id', 'eq', trigger.to_state.context.user_id) | map(attribute='name') | first | default('Unknown') }}" to get the name. Keep in mind it will be Unknown if it cannot find a user that is also a person.
If the person entities match the name you are using for the counter entities, you can just template the entity_id
And where do i have to add that? I am new with templates :(
You can try this
https://dpaste.org/OW1Pu
If my previous comment applies
Hi, I have following {% for x in range(0,somelist|count) %} is there a nice embedded way to limit this to max 5? i.e. use somelist|count but if it is more than 5, take 5. The alternatve is a if / then section following the for statement but ...trying if this cane look nicer 🙂
{% for x in range(0,somelist|count if somelist|count <= 5 else 5) %}
if you're trying to access the object tho, that's the worse way to do it
{% for someitem in somelist[:5] %}
instead of using range
only use range when you need an index
and even then, you don't need that because of loop.index
thanks
the somelist is json and ahs dozens of groups, I onlu want to handle data of the first 5 groups IF there are 5 groups, sometimes there are less
Is there a way to print the config of a template sensor?
I have a trigger sensor, but the trigger condition doesn't for an update
You mean like the trace of an automation/script?
yea, something like that
or just what HA thinks the current template is to check when I last reloaded
What's your current code?
- trigger:
- platform: state
entity_id:
- vacuum.roomba
from: "Cleaning"
sensor:
- name: "Last Roomba Cleaning"
state: "{{ as_timestamp(now()) }}"
``` in template.yaml
Check the actual state while it's cleaning in devtools > states
I don't think it will be Cleaning
hm, that shows it as lower case cleaning. While the history view displays it in upper case, Cleaning. I'll try lower
I guess that was it 🤦
Everything in the UI is translated, always check the dev tools -> states page when writing templates and yaml automations
Hi all,
i'm trying to make a repeat sequence in an automation using a condition to stop the repeat sequence. This is the condition
- condition: template
value_template: {{ is_state('input_boolean.' + trigger.calendar_event.summary, 'off') }}
can you please tell me what my error is. i checked the syntax in the states page, but could not use the calendar trigger data and i got the expected result with another entity.
When trying to save my automation i get the error
Message malformed: invalid template (TemplateSyntaxError: expected name or number) for dictionary value @ data['action'][1]['repeat']['until'][0]['value_template']
you need to surround your template in quotes
🤨 thank you, man how dumb does i feel
Is there anyone on here that's using the Mopeka propane integration? I'm trying to convert the measurement into a percentage rather than distance.
I tried creating a Template sensor the code works but the entity has an unknown state.
https://pastebin.com/hRXujaAW
@grave solstice I converted your message into a file since it's above 15 lines :+1:
- condition: template
value_template: "{{ is_state('sensor.mqtt*', 'grafitti_road') }}"
Trying this
That's still wrong
you're making up syntax that doesn't exist
{{ states.sensor|selectattr('object_id', 'match', 'mqtt')|selectattr('state', 'eq', 'grafitti_road')|list|length > 0}}
"graffiti" is also spelled incorrectly
- condition: "{{ is_state('device_tracker.iphone', 'away') }}"
That came from documentation.....
you added a "*"
ahhh
I guessed at what you really meant
You were correct however im getting syntax problems trying to paste in your code - Nah got it... now going to test
Well thats speellt wrong everywere ...so another day 😄
You code worked ... Big thanks.... Is there a smart way of removing all triggers.... Basically trigger on all states now that i got the condition?
Why not just make that condition the trigger instead? Overactive trigger is not optimal.
Care to show me?
not really. template trigger is the same syntax as condition trigger.
ok
alias: Door Unlock Presence Trigger
description: ""
trigger:
- platform: template
value_template: {{ states.sensor|selectattr('object_id', 'match', 'mqtt')|selectattr('state', 'eq', 'grafitti_road')|list|length > 0}}
condition: []
action:
- service: lock.unlock
data: {}
target:
device_id: 7300bb4e88885723308c41981ab00730
mode: single
Can someone get me on the right track
I have a question. I have a tuya led strip with RGBW lights (rgb leds and white leds). I connected the data pin to a esp8266 to use with WLED. Both entites (wled and tuya led strip) are in home assistant. How can I combile these into one light entity and make sure white lights turn off if i use RGB and the other way around. I cannot seem to get it working
I tried but it's super confusing
I don't understand why you have two entities controlling this. Does the LEDs have two drivers? why?
Add quotes around your template
It must be Wednesday: #templates-archived message
Sorry guys... just really tired...sorry
Hi, welcome to the #templates-archived channel. Did you surround your template in quotes?
Any help would be greatly appreciate to my above post
You tried running it in developer tools -> templates? It looks ok to me at first glance.
I'm trying to overwrite the attribute media_title in a universal media player but it doesn't seem to work. Is this not possible?
Seems like the issue is that the TV does not have a media_title attribute. Anyone know how to "clear it" if it is not matching my conditions?
{% if is_state('media_player.lg_c2', 'on') and (state_attr('media_player.lg_c2', 'source') == 'Apple OTT') %}
{{ state_attr('media_player.kontor', 'media_title') }}
{% else %}
{{ state_attr('media_player.lg_c2', 'media_title') }}
{% endif %}```
can we write a persistent trigger template, that reflects the amount of times a certain automation was triggered, and has say the last 5 times as attributes history? I have smth like that for last motion triggers, but then simply template the triggering sensor, and not a adding number
a bit like this, but how to template that state, and the set number. https://www.home-assistant.io/integrations/template/#number
Hello all,
in an automation using a calendar event as a trigger i want an action repeating until the current time is after the event.end time.
this is what i've done but it does not work. Can you see what i'm missing ?
value_template: "{{ as_datetime(trigger.calendar_event.end) < as_datetime(now() | string) }}"
Seems like if/else statements aren't allowed in attributes for universal media player
Ofc I've considered the 'counter' https://www.home-assistant.io/integrations/counter/ but that is not persistent across restarts. here's a post in the community which makes it a bit easier to explain https://community.home-assistant.io/t/how-to-count-the-times-an-automation-was-triggered-restart-persistent/548475 Consider the above a morning lapse.... Counter does restore state, and post was updated with the effects that has for my requirements... sorry
still seeking. I found some errors with my template.
I added an action feeding an input_text entity with {{ as_timestamp( trigger.calendar_event.end) }} that works and store a timestamp of the event.end time
I changed my condition to
- repeat:
until:
- condition: template
value_template: "{{ as_timestamp(trigger.calendar_event.end) | float < as_timestamp(now()) | float }}"
I had check this in the template dev tool and can see the result switches to true there, but my condition is still not stopping the repeat loop. 😦
works 🙂
@lofty mason I did and it works once I add it to the configuration the sensor is created and the status is unavailable.
Is there a template to know if a state is a list? I had one for number but the entities changed and the numbers are now in a list. I just want to say if list do this else do that.
states are always strings
so you have to search for things that would make it a list, like ','
@tidal heart ^
Ah! I’ll will try that, ty
are you sure it's actually a list and not a large number?
@mighty ledge I now made this macro as a Dutch variant for relative_time with the additional options to choose how many time periods you want tot use, and if you want to use weeks as a time period or not
https://dpaste.org/qRkec
Works nice in dev with the new import function:
{% from 'relatieve_tijd.jinja' import relatieve_tijd %}
{{ relatieve_tijd(1,3, true) }}
53 jaar, 2 maanden en 2 weken
So I checked if the first input is a string or a number (so you can apply as_datetime) and I wanted to add some check if it was a datetime for some error handling
You can probably create a macro for checking datetimes too
when I get to the beta, i'll be revamping my system most likely
Hello, I have a sensor that counts expenses and displays a number. This number changes throughout the day (increases). I need to create statistics that remember the total number for each day so that I can see what value the sensor has reached each day. I want to do this through a https://www.home-assistant.io/integrations/history_stats/, but I'm not succeeding. I keep getting a result of zero.
Thank you for help
Just make a template sensor that stores the state of the other sensor at midnight
History stats won’t do what you want
@unborn sequoia I converted your message into a file since it's above 15 lines :+1:
Of course, I tried that, but the result is still zero.
I have this sensor: now shows the value 205.40
- platform: template sensors: home_costs_without_measurement: friendly_name: "Home costs without measurement (+-)" value_template: '{{ states("sensor.energy_home_costs") |float + states("sensor.energy_home_savings") |float + states("sensor.energy_home_sales") |float }}'
and this history_stats:
- platform: history_stats name: Celkové náklady na domácnost entity_id: sensor.home_costs_without_measurement state: "on" type: time start: "{{ now().replace(hour=0, minute=0, second=0) }}" end: "{{ now() }}"
you need to use a trigger based template sensor with a time trigger
and you need to use the new template sensor format for that. You are using the legacy format in your code above
Thanks for the reply. So I've written the sensor wrong? In an older format?
well, petro proposed to store the state of the sensor at midnight, for that you need a time trigger, which is not supported in the format you are using
Do you have a link to a similar example where it is solved? I'm new to HA and don't know much yet. Thank you
template:
- trigger:
- platform: time
at: "00:00"
sensor:
- unique_id: petunia_banana_whale_orange
name: Sensor status at midnight
state: "{{ states('sensor.your_source_sensor') }}"
put this directly in your configuration.yaml, amend where needed and wait until midnight
this will create. sensor.sensor_status_at_midnight (based on the name)
OK, thank you very much
one more question. Instead of sensor.your_source_sensor i will complete sensor.home_costs_without_measurement
What must be in place of petunia_banana_whale_orange?
There will also be: sensor.home_costs_without_measurement
Whatever you want as long as it's unique
so this is basically the name of this trigger?
No, it's the unique id used to store the entity in the entity registry
OK, so it doesn't matter if there's going to be anything unique.
One more question. I can easily set that 00:00 to 8 PM for the test now, right?
This will write the current value from the sensor right now and I'll know it's working. It is so?
Yes
in that case it doesn't work.
the sensor.home_costs_without_measurement now shows a value 276.87 and I already tried to execute this trigger twice and the value is still unknown.
I have 2 statuses recorded on the timeline and each time it is Unknown
huge problem with my template to get a sensor value.
{{ states.sensor.10_0_0_26_containers_active.state }} returns TemplateSyntaxError: expected token 'end of print statement', got '_containers_active'
What is your current code?
As mentioned in the docs object ids starting with a number don't work like you are using it
As also mentioned in the docs, you should not use states.sensor.whatever.state anyway, but states('sensor.whatever'). If you would have used that, you wouldn't have had any issues 🙂
Thanks for the attitude...An integration(Glances) named the object id's not me. No easy way to rename all 750 entities provided from this integration
You're welcome! 🙈
And still thanks for the help 😀
Here's the starting with numbers issue they refer to: https://www.home-assistant.io/docs/configuration/templating/#entity_id-that-begins-with-a-number
The info about states() is in the warning message at the bottom here: https://www.home-assistant.io/docs/configuration/templating/#states
You don't need to rename them, just use the states method instead, it's less characters too. {{ states('sensor.10_0_0_26_containers_active') }}
if you're dead set on useing the states object {{ states['sensor.10_0_0_26_containers_active'].state }}
I thought you needed to put the object id between square brackets, but both options seem to work
__getitem__ for the states object is magical
fyi [ ] uses __getitem__ if you're looking at the code
and __getattr__ is what's used after .
so when you do ['x'] it calls __getitem__, when you do blah.x it calls __getattr__
blah( uses __call__
there, you have a crashcoarse in the backend code
for templates
Hi guys! is it possible to get a value from an Area in templates?
For example, I created an Area called Bedroom
I'd like to do something like :
If any device inside the Bedroom is on , do this ... I know the template syntax , I'm interested in the area part.
Thank you
{{ states('area.bedroom') }} ... something like this to get on/off
Yes this is the cause. I have removed this part. New sensors are now detected by HA
You can get the entities in an area, but from there you have to build the logic to get the states you want
This is hard for me cause I'm not a programmer.
{% set entities = area_entities('Office') %}
{% set any_on = false %}
{% for entity_id in entities %}
{% if states(entity_id) == 'on' %}
{% set any_on = true %}
{% endif %}
{% endfor %}
{% if any_on %}
yes
{% endif %}
but it would be something like this?
The idea is correct and would work in most languages. Unfortunately that won’t work in jinja.
I’m on mobile so I can’t provide an example atm
what do you want {{ entity }} to return?
the yes part you can do like this:
{% set entities = area_entities('Office') %}
{{ 'yes' if entities | select('is_state', 'on') | list | count > 0 }}
Typo, sorry
No worries mate 😀
Gonna check this as soon as I get home. Thank you!
Hey everyone, trying to think of a way to define a sensor that +1 every time a different sensor goes to a specific state (like a counter) that will reset at midnight. For example if sensor.i_need_help goes to ready I would like to count that on a daily cycle.
Are you opposed to using a counter helper and an automation? Seems pretty straightforward.
Actually I think history_stats does exactly this already, if that fits what you need.
I attempted a utility helper but there is no way to define a specific state that it needs to be to increment. I only want to count the "ready" state.
I'll go take a look thanks!
What template would read out the time an event was last fired? In my case the event type is mobile_app_notification_action, event data is - action: TOGGLE_LIGHT
You can create a trigger based template sensor, which triggers on the event, and just put the current datetime in it's state
hi. what's the proper way of extracting the tag_id from a trigger by the tag platform? The trigger variable seems to contain the key 'event', which then looks like <Event tag_scanned[L]: tag_id=6A-74-98-1A, device_id=2bb60a1ab97813b534d5f06136f72b94> There is not tag trigger in the trigger variable docs https://www.home-assistant.io/docs/automation/templating#available-trigger-data
it's an event
so you need to use event variables
trigger.event.data.tag_id
or
trigger:
- platform: event
event_type: tag_scanned
event_data:
tag_id: bananas
great, the trigger.event.data key works! THanks
How would I get epoch time in miliseconds?
{{ (now().timestamp() * 1000) | int }}?
Perfect thank you.
A couple of zeros to much there for milliseconds...
Turned out I actually needed microseconds so it was perfect lol. I found out when I used an epoch converter to check the to see how accurate the output was.
I'm trying to get check if a state is a list. This one is pulling the RGB and makes it in hex format for mushroom card to use. But my recent change with the bulbs the RGB state is changed from number to list.
Previously I used it like this
{%- if is_state("light.bathroom_mirror", 'on') %}
{%- if state_attr("light.bathroom_mirror", 'rgb_color') is number %}
{{ '#%02x%02x%02x' % state_attr("light.bathroom_mirror", 'rgb_color') }}
{%- else %}
orange
{% endif %}
{%- else %}
grey
{% endif %}
But as it's no number anymore it fails the second IF check. How can I change the check from number to list?
{%- if state_attr("light.bathroom_mirror", 'rgb_color') is number %} its this part I'm wondering about
rgb_color is always a list with 3 numbers in it
The output of {{ state_attr("light.bathroom_mirror", 'rgb_color') }} is ```yaml
[
255,
237,
222
]
Ah ofc I could check if none and then if the light is on/off and if on it can be orange! Thanks
or just replace is number with is not none
Any idea how to strip everything after the decimal?
Doesn't seem to work
then your parenthesis are wrong
Got it
order of operations
| int before the *
no, you'd int after you get the result
pedmas
parenthesis, exponents, division, multiplication, addition, subtraction
This works
{{ (now().timestamp() + 300) | int * 1000 }}
filters are applied before all of that
Pepperidge farm remembers lol
I'm assuming you orginally had this
{{ (now().timestamp() + 300) * 1000 | int }}
Anyone know if you can tell universal media control which child should be active at any given time? It tends to select my apple tv even though it's not doing anything
all you needed to do was
{{ (now().timestamp() + 300 * 1000) | int }}
however, you probably wanted to reverse the 1000 and 300
{{ (now().timestamp() * 1000 + 300) | int }}
because pedmas
That isn't epoch time (microseconds) in 5 minutes.
if the 300 is supposed to be seconds, then you'd need to add 300000
regardless, this is all just math and order of operations
Yep and preference.
that's the point I'm making here
lastly, I'm not sure why you're using seconds anyways
{{ (now() + timedelta(minutes=5)).timestamp() | int }}
It's not me lol. It's nutanix. They use epoch time in miliseconds. So I started with seconds then converted to miliseconds.
milliseconds or microseconds?
I thought it was microseconds because the sme told me it was but it's actually miliseconds apparently.
I made an entity in a template, and it's a copy-paste of others that work but for some reason I can't find the entity in the Dev Tools. I also see no problems in the Log. Do I have a stupid typo somewhere?
# TEST - Hourly prices for the dishwasher
- name: "Cost for dishwasher EUR per hour"
unique_id: cost_hourly_dishwasher
unit_of_measurement: "EUR"
state: >
{{ (states('sensor.dishwasher_hourly_energy_use') | round (3)) * (states('sensor.energyprices') | round (3))}}
where did you place it?
under sensor: in a templates.yaml file
The other sensors and templates in that file work perfectly
It almost looks like it's got an old entity ID from a previous version of my yaml. Could that be?
Since I just found another entity with the right data, but the entity id is different. And I don't have any YAML code or UI entity for that sensor. Which means HASS thinks the entity with that unique_id has a different id I think...
do you now have
sensor:
- bla
sensor:
- foo
if you reused the unique_id it will still use the old entity_id
If I change it, it will create a new entity right, with new data?
yes
but because you added it, you can change the entity_id in the GUI
that will not affect historical data
it will still be available
Great thanks!
Ah, adding the unique id is what makes it possible to change through UI? Good to know!
Hi all. Having trouble utilizing a different icon based on state of group entity. Is this right: https://hastebin.com/share/nosagizejo.makefile
is cover.living_room_curtains_straight the cover that's being created?
yes, its a helper group of 2 curtain covers, i check the state and it is changing between open and closed. so the icon should work
are you creating a template cover though?
in the cover section of configuration.yaml using platform: template?
a template cover is an integration that makes a cover entity in home assistant using other entities as reference while you provide your own code to determine it's behavior. That's the only place you can use icon_template for a cover entity.
oh right, so should i just be using "Icon:" instead of icon_template ?
see i have cover entities through z2mqtt, i grouped them as a cover group
so i did not crate any cover" section to my config yaml
you can't set custom icons for on/off on a cover without icon_template
so if your goal is to have a unique icon for on/off on a cover, you can't do that
oh ok
If your entity is in HA and provided by an integration, you can simply change the "display as" in the UI and choose what to display the cover as
chances are, it'll have curtain icons as an option
@shell leaf do you know where that option is?
i only want to change the icon in my dashboard based on state. Can you point me in how to crate the cover template that allows me to use icon_tempalte
right
click on your cover entity, go to the cog wheel
that will be your settings page, there's a display as dropdown
and you should be able to switch it to curtain
ok thats done
sorry, I have not provided enough clarity, I have a mushroom card, that asks me to select the icon i want for that entity, I would like to use a template to change that icon, ill share the full card
ok, let me try that now
that works, didnt know it was automatic from the entity, thought all entities came with static icons
thanks for walking me through that
Hi, sorry for the long answer.
So even at midnight, no value was recorded.
My current code is this:
template:
- trigger:
- platform: time
at: "00:00"
sensor:- unique_id: petunia_banana_whale_orange
name: Sensor status at midnight
state: "{{ states('home_costs_without_measurement') }}"
You're missing the sensor. part in the entity id
{{now() - 'sensor.saugroboter_og_cleaning_history' >= 3 }}
I am trying to check if the last cleaning was 3 or more days ago.
The sensor reports the following attributes:
Attributes 2023-03-15 10:10:21 cleaning_time: 26 min cleaned_area: 25 m² status: Cleaning completed: true water_tank: Not installed
Does that datetime string also have a key in the attributes?
It is shown like this:
(cant post a screenshot directly here)
https://imgur.com/a/uquOYFh
Ah okay
It's the state
{{now() - states('sensor.saugroboter_og_cleaning_history') | as_datetime | as_local >= timedelta(days=3) }}
I'm trying to write a template trigger that acts as a counter. Is there a way to get the current state within this context? Or would I just have to refer to the absolute entity name? (e.g. this.state vs states('sensor.my_counter'))
Either would work, just trying to get a better idea of what context you have inside these template trigger sensors
Looks like that is exactly what I want. Tyvm. Maybe I can do it alone the next time 🙂
I don't think this.state is available in the trigger
Is there anything like that, though?
Also trying to make sure I'm differentiating here between the trigger context and the sensor context (if they are even different)
The this object is created when a trigger triggers
But I don't understand what you are trying to achieve
- trigger:
- platform: state
entity_id: sensor.foobar
to: 0
sensor:
- name: My counter
state: "{{ states('sensor.my_counter)|int + 1}}"
Roughly this I think
Just wondering if there's something more succinct I can do for the template there, such as accessing the current sensors state if that's possible
You can use this.state for that state template
Ok cool
You do need a default for the int filter though, as the first time it will trigger the state will be unknown
Ah yeah. I really need to stop getting lazy with my casting
Actually, the first time it triggers should be the only time that this would occur right?
Yes
I think I've actually been kinda hesitant to use defaults for casting, because I actually want it to error out if I get a weird value so I'm aware of the problem.
What are your thoughts there?
You can work around that using availability templates or using thing like is_number
Like if I have template that uses an underlying sensor, and that sensor starts reporting values I'm not expecting, I don't want to just fall back to a default, I want an error to bubble up.
Without filing your logs with errors
oops, you're right. I overlooked this one.
Thank you
Ok. So in this case, I'd want to have an availability template on the counter sensor that looks at the underlying sensor (sensor.foobar) and does a check to see if it's available, correct?
That sounds great, and I think I'd use that here. One thought that comes to mind is that I don't think all sensors have availability templates, no?
It does look like all template sensors have it: https://www.home-assistant.io/integrations/template/#availability
I get a sense that there are gaps somewhere though. I guess I'll cross that road when I get to it if that's the case.
Well, you don't need that, as it only triggers when it goes to 0, so you know it's available
And in this case you really don't want an availability filter, that will reset your count
-> Templates to test