#templates-archived
1 messages · Page 80 of 1
That’s it!
however in developer tools -> states...
no forecast attribute.
i.e. you have to use the service
Is this internally stored/polled periodically, or is the service just being called when I browse to the entity?
does it matter? You don't have access to that without the service
And service = retrieve the data from NWS (request data, wait for reply over Internet) each time?
You're assuming it does htat
each weather integration is different
it may be cached data, it may request new data. Each integration is different.
That integration polls for data every 60 minutes, regardless how many times you call the service. I.e. it's cached data.
So, services may cache data and don’t do asynchronous retrievals each time? That’s what I was trying to ask. I see that many of the weather integrations limit how many calls per hour/day you can do.
integrations do the caching
integrations manage the services they create
the service can do anything the integration code-owner can dream up
OpemWeatherMap, for example wants a credit card in case you go over so many per day.
If you're not willing to read the code, you'll have to do practical tests to find this information out.
Gotcha. Was thinking that maybe the data wanted is stored in an “entity” object and I could somehow access it directly from Jinga with some function and do everything in Jinga.
no, entities are designed to have the least amount of data as possible because their states go directly into the database
So, state=sensor=local and service=get from integration (possibly cached)? All integration interaction with templates falls under these two categories?
I'd say, it's a safe bet to assume every weather integrations get_forecast is cached hourly.
otherwise, look at each integrations coordinator file to see the polling frequency
I don't really understand your template comment
templates access the state machine and they are synchronous, not async. So templates are limited to a "snapshot in time"
which is what the state machine provides
If I move my template sensors from config.yaml to a split file (templates.yaml), will this keep the history (or create a new sensor)?
everything will remain the same if you don't alter the entities. Restart, don't reload.
Great
Is this also true for changing the syntax of the template? I've got both today and would like to harmonize it. As in:
sensors:```
and
```template:
- trigger:
Only if you have unique_id's
if you don't have unique_id's, add them. Restart. Then convert them to the new style. Then restart again.
Do not reload under any circumstances
Hmm ok, even if they are not created from the ui?
Not sure what the UI has to do with this
unique_id creates a config entry for the entity. Then when you convert to the new style, nothing will alter because you have a config entry that it will use.
I heard somewhere, on the podcast I think, that templates from the UI was dependant on unique ids. Or something. But whatever - thanks, will try!
I think you're miss hearing things. They were most likely mentioning that you don't need to add a unique_id because the UI is creating it
Yeah probably
Is there a way to pull time information off of a history graph? For example, I have a sensor that shows how long a playstation is on and I would like to have it show Playstation - 30 Mins or something like that.
@brisk storm I converted your message into a file since it's above 15 lines :+1:
make a template sensor with it
ohh, that makes a bit more sense
a more compact way to express that would be:
{% set mode = states("sensor.toplotna_mode")|int %}
{% set map = {0: 'Hot water', 1: 'Heating', 2: 'Cooling', 3: 'Hot water + heating', 4: 'Hot water + cooling'} %}
{{ iif(mode <= 4, map[mode], 'Unknown mode: ' ~ mode) }}
i was looking for something like this!
thanks
there's a ) missing somewhere on the 3rd line and i'm not entirely sure where it's supposed to go
got it
oh yeah, it's all coming together :)
Oops, yeah
How can I find out how many times a temperature sensor has changed in the last 24 hours? And maybe even how many times just the number in front of the decimals?
A trigger based template sensor which triggers on every state change of the temperature sensor and then increments it's own state with one
Copying from #automations-archived because I went the wrong place (again):
Okay, I feel like this should be easy. I want to keep this simple for my sister and have a card that lets them set time and temp for day mode and night mode for a heater in a plant nursery. Have that all working but I just learned about the generic termostat helper, so I'm migrating to that. There should be a way to run an automation to set the temp at a helper number when the correct time comes around, but I'm failing because it's looking for a float value
Hi! I have a card for my 3d printer, based on the octoprint state sensor: https://dpaste.com/6BQ2YBQ63
The states for it can be: Printing, Operational, and Unavailable.
Is there any way to just show the card as 'off' when Unavailable? I don't like seeing it as a faulty device on my dashboard
@hoary nest I converted your message into a file since it's above 15 lines :+1:
temperature: "{{ states('input_number.space_heater_day_temp') }}"
it's working as expected with https://tmep.cz/vystup-json.php?id=8234&export_key=jn9d1x8g7s but i'm not sure why
That's a #frontend-archived question
value_template: "{{ value_json['8234'].cas }}"
json_attributes_path: "$.8234"
We bow to our green gods
Don't tell that the yellow gods
What about the purple ones?
We are daemons
WOOT! YES! Programs unite!!!
one more thing. Is it because it's nested JSON ?
Hi folks - i need a little help with hardening a template sensor that occasionally becomes unavailable. I think it is related to using this.state as an attribute but I can't find a better way.
`# Sensor to compare the latest GPS speed data when it changes
Holds latest acceleration calculation as state
- trigger:
- platform: state
entity_id: sensor.jago_iphone_speed
sensor:- name: "Jago iPhone Acceleration"
unique_id: jago_iphone_acceleration
icon: "mdi:speedometer"
state_class: measurement
state: "{{ ((trigger.to_state.state | float(0) - trigger.from_state.state | float(0)) / states('sensor.jago_gps_age') | float (0)) | round(4) }}"
attributes:
speed_last: "{{ trigger.from_state.state | float(0) }}"
speed_now: "{{ trigger.to_state.state | float(0) }}"
state_last: "{{ this.state | float(0) }}"
state_delta: "{{ (states('sensor.jago_iphone_acceleration') | float(0) - state_attr('sensor.jago_iphone_acceleration', 'state_last') | float(0)) | round(4) }}"`
- name: "Jago iPhone Acceleration"
- platform: state
Dividing by 0 if the GPS age is unavailable might break it
when it works it works. I need state_last attribute to hold the last state to allow me to work out state_detla
I have tried to use {{ has_value(states('sensor.jago_gps_age'))}} but this always returns false
even when it has a value
Whenever that sensor is not numerical, it will default to 0 in your template. And that is a problem
Because that's the wrong syntax: has_value('sensor.jago_gps_age')
thanks - what is wrong with the syntax?
you were providing the state of the entity and not the entity
you can see the difference between yours and his?
yes - now I can. sorry. didn't look properly
the docs say you can use has_value as a filter. would this be a good approach for hardening this template?
You can use that for an availability template. But that wouls also mean being unavailable, when that sensor has no value.
Thank you. I want the sensor to be available at all times and always trigger - happy with it returning 0 when gps_age is unavailable. how can I harden so this is the case?
At least you need to change the default value of GPS age to something else than 0. Some sane value.
OK. i will change the default to 1 for gps_age.
If you want the state of the complete template to be 0 when GPS age is unavailable, I guess you would have to work with if-else or iif
I have a feeling the issue is with using this.state as an attribute so I will use has_value to harden this and also look to usee iif for the state
is using iif a better way than using a filter with default or no difference? For example...
{{ iif( has_value('sensor.jago_gps_age'), states('sensor.jago_gps_age'), 0 ) }} {{ states('sensor.jago_gps_age') | float(0) }}
to be clearer do the above examples do exactly the same thing? Return 0 if unavailable or unknown
That won't help at all.
Your logic would have to be
if GPS age has value: use the template (I'd still set the default for the GPS age to 1)
if not: state is 0
sure - i will change gps age default to 1. That's easy.
when you say 'use the template' do you mean the state inside the triggered template sensor? (sorry i'm quite new to this stuff)
I meant that template from the state section earlier
If-else-endif might be easier readable to begin
https://www.home-assistant.io/docs/configuration/templating/#building-templates
state: >
{% if has_value('sensor.jago_gps_age') %}
{{ ((trigger.to_state.state | float(0) - trigger.from_state.state | float(0) / states('sensor.jago_gps_age') | float (1)) | round(4) }}
{% else %}
0
{% endif %}
Thank you @marsh cairn - understood. That is what I thought too so I did understand after all
#frontend-archived message looks like i greatly overcomplicated this. the answer is simplyThere are {{ states['light'] | selectattr('state','eq', 'on') | list | count }} lights on and {{ states['opening'] | selectattr('state','eq', 'on') | list | count }} doors open.
I don't think that states['opening'] is a thing unless you've installed a custom_component that supports it
If not, you need states.binary_sensor and you need to check on the device_class attribute
Can I get the timestamp from an event in a template? I'd like to get the exact time of the event which has triggered an automation. I've tried sensor.date_time_iso but that is only giving me the time the automation executed to the minute. I'd like to at least get to 1 second resolution.. Thanks.
The last_triggered attribute gives you the date and time it last triggered accurate to the microsecond
If you want the exact time the event was sent, create a trigger based template sensor which triggers on that event and writes the time (either of the trigger, or just now()) to it's state
Oh right, now I see your actual question in #automations-archived
Just use now().strftime('%H:%M:%S') in a template to get the current time including seconds
For more options see https://strftime.org
Thanks!
@willow wing I converted your message into a file since it's above 15 lines :+1:
Use {%- and -%} (https://jinja.palletsprojects.com/en/3.1.x/templates/#whitespace-control)
ah looks beeter now, but the spacees beetween etch word is away too now
Change secondary: |- to secondary: >- (https://yaml-multiline.info/). |- keeps newlines.
makes no change (no space beet etch word)
why do you have new if statements every time?
dont know how i can do it in a other way
@willow wing I converted your message into a file since it's above 15 lines :+1:
@willow wing how about this?
{% set sensor = 'sensor.iphone_chrissi_companion_app_geocoded_location' %}
{% set attr = states[sensor].attributes if sensor | has_value else {} %}
{{
[
attr.get('Thoroughfare', 'N/A'),
attr.get('Sub Thoroughfare', 'N/A'),
attr.get('Locality', 'N/A')
] | reject('eq', 'N/A') | join(' ')
}}
ahhh, thats cool and works perfect, would never have thought of it, would it be possible to check the value "null" to? can i add this via a comma?
reject('in', ['N/A', none])
If I understand you correctly
which value would be null?
all three can have this vlaue "Thoroughfare, sub Thoroughfare and Locality"
so its enought to add it in the reject line like your example?
yeah, in that case you can do this:
{% set sensor = 'sensor.iphone_chrissi_companion_app_geocoded_location' %}
{% set attr = states[sensor].attributes if sensor | has_value else {} %}
{{
[
attr.get('Thoroughfare'),
attr.get('Sub Thoroughfare'),
attr.get('Locality')
] | reject('in', ['N/A', none]) | join(' ')
}}
perfect thank you 👍🏻 👍🏻 (but the comma does not be setted in you example)
can i ask you one more too?
which comma?
my format was "street number, location"
so it is missing a comma after the Sub Thoroughfare
i got it, thanks 🙂
how did you add it?
attr.get('Sub Thoroughfare') +",",
that will not work in case its none and will break the reject filter
ah okay, than its bad 🙂
Wouldn't join(', ') work?
then you will have a comma between each
but its no worry only nice to have, the UI is never perfect ^^
Right, but if attr.get('Thoroughfare') is N/A or none, then it would just be attr.get('Sub Thoroughfare'), attr.get('Locality').
{% set sensor = 'sensor.iphone_chrissi_companion_app_geocoded_location' %}
{% set attr = states[sensor].attributes if sensor | has_value else {} %}
{% set t, s, l = attr.get('Thoroughfare'), attr.get('Sub Thoroughfare'), attr.get('Locality') %}
{% set ts = [t, s] | reject('in', ['N/A', none]) | join(' ') %}
{{[ts, l] | reject('in', ['N/A', none, '']) | join(', ') }}
lol that's awesome.
it works you'r crazy, thank you very much
you're welcome 🙂
Can't I use a template to get the changes in temperature from history?
a template only has access to the current states, no history
you can create an sql sensor to recteive data from the database
Aha. Then thanks. 🙂
and you could store changes in an attribute of a template sensor, so you can build up your history
It was more of a one time thing to figure out if I should update an eink on every change. But I guess I can use SQL manually to do a count.
I need help, been searching the web and trying a few things and can't wrap my head around this. I need something to be able to pull states from a device/entity history and output the time of that state. For example, on a game councel, the history will show "Playing" and "Idle". So between 07:00 and 08:45 the states is playing then 08:45 to 14:00 is idle then 14:00 to 18:00 is "playing" Trying to create a card that will show the total amount of time it was in the "playing" state and it updates through out the day.
Hope that makes sense.
history statistics integration
OMG. I can't beleive I have missed that. I'll check it out and see if that works. Thanks 🙂
Yup. looks like this is doing what I wanted. 🙂 Thanks again for the help!!
Hi all, I am trying to set an automation for when I trigger an alarm. I want to send a notification to my phone where I get to know the name of the entity that triggered the alarm. How do I do that? I know to get a sensor state I need to use {{ states('sensor.id') }}, but what about the name?
trigger.to_state.name should work
but it's a bit depending on the trigger you use in the automation
Let me take the template I currently have
@tough depot I converted your message into a file since it's above 15 lines :+1:
Reason why I want to do it this way is in case in future I change in HA the name of the sensor to something else, so that I can avoid having to go change the name in the notification message every time as well
Ok, this worked, thank you!
For some reason couldn't find exactly what I needed online
Become a real Jinja2 Ninja! Don't worry my Genin, we are here to help! You can find general Jinja docs at https://jinja.palletsprojects.com/en/3.1.x/templates/, Home Assistant extensions at https://www.home-assistant.io/docs/configuration/templating/, and trigger variables at https://www.home-assistant.io/docs/automation/templating/
This channel is for support with Jinja templates. Some custom Lovelace cards support other types of templates, such as those written in JavaScript, and #frontend-archived is the right channel for that.
Please use http://pastie.org/, https://dpaste.org/, or https://paste.debian.net/ to share code or logs
follow the trigger variables link for some more information and options
O.k. at a loss again. I have a history sensor up and running and working. When I go into devolopment and states to find the sensor, I see it and change the unit of messurements from h to min. I go into the entities to look at it and it updates there. But then when I go to add the card, it shows as xx:xx ie 20:12. Am I missing something somewhere?
I am trying to get the card to show it in min such as 20 min
how it is shown on the frontend depends on the device class of the sensor
but this is more something for #frontend-archived
Hoping this is the place for this questions. So I got my sensors up and running the history_stats is working. What it does is gives me a running total but I would like it to reset and start at 0 every day. Is that possible?
that's what history_stats does? what did you give for the time parameters?
Orrr, will it reset everyday. I guess when I add the end time to go back 1 month, it added all of that time on today. So it basicly went from 65 minutes up to 760 minutes within a matter of seconds lol.
name: DarkPlaystation Play Time
unique_id: 5432154
entity_id: sensor.darkplaystation_activity
state: "playing"
type: time
start: "{{ today_at().replace(day=1) }}"
end: "{{ now() }}"```
O.k. and then it keeps that history of each day still, but restarts at midnight?
this is a sensor. it updates its value throughout the day. whatever history was recorded in the past will never change
the parameters you give it tell it how to compute its current value
o.k. That makes sense.
So is there away to have this sensor pull the history going back as well? or am I SOL with that and have to let it just gather new data going forward?
you can only ever change its current value. what was recorded in the past, is fixed
I’m confused by your phrasing. History stats looks at history.
When I placed the start to go back 1 week. it took the time of the playing state and added it to the current day. The history graph didn't show the previous 7 days, just today with the added time.
oh, I see what you're asking. Nothing you add in home assistant will ever add history
it's always from this point forward
if you want to see just last weeks count, you'd have to adjust your start and end to show last weeks start and last weeks end
O.k. but to track it with the history_stats sensor, it's only going to record going forward.
I dont think you understand what start and end are doing
It's o.k. not a big deal 🙂
If you set the range to be start 7 days ago and end 6 days ago, you get the value from 7 days ago.
But the result is added to your system at this moment
It won’t have a history
Because you just added it
The result of the sensor will always be 7 days ago.
hello again!
i have a modbus sensor which gives me a 16bit number and each bit means something (basically i wanna break a single sensor down into 16 binary sensors). how do i do something like this? i'm pretty sure a template sensor is only 1 and can't multiply and i also don't feel like creating all of those maually
About to mow the lawn, post an example output from the source sensor and I can help in about an hour or so
here's a copypaste from the datasheet:
bit0: O01 System 1 compressor output (0-OFF/1-ON)
bit1:Reserved
bit2: O03 Fan high speed output (0-OFF/1-ON)
bit3: O04 Fan low speed output (0-OFF/1-ON)
bit4: O05 Main circulating water pump output (0-OFF/1-ON)
bit5: O06 Domestic hot water pump output (0-OFF/1-ON)
bit6: O07 Four-way valve 1(0-OFF/1-ON)
bit7: O08 Electric heating energy level one (0-OFF/1-ON)
bit8: O09 Electric heating energy level two (0-OFF/1-ON)
bit9: O10 Hot water 3-way valve (0-OFF/1-ON)
bit10: O11 Alarm output (0-OFF/1-ON)
bit11: O12 crankshaft heating tape (0-OFF/1-ON)
bit12: O13 chassis heating tape (0-OFF/1-ON)
bit13: O21 heating pump (0-OFF/1-ON)
bit14: O22 hydraulic module water circuit electric heating (0-OFF/1-open)
bit15: O23 hydraulic module water tank electric heating (0-OFF/1-ON)
as i said, it's a 16bit number as always but this time it uses the bits as flags for different things
right now the value is 85 aka 0b0000000001010101
honestly, i'm not sure if i care enough to implement the bitfields
there's 11 registers like this and it's usually just pointless information i don't care about or error flags
i'll do it if there's an easy way but if not, that's fine
Back, it's super easy
{% set bytes = "{0:016b}".format(value) | map('int') | reverse | list %}
just put the sensor output in value
@brisk storm ^
bytes[0] is byte 1
etc all the way up to byte 16 bytes[15]
as a template sensor...
template:
- trigger:
- platform: state
entity_id: <FILL THIS OUT>
variables:
bytes: >
{{ "{0:016b}".format(trigger.to_state.state | int(0)) | map('int') | reverse | list }}
binary_sensor:
- name: Byte 1
state: {{ bytes[0] }}
- name: Byte 2
state: {{ bytes[1] }}
- name: Byte 3
state: {{ bytes[2] }}
- name: Byte 4
state: {{ bytes[3] }}
- name: Byte 5
state: {{ bytes[4] }}
- name: Byte 6
state: {{ bytes[5] }}
- name: Byte 7
state: {{ bytes[6] }}
- name: Byte 8
state: {{ bytes[7] }}
- name: Byte 9
state: {{ bytes[8] }}
- name: Byte 10
state: {{ bytes[9] }}
- name: Byte 11
state: {{ bytes[10] }}
- name: Byte 12
state: {{ bytes[11] }}
- name: Byte 13
state: {{ bytes[12] }}
- name: Byte 14
state: {{ bytes[13] }}
- name: Byte 15
state: {{ bytes[14] }}
- name: Byte 16
state: {{ bytes[15] }}
fill in the rest
and or perform math
or do whatever
Does anyone have a quick one liner to get a list of all the notify.* services?
not possible 🎉
I figured as much, but thought I'd ask. Thanks.
Hi there. I'm having an issue with a RESTful sensor. It's pulling the data ok, but when I try to update through Lovelace, it's coming up appended with a _3 and getting the following error. "This entity ('sensor.wet_bulb_globe_thermometer_3') does not have a unique ID, therefore its settings cannot be managed from the UI. documentation for more detail."
- platform: rest
resource: https://swd.weatherflow.com/swd/rest/observations/station/2xxxx
method: GET
name: "Wet Bulb Globe Thermometer"
device_class: temperature
headers:
Authorization: !secret tempest_api
value_template: '{{ value_json["obs"][0].wet_bulb_globe_temperature | int }}'
scan_interval: 5
I've been looking around and can't quite figure out how to give it a Unique ID. I need this because that value is coming over as Celcius and I want to convert it to Fahrenheit without doing a seconday template with a formula.
Add unique_id: to your YAML.
@north helm To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks.
```yaml
example: here
```
Don't forget you can edit your post rather than repeatedly posting the same thing.
But what do I specify after unique_id?
Whatever you want.
It can be a string of anything, as long as it's unique. You could use "981273098127390812739018273" or whatever strikes your fancy. 🙂
Huh.... Let me try that. That's FAR too easy if true. 🙂
It's true. The docs don't lie: https://www.home-assistant.io/integrations/sensor.rest#unique_id 😉
Well son of a.... Don't I feel silly now?
lol no need to feel silly... I still get it wrong from time to time.
Now I just need to get the unit conversion working. Guessing it's something like unit_of_measurement: C
unit_of_measurement: F should automatically do the conversion (I think).
What does the JSON look like?
"wet_bulb_globe_temperature": 21.4,
Added native_unit_of_measurement: °C. and now getting This entity is no longer being provided by the rest integration. If the entity is no longer in use, delete it in settings.
That's because native_unit_of_measurement isn't a valid attribute.
That's for a sensor entity. The rest sensor entity doesn't have that attribute. What you linked is the base sensor class, but not everything derives from that.
Ohhhh
So, it looks like you need to do the conversion in your value_template from C to F.
OK. I can do that. It's ugly but I can do it.
'{{ ((value_json["obs"][0].wet_bulb_globe_temperature | int(0)) * 1.8) + 32 }} should do it.
Actually... my parens might be off there. I didn't test it. Doh.
There we go. Fixed it.
{{ ((value_json["obs"][0].wet_bulb_globe_temperature | int(0) * 1.8) + 32) }} Ahhh, yours should be right.
LOL... Yeah, mine came back as 57.7 degrees.... HA!
I do temp calcs WAY too often. lol
Stupid metric system, amirite?
lol you said it... not me!
Still unavailable.... Hmmmm. And look, I grew up on metric, but Americans will do anything to avoid it so here we are.
The sensor is unavailable?
Yeah....
Ok. 1 sec. Let me test it.
Thanks. I'm probably doing something really dumb.
unique_id: MercuryWetGlobe
resource: https://swd.weatherflow.com/swd/rest/observations/station/26820
method: GET
name: "Wet Bulb Globe Thermometer"
device_class: temperature
native_unit_of_measurement: °F
headers:
Authorization: !secret tempest_api
value_template: '{{ ((value_json["obs"][0].wet_bulb_globe_temperature | int(0)) * 1.8) + 32 }}'
scan_interval: 5
Change native_unit_of_measurement to unit_of_measurement.
Damnit.
🤣
Now I has teh shame.
Woot!
Thanks for being so patient with me.
Oh, not a problem at all!
I really appreciate your help.
If you want to test it in dev tools > templates:
{% set value_json = { 'obs': [{ 'wet_bulb_globe_temperature': 20 }]} %}
{{ ((value_json["obs"][0].wet_bulb_globe_temperature | int(0) * 1.8) + 32) }}
I don't use that tool enough.
Oh yeah, that needs to change.
It certainly will!!
I wish I didn't have to run, but movie night is starting and I need to pay attention. Hope you have a good weekend and stay cool. Thanks again!!!
Right on. Sounds good. Have a good weekend yourself and happy to help. 🙂
I'm sure I'll be back later this weekend now that I've gotten into the guts of my system. 🙂
Is there a way to determine if a sensor's value is increasing or decreasing in a template? My use case is that I am trying to write an automation to send a notification when the house reaches "temperature crossover." So, I want to have one trigger for when the outside temperature is rising and equals the inside temperature (would naturally occur sometime in the morning). Then, I want another trigger for when the outside temperature is dropping and equals the inside temperature. This way I can send notifications to either open or close windows depending.
So set up a template sensor to represent the delta and then trigger on the numeric state as usual?
What I was thinking was a template trigger similar to: {{ float(states(sensor.inside_temp)) == float(states(sensor.outside_temp)) }}
but I suppose a template sensor and then numeric state trigger is cleaner
wait, are you saying to use the value template in numeric state trigger, @inner mesa ?
So, something like...
platform: numeric_state
entity_id:
- sensor.outside_temp
id: crossover_morning
above: sensor.inside_temp
Yes. That will trigger when the outside temp becomes higher than the inside temp
Thank you!
is there an elegant way to convert an arbitrary timezone-aware datetime into UTC?
I'm using this at the moment:
{% set dt = '2022-12-18T15:10:00-05:00' | as_datetime %}
{{ dt.astimezone(as_datetime(0).tzinfo) }}
excellent, thanks!
{% set dt = '2022-12-18T15:10:00-05:00' | as_datetime %}
{{ dt.astimezone(utcnow().tzinfo) }}
Maybe this?
Not that elegant though
No elegant way unfortunately
can somebody explain me what data home assistant expects as daily and hourly forecast data? i'm trying to populate a template weather entity. From looking around i understood that the forecast values are no longer stored within the weather entity itself (although populating the "forecast" attribute does show the forecast...) The documentation isn't really helpful either concerning this detail...
It depends on the weather integration(s) you are using.
well..that's the thing: I'm not using any integrations for this. What I want to achieve is setting up a weather entity without having to go through the process of writing my own integration...
You can’t do that. You need to have a weather integration added.
ah dammit... well then time to spin up the environment then 🙂
if {{ events | map(attribute='summary') | join(', ') }} results in Test1's Birthday, Test2's Birthday, Test3's Birthday how would I get the result Test1, Test2 and Test3's Birthday? I have been playing with loops but can't even get close to figuring it out
{{ events | map(attribute='summary') | join(', ') | replace("'s Birthday", '') }}'s Birthday
if you want the and, it's a longer template
yea, was trying to get the and
you just have to separate out the [0:-2] and the [-1] or |last element
I was also playing with | replace with a count but you cant work that backwards
but will that be dynamic?
concatenate everything but the last one + ' and ' + the last one
yes
but then if you sometimes don't want the 'and'...
I always want the and for the last one
using code to generate consistent grammatical language sucks
no
I'm saying divide the problem into the items up to the last one and the last one
it's a list
kind of a stupid example, but:
{% set events = ['a foo', 'b foo', 'c foo'] %}
{% set replaced = events|map('replace', ' foo', '')|list %}
{{ replaced[0:-1]|join(', ') ~ ' and ' ~ replaced[-1] ~ "'s birthday" }}
-> a, b and c's birthday
to be consistent with your birthday theme:
{% set events = ["a's birthday", "b's birthday", "c's birthday"] %}
{% set replaced = events|map('replace', "'s birthday", '')|list %}
{{ replaced[0:-1]|join(', ') ~ ' and ' ~ replaced[-1] ~ "'s birthday" }}
ok, I am trying 🙂
you can add a second comma there if you're a fan of the Oxford Comma
I havent even figured out how to replace ["a's birthday", "b's birthday", "c's birthday"] with my actual sensor info
events | map(attribute='summary')|list
auh so:
{% set events = [events | map(attribute='summary')|list] %}
{% set replaced = events|map('replace', "'s birthday", '')|list %}
{{ replaced[0:-1]|join(', ') ~ ' and ' ~ replaced[-1] ~ "'s birthday" }}
the huge problem I am having is event is an actual variable in the sensor and I dont really understand variables and variables wont work in the template editor will it?
I'm creating two variables right there
I don't know what "variable in the sensor" means, unless you really mean "attribute"
auh hold on. i think the template editor still gave me a clue
Here's a step by step guide
you're describing the most annoying thing in the world 🙂
How can we make this as complicated and time consuming as humanly possible? Now, let's add more steps
paste
{% set <RESPONSEVARIABLE> = {"calendar.lambosino_s_random_events":{"events":[{"start":"2024-07-13","end":"2024-07-15","summary":"Palmerton Super & Sprint"}]}} %}
but change the <RESPONSEVARAIBLE> to whatever you want to set in your actions
then test away
SHUT IT TIM BEFORE YOU SAY ANYTHING ABOUT MY PR
I did propose a new copy template button there... just waiting for merge 😬
Oh I gave up on you a long time ago 😉
Nice, does it create the Jinja or just hte JSON?
{% set service_response = ... %}
Yeah
what I really want is to be able to write a temporary script that can populate the Jinja environment
see now I wanted to have response_variable as a field in the service caller and when you copied it, it would use the variable
I couldn't get the UI layout correct for the response_variable field so I dropped the PR
yeah I just left it hardcoded
better than nothing, but I don't like to deliver things that annoy me still 🤣
problem with being a perfectionist with PRs even though I never do anything perfectly
I got it. Now I just need to look at it and understand it. Thanks!!
you got a link to your PR?
just curious how you did it
so I have gotten to this:
- variables:
events: "{{ birthdays['calendar.family_birthdays'].events }}"
count: "{{ events | count }}"
descriptions: >- #"{{ events | map(attribute='summary') | join(', ') }}"
{% set events = events | map(attribute='summary') |list %}
{% set replaced = events|map('replace', "'s Birthday", '') |list %}
{% if count == 1 %}
{{ events }}
{% else %}
{{ replaced[0:-1]|join(', ') ~ ' and ' ~ replaced[-1] ~ "'s Birthday" }}
{% endif %}
which works perfect for more than one event
but if there is only one event, the state has [ ] around it
awesome!!! Thanks
I've setup a custom piper assist voice (glados) and am able to make it say stuff based on templates in the test voice option in the voice settings, it then tells the values of the templates.
But when I try to make an automation for the voice it reads the template out loud, instead of telling the value of the template. From what I googled I understand this is because I need to use data template, instead of data, but Im struggling on how to convert the automation i made so it works. I created the Automation using the gui, not 100% sure if thats the best way to do it, as the yaml code looks so different compared to other tts automations I have
service: media_player.play_media target: entity_id: media_player.woonkamer_speaker_lamp data: media_content_id: >- media-source://tts/tts.piper?message=+Hello+human%2C%0AThe+outside+temperature+is+%7B%7B+states%28%27sensor.buienradar_temperature%27%29+%7D%7D%C2%B0.++It+is+%7B%7B+states%28%27sensor.buienradar_condition%27%29+%7D%7D+%0Awith+a+windspeed+of+about++%7B%7B%0A++++states%28%27sensor.buienradar_wind_speed%27%29+%7D%7D+km%2Fh.+Tomorrow+will+be+%7B%7B%0A++++states%28%27sensor.buienradar_condition_1d%27%29+%7D%7D.+It+will+be+about+%7B%7B%0A++++states%28%27sensor.buienradar_temperature_1d%27%29+%7D%7D%C2%B0.%0A%0A++++And+incase+you%27d+like+to+know%2C+there+are++%7B%7B+states.light+%7C+rejectattr%28%27entity_id%27%2C+%27in%27%2C%0A++++label_entities%28%27Lightgroup%27%29%29+++++%0A+++++++++++++%7C+selectattr%28%27state%27%2C+%27eq%27%2C%27on%27%29+%0A+++++++++++++%7C+list%0A+++++++++++++%7C+count+%7D%7D+lights+turned+on.%0A&language=en-us&voice=glados media_content_type: provider metadata: title: >2 Hello human, The outside temperature is {{ states('sensor.buienradar_temperature') }}°. It is {{ states('sensor.buienradar_condition') }}
@bold vale I converted your message into a file since it's above 15 lines :+1:
data_template was deprecated in core services nearly 4 years ago, so it is very unlikely that using data is the issue. You may want to ask over in #voice-assistants-archived .
Anybody know why I can't use lists in 'include_entities'? I've tried everything
selector:
entity:
multiple: true
include_entities: |-
['switch.3cf8c52f004b1200_1_water_switch']
I can't use sameline because I'm trying to do a template and it throws a syntax error over the {%
seems like this is for a #blueprints-archived ?
in any case, it looks like it just takes a list
well, it won't take this
{%set ns = namespace(entities=['switch.3cf8c52f004b1200_1_water_switch'])%}
{%for area in areas()%}
{%for entity in area_entities(area) if 'water_switch' in entity%}
{%set ns.entities = ns.entities + [ entity ]%}
{%endfor%}
{%endfor%}
{{ ns.entities | list }
it says 'found None'
include_entities:
- switch.3cf8c52f004b1200_1_water_switch
- switch.someotherthing
that's because it's a multiline template
template viewer shows the list properly
you need to use include_entities: > and then indent that whole thing on the next lines
tried this
include_entities: >
{%set ns = namespace(entities=['switch.3cf8c52f004b1200_1_water_switch'])%}
{%for area in areas()%}
{%for entity in area_entities(area) if 'water_switch' in entity%}
{%set ns.entities = ns.entities + [ entity ]%}
{%endfor%}
{%endfor%}
{{ ns.entities | list }
now you're missing a }
missed copy, not from source
I'll move to blueprints because this may be something blueprint specific
Hi,
I have a template sensor that gives Callander message for my rubbish collection calendar of either Black or Pink (colours of the sacks) is there a way to change the state colour automatically. For example when the calendar message is Black the state colour is black, when the calendar message is Pink the state colour is pink. Hope that makes sense and someone is able to help. Thanks - Jake
Template sensor:
“ {{ state_attr('calendar.rubbish', 'message') }} “
You can use this in an entities card: https://github.com/thomasloven/lovelace-template-entity-row
But otherwise it really depends on the card you're using as to what you can do
Hi all,
I used to have a tempate that displayed the logged in user with {{name}}.
I noticed that this does not seem to work anymore... did I miss a notification on the developer portal ?
that only works in the frontend on cards that have the variable.
@lean yacht I converted your message into a file since it's above 15 lines :+1:
I used it in the mushroom template card. but it suddenly stopped working.
I deleted browser cache and cookies and logged in again, but still not working
what version of Mushroom are you using ? I'm on 3.6.4
the version has nothing to do with it
it's a tepmlate, registered the same way as all other templates
That was it... completely overlooked that
thanks
thanks
@deft ice I converted your message into a file since it's above 15 lines :+1:
a less wrong version, but still not working
@deft ice I converted your message into a file since it's above 15 lines :+1:
Looks like something for #frontend-archived
I don't see any Jinja in there
the problem I'm having is with the syntax of whats inside the [[[ ]]]
thought you'd me more used to the syntax
That's JavaScript, which is used in the #frontend-archived
ah, thanks, I'll go there
where?
@deft ice
"tab_number": "{{ variable.var_tab_number }}"
gonna try
Failed to call service script.turn_on/[object Object]. expected str for dictionary value @ data['service']. Got {'entity_id': 'script.set_monitoring_tab_number', 'data': {'variables': {'tab_number': '{{ variable.var_tab_number }}'}}}
do you know what it is or is more to frontend?
Why not just simply use the call_service tap action?
because I want to use 2 actions, I trying to make the first one work
besides this one I have to
call a dom event with this:
local_condicional_card:
action: set
ids:
- tabs1: hide
- tabs2: show
- tabs3: hide
Well, tap actions are surely something for #frontend-archived
Hey guys. I need help with templates of a certain time. I'm trying to make a sensor that will show the next sunset in plain time, not this example...```
2024-07-15T01:26:57+00:00```
I know how to make template sensors, but I'm out of my depth with changing timestamps to regular time.
Assuming that is a datetime string and "regular time" means "HH:MM" format...
{{ ('2024-07-15T01:26:57+00:00'|as_datetime|as_local).strftime('%H:%M')}}
Thanks. I found this is exactly what I wanted.```
{{ ('2024-07-15T01:26:57+00:00'|as_datetime|as_local).strftime('%-I:%M %p')}}
Hello, been trying to get my power consumption to be logged by HAOS, but struggling with the integral (Riemann sum) sensor
Even after waiting for several hours for the sensor to update stat history it remains at 0.0 kWH
Current setup is:
I have a template sensor exposing the current consumption (W) of my switch and then I use said sensor as the source for the integral sensor
platform: template
sensors:
mainpc_power:
friendly_name: "Main PC Power"
unit_of_measurement: W
value_template: "{{ state_attr('switch.gaming_pc','current_consumption') }}"
Integral sensor confiuration:
Metric prefix: k (kilo)
Time unit: Hours
Input sensor: sensor.mainpc_power
Integration method: Trapezoidal rule
does the template sensor show data? And that second block is not the sensor configuration, those are the attributes of the sensor
Yep, template sensor shows the expected 89.9W
My bad, will adjust it
Riemann kind of has the issue that it only updates when the source sensor changes.
So it doesn't work great with constant value templates.
So if it was outputting a constant 89.9W it won't perceive that change and assume it's sitting at 0?
Well it doesn't assume anything, it's just waiting for the next update of the source sensor to update itself. as soon as your PC shut off it would then instantly jump to the correct value
Is the source sensor changing?
actually I'm sorry I misread and thought your sensor was a constant template. you can ignore what I said.
Wait, so I don't have a constant template?
karwosts meant like a fixed value. Your value is based on actual consumption provided by the smart plug
Ohhh, yeah, based on the state of my switch's reported current consumption
I've adjusted it
All other values were left untouched (save for the name of course)
This has been addressed in 2024.7 with max_sub_interval
Oh neat, didn't realize that made it in 👍
Does anything seem to be amiss with the way I have the sensor set up?
I tried making an integral sensor for a different device that just has their current consumption exposed as a sensor and it reports just fine
I think I've figured it out(?)
The kWh measurement was so low that it was a whole decimal place lower than what I expected
So the value reported just (0.00) needed to be expanded (0.004)
But also switched to left riemann sum
Hi. I have a rest sensor to retreive a numeric value. From time to time it fails (no service, no internet ...) . Is there a way to return "No value" or "None" or "Null".
For me it's a normal case, and i don't want to have errors in the log. The workaround |float(0) will produce wrong statistics. Thx.
You can set the availability: https://www.home-assistant.io/integrations/sensor.rest#availability
Thx @silent seal . I copy/pasted one example and missed that option. I'll give a try! Thx for your quick answer! 😉
is there a way to have a icon via a label template? example in a complication?
hey, i am trying to get the percipitation probability at a specific time, i am almost there, but the timezone stuff is messing with me and i don't know how i can get the correct values
selectattr('datetime', 'ge', now().replace(hour=11, minute=59, second=59, microsecond=0).isoformat()) |
selectattr('datetime', 'lt', now().replace(hour=13, minute=0, second=0, microsecond=1).isoformat())) |
map(attribute='precipitation_probability') | list
}}```
This is my current template, the issue is that the values stored in the weather sensor are at utc 0, but my timezone is utc +2 in the summer and i think it changes to utc+1 in the winter so just subtracting 2hours only works during the summertime. how can i get the correct value independent of the timezone? i want to get the percipitation value from 11 am to 12 am (2 values)
today_at('11:59:59').astimezone(utcnow().tzinfo).isoformat()
That will return 2024-07-16T09:59:59+00:00
BTW, you are only getting 12:00 now
awesome, that works thank you very much
Hi all, can somebody help me with the following:
I have put data from my pyscript into 2 sensors(min_price and max_price) which are updated each minute.
it's a min and max energy price.
With the statistic integration I can allow home assistant to have 2 additional sensors which are a minimum value of the past 15 minutes of min_price and the maximum value of the past 15 minutes of max_price.
How can I trigger this on the exact hour, 15minutes past, 30 minutes past and 45 minutes past the hour?
I know it must be a simple thing but i cant get my head around it.
Template sensor with a time_pattern triggers:
trigger:
- platform: time_pattern
minutes: "/15"
"/15" will trigger on the whole hour, and 15, 30 and 45 minutes
no need for 4 triggers
Ah... right.
Thanks, right now I have the sensors created under my 'sensors.yaml' file.
I must move them to my 'templates.yaml' file and use a trigger with time pattern
Does this change the functionality of the statistics max_age 15 minutes?
Because when I use the statistics it just holds a min or max value 15 minutes, lets say from 14:20 untill 14:35 but i want it to hold it from 14:15 untill 14:30
Is there some mechanism to add an attribute to an entity (via customize.yaml) that has either a template value, or the value of another entity? Or are only static string/number values allowed?
I have a dehumidifier via a custom integration that have a action property, and I was hoping I could use the power draw from another sensor to set it to "DRYING" or "IDLE" according to the docs.
Your Statistics sensors should stay in sensors.yaml since they are part of the sensor integration. The trigger-based template sensor goes in templates.yaml.
Only static values are allowed in customize.yaml. If you want to combine elements of entities you would need to set up a template sensor or one of the other types of template entities.
OK, done!
Is there a better way to have a template sensor trigger on specific hours beyond having a trigger for each hour? e.g.
template:
- trigger:
- platform: time_pattern
hours: "6"
- platform: time_pattern
hours: "7"
- platform: time_pattern
hours: "8"
action: ...
I want to trigger that template sensor to update every hour between 06:00 and 17:00 only.
Trigger every hour (/1) and use a template condition to avoid the ones you don’t want
{{ 6 <= now().hour <= 17 }}
or a time condition: https://www.home-assistant.io/docs/scripts/conditions/#time-condition
🤔 I tried adding a condition, but it caused an error. Can you point me to docs or examples of what you mean by template condition?
I had tried a time condition, to be clear.
It’s on the same page RobC linked, just scroll up slightly
But there’s no reason the time condition wouldn’t work. We can help with errors. But should be in #automations-archived
This is for a template sensor in configuration.yaml, which is why I posted here. I'm happy to move it elsewhere if this isn't the appropriate channel.
Well that is the problem
Trigger-based template sensors don’t accept conditions. At least, a conditions section is not supported.
Okay, yeah... that's what I figured from the error... which is what brought me here.
You can either do a template trigger with all the logic, or you can do the hourly time pattern trigger and put some logic in the template where you are setting the state (and attributes, if you have them).
Let me un-XY this and present my use case to see if there's a better solution. I need to parse the result of the service call weather.get_forecasts with type twice_daily to extract the daily high temperature for a specific time window (my weather entity doesn't support hourly or daily for $reasons). and that time window is only available from 06 to 17:00, so i want to get it each hour (it may change during the day as forecasts update). I want that queryable in automation conditions.
if i query the service outside that time window, it would be unavailable... so either handle the unavailable case and don't update the value or limit the sensor update to those hours were the two paths i could think of.
a template trigger with all the logic
this is probably the sanest approach
Yeah I’m still pondering but that is my gut reaction. Was also hoping someone else would jump in with a brilliant idea.
story of my life right there
thanks for the ideas/pointers/troubleshooting! much appreciated!
No problem
{{ now().minute == 0 and now().hour in range(6, 18) }}
can anyone please help me figure out why this script I was using to make a noise machine isnt working anymore? it starts the playback on the device just fine. But it no longer stops after the amount of time i select from a drop down I created.
== '2 hour' %}\n 02:00:00\n{% elif duration == '4 hours' %}\n 04:00:00\n{%
elif duration == '6 hours' %}\n 06:00:00\n{% else %}\n 04:00:00\n{% endif
%}\n"```
we can't answer that without knowing all the available states for the input_select and where you're using the template.
oh sorry
one sec
I have it set for 2 hours, 4 hours and 6 hours.
and I am using the template in a script that turns the media player on, starts a playlist then has that template as a delay template.
Hi, I've created a statistics for wind speed as follow :
platform: statistics entity_id: sensor.solarws_windspeed_meter name: "Wind Speed Statistics" sampling_size: 10 max_age: minutes: 10
and I want to get wind gust with the follow sensor :
`- sensor:
- name: "wind_gust"
unit_of_measurement: "km/h"
state: >
{{ state_attr('sensor.solarws_windspeed_meter', 'max_value') }}`
Problem, sensor always return null, but I can see in statistics that there is value recorded
Sorry, but you actually hve to provide us YAML. Otherwise it's still a guessing game.
where are you putting each configuration?
I am going to put the actual script I have in here is that ok?
@warped blade I converted your message into a file since it's above 15 lines :+1:
sorry if i seem slow. brain issues
I don't see how that wait template ever worked
that sounds about right. I have zero idea what im dong with templates
You're using multi-line and single line notation for your template.
use one or the other
I have a splitted configuration like this :
sensor: !include_dir_list ../entities/sensors template: !include_dir_merge_list ../entities/template
1st code is in the template folder and is working, 2nd is in sensor but return null
well then statistics doesn't support setting the entity_id.
all i did was create it from the ui and enter the wait template chatgpt made for me. so if theres a better way for me to do it I will do that
and you're probably using the wrong entity_id in your template
Well, chatgpt gave you the wrong format for your template.
i see that now
if you use a template, you need to stick with a single line template or multiline template
not both in 1
ok, sorry i am still new to this and dont understand
multiline: >-
{{ ... }}
singleline: "{{ ... }}"
you're doing
blah: >-
"{{ ... }}"
removed entity_id from statistics but same thing still no max_value
I've triple check this it's ok. I've pasted the value from the wheel in the graph
The only reason it would be unavailable is if you have it in the wrong file, you have the wrong entity_id, or the attribute doesn't exist, or the attribute is none. You've confirmed it's in the correct file. So now you have to confirm the entity_id, attribute, and it's value.
i am double checking everything
From the states dev tools :
state_class: measurement
unit_of_measurement: km/h
icon: mdi:weather-windy
friendly_name: solarws Windspeed Meter
notice the lack of max_value attribute?
in fact i just see that the statistics template is not created :(....
what do you mean 'statistics template'?
you mean the statistics entity?
that's not the correct lingo
it's not a template. A template is only the syntax between {{ }} {% %} and {# #}
everything else is a configuration and it's yaml.
so when you say 'statistics template', that doesn't make sense
plateform sorry !
that's your statistics entity, look in your logs for errors.
no in fact the sensor is from my weather station. I need to check to understand why the statistics plateform was not created. Thx for the road !
make it in the UI
exactly !
but you're making it in yaml...
statistics can be made from the UI. So if you are struggling or don't understand yaml, then make it in the UI.
Then, once the stats entity exists, you use THAT entity_id for your template, not the source of your statistic sensor.
generaly I do all in yaml, but time to time, I made more bug than I resolve 😄
@mighty ledge it was exactly like you said. i changed to using only 1 type of template in there. and wouldnt you know it the friggin thing turns off again.
Good morning- I have a json response from Mealie that is captured at https://pastebin.com/raw/tXH1gjLi . I'm trying to figure out how to get each recipe name listed under the 'items' array to show up in a card. I looked at the restful integration to maybe create multiple sensors, but since it is an indeterminate number of values I can't hard code anything. The desired endgoal is phase 1) get all available recipes to be listed in a card; phase 2) be able to click on them and view the recipe.
So far I have created the following code that prints each available name:
{% for item in my_test_json['items'] %} {{ item.name }} {% endfor %}
but I don't know what to do with it or how to get that into a card. Any help is appreciated
Is there a way to specify the icon color for a template sensor (defined in the UI) ?
More a #frontend-archived question, but if you are using a tile card, you can define the color there.
If you want to be more crazy and change colors depending on status, you would need custom cards/integrations.
Was thinking of having it red when the sensor reported an error, green when in the normal state and a few other colors for other states
I don't know if I've missed a breaking change, but this used to work and now it doesn't
Can anyone notice anything wrong with it?
entity_id: >-
{% set ignore = [ 'switch.bedroom_main_2', 'switch.porch_blinds', 'switch.porch_left', 'switch.hs110_4', 'switch.cinema_tv_internet', 'switch.lounge_tv_internet', 'switch.iot',
'switch.not', 'switch.virus2', ] %} {{ dict((states.switch|list)|groupby('state'))['on'] |
map(attribute='entity_id') | list | reject('in', ignore)| join(', ') }}
service: switch.turn_off
I'm getting the following when I execute the script.
Error running action
not a valid value for dictionary value @ data['entity_id']. Got None
But when I try the template in dev tools not errors are showing. Weird
it's got some weird stuff in it, too
{{ states.switch|map(attribute='entity_id')|select('is_state', 'on')|reject('in', ignore)|list }}
{{ states.switch | map(attribute='entity_id') | reject('in', ignore) | select('is_state', 'on') | list }}
pfft
reject before you select
yeah, thought about that after I hit enter, but I had to beat you
lol
The ignore list would be a lot easier with labels, I would think. label_entities('ignored switches') | ...
I'd only have labels for what I want to target
Same.
then you wouldn't be throttled or traversing the whole domain
I've tried to avoid that a lot in my templates lately.
Thank you both, was just testing what gpt gave as a solution and it seems to be working.
service: switch.turn_off
data_template:
entity_id: >
{% set ignore = ['switch.bedroom_main_2', 'switch.porch_blinds', 'switch.porch_left',
'switch.porch_right', 'switch.hs110_1'] %}
{% set switches_on = states.switch | selectattr('state', 'eq', 'on') | map(attribute='entity_id') | list %}
{% set switches_to_turn_off = switches_on | reject('in', ignore) | list %}
{% if switches_to_turn_off | length == 0 %}
{{ 'none' }}
{% else %}
{{ switches_to_turn_off | join(', ') }}
{% endif %}
Ask here before using ChatGPT. 95% of the time it's old syntax or just outright wrong.
yeah for sure, everyone here is always great help. Just got impatience as it's 4am here 😩 haha
Would you recommend adding anything to improve the above?
Don't know how or where I'd incorporate this
you can tell it's ChatGPT because it's using data_template, which has been deprecated for many many years
and that it was crap
Label the entities in the UI and then use label_entities() instead of the static list in ignore.
Interesting, but seems to still work in ha?
You're returning this to an entity_id attribute in a switch.turn_off service call, right?
Thanks, yeah that would work, though I have many switches and I find it much easier to set only the few I don't want to turn off when I go to bed/leave home. Rather than labeling/listing the vast majourity that I do want to turn off
nah this was a very old one that I think Tinkerer helped me with back in 2020 or so
Yes this was gpt
is just a super verbose way of doing what petro and I gave you
please don't post ChatGPT stuff here
especially not in the context of "this is what chatgpt gave me, please help debug it"
Sure thing 🫡
Though I don't see the harm in posting it if it is in fact working?
Anyhow, all good
besides, I didn't ask to debug that one. Just that this is what gpt spat out and it worked
@nocturne chasm I converted your message into a file since it's above 15 lines :+1:
I keep getting Trigger Update Coordinator: Error executing script. Error rendering template for variables at pos 3: TypeError: '>' not supported between instances of 'int' and 'str'
and I am pretty sure it has to do with lines like this (states('sensor.other_birthdays_days') == '0')
but I cant get rid of the error
you're doing some string math in there
for instance:
{% elif count_other == '0' and count_next > '1' %}
that seems like a fragment of a larger template as I can't see where you're setting count_other and count_next
in any case, everywhere you're using > and == you should be comparing against numbers
and you're currently comparing strings all over the place
let me get you the whole thing because honestly I have tried and cant figure it out. I get exactly what you are saying though
my assumption is that the error is from the first > so I tried to fix that hoping it would move to another operator and I never get past >
all the count variables are intergers so no parens around the numbers?
but states are strings so they should be |int > 0?
Just remove the quotes around all the numbers
You're turning the integers into strings and then comparing them with integers
yup. I figured it out
Hello! I made a simple template that changes an icon based on a location sensor. Is it possible to extract the icon attribute in an entities card's icon field?
You'll want to ask in #frontend-archived
Could somebody please take a look at this trouble I am facing - https://community.home-assistant.io/t/get-pyscript-configured-in-visual-studio-code/750972?u=suvopam
- You literally posted that on the forums 4 minutes ago.
- VSC doesn't support pyscript auto-complete. There is no extension for it.
I see. So jupyter notebook is all using to play around then?
Or just write your code and test it 😉 (That's what I do; I'm not a jupyter fan)
I recently got a oral-b io toothbrush and am trying to make a toggle of "have teeth been brushed". How as a helper preferably would i say if this value has been seen true and stay true until x timeofday then false. So far i have got it to go True if teeth brushed for 2 min but the second any other change occurs the duration changes to 0 and thus false. any help apricated my regular hass guy is on holiday atm
@sturdy tendon Sadly we're not mind readers (any more anyway, not after the last time we tried). Please share the YAML and any errors so we can see what you've done.
all i got so far:
{% set t = states('sensor.io_series_6_7_ff7e_duration') | int%}
{% if t >= 5 %} {{true}}
{% else %} {{false}}
{% endif %}
I would just use the history_stats integration with the very first example in the docs: https://www.home-assistant.io/integrations/history_stats/#configuration
From the Oral-B integration docs, it says it offers this sensor:
Toothbrush state - whether the toothbrush is running, idle.
if you use that sensor and check for whatever the "running" state is (look at
-> States), then if that sensor is greater than zero, the toothbrush has run today
Hi, I need some help. I am trying to have 4 template sensors (temperatures) stored in long-term statistics, and thought it would suffice to add state_class: measurement, as can be seen in https://github.com/FlorianOosterhof/HomeAssistantConfig/blob/main/templates/knmi_edr_temperatures.yaml#L55 , but somehow this isnt working. According to the developer tools indeed the state_class is measurement, but still no statistics..
Does anyone know what I am doing wrong?
Hi guys!
I am a noob coder trying to make his "What is Maxi doing" template code better.
(This is my current messy code for this sensor:https://pastebin.com/dPSm0k89)
I've started by doing a decision tree diagram of how it should work.
Diagram --> https://i.imgur.com/nn2rfvl.png
I am now blocking on how to merge different branches within the Jinja2 template. Specifically all the "No" branches going to "Is there music playing somewhere".
My goal is to reduce the amount of duplicated code and checks.
Is there a way to send the code directly to "anchors" just like we do in windows scripting? (With goto)
Hey friends. I have a list (or an array, whatever jinja calls it) and I want to find the first element based on some criteria. Is there a good way to do that?
the details depend on what criteria and what the list items are
The list items are objects, the criteria is a key on that object
so, dicts
or what kind of objects?
I mean, some form of this is probably what you want:
{{ somelist|selectattr('somekey', 'eq', 'somevalue')|list|first }}
yep, that did it thanks
well, is there a way to do the key where somekey is equal to a list of possible values? In JS it's like ['a', 'b', 'c'].includes('a')
perhaps in instead of eq?
yep, that worked
Hi all, is there a UI helper that can track state of 10 switches and report as binary.sensor when all are OFF/ON, or would this be purely a template territory.
It's a group
But won't a group create a 'group' switch and not a binary sensor?
You just need to use the "all entities" option
I know it's semantics though still, wouldn't want it actuated by mistake.
No, a group is a kind of binary sensor in this case
When you add the group it asks you what kind of group, and that is the domain of the group it creates
You could also do a template binary sensor that tracks your switches state if you really need a binary sensor. Just an additional option for you.
That is what I was thinking would be necessary
@silent seal maybe I am thick, but going for a group, when I select binary sensor, since switches are technically not binaries, they are not selectable.
When I select switch though, I can add them, which is creating a functional switch then.
I must have misread before, I thought they were sensors already
You'll probably be best off with a template binary template sensor
On to 'typing' from clicking.
@undone jungle I converted your message into a file since it's above 15 lines :+1:
Would this be a sensible way of going about it?
I'd probably add an availability as well
Personally, I would label the switches in the UI and then use label_entities() instead.
Hmm.. may I ask why? What's the benefit - wouldn't labels change more often than entities?
Not if you don't change them
But it also means you can easily get all of those devices elsewhere too
And you can use them for auto-entities in a card in a #frontend-archived dashboard.
I've not 'subscribed' to the label 'craze' yet 🙂 Haven't had the time to play around with it.
May be my chance now... 😉
So, the way I would do it is:
{{ (label_entities('your label') | select('state', 'eq', 'on') | list | count) > 0 }}
Bascially, if any switch with that label is on, then the binary sensor will be true. Otherwise, it'll be false.
And availability-wise?
So that any physically ON switch in a unavailable state doesn't make me heat and cool at the same time
Do capital letters matter?
I don't think case matters.
In other words : {{ (label_entities('Floor heating') | select('state', 'eq', 'on') | list | count) > 0 }}
One sec. I can solve for that.
This one handles unavailable / unknown as well.
{{ (label_entities('Switch') | select('is_state', 'on') | list | count) > 0 }}
Needs both correct case and an underscore for spaces
This template does not listen for any events and will not update automatically.
Where did you set the label? On thhe device or the switch entity itself?
You can't put YAML into the editor.
It only accepts templates.
Only put: {{ (label_entities('Switch') | select('is_state', 'on') | list | count) > 0 }} in.
Plus... you can also just use a template binary sensor helper in the UI if you want to 😉
On entites:
https://i.imgur.com/wXf48DD.png
This may be a bug or something I don't understand, but it works differently with and without the underscore in the name.
That might be a bug. I don't know. But it works here: https://imgur.com/a/UstHj5J
label_entities can take the ID or the name as a parameter
Then without the underscore it works just fine, like it does for you
Somehow doesn't like the ID thought...
Eh, then go with the name. Or you could add a label_id() call in there, but that's just fluff.
Yes, they are!
Woot! Throw that into your YAML (or helper in the UI if you want) and let that puppy go!
just one is a little strange, which must be some issue in my entity naming or labeling
Coming back to this for just a second - what did you mean?
Possibly. Like, you have a label at the device level and then use the same label at the entity level, it seems to get a bit weird.
https://imgur.com/a/UstHj5J (Settings > Devices & Services > Helpers > Add helper > Template > Binary sensor)
Didn't realize the wealth of possibilities!
And down the rabbit hole you go…
The only thing that still eludes me is how I should handle availability issues
These Tuya based floor heating switches are at times finicky leading to switch being unavailable while on for an hour or so, and I'll be airing the house while heating.
So do you want to assume unavailable is on or off?
You don’t have to. The select takes care of that already.
If the state of the valve is unavailable, it won’t be selected.
If they are all unavailable, the count will return 0.
Well that is the problem right there.
It needs to be the opposite!
The unavailable being assumed OFF is incorrect for this use case, because unavailable can be ON, which is when I don't want to pump cold air into the house.
{{ (label_entities('Switch') | expand | selectattr('state', 'in', ['off', 'unavilable']) | list | count) > 0 }}
Thank you both so much! My automation is coming along nicely.
Or without expand
{{ label_entities('Switch') | select('is_state', ['off', 'unavailable']) | list | count > 0 }}
I was sure you could do that but it wasn't working for me yesterday. I guess my original entity list didn't have any of those
Switched to left from trapezoidal and it seems more accurate, anyone know why this is?
It depends on what your source sensor data looks like.The docs explain the different methods
Since 2024.7, you also have the parameter max_sub_interval which can improve accuracy in certain scenarios also
So i have a bunch of zone triggers and these trigger notifications tailored to the zone that was triggered in one automation, this works but when my GPS flutters i will get multiple notifications within a minute for entering that zone. Can i use a template to delay the time between repetitions of the same zone?
Ugh, I meant to say this in #automations-archived but couldn't you just use the hold state to do that? So, your entity state trigger on zone.whatever for: 00:01:00 or something like that? So, if you are in the zone for a minute, THEN trigger?
But once the gps leaves the zone it would reset the minute right? Meaning if it’s bad it would never trigger
Correct. It holds the current state. If the state changes, the timeout resets.
You could add a trigger for leaving the zone that uses a 1 minute delay. Then set the mode to single. This would cause subsequent dithering to be non-existent
just understand that you can't leave a zone then reenter it, legitimately
Can someone take a look at my automation and tell me what I am doing wrong? Pretty sure I am not formatting the dictionary call in the highlighted line correctly but can't figure it out.
I see in traces that the value is not being populated
Is the variable defined correctly? Because you used the multi line indicator I think it's a string now, and not a dict. You could just use a YAML mapping.
First time messing around with dictionary (I think) so very well could be incorrect. Can you guide on how to define?
I think you're right. Just define the dict in YAML
Hmm. I may have done that before.
Other solution would have been to wrap it between {{ and }} as that would make it a template and then it would be parsed to a dict.
Hello and happy
Well I didn't mean to post that. I was going to say Hello and happy Sunday to you all. Is there anyone on here that might be willing to share or tell me where I might find a weather template write up using tomorrow.io. So that I can see how t owrite and configure the weather template.
service: conversation.process
metadata: {}
data:
agent_id: conversation.chatgpt
text: >-
keep your answer to two or three sentences. provide your answer as python
dictionary. return only the dictionary and no other data. Do not include
back ticks or the word python. The dictionary should include my original
question with key of question and your answer with the key answer. My
question is: {{ trigger.slots.question }}
response_variable: ai_answer
So I'm using this automation and it appears to be sending me back a python dictionary:
{
"question": "what is the date",
"answer": "Today's date is 2024-07-21."
}
But I can't parse it. I'm guessing it is a string and not an actual dictionary. Any tips on converting it?
what does "But I can't parse it" mean?
Apologies:
set_conversation_response: "{{ai_answer.response.speech.plain.speech}}"
This will give back the dictionary I posted above, but when I try to do:
set_conversation_response: "{{ai_answer.response.speech.plain.speech.answer}}"
I get nothing back. Perhaps I'm not structuring that correctly
tried asking it for a YAML formatted dictionary and still can't pull just the answer value
{{ ai_answer.response.speech.plain.speech.answer | from_json }}
Thanks but getting an error:
Error: JSONDecodeError: Input must be bytes, bytearray, memoryview, or str: line 1 column 1 (char 0)
traces shows this as the changed variable:
ai_answer:
response:
speech:
plain:
speech: |-
question: what time is it
answer: 19:24:09
extra_data: null
Sorry, I forgot to move answer:
{{ (ai_answer.response.speech.plain.speech | from_json)['answer'] }}
ohhhhh
Still no good though. I'm getting this:
Error: JSONDecodeError: unexpected character: line 1 column 1 (char 0)
Got it now. Had to switch back from YAML dictionary to Python and now it is working. Thanks so much
Where can I go to get some help or guidance on my template? Everytime I post in this Discord "templates" under Home assistant no one responds to my request. Please can someone tell me a better place to locate a person who can assist me. I would very much appreciate it.
Try the forum. We're all volunteers who answer what we can when we can
looking back through your post history here, I see plenty of people resonding to your posts 🤷
so maybe adjust expectations
Did you check out the example in the docs? https://www.home-assistant.io/integrations/weather/#service-weatherget_forecasts
I don’t use weather.io but there shouldn’t be anything special with the different weather integrations. The example in the docs applies to any integration.
Hi, i want to turn on a fan is the dew point difference between outside and inside is > 5. Can anyone help? I installed thermal comfort, it calculates the dew points. I tryed to make a helper that calculates basement dew point - 5, but this does not give me any values
This is my template: {{ sensor.keller_taupunkt - 5 }}
{% set duepoint1= states ( 'sensor.thermal_comfort_bedroom_dew_point' ) | float() %}
{% set duepoint2= states ( 'sensor.thermal_comfort_living_dew_point' ) | float() -5 %}
{% if ( duepoint1 > duepoint2 ) %}
result 1
{%else %}
result 2
{%endif%}
@steady spindle thanks... is moves the comparsion in the helper, right? How do i create such a helper?
Sorry... but io am new to HA... i need to find the starting points first 🙂
Helper using a template
yeah ...it's never easy the first time 🙂 -)
But... do you have any idea, why my helper did not work? Do i need the states function and return a result?
let me try. I just gave you a quick and dirty solution. not fully tested. just the idea 😉
forget it... i got it 🙂
{{ states( 'sensor.keller_taupunkt' ) | float() - 5 }}
Now i know 2 ways to solve that problem... thanks 😉
In case you're lazy (like me)... There is no need to add parenthesis to filters if you don't add parameters
So | float is fine
Thankyou for responding and providing the link. I had not seen that before. I was working off some other information.
I've created a custom template sensor which is calculating the fraction between two other sensors and return a float value. However, in history view it is presented as a bar of numbers and not as a graph. I've searched the docs for a suitable device class, but none really fits and there is no unitless "fraction" or "ratio"-class. Any ideas what I can do to get it displayed as a graph?
don't you just need to assign a unit_of_measurement?
Assign: state_class: measurement to your entity. Then you get a unitless numeric graph.
Perfect. That worked. Thank you.
I'm not sure there is a unit when you divide the same unit by itself. E.g. V/V = 1 thus becomes unitless. I don't know if HA have "units" for unitless things. Anyways it worked with setting the state class, so that fixed it for me 😄
Right, makes sense to use state_class. I didn't know that had the same effect
Good day,
I am trying to display the value of an attribute from my entity. I realize now that I am having such a time because its then nested under a property within that attribute. Is there a way to isolate that property?
[2:59 PM]
This is specifically with a Eufy Lock.
{{ state_attr('your_lock_entity', 'attribute_name') }} should work.
{{ state_attr ('binary_sensor.front_door_debug_device' , 'locked') }}
So thats what I have but it reports null
However I can watch it change under properties when I lock or unlock the door from true to false
Its like I need it to drill down one more level into the properties to report the state change but I cant find anything that mentions this online
Why are you doing it that way? Isn't the Eufy lock exposed as a lock entity?
negative. I followed all the walk thrus I could and it reports as a debug device
I was just happy I got it to show up at all
Which integration is it? That seems... weird
The only one I could get to report was Eufy Security but I needed to add a add on to get that to work
But with that the door lock somehow showed up but not as a lock
For clairification. I am a super noob to HA and knowing what I know now I would have bought a few different things haha
This integration, right? https://github.com/fuatakgun/eufy_security
That's weird that there is no lock entity created.
You might want to remove the integration, restart HA and then readd it again. Because something is not right there.
Ok sounds good. Will do
Well from everything I can find it should be reporting as a lock. Its supported. Everything checks out. But it still shows up as the wrong device
Cancel last
I am a moron
lol yes?
lmfao yeah, that does help.
I need to start smoking again.......Good god. Well thats an entire day I will never get back
Eh, it happens. At least you got it figured out.
I think I am basically a Hacker now
I've been searching, but can't find anything specific in the release notes, forums, etc. Has something recently broken old templates? I didn't realize I was using old templates, but on the Latest container, I am getting 3 or 4 of these errors
I knee-jerked my version back to 2024.5.5, and it seems to be working. I believe I was on 2024.4 previously.
The thing that happened the most recently was adding the ability to link template entities to actual devices, but that only applies to ones created in the UI.
My speculation is that there's something in your template that's not valid, and the definitions tightened when the new feature was added, hence the failure.
Cheers, thanks. I think I'll probably have to figure out the right way to convert these
Was hoping there was a quick and obvious issue.
if there's more to the log than that, maybe there is
that usually indicates something that would be caught by checking the config
I have a section of a weather template I am working on. The YAML checker website is saying I have duplicate mapping keys in a particular section. I looked up what is meant by "duplicate mapping keys" and the stackoverflow web site mentions merging parameters into a single list. Except I need someone to look at this section of code and tell me how I am supposed to "merge the parameters" and still get out seperate information for each unique_id. Can I post a section of the code? and how should I go about doing that so someone can take a look?
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.
it just means that you have two identical keys at the same level in the YAML
foo:
foo:
Would you RobC if you are avalible please take a look at my section of code. At the bottom is the error I'm getting from the YAML checker website. What I am gathering is it wants me to eliminate the duplicate mapping key of the unique_id I have for "tree-pollen" if I do that how will the code calculation know the "tree-pollen" is separate from the "grass-pollen" or the "weed-pollen" I'm a bit baffled. http://pastie.org/p/1G97Esp8kXdHJTRJ9VycuU
several issues there
first, you're missing the fact that you need to format the sensor blocks as list items
see this from the example in the docs:
sensor:
# Keep track how many days have past since a date
- name: "Not smoking"
state: '{{ ( ( as_timestamp(now()) - as_timestamp(strptime("06.07.2018", "%d.%m.%Y")) ) / 86400 ) | round(default=0) }}'
unit_of_measurement: "Days"
specifically, the leading "-"
each sensor block needs to be another list item, and you're getting that error message because you just have one big block with the keys duplicated over and over
second, you haven't provided a name for the sensors beyond the first one
third, you just have some bad formatting in there
{% else %}
Unknown
{% endif %}known
{% endif %}
fourth, you can set up a variable mapping in the action to greatly simplify all that
Thankyou for your input and feedback. Do you have a link to some doc where I can look up how to break up the sensor block. And how to setup the variable mapping so that I can simplfy it?
just the docs, really
I'm fixing it for you
somethign like: https://dpaste.org/zCAjn
Hey RobC I really appreaciate your help. And I aprreciate your time in fixing it. That will give something to look at a see what exactly you are talking about.
That is awesome and very simplified indeed! Thank you again!
there's still a bunch wrong with it
I'm going to stop here
mainly because I don't really know what you're doing
you seem to want to get the forecast, but then use other entities as the state for the template sensors
you do one or the other, but not both
I think I got the weather template all figured out. I got the green check at the YAML checker website. So I went and posted it into my configuration.yaml file. And I got the green check mark. I saved it and then I went to Developer Tools and hit "check configuration before I went to restart. And it gave me the following error message.
Configuration errors
Error loading /config/configuration.yaml: while scanning for the next token
found character '\t' that cannot start any token
in "/config/configuration.yaml", line 294, column 1
Ok, never mind. I got it fixed and it all checked out.
that was a tab. only spaces, no tabs
thanks for that. i had some bad zwave device IDs in my config. been awhile since i used the checker script. really should be step one 😅 🫢
@fossil oriole I converted your message into a file since it's above 15 lines :+1:
is it possible to convert brightness_pct to brightness in a template? its for the mqtt.publish service
The first goes from 0 to 100 while the other goes from 1 to 255.
That should work.
Why are you using mqtt.publish() instead of the light.turn_on service? To your question, I can't think of any easy way to convert 0-100 to 0-255 off the top of my head.
multiply with 2.55 and then round to 0 decimals?
To be fair, multiplication is hard 🙂
yeah templating is rather new to me but i could have done a little more research, thanks!
No worries. Just keeping it simple. 😊
Understandable, this was for the AL 'annoyance' i've been having which you helped me with yesterday - it seems to be working like i want it to now but this feels like a very roundabout way of doing so 😝
template ended up looking like this:
{
"color_temp": "{{state_attr('switch.adaptive_lighting_upstairs', 'color_temp_mired')}}",
"transition": "0",
"brightness": "{{(state_attr('switch.adaptive_lighting_upstairs', 'brightness_pct') | multiply(2.55) | round)}}",
"state": "OFF"
}
I still feel like you're following some documentation that tells you to use MQTT (like Z2M) when you can just use native HA service calls (callback to #templates-archived message)
If i were to use the light.turn_on service and set the color temperature while keeping the light off the color temperature doesn't actually change.
with mqtt.publish it is possible to do so, hence why i use that service for this specific usecase
@inner mesa or did i misunderstand what you said? Still pretty new at this.
no, I think you're right
you cannot change the brightness of a light without also turning it on
perhaps you can via Z2M directly through MQTT
or the color temp, I guess. I don't have any such lights, so can't say for sure
Yeah the color option execute_if_off helps and doing it like above keeps the light off
You might need to cast it to an integer if you use it like this
could you elaborate?
ah thank you :)
does the statistics platform only work for the last 10 days in the recorder? I'm trying to use it on a template sensor that is included in long term statistics, I'm only getting very recent data (based on count and coverage ratio). Any way of getting averages from long term statistics?
- platform: statistics
name: Switch Usage Stats Last Year
entity_id: sensor.switch_usage
unique_id: sensor.switch_usage_stats_last_year
state_characteristic: average_step
max_age:
days: 365
Any way of getting averages from long term statistics?
Aside from a frontend statistics card, no you cannot.
Unfortunately statistics integration just uses your recorder history and is completely separate from LTS.
thats unfortunate
I guess my next best option is to run some python script directly on the SQL DB?
There is SQL sensor integration, maybe you can do something with that
How do add multiple state entities here:
{% set state= expand(states.light.kitchen) | selectattr( 'state', 'eq', 'on') | list | count %} {% if state > 0 %} | {{ state }} light {% else %} {% endif %}
that's a weird one
what are you trying to do there?
I mean, I guess this is what you're looking for:
{% set count = ['light.one', 'light.two']|select('is_state', 'on')|list|count %}
Just display, how many lights are in a light group tbh
so basically, it will show multiple groups of lights, not indivual ones
I have an apollo MTR presence sensor, it has 3 definable zones, each zone will show a count of "Zone X All Target Count" which is really helpful for writing conditional automations.
For my dashboard I really want to represent presence as "Detected" or "Clear" to match the rest of my presence sensors. Basically if the "target count" is > 0 the result should be "Detected" if the target count is 0 the result should be "Clear". Do I accomplish this with a "Template sensor?"
Template binary sensor (w/ device_class occupancy or motion, or whatever your other sensors have you want to match)
thank you! digging into that now. Thanks for pointing me in the right direction.
Question, im trying to make a response notification, and where i dont respond (aka timout)
It will the device turn off\
{{ wait.trigger.event.data.action == continue_on_timeout }}
does that work?
got it working! Thanks again.
i did that with the old style templates, unsure if new ones will work yet. haven't gotten back to troubleshoot an issue i had
if anyone cares what I was trying to do: #1129817404957007933 message
Hi all. Just got an aqara G4 can't figure out how to get the button press automations working in HA. It is not a binary sensor / sensor, but instead an event. It shows up on the device, with an updated timestamp when pressed. The event type is single_press. But it doesn't show in developer tools > events when I listen for single_press events. As the event itself is just a timestamp I don't know how to work with it.
I found a blueprint that that I could use to get a notificaton with snapshot from camera and some buttons to be able to open the aqara app, open our front gate etc. But don't know how to trigger from the event.
Trying to make a card that changes its color based off the color of an LED, but im having issues with it. https://i.imgur.com/3XNlJRT.png
it has the brackets and separate lines which arent allowing my code to work
ive been fighting this issue for 3 days holy crap ive exhausted google
No, it doesn't
It's explained here https://www.home-assistant.io/docs/scripts#wait-variable, you need to check if wait.trigger equals none
@tawny coral I converted your message into a file since it's above 15 lines :+1:
Usually contact binary sensors are 'on' when doors are open, so if that is the case for your sensors you would need to look for {{ 'on' in doors }}
Why did you call it "all doors closed" if you want it on if any are open?
true, too many double negatives 😄
so on = open and off = closed
right
{% set doors = [
states('binary_sensor.vardagsrum_altandorr'),
states('binary_sensor.kok_altandorr_mot_baksida'),
states('binary_sensor.entre')
] %}
{{ 'on' not in doors }}
then this would make more sense?
still a double negative, shit
friendly_name: "All Doors Closed"
value_template: >-
{% set doors = [
states('binary_sensor.vardagsrum_altandorr'),
states('binary_sensor.kok_altandorr_mot_baksida'),
states('binary_sensor.entre')
] %}
{{ 'off' in doors }}
This makes sense then
nvm i'm stupid. on in doors is correct... duh
that's not really "all doors off"
that will report if 1 in the 3 is off
{% set doors = [ 'binary_sensor.vardagsrum_altandorr', 'binary_sensor.kok_altandorr_mot_baksida', 'binary_sensor.entre'] %}
{{ doors | select('is_state', 'on') | list | length == 0 }}
that will tell you if all doors are off
You could also make a binary sensor group and just look for it being off.
Ignore their sensor name they actually wanted "binary sensor to on if any of the doors are open"
Which now I think about it could be done a lot simpler with a group.
ok, then just a binary sensor group
@neat crag I converted your message into a file since it's above 15 lines :+1:
Do share the error 😉
Right here 😄 sorry
2024-07-25 09:41:30.993 ERROR (MainThread) [homeassistant.config] Invalid config for 'template' at configuration.yaml, line 29: invalid template (TemplateSyntaxError: unexpected ')') for dictionary value 'sensor->0->state', got "{% if is_state('binary_sensor.garage_sensor', 'on') and is_state('switch.garage_door', 'on') %}\n opening\n{% elif is_state('binary_sensor.garage_sensor', 'off') and as_timestamp('states.switch.garage_door.last_updated') < 5) %}\n closing\n{% elif is_state('binary_sensor.garage_sensor', 'off') %}\n open\n{% else %}\n closed\n{% endif %}\n"
I dont know if "states.switch.garage_door.last_updated" is correct syntax? I searched in the docs, etc. but it seems to be the correct structure.
or maybe i take the wrong approach? all i want to achieve is to check when the switch was pressed the last time and compare it to the current time
Looks lke the problem is a stray ), but I'll let the template gurus help when they're around
thank you anyways 😉
the final goal is to have the garage door in opening or closing state when the button was pressed max 18 seconds ago (door needs about 18 seconds to open and close)
< 5)
^ there
thats the counterpart of this first one -> (now() , do i need to remove the leading one aswell?
i changed it to
now() - as_timestamp('states.switch.garage_door.last_updated') < 5
at least the error is gone, now i get the state "unknown"
{% if is_state('binary_sensor.garage_sensor', 'on') and is_state('switch.garage_door', 'on') %}
opening
{% elif is_state('binary_sensor.garage_sensor', 'off') and as_timestamp('states.switch.garage_door.last_updated') < 5) %}
closing
{% elif is_state('binary_sensor.garage_sensor', 'off') %}
open
{% else %}
closed
{% endif %}
This is the template from your error message, there is no (now() in there
What to have there doesn't work, you need to convert the datetime to a timestamp as well
Or do
now() - states.switch.garage_door.last_updated < timedelta(seconds=5)
Convert like as_timestamp(now())?
Thx i will try that
Thank you sir for your help!
doesn't work
this looks promising
Hi folks, I'm trying to include the numeric state that triggered an automation in the message (I have an automation that includes 3 sensors with an upper or lower threshold in each, so 6* 'or' when triggers. it's close - I can see the values in the trace but not prettily in the message
message: Voltage out of spec ({{ trigger.entity_id }} to {{ trigger.to_state }})
Hi, i have an agenda trigger that tell's me of an upcoming appointment. Now it says just that there is a appointment coming. Is there a way to know for which appointment the trigger is fired? And @arctic sorrel suggested that a template can do that, probably. Could someone suggest on how to do this properly?
When you say an "agenda" trigger, you mean from a calendar?
i've got a template i want to use in a template binary sensor to combine three different binary sensors with some simple rules https://dpaste.org/oT46v#L7
the template editor says this template will only be listening too the first two of the tree sensors. any idea why? if i put the third sensor on its own line, its listed
That's normal. The editor will only listen to the entities in the first condition. However, if that condition is false, then it will listen to the entities in the next condition.
ah right. so i can safely ignore it
Yup.
i currently have templates in configuration.yaml. how do i move them to templates.yaml?
if i add "template: !include templates.yaml" studio code server says it already exists...which is true.
so i suppose im not allowed to include templates of a file, AND have templates in configuration.yaml at the same time....So i need to move.
Just move them to templates.yaml and save the file.
does anyone have a weather forecast template example for precipitation for next 2 hours?
or 1h...i can try to mess with it and see if i can get it working for myself.
yes i mean the calander
that worked, thanks 🙂
always a bit scared stuff breaks by messing with so much code.
I have template sensors pulling the hourly and daily forecasts in attributes.
That JSON can be used in template sensors
....i dont know what that exactly means 😅
https://dpaste.org/hnLUQ
That creates one sensor with all available hourly and daily forecasts as JSON in attributes.
That JSON can be processed in other templates.
do you have a example of a sensor created to pull from that json?
I created a weather entity to show the forecast for tomorrow.
i also tried to modify the weather forecast example to make it work for me...but no luck. this is what i have now:
- platform: time_pattern
hours: /1
action:
- service: weather.get_forecasts
data:
type: hourly
target:
entity_id: weather.openweathermap
response_variable: hourly
sensor:
- name: Precipitation Chance 1h
unique_id: precipitation_chance_1h
state: "{{ hourly['weather.openweathermap'].forecast[0].precipitation_probability }}"```
But it does not create a entity.
It will be triggered on the next full hour
then it makes a new entity automatically?
If the data structure is correct, it should.
That's why I added the triggers for HA start and template reload. To have the data available immediately
Did you reload the templates?
just 4 mins remaining now 😄
does this use a API call as well to reload these?
or does it grab data from whats currently available from the openweathermap integration, and depends on polling time of that integration?
it did not create a entity.
reloading templates in developer settings did not help.
If this is your first template sensor, you need to restart HA.
no success.
my configuration.yaml shows: template: !include templates.yaml
my templates.yaml has:
- trigger:
- platform: time_pattern
hours: /1
action:
- service: weather.get_forecasts
data:
type: hourly
target:
entity_id: weather.openweathermap
response_variable: hourly
sensor:
- name: Precipitation Chance 1h
unique_id: precipitation_chance_1h
state: "{{ hourly['weather.openweathermap'].forecast[1].precipitation_probability }}"
Remove the template:. It's not valid in included files.
that worked, thanks!
now to figure out how to copy this sensor to include 2h results. is that the number in .forecast[1].precipitation_probability?
Maybe forecast[2]?
i guess forecast 0 is the hour ahead, and 1 stands for 60-120 mins? 🤔
and still wondering if this template thing will use a api call on openweathermap or not?
Perhaps. IIRC, OWM has their API response published somewhere. You'd just need to scan that JSON and see what it returns. And yes, it will use api calls.
Just to clarify, the get_forecasts service call itself doesn't count against your number of allowed or free API calls. The integration makes API calls on startup and at a set interval (IIRC it's every 10 minutes for OWM), then stores the data. The service call just retrieves the data from where it's being stored.
Really? Huh... Wasn't that one of the things that was mentioned with forecasts were removed from the state machine?
thanks, so i can put in the template every 1 min refresh, it doesnt matter as the standard polling (and api usage) is 10mins, for openweathermap.
I could be mistaken...
Honestly, I don't remember off the top of my head. I remember the megathread that came out with the change and I could have sworn there was something there about consuming api calls on OWM (and maybe others?). I'm not sure.
That makes much more sense now... And @scenic verge: https://community.home-assistant.io/t/reviving-openweathermap-forecast-entities-using-templates/746966/3 (Rather than triggering every minute)
Thanks for that.
Can i assume correctly that the number in the end of this template is the hour it gets info of?
Does anyone know?
(the forecast[0]) number
That is the number of the item in the list that it is picking out, and is zero-indexed. So whatever list is returned, [0] is the first item, and [1] is the second item, and so on
how do i check that list?
i currently have copies of the following, with different entity name and id, and then just the forecast[1] number changed....but both entity's that were created, return the same precip chance... 😦
- platform: state
entity_id: weather.openweathermap
action:
- service: weather.get_forecasts
data:
type: hourly
target:
entity_id: weather.openweathermap
response_variable: hourly
sensor:
- name: Precipitation Chance 1h
unique_id: precipitation_chance_1h
state: "{{ hourly['weather.openweathermap'].forecast[0].precipitation_probability }}"```
You can return the entire forecast by removing after the word forecast starting with the bracket, so it ends like …forecast }}"
However you may run into the 255 character limit on the state, so I’d recommend you put that into an attribute instead of the state
Yes
so change from platform: state to platform: attribute?
No, keep the trigger unchanged. Keep the state template unchanged. After the state: line, add an entry for attribute: then another line my_attribute: "{{ stuff }}"
Just run that service call in devtools > services, and you'll see the entire list
Well, actually it's a mapping, containing a list
Well that is definitely the easier way to do it