#templates-archived
1 messages ยท Page 39 of 1
{% set value_json = state_attr('sensor.suburb_coordinates', 'entries') %}
{% for x in value_json %}
{% set testPostcode = x["postcode"] | int %}
{% if testPostcode == postcode %}
lat={{ x["lat"] }}&lng={{ x["long"] }}
{% break %}
{% endif %}
{% endfor %}
{% endmacro %}```
The suburb coordinates bit is just a text file that I've made into a sensor - the idea is that I give it a postcode and it gives me a lat/long coord back
Then I want to append those coords to a url and attach that to a rest sensor
There's a bunch of literal whitespace in there, you need to use modifiers on the tags to strip the excess whitespace
{% macro suburbCoords(postcode) %}
{%- set value_json = state_attr('sensor.suburb_coordinates', 'entries') -%}
{%- for x in value_json -%}
{%- set testPostcode = x["postcode"] | int -%}
{%- if testPostcode == postcode -%}
lat={{ x["lat"] }}&lng={{ x["long"] }}
{%- break -%}
{%- endif -%}
{%- endfor -%}
{% endmacro %}
sensors:
washing_machine_door_lock:
friendly_name: 'Machine Door lock'
value_template: >
{{ 'on' if is_state('binary_sensor.front_load_washer_door_lock', 'on') else 'unlocked' }}``` this is what I use when item has a strange name in idle state, but entity normally happens to be on/off open, is there a template or way that if a item has a state between 400 and 1400 I can just make a sensor from the the entity so it only changes the not_selected one? or do I have to list all the values, or just simply use between 400 and 1400.
You want something to reflect in the state when it's between 400 and 1400 and another value when it's outside of that range?
yep currently the value is Not selected when its out of that range
What should be values be? Do you want it to be a binary_sensor w/ on within the range and off outside?
its not that sensor, its my sensor.front_load_washer_spin_speed, it has speed of 400, 800, 1000, 1200, 1400 and then reports the state as "not selected" when its not spinning.
{% set spin_speed = states('sensor.front_load_washer_spin_speed') %}
{{ 'your value' if spin_speed == "not selected" else spin_speed }}
I think this is what you're looking for, obviously replace your value with whatever you want not selected to be
so this should work - platform: template sensors: washing_machine_spin_speed: friendly_name: 'washing machine spin speed' value_template: > {% set spin_speed = states('sensor.front_load_washer_spin_speed') %} {{ 'slow' if spin_speed == "not selected" else spin_speed }}
I'd say so.... you did say earlier not_selected and then later said not selected, so just confirm if there's an underscore or not
Works but was Not Selected (exact case)
Thank you so much, will help me in the future too ๐
Awesome, glad to help
Hello all. First timer and just now getting into the HA scene. I've added all my DSC Door/Window and Garage door sensors using RTL_433 and MQTT. Trying to show the Open/Closed status of all but unsure of the code to do so. Any help would be appreciated, not much of a coder but can understand patterns and this would help me to connect other dots. States/JSON Template? Lost.
mqtt.yaml
binary_sensor:
- name: "Master_Bedroom_Sliding_Door"
unique_id: "2152649"
state_topic: "rtl_433/DSC-Security/2152649"
device_class: door
Payload from RTL_433
{"time":"2023-05-06 22:37:00","model":"DSC-Security","id":2152649,"closed":1,"event":1,"tamper":0,"battery_ok":1,"xactivity":0,"xtamper1":0,"xtamper2":0,"exception":0,"esn":"20d8c9","status":131,"status_hex":"83","mic":"CRC"}
Hope this is the right section. Can move if not.
The "closed":1 changes to 0 when opened.
I made a PR and your example has been added to the Calendar documentation. https://www.home-assistant.io/integrations/calendar/
Question/Issue:
I have a trigger in a blueprint that looks like:
entity_id:
- !input motion_sensor
to: "off"
for:
hours: 0
minutes: 0
seconds: "{{(seconds_delay if is_state('binary_sensor.night_mode', 'off') else seconds_delay * 2)|int}}"```
`seconds_delay` is defined in the blueprint under `variables:` as `seconds_delay: !input seconds_delay`
This code doesn't work - i.e. never triggers - because of the template string. If I replace the template string line with `seconds: !input seconds_delay` then it works.
My template evaluates to a valid number when testing it in Developer Tools. Any idea what may be wrong?
I believe you'll need to define that in trigger_variables instead
https://www.home-assistant.io/docs/automation/yaml/#trigger_variables
Ahh that's likely it, thank you! Didn't know that was a thing ๐
I have the following template that pulls an event from the local HA calendar and works as intended. However I actually want to use the CalDav entities and when I change the calendar name it fails to work.
Any suggestions? Or is this only possible with local calendars?
what's for dinner tonight? {% if now() >= state_attr("calendar.dinner_2", "start_time")|as_datetime|as_local %}
{{ state_attr("calendar.dinner_2", "message") }}
{% else %}
{{
state_attr("calendar.dinner_2", "message")
}}
{% endif %}
Figured it out.
binary_sensor:
- name: "Master_Bedroom_Sliding_Door"
unique_id: "2152649"
state_topic: "rtl_433/DSC-Security/2152649"
device_class: door
value_template: "{{ value_json.closed }}"
payload_on: "0"
payload_off: "1"
I'm working with a sensor attribute and I'm trying to pull it into a template / notification . But I'd like to format the template so it shows the time format like this 8:30 AM. Right now it'll show times like this. 726 AM , 930 AM I'm also guessing they could be formatted like this at times too; 726am / 726pm / 726PM / 727AM. Is there a way I could detect when the time format is outside of what I'm looking for and to reprint the message to show the time in a format like this 9:30 AM?
Filter timestamp_custom(format_string, local=True, default) converts an UNIX timestamp to its string representation based on a custom format, the use of a local timezone is the default. If that fails, returns the default value, or if omitted raises an error. Supports the standard Python time formatting options
find info on it here https://www.home-assistant.io/docs/configuration/templating/#time
This is what the output from the two sensor attributes looks like:
Attention!!! Weather alert for place. A Special Weather Statement issued May 1 at 7:45 AM EDT. Strong thunderstorms will impact portions of place, place, place, place and place through 1030 am edt.
At 726 AM EDT, Doppler radar was tracking strong thunderstorms along a line extending from 6 miles southeast of place to place to near another place. Movement was east at 40 mph.
HAZARD...Penny size hail.
SOURCE...Radar indicated.
IMPACT...Minor damage to outdoor objects is possible.
Locations impacted include... list of places...
If outdoors, consider seeking shelter inside a building.
Is it still possible to use timestamp formatting like that since it's a timestamp randomly in the middle of the attribute?
you would have to use regex to find and replace it. if thats the case you may just be better off doing it all in regex
this gets you most of the way there {{(yourmessage|regex_replace('(\d{1,2})(\d{2})\s?([AP]m)( e[ds]t)?','\\1:\\2 \\3', 'i')}}
only thing it doesnt do is capitalize am/pm if its not capitalized
Thank you for the example! ๐
I am looking to extract the title field information from rss feeds to display on a LED ticker. I have feedparser sensor set up which displays the information in link below. Could anyone tell me how i could extract this infromation using a template? Its for a bbc news rss feed and this is how its displayed in the feedparser sensor - https://pastebin.com/PaCjp41A
what information excctly are you trying to get here
can you do a rejectrattr on entity_id to remove all devices with light.*_status_led?
rejectattr('entity_id', 'search', '_status_led$')?
yup...
just looking for guidance on how to extract the title text for each entry in the rss feed
is this using the rss feed templat eintegraiton
Using feedparser custom component which creates a sensor name sensor.bbc_news_feed and that sensor displays the text as show in pastebin link above
anyone have a template to count zigbee devices online or can help me make one
Which Zigbee integration?
{% for entity in integration_entities('zha') if states(entity) == 'unavailable'%}
{%if device_attr(entity, 'name_by_user') != None%}
{%if device_attr(entity, 'name_by_user') not in ns.list %}
{% set ns.list = ns.list+[device_attr(entity, 'name_by_user')] %}
{%endif%}
{%endif%}
{%endfor%}
{{ns.list|sort}}```
~~(i was bored, feel free to correct me if it can be done better), also fixed~~
yay for not preserving formatting
wondering if someone can help me understand what I am doing wrong.. I have the following in the Developer Tools->Templates and it works fine.
Driveway Gate: {{ {% is_state('light.driveway_gate', 'on') | iif('Closed', 'Open') %} }}But when I use it in the automation, it errors and I can't save it.-service: telegram_bot.send_message data: message: >- Driveway Gate: {{ {% is_state('light.driveway_gate', 'on') | iif('Closed', 'Open') %} }}
im gonna guess its the {% %} but i would think that woudl cause an error in dev tools template as well
I have tried it with {{ and {%
it would be with {{ }}, so take out the {% that should work from what my eyes see
This is what is working in Templates: Driveway Gate: {{ is_state('light.driveway_gate', 'on') | iif('Closed', 'Open') }}
what does it actually say the error is when you try to save
I think I need to sleep... the {{ }} worked this time. I think I had too many {{ {{ }} }}
or in this case {% %}
lol, happens to the best of us
appreciate it... thanks
@plucky temple I converted your message into a file since it's above 15 lines :+1:
@ashen terrace I converted your message into a file since it's above 15 lines :+1:
adding - as your very first and last character in certain places within each {{}} and {%%} will fix the whitespace
@plucky temple
I have error: mplicit map keys need to be on a single line
What exactly does that do, and which specific places would I need to add that?
it removes the whitespace, and honestly idk which places exactly lmao
you can start and end with it everywhere..even if its not necessary in all places so
thats the easy route
That does seem to be working, thanks! Now I thought that was causing it to output false when it should have been true, but its still saying false. Any ideas?
And yes, it is supposed to rain so thats not my problem lol
its overwriting the variable every loop, you need to set a break if true so it doesnt write over it
But its only writing true if it will rain, it is never writing false.
I need it to say true if even only one of the forecasts says rainy.
oh, cause variables set inside a loop dont carry out of a loop
so you can either use namespace or break
Even if it's declared before the loop?
Huh thats very different from other languages. How would I go about that?
{%- set forecast = state_attr("weather.forecast_home_hourly", "forecast") -%}
{%- set rainy_in_next_5_hours = False -%}
{%- for item in forecast[:5] -%}
{%- if item.condition == "rainy" -%}
{{"Working maybe?"}}
{%- set rainy_in_next_5_hours = True -%}
{% endif %}
{% endfor %}
{{- rainy_in_next_5_hours -}}
That is my code right now.
{%- set ns = namespace(rainy_in_next_5_hours = False) -%}
{%- for item in forecast[:5] -%}
{%- if item.condition == "rainy" -%}
{{"Working maybe?"}}
{%- set ns.rainy_in_next_5_hours = True -%}
{% endif %}
{% endfor %}
{{- ns.rainy_in_next_5_hours -}}```
i think this is right, i can never remember namespace syntaxc
UndefinedError: 'rainy_in_next_5_hours' is undefined
ns.rainy_in_next_5_hours
oh, missed the one at the end
I was curious if this would work, seems to be good on my end.
{{ forecast[:5] | map(attribute="condition") | contains("rainy") }}
Yes it does, and that sure simplifies things!
What happens if you remove the space after expand?
@ashen terrace
You have an extra { before and } after in your template
Thank you, that was easy... Thanks for help ๐
I sort have a issue with a template, works in template editor but not in config, I get the triangle of shock lol ๐ - platform: template sensors: washing_machine_run_state: friendly_name: 'washing machine run state' value_template: > {% set run_state = states('sensor.front_load_washer_run_state') %} {{ 'Standby' if run_state == "-" else run_state }} yes for some reason the standby is shown as state (-) when in standby.
@cursive ice I have no clue what you mean with the triangle of shock. However the template editor only checks the jinja part. It doesn't check the yaml
so it could be there's something wrong there
is this code placed under sensor:?
yes it is, by tringle of shock is instead of showing state I set (standby) it is just showing a error triangle
What error message do you get when checking the configuration?
none
see image bellow the power symbol https://ibb.co/8DRmLG1
thats what state label returns from that template
OK, what is the state of washing_machine_run_state?
Standby
well, in that case the sensor seems to work
this is an issue with the card, not a template issue
what makes it even more confusing is this one displays correctly - platform: template sensors: washing_machine_current_course: friendly_name: 'Washing Machine Current Course' value_template: > {% set current_course = states('sensor.front_load_washer_current_course') %} {{ 'Program set' if current_course == "-" else current_course }} which is very strange to me
I guess you should check the card configuration.
Omg what a newb mistake... - type: state-label entity: washing_machine_run_state style: top: 96% left: 50% pointer-events: none font-size: 15px font-family: var(--font-family) color: AliceBlue line-height: 30px lol ๐ณ
I think sensor. missing was not helping
how can I have a wait template that does
{{ is_state('input_select.home_status', 'Off') }} OR 3pm ?
or now() >= today_at("03:00")
thank you - is that pm?
no, add 12
{{ is_state('input_select.home_status', 'Off') or now() >= today_at("15:00") and now() <= today_at("15:01") }}
would that work?
I want it to only continue the automation if its between 03:00pm and 03:01pm
sure
thanks for your help ๐
Hi All, I'm fairly new to HA (a few months) and I've create some nice macros (introduced in 2023.4) for my templates.
Now my question is: Is it possible to add a sensor template to all entities of domain or whole entity glob (device_tracking.*) automatically?
Okay, thank you for your quick answer
did OpenWeatherMap change its uv index value? before I had this working because it returned integers, but now get all unknowns in the attributes
so, I have to add a round(0) there on the index, and change all mappers to use numbers instead of strings?
Well, if you get unknown in the uv_index attribute, is the actual state of sensor.openweathermap_uv_index unknown, too? Maybe it's not reporting the value right now?
it reported integers before. see my js code for the button I have:```
variables:
text_color: >
[[[ var index = entity.attributes.uv_index;
var colors = ['green','green','green','green',
'orange','orange','blue',
'maroon','maroon',
'red','red'];
return colors[index] || 'grey'; ]]]
icon_color: >
[[[ return (entity.state == 'on') ? 'var(--alert-color)' :'grey' ; ]]]
[[[ return (entity.state == 'on') ? entity.attributes.awareness_level.split(' ')[1].slice(0,-1) :'grey' ; ]]]
icon: >
[[[ return 'mdi:numeric-' + entity.attributes.uv_index + '-circle'; ]]]``` all relying on those numbers
somehow its returning 4.96 all of a sudden...
wondering if that is a fluke, a resource change, or a HA integration thing
uv index is a number that ranges from 0 to 10. It's a float
the api is probably returning more significant figures
yes, I suspect that to be the case, and it seems to be doing this since this afternoon.... my buttons were fine yesterday ๐
did you update HA? If no, then the api changed
hmm, I did update to the latest yes, but not yesterday. now you're making me doubt that.
Ok, then openweathermap updated how it sends data
looking at the source, it hasn't changed in 3 months
yes, I had checked that, but figured maybe some other part of HA was changed influencing the state
that's not how code works
on the final state I need: I'd use round(0) and not |int right?
unless it's inheriting from a base class
you can use whatever you want, round or int
the weather entity wasn't updated either, so it's definitely coming from the API, not HA
heck, it changed from 4.96 to 5.11 now.... before the |int made 4 of that, and the |round resulted in 5
Just confirmed, it's 100% coming from their api
right, that's how int and round works
int chops, round rounds
check. this works too now: variables: text_color: > [[[ var index = Math.round(entity.attributes.uv_index); var colors = ['green','green','green','green', 'orange','orange','blue', 'maroon','maroon', 'red','red']; return colors[index] || 'grey'; ]]] icon_color: > [[[ return (entity.state == 'on') ? 'var(--alert-color)' :'grey' ; ]]] icon: > [[[ return 'mdi:numeric-' + Math.round(entity.attributes.uv_index) + '-circle'; ]]] sorry for the JS, but it underlines the change in the API output
Math.round() required now to create integers
so they changed it at 11.36 this morning ๐
Hi there! I'm trying to get the temperature reading from a climate entity (climate.mh1 => current_temperature attribute). I added the lines below to my configuration.yaml. No errors, but can't get it to appear into my "Developer Tools>States>Filter: "temperature" listing. Any tips?
configuration.yaml:
..
..
template:
- sensor:
- unique_id: temperature_mainbuilding_mh1
name: Temperature > MainBuilding > Bedroom1
value_template: >
{{ state_attr('climate.mh1', 'current_temperature') }}
unit_of_measurement: ยฐC
icon: mdi:thermometer
attributes:
template: temperature
- unique_id: temperature_mainbuilding_mh1
Looks like you're mixing modern and legacy config. value_template should be state
Omg, thanks! Tried to get it to work for hours 
Anyone have any idea how to adapt the following code but to look at state attributes for "last_period" ?
{% set ns = namespace(items=[]) %}
{% for s in expand('sensor.plex_usage_monthly_john', 'sensor.plex_usage_monthly_brian', 'sensor.plex_usage_monthly_carl', 'sensor.plex_usage_monthly_terry', 'sensor.plex_usage_monthly_hank', 'sensor.plex_usage_monthly_jobe', 'sensor.plex_usage_monthly_larry', 'sensor.plex_usage_monthly_muriel', 'sensor.plex_usage_monthly_ryan') %}
{% set ns.items = ns.items + [ {'name': s.name, 'state': s.state | float(0) } ] %}
{% endfor %}
{% set items = ns.items | sort(attribute='state', reverse=True) %}
๐ *Top 5 Users: {{ states.sensor.month.state }} {{states.sensor.year.state }}*
1. {{ items[0].name }}
_{{ items[0].state }} hours of content watched_
if you don't have "Last period" entities, you won't be able to adjust that template to show last period values.
i.e. you only have sensor.plex_usage_monthly_john, you don't have an entity sensor.plex_usage_last_monthly_john
if those entities don't exist, you'd need to come up with a way to get them.
ah damn, I thought there might be something I can add to pull state attributes like you can name and state
thanks ๐ will go back to the drawing board
your sensor has an attribute last_period?
yes that's right. It's a utility meter sensor that counts how many hours people are watching content on my plex server
the last_period stores the last month's hours watched
the above code tracks which user watches the most content in a month
but I want to be able to manipulate it to send out a notification to our telegram group with last month's data, without several automations to store the data at the end of the month when it's already stored as a state_attr
{% set ns.items = ns.items + [ {'name': s.name, 'state': s.attributes.last_period | float(0) } ] %}
does this give you the desired result
'state': s.attributes.last_period
ah yes, that's perfect, thank you!
I had tried a variation of that code but couldn't pin down exactly what was missing
thank you so much ๐
you can get attributes that way by using .attributes.attributename where youd use .state
yw
When doing an icon template in a sensor, is there a shortcut to refer to "id or value of the sensor that i'm defining"?
i am dumb my value template was not enclosed in quotes
you can use the this object
Iโll give that another go then, thanks
Do note that it contains the values before the templates are rendered, so this.state will be the current state value, and will probably change soon
is is_state(state, value) vs states(state) == value just preference or is there a benefit of one over the other
is_state gives you odd results when there is no state.
er no, i'm thinking of is_state_attr
when your attr is none but you check for none, it'll still return false
Ah, you mean like this {{ is_state_attr('sensor.foo', 'bar', none) }}
is this because there technically is no attribute?
strange that it would return false
because youre checking if the attribute is equal to none would be my first line of thought
well for 1, you shouldn't be checking for none with ==
and that's what is_state_attr does
none is an object, it should always be checked with is none or is not none
dont have that much knowledge here, so what exactly is the difference in how its interpreted
ahh, i see, til
But can you actually distinguish between using state_attr() on an attribute which doesn't exist, or which does, but with value none?
In both cases state_attr() will return none right?
hi, i have a problem with my templatein. at least i think so. maybe someone could help ๐
okay here is my problem, i am trying to get a message on my phone when a new licence plate is detected by my plate detection system. the message on the phone needs to include the detected plate. as of now i have it set up so that the plate detection software sends a webhook trigger with data attached to my ha server. here i gather the data and try to filter out het 'plate' value listed unther 'results'. but in this filtering i have a error, i cant seem to get de value of the plate key in my message. the webhook data send is x-www-form-urlencoded.
this is the data ha recieves when the webhook is triggerd: https://pastebin.com/UYCWyEnU
this is my yaml of the automation: https://pastebin.com/mUfweuTK
Are you able to send it as application/json?
unfortunately not because i cant edit the sending part of the plate detection code ;C
if i could i had solved it already. i tested the same data in correct json format with postman and it worked like a charm...
this is the trace of the automation, if it is of anny help: https://pastebin.com/XWe563Ab
Yeah, pretty sure both cases return none
I'd try this in your automation {{ (trigger.data.json | from_json).data.results[0].plate }}
that's not json
it's json after the 6th character
my eyes
so if it truely comes over as json: {... then...
{{ (trigger.data[6:] | from_json).data.results[0].plate
Sending it as form data though and it looks like it's getting deserialized appropriately in the data repr (line 44 of the trace)
well that shows it being completely different
I didn't see the trace
where is he getting json: then in his first post?
also, the presentation of the data for the trigger is odd
it's showing repr
wow guys your amazing!!! it works
for someone just beginning in templating this is a huge help, have been struggling for 2 days now
Odd that this is how we display mappingproxyobjects from triggers
repr's are meant for general public
it should display it as a dictionary
I'll write it up
so odd to me some of the stuff check config doesnt flag
{%if {{states.sensor.lumi_vibration_tilt is defined}} %}
im getting this
2023-05-08 18:23:48.198 WARNING (MainThread) [homeassistant.helpers.template_entity] Template loop detected while processing event: <Event state_changed[L]: entity_id=binary_sensor.dishwasher, old_state=<state binary_sensor.dishwasher=off; door=closed, last_run=2023-05-08 22:23:48.117643+00:00, device_class=running, icon=mdi:dishwasher, friendly_name=Dishwasher @ 2023-05-08T18:23:47.858189-04:00>, new_state=<state binary_sensor.dishwasher=off; door=closed, last_run=2023-05-08 22:23:48.144391+00:00, device_class=running, icon=mdi:dishwasher, friendly_name=Dishwasher @ 2023-05-08T18:23:47.858189-04:00>>, skipping template render for Template[{{states.binary_sensor.dishwasher.last_updated}}]
is it possible to see which entity is causing in my template is causing it
nvm, its at the bottom..
ok i actually do need help, the following attribute is the problem. i changed it to this, but its still doing the same thing
last_run: '{{this.last_updated}}'
can i stop it from looping or do i just ignore it
I think the answer is "no", but would like to confirm: is there any way to access statistics data in a template? In particular, what I'd love to be able to do is access the most recent 5-minute or hourly change in sum for a total/total_increasing sensor and the same period mean for a measurement type sensor. That way I could, for example, calculate the from-grid low-carbon amount myself from a grid consumption and fossil percentage sensor.
Templates can only access real time data, not historical data
you can use an SQL sensor to get access to historical data
or that one
Yeah, I figured. I don't actually want anything actually historical -- I want the most recent values of the statistics -- is why I wasn't sure, but a SQL sensor might be the way to do it. I didn't want to use history_stats because I wanted the actual stored statistics value (so it will exactly match the energy dashboard, or at least what the energy dashboard should show, since low-carbon energy is buggy)
This code used to work - http://pastie.org/p/3LshZmCjMpofojUkeoGfRq
Unsure when it stopped but I am guessing its after an update as I have this code with two different sensors
@sacred sparrow I would guess the device_class
it expects a numeric state, and a unit_of_measurement of either d, h, min or s
not a string
There's probably a message about that in the log
that did it ๐ thanks for that
its worked for well over a year - strange it stopped now
HA became more strict in checking the selected device_class with the values
Interested in listing all entities in light or vacuum.
Running {{ states|....}} gives me too many results, and {{ states.light|...}} too few
How can I get a union between domains?
Can probably do (states.light + states.vacuum)|...
Seemed like a perfect solution. Got this error, sorry mate:
TypeError: unsupported operand type(s) for +: 'DomainStates' and 'DomainStates'
Ah, yeah. They may need to be turned into proper lists first
This didn't error:
{{(states.light|list + states.vacuum|list)}}
Yup, like that is what I was thinking. I don't know all the consequences of casting things to a list like that so ymmv, but hoping it works for you
Feels clunky but it is working; that's the important part ๐
Thanks @compact rune!
What do you exactly want as the end result? You could do the selection per domain first and add the results together
End result is a list of all objects that are on for both light and vacuum @marble jackal
{% set l = states.light | ... | list %}
{% set v = states.vacuum | ... | list %}
{{ l + v }}
My vacuum never has the state on
Ah that's a good catch .... your solution means I could select on cleaning
Yep
Going to run with this.
Thanks @marble jackal and @compact rune
hey guys, not sure if this is the right channel but i'm trying to use this integration https://www.home-assistant.io/integrations/rest/
i'm trying to use it to, given a postcode/zip code of my choosing, find the cheapest petrol for the area
my json that i'm using returns the 10 closest stations, and the json has a thing for "Stations" so that "Stations[0]" is the first one, "Stations[1]" is the second and so on
i was hoping to make a single sensor that had all 10 stations in it so i could manipulate it, but the only thing i'm seeing is to make a single sensor for each station and then manipulate them from there? is there a better way?
post the json please
there's an example of the json - can post it as a pastie or gist or whatever if that's easier?
You want it sorted by price, but just want the names?
You can also make a template sensor with a stations attribute that just has all that data stored
then you can use that however you want
just keep in mind that may fill up your database
I'll be honest, I'm jealous that the US doesn't have resources like this
this is super new - for the longest time i hadn't heard of it and found it completely by accident and i absolutely love it - i've made a number helper that lets users put in their postcode so they can find the cheapest petrol wherever they are!
and i think i'd like a few things - price, name/brand and maybe address just in case you don't know where you are or where it is
Ok, then your only choice is to just get all the data
and then make template sensors
@clear mist I converted your message into a file since it's above 15 lines :+1:
that's fine
how would i do that though - i'm still very new to HA and programming and whatnot and haven't done that stuff before
rest:
- resource: https://www.racq.com.au/ajaxpages/fuelprice/fuelpricesapi.ashx?lat=-27.4650118&lng=153.0132267&fueltype=37
sensor:
- name: All Petrol Data
device_class: timestamp
value_template: "{{ value_json.Timestamp | as_datetime }}"
json_attributes:
- Stations
oh man, i just had an awesome thought that ties in with year of the voice - being able to ask your assistant where the cheapest petrol is nearby and have it answer for you! or even to be able to ask by "brand" in case you have discounts or anything at particular places!
Then you'll need template sensors to sort and chug through the data
which is where all the templating will occur
template sensors?
Yes
sorry, i'm still learning things - what are template sensors? i don't think i've come across them yet
Template sensors are sensors that run code to get things into separate entities for use in automations
a more flexible option here is
{{states|selectattr('domain', 'in','[light, vacuum]')}}
either way, that rest sensor will get all the data into HA, then you can do whatever you want after the fact.
hmm, sounds complicated but i'll give it a shot
alternatively isn't there the option to group sensors? maybe i'll try all separate so i can present it nicely in some mushroom cards or whatever and do a group to get the cheapest one or something?
Well that's my point, if you want to sort it, you need template sensors
you can't manipulate data from a rest endpoint without using a template sensor
fair enough - i'll have a look and see what looks good then! thanks for the help!
template:
- trigger:
- platform: state
entity_id: sensor.all_petrol_data
variables:
sorted: >
{{ trigger.to_state.attributes.Stations | sort(attribute='Price') | list }}
- sensor:
- name: Cheapest Petrol
state: "{{ sorted[0].Name }}"
attributes:
name: "{{ sorted[0].Name }}"
brand: "{{ sorted[0].Brand }}"
price: "{{ sorted[0].Price }}"
address: "{{ sorted[0].Address }}"
suburb: "{{ sorted[0].Suburb }}"
last_updated: "{{ sorted[0].LastUpdated }}"
but to be honest, it looks like it's already sorted by price
so you might be able to just skip this step
Thank you. That's what I was trying to come up with. I guess off that I can conditional the state to be either "on" or "cleaning" in a one liner ๐
yep same way, just use in and a list
Hi, is someone here with expertise on "limited templates" ?
what's the question
trigger_variables:
ย controller_device: !input controller_device
ย controller_id: "{{controller_device}}"
ย controller_entity: "{% for entity in expand(device_entities(controller_id)) | selectattr('attributes.device_class', 'defined') | selectattr('attributes.device_class', 'eq', 'motion')ย %}{{ entity.entity_id }}{% endfor %}"
trigger:
ย - platform: event
ย ย event_type: state_changed
ย ย event_data:
ย ย ย entity_id: "{{ controller_entity }}"
ย ย ย attributes:
ย ย ย ย device_class: motion
You can't use those functions in limited templates
you also can't use templates in event data
templates can only be used in specific places on triggers, spelled out in the documents
MQTT topics for mqtt triggers, for in state triggers, and value_template for template triggers.
Okay, your first statement seems to be valid, the second one, I can prove. that i have working solutions like that
limited templates are limited in that you cannot use the state machine at all
that means, almost all HA custom functions, filters, and tests cannot be used
okay
basically, you're stuck with base jinja
Do you know which developer is responsible for those limitations?
it's limited because access the state machine is not possible in triggers
it's the nature of triggers, it's literally impossible to change
in regards to the code, the hass object is not usable, so any function that uses the hass object is not usable in limited templates
I've worked on this code as well as many others.
So, I suggest you find a different route
I do understand that this should not be possile in a usual automation. Due to make things more convienent to use, I would like to discussion the idea to make this avaible during setup of an automation by using a blueprint. I'm a developer myself, I understand the difference between an entity and a device and how things relate to each others. But there are tons of users which do not understand. that's why I try to enhance the convienent use of such blueprints.
So I would suggest, the idea, having templating fully available during setup, so that those variables are filled once, would make really sense to broaden the user base. What do you think?
It's a chicken vs egg scenario
it's been tried in the past and it's been denied
templates themselves are only available in specific locations as well and the documents spell this out
limited_templates are only useful for MQTT triggers, and that's the reason they were created
I know that the document spells out alot. But aren't we developers to change this?
Sure we are, but you're trying to change the foundation of all HA
and not to mention, you can do pretty much all of this already via conditions and variables that are executed after the trigger
I do not agree. than the automation (blueprint) would be executed several more times. Esecially those stuff like "mode: restart" would effect many broken automations, because it will be triggered without a match.
no?
the condition stops the automation from firing
trigger starts the automation. Condition decides whether it continues
actions are what occur after the condition is met
mode would not impact this
so this condition section will have not limited templates?
it has templates
and variables
triggers are limited to limited templates
all other sections are not
maybe I had a miss-understanding there. If seen many snippets defining trigger_variables which have been used in this condition-section.
I have no idea why people are using limited_templates
that is people doing the wrong things
most things should be included in the variables section
which executes between triggers and conditions
this changes a lot ...
order is: limited_templates -> triggers -> variables -> conditions -> actions
thanks for your help
np
FYI you can include DIRECTLY to your triggers btw
as long as the trigger accepts that object
e.g. a device trigger would be able to use !input controller_device
without a template extracting it
@stark hamlet here's an example of a 'good blueprint': https://github.com/SirGoodenough/HA_Blueprints/blob/master/Automations/AutoFanControl_HA_fan.yaml
most of his blueprints are well built
This is also good https://gist.github.com/Blackshome/6edfec0ff6a25c5da0d07b88dc908238
I can't comment on their actual jinja code, but those blueprints use !inputs, triggers, and variables properly.
wew, 1100 lines of blueprint
I can't find any short blueprints that have good examples of "best practices
most blueprints aren't great
I'd use blueprints, if they could also create scripts on the fly
I was previously using the garbage collection integrations from HACS but this is being removed in favour of Calendar.
I had been using a template with mushroom cards to change the colour of the mdi based on how many days until garbage collection etc.
Currently trying to figure out how I can run a similar template off of calendar data. Has anyone got any suggestions? It doesnโt seem to be anywhere near as simple to do
You can make a template entity to count the days until your calendar event
I also made a template library that does this for you https://community.home-assistant.io/t/easy-time-macros-for-templates/557374
Hero. Thank you
@swift veldt I converted your message into a file since it's above 15 lines :+1:
second line of the template has ( but no )
@swift veldt you should make use of availability templates
- sensor:
- name: EZO EC mS/cm
state_class: measurement
unit_of_measurement: "mS/cm"
availability: >
{{ states("sensor.ezo_ec_mys_cm") | is_number }}
state: >
{{ (states("sensor.ezo_ec_mys_cm") | float / 1000.0) | round(3) }}
Any suggestions on how I could modify this to count instances of different attributes?
I tried 'attribute' instead of domain, but I get a "UndefinedError: 'homeassistant.helpers.template.TemplateState object' has no attribute 'attribute'" error.
{%- for d in states | groupby('domain') %} {% if loop.first %}{{loop.length}} Domains: {% endif %}- {{ d[0] }}: {{d[0]|count}} {%- endfor %}
@latent geyser I converted your message into a file since it's above 15 lines :+1:
Any guidance would be appreciated, even to loop it twice with a delay, I'm very new to YAML and could use guidance.
Do you not have a close_cover action? Seems like its complaining that it doesn't find that, and I don't see it in your template.
How do I do this?
value: "{{ [7, states('sensor.ender5_bed_temperature') - 40)/25 | float]|max }}"
I know that if sensor.ender5_bed_temperature was a number it would all be fine, but I think it's seeing it as a string(it definitely returns a number in the human sense).
I just want to subtract 40 from that sensor reading and then divide by 25
put |float after the sensor to make it a number
Awesome. So simple. Thanks for the super fast response. It worked.
I struggled with it for like 30 minutes, and after your solution, it's SO obvious.
haha, just takes some understnanding of whats going on
all states are strings, so if they arent supposed to, you just need to tell the templating engine what its supposed to be
I have a command_line sensor that returns multiple json keys .... can I have multiple value_template entries to map each one?
No. That would imply multiple states
think I'm tracking
that's what I've been trying.... and I see the JSON fields if I run from the command line... but they aren't making it into HA
- platform: command_line name: water-meter unique_id: watermeter2023 command: /usr/local/bin/rtlamr -server 10.15.100.16:1234 -filterid=1569772012 -msgtype=r900 -format=json -single -duration=1m | jq -c '. |= del(.Message) + .Message' command_timeout: 45 device_class: water value_template: '{{ value_json.Consumption | float / 10 }}' unit_of_measurement: 'gal' json_attributes: - Time - BackFlow - Consumption - Leak - LeakNow
but for attributes all I have is:
unit_of_measurement: gal friendly_name: water-meter
I've seen 2 YT'ers in the last week put out videos training templates in the deprecated format. Kind of sad..
Anyone have a hint when the old format will be killed. I'm expecting that might happen soon...
Me thinks it's been about a year since the new was introduced.
I sent a note with his code correctly formatted and links to the HA docs to the first guy and he deleted it without response.
And he had people in the comments thanking him for the help with templates and the fantastic training. Really sad.
I don't expect it will be killed soon. It hasn't even been depreciated yet.
MQTT took about a year, so I'm expecting it sooner than later.
Good morning everyone
Is it possible to list all devices of a certain integration?
E.g. I would like to see all my tasmota devices and all my shelly devices.
Sorry, found it
{{ integration_entities('hue') }} # ['light.hue_light_upstairs', 'light.hue_light_downstairs']
The "new" format for template sensors has been introduced before the new format for mqtt if I remember correctly, and it was immediately announced the old format for mqtt was depreciated as of then and would be removed.
So far there has been no announcement about the legacy template format being depreciated.
It's not happening anytime soon. There's no reason to deprecate it and it doesn't cost any extra code or overhead. It won't be getting any new features, so that's the incentive to switch to the new format.
I doubt it will ever happen
unless there's an overhual that will cause it to not work. But, knowing the code, even an overhaul will unlikely kill it because all we do is pass the old format yaml to the new format when creating the entities.
Are you active on here often?
That's a #frontend-archived question
oh sry misclicked
Does the state object in templates contain the integration/domain - aka how could i get a list of all my SONOS media players?
integration_entities('sonos')
I see ๐ and pull out media players
Given 2 lists does Jinja support the intersection?
You can use integration_entities()
Right but how do i filter that for juts media players?
That gives you a list of entity_ids
Trivial to filter for specific domains from there
Do i pipe it to a regex match?
That's one way
is there a better way?
just select things that search for media_player.
{{ integration_entities('Roku')|select('contains', 'media_player.')|list }}
Ah! Thats a bit better than:
{{ integration_entities('sonos') | regex_findall('media_player\.\w+') }}
Thanks...
or: {{ integration_entities('Roku')|select('match', 'media_player')|list }}
depends on what you want to do with the list, really
Thanks rob! ๐
I've adopted the BluePrints channel here and kind of ignore everything else. With Moddin on Drzzs channel and my own stuff going on, it's about my bandwidth limit. Also stick with what you know,,, My BP's are under SirGoodenough nick, so thanks for the kind words above.
can I pass the value of a timer to the duration field in an automation? When i try this, and save it, it gets replaced with 'null'
delay: hours: 0 minutes: {{ state_attr('timer.sprinkler_offset', 'duration')}} seconds: 0 milliseconds: 0
thanks! little stuff like that keeps getting me
just confirming:
delay: "{{ states('input_number.spinkler_offset' )}}"
got it, so I have to specify which time field the helper is being used for
examples in the docs: https://www.home-assistant.io/docs/scripts/#wait-for-time-to-pass-delay
the last example takes minutes and turns it into seconds
when I use that example with a helper number, I get 'no default specified' ... I'm ok to use the hours minutes seconds field and just apply the template to the minutes field
it does have a value, in this case, '3.0'
but if I do the multiply (60) before converting to an int, then it works
you would need to share the actual code that you're using
I think this is working...
delay: >- {{ ((states('input_number.sprinkler_run_minutes') | float + states('input_number.sprinkler_run_minutes') | float) * 60) | int }}
now I'm trying to set the value of a value of a helper using a timestamp attribute of another entity:
service: input_datetime.set_datetime data: time: "{{ as_timestamp(state_attr('sun.sun', 'next_rising')) | timestamp_custom("%H:%M:%S", true) }}" target: entity_id: input_datetime.sprinkler_am
is time() a thing?
oops...type in my paste, edited
Hey, struggling with how to get the item selected in an input select to work in a script to play the media file of the same name. I'm editing a script I had working which pulls the info from a sensor, but I want to use an input select so I can choose a track.
one sec I'll paste the code in
'file_list')
That's what I have working, I want to replace it with the item selected in an input select
I tried:
states() not state()
someone now how to remove the date of the attr?
input:
{{ state_attr('calendar.www_*****_gmail_com', 'start_time') }}
output
2023-05-11 09:10:00
Aha! Thanks, I'll give that a go. Another basic question, I have to edit the filepath, I have a "replace" command working fine, but is there one to prefix some info?
eg the input select says "track.mp3" and in the script I need to say path/to/track.mp3
like you want time sans date? so 09:10:00?
yes
timestamp_custom filter
When working with templates, don't forget:
- You can test them in Developer tools -> Templates
thanks
This fixed it, I'm an idiot. Thank you!
This used to work, but in dev-templates it evaluates to 'evening', which should be night, so guess something is up here... Can this be rewritten more efficiently perhaps?
{%- if (as_datetime(states('input_text.morning'))
<= as_datetime(cTime) <= as_datetime(states('input_text.day'))) -%}
morning
{%- elif as_datetime(states('input_text.day'))
<= as_datetime(cTime) <= as_datetime(states('input_text.evening')) -%}
day
{%- elif (as_datetime(cTime) <= as_datetime(states('input_text.night'))) -%}
evening
{% else %}
night
{% endif %}```
OK, next question. I have my input select being populated by the contents of a folder (and I'm removing the path to make it look better). How can I randomise the order? If I include random in the template it just picks one item from the folder and puts that in the input select, instead of all items.
service: input_select.set_options
target:
entity_id: input_select.big_red_button_playlist
data:
options: "{{ state_attr('sensor.big_red_button', 'file_list') | map('replace', '/media/Sounds/Big Red Button/', '') | list }}"
what are your values for ctime and the input_text
I think maybe I need to include "| shuffle" instead of "| random" but it gives an error:
Failed to call service input_select.set_options. template value should be a string for dictionary value @ data['sequence'][0]['data']. Got {'options': "{{ state_attr('sensor.big_red_button', 'file_list') | map('replace', '/media/Sounds/Big Red Button/', '') | list | shuffle }}"}
shuffle isnt a valid filter in jinja from what i can tell
not sure if this is the best solution, but this works
{%set ns.newlist=[]%}
{%for each in ns.oldlist%}
{%set ns.newlist = ns.newlist + [ns.oldlist|random]%}
{% set ns.oldlist = ns.oldlist|reject('in', ns.newlist)|list%}
{%endfor%}
{{ns.newlist}}```
obviously where oldlist is your list
Thanks, I'll give it a go
@pliant egret I converted your message into a file since it's above 15 lines :+1:
Just use {{ trigger.from_state.state == "on" }} if you want to see if it was on
annnnd it works. Thanks folks
that's not working because is_state() expects an entity_id and you passed a state object
Gotcha, figured it must be something like that.
and got it all working! thanks all!
And thanks for the help the other night pointing my Rob! Got the blueprint working and will use that to push to multiple switches!
when using |int(default=0) in templates, is there a way to use the most recent value in history in stead of a defined integer?
I'm building a sensor for getting forecasted electricity price for the next 24h through a restful API. Can I just add the forecasted data to a custom named attribute to visualize it? Are there any reserved names for a forecasting data to enable easy integration to my GUI?
i have a mqtt sensor on which i would like to use a template. If the value of the mqtt output is 0 it should ignore that value. if not it should go through. i can seem to find how to do this properly.
- name: "Gasverbuik test met filter"
state_topic: "p1monitor/smartmeter/consumption_gas_m3"
device_class: gas
state_class: total_increasing
unit_of_measurement: mยณ
value_template: |-
{% if value_json == 0 %}
{{ false }}
{% else %}
{{ value_json }}
{% endif %}
I have this at the moment.
This seems to work. atleast i get the right value. Will this work when the value hits 0? or will this render an error when it posts false? or should false be something else
But it's a total increasing? Adding 0 to something is still the same something ๐
The problem is dlthat it drops to 0 which adds nothing but then the value becomes normal again to aroun 2000 M3 and then the energy integration thinks nice! Let's add 2000 M3 in a few seconds!!
so the problem is, why is the source dropping to 0?
according to the docs, that shouldn't matter
Doesn't adding it to the energy board just work?
not sure how you connected your P1
I would use this.state instead of false -- that should make it keep the previous value of the sensor when it gets a 0.
value_template: "{{ this.state if value_json == 0 else value_json }}"
Thanks
other options (as 0 is falsely):
{{ value_json | default(this.state, true) }}
{{ value_json if value_json else this.state }}
{{ iif(value_json, value_json, this.state) }}
{{ value_json | iif(value_json, this.state) }}
its hard for me to understand how these options really work because my knowledge for this is very limited. if im correct value_json is the actual value received from the mqtt message. for example {{ value_json | iif(value_json, this.state) }} what does this do? this.state is the current state before a new value is received i guess? so the iif will check if value_json == this.state?
normally im used to write the if statement first and the action afterwards. but {{ value_json if value_json else this.state }} is written the other way around correct? so it will post value_json when value_json has a value or else it will keep the old state right?
Sorry for this but i would like to understand how this works so i dont need to ask all these questions everytime ๐คฃ
im trying to create a fan.
To change the fan speed, I call an API endpoint http://esp.local/api?rfcommand={{command}}.
There are 4 presets, auto, low, medium, high.
To read the current speed percentage, I use a sensor sensor.itho_percentage
I was using the fan template from the docs, but can't figure out how to set it
I can't control it with the percentage
the percentage is from an mqtt
- name: "Itho Percentage"
state_topic: "itho/ithostatus"
unit_of_measurement: "%"
device_class: "power_factor"
value_template: "{{ value_json['Absolute speed of the fan (%)'] }}"
unique_id: "itho_percentage"
0 is considered to be false if you use it in an if statement.
so in case of {{ value_json if value_json else this.state }} it will return value_json if value_json is not equal to false, 0, [], "", {}
iif is and immediate if which can be used as a filter or function which you can use instead of "foo" if x > y else "bar"
ok thanks! its allot more clear now
hello guys
I am trying to add a sensor that makes me a simple calculation of multiplication between 2 sensors. The problem is that I didn't have created the file "sensors.yaml" I just created it and I added in config.yaml the "include".
It detects the new sensor created, but it gives me value 0, because it is not taking correctly the value of the sensor that I already had configured. In fact I have checked all the .yaml documents and I can't find them anywhere and where they are located.
I suppose that there is the problem, as they are not in the same place it is not able to read the value of the sensor to make the operation.
Can someone help me to solve it?
Thank you very much!
i'm new in home assistan and i'm trying in VM
@long hinge Please use a code share site to share code or logs, for example:
- https://dpaste.org/ (select YAML for the language, and consider picking a longer expiry)
- http://pastie.org/ (select YAML for the language)
- https://paste.debian.net/ (you guessed it, select YAML as the language)
Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.
Post all your code please.
from which file?
at this point, configuration.yaml and sensors.yaml
and include the name of the file you used for sensor.yaml
Is there a way to turn a whole set of state objects into JSON with the attributes and all?
I know i can pass to the expand filter a set of entities but I haven't figure out the next step
TypeError: Type is not JSON serializable: TemplateState
I run into that problem
configuration.yaml:
Loads default set of integrations. Do not remove.
default_config:
Load frontend themes from the themes folder
frontend:
themes: !include_dir_merge_named themes
Text to speech
tts:
- platform: google_translate
automation: !include automations.yaml
script: !include scripts.yaml
scene: !include scenes.yaml
sensor: !include sensors.yaml
sensors.yaml
- platform: template
sensors:
total_energy_cost_p1:
friendly_name: 'Total cost P1'
value_template: '{{ ((states.sensor.acumulado_mensual_punta.state | float * 0.2)) | round(0) }}'
unit_of_measurement: 'โฌ'
I got this sorted by the way. This template (created with the help of Google Bard!) looks at a sensor monitoring files in a folder, then generates a shuffled list of the file names, which is different each time it's run.
options: "{% set songs = state_attr('sensor.big_red_button', 'file_list') | map('replace', '/media/Sounds/Big Red Button', '') | list %}{% set ns = namespace(x = songs) %}{% for i in range(ns.x | length - 1, 0, -1) %}{% set j = range(0, i + 1) | random %}{% if j != i %} {% set ns.x = ns.x[:j]+[ns.x[i]]+ns.x[j+1:i]+[ns.x[j]]+ns.x[i+1:] %}{% endif %}{% endfor %}{{ ns.x }}"
No, you have to make it manually.
please format them
add 3 backticks before and after
`
or use a code sharing website like I linked before.
@long hinge I converted your message into a file since it's above 15 lines :+1:
I think I found my problem....
Platform template not ready yet: The template button platform doesn't support trigger entities
which is not what the docs say, so I am hoping an update will fix it up
post your code
@long hinge you need to use an availabilty template and also use the states() function
- platform: template
sensors:
total_energy_cost_p1:
friendly_name: 'Total cost P1'
value_template: "{{ (states('sensor.acumulado_mensual_punta') | float * 0.2) | round(0) }}"
availability_template: "{{ states('sensor.acumulado_mensual_punta') | is_number }}"
unit_of_measurement: 'โฌ'
@austere basin I converted your message into a file since it's above 15 lines :+1:
Button's would only support a trigger if you had teplates in name, icon, availability, and attributes
- button:
- name: "Matthew Desktop Mute"
unique_id: "muteymeetingahoy"
icon: >-
{% if is_state("binary_sensor.matthew_meeting_mute","on") %}
mdi:volume-off
{% else %}
mdi:volume-high
{% endif %}
press:
service: button.press
target:
entity_id: button.desktop_toggle_mute
trigger is unnecessary anyways
you weren't even using the trigger
if you're interested in optimizing...
- button:
- name: "Matthew Desktop Mute"
unique_id: "muteymeetingahoy"
icon: mdi:volume-{{ iif(is_state("binary_sensor.matthew_meeting_mute","on"), "off", "high") }}
press:
service: button.press
target:
entity_id: button.desktop_toggle_mute
I'm not sure what you mean by that.
Your code was using a binary sensor.
matthew_meeting_mute
yeah, but for some reason it wasn't working as a binary sensor so I changed it
is this an entity or not binary_sensor.matthew_meeting_mute?
it isn't. It WAS, but not anymore.
so what do you have now?
it works now ๐
button:
- name: "Matthew Desktop Mute"
icon: >-
{% if is_state("sensor.matthew_meeting_mute","True") %}
mdi:volume-off
{% else %}
mdi:volume-high
{% endif %}
press:
service: button.press
target:
entity_id: button.desktop_toggle_mute
it's beautiful. Using mutesync, now I can have visibility and control of the mute status not just of the audio device, but within teams.
Then I can use it to display status on the RGB LEDs I have put in my mic
thanks! works fine. Thanks
How can I make it show 2 decimals?
Thanks
where do I have to add this part?
all you need to do is change rount(0) to round(2)
nice!! thanks!
Hi, im trying to change a sensor which provides a date into "Tomorrow" "in x days" etc. From the forums i found the following snippet which seems close to what im trying to achieve. However when i replace set event= '2020-11-03' with my sensor, its throwing error. Anyone who can push me in the right direction?
{% set midnight = now().replace(hour=0, minute=0, second=0, microsecond=0).timestamp() %}
{% set event = '2020-11-03' | as_timestamp %}
{% set delta = ((event - midnight) // 86400) | int %}
{% if delta < 0 %}
{{ -delta }} Days Ago
{% elif delta == 0 %}
Today!
{% elif delta == 1 %}
Tomorrow
{% else %}
In {{ delta }} Days
{% endif %}```
I think this will help: https://github.com/TheFes/relative-time-plus
Hi, I have this template:
{% set num_adults = expand('group.adults_home_tracker') | selectattr('state','eq','home')|list|count %}
{% set num_adults_beds = ['binary_sensor.bedroom_daddys_bed_occupancy', 'binary_sensor.bedroom_mommys_bed_occupancy' ] | list %}
{% set occupancy_adults_beds = states | selectattr('entity_id', 'in', num_adults_beds) | selectattr('state', 'eq', 'on') | list |count %}
{% if num_adults <= occupancy_adults_beds and num_adults != 0 %}
on
{% else %}
off
{% endif %}
Why: "This template listens for all state changed events" and trigger looks like that:
Turned off triggered by state of Tรกta was detected at home
6:48:43 AM - 15 hours ago
Turned on
6:10:46 AM - 15 hours ago
Turned off triggered by state of Bathroom Washing machine plug changed to 0
5:08:04 AM - 16 hours ago
May 10, 2023
Turned on
11:58:26 PM - 22 hours ago
Turned off triggered by state of Dining room ATC Signal Strength changed to -92
11:47:26 PM - 22 hours ago
Turned on
11:45:26 PM - 22 hours ago
Turned off triggered by state of Living room ATC Temperature changed to 21.48
11:40:26 PM - 22 hours ago
format your code like this by surrounding it with ``` 3 back ticks on either side ```
its very difficult to read otherwise
{% set num_adults_beds = ['binary_sensor.bedroom_daddys_bed_occupancy', 'binary_sensor.bedroom_mommys_bed_occupancy' ] | list %}
{% set occupancy_adults_beds = states | selectattr('entity_id', 'in', num_adults_beds) | selectattr('state', 'eq', 'on') | list |count %}
{% if num_adults <= occupancy_adults_beds and num_adults != 0 %}
on
{% else %}
off
{% endif %}```
your template listens for all state changes because youre using state. as for why its triggering on unexpected state changes, maybe someone who knows better can tell with less info, but to me it appears that occupancy_adults_beds is selecting entities that you dont want
the sensor works perfect, its not a problem, but the triggers looks weird
because youre listening for all states with states
you can narrow it down with states.binary_sensor
here? ['binary_sensor.bedroom_daddys_bed_occupancy', 'binary_sensor.bedroom_mommys_bed_occupancy' ] ?
right here {% set occupancy_adults_beds = states | selectattr('entity_id', 'in', num_adults_beds) | selectattr('state', 'eq', 'on') | list |count %}
actually, you should just be using num_adult_beds|selectattr('state','eq','on'|list|count) on that line
you only need to be listening for state changes of things in that group, right?
This template listens for the following state changed events:
Domain: binary_sensor
Entity: group.adults_home_tracker
Entity: person.daddy
Entity: person.mommy
not binary_sensor.xxxx occupancy
not sure i follow what youre saying
i am not sure, after this change, it listen to 'binary_sensor.bedroom_daddys_bed_occupancy', 'binary_sensor.bedroom_mommys_bed_occupancy'
why are you using state|selectattr('entity_id', 'in', 'num_adult_beds') when you could be using num_adult_beds instead
ok, I dont know... I will try it
that should fix your issue with it firing on every state change, by only listening for things that happen in that list rather than every state change
expand(num_adults_beds) btw
group is number of people at home, what you mean?
num_adult_beds is the beds that youre looking for occupancy in, youre checking to see how many beds are occupied
right?
oh, sorry i miss understood your question. when i said group i meant the list num_adult_beds
yeah, and you were iterating through every single state object with state when you only needed to iterate through the objects in num_adult_beds
Yes
It also limits the updates in the templates, if you use states it's limited to once per 10 seconds
im guessing thats why completely unrelated state changes were showing up as being the trigger?
Most probably yes
How to get the time since a person entity changed states? For ex. Person.Marcin in my logbook was โhomeโ nearly 5,5hrs ago, but using person.marcin.last_changed gets me: โ24 minutesโ ๐ณ
Do I really need to use a script to access the DB to get this value? ๐ข
https://community.home-assistant.io/t/real-state-last-changed/15928
^
wait
well yeah
last changed doesnt persist on reboot
which is why it only shows 24 minutes
But I didn't restart my HA
Even if, is there any other way to mitigate this?
An easier way to get the value that is in the logbook?
I tried ChatGPT, but it gave me code like this:
{% set person_id = 'person.user' %}
{% set last_home = states[person_id].attributes.last_changed %}
{% set last_not_home = as_timestamp(history.state(person_id, 'not_home').last_changed) %}
{% if last_home > last_not_home %}
The person was last seen at home on {{ as_local(last_home).strftime('%Y-%m-%d %H:%M:%S') }}.
{% else %}
The person has not been seen at home recently.
{% endif %}
nah i think last_changed is what you wanted (honestly can never remember which is which)
chatgpt is stupid
I don't think such a thing as "history.state" exists
it makes up stuff that doesnt exist
Well, I wish history.state would exist ๐ It's just imagining things I guess
you can use the history stats integration to make a sensor that tells you how long an entity has been in a state
Oh, which one is it?
scroll up a tad
states.person.last_changed should persist though until restart or state change (based on my limited knowledge)
I'll give that history_stats a go, thanks!
@final sun I converted your message into a file since it's above 15 lines :+1:
@final sun you can only get the previous state when the state is changing and store it in another sensor. Or in an automation by looking at the 'from_state' if you used a state change trigger.
hello...
I have an mqtt sensor with a value template like this:
{
"name":"Glow Worm Luciferin Version",
"icon":"mdi:numeric",
"unique_id":"Glow_Worm_Luciferin_Version",
"state_topic":"lights/glowwormluciferin",
"value_template":"{{ value_json.ver if value_json.ver is defined else states('sensor.glow_worm_luciferin_version') }}",
"unit_of_measurement":" ",
"force_update":true
}
@marble surge I converted your message into a file since it's above 15 lines :+1:
since the latest HA update I get this error in the logs (modificato)
ValueError: could not convert string to float: '5.5.5'
but who said it that it's a float? I want it as a string
it seems that this sensor does not accept strings like this "pippo"
can't understand why HA things that it's a numeric field instead of a string one
remove the unit of measurement, your state is not a number.
ooops, sorry for the dumb question ๐
thank you very much petro
Is it possible to do a regex replace if there's only 1 word. Replace with upper? Meaning there's no whitespace between characters essentially. If there is whitespace as in more than 1 word then just do filter title.
How is that different from just using |title in both cases?
Because if it's 1 word I would prefer all uppercase. If it's not then title Foo Bar vs FOO for example
Title would turn foo to Foo not FOO. The values would be dynamic so that's why I was trying to see if there's some way to just detect 1 word by checking for no whitespace between characters. And do upper else title
Not regex, but ....
{% set x = "foo bar" %} {{ x|upper if x.rsplit(' ')|count==1 else x|title}}
That is awesome. Thank you.
if you're looking for speed, you'd want to use ' ' in x instead
@jagged dune I converted your message into a file since it's above 15 lines :+1:
@jagged dune templates fans only accept on/off as the main state. You cannot put other values into the state
Do you perhaps also know how to use the preset modes with Google home?
When i use them, Google just searches the web.
My language is set to Dutch.
So Template extensions. I tried some, they didn't seem to work I trird an inport that was just false, and it didn't seem to do what I thought it should. I don't really need to share code yet that you'all have to look at. Just wondering if the Developer sandbox is set-up to accept the extensions so we can do some pretesting? It doesn't seem to be, so assuming that it is not, it this a thing that's possible? Asking the experts here before I bother to add an FR.
I just created /config/custom_templates/test.jinja with this content:
{% macro groot() %}
{{ "I am Groot" }}
{% endmacro %}
called the homeassistant.reload_custom_templates service
and put the following in the template dev tool:
{% from 'test.jinja' import groot %}
{{ groot() }}
the result: I am Groot
@jagged dune I have a sensor for an mqtt 3 speed+ off fan if that helps you. https://github.com/SirGoodenough/Home-Assistant-Config/blob/master/mqtt/sensor/MQTT_snr_fan.yaml
I did one that was just 0 (also a false one) and returned it to a template sensor availability but the sensor kept showing. That lead me to the sandbox and when that couldn't find the import path, just thought that might be a good thing to have. So I'll sort my code problem, the question is more about the sandbox. my sandboz can't find the template, so there's my problem...
Thanks. I think i have it working.
Just trying to figure out how to use it with Google Home (Google Assistant).
I can give commands in numbers. The preset words don't work ๐ฅฒ
They do show up in the entity of Google
I tell my google a percent and it works
Important to know:
- The result of an imported macro is always a string
- If you don't add a hyphen to all your opening and closing tags (so use
{%-,-%},{{-and-}}) you're result will include unintended whitespace.
Yeah that works for me as well. But my fan only supports presets actually
I rather say put it on medium, or put it on auto
If i say, put it in 1%, it responses with: i will put it on low
The string got me for sure... So that really needs to be in the docs, I don't remember that. I'll check and get on it if not. Thanks
entity_id:
- sensor.saugroboter_eg_cleaning_history
id: Saugroboter Modus wechseln
to: unavailable```
Can I modify the trigger to only trigger if the sensor didn't change to unknown or unavailable?
Ah ty. Didn't know what to search for
Hi! Checked the release notes already, but can't find it. Somehow some templates I had were working perfectly a month ago, and now they don't (was on holiday in between, and only difference is I moved from 2023.3 to 2023.5). Anything in here that might not be compatible anymore?
# Find the cheapest time in before an input time for the washing machine
- name: "NextEnergy Cheapest Hour Washing Machine"
unique_id: 2019ac19-72b2-407c-8609-403b2305732e
icon: mdi:clock
unit_of_measurement: "EUR"
state: >
{% set hour_threshold = states('input_number.washing_machine_hours_ahead') | int - 3 %}
{% set time_threshold = now().replace(minute=0, second=0, microsecond=0) + timedelta(hours=hour_threshold) %}
{% set items = state_attr('sensor.energyprices','raw_today') + state_attr('sensor.energyprices','raw_tomorrow') %}
{% set lowest = items | selectattr('start', '>', now()) | selectattr('start', '<=', time_threshold) | sort(attribute='value') | first %}
{% set lowest_price = lowest.value * states('input_number.nextenergy_additional_electricitycosts') | float(0) %}
{% set cheapest_time = lowest.start %}
{{ cheapest_time }}
This is the error (in the log, not very clear)
Error while processing state change for input_number.washing_machine_hours_ahead
Traceback (most recent call last):
File "/usr/src/homeassistant/homeassistant/components/sensor/__init__.py", line 579, in state
numerical_value = int(value)
ValueError: invalid literal for int() with base 10: '2023-05-14 11:00:00+02:00'
You seem to have a datetime string in an input_number
You can and should add a default for the |int conversions like |int(0), but you should also figure out what caused the broken input_number value
The strange thing is it worked before. So something must have changed. Either the input from a sensor, or the way my template is parsed.
The error message is clear enough. Go look at the state of the entity
Oh wait, I think I found something else in the error.
: Sensor sensor.nextenergy_cheapest_hour_washing_machine has device class None, state class None unit EUR and suggested precision None thus indicating it has a numeric value; however, it has the non-numeric value: 2023-05-14 11:00:00+02:00 (<class 'str'>)
Damn, remnants from a previous way of doing it. I see some leftover code I should remove
Works! Damn. So in 2023.3 that bit of code had no effect, but now it does. Should I share this somewhere? I had unit_of_measurement: "EUR" for a template that is a datetime.
So, I want a template binary_sensor driven by the span of a specific calendar event (i.e. by message), so it turns on X hours before the start, and then turn off Y hours later (or relative to the end time, either way); I thought I'd be able to add a trigger to that template sensor, with my -X offset, and then set the state by checking trigger.calendar_event.message, such as: state: "{{ trigger.calendar_event.message == 'Trash day' }}". But by doing it this way, don't we lose the ability to have a one-to-one relationship of event-to-entity? That is, this works if the calendar contains ONLY my trash day event (or at least, does not contain any other event within X-Y hours of trash day) - if there's another event, say 30 minutes after the "trash day" event, then that will not satisfy the state template, and therefore my binary sensor will turn off, even though it's still within the window of the trash day event. Am I missing something obvious?
i am trying to save a snapshot:
service: camera.snapshot data: filename: "/tmp/snapshot_{{ entity_id.name }}.jpg" target: entity_id: camera.gate_high
but i get Error rendering data template: UndefinedError: 'entity_id' is undefined
but the docs say "Template of a Filename. Variable is entity_id."
Hi, I have a setup already working in Home Assistant with 1 wall switch, would like to add a 2nd dumb switch to make it work as a 2 way, I found the trigger.to_state,state ... but unsure it'st the best way
https://community.home-assistant.io/t/link-on-off-state-of-multiple-devices/460310
probaly will save you some time rather than having to template it yourself
for a dumb switch you can just make a helper toggle
Hi, I am trying to make a template trigger, that will trigger when any of my zwave 'node_status' sensors go dead.
{{ integration_entities('zwave_js') | unique | list is search('node_status') }}
Is where I am starting, but that node_status returns a bool.. I need a list of the actual entity
|select('contains', 'node_status')
yeah, nice shout. I just found select also
{{ integration_entities('zwave_js') | unique | list | select('contains', 'node_status') | list | select('is_state', 'awake') | list }}
and for the main event
{{ integration_entities('zwave_js') | unique | list | select('contains', 'node_status') | list | select('is_state', 'dead') | list | length > 0}}
You can get rid of the first two |list
so it appears to me that macros cant use variables from within the automation. i suppose i could specify in the macro to provide them, is there any way for it to reference those variables otherwise?
Do you have an example?
so in otherwords, the following doesnt work: https://dpaste.org/ddSFH
instead, i have to do this: https://dpaste.org/NCuH3
which isnt inherently a problem, just if i have a lot of variables
I'm not really following. In any case, you have transition in one place and transitions in another
im not seeing it
I see now. Did you change one of them?
I would believe that the variable scope of a macro is separate from the one in which it's used
You can pass a dict...
Or maybe a namespace works?
i edited them so i might have made a mistake before
namespace doesn't work, either. I suspect it's just the way the scope of macros works
Itโs important to know that imports are cached and imported templates donโt have access to the current template variables, just the globals by default. For more details about context behavior of imports and includes, see Import Context Behavior.
eureka!
{% set ns=namespace(foo='blah') %}
{% from 'test.jinja' import groot with context %}
{{ groot() }}
->
I am Groot - blah
test.jinja:
{% macro groot() %}
{{ "I am Groot - " ~ ns.foo }}
{% endmacro %}
that should help you
interesting! that solves my woes, tysm
do script variables and/or macros reevaluate when a state changes? ie, can they be used in the in a condition of while or until of a for each
for context, i use the following in a few difference places, so id like to just define it once if possible:
@orchid oxide I converted your message into a file since it's above 15 lines :+1:
Good Morning. i have a gas sensor template for a sensor.yaml file. But i dont have a sensor.yaml file. How should that look, when i want to put it into my conifguration.yaml ?
- platform: template
ย sensors:
ย ย gasverbrauch:
ย ย ย value_template: ย >
ย ย ย ย ย {% if states('sensor.gasverbrauch_esp') | float == 0 %}
ย ย ย ย ย ย {{ states('sensor.gasverbrauch') }}
ย ย ย ย ย {% else %}
ย ย ย ย ย ย {{ states('sensor.gasverbrauch_esp') | float }}
ย ย ย ย ย {% endif %}
ย ย ย unit_of_measurement: mยณ
ย ย ย device_class: gas
ย ย ย attribute_templates:
ย ย ย ย state_class: total_increasing
Hi, I created a trigger based sensor which should save my finances. The sensor has 12 attributes for the 12 months. But since last month the values doesnt get saved anymore. When I restart home assistant a very big chunk just gets lost. I paste here the sensor with just the first month and the sensors which should create a nice graph based on the finance list sensor.
You'll have to paste that on dpaste.org or something else
What does your home-assistant.log say during start up? And what do you mean by a very big chunk just gets lost?
I dont have screenshots sadly. But I have a graph that shows what I have spend this month and another graph how much money I got this month. When I look at the data it all is normal and all states are correct. When I restart HA then a lot (for me random chunks) of data in the past gets lost.
So, is the sensor itself right and the front-end is wrong?
in the present yes. But after a restart backend data is lost as well. In history tab there is shown: no data for this period
https://dpaste.org/Qavo1 the logs
Some of your sensor.legro_ and sensor.miri_ entities are not numbers. You need to track down what's wrong with those
I suppose if those are also templates though, it could just be a temporary issue
i have paste them into https://dpaste.org/qSiSc at the end
@mental violet I converted your message into a file since it's above 15 lines :+1:
It's probably too big, I guess you have a warning in your log about an attribute exceeding xxx bytes and therefore not being saved
I went through all of the errors with bytes and the only error I get is this:
``` but this is from the HA app
but in general I have these errors alot (70 times):
If that is the error, can I override it and define that this particular sensor should be saved?
do I have to create then a sensor for each month? would that evade the problem with to many bytes ?
- platform: template
sensors:
current_rain_per_square:
friendly_name: 'Tomaten Regen'
value_template: {{ states('sensor.openweathermap_forecast_precipitation') | float 0.1 }}
unit_of_measurement: 'mm'
Hey guys,
Im trying to create a new sensor by multiplying the value of the existing sensor, but I keep getting these invalid key errors.
Does anybody know why and how I can fix it?
invalid key: "{'states.sensor.openweathermap_forecast_precipitation | float 0.1': None}" in "/config/sensor.yaml", line 7, column 0
copied wrong. I didnt forgot to multiply
{{ states('sensor.openweathermap_forecast_precipitation') | float * 0.1 }}
Surround it in "s
and please format your code
To format your text as code, enter three backticks on the first line, press Shift+Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks.
```yaml
example: here
```
Don't forget you can edit your post rather than repeatedly posting the same thing.
- sensor:
- name: Time
unique_id: time_am_pm
state: "{{ now().strftime('%-I:%M %p') }}"
- name: Date
unique_id: date_month_day_year
state: "{{ now().strftime('%B %d, %&') }}"``` - Should this work for date when i did and restarted the yaml it was blank.
...
Hi, thanks for answering! Having debugged more I have identified another script to be the issue/cause. I still haven't found a solution though. This is what I need to work https://paste.debian.net/hidden/12988009/ Thanks
why aren't you using input_datetimes?
@lean yacht I converted your message into a file since it's above 15 lines :+1:
Nver mind. Looks like a reload issue... reloading the all YAML fixed it...
There is a reason for that, I don't have it fresh on top of my head right now, but agree it sounds better. I have tried to use them, but for now don't remember why it didn't work out...
@lean yacht I converted your message into a file since it's above 15 lines :+1:
@lean yacht read the first pin in the channel
Is there a way to filter entities by which have a speaker?
For instance I want to do something like this:
{{ (area_entities('Some Room') | selectattr('device_class', 'eq', 'speaker') | list)[0] }}
Then want to play some TTS using it
is that a real device_class?
if so, you just need to add |expand after area_entities()
apparently not, UndefinedError: 'homeassistant.helpers.template.TemplateState object' has no attribute 'device_class'
Is there a better way to filter by speaker or media player?
media_player is a domain
hmm okay perhaps I can filter on entity name if I name them all so they end in _speaker?
{{ states.media_player|map(attribute='entity_id')|list|first }}
no idea
you need to figure out what constitutes a speak for you
Well for me its all just unifi cameras with speakers/mics
I just need to do it by area
by that I mean, something that you can actually filter on
Basically trying to do when a person is detected speak in said room but wanted to avoid using a choose
I have found no such thing, other than media_player entities typically have speakers
hmm okay
yeah I dont really get why I cant do it by device class as I can see it in the states list
Try adding selectattr('device_class', 'defined') before the other speaker filter
you can, but I see no evidence that there's a "speaker" device class
maybe there is and I just don't have any
hmm no that didnt work
ok, so there is one: https://www.home-assistant.io/integrations/media_player/#device-class
you wanted selectattr('attributes.device_class', 'defined')
hmm I dont think that worked either
the other way was better
UndefinedError: 'str object' has no attribute 'attributes'
This works:
area_entities('greatroom') |
selectattr('device_class', 'defined') |
list
But gives back an empty array
so I feel like its missing something let me double check the room name is right
You still need expand
Like this:
{{
area_entities('entryway') |
expand |
selectattr('device_class', 'defined') |
list
}}
{{ area_entities('entryway') | expand | selectattr('attributes.device_class', 'defined') | selectattr('attributes.device_class', 'eq', 'speaker') | list }}
I double checked the area and there is for sure a device in it
Seems like that worked
Can you set variables in an automation? Just want to store this in a variable temporarily to make things easier to read
Can I set it part way through an automation though?
Like I think Ive seen elsewhere people do a set variable
oh okay cool
thanks
lol jfc
Ok trying to figure out what unit of measurement and/ or state class to use for this template sensor. Goal of the sensor is to parse out hvac action from my nest thermostat and save it in a way that I can plot it along with my temp sensors in grafana
Can someone please paste a template/way for "sunrise effect" by controlling brightness of a smart bulb, from 1%-100% in 1hr time span?
Grateful
yeah sorry I thought I saw something about enter three tildes and ctrl enter and all that but can't find now
Unit of measurement is for sensors with a numeric state
For this I would use a binary sensor
and the logic could be simplified
yes I may have an extra case in there for 'off' that is not needed but I think I was seeing some error when hvac was set to off and it successfully evaluating the other cases
- binary_sensor:
- name: "Addition HVAC Running"
state: "{{ is_state_attr('climate.addition', 'hvac_action', ['cooling', 'heating']) }}"
unique_id: "addition_hvac_running"
thank you
ok thanks again, i'm up and running with that (and another HVAC) as binary sensors. For some reason, I was convinced that they needed a unit of measurement to show up in influx db/ grafana
Is there a way to print the type of a "thing" ... i'm struggling to get relative_time to work correctly for looking up how far in the future is the next calendar "thing"
My start time looks like 2023-05-16 07:30:00 so I try to get a timezone in there by tossing it through: as_datetime(states.calendar.test.attributes.start_time).isoformat()
And then I wanted to run the relative time on it and i just get the same value: ISO Format: 2023-05-16T07:30:00
Am i missing something here?
the standard "relative_time" only works for things in past
I believe that this may help: https://github.com/TheFes/relative-time-plus
Is there a way to get whether an entity is exposed to assist? (Something that would be along the line of state_attr(entity, 'is_exposed') ?
not that I'm aware of
voice assistants don't support weather entities
so, even if you could, it wouldn't do anything
@inner vault ^
Good to know on the weather entity as I did not know that, but you probably misread whether as weather ๐
I guess you can get results of weather entities using custom intents
Yeah, that's the only way
but TBH, there's no point when voice assistants do weather naturally
Is it possible to do {{ listvar is regex("\d{3}$") }} to check each item in a list and be true if either matches the regex? I keep getting false
- foo001
- foo002
- foo003
You want it to provide a single aggregate result of if any match, or the result of each?
{{ ['foo001','foo002','foo003a'] | map('regex_search','\d{3}$') | list }}
That will give you the result for each list item
{{ ['foo001','foo002','foo003'] | map('regex_search','\d{3}$') | select | list | count > 0 }}
Should do that
{{ listvar | map('regex', "\d{3}$") | select('true') | first | default(False) }}
Perfect thank you guys
or
{{ listvar | map('regex', "\d{3}$") | select('true') | list }} if you're going to set that to a variable and do {% if x %}
There doesn't appear to be just a regex filter, that's why I mentioned regex_search
Yep that's what I just noticed
aren't you using ansible though?
Unless you're doing this for HA, then you need to use regex_search, if you're doing this at your job (IIRC ansible), then regex exists
You're right this is for Ansible
Ok then, you can use regex
ah, it's only a test
so
{{ listvar | select('regex', "\d{3}$") | list }}
FYI you should learn the differences between a test, filter, and function and then use the ansible docs
iv'e never used ansible, but I can read docs ๐
Lol I have been reading them. It's crazy because the list is empty when I try that. It doesn't make any sense. Going to keep messing around with it.
These code snippets are still helpful for how to approach this
Is there a way to remove a key and it's associated value from a json array with Jinja?
So "foo": "bar" would be removed simply by searching to remove foo
And even better providing a list of keys to remove the kvp from the array
You cannot modify a dict once created, but you can create a new one based on a filtered version of the original
How would I do that?
you can use xxx.pop('key')
to remove
to add, it's a whole ordeal and I've shared the code with you in the past
although pop might be blocked
Yep I remember that, do you have that url? I may need to actually try this lol. I need 99% of a dict to be reused but change some key values to different values.
Yeah I didn't think so.
the method required depends on your keys
Example of replacing a key:
{% set month = 'mai' %}
{% set x = 110 %}
{% set paid = {'januar': 85,'februar': 85,'mรคrz': 85,'april': 85,'mai': 0,'juni': 0,'juli': 0,'august': 0,'september': 0,'oktober': 85,'november': 85,'dezember': 85} %}
{{ dict(paid.items() | rejectattr('0', 'eq', month) | list, **{ month: x }) }}
That method will only work if you don't have spaces in your keys
No spaces.
then you can use that
you also can't have special characters
so a-zA-Z0-9, starting with a letter
if your keys start with numbers, you have to use from_keys
or fromkeys
Interesting ok let me try this example.
I saved that a long time ago because it would take me too long to try to build it from scratch ๐
I'm saving it too lol
I have a template that converted degrees from a NOAA buoy to direction. It worked fine until recently. friendly_name: 'wind direction' value_template: > {% set direction = ['N','NNE','NE','ENE','E','ESE','SE','SSE','S','SSW','SW','WSW','W','WNW','NW','NNW','N'] %} {% set degree = state_attr('sensor.buoy', 'MWD')|float (0) %} {{ direction[((degree+11.25)/22.5)|int] }}
The degrees still show in my sensor.buoy. Any ideas on what changed that is causing this to fail?
Also in the template editor it shows correctly. The degrees show as 189. The sensor shows N, the template editor shows S.
It shows the wrong value. The degree is 189. This converts to S. It shows south
If I past the template into the editor. It shows south.
wind direction N for the sensor created by the template.
Value in Editor is now SSW as the degree has changed from before.
MWD: 193
Not sure how this is happening. Saw another user questioning his senor in the forums and this caused me to look at mine.
what does the template editor say that it's listening for changes for?
you can convert that sensor to the modern format and add a state trigger for it, but I don't see why you should have to
I have two Identical sensors, one works and the other doesn't. What is the modern format I should use?
If I was debugging this I would start by replacing with something like this, and see what it says:
friendly_name: 'wind direction'
value_template: >
{% set direction = ['N','NNE','NE','ENE','E','ESE','SE','SSE','S','SSW','SW','WSW','W','WNW','NW','NNW','N'] %}
{% set degree = state_attr('sensor.buoy', 'MWD')|float (0) %}
{{ degree }}
If that works, then just slowly build back up to what you had:
{{ ((degree+11.25)/22.5) }}
{{ ((degree+11.25)/22.5)|int }}
...
Where am I debugging?
isnt {{ ((degree+11.25)/22.5)|int }} just {{ degree/22.5)|round }} ? why not just use that, one less thing to account for
Again, I'm not sure what I am debugging? The code above works in the template editor. It also works correctly for my sensor.weather. It just recently stopped working for my sensor.buoy. All identical code
I don't know what you want me to say, obviously the sensor is not working, so I suggested trying to break it down in steps to see what exact part of the template is not working in the sensor.
I understand this, but where do I break it down? In the yaml file?
yes literally just replace your existing template sensor with what I posted, and reboot (or reload yaml). When it comes back, see what it says:
value_template: >
{% set direction = ['N','NNE','NE','ENE','E','ESE','SE','SSE','S','SSW','SW','WSW','W','WNW','NW','NNW','N'] %}
{% set degree = state_attr('sensor.buoy', 'MWD')|float (0) %}
{{ degree }}
If the sensor value shows "0", than you know something is not working in the state_attr correctly.
at least this gives some idea of where things are breaking down for further investigation
The above pasted in my template editor shows 0
Just looked at the buoy and the buoy did not send the direction for some reason. I'll try again after it updates
I am having a similar issue to what @amber hull posted above. My sensor template looks like:
value_template: > {% set direction = ['N','NNE','NE','ENE','E','ESE','SE','SSE','S','SSW','SW','WSW','W','WNW','NW','NNW','N'] %} {% set degree = state_attr('sensor.bibuoy', 'MWD')|float %} {{ direction[((degree+11.25)/22.5)|int] }}
This returns "unknown". But if I place this same code into the developer tools template editor, it return "SW" as it should.
I tried the following, and it returns "218" so the sensor is working, it is the template that doesn't seem to fetch the value from the string array.
value_template: > {% set direction = ['N','NNE','NE','ENE','E','ESE','SE','SSE','S','SSW','SW','WSW','W','WNW','NW','NNW','N'] %} {% set degree = state_attr('sensor.bibuoy', 'MWD')|float %} {{ degree }}
I tried a few more things in the sensor template to try and debug the issue. In that last line, I did {{ direction[3] }} and it also returned "unknown" instead of the expected "ENE". I also tried having the direction array store integers in each item instead of strings, and that worked. But of course it is the strings that I actually want.
I have several sensors just like this and they are all acting the same way. They had been fine for half a year but just started acting like this recently. And no changes have been made to any of the code. Not sure what other debugging steps to take.
What does 'acting like this recently' mean. It broke on a HA update? Or it just stopped working unrelated to any updates?
I just tested something similar on 2023.5.3 and it is working as expected, for me at least:
- platform: template
sensors:
wind_1:
value_template: >
{% set direction = ['N','NNE','NE','ENE','E','ESE','SE','SSE','S','SSW','SW','WSW','W','WNW','NW','NNW','N'] %}
{% set degree = states('input_number.direction')|float (0) %}
{{ direction[((degree+11.25)/22.5)|int] }}
I was trying to create some rest sensors but got the value error ```yaml
- platform: rest
scan_interval: 60
name: '5G Temp'
resource: http://192.168.12.123/status-data.jsx
method: POST
payload: _http_id=dfsdnfsdnfsdklfnds
headers:
Content-Type: 'text/plain;charset=UTF-8'
Authorization: 'dfnsdjkfnsd=='
User-Agent: Home Assistant
value_template: '{{ value | regex_findall_index("eth2: 5G - (\d+)") | int }}'
state_class: measurement
device_class: temperature
unit_of_measurement: 'ยฐC'
error in developer tools > templates UndefinedError: 'value' is undefined
Not in
-> Templates
I have added it in configuration.yaml but no sensors created
how to fix it?
What is the response format of the url? can you see HA hitting it?
now sensors have created but value unknown still
how do I check format?
curl or similar, then see what comes back. you probably need to pick the value out of the json
bcz opening in browser http://192.168.12.123/status-data.jsx turns up blank
use curl. in browser you're missing authorization.
if you don't get back something useful from curl, HA isn't going to fare any better
should I try in ssh?
do it from your workstation if you like.
curl -v \
-H "Content-Type: text/plain;charset=UTF-8" \
-H "Authorization: dfnsdjkfnsd==" \
http://192.168.12.123/status-data.jsx
Or something like that
use ssh if that's easier, or you don't have curl on your local
Your auth value looks a bit suspicious too
it was obviously obonxed for posting
@stuck dock I converted your message into a file since it's above 15 lines :+1:
this is from ubuntu 20.04 wsl2
Your authz is no good. 401 Unauthorized
I think word basic is missing
What provides http://192.168.12.123/status-data.jsx?
@stuck dock I converted your message into a file since it's above 15 lines :+1:
that is device tracker only, I was using it previously didn't provide any data on temperature
blank page
working fine now
https://www.linksysinfo.org/index.php?threads/homeassistant-integration.77338/post-342662 there was a issue with missing Basic with a capital B
๐
I need help with a template condition
need to check script.clean_upstairs is not running, and has not run since midnight (I feel those 2 statements may be redundant?)
I tried using Chat-gpt for the first time (for the lolz) and it gave me this non-working code:
{{ not is_state("script.clean_upstairs", "running") and (as_timestamp(now()) | int - as_timestamp(now().strftime("%Y-%m-%d")) | int) == 0 }}
{{ is_state('script.clean_upstairs', 'off') and state_attr('script.clean_upstairs', 'last_triggered') < today_at('0:00') }}
Should work
Left side checks that it's not running and right side checks that it was last triggered before midnight
if it was running now, would it not show as "has run since midnight?"
state is on when it's running
ah I understand what you're saying
That's true, last triggered is updated immediately
thought so. not after completion.
Yeah, you could nuke the left side of the and then
thanks.
{{ state_attr('script.clean_upstairs', 'last_triggered') < today_at('0:00') and is_state("vacuum.bitch_vac", "docked") }}
Thanks Tim. Interestingly, mine looked like yours (at least the template), but yours worked. See mine below. So then I decided to remove other sensor options one by one and turns out that the culprit was the line unit_of_measurement: "". Removed that single line and all my sensors are fine now. Weird that this has worked for a long time but a recent update seems to not like that line. Anyway, back in business so thank you again.
`
- platform: template
sensors:
bi_wave_direction:
friendly_name: "Mean Wave Direction"
unique_id: "bi_wave_direction"
icon_template: mdi:waves-arrow-right
unit_of_measurement: ""
value_template: >-
{% set direction = ['N','NNE','NE','ENE','E','ESE','SE','SSE','S','SSW','SW','WSW','W','WNW','NW','NNW','N'] %}
{% set degree = state_attr('sensor.bibuoy', 'MWD')|float %}
{{ direction[((degree+11.25)/22.5)|int] }}
`
sensors that have unit_of_measurements are assumed to be numerical results. This is being strictly enforced now.
ok thanks
Trying again. I seek to simplify this if possible. https://paste.debian.net/hidden/df1825a8/ It is one of four sections that will (or should) update input helpers with a timestamp in a rolling manner. I guess I could use input_datetime, but that won't simplify anything really. Can this be done smarter?
smarter, yes by using datetimes. Optimized? No
without getting into heavy template*
Shouldn't this work according to the docs? If keeping "initial" it does not...? This is from my configurations.yaml
input_datetime:
morning:
name: Morning
has_date: true
has_time: true
initial "05:00:00"
you didn't provide a date
How can i find the domain of a given sensor via templates?
sensor itself is a domain
Is there a simple way to have a switch helper whose value is based on whether another switch's on or off button has been pressed?
Right now I have that as two automations but that seems... very clunky and wrong
the state of a template switch can be whatever you want
I'm not sure what you mean by "switch helper"
Any way to count how many of a particular sensor have the same state_attribute? For example, I pull in my wine data from cellar tracker and want to make a template sensor that will count how many bottles have the country argentina, france, portugal, etc.
but would prefer not to define the countries as they are dynamic and would hate to think I might have missed one out
these are the attributes of one of my sensors:
count: 1
value_total: 21.3744
value_avg: 21.3744
%: 1
Wine Name: Tulloch Shiraz JYT Selection
Vintage: 2016
Colour: Red
Country: Australia
Best after: 2022
Best before: 2025
unit_of_measurement: bottles
icon: mdi:bottle-wine
friendly_name: cellar_tracker.tulloch shiraz jyt selection_2016
a Helper that's a switch
as in, defined on the Helper page as type "switch"
want to collect all my sensor.cellar_tracker_* sensors and categorise them by country
bonus points if I can just do this easily enough in custom:flex-table-card which I can't seem to see at the moment
you can create a switch template and use the on/off values to reflect the "real" switch
the real switch is a ZHA device so I can only see its actions, it seems
That just converts a switch to some other domain. You cannot customize how it behaves
oh, sorry, I mean binary_sensor.
You can map a switch to states, so if a state is on, the switch will say it's on, then you can define an action which toggles another action (like switching it off), but it can sometimes be slow
I use it to convert media players to easy to use on/off toggles
basically: when zha switch fires "on", set binary sensor to true; when zha switch fires "off", set it to false.
but the switch is only a device, not an entity
that sounds like a template binary_sensor with a trigger
I am trying to lump some devices together in a template as a light but it isn't working. Any thoughts?
- platform: template
lights:
esphome_status_leds:
value_template: >-
{{ states.light | selectattr('entity_id', 'search', '_status_led$') | map(attribute='entity_id') | list }
for one, you're missing the trailing }
Ugh
It's there in the config.
Well it isn't showing up in the entities list
I know the code template works as it returns the list of lights I'd like to control all at once
Ahh I know the issue
I tried this, but 'trigger' is apparently undefined according to the dev tools:
template:
- trigger:
- device_id: 3a8fdb75a216f23f8431e58838bc73b2
domain: zha
platform: device
type: remote_button_short_press
binary_sensor:
- name: test
state: '{{ trigger.subtype == 'turn_on' }}'
You can't directly test trigger variable based templates in the Template editor tool, because the trigger variable is undefined.
You don't need to reboot even once, just set up the binary sensor, reload Template entities, then watch its state in the States tool when you press the button.
@dim roost I converted your message into a file since it's above 15 lines :+1:
{{ states.sensor | select('search', 'cellar_tracker_')
| selectattr('colour', 'Red') | list | count }}
Template is returning TemplateRuntimeError: No test named 'Red'. Am I missing something?
@haughty breach I converted your message into a file since it's above 15 lines :+1:
Thanks @haughty breach
@dense swan I converted your message into a file since it's above 15 lines :+1:
How do I use this? Getting an error about not in dict.
Error executing script. Error for call_service at pos 1: Error rendering data template: Result is not a Dictionary
Yes, you didn't provide a test. selectattr('colour', 'eq', 'Red')
thanks
I used state_attr in templates to get an attribute of a sensor. I was told this is the old way of doing it. What is the correct way now? i.e value_template: "{{ state_attr('sensor.kohler_sensors', 'lube_oil_temperature') }}"
there's no better way
the "old" way would have been states.sensor.kohler_sensors.attributes.lube_oil_temperature
So this is correct?
what you have is correct