#templates-archived
1 messages · Page 68 of 1
ye im done.. cant seem to find a valid syntax for the minimum value for all Amersfoort gasstations
been reading about min() max() sum() etc, but all go into error mode
this is the site/json/syntax so far...
I read here that it's not gonna happen
I'll be making a couple of sensors from rest I guess and ditch the attributes idea
Put all of Amersfoort in the attribute, then create a template sensor like my example above which uses the data from the rest sensor attribute
I found a sensor that somebody listed it in a forum, and I would like to add that into my system. It basically says if it's nighttime. I've added the script to a sensor.yaml and change the configuration.yaml to include the sensor.yaml. BUT how do I access this in an automation?
"sensor:
- platform: template
sensors:
Period of the day
period_of_day:
friendly_name: 'period of the day'
value_template: >-"
Sorry I was trying to add the script
so in automation condition if the period_of day = night then turn on light.
how do I access period_of _day
it will create an entity sensor.period_of_day which you can use in a state trigger or state condition
and to format it properly
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.
I looked all over for a way to edit the post and I don't see it anywhere. I must be blind. i found out there must be something wrong with this text of this script as I found the errors in the log.
you are actually not sharing the template part
@tardy saddle I converted your message into a file since it's above 15 lines :+1:
and when you hover over your post, you will see a menu with a pencil icon
use that to edit it
Invalid config for 'sensor' at configuration.yaml, line 13: required key 'platform' not provided,
I have only been doing HA for about six days now and still struggling to figure out all of this stuff I'm sorry for the delay questions
the first line with sensor: should not be copied to sensor.yaml
you already have that line in your configuration.yaml
ooooooh THANK YOU
you should also use state_attr() in your template, and if this is your first template sensor, I would suggest to start with using the modern format
and not the legacy format
I just copied this from the forum
yes, but probably from a rather old post
when I what to check if its Night time using this sensor what is the trigger type?
# in configuration.yaml
template: !include template.yaml
# in template.yaml
- sensor:
- unique_id: bbcc8586-8f93-4fb5-8360-8f132d9d7ac5
name: Period of the day
state: >
{% if as_timestamp(state_attr('sun.sun', 'next_dusk')) - as_timestamp(state_attr('sun.sun', 'next_setting')) < 0 %}
dusk
{% elif as_timestamp(state_attr('sun.sun', 'next_rising')) - as_timestamp(state_attr('sun.sun', 'next_dawn')) < 0 %}
dawn
{% elif state_attr('sun.sun', 'elevation') < 0 %}
night
{% else %}
day
{% endif %}
icon: >
{% if is_state('sun.sun', 'above_horizon') %}
mdi:weather-sunny
{% else %}
mdi:weather-night
{% endif %}
availability: "{{ 'sun.sun' | has_value }}"
that's the modern format
trigger type will be entity > state (assuming you use the GUI)
is it ok to copy your code?
yes
thank you so much for your help. I really do appreciate it. Honestly this is too complicated for me. At this point I used to program all the time but I'm now 70 years old and haven't quite been doing programming for a while so I'm not familiar with the syntax, but I can definitely follow it, I will learn. If this hadn't worked, I had made a boolean helper call nighttime and have a automation to turn it off and on based on sunrise and Sunset. I think that would work but I would like to make this idea work also..
what does it return? Like I have sensor.period of the day state but does it not return like night, dusk, dawn, day
that would eventually be a workaround. The aim was once sensor. The cheapest+town+address+etc all rolled into one. I dont mind a second sensor, but it was fun trying....
Did you already manage to put all the data in an attriubte of a rest sensor?
well you aren't looking in the right spot.
$.[?(@.town=='Amersfoort')][?(@.price==$.[?(@.town=='Amersfoort')].price.min())]
should work
getting compile errors when trying it online with at different sites
the online sites don't appear to allow functions
ok ill test it in the rest sensor and see what i get
You may need to alter it
using $..price.min() instead of filtering to the town
I'm no json path expert, so your mileage may vary
keep running out of gas anyway, so any milage is progress 😉
resource: "xxx"
scan_interval: 600
sensor:
- name: "Benzine Amersfoort #1 prijs"
unit_of_measurement: '€'
value_template: "{{ value_json | selectattr('town', 'equalto', 'Amersfoort') | sort(attribute='price') | map(attribute='price') | first }}"
json_attributes_path: $.[?(@.town=='Amersfoort')]
json_attributes:
- town
- address
- gps
- price```
For starters using the wrong path, this works. Im getting the first hit in the list as attributes
Thanks to Thefes for sharing the example i have a min temp sensor. Now if sensor.temp_woonkamer drops to 0 (after a restart or server connection lost...) the min temp show 0. Is there anything i can do to ignore 0 value.
- platform: statistics
name: Min temp woonkamer
unique_id: min_temp_woonkamer
entity_id: sensor.temp_woonkamer
state_characteristic: value_min
max_age:
hours: 12```
isn't relative_time() suppose to convert a date to like "1 day ago" etc?
it does
you should fix sensor.temp_woonkamer
to ensure it doesn't output 0 on restart
i'm sitting on 2024.2.1 and even the default example in the template under dev tools is showing relative time as The sun will rise at 2024-02-19T07:02:48.967075-06:00.
that's a string not a datetime
{% if is_state("sun.sun", "above_horizon") -%} The sun rose {{ relative_time(states.sun.sun.last_changed) }} ago. {%- else -%} The sun will rise at {{ as_timestamp(state_attr("sun.sun", "next_rising")) | timestamp_local }}. {%- endif %}
thats the default entry for the template thing
the ago part confuses me if it's not broke lol
right but look at it's output above
Petro, any change you can show me how to fix this. 🙂
unique_id: "temp_woonkamer"
icon: "mdi:sofa-outline"
state: "{{ state_attr('climate.vicare_heating', 'room_temperature') | float(default=0) }}"
unit_of_measurement: "°C"```
that's from your else statement
which is using timestamp_local
remove the default=0 and add an availability template
ok then I don't get why 2024-02-19T12:14:44+00:00 dosen't work.. shouldn't it?
Also, relative time only works on times in the past
Like this?
unique_id: "temp_woonkamer"
icon: "mdi:sofa-outline"
availability: "{{ is_number(states('climate.vicare_heating')) }}"
state: "{{ state_attr('climate.vicare_heating', 'room_temperature') | float(0) }}"
unit_of_measurement: "°C"```
Thanks TheFes!
So it will not warning that there is no default because of the availability?
no, because it will not render that template if the availability template renders false
the float filter is useless there because of two reasons
- the state will be a string anyway
- the value will already be a float
Thanks again for clearing that out.
- name: "temp_woonkamer"
unique_id: "temp_woonkamer"
icon: "mdi:sofa-outline"
availability: "{{ is_number(state_attr('climate.vicare_heating', 'room_temperature')) }}"
state: "{{ state_attr('climate.vicare_heating', 'room_temperature') }}"
unit_of_measurement: "°C"
Yep that's what i have now, thanks!
wiat
wait
you should check on the attribute in the availability filter
the state of the entity will be a string like heating so this will always be false
This?
- name: "temp_woonkamer"
unique_id: "temp_woonkamer"
icon: "mdi:sofa-outline"
availability: "{{ is_number(states('climate.vicare_heating','room_temperature')) }}"
state: "{{ state_attr('climate.vicare_heating', 'room_temperature') }}"
unit_of_measurement: "°C"```
ya
state_attr instead of states
Oeps! 🙂
like you have for your state template
Just to be sure.
unique_id: "temp_woonkamer"
icon: "mdi:sofa-outline"
availability: "{{ is_number(state_attr('climate.vicare_heating')) }}"
state: "{{ state_attr('climate.vicare_heating', 'room_temperature') }}"
unit_of_measurement: "°C"```
Think this will be it?
yes, which is exactly what I posted above 😛
nope, you keep messing it up
Yep i know my bad 🙂
just copy/paste thefes
unique_id: "temp_woonkamer"
icon: "mdi:sofa-outline"
availability: "{{ is_number(state_attr('climate.vicare_heating', 'room_temperature')) }}"
state: "{{ state_attr('climate.vicare_heating', 'room_temperature') }}"
unit_of_measurement: "°C"```
oh yes, I missed that you removed the attribute now
this one is exactly what I posted above
FYI, you can use easy_time macros and it will add the ago
Mmm i thought it must always start lower case?
If that is what you mean by "slugified name"?
it also works with future times
my problem was I was using a string to try and use relative_time than when I saw the default example output what it did I thought my HA instance was borked lol
it's early am for me.. this is always when I get brain farts trying to mess with my dashboard
btw relative_time was spitting out the exact same string in the editor. shouldn't that have error?
oh. that was part of why I was running in loops lol
no, you can anything in the name, it will be used for the entity_id, in which it will lowercase it, and replace spaces with underscores
so name: This is a nice name for a template sensor will result in sensor.this_is_a_nice_name
you can use relative time plus or probably one of macro's in petro's easy time set
I just had to use as_datetime then use relative_time on that in a sensor
- platform: template
kwh_per_km:
friendly_name: 'kWh per 100 Kilometers'
value_template: >-
{% if states('sensor.zoe_mileage')|float > 0 and states('sensor.zoe_plug_s_energy')|float > 0 %}
{{ 100 / (states('sensor.zoe_plug_s_energy')|float / states('sensor.zoe_mileage')|float)|round(2) }}
{% else %}
N/A
{% endif %}
unit_of_measurement: 'kWh/100km'
I want to create a template to measure kWh/100km usage of my renault zoe. I use a shelly plug s to on the 230V charger
Till now it displays 0kWh/100km
@keen vale 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 forgot the closing tag
ok so i give up on jsonpath to find my minium price gaspump and gonna try your route.
$.[?(@.town=='Amersfoort')]
This gives me all the Amersfoort items in the list like so:
https://dpaste.com/5E8X6EV6H
How do i move this stuff into one json_attribute?
{{ value_json | selectattr('town', 'equalto', 'Amersfoort') | sort(attribute='price') | map(attribute='price') | first }}
json_attributes_path: $.[?(@.town=='Amersfoort')]
json_attributes:
- WHATGOESHERE?```
I don't think you can, because it requires a key, which you don't have
after that i can write ninja2 stuff to sort this i guess
You can't use any jinja for the attributes
I wasn't aware you could write json paths as petro suggested, I do think that is the route you need to take
but I don't have any experience with that
nor me.
im mean... the question isnt hard, the answer seems unrationally hard lol
i cant even use platform: file to fetch it into attributes since its not supported
i give up
using jq?
this post highlights the way to get all the data into attributes when your main object is a list
ah, it takes the data, puts it in a named dict, and then you can use that for the attributes.
thx. yet another language to sift through. This is hobby and agony at the same time
Any suggestions how to improve it?
1.) I don't like datetime comparisions with timestamps, maybe there is a better, more semantic way?
2.) I'd love to get rid of the loop and maybe filter with something like select.
{% set open_outer_doors_and_windows = state_attr('binary_sensor.outer_doors_and_windows', 'entity_id') | select('is_state', 'on') | list %}
open_outer_doors_and_windows: {{ open_outer_doors_and_windows }}
{% set ns = namespace(open_for_too_long_outer_doors_and_windows=[]) %}
{%- for open_outer_door_or_window in open_outer_doors_and_windows -%}
{%- if now().timestamp() - states[open_outer_door_or_window].last_changed.timestamp() > 30 -%}
{%- set ns.open_for_too_long_outer_doors_and_windows = ns.open_for_too_long_outer_doors_and_windows + [open_outer_door_or_window] -%}
{%- endif -%}
{%- endfor %}
open_for_too_long_outer_doors_and_windows: {{ ns.open_for_too_long_outer_doors_and_windows }}
well, you can use shorter variable names for starters
{{ expand('binary_sensor.outer_doors_and_windows') | selectattr('state', 'eq', 'on') | selectattr('last_changed', '<', now() - timedelta(seconds=30)) | map(attribute='entity_id') | list }}
that also works
diffferent apporach
fyi fes, that should be seconds
not minutes
timestamp is seconds
oh
I knew that of course, but I just noticed the 30 and assumed a door which is open for 30 seconds wouldn't be considere open for too long
yeah, it won't cause the template to update fast enough
awesome, exactly what I was looking for, thx!
BTW, I've stumbled upon expand, but I didn't really explore it, as I could find any documentation for it…
It's not a Jinja function, as it is not listed here: https://jinja.palletsprojects.com/en/3.1.x/templates/
So it must be a HA addition – the only mention I've found was https://www.home-assistant.io/docs/configuration/templating/#working-with-groups
The expand function and filter can be used to sort entities and expand groups. It outputs a sorted array of entities with no duplicates.
Kinda circular definition 😄 Expand can expand groups 😄 Whatever that means 😛
So I'll just ask… what does it do exactly?
it takes a list of entity_id's and turns them into an expanded list of state objects
when used on a group it expands the group members
it also works on nested groups, so it goes down to the actual entity ids
wdym by "expanded"? i feel like i'm missing some kind of english/programming nomenclature.
{{ expand('binary_sensor.outer_doors_and_windows') }} gives me a list of <template TemplateState( objects, whatever they represent… I guess I'd need to look into HA's source code.
TemplateState is the state object
ah, so it converts/extracts "state objects" from "entity objects"?
if that binary_sensor is a helper group of binary_sensors, it will expand the group into individual state objects
state objects are the backbone of HA
there's entity_id's and state objects, nothing else
an entity_id is a string
an identifier for the entity itself, which is a state object
ok, so it is just a function that takes a list of entity_ids and returns a list of state objects with the entity_ids from the objects storage? it's a service object locator, one would say, right? 😄
it's main use is to expand grouped entities
i.e. if you have a grouped entity named binary_sensor.abc that is made up from 2 binary sensors binary_sensor.1 and binary_sensor.2
when you expand binary_sensor.abc you will get state objects for binary_sensor.1 and binary_sensor.2
if it's not grouped, you'll just get the state object for the input entity_id
wow, first time i hear about "grouped entities".
I know groups as the integration feature, but i guess those are a different thing or a subtype?
how do I know/identify which entities are "grouped" if I look into a device, see a "lqi" entity, can I discover if it is a "base" entity or a "grouped entity" consisting of some "subentities" that expand would also give me?
they are helper entities that you create in the UI or if you create the old school entitys that start with group.xxx
if you didn't create it manually in the UI, it's not a grouped entity
ah, ok, easy then
although I see that {{ expand(['sensor.sonoff_snzb_02_temp_humid_th1_linkquality']) }} also works -> so it handles not only groups, but also simple arrays
so i''' sum up my understanding: it takes string/iterable (of entity_id(s)) and returns an array of state objects (it is a entity_id -> state_object mapper)
it handles everything
yes, but it would also work on a comma seperated string
{{ expand('sensor.a, sensor.b') }}
lists, arrays, tuples, extra arguments
magic, haha 😄
And that's what's missing: a solid documentation… list of every function/filter - with described arguments, return values, error handling, etc… just my little rant. i hope i can help to improve it, although my knowledge is cleary lacking here 🙂
it's been mentioned many times, but no one wants to put in the work to do that
in an agreeable format
yeah, i guess… i can see simple tables, DL/DT/DDs, linkable headers, etc. no standard format. there is also a {% configuration %} tag, which looks promising to be used on a larger scale. anyway, still exploring. when too many standards, i may invent yet another standard to rule them all… <fameous xkcd comic here> 😄
tables don't look good on mobile
so thats out
#devs_documentation-archived problems
the standard isn't the hard part, it's actually documenting each filter, function, and test
it would be a massive amount of work to do this. Once the format is decided, the work will most likely be done by a few of us volunteers.
#devs_documentation-archived is kinda quiet… i already have a list of questions/ideas, don't wanna spam there, so I just ask one at the time, but i don't get any answers 😦 i guess i'll make a few prototypes, PRs, and see how are they received.
I think one of things that will come out of that is inconsistency and limitations in existing functions. Some take single entity_id but not a list, for instance
Is hard to tell now unless you try it and you get some unfriendly error
it'll be treated like python's docs tho
I 'fixed' a few of those in a branch, but didn't follow through
frencks spook documentation has examples
i got this going now. After trial and error on some jq explorer website i have an Amersfoortlist, sorted on price
cat test.json | jq 'sort_by(.price) | .[] | select(.town == "Amersfoort")'
now the next step is to select the first/second/third option etc and try to make something out of it
yeah, this is what i wish we had, instead of the Templating docs page mess, awesome 🙂 well, i'll do what i can until that, but that's an offtopic; thx again for the expand explanation, and @marble jackal for a much improvement to my little template 😗
well, that's most likely what is coming, we are waiting on frenck to decide on the format, lay the ground work, so we can all start adding the separate pages
even more good news. selecting the first sorted item:
[ sort_by(.price) | .[] | select(.town == "Amersfoort") ] | .[0]
or first remove crap, then sort.
[ .[] | select(.town == "Amersfoort") ] | sort_by(.price) | .[0]
and the cli
curl "httpaddress" | jq '[ .[] | select(.town == "Amersfoort") ] | sort_by(.price) | .[0]'
why aren't you just putting it all in data like the post?
otherwise, if you have 3 of these separate calls, you'll be hitting the endpoint x3 instead of x1
im just posting my steps
not to mention, you can then just do the sorting in jinja whenever the data updates instead of every time you poll
the last one is the one i need
then hopefully i can attribute this single json entry
finally!
name: "Benzine Amersfoort prijs #1"
command: curl "https://xxx/" | jq '[ .[] | select(.town == "Amersfoort") ] | sort_by(.price) | .[0]'
command_timeout: 30
scan_interval: 300
value_template: "{{ value_json.price }}"
json_attributes:
- organization
- town
- gps
- address```
I am trying to learn and understand a sensor. The sensor returns a state and an icon. On the automation GUI it has fields for another Entity and Attribute, From, To. Where do I check the state? Does that make any sense? I want to say that if the sensor state = night then turn on the lights.
boooo json path, yeah baby jq
The true values of states and attributes can be found in the Developer Tools - States
https://my.home-assistant.io/redirect/developer_states/
I am looking in developer tools -> states and at the sensor. I put the entity in and it shows state and state attributes. When I'm trying to find out is how do I refer to that in the GUI automation.
For example with state triggers or state conditions.
for example: ``` alias: test day time
description: ""
trigger:
- platform: state
entity_id:- sensor.period_of_the_day
attribute: night
condition: []
action:
- sensor.period_of_the_day
- service: light.turn_on
metadata: {}
data: {}
target:
device_id: 7b09c5dd81a3e1df6ac5f2811e7ce16b
mode: single
is putting attribute night, the place where I checked to see if that's the right state? Maybe the GUI doesnt have the right field?
In this case, the automation will fire on any change of the attribute "night"
@tardy saddle I converted your message into a file since it's above 15 lines :+1:
You don't have an attribute "night". I assume you try to trigger on the state "night"
Then you cannot use any attribute. Leave that field empty and put "night" into the "to" field.
ohhh
using developer tools if I enter the state and then click set state, is that supposed to simulate the state and should trigger the automation?
Yes
hummm didnt triger. The automation does turn on the light if I click run, so I know that part is correct.
description: ""
trigger:
- platform: state
entity_id:
- sensor.period_of_the_day
to: night
condition: []
action:
- service: light.turn_on
metadata: {}
data: {}
target:
device_id: 7b09c5dd81a3e1df6ac5f2811e7ce16b
mode: single ```
automations only trigger when state changes occur
if the state was already night, it's not going to trigger
thats it. got it!!! THANK YOU!!
now I need to examine that sensor that I found online and see if it really makes sense or should I just use sunrise and Sunset and had a helper boolean turned on
does anyone have an example of a template sensor that uses attribute_templates? i want to have a template sensor that has a few different attributes based on conditions
Hi all - I’ve successfully connected my Litter Robot to Discord so I can get notifications when there’s a change in state or status. However when I read the status code all I can get is the 3 letter abbreviation versus the expanded meaning that shows up in the Home Assistant interface. How can I use templates to get the expanded text? I saw a post in forums where someone had to recreate the mapping even though it already exists in the code, and thought there has to be an easier way than this, right?
how did you connect it to Discord?
Discord integration - I’m using notifications to send messages to a Discord channel
then you can send whatever you want
So I’m in the same situation as this person, but I don’t understand why I have to recreate the dictionary if it already exists in code to render in the HA WebUI https://community.home-assistant.io/t/extracting-status-message-and-tts-from-litter-robot/486418/3
Plus that’s not really maintainable if the manufacturer decides to add a bunch of statuses later
can't you just use the existing attribute?
that's what I use to display the status in the frontend
{{ state_attr('vacuum.litter_robot_4_litter_box', 'status') }}
seems like you're using the state from sensor.litter_robot_4_status_code
all the workarounds in that thread seem unnecessary, and it was from 2022
if you need it to be the state of an entity for some reason, just create a template sensor with something like what I put above
I'm trying to make a template in a mushroom card result in an invisible character because I cannot leave it empty (if I do the title gets vertically centered and collides with secondary info, see https://file.coffee/u/cFPmt-Y2zczEvYwdJUt2u.png). But I have tried a few ASCI invisible characters and they seem to get ignored by the template and gets detected as empty. Can anyone tip me in the right direction?
type: custom:mushroom-template-card
primary: Kitchen
secondary: |-
{% if is_state('timer.kitchen_lights_timer', 'active') %}
----- here I need an invisible character, so it isn't empty ---------
{% else %}
{{ states('sensor.wiser_lts_temperature_kitchen', with_unit=True) }} | {{ states.binary_sensor.kitchen_presence_sensor_presence.last_changed | relative_time }} ago det
{% endif %}
https://www.editpad.org/tool/invisible-character copy from here and paste in your card
If you want it to conditionally change, you need to refer to itself in case you don't want it to change.
And you have to safeguard that for the cases it doesn't exist yet
attributes;
your_attribute: >
{% if something %}
whatever
{% else %}
{{ this.attributes.your_attribute | default('unknown') }}
{% endif %}
This works best with trigger based template sensors
yay! It worked!! I didn't expect it to since when I did I was also copying it from an ASCII table. Thanks!
Hey everyone! I'm building a sensor to get the electricity price of the previous hour. I have a sensor with all prices per hour, but I am having trouble getting the previous one
```{{ (state_attr('sensor.nordpool_kwh_fi_eur_3_10_024', 'raw_today')).22.value }}''`
Basically, I would need to change the '22' here to always show one less than the current hour - I was able to make a template sensor, but I'm not sure how to replace the '22' with a reference to the sensor?
{{ (state_attr('sensor.nordpool_kwh_fi_eur_3_10_024', 'raw_today'))[now().hour - 1].value }}
like that?
no need for a separate template sensor if you just want the current hour
Well, that certainly simplifies it! I didn't know the correct syntax to use :)
Thank you, I will confirm it works in a moment
you'll probably have an issue at midnight
Yeah, that's why I had the template sensor to fix that
if you have a sensor that does what you want, you can just replace the portion above with [states('sensor.whatever')|float]
The state of that sensor is the current price right? You could trigger on a state change in a trigger based template sensor and store the previous value as the template sensor state
That also sounds like a good solution
If I can figure out how to store the pre-change value, that is!
- trigger:
- platform: state
entity_id: sensor.nordpool_kwh_fi_eur_3_10_024
not_to: ['unavailable', 'unknown']
not_from: ['unavailable', 'unknown']
sensor:
- unique_id: nordpool_previous price_sensor
name: Nordpool previous price
state: "{{ trigger.from_state.state }}"
Ah, thank you @marble jackal You're entirely too kind!
And thanks to you too, Rob, for the assistnace
Don't restart HA 30 seconds prior to the hour change though 😉
I have an automation trigger on an event. can I get the event data in a notification message or condition?
I'm looking to get event.data.device_id. when I look at {{ trigger }} it looks like the event property is empty.
platform: event
event_type: tag_scanned
variables:
source: "{{ trigger.event.data.device_id }}"
this seems to work
then I use {{ source }}
is there an easier/shorter way to write this?
{% set front_door = is_state("input_text.tagreader_front_door", source) %}
{% set side_door = is_state("input_text.tagreader_side_door", source) %}
{% set back_door = is_state("input_text.tagreader_back_door", source) %}
{% if front_door %} lock.front_door_deadbolt
{% elif side_door %} lock.side_door_deadbolt
{% elif side_door %} lock.back_door_deadbolt
{% else %} none
{% endif %}
ideally I'd just get front/side/back and chain it with the string?
{% set location =
is_state("input_text.tagreader_front_door", source) and "front"
or is_state("input_text.tagreader_side_door", source) and "side"
or is_state("input_text.tagreader_back_door", source) and "back" or "none"
%}
{{ "lock." + location + "_door_deadbolt" }}
not sure if this is better or worse 😂
It doesn't make sense
The last attempt
The 'and "front"' part and such
There's nothing wrong with the first one. There are fancier ways, but 🤷
Anyway to get the previous state of an input_text in a template? or do i have to do SQL
a trigger based template sensor which triggers on the state change of that input_text, and then stores trigger.from_state.state
quite similar to this #templates-archived message
wow it was one cm above my post facepalm. thanks man
Speaking of trigger templates, how would I sum the previous and new state? Surely it's not {{ trigger.from_state.state }} + {{ trigger.to_state.state }}
Both should be treated as floats
{{ trigger.from_state.state | float + trigger.to_state.state | float }}
Thanks again!
it sets location to front, side, back, or none 🤷♂️
is there a way to provide a default for a trigger state in a template? I have an automation that automatically turns on the radio when the light turns on. Same with off. i currently use this action template, but on every startup HA complains that the automation could not be validated and might be broken, because the state is not known during it's check.
data:
entity_id: media_player.soundtouch_bathroom_stefan
service_template: media_player.turn_{{ trigger.to_state.state }}
post the full automation
@placid kindle I converted your message into a file since it's above 15 lines :+1:
add unavailable as a not state condition
thanks, will give it a try
or do this:
- entity_id: light.home_secondary_bathroom
platform: state
to:
- "on"
- "off"
you can remove the condition then.
not a fan of having to track yet another helper entity (and exclude it from history etc etc)

that's not another helper entity?
where else would you put the suggested code if not into a yaml defining sensor entities etc?
he's telling you to modify your trigger
which has nothingt o do with a helper entity, that's why we are all confused by your response
your automation would look like this instead:
alias: "Auto: Bad-Radio an/aus"
description: Radio an/aus wenn Licht in Bad an/ausgeschaltet wird
trigger:
- entity_id: light.home_secondary_bathroom
platform: state
to:
- 'on'
- 'off'
action:
- data:
entity_id: media_player.soundtouch_bathroom_stefan
service_template: media_player.turn_{{ trigger.to_state.state }}
mode: single
well, just a code snippet alone did not tell me where to put it. And it looked like a sensor definition to me
well, its a trigger
not a sensor def
- platform: xxxx is only used for old style yaml configurations.
otherwise it's a trigger
if you know this syntax, then yes. I create my automations via UI 😉
then just remove the condtion and add on and off in the too field via the UI
you can always swap to yaml mode to view the output as well
no need to get testy with us 😉
well, I wrote my own blueprint about a year ago, but that's about it. Forgot whatever I had learned back then since I don't have that many automations, and all the others could be easily done via UI
and even though I do code for a living, I prefer to not have to do so for private things.
Hey! Came for some help, as I am having some difficulties when trying to comprehend the error messages. I have set up this light template (http://pastie.org/p/0hFLPjYKIxyHYTOVpL1jYe), and I'm getting some errors.
TemplateError('TypeError: %x format: an integer is required, not float') while processing template 'Template<template=({{ '%0x' % (int(0) * 255 / 100)}}) renders=4>' for attribute '_state' in entity 'light.inspire_light'
TemplateError('ValueError: Template error: int got invalid input 'unknown' when rendering template '{{states('input_number.temperature_input') | int}}' but no default was specified') while processing template 'Template<template=({{states('input_number.temperature_input') | int}}) renders=4>' for attribute '_temperature' in entity 'light.inspire_light'
TemplateError('ValueError: Template error: int got invalid input 'unknown' when rendering template '({{states('input_number.h_input') | int}}, {{states('input_number.s_input') | int}})' but no default was specified') while processing template 'Template<template=(({{states('input_number.h_input') | int}}, {{states('input_number.s_input') | int}})) renders=4>' for attribute '_hs_color' in entity 'light.inspire_light'||.
It is probably a very dumb error, as it's my first time trying this srry
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.
Trying to convert my download speed 202546408 to (202.55 Mbps)
divide by 1024 ?
a few things
this part doesn't make sense:
"{{ '%0x' % (int(0) * 255 / 100)}}"
what's the int(0) doing there?
That is supposedly to make it hexadecimal, I got this code from an example of someone on the internet
0 in hex is 0 decimal
I suggest not using code from whoever posted that
you're taking 0, multiplying it by 255/100, which is still 0, then converting it to hex
that's a ton of extra steps when you can just output 0
hex is interpreted as an integer by the resolver too. So it's alot of extra steps.
I suspect that that int(0) there was supposed to truncate some other value?
Maybe? (no idea tbh)
the danger with copying stuff
I think it will be better to remake that part
why don't you just explain what you are trying to do
based on what I see, you copied most of it because the other templates shouldn't fail unless you use the wrong enitty_id
so, you basically never updated any of the code it seems
to use your entities
I'm trying to pass that value into hex because the script that will use that needs to send a ble write in hex
If i add device_class to this , can i do a convert in gui ? on data_rate ?
sensor:
- name: "Download"
value_template: "{{ value_json.data.download | round(0) /1024 }}"
unit_of_measurement: "Mbps"
icon: mdi:download
Yes I'll have to admit that. As I said, it's my first time doing this and I feel quite lost
add unique_id
and device_class
can i just create a unique id ?
yep
ah thnks
that's why it's best to describe your whole goal, not just the pointed question about the templates
if you are trying to write hex to a service call, post the service call and how you want to use it and we can help
- name: "Download"
unique_id: downloadzorssss
value_template: "{{ value_json.data.download | round(0) }}"
device_class: data_rate
unit_of_measurement: "Mbps"
icon: mdi:download
- name: "Upload"
value_template: "{{ value_json.data.upload | round(0) }}"
unique_id: uploadzorssss
device_class: data_rate
unit_of_measurement: "Mbps"
icon: mdi:upload
this about right ?
hmm it can do decimal conversion, but no conversion of mb/s kb gb etc ...
yeah, as long as data_rate is valid
your unit of measurement needs to match with the device_class
not sure which what you're intending it to be with Mbps, I would assume MB/s
B would be byte
Bit is bit
very different
Latest download
202.87 Mbps
0.28% faster
but api outputs in
"download":202869048,"upload":186606752
is there an issue?
guess its bit/s ?
what did you expect it to be?
confused , was bit/s , mb and mib brrrrr
ty working
conversion now , pretty sensor ! 😛
that looks like bits
how do i clear historical data from these sensors ?
- name: "Download"
unique_id: downloadzorssss
value_template: "{{ value_json.data.download }}"
device_class: data_rate
unit_of_measurement: "bit/s"
icon: mdi:download
found it , purge service
does anyone have a drop in template for making a new sensor which mirrors another temperature sensor with an offset?
EG I have temp sensor 1 at 20 degrees,
I want to have temp sensor 2 which is 20 degrees minus 5.5 degrees.
Create a template sensor helper with state {{ states('sensor.1') | float - 5.5 }}
Thank you for the response, I ended up changing the value in esphome as it was an esphome temp sensor, did not know you could do that until today
hello,
is this correct please ?
{{ states('binary_sensor.rain_sensor_switch1') == 'on' and states('sensor.gw1100a_v2_2_1_rain_rate') | float(0) >= 7 }}
it gave me the following error on reboot
https://dpaste.org/Et2yL
I was wondering if there is a way I can prevent it ?
The version you posted here will prevent that error
it didn't - it still gave error
This is the version which caused the error {{ states('binary_sensor.rain_sensor_switch1') == 'on' and states('sensor.gw1100a_v2_2_1_rain_rate') | float >= 7 }}
It doesn't have the default for the float filter
Hi! Is it possible to use a state as an attribute like: {{state_attribute('sensor.mySensor','sensor.mySensor.state')}} or: How to quote a Doublebracket inside a Doublebracket? Thanks!
Yes, but it is best practice to use the states() function, also when it's an object or function don't use quotes because that renders it as a string
{{state_attribute('sensor.mySensor',states('sensor.mySensor'))}}
You are missing a closing parenthesis
G'day All! I'm losing the plot here on something simple that I've done a thousand times with strings but never with datetime stuff. I'm trying to combine a date field with a time field to get a datetime that I can compare. I'm buggered if I can concat them properly to convert. For example, I have: {% set last_detected_timestamp = states('sensor.birdnet_last_detected_date') ~ states('sensor.birdnet_last_detected_time') %} I know I haven't done the as_datetime yet but it makes one long string without the space and therefore will not convert. I know it's something basic but I've been looking at it for too long. Could someone steer me in the right direction please?
Tried that in the Dev Tools and get an error. unexpected '}', expected ')' . Guess this is what TheFes means.
Yep edited the post
Works! Thanks also @marble jackal
Add the space as well? states() ~ ' ' ~ states()
Or do something like:
[ 'sensor.foo', 'sensor.bar'] | map('states') | join(' ')
Thank you. I'll give that a go. I think as_datetime must be very fussy about how you feed it! 🙂
That seems to work. I thought that as_datetime might be able to take two sep. inputs to combine but I see I need to feed it the concatenated string including the space. Ahh well. Thanks for confirming. I did it the second way with the join as it appeals to me more. 🙂 Thanks @marble jackal
Hi! I have a device that writes this to me from mqtt explorer but I can't control it. Can anyone help me?
connect = true
stat = LED1_R:OFF;LED1_G:OFF;LED1_B:128;RELAY1:0N;SW1_AC:PULL;SW1_DC:PULL;=>0
I should create a switch
You'll have to provide more information that that @dusk gate
that's not enough info for anyone to help you create a switch, on top of that, you will need to know the commands that turn the switch on and off.
you'll also need to tell us what information in the topics mean that the switch on or off.
I have this 4box brand device. it is a switch with 2 relays. I managed to connect it via mqtt to my server and from mqtt explorer I can see the status changes.
I created a switch on home assistant that changes state when the relay changes state. my problem is that I don't know the commands to send for relay toggle. the manufacturer doesn't provide them to me and I wanted to know if there is a way to find them myself
If you tell me what information you need I can provide it
I already told you what information we need
we need to know what topics to use to turn the switch on and off
we need to know the comand that is required for the device that does the turning on/off
we need to know what value in the inforamation you provided, represents the state of the switch being on or off
we need to know the topic that this information is stored
M053B-90380C349464
stat = LED1_R:OFF;LED1_G:OFF;LED1_B:ON;LED2_R:OFF;LED2_G:OFF;LED2_B:OFF;RELAY1:OFF;RELAY2:OFF;SW1_AC:PULL;SW2_AC:PULL;SW1_DC:PULL;SW2_DC:PULL;=>-1.00=>0=>0=>MOTOR_STOP
led
2
r = off
1
r = off
relay
2 = off
1 = off
sw
2
dc = pull
1
dc = pull
this is what I get on mqtt explorer. I apologize in advance but I'm not an expert in this
That's still only the status and that doesn't tell us how to use it
which is what you need to figure out
there will be a manual with your device that describes the things I'm asking for
nope. unfortunately Italians are jealous of their jobs and want to have control 😅 so they don't provide this information. in fact, even when I asked, they didn't provide me with anything, which is why I was asking you if you knew a way to find them independently
then there's nothing you can do if you don't know how to reverse engineer it
without knowing what command to send to the device to turn it on, you won't be able to do that
I can tell you that I managed to enter the http page by finding the user and password (they don't provide it) and from there there are the http commands to control the device.
same for off
if there are http commands you can attempt to use rest commands with the device to turn it on or off.
which means you'd need to make mqtt binary sensors for each relay, 2 rest commands per relay, then combine them with template switches
http://192.168.1.74/cmnd?action=ON2 If I use this I can turn it on. the problem is that it asks me for username and password. Can this information be included in the link?
that can be included in the rest command
Can you give me an example of how to do it?
ok perfect I can control it ❤️
to combine mqtt and REST I can't create a switch but can I only use it with automations? correct?
@dusk gate I converted your message into a file since it's above 15 lines :+1:
this is my configuration and now the "test" switch works correctly and follows the status of the relay even if an error pop-up appears below: an error occurred while requesting the resource.
Does anyone know how to do better than this? advice?
don't make a switch for the MQTT entity. Make a binary_sensor
are you getting an error with the rest command?
or with the MQTT switch?
or with the test switch?
yes, when I change status from the switch test dashboard, the popup appears at the bottom left
but it still works
ok I'll do it later I'm not on the PC anymore. thank you very much for now
Hi best Community again : Now I'm struggeling about another Problem and don't know, where to start. The Topic is: Combining If-Clauses. So I have 2 Sensors A = [x,y,z] & B = [1,2,3] (just for Example!) … When A is something do something if B is something … does have anyone an examplecode to orientate in that … cannot put it together within the Dev-Tools by myself. Cheers - M.
Do nested if's:
if condition 1: if condition 2: ...both are true else ... 1 is true, 2 is false else if condition 2: ... 1 is false, 2 is true else ... 1 is false, 2 is false
At least conceptually. Doing it in templates, I'd have to think about it some more.
Quick Q, can I set the state of an entity in a template? I have a Zigbee light that is connected to a power strip that is sometimes switched off. If that happens when the light was on, the state of the light remains on, and I cannot switch the light off because it cannot be reached. I would like to change the state representation like you can do in Dev Tools, but in an automation. Is that possible and how?
no you can't change the state of some other entity
Too bad. I hoped that would be possible since you can do it in the UI
You can create a template light, and you can have the logic for the off state be affected by whether or not the Zigbee light is available
that's more of a hack for testing, you wouldn't want to do that even if you could. it gets reset the next time the device updates.
What exactly does 'it gets reset the next time the device updates' mean? Would it update even if it is unavailable? Because I am fine with the device updating once it has power again. I can determine whether or not it has power through the state of another entity. The only logic I want to have is: 'if power to device is off, consider device off' . In all other cases the state of the device is whatever it tells you it is.
well, it doesn't matter because you can't do it anyway.
you can make a template as suggested
I'll give that a try, thanks @lofty mason and @lucid thicket for the suggestions and clarifications.
I feel like this one is more difficult than it should be, but I'm also very fresh to using Templates. Maybe someone can get me started in the right direction?
My goal: count how many applications in TrueNAS have a pending update.
Data available: Using the TrueNAS integration, a device was created that has multiple sensor entities, each representing an installed application. The main state information is simply if the application is on or off. Each application has additional attributes, including "Update Available" (value of 1 or 0).
As I expect the applications to change relatively frequently and I'd like to not manually redefine this over and over, I'd love to: produce a list of all sensors/entities belonging to this device. Test each entity for the "Update Available" attribute. Count how many entities has "Update Available" equal 1.
Alternatively, an equally as useful item would just be a complex filter for a UI card. Filter to display entities belonging to that device. Filter again to display entities with that attribute state equal to 1.
filter for a UI card
might be possible with https://github.com/thomasloven/lovelace-auto-entities
Thank you. This looks like a good lead for the card approach. I'll investigate this further!
I checked and the problem was an automation that I had created during testing that gave me that problem. thanks so much for the support
https://www.home-assistant.io/integrations/history_stats/ is this a legacy sensor or template sensor thingie?
it must be, with the platform
That’s a different integration.
So “neither”
but it needs to be set up under sensor
Yep, becaues it's a platform
unless somebody moves it to a history_stats integration (and adds a config flow)
Pff, I had to correct at least 3 typo's there.. might indicate I need a coffee
are you on mobile or keyboard?
on keyboard
ah yes, then you need a coffee
I've noticed that autocorrect on IOS has become shit
it has started auto completing words as I type and completing the words while keeping both the incorrect word and correct word
Hi! I tried to get the Humidity for my Aqara Temperature / Humidity Sensor via Template. This command just returns "null", i don't know what to do
{{ state_attr('sensor.aqara_umweltsensor_wohnzimmer_luftfeuchtigkeit', 'humidity') }}
now i tried {{ states('sensor.aqara_umweltsensor_wohnzimmer_luftfeuchtigkeit') }} and it works ... im new in home assistant 😄
so it was just the state, then
I don't know what most of those words mean 🙂
anyway,
-> States in the future
it kind of means "sensor.aqara_environmentsensor_livingroom_humidity" 😄
then yes, it was just the state
just curious, what made you think you had to get humidity from the entity when the name has humidity in it?
random copy/paste
just trying to build a helper for an alert...so the idea was to check if the humidity is above 60% ...but i guess my approach to get the humidity from the entity was wrong
it's important to understand the difference between states and attributes to be successful in HA
yeah i think i have to do a little research 😄
you shouldn't need templates for this btw
seems you've googled yourself into a weird area
a simple automation using a numerical trigger would alert you. All done via the UI, no templates.
yes thats what i did in the first place. but then i wanted to implement an alert that sends notifications while the humidity is above 60% and only stops when it falls below 60% again
that would be a time pattern trigger every x minutes that checks a condition if the numerical value is above 60%
okay yeah maybe there is a more easy way to do this...as you already mentioned I did a lot of google research in the last hours 😄
The Wisdom of Google is sometimes overrated
well, also if you input 💩 to google, you get 💩 out
might be best to hit up the HA glossary before going google happy
If I have a list of dictionaries, is there a good way to get the index of one of the dicts based on either a unique key or k-v pair existing in the dict?
NVM
typically, you want to avoid using indexes if you can
Hi. Im looking to convert the number of seconds (media_duration attribute of kodi media_player entity) to an HH:mm:ss format in a template. Is there a better way of calculating that than the one described here: https://community.home-assistant.io/t/convert-seconds-to-days-hours-minutes/23152/17 which seems to be very long and complex?
It looks like I was able to get this working!
filter:
include:
- device: TrueNAS Apps
- attributes:
Update available: '1'
exclude: []
card:
type: entities
title: TrueNAS App Updates Available
state_color: true
sort:
method: state
reverse: true```
Gave me a list of apps that have an update available.
Oh, actually...it's not updating. Attributes have changed, but the filtering isn't.
@sudden bison I converted your message into a file since it's above 15 lines :+1:
That message has a question about proper syntax... My attribute name has a space in it. The auto entities card strips out any quotations I put around it. If I use a different attribute without a space, the test works and I get expected results. I can use the dev tools for state testing and get expected values from the attribute with a space in it, but it lets me use quotes.
I guess...what's the correct way to escape out a space in this context?
idk, but you can try backslash
https://github.com/thomasloven/lovelace-auto-entities/issues/154
It's a known issue that will not be fixed.
@gentle belfry I converted your message into a file since it's above 15 lines :+1:
Ok, I'm so sorry to noob you all with this. My google foo is poor (spent days on this already) I am really hoping you all will take mercy upon me and forgive me my noobness.
I have popped this webhook triggered sensor into my templates.yaml file (which I'm calling via the include in my config.yaml file). And I am not getting the expected outcomes.
First problem is the binary sensor showing the valve state seems to be inverted with it's icon display. When the state value is "on" it is showing that correctly but is instead displaying the "closed" icon, and when it is "off" it is showing the "open" icon. I can't for the life of me work out why.
Second problem is that it seems my level sensor is not correctly evaluating the value and displaying the appropriate icon. So I'm pretty sure I am totally misunderstanding how that is supposed to work.
Your help would be much appreciated. 🙂
@gentle belfry I converted your message into a file since it's above 15 lines :+1:
I've flipped the icons around in that binary sensor so that it displays correctly, as you can see, but if I put them back the right way (so the open is shown when the state is on) then it actually displays them wrong.
For your level sensor, you have parenthesis in the wrong spot
Should be like this:
{% if states("sensor.tank_level") | float < 1 %}
Whenever using a trigger-based template sensor you should recalculate values for attributes and icons instead of using this because this will be the previous state, not the current state.
Ah, good point, thank you. I’ll remove that reply
I can’t see anything wrong with the icon template on the binary_sensor then.
So to confirm: the this object will be frozen as the state object of the entity at the time of the trigger, prior to rendering any state or attribute templates?
But for state based template sensors, the this object is updated after the state and after each attribute. Probably because the template sensor is being re-triggered upon each of those updates and therefore this gets updated each time?
Thank you. Looks like I need to make some tests on my system to ensure I know exactly what it is doing
When I change is_state to this.is_state I get this error when I hit the webhook.
Error rendering icon template for binary_sensor.tank_valve: UndefinedError: 'homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'is_state'
this.is_state isn't a thing
so digi is referring to some other this?
icon: >
{% if this.is_state("binary_sensor.tank_valve", "on") %}
mdi:valve-open
{% elif this.is_state("binary_sensor.tank_valve", "off") %}
mdi:valve-closed
{% else %}
mdi:valve
{% endif %}
No
not like that?
No
my noobness is showing i bet. 😉
without knowing what you're doing
You've misunderstood, you should use trigger.json.open not this
but the value is setting correctly
it is just the icon is not
oh, evaluate the trigger value
not the state object
that's what you are saying?
icon: >
{% if ("this.trigger.json.open", "on") %}
mdi:valve-open
{% elif ("this.trigger.json.open", "off") %}
mdi:valve-closed
{% else %}
mdi:valve
{% endif %}
like that?
wait, without the is_state
the first argument of is_state is an entity_id
no
I'm going to take a stab at whatever it is you're doing
icon: >
{% if trigger.json.open == "on" %}
mdi:valve-open
{% elif trigger.json.open == "off" %}
mdi:valve-closed
{% else %}
mdi:valve
{% endif %}
Rob you've got hanging )
Yep
so i'm passing boolean true or false in that json payload
should i use that, or use the "on" and "off" in the conditional eval?
you should use whatever you're sending
roger that
reloading now
🙂
working perfectly!!!
so that was a race condition on my eval right? because the state object was not updated yet
Since you're passing a bool and the output are static strings you could also use immediate if:
icon: >
{{iif(trigger.json.open,"mdi:valve-open","mdi:valve-closed","mdi:valve")}}
so evaluating my trigger input is the safest way to do it
legend!!!
let me take a shot at fixing the level sensor below. 🙂
brb
Do i need to cast the json value to a float when i am setting the state, or will it do that for me?
{"open": true, "level": 0.0}
that's my input
You shouldn't need to cast to float based on your input, but it won't hurt to do so
I hope that second comma is really a colon
nope, did not need to cast it.
yeah, sorry, is colon
😛
works perfectly!!!!
icon: >
{% if trigger.json.level < 1 %}
mdi:gauge-full
{% elif trigger.json.level < 2 %}
mdi:gauge
{% elif trigger.json.level < 3 %}
mdi:gauge-low
{% elif trigger.json.level < 4 %}
mdi:gauge-empty
{% else %}
mdi:alert-circle
{% endif %}
should have occured to me that evaluating the state object may have been a race condition
should have been evaulating my input, as i knew that was current
lol
this is why i got a B- average for my CS bachelors. 😉
thanks guys, you are legends!!! so sorry for my noobness. 🙂
no worries
forget it. I found this error in the registry
Logger: homeassistant.components.websocket_api.http.connection
Source: components/websocket_api/commands.py:240
Integration: Home Assistant WebSocket API (documentation, issues)
First occurred: 22 febbraio 2024 alle ore 22:07:02 (22 occurrences)
Last logged: 22 febbraio 2024 alle ore 22:25:18
[547634908736] Client error occurred when calling resource 'http://192.168.1.194/cmnd?action=OFF2'
[547967039552] Client error occurred when calling resource 'http://192.168.1.74/cmnd?action=ON2'
[547967039552] Client error occurred when calling resource 'http://192.168.1.74/cmnd?action=OFF2'
[547967039552] Client error occurred when calling resource 'http://192.168.1.194/cmnd?action=ON2'
[547967039552] Client error occurred when calling resource 'http://192.168.1.194/cmnd?action=OFF2'
Traceback (most recent call last):
File "/usr/local/lib/python3.12/site-packages/aiohttp/client_reqrep.py", line 966, in start
message, payload = await protocol.read() # type: ignore[union-attr]
^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.12/site-packages/aiohttp/streams.py", line 622, in read
await self._waiter
File "/usr/local/lib/python3.12/site-packages/aiohttp/client_proto.py", line 224, in data_received
messages, upgraded, tail = self._parser.feed_data(data)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "aiohttp/_http_parser.pyx", line 557, in aiohttp._http_parser.HttpParser.feed_data
aiohttp.http_exceptions.BadHttpMessage: 400, message:
Data after Connection: close:
b'<ON2>HTTP/1.1 200 OK'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/usr/src/homeassistant/homeassistant/components/rest_command/init.py", line 143, in async_service_handler
async with getattr(websession, method)(
File "/usr/local/lib/python3.12/site-packages/aiohttp/client.py", line 1194, in aenter
self._resp = await self._coro
^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.12/site-packages/aiohttp/client.py", line 605, in _request
await resp.start(conn)
File "/usr/local/lib/python3.12/site-packages/aiohttp/client_reqrep.py", line 968, in start
raise ClientResponseError(
aiohttp.client_exceptions.ClientResponseError: 400, message="Data after Connection: close:\n\n b'<ON2>HTTP/1.1 200 OK'\n ^", url=URL('http://192.168.1.194/cmnd?action=ON2')
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/usr/src/homeassistant/homeassistant/components/websocket_api/commands.py", line 240, in handle_call_service
response = await hass.services.async_call(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/src/homeassistant/homeassistant/core.py", line 2279, in async_call
response_data = await coro
^^^^^^^^^^
File "/usr/src/homeassistant/homeassistant/core.py", line 2316, in _execute_service
return await target(service_call)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/src/homeassistant/homeassistant/helpers/service.py", line 892, in entity_service_call
single_response = await _handle_entity_call(
^^^^^^^^^^^^^^^^^^^^^^^^^^
@dusk gate I converted your message into a file since it's above 15 lines :+1:
include:
- template: "{{ states | map(attribute='entity_id') | select('is_state_attr', 'Update available', 1) | list }}"
@sudden bison
you can filter that down to truenas if you know the integration name for truenas
The integration name or the device name?
I ask because it has multiple devices.
devices don't matter
if you have an entity that you know is created by truenas, post the result of this template from the template editor
{{ device_attr('yourentityhere', 'identifiers') }}
make sure you put your entity in the yourentityhere
I think in this case, it might actually, but I may wrong. In this integration, each "device" has a wildly different set of entities. They're all representing different aspects of a server appliance. There actually probably wouldn't be a conflict in this instance, as that's likely not the same attribute in the other "devices," but if there was, it would be information I actually don't want showing in the card.
you are wrong, devices don't matter HA works off entities
please post the information I asked for
or if you know the device_id for the Truenas Apps device, that works too
either way, need that info
one of the 2
Yeah, I wasn't getting expected values out of that in the States editor. I'm just getting an empty set:
[]
Sorry, was originally on a phone and that was way too burdonsome for this task. Just repeated on my computer. Pasting this:
{{ device_attr('binary_sensor.ha', 'identifiers') }}
still yielded
[]
That's one of the sensor entities associated with TrueNAS Apps
not according to the template
it should have identifiers
can you post a screenshot of binary_sensor.ha in developer tools -> states page?
I guess it's possible it doesn't have identifiers
is this a custom integration?
how about this instead {{ device_id('binary_sensor.ha') }}
It won't let me share an image in here. Here's the text output anyway.
Name: ha
Human version: 2024.2.1_23.2.0
Update available: 1
Container images update available: 0
Portal: https://ha.wirefox.me:443/
icon: mdi:server
friendly_name: ha````
It is. Let me run that other template you've sent.
12dae07592ad7d75cc4f9993f7170fb9
Well it seems that the truenas dev is not doing anything by the books
which is the root cause of your problems
I'll raise some issues in the repository.
include:
- template: "{{ device_entities('12dae07592ad7d75cc4f9993f7170fb9') | select('is_state_attr', 'Update available', 1) | list }}"
that template will filter down to what you want
no other filters needed.
you can verify that in the template editor
Yep, the template editor looks like it gave me an accurate list. Shows a good list of everything it checked, and then the actual filtered result string.
Only small adjustment I had to make for it work in the card was to raise "template" up a level.
template: "{{ device_entities('12dae07592ad7d75cc4f9993f7170fb9') | select('is_state_attr', 'Update available', 1) | list }}"
include: []
exclude: []```
Really appreciate your help here, Petro. It's a nice frontend card that my learning experience got marred with by what seemed to be a non-compliant custom integration. That template you wrote makes good sense to me, and since I know what it was trying to do beforehand, that's a good basis to help me understanding the syntax in templating a little bit better. The filter character was...not clear to me in how it was working. It's still not 100%, but I'm going to keep looking into it further and play around a bit until it makes more sense to me. I want to actually learn this instead of just use it, after all.
Yeah, that's what I meant earlier when I said that templates act like a logical "OR" operation to everything else in the include section.
It all comes out OK in the end here though.
well you don't need include or exclude when using a template
because it can do it all
As I see now!
you can even have the template output dictionaries that represent your cards and all the information that's placed in the cards
instead of it outputting a list of entities
card_param makes the output of filter and places the values as cards instead of entity_id's
which builds this for me
non entities, but calendar events
when I say you can do anything with auto-entities, i truely mean it. There are very few limitations.
I see, yeah, I can definitely see it being a powerhouse.
@clear python I converted your message into a file since it's above 15 lines :+1:
sensor:
- platform: template
sensors:
home_energy_usage:
friendly_name: "Home Energy Usage"
unit_of_measurement: 'lx'='
device_class: 'illuminance'
value_template: "{{ states('sensor.myenergi_my_home_power_generation') }}"
this throws a fit of a error and again dont understand any of it if its even close
'Sensor None has device class 'illuminance', state class 'measurement' unit 'lx' and suggested precision 'None' thus indicating it has a numeric value; however, it has the non-numeric value: 'sensor: - platform: template sensors: home_energy_usage: friendly_name: "Home Energy Usage" unit_of_measurement: 'lx'=' device_class: 'illuminance' value_template: "804"' (<class 'str'>)
'
That unit of measurement doesn't make sense
Probably should just be lx, but you have three quotes and an =
Further:
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.
changed that still get this at bottom
Sensor None has device class 'illuminance', state class 'measurement' unit 'lx' and suggested precision 'None' thus indicating it has a numeric value; however, it has the non-numeric value: 'platform: template sensors: home_energy_usage: friendly_name: "Home Energy Usage" unit_of_measurement: lx device_class: 'illuminance' value_template: "583"' (<class 'str'>)
sorry im genuinley lost with this stuff i just want a simple
this entity -sensor.myenergi_my_home_power_generation
which is displaying in watts
into a 'fake' Luxs sensor so i can expose it to homekit
Please use formatting
sensors:
home_energy_usage:
friendly_name: "Home Energy Usage"
unit_of_measurement: lx
device_class: 'illuminance'
value_template: "{{ states('sensor.myenergi_my_home_power_generation') }}"
apologies didnt even know that was a thing
you missed the last sentence of that bot message 😉
god damn it
Seems like there's an extra quote in the state of that entity making it not look like a number?
Yep as you can probably imagine
that went clean over my head
i can see in the error its changing with the sensor live so i assume this is close
Funny enough, I was spending some time creeping through the integration code to try and understand what they were doing/why it went wrong.
They clearly had the intent for the attribute names to not have spaces. In the code defining the attributes, I'm seeing "human_version", "update_available", and "container_images_update_available" all listed as attribute name strings for this entity type. It's pretty consistent throughout all the code.
I did find a helper function that looks like it intends to just give a human-readable version of various attributes. Lots of calls for
res = res.replace("some-data-that-exists", "a-more-readable-version-of-some-data")
But the first call looks problematic.
res = attr.replace("_", " ")
If I'm not mistaken, that function just replaced the value of attr, then defined res as that value. Instead, it should have defined res as attr (no modifier), and in a separate line, redefine res as a modified version of itself.
Dang it, that formatting stripped out my underscores.
Regardless, my assumptions seem to be wrong. The method seems to be a fine way that doesn't modify attr.
I am 100% in over my head, but it's a fascinating learning experience.
Is there a function which would replace national accents with latin letters in a string in jinja2?
I think it’s called normalization in Python
I don't believe so, but you can use the replace function with a series of characters you want replacing
You can also create a macro which lets you re-use a function: https://www.home-assistant.io/docs/configuration/templating/#reusing-templates
Would slugify do that?
I mean I could just do a replace on polish characters but I would rather do something universal and share with community
That will change it to lowercase and replace spaces with _ I think
And probably also do what you want, but more that you don't
That’s should be ok because I’m trying to prep a string for display on Awtrix, which uses a font without accents but also without lowercase/uppercase 😉
it will remove all odd characters tho
What's the best way to get this condition to pass if the automation has never triggered? condition: condition: template value_template: "{{ now() - state_attr('automation.workshop_camera_motion', 'last_triggered') > timedelta(minutes=1) }}
What I came up with: {{ now() - state_attr(this.entity_id, 'last_triggered') > timedelta(minutes=1) if state_attr(this.entity_id, 'last_triggered') is not none else true }}
I think you could just do:
{{ state_attr(this.entity_id, 'last_triggered') is none or now() - state_attr(this.entity_id, 'last_triggered') > timedelta(minutes=1) }}
just a shorter version of what you have
whenever you return "true" or "false", there's usually a better way
I usually use:
{{ now() - this.attributes.last_triggered|default(as_datetime(0),1) > timedelta(minutes=1) }}
This is why I asked. Thanks.
https://pastebin.com/nQML0t5a is it possible to do something like this ? its the color_threshold value i want to have dynamicly set to the value of my input_number
solved it with config-template-card
Hi guys, I need a bit of help with templates, please. I'm trying to filter entities that are of device_class:battery and then from them ones that have value below 20%. Apparently it would seem that state is not an integer so my function does not work correctly. Does anyone know how to correct it? Thanks! {{ states.sensor|selectattr('attributes.device_class','eq','battery')|selectattr('state','le','20')|list }}
The second selectattr is problematic, if I use " equal to 100" then it works properly. So either state is not an int or le function does not compute?
You ahve to use namespace and convert the state to a float or integer
I was actually trying to convert it from namespace into this to "simplify" 😄 So it doesn't work this way. Thanks!
Hey there. I have a quick question. I wanted to create a dummy lock... I am able to create one, but I had to create a dummy switch with it to get it to work for value_template. Is there a way to do this without a dummy switch? Just have the dummy lock with lock/unlock services?
I tried omiting value_template, but it didn't like that. Then I tried pointing value_template to itself:
value_template: "{{ is_state('lock.dummy_lock', 'unlocked') }}"
and that made the lock stuck in unlocked mode... I couldn't click lock... It did nothing.
In a template is it possible to serialize json?
Use the filter to_json
Thank you, but I misspoke. Do you know how to convert JSON into a string.
There is a string filter also
I haven’t tried this, but try optimistic: true and use value_template: "{{ 'on' }}"
If my guess is correct, the lock will start in the locked state after every restart and will then change between locked/unlocked when it is activated. If you do need it to retain state across reboots, I think you’ll have to use another entity to store that state (like your toggle helper)
@lucid thicket Perfect. Thank you! I will give this a shot later today!
Hey everyone,
I'm looking for an easy way to monitor all battery levels for my zigbee devices.
I'd like HA to send me a notification every time I come home and a device is below 10%. (And which one)
Is there a template for that?
Alternatively I could make an automation but I would have to put every device entity as a condition and whenever I get notified I would have to check manually which device triggered it.
Or is there an easier way to monitor zigbee battery levels?
Hi, I need help with actionable notifications. Is possible to show actions only is relevant? I mean action iron_plug, only if is iron on?
service: notify.mobile_app_jiri_ipx data: title: Upozornění! message: "{{message}}" data: actions: - action: HOME_TURN_OFF title: Vypnout vše - action: IRON_PLUG_TURN_OFF title: Vypnout žehličku - action: LIGHTS_TURN_OFF title: Zhasnout - action: MEDIA_TURN_OFF title: Vypnout média - action: FANS_TURN_OFF title: Vypnout větráky
You can, but you need to template the whole action section
What do you mean?
Heya, pls apologize for another n00b question: Is there a more elegant way to define the months in here?
Aim is to display annual tasks from a dedicated 'per year' calendar - its working in HA already, but feeling like writing self-repeating poems.
Reference pic from my 'old' system see [here](#frontend-archived message).
Thanks Rob, appreciate the instant answer, on first glance it exactly sounds what I am looking for. 🙂
there has to be an easier way to select a sensor with the most recent datetime
@lethal bison I converted your message into a file since it's above 15 lines :+1:
3rd pinned message in this channel: You need to use a namespace if you want to access variables set inside a for loop
You were almost there, instead of:
{% set next_alarm = {'entity': 'unset', 'time': comparison_time.timestamp()} %}
You need to use
{% set next_alarm = namespace(entity='unset', time=comparison_time.timestamp()) %}
I would suggest to do it more like this
https://dpaste.org/TbrAC
The syntax of the templates to me is quite complex.
Is there a plan to get rid of it with something more user friendly such as js or python?
I don't think so, that would be a major breaking change. And I think it quite fits the purpose
I don’t like the multi line part where each line you have to do the parenthesis
Or would it be an idea to implement auto completion in the editor for things like this?
@digital harness I converted your message into a file since it's above 15 lines :+1:
availability: requires a template
https://www.home-assistant.io/integrations/template/#availability
hello
I have a template light. It has turn_on, turn_off, set_level and set_temperature
each one of those calls a service: light.turn_on(off) command
when I have an automation that turns on the light I get the error 2024-02-25 07:55:38.149 WARNING (MainThread) [homeassistant.helpers.script.upstairs_led_template] Upstairs LED Template: Already running
I think that the way the automation calls the light.turn_on for the template light, which includes brightness and color temperature, calls the set_level and set_temperature commands of the template light in rapid succession, such that the template light is completing the set_temperature command when the set_level command is called
@coral garden I converted your message into a file since it's above 15 lines :+1:
How can I avoid this problem because my template light isn't executing the brightness command
i forgot a ?
Thank you!!!
Template variable warning: 'brightness' is undefined when rendering '{% if brightness is defined %}
?
how to I check if a variable is defined?
It's probably from somewhere else
so template light calls set_temperature if the light.turn_on call has color_temp:
I am not formatting this correctly.
the only way to set brightness if the light.turn_on call has color_temp is to include {{ brightness }} in the set_temperature section of the template light
but, if I call light.turn_on with only color_temp, the call fails because there is no {{ brightness }} and I don't know how to check for {{ brightness }} if {% if brightness is defined %} throws an error
What error?
I think the template light integration, should check if there is {{ brightness }} in a light.turn_on call that has color_temp and handle it gracefully
Template variable warning: 'brightness' is undefined when rendering '{% if brightness is defined %}
I chuckled at it
You'd have to make separate service calls if you want to include or exclude keys unless you make it even more complicated
you mean do a light.turn_on with just color temp and then one that sets the brightness?
I'm already too deep
maybe this is an template light integration issue. I think it would be helpful if the template light could handle a light.turn_on call with only color_temp
Yes
yes, it works in the template editor but not in the template light
You can template the entire data section if you want
@coral garden I converted your message into a file since it's above 15 lines :+1:
@marble jackal I'm awake now!
I'm testing the code you pasted, it appears the time is determined and set to next_alarm.time correctly, but the entity_id is not copied to the next_alarm variable. Odd because if I change the line
{% set next_alarm.time = alarm_dt %}
to
{% set next_alarm.time = alarm_dt %}
{{alarm_dt}} {{alarm.entity_id}} {{next_alarm.entity}}
alarm.entity_id is correctly shown, but next_alarm.entity is still 'None'
For anyone interested, I've made a group for each person in my household, with all of the sensors exposed for their phones by the companion app. The intended purpose is to trigger adaptive lighting for their bedroom, say 30 mins before their alarm goes off, the lights in their room will slowly increase brightness and color temp
Trigger warning - I havent done any reasearch yet -
What's the datetime format that would be easiest to interact with natively in HA? I have access to the alarm timestamp, but the datetime reported by the _next_alarm sensor appears to use ISO format
how do I ignore the state change if attributes.last_called_summary is ","
Summary: >
{{ expand('media_player.alexa_sonos_beam', 'media_player.alexa_echo_show', 'media_player.alexa_echo_spot', 'media_player.alexa_echo_dot')
| selectattr('attributes.last_called_timestamp', 'is_number')
| sort(attribute='attributes.last_called_timestamp', reverse=true)
| map(attribute='attributes.last_called_summary') | first }}```
use a reject filter:
| reject('equalto', ',', attribute='attributes.last_called_summary')
when I do that : {{ expand('media_player.alexa_sonos_beam', 'media_player.alexa_echo_show', 'media_player.alexa_echo_spot', 'media_player.alexa_echo_dot') | selectattr('attributes.last_called_timestamp', 'is_number') | sort(attribute='attributes.last_called_timestamp', reverse=true) | map(attribute='attributes.last_called_summary') | first | reject('equalto',',', attribute='attributes.last_called_summary') }}
it says "<generator object select_or_reject at 0x7f886ef120e0>"
if I move the rject after the expand I get: "TypeError: _operator.eq() takes no keyword arguments"
Why is this not working?
{{ is_state('input_boolean.laddbox_schema', 'On') ? 'green' : 'red' }}
I got
TemplateSyntaxError: unexpected char '?' at 50
How should I write?
{{ 'green' if is_state('input_boolean.laddbox_schema', 'on') else 'red' }}
Also note the state will be on, not `On'
Thanks , seems to work fine 🙂
Alternative
{{ is_state('input_boolean.laddbox_schema', 'on') | iif('green', 'red') }}
Which is more in line with what you had
what would be the difference of states("sensor.nordpool_kwh_se3_sek_3_10_025", "current_price") vs state_attr("sensor.nordpool_kwh_se3_sek_3_10_025", "current_price") ? 🙂 the documentation i find isnt so complete imho 🙂
There is a thread about it here:
https://community.home-assistant.io/t/what-is-the-difference-between-states-and-state-attr/407627
That's a different thing
But related though
states() is used to return the current state of the entity
state_attr() is used to return the value of one of the attributes of an entity
yes, but seems states() with entity name and then the attribute does the same thing? 🙂
No, it doesn't
That's just for that particular example, as the attribute value is the same as the state
hmm ok 🙂 so i might just have gotten luycky with that nordpool entity then 🙂 updated the templates to use state_attr insted 🙂
the 2nd parameter for states() indicates if you want to use the full state value as stored in the database, or if you want to use the precision set in the entity settings
so basically you were using:
states("sensor.nordpool_kwh_se3_sek_3_10_025", rounded="current_price")
oh, thats what i find missing in the documentation realy 🙂 the syntax of the actual function .. all i find is a bunch of examples of how to use it in the documentation but nothing that realy tells what the arguments are 🙂
I was just about to post the exact same thing
But, the templating docs are not the best, there are ideas to improve them
@marble jackal ah must have missed that then, would be nice with an ordenary documentation where you get the function name, click on it and get the arguments etc not baked into some text somewhere 🙂
Yeah, that's the current idea
It will probably be made more like https://spook.boo/flatten
yes!
list filter?
| selectattr('attributes.last_called_timestamp', 'is_number')
| sort(attribute='attributes.last_called_timestamp', reverse=true)
| reject('eq', ',')
| map(attribute='attributes.last_called_summary') | first
}}``` ?
After the map filter, otherwise you are still working with the full state objects
and before the first filter
you can also do it before map, but then you need to use | rejectattr('attributes.last_called_summary', 'eq', ',')
I'll give it a go 🙂 thanks!
Plugging my message #automations-archived message from #automations-archived to see if anyone has any advice. The gist is that I'm trying to conditionally include a key into a dict
for a service call?
specifically for the service calls data field?
A service call, for the image field within data
Basically want one of these, based on the condition of a template:
data:
image: "{{ snapshot }}"
# or
data:
video: "{{ snapshot }}"
ok, are you planning on sending other things?
ok
how do you plan on knowing which one?
From a template conditon. Can use a trigger id or the payload of the mqtt request
ok, what's the trigger ID?
If it's triggerid is new I want image otherwise I want video`
Just to clarify, I specifically want one service call. I'm trying to avoid using a choose action if possible
ok
so
data: >
{% if trigger.id == 'new' %}
{{ {'image': snapshot} }}
{% else %}
{{ {'video': snapshot} }}
{% endif %}
Oooh, then I conditionally return the dict itself? Does it have to formatted as json?
typos
sorry
you can conditionally return the dict or you can do some fancy add/removing of the key
but conditionally with the dict is eaiser if you just have 1 options
multiple options, you want to go the other route
Ok sweeeeeet, this makes sense, I will tinker around with that later.
I can test later, but do you know if I format it as yaml in the template?
data: |
{% if trigger.id == 'new' %}
image: {{ snapshot }}
{% else %}
video: {{ clip }}
{% endif %}
tag: {{ tag }}
url: {{ url }}
that will not work, it's not a dictionary
you have more keys there
Gotcha, so we're relying on jinja to convert the json to dict
I do have other keys I want included
Right haha I know, just trying to understand limitations of jinja
I do need the other keys. The main reeason I want to do this is because the two notifications share all the other keys except for choosing either image or video
data: >
{% set ns = namespace(items=[('tag', tag), ('url', url)]) %}
{% if trigger.id == 'new' %}
{% set ns.items = ns.items + [('image', snapshot)] %}
{% else %}
{% set ns.items = ns.items + [('video', clip)] %}
{% endif %}
{{ dict.from_keys(ns.items) }}
Looks straightforward enough, haven't heard of namespace but will look into it! TY
I'm not seeing any docs on the dict.from_keys() fn though, do you have link for docs?
there wont be any docs about it
it's a built in for python dictionaries
it's not even documented there
I didn't realize you had access to python builtins from jinja?
Is jinja literally just exec'ing python code in the expressions?
just know that it takes a list of tuples [('key', 'value), ('key', 'value')]
no, it's alittle more complciated than that, but it has restricted access to specific functions/methods/properies on some of the returned python objects
I think what I'll probably do is define the dict of shared values in a variables block, then conditionally add the image or video block in the template
pretty much any 'complex object' in jinja is going to be a python object with a few exceptions
one being namespace
ahh gotcha
jinja is limited to scope
meaning that you can't adjust a variable inside an if statement and expect it to change when outside the if statement
you have to use namespace to get that
variables:
json: "{{ trigger.payload_json.after }}"
type: "{{ json.type }}"
event_id: "{{ json.id }}"
label: "{{ json.label }}"
camera_id: "{{ 'camera.' ~ json.camera }}"
camera_name: "{{ state_attr(camera_id, 'friendly_name') }}"
base_url: https://redacted/api/events/{{ event_id }}
clip: "{{ base_url }}/clip.mp4"
snapshot: "{{ base_url }}/snapshot.jpg?crop=1"
shared_data:
tag: "{{ event_id }}"
So I couldn't use the shared_data here?
i.e.
{% if x == 4 %}
{% set y = 2 %}
{% endif %}
{{ y }} # ERROR
Cause shared_data should be available globally to all actions
shared data will be a dict, but you won't be able to alter it
Could I convert it to a namespace and add a key to it?
if you want to pass shared data as the dict, you have to do even more crap
no, namespace is not a dict
in regards to what you want to do...
this would also work...
namespace behaves as a dict though right?
Just in a limited scope?
eww i see something nasty i could do....
loop over items in shared_data then add them to namespace, then convert namespace to dict
data: >
{% set output = dict(url=url, **shared_data) %}
{% if trigger.id == 'new' %}
{{ dict(image=snapshot, **output) }}
{% else %}
{{ dict(video=clip, **output) }}
{% endif %}
ah that's much cleaner
** is python
right
for kwargs
yup yup, cool
doesn't work if your keys have spaces in the name
so ambiguous which python features are avail to jinja lol
which means you have to use the KVP method above
yup yup, makes sense
basically, we have to work around the restrictions that jinja imposes on dictionaries
i.e. you can't change a value in the dictionary and you can't add to a dictionary, and you can't use the update function on a dictionary
so you're stuck making new dictionaries in stupid ways
yeah, that's an ok limitation with me, still makes the template lib powerful as hell lol
yes it does
take a look at my automations
I abuse the shit out of this everywhere
well i appreciate you taking the time to explain all of that, this should make my shit wayyyyy more DRY
look in scripts & automations folders
have fun 👍
you already understand complex concepts more than most people (99.99999%), so you should be GTG
ye, im a software dev, it's been a fun side project. Just redid my whole homelab setup and am working on configuring my NVR
Seeing a lot of fun syntax in: https://github.com/Petro31/home-assistant-config/blob/master/automation/frigate_notifications.yaml
lol
Hah, I don't actually use that anymore
Hi. I am new user of Discord and HA. Where can I ask a question about creating helper and using it in automation? I have created temperature helper and I understand that states are always strings. Now I am trying to compare it with number but getting 'undefined' error. Sorry if this is not the right place to ask...
please share the code that you're using
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.
state template
{{ state_attr('weather.forecast_home', 'temperature')}}
I have created it via frontend - it shows graph with data, so far so good
In the automation:
- service: light.turn_on
entity_id: light.rgbcontroller
data_template:
rgb_color:
- "{% if sensor.tempoutside | int <= -35 %} 255 {% elif
sensor.tempoutside | int == -34 %} 240 {% elif sensor.tempoutside
| int == -33 %} 225 {% elif sensor.tempoutside | int ==
-32 %} 210 {% elif sensor.tempoutside | int == -31 %} ``` and so one - found this one online
sensor.tempoutside should be states('sensor.tempoutside')
you used state_attr() in the first one, so presumably you're aware of the templating docs?
if you found that online, I wouldn't vist there again for a correct answer
it's also missing a trailing "
Ok. This worked:
- "{% if states('sensor.tempoutside') | int <= -35 %} 255 {% elif
states('sensor.tempoutside') | int == -34 %} 240 {% elif states('sensor.tempoutside')
| int == -33 %} 225 {% elif states('sensor.tempoutside') | int == ```...
thank you!
Having the following triggers in a new template that is working well at startup / yaml reload:
- trigger:
- platform: homeassistant
event: start
- platform: event
event_type: event_template_reloaded
- platform: state
entity_id: calendar.jahreskalender
Expectation was that it is also triggering when the calendar is changing (local HA calendar, last entry). However, it doesnt fire when adding / changing / deleting entries in that calendar. Of course its all layer 8 fault - but what did I do wrong?
Can someone help me with a template for a change in numeric state. I need the condition to be previous state is greater than new state.
pretty straightforward
{{ trigger.from_state.state|float > trigger.to_state.state|float }}
Ty so much!!
Is it not possible to use jinja for template sensors with a yaml dictionary?
I keep getting
template value should be a string for dictionary value for the last 2 keys in webhook_ids
I tried this both with the states('input.text.xyz') inline with each value (frigate,zwave_js) and broken out the way I have it now with separate keys under image_names
you can only use a template in an attribute, so you can't use a yaml dict
use something like
image_names: >
{{
{
'frigate': states('input_text.frigate_image_name'),
'zwave_js': states('input_text.zwavejs_image_name')
}
}}
Ah ok that's what I was going to try next thank you.
i have these spikes going to zero(0), because well... my default is 0. How can i ignore zero values so my graph wont look all wonky?
sensors:
stroom_import_export_balans:
value_template: "{{ 1000 * (states('sensor.power_production') | float(0) - states('sensor.power_consumption') | float(0) ) }}"
unit_of_measurement: 'W'
friendly_name: "netto import of export"```
add an availability_template so the sensor will be unavailable when your source sensors are not providing numeric data
ive heared of that one before! ill look into it. thx!
Is it possible to create a template sensor that gets info from the event after the next event of my calendar? The calendar entity returns the directly next one. I need the one after as well for some specific reminder. The event exists in the calendar.
yes, using the service call in a trigger based template sensor.
https://www.home-assistant.io/integrations/calendar/#service-calendarget_events
I was reading just that
is get_events the same as list_events?
the link to docs points to the same plance, but both calls exist
list_events is old, avoid it
list_events is de old one, which is depreciated, get_events is the newer one, which allows multiple calendars as target
yeah, sorry for the double post
xD
seriously wasn't thinking on a service call to achieve it, and skipped the services part in the docs, mb
@wary yew I converted your message into a file since it's above 15 lines :+1:
This is the call response if it helps:
calendar.meals:
events:
- start: "2024-02-27T23:00:00+00:00"
end: "2024-02-27T23:30:00+00:00"
summary: Sopa y 3 burgers de pollito
description: >-
El caldo es el que ha sobrado al mediodía. Sacar burgers pollo a
descongelar.
- start: "2024-02-28T15:00:00+00:00"
end: "2024-02-28T15:30:00+00:00"
summary: Pechugas de pollo al horno con especias y patatas al horno
description: Sacar 2 pechugas de pollo a descongelar.
why does this work {{ state_attr('calendar.meals', 'message') }} but this {{ message | state_attr('calendar.meals', 'message') }} returns an error Error rendering data template: TypeError: state_attr() takes 3 positional arguments but 4 were given ?? I don't get what it has to do with state_attr
just looking to use the variable message if it exists, and the state_attr if not. That's what the ternary operator does, right?
what is your goal with the second one?
it's not valid
are you trying to set an attribute?
I'm saying that this is nonsense: {{ message | state_attr('calendar.meals', 'message') }}
I want it to use the variable "message" from earlier if it was passed on, and it it doesn't, for it to use the value of the sensor
I get it, I just don't get whyx D
prob it's my bad understanding of |
hmmm, not familiar either. Chatgpt misled me too then. What would it be the right way then?
what does "if it ws passed on" mean? not defined?
it also suggested {{ message if message else state_attr('calendar.meals', 'message') }}
if you're using ChatGPT, you're just getting yourself in trouble. please don't
nobody here wants to debug the crap that ChatGPT produces
just wanted to don't be too much of a bother here...
question remains:
what does "if it ws passed on" mean? not defined?
automation is making the service call. Then calling the script. #templates-archived message
but other automations call the same script without generating that variable
so I want to use the variable if it was passed to the script by the automation, or else use the default sensor value
so what value does it have when you don't want it to be used?
state_attr('calendar.meals', 'message')
"none"?
that's the "default"
no, the message variable
again:
what does "if it ws passed on" mean? not defined?
you're assigning something to the "message" variable, and then wanting to decide something based on its value later
yep
so.....
data:
variables:
message: {{ state_attr('calendar.meals', 'agenda')[1].summary }}
description: {{ state_attr('calendar.meals', 'agenda')[1].description }}
you need to know what value it has when you want to use its value and when you want to use the attribute
I think we're just going in circles now
not within the script
so, what value does it have when you want to use it, and when you want to ignore it?
you are passing it to the script....
no
you aren't conditionally passing it to the script, you are always passing it to the script
not always. The script will be called by other autos that do not have the variable
What is the purpose of using get_events if your script isn't passing anything from the response?
if you're not passing it at all, then you can use {{ message if message is defined else state_attr('calendar.meals', 'message') }}
I'm using get_events and getting it into the variable here
maybe you can use iif() there, but I don't know for sure
just for my learning, what does | do then?
I def got that wrong
I thought it was a type of IF
| applys a filter
ok, will read on that
got it, thanks
oh missed this. So this should work then. omw to test