#templates-archived
1 messages · Page 73 of 1
Just tested it with a mock sensor. The reload all yaml configurations seems to work after you've setup at least one sensor with the filter platform. @silent vector
ah, I was just rebooting
I inititially placed my test sensor in the wrong folder, so it was under template
Haha even experts can sometimes be confused with a sensor platform and the template integration😛
This is how all platforms & integrations work. Need at least 1 in the system in order to reload. You need to restart HA if you add it for the first time. Just remember this always
Assuming the integration/platform supports reloading
but all yaml configuration is a bit misleading in that sense, it's all yaml config which for which at least one config entry was already loaded, and which supports reloading 😉
Yep, its been missleading like that from day 1 though
You guys weren't involved in HA when that reload service & page was implemented
But that was a "big todo" back in the day
"todo" as in, people were all pissed that it didn't reload everything
but after finally adding a test config the right way, it does show in the list
Well, the all yaml config button is rather new right? It used to be only the individual reload options
no, it's always been there
what's new is that it reloads only the pieces that need reloading
ah okay
new as in "about a year old now"
before, that button would reload it all
regardless if things changed or not
maybe I'm confused with the option being added under the restart menu
the quick reload option
I just restart because my restart time is ~10 to 30 seconds
reloading comes with issues
especially integrations that don't have unique_id
you get duplicate entities
the only integration I reload are ones with unique_id
Could HA not require to set a unique_id to newly setup entities? Which already is for core integrations that are at least silver on the quality scale
it could, but that doesn't help for yaml integrations that support reloading that don't support unique_id
first there was yaml, then there was the UI, then there was yaml reloading, then there was unique_id for yaml (to adjust in the UI)
there are many integrations still stuck in the first there was yaml stage
all it takes is the integration to get abandoned at any stage, HA still has to support every rendition
Mind you, these stages occured over 8 years
I doubt we will ever have all integrations move from stage 1
unless someone with some gusto goes through and updates old integrations. Which @sleek trail has been doing.
Okay but it should be doable to require it for everything that supports reloading
it is a requirement
yes
but sometimes youre at the point where you need the actual devices to be able to continue
Yep
it's a catch 22
we want things to be up-to-date, but there's only so much crap you can do
so we have really old yaml only integrations that are abandoned, with some things ham-fisted into them.
like reload services
And if the code-owner or someone else with the knowledge to do so doesn't have that device or services it will be in that state until the core-team decides to break it
well it won't be broken
but you're making an assumption that all integrations have code-owners
there are many dead integrations that still just work because nothing has changed
the core team manages the linkings to HA core
so the integration will still be supported, even though it's abandoned
but then you end up with situations like reloading causes duplicate entities
because it's running off an old framework
Well this was all very insightful as to how the reload option works.
I do see the filter entities option now
is the individual domain columns mean "Uses platform"?
yep
for what
to remove -platform loading
oh but this is every integration
also config flow
this just means that it has that platform
oh, so it's not actually meaning "platform loading"
doesn't mention if it uses CONFIG_SCHEMA or PLATFORM_SCHEMA
that's pretty important info, seeing that it's what greatly effects reloading & restart speed
Could add that as well
meh
`more than half of the integrations don't have a config flow
Also take in mind the system ones
Yeah okay minus the default config and some others
Yep, most are one-off random integrations.
Hmm, why didn't it update
ffs petro
I now found a new integration to migrate
I can't test it tho, so that means I have to do it well, or break it and get testers via github
You should do it well 🙂
what one
KEF
I don't know any of it, but it looks doable and the services that it provides can easily be number and select entities at this point
All 55 people will be upset that you removed yaml
DO yamaha
I was checking with Martin about wake on lan last weekend
I can help with yamaha
I have someone who has that
he was upset we removed the discovery integration
The downside of that is you'll end up removing source naming
but I can live with that
What kind of discovery do they do
what do you mean?
I would assume the discovery would be one of the main types
it used to be in discovery
oh lol
meeting brb
it uses SSDP
Is that a contempt for people wanting to use YAML?
Didn't Paulus say roughly 30% opt-in to analytics. So I based on that 150 people will be angry
80% share integration data
so
(55/80*100)/30*100
80% of 30%
Hey All, I have a script with a bunch of conditions that are all iterations of
- condition: numeric_state entity_id: sensor.kw13_temperature above: 29.9 below: 40 sequence: - service: light.turn_on metadata: {} data: color_name: darkblue brightness: 100 transition: 5 target: entity_id: light.master_light_on_off
The only thing that changes in each condition section is the above/blow and color_name values. Is there a way to have a variable called "color". Do the temp comparisons and set "color" based on the correct range then at the end call the light on method with "color" as the color_name value?
Well I waited until the last minute and now I need to convert my weather entities to the new format. I have several template sensors that pull various weather related data for automations but can't seem to get the new format working. I understand I need to first call the weather.get_forecasts service and create the sensor from there but the trigger sensor is not working. I have followed the examples and searched endlessly but can't seem to get it working. I keep getting the error "end of the stream or a document separator is expected". What am I missing? I'm using a templates.yaml file with this inserted directly as the first line.
- trigger: - platform: time_pattern hours: /1 action: - service: weather.get_forecasts data: type: hourly target: entity_id: weather.forecast_home response_variable: hourly sensor: - name: "Temperature in 2 hours" unit_of_measurement: "°F" state: "{{ hourly['weather.forecast_home'].forecast[2].temperature }}"
does /1 need quotes around it maybe?
something like this:
- variables:
color: #values are lower limits
lightblue: 0
blue: 20
darkblue: 30
red: 40
- service: light.turn_on
data:
color_name: "{{ color.items() | rejectattr('1', '>=', states('sensor.kw13_temperature') | float(0)) | map(attribute='0') | list | last }}"
brightness: 100
transition: 5
target:
entity_id: light.master_light_on_off
Thanks for the suggestion. I just added quotes and tested but still receive the same error.
so in you configuration.yaml you have template: !include templates.yaml and the code above is placed in that file?
Correct. Code above is placed in the temmplates.yaml file that is referenced in config. All other templates types (sensors, binary_sensors, etc.) work. I've also tried moving the trigger entry to the bottom of the file and rewriting it but no luck.
is the indentation the same?
Awesome, thanks! I'll give it a try.
I've tried all types of different indentations and mirrored examples online. I assume it's related to that but can't determine what.
I've also considered it's because it is it's own entry when everything else is nested under sensor: or binary_sensor: but couldn't find an answer. I've read that trigger is a list so I put the code block in brackets as well but still nothing.
can you share your entire templates.yaml?
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.
cant you do MPD? (sorry for the continued off topic btw...)
Oh lol, I closed a PR for that last week
moving to UI?
sensor (line 16) and binary_sensor (line 115) should be list items as well
adding unique id
ah. so can at least set some properties in the UI, nice
no I closed it
as in, didn't merge
we don't allow that if it doesn't have a config flow
heck., thats what I figured, hence my responce for the UI...
well, you know what to do next then 😉
graduate
If I need the service: Light.turn_on section to be in a nested condition, where do the variables get instantiated?
before
Does it go:
`- conditions:
condition: ...
condition: ...
variables: ...
sequence
- service: ...`
if you do it inside the loop, they are only available inside the loop
Hard for me to know since the gui doesn't like the variables there but studio code editor accepts it
having this attribute template using an old style group tekst: > {% set last = as_local(states.group.media_players_device_trackers.last_changed) .strftime('%D %X') %} {% if this.state|int(-1) != 0 %} {% set count = this.state %} Tracked: {{count}} -- {{this.attributes.get('home')}} {% else %} Nothing tracked: {{last}} {% endif %} which I want to replace with the label_entities('speler_tracker')
Or, does it go directly under actions: before - Choose:?
studio code editor makes guesses, HA knows correctdly.
you can't instantiate variables in the condition section
and that's your problem
Ah, yeah, I just moved it out under Action: and gui seems much happier
am in a bit of trouble as the former entity of the last_changed was the group.... what would be the most efficient way to check the last changed if the label entities?
Thanks, @mighty ledge
this is the complete sensor for your info, I am trying to replace the bottom 'tekst'
{% set last = (label_entities('label') | expand | map(attribute='last_changed') | map('as_local') | first | default(now())).strftime('%D %X') %}
perfect! thanks a lot. 1 2 groupS down 😉
too bad the auto-entities card using the include for label is reallly slow..... need to add those in the yaml dashboard as the UI editor just wont surface... Hope that will be fixed some time soon on auto-entities
just use a template
no different
filter:
template: "{{ label_entities('label') }}"
I don't even bother using anything but template for auto-entities
just way too much control with templates instead of multiple filters
sure, but templates filter needs some careful crafting if you want 'options'. that's where the simplicity of the include shines.
and yes, the template option is as fast as before, (relying on the core templating engine), so its definitely an auto-entities card thingy for now
I am trying to send an email with the sensor value, I have tested with the following:
{{ states('sensor.apollo_air_1_ce7424_co2.state') }}
I am still getting the following error: expected dict for dictionary value @ data['data']. Got None
if you're using states() function then you don't append .state to the entity_id
Is this correct? the following gives the same error:
{{ states('sensor.apollo_air_1_ce7424_co2') }}
sorry for replying back late. What confuses me, is that when I go into that automation that template code is entered as a line in the visual editor instead of being an actual template like so: https://i.imgur.com/naJCKUP.png
so that leads me to think I'm not entering the template code properly.
Make sure data and target is unchecked on the screenshot you showed me before
and make sure you delete the contents of those fields if you filled them out
I used the template helper so I don’t think it puts anything into the yaml file, right? Should I create the sensor manually instead?
{{state_attr('climate.heat_pump', 'target_temp_high') or this.state | default(0, True)}}
I changed it to this last night and it looks better but I need to see if there are any more bad values in the states table
{% if state_attr('climate.heat_pump', 'target_temp_high') %}{{state_attr('climate.heat_pump', 'target_temp_high')}}{% endif %}
I wasn’t sure if returning nothing would do the same as returning bad values
nothing == unavailable
yes
Thank you! Not sure how I missed that but it fixed the error and created the value. Now to work through the weather parsing.
Thanks , I found the answer ! And it works
I'd like to make a template sensor of desired climate temp based on outside temp and presence. I was thinking of adding an attribute for mode=cool or heat but it looks like you can't do an attribute template for GUI-created sensors. Would it make sense to have a second sensor which is just the mode, or is there a better way to accomplish this other than doing it in the yaml file?
you can add attributes via yaml
did you go to the spartan races?
damn! Nice, I've only done 3. In my dotage I've wanted to do more but I've got some minor injuries that make it doubtful
keep on going!
what injuries? Just barrel through them!
I have my first ultra of the year in 3 weeks
Not looking forward to that one, but I am looking forward to all the other races 🤣
I've only ever done the first stage of the races. Compressed disc was the first one, it's better but I've got a back/hip problem that's chronic, now i've got a shoulder issue, and my right leg is ... weird to say the least. I've been lifting weights for a long time and cycling through various injuries. It's very tempting, the race is a lot of fun though!
oh yeah, that makes sense
leg issues are not great for the races
If you can't trail run, then you shouldn't spartan race
if you can trail run, then you can definitely do the races, just take it slow
Could I get help with syntax on this? {{ state_attr('climate.family_room', 'temperature') | default('76.0') }} (hoping to get 76.0, instead gettign None)
yeah, I've only ever walked fast lol, enjoy yours!
default('76.0', True)
They probably want it without the quotes, though. @atomic oak
will give that a crack, cheers!
hrmm. Invalid config for 'template' at configuration.yaml, line 234: 'entity_picture_template' is an invalid option for 'template', check: sensor->3->entity_picture_template
i wonder if that's why i originally had it under the sensor integration
I'm using a restapi call that returns:
- joke: Why do bees have sticky hair? Because they use a honeycomb.```
If I do ```{{ joke_response['content'] }}``` I get back ```[{'joke': 'My toddler is refusing to nap. He’s guilty of resisting a rest.'}]```
But if I do ```{{ joke_response['content']['joke'] }}``` I get nothing
How do I pull the joke portion out?
Does this work? {{ joke_response['content'][0]['joke'] }}
The outer [] indicate an array I believe.
That's it! So you are selecting the first element ("0") and then within you are selecting the value associated with joke. I thought I was already getting back that element but I get it. Thanks for showing me this
{{ now() - states.sensor.tabletmaster_browser_path.last_changed }}
I'd like to see if the browser path has changed in the last twenty seconds. I know that in the Dev tools->Template area these are not evaluated quickly enough to show this. My question is can I use this reliably in an if statement or is the evaluation time also delayed. Not sure if that makes sense.
Or maybe I should think about this a different way and ask a different question. This is what I want to do in an automation:
- store the last changed time of states.sensor.tabletmaster_browser_path.last_changed in a variable
- wait for 20 seconds
- check the current time against the variable stored time above
- If they match then change to a different page, if they don't, then do nothing.
So the question is now does that last_changed value change immediately on state change and I can do what I'm talking about above with confidence?
[[[ WAIT HERE 20 SECONDS ]]]
{% if changed == states.sensor.tabletmaster_browser_path.last_changed %}True
{% else %}False
{% endif %}
Just use a state trigger in an automation with a for:
I'm not understanding.
The state trigger is the comparison above and the for is my wait time (20 seconds)?
A state trigger triggers when the state changes. If you just want to know whether a state didn't change for 20s, use a for: block
Whatever you're trying to do with this calculation seems like a hack for something simpler
Agreed. I'm still finding my way on most of this.
Right now I have an automation that checks to see if the display device has changed views AND if the display device is in normal mode. It then waits 20 seconds and then switches the view back to a predefined view (clock). BUT, what can happen is that a user makes an assist call for a different thing and the display changes during that 20 second wait. The new view is shown BUT the wait time elapses and it switches back to the predefined view (clock). This makes the new view show for a time much shorter than desired especially if the wait time is about to elapse.
So that's where this comes in. After the wait I want to check to make sure that view has not changed while the wait is active. If the view has not changed then go back to clock. If the view has changed, don't go back to the clock until 20 seconds has passed.
- condition: state
entity_id: states.sensor.tabletmaster_browser_path.last_changed
for:
seconds: 20
I don't think this is right?
sorted it - seems you can just put the template code into 'picture' now. Thanks for your help!
template:
- sensor:
- name: testbin
state: >
{% set is_after_thu = today_at().isoweekday() > 4 %}
{% set is_odd_weeknumber = bool(today_at().isocalendar()[1] % 2) %}
{{ 'Recycling' if (is_after_thu == is_odd_weeknumber) else 'Garden' }}
picture: >
/local/images/{{ 'bin_yellow.png' if is_state(this.entity_id, 'Recycling') else 'bin_green.png' }}
remove the last_changed part. The point is that you're triggering when the state of the entity changes
- condition: state
entity_id: sensor.tabletmaster_browser_path
for:
seconds: 20
I need to remove the 'states.' part in the front too right? This will be true when the state of that entity has not changed for 20 seconds, correct?
Correct
Hey there. I have a YAML formating question for Templates... I was trying to clean up my templates part of my configuration and would like to change the configuration.yaml to:
template: !include templates.yaml
so that way my templates are in a separate file. I was able to do this and it worked for my sensors and my binary_sensor area... But I can't figure out how to format it for a trigger template...
So in my template.yaml, I have
sensor:
- name: "My Sensor 1"
state: "My State 1 Template"
- name: "My Sensor 2"
state: "My State 2 Template"
etc... But not sure how to do the trigger template.
I tried doing this....
trigger:
- platform: time_pattern
...
action:
- service: weather.get_forecasts
...
sensor:
- unique_id: c1a120b6-f065-4cd4-ac83-5b09c62e3e02
name: Daily Weather Forecast
...
But that casuses an error saying there is a duplicate for "sensor"
@rocky crypt template expects a list
So it should be:
# templates.yaml
- sensor:
- name: ...
- name: ...
- trigger:
- platform: ...
action:
- service: ...
sensor:
- name: ...
- binary_sensor:
- name: ...
Does anyone know how to only let this template trigger when the outside temperature was higher before then inside?
platform: numeric_state
entity_id:
- weather.buienradar
attribute: temperature
id: "Buiten koeler dan binnen"
below: sensor.gemiddelde_temperatuur
alias: "Buiten koeler dan binnen "
now it randomly triggers during the day 😦
You could use a template trigger
platform: template
value_template: "{{state_attr('weather.buienradar','temperature') < states('sensor.gemiddelde_temperatuur') | float(0) }}"
id: "Buiten koeler dan binnen"
alias: "Buiten koeler dan binnen "
Thanks very much
Does anybody know how I can use the new labels in a template to check the state of any of the entities marked with a label similar to a group, i.e. {{ is_state(label_entities('kitchen_light'),'on') }} gives an error msg TypeError: unhashable type: 'list'
{{ label_entities('kitchen_light') | select('is_state', 'on') | list }}
@stable vortex ^
thank you
if you want to get a boolean "are there any on?" instead of a list of the ones that are on, the easiest way is probably to add | length > 0 to the end of that.
Still at this. It's becoming a question for #automations-archived but can someone confirm that my condition is correct. Will be true once that browser state goes unchanged for 20 seconds or more?
I will somehow have to make this in a loop as the trigger happens and the conditions are checked and they fail because the wait time has not happened. I know this can be done but I'm not sure the best way to do it
it's not
stop using the non-states method, use states method
states('xxxx.yyyy')
also, conditions don't support templates
Just remove that entire state line
Without it the condition will just check if it has been on the state it is on now for 20 seconds
I'll give it a go. I was doing it in the ui editor and it was showing as required if I remember correctly
Message malformed: required key not provided @ data['action'][0]['then'][2]['if'][0]['state']
When I try to do:
condition: state
entity_id: sensor.thinksmart_lr_browser_path
for:
hours: 0
minutes: 0
seconds: 20
Okay, then it's required. Then you should use a template
According to petro that's not an option:
also, conditions don't support templates
A template condition supports, well, templates
oh yeah.. ha. I'm normally not clear thinking but today is exceptionally bad
template conditions support templates
just not the condtion you were using
Yep. I know what to try now, thanks
value_template: "{{ states('sensor.thinksmart_lr_browser_path') }}"
for:
seconds: 20
So this is the idea but I get malformed error due to the for. I'm really trying to piece different parts together but I guess they don't match.
value_template needs to resolve true
or false
outside that, you should really just check the time on the state object.
{{ (now() - states.sensor.thinksmart_lr_browser_path.last_changed) > timedelta(seconds=20) }}
When we get more complicated how would I do it here
{% set x = [{"first":{"goo":"morefoo","Santa":"Claus"}},{"second":{"tree":"light"}}] %}
{{ x | first }}
Oh I edited a message instead of sending a new one. Yikes lol
When it's nested it appears not so easy to strip the list
You're not 'stripping the list', you're referencing an element in it
What is not so easy about it?
In my second example how would I keep the dictionary and remove the list? Using | first will jut take the the first element vs taking both elements
What you need determines what you do
Again, there is no stripping the list. You can process each element in it
Hm alright will play around with this
{{ x | combine }}
Did it work?
Wow it did
I thought you actually needed to pass it something for it to work
I'm using that in my code to combine dictionaries had no idea it could do this too
so you aren't working on HA stuff then
I have my ways
I think frenck said he might bring combine to spook some day
So hopefully ha will be able to take advantage too
We are all amazed at work right now that this even worked
what's so amazing about it? Ansible has a ton of functionality
We are amazed because we use combine to combine dictionaries but never to do this with a list of dictionaries
Some things ansible does that would be amazing for ha (flatten (spook has this now), combine, json_query)
Wow I didn't know that
flatten was added to Spook FWIW
Yeah it was I guess the difference is flatten can also do multiple levels
Hm not as clean as | flatten(levels=2)
But good to know I wonder what else sum can do
it can't sum dictionaries
Interesting.
Any nice way to check how many levels there are and use sum() that many times? To always “completely” flatten I’ve used a hacky method involving converting to a string and replacing brackets. If there is a better way, I’m interested.
Can someone please tell me whats wrong with my logic? it works until 99 but not when the value is 100
{% set battery_level = '100' %}
{{battery_level}}
{% if battery_level >= '70' %}
mdi:battery-high
{% elif battery_level >= '20' %}
mdi:battery-medium
{% else %}
mdi:battery-low
{% endif %}```
while the value is 100, it gives me "mdi:battery-low"
You are comparing strings
ok how to make it float then?
get rid of the quote marks around the numbers
oh ok that works. Thanks for your help @haughty breach
Hmmm, a recursive macro would work but it would return a string.
Yeah that’s what mine does but it converts it back.
{% macro flatten(nested_list) %}
{{ (('{"items":[' ~ nested_list | string | replace('[','') | replace(']','') | replace('\'','"') ~ ']}') | from_json)['items'] }}
{% endmacro %}
@cerulean matrix I converted your message into a file since it's above 15 lines :+1:
missed comma between flow collection entries (16:2)
struggled a bit to figure out how to troubleshoot templates that use "this" variable in the template developer tool. correct syntax to assign a variable to "this" is:
{% set this = states.light.cct_light %}
I have a Device that I can modify using an automation which modifies a SELECT to change from OUTPUT_HIGH to OUTPUT_LOW - I want to have this available in Home Assistant as a switch so it can be toggled and accessed through the "turn off" service.. Can anyone point me at the right documentation for something like this? This is the YAML of my automation at current..
device_id: 763a96a92040e0eb6fceab52b9b36df6
domain: select
entity_id: a605379fe60aaaccf3166628f2d24590
type: select_option
option: OUTPUT_LOW
I have ~20 devices with the same config which is why I thought a template would be suitable here.. Thanks in advance ❤️
you can't use templates in device actions
you can in service calls, so you need to convert that to a service call instead:
service: select.select_option
target:
entity_id: a605379fe60aaaccf3166628f2d24590
data:
option: OUTPUT_LOW
oh, wait on reading your question better, you want a switch to toggle the select entity
option 1: no templates required
Create a toggle helper (input boolean) and create an automation which changes the select entity to the right option based on the state of the input boolean
option 2: some templates required
Create a template switch to do the same thing, but then in one configuration part
Thanks @marble jackal that's really useful, I'll lookup toggle helpers
Hrm, just thinking out loud, wouldn't a helper be required "per device"? IE I couldn't make a helper for all of these devices? I don't fancy making 20 helpers plus all the additional ones when I add more devices 😛
do you want a toggle per device?
Yes, please 🙂
or one toggle to rule them all?
One per device...
Ideally I want this select to be accessible as if it was a switch.. I wonder if I need to expose it different in ESPHome to HA instead of assuming HA can template this?
then you need to create a helper per device, or a template switch per device, there is nothing in HA to craete multiple entities in one go
Yeah, fair enough 🙂
if it is in ESPHome you could just creeate the switch in the ESPHome config
Do me a favor please, I did do some googling to find a good reference template switch but failed, could you please provide a string I can use in a search engine?
There is a link at the top of the template documentation
that link looks like the thing you need
but again, if it is for ESPHome devices, I would create the switch there
I agree, I'll look into both options
Thanks again for your time man
You got anywhere I can donate you a coffee?
there is a link in my Discord profile if you really want to give me a coffee 🙂
what I wanted to add
with substitutions and packages in your ESPHome config, you can create one config for all 20 devices, so you can manage it one place
as an example, I have around 15 ESPHome relays (Shelly, Sonoff Mini, older gen Sonoff) which all use a config like this:
substitutions:
name: Trapkast
connected_light: light.trapkast
lower_name: sonoff-trapkast
ip: 192.168.2.63
default_button_type: Detached
packages:
sonoff: !include packages/sonoff/sonoff_mini_r4.yaml
in the end the package included here, includes a new package which has the most inportant config part, and is the same for all relays
If I want to change something in it, I only need to do it in one place
The thing I need to wrestle with is I can't yet access the firmware on these devices. I just flashed them with tuya cloudcutter and they aren't available in the ESPHome addon but are available as an ESPHome Device if that makes sense?
You must have flashed a firmware to it, based on YAML you created
Cloudcutter has pre-baked firmware...
I can do an OTA update
okay, well last time I tried it it only had some basic firmware without any actions, which you could use to find the right pins yourself.
If you can do OTA updates, it must be shown in your ESPHome add on
as far as I know
OTA updates are through Web UI exposed by ESP on the device
ah
okay, I assumed using the update entities from the ESPHome integration
do they publish the YAML somewhere?
Anyway, if you want to go the ESPHome route, you might want to ask here for help
I assume selects don't show up in states which is why I can't find it 😛
I'm just trying to ensure I have the right entity and trying this {{states('input_select.a605379fe60aaaccf3166628f2d24590')}} results in Result type: string with value unknown
{{states('select.a605379fe60aaaccf3166628f2d24590')}} also returns same thing
then you have the wrong entity_id
alias: TEST Plug 17 pin mode to high
description: ""
trigger: []
condition: []
action:
- device_id: 763a96a92040e0eb6fceab52b9b36df6
domain: select
entity_id: a605379fe60aaaccf3166628f2d24590
type: select_option
option: OUTPUT_LOW
mode: single
oh is it select_option ?
hrm, nope
that is not the entity id
that is the entry_id
which is used in device actions so you can change the entity_id
TIL 😛
go to `Settings > Devices & Services > ESPHome and then to the right device
there you can click on the select entity and see the details, including the actual entity id
this looks like you are using that exact firmware I was talking about
which is used to find the right pins to base your actual config on
Write an actual switch firmware for this device, and flash it to your device, you can do that in the web interface or using the ESPHome add on. If you then place it in the esphome folder you will be able to edit it there and you will also get update entities so you can update without the web interface
@broken viper I converted your message into a file since it's above 15 lines :+1:
yea that's the long term goal for sure
I think maybe I want "select" not "input_select" for the service
yes
an input_select and select are different domains, and therefor use different service calls
@broken viper I converted your message into a file since it's above 15 lines :+1:
Winrar 🙂 Working!.. Okay now to replicate that config 20 times... 😛
Thanks @marble jackal I'm defo capable to take it from here
Great!
and I agree RE Firmware, that's for next week after Hackaday Berlin 😛
Or maybe a nice project for while I'm there assuming there will be HA presence
I'm new to templates, yaml and jinja, and trying to create a binary sensor that shows when a device tracker is moving. I have this in my configuration.yaml:
`template:
- binary_sensor:
- name: "Car Is Traveling"
state: >
{%- set new_lat = state_attr('device_tracker.niro_ev_19_location', 'latitude') | round(3) %}
{%- set new_long = state_attr('device_tracker.niro_ev_19_location', 'longitude') | round(3) %}
{{ (new_lat != state_attr('binary_sensor.niro_ev_19_is_moving', 'lat')) || (new_long != state_attr('binary_sensor.niro_ev_19_is_moving', 'long')) }}
attributes:
lat: "{{ new_lat }}"
long: "{{ new_long }}"`
- name: "Car Is Traveling"
But, I get this error related to the state: > line (192):
`Logger: homeassistant.config
Source: config.py:623
First occurred: 10:32:21 (1 occurrences)
Last logged: 10:32:21
Invalid config for 'template' at configuration.yaml, line 192: invalid template (TemplateSyntaxError: expected token 'name', got '|') for dictionary value 'binary_sensor->0->state', got '{%- set new_lat = state_attr('device_tracker.niro_ev_19_location', 'latitude') | round(3) %} {%- set new_long = state_attr('device_tracker.niro_ev_19_location', 'longitude') | round(3) %} "{{ (new_lat != state_attr('binary_sensor.niro_ev_19_is_moving', 'lat')) || (new_long != state_attr('binary_sensor.niro_ev_19_is_moving', 'long')) }}"\n'`
Any ideas gratefully received 😦
@marble jackal one final noob quesstion.. My Device named plug5 is called plug5 but loads of entities are stuff like sensor.pin_state_6 -- is it possible to fix that? 🙂
by Fix I mean change to pin_state_5 which is what you'd expect...
the config is most probably created to give it the name pin_state
the number is added becasue that entity_id was already in use
yerp, any clean way to fix that up or just live with it? I can live with it obv but just enjoy a clean config 😛
it's failing on this double pipe in your state template
as it is a binary sensor, the result of the state template should be true or false
not sure what you are trying to output there, but it doesn't look like this will return true or false
no or is or in jinja 🙂
Blimey - no error in the config any more 🙂 Unfortunately Developer Tools shows me that the lat and long attributes are empty strings at the moment
Maybe the device tracker wasn't ready when the template got evaluated
That is because variables are only tied to their local scope. So the attributes are not aware of the variables you use in the state
Aha - thank you
ah, right, should have seen that 🙂
but I don't think this will work
your attribute change will trigger the state template to render again, so after the attribute are changed to the current state, the state template will render again, and the result will always be false
Huh. OK, that's what I was trying to check. Is there any other way to reference the previous values at update so that I can compare them?
I want to use the state transitions of this sensor (false to true, true to false) in a trigger to log the start and end of my car journeys.
Anyway, thanks for helping me fix up what I had. I'll keep it in my config for now to see it fail after my next drive 🙂
Current version, expected to always be false:
`template:
- binary_sensor:
- name: "Car Is Traveling"
state: >
{%- set new_lat = state_attr('device_tracker.niro_ev_19_location', 'latitude') | round(3) %}
{%- set new_long = state_attr('device_tracker.niro_ev_19_location', 'longitude') | round(3) %}
"{{ (new_lat != state_attr('binary_sensor.niro_ev_19_is_moving', 'lat')) or (new_long != state_attr('binary_sensor.niro_ev_19_is_moving', 'long')) }}"
attributes:
lat: "{{ state_attr('device_tracker.niro_ev_19_location', 'latitude') | round(3) }}"
long: "{{ state_attr('device_tracker.niro_ev_19_location', 'longitude') | round(3) }}"
`
- name: "Car Is Traveling"
@marble jackal I just realized a problem w/ my config.. I make the assumption that "Pin" set.. Because during testing I was manually setting it and it sticks but when ESP restarts it is set back to a null value 😛
*mutters inaudibly
you really should just create a proper config for these devices
yeah, I agree, it's just a case of ticking it off before I go away tho
4 hours sorting firmware vs 30 mins HA kinda thing
but the switch turn_on and turn_off sections are just like the sequence in a script
you can add mutliple actions, so you can first set it to the right pin
switches:
plug17:
value_template: "{{ is_state('select.pin_mode_15', 'OUTPUT_LOW') }}"
turn_on:
- service: whatever
- service: select.select_option
target:
entity_id: select.pin_mode_15
data:
options: OUTPUT_LOW
turn_off:
- service: whatever
- service: select.select_option
target:
entity_id: select.pin_mode_15
data:
option: OUTPUT_HIGH
Maybe defining a trigger will stop the attribute change re-evaluating the state? https://www.home-assistant.io/integrations/template/#trigger-based-template-binary-sensors-buttons-images-numbers-selects-and-sensors
Version to be tested:
`template:
- trigger:
- platform: state
entity_id: device_tracker.niro_ev_19_location
binary_sensor: - name: "Car Is Traveling"
state: >
{%- set new_lat = state_attr('device_tracker.niro_ev_19_location', 'latitude') | round(3) %}
{%- set new_long = state_attr('device_tracker.niro_ev_19_location', 'longitude') | round(3) %}
"{{ (new_lat != state_attr('binary_sensor.car_is_traveling', 'lat')) or (new_long != state_attr('binary_sensor.car_is_traveling', 'long')) }}"
attributes:
lat: "{{ state_attr('device_tracker.niro_ev_19_location', 'latitude') | round(3) }}"
long: "{{ state_attr('device_tracker.niro_ev_19_location', 'longitude') | round(3) }}"`
- platform: state
yea that's exactly how I did it
and while I was doing it I wondered if they execute in parallel or series, I imagine parallel
anyway, all done I think now 😛
you should first set it on the right pin, and then change the pin setting
so not parallel
sorry to get back to this, but the last_changed of the (former) group is not correctly templated with this. Consider the group was an all 'on', it would have changed when I turned off 1 of the entities, like this
turning it on again after that should have registered that last_changed . In stead, it seems to return to the last HA OS restart? while the individual entity did register its time correctly
last changed is updated on restart
you're also not sorting the list, like I originally had
you completely removed the sorting
or omitted it
or maybe I accidentally did
regardless, sort it based on last_changed
| sort(reverse=True)
after the map
ok will test, but you posted this: {% set last = (label_entities('label') | expand | map(attribute='last_changed') | map('as_local') | first | default(now())).strftime('%D %X') %}
{% set last = (label_entities('label') | expand | map(attribute='last_changed') | map('as_local') | sort(reverse=True) | first | default(now())).strftime('%D %X') %}
relief!: tekst: > {% set last = (label_entities('kritiek') |expand|map(attribute='last_changed')|sort(reverse=True)|map('as_local')|first| default(now())).strftime('%D %X') %}
o sorry, crosspost there.
thanks again! (edited https://community.home-assistant.io/t/2024-4-organize-all-the-things/712586/532 too) where I referenced our chat here...
i have a commandline sensor running a remote shellscript. That script ends plainly with an echo, spitting out a string. the command works in the HA terminal so i presume it works because i get the string echo'd.
But the sensor stays empty. How do i catch this string?
23 uur```
terminal output
got it! removed unit of measure, because well.... its a string 🙂
Hi all, so i have soil moisture sensor, but it all over the place, I know what on the front end i can see min, max and mean. But i would like to make an automation that is triggered by the mean of the sensor, can someone help? I have something like this
{{ (states('sensor.sonoff_7895e1021e_humidity' , 'mean'))}}
But obviously this wont work
On the front end i have this
chart_type: line
period: hour
type: statistics-graph
entities:
- sensor.sonoff_7895e1021e_humidity
stat_types:
- mean
hide_legend: true
days_to_show: 3
logarithmic_scale: true
So here i can set the stat_type as mean
long term statistics are not extractable for further usage.
If you want a mean sensor, you'll have to create it yourself via the statistics integration
i didnt think it was a long term stat. What i look at the sensor, i see a Min a max and a mean all at the same time. So i would like it to Triger if the mean drops below 19% moisture. Eg, min is 17% mean is 19% and max is 21%, and if i watch the sensor in real time it jumps between 17% and 21% in seconds. but the wetter it gets then the min max and mean are as far apart as 34% 49% and mean at like 41% in real time
What i look at the sensor, i see a Min a max and a mean all at the same time
If you're opening the more-info popup, yes those are the generated statistics. Could be short term or long term, but the answer is the same, you cannot reference them with a template or in any other way.
you need to create an average sensor manually
ok, so if i did this
- sensor
- platform: statistics
name: "Moisture humidity"
entity_id: sensor.sonoff_7895e1021e_humidity
state_characteristic: mean
max_age:
minutes: 10
How would i make that a trigger in an automation, i am confused
that will create a new entity, and the state of that entity will be the mean
then you just use that entity with a numeric_state trigger
and the entity will be called Moisture humidity?
some slugified version of that, I don't know exactly what it will be called
but it will be a new sensor.something entity
Ok, i will give this another try, because it didnt work for me earlier,
Hi guys, I am trying to display the value of a sensor in a template, the Developer Tools -> States ui shows the status correctly, but neither
states: {{states('vacuum.535_burgstaller_m')}}
nor
state_attr {{state_attr('vacuum.535_burgstaller_m','status')}}
shows anything, what am I doing wrong? The entity is an enum entity from Husqvarna automower
Got it to work, and found the sensor, thanks for the help and guidance
Are you using those templates in the dev tools template section or a template sensor? Is it is a sensor, please share the full code of that template sensor
in the dev tools ui
And the entity id vacuum.535_burgstaller_m really exists? Or its attribute status ?
Also: are you talking about the states page or the template page?
the entity shows up in the developer tools -> states ui, I copy the entity name from there, in the 2nd column it shows the current state which is docked
And what exactly are you posting - and where?
dont understand this question, the ultimate goal is to use this as a mail content in an automation, but to get the content right I use the template debug ui
Okay. In some places it needs to be in quotation marks. That's why I am asking.
So you are posting {{states('vacuum.535_burgstaller_m')}} and nothing else in the template debug ui
That should work. My guess would still be a wrong entity id
this it the template ui content
states: {{states('vacuum.535_burgstaller_m')}}
state_attr: {{state_attr('vacuum.535_burgstaller_m','status')}}
this is the output
states: unknown
state_attr: None
I am pretty certain the entity name is correct, in the templates ui it says:
This template listens for the following state changed events:
Entity: vacuum.535_burgstaller_m
also if I go into the states UI and filter for this entity name, it finds the sensor and shows me docked
Are you 100% sure, that the entity id of the vacuum really ends with m?
100%
I see no syntax errors
there are none, I used the same approach for lots of other entities and that worked fine, not sure whats special about this one
it is a device_class: enum not sure if this makes any difference
You say sensor. Might it be sensor.535_burgstaller_m instead of vacuum.535_burgstaller_m ?
device_class enum is only for sensors
FYI, you can get the entity_id from the UI
e.g.
I have the same problem with sensor.535_burgstaller_m_problem_sensor
however the strange thing is that this entity does not appear to be related to the new husqvarna automower integration, the automower integration was previously a HACS integration which was in-sourced
maybe this is an "outdated" entity (I did remove the custom integration)
@quick frigate I converted your message into a file since it's above 15 lines :+1:
can you post a screenshot of devtools > states showing the entity, and your input in devtools >templates
you can use imgur to upload the images
@quick frigate this is unrelated to templates, but the Studio Code Server add-on automatically saves your changes unless you turn that off, and you need to restart HA after you added customize dit the first time. After that you can reload it under developer tools > YAML
Ah I'm sorry, i thought it would be, as it's how info are displayed on templates. Where should I keep this converstion going then ? I apparently did it wrong, I can't restart
with the forecast attribute being deprecated from the weather service, is there any way to get/save the forecast using the frontend UI or do I have to create a template sensor via configuration yaml?
when creating a template sensor from devices > helpers it doesn't seem that there's an option to set a trigger. which is what the recommendation seems to be from https://www.home-assistant.io/integrations/weather/#examples
is there no way to configure a weather service and get the forecast from the frontend? I thought frontend config was the way forward 😕
Holy cow, I just successfully created my first working template using only the documentation and my feeble mind ... sorry for spamming the channel, but I had to share my shocked satisfaction
I found a way to do it all via the UI without having to create a template sensor. added a service: weather: get forecasts and set a response variable, then use the response variable in my template (for google tts) https://imgur.com/a/vEZRsg8
in my template {{ daily_forecast['weather.home'].forecast[0].temperature }}
it's a little weird to me that I define the weather entity in the service but then have to specify it again in the template
daily_forecast:
weather.home:
forecast:
- datetime: '2024-04-12'
as in the example, you can request for multiple entities at once
service: weather.get_forecasts
target:
entity_id:
- weather.tomorrow_io_home_nowcast
- weather.toronto_forecast
data:
type: hourly
response_variable: weather_forecast
the first implementation (without the 's') only returned a single forecast for a single entity, and this new version replaced it
I rebooted home assistant and now a day later those "phantom" entities no longer show up in the "Developer Tools -> States" view. I guess my assumption was correct and these have been entities from the old integration.
However, why they still showed up yesterday and now have "aged out" I am not sure.
can somehelp help me make a template trigger for my temperature sensors when they havent been updated 24 hours? Sometimes my temperature sensors dont update anymore and i havet to reset them ..
value_template: >-
{{ now() - states.sensor.gang_temperature.last_changed >= timedelta
(minutes=180) }}
id: Gang temperature
alias: Gang Temperature
Is this correct?
@hoary wing 180 minutes is 3 hours, not 24 hours
Why not just use timedelta(hours=24)
Besides that the trigger looks fine, but do note that last_changed is updated on a HA restart, so if you frequently do a restart you might never reach 24 hours
That’s why I choose 3 hour 🤣
@naive swan I converted your message into a file since it's above 15 lines :+1:
Hey everyone, I've tried using the template on the docs to get the weather forecast for my morning routine at https://www.home-assistant.io/integrations/weather/ replacing weather.home with the name of my weather entity however it's just showing as unknown on the entity it creates, not sure if I'm going wrong somewhere or if it just hasn't updated yet
what happens when you run the service call in developer tools > services
service: weather.get_forecasts
data:
type: hourly
target:
entity_id: weather.dunedin
response_variable: hourly
It runs fine in developer tools, I get the response
okay
and you wait until it triggered, or did you create it in the last hour?
it will trigger every hour, so until it did, it will show unknown
Ah, i thought you can sometimes force them to trigger by using the service
Good to know i just need to wait 🙂
nope, that doesn't work on trigger based templates, they only update on the trigger
it should have a value now
So this just gives me the high for the next hour by the looks of it. What's the best way to get all the forecast info and not just temperature for the day. switch the type to daily seems obvious but not the rest. Basically after the full read out like the weather forecast used to have to reference in tts.
that's what you asked for in your template: "{{ hourly['weather.dunedin'].forecast[0].temperature }}"
it takes the first item of the forecast (so that's the next or current hour (this differs per integration)) and takes the temperature value from that item
What value are you looking for then?
if you want the entire forecast, put that in an attribute
but that goes against the whole change to remove the attribute in the first place
For the forecast I was after the condition of the day ahead so I could dress/carry items like an umbrella accordingly, as long as getting the high/low for the day and humidity. I've always wanted the chance of rain but no sensors here ever pick that up.
you can take the forecast of the next day out of the daily forecast, it should have a precipitation_probability key
struggling a bit here with the response variable for a todo item list... having this service```
action:
- service: todo.get_items
target:
entity_id:
- todo.huishouden
data:
status: needs_action
response_variable: taken_overzicht
sensor:
- unique_id: todo_huishouden_overzicht
state: >
{{now()}}
attributes:
te_doen: >
{{taken_overzicht['todo.huishouden'].items}}
but it returns this
while the respnse should be this
to my eyes Ive copied a straight config from my working weather forecast sensors, but apperently not.. can anyone spot the error?
Nah, only precipitation, its never had it here but we can't even get live weather data for our flights half the time so its no surprise
you can try another integration
it tries to use the function items() instead of taking the key items
use {{ taken_overzicht['todo.huishouden']['items'] }}
works, thanks!
Not even our government website for it gets it mate, we can never get full metar information, not even for flights 😄
rebuilding some templates to use the label entities, Ive found a challenge: {% set hubs = expand(label_entities('hub')|select('is_state','home')) |map(attribute='name')|list %} works perfectly, for entities that have individually set the label. Now consider a binary_sensor.doors helper, (with the label alert) containing all doors, and the template ```
{% set alerts = expand(label_entities('alert')|select('is_state','on'))|map(attribute='entity_id')|list %}
this expands the binary completely, and when counted, lists all member entities inside that binary (group), and not only the 'on' members.. which is what I am looking for
{{- expand('binary_sensor.alerts') |selectattr('state','eq','on') |map(attribute='name') |join(',') -}} does work (only counts the open doors inside the member binary_sensor.doors, and it has the exact same members as the label entities
can we not iterate the label_entities like that?
can loop: {%- set ns = namespace(alerts_on=[]) %} {% for a in expand(label_entities('alert')) if a.state == 'on' %} {% set ns.alerts_on = ns.alerts_on + [a] %} {% endfor %} {{ns.alerts_on|map(attribute='name')|list}}
that was just a bit more involved than I would have hoped:```
{%- set ns = namespace(alerts_on=[]) %}
{% for a in expand(label_entities('alert')) if a.state == 'on' %}
{% set ns.alerts_on = ns.alerts_on + [a] %}
{% endfor %}
{% set alerts = ns.alerts_on|map(attribute='name')|list %}
{% set count = alerts|count %}
{%- if count == 0 -%} Ok, geen alerts, alles is in orde
{%- elif count == 1 -%}{{count}} Alert voor: {{alerts[0]}}
{%- elif count == 2 -%}
{{count}} Alerts voor: {{alerts[0]}} en {{alerts[1]}}
{%- else -%}
{{count}} Alerts voor: {{alerts[:-1]|join(', ')}}, en {{alerts[-1]}}
{%- endif %}```
In your second example you’re just doing things in the wrong order. You get the entities with the label, which returns a group entity) and then you select those entities which have their state on (which the group does) and then you expand the group and list all the entities
{{ expand(label_entities('alert'))
| selectattr('state','eq','on') | map(attribute='entity_id')| list }}
you dont even need expand
{{ label_entities("alert") | select('is_state', 'on') | list }}
at this point, expand should only be used to expand groups, or to access a state object's properties (context, last_reported, last_updated, last_changed)
all other cases, use select with is_state and is_state_attr
not only is it more efficient, it properly uses generators where expand always returns a list.
i.e. all around better to use
But that is the case here, Mariust has labeled a group entity and wants to list out the group members that are on
I'd probably still go a separate route to avoid expand, but yes then using expand will be ok
{{ label_entities('alert') | map('state_attr', 'entity_id') | sum(start=[]) ...
expand would still work better than that because non-groups would cause issues
Well I still learned something today, thank you
np
this is the exact thing that does not work. it lists ['binary_sensor.deuren', 'binary_sensor.ramen'], and not the open doors/windows inside those binaries
read the remaining responses 😉
ah, sorry... {{ expand(label_entities('alert')) | selectattr('state','eq','on') | map(attribute='name')| list }} works ok indeed, thanks Mecaneck (why didnt I test that...hmm.)
and making that text template much more readable:```
{% set alerts = expand(label_entities('alert'))
|selectattr('state','eq','on')|map(attribute='name')| list %}
{% set count = alerts|count %}
{%- if count == 0 -%} Ok, geen alerts, alles is in orde
{%- elif count == 1 -%}{{count}} Alert voor: {{alerts[0]}}
{%- elif count == 2 -%}
{{count}} Alerts voor: {{alerts[0]}} en {{alerts[1]}}
{%- else -%}
{{count}} Alerts voor: {{alerts[:-1]|join(', ')}}, en {{alerts[-1]}}
{%- endif %}
yeah, cant make this do the right thing. Ive noted the difference in the methods though, in relation to the source they are used on.
summary:
I would expect the 2nd one here to return what you want
the names of the binary sensors within the entities labeled alert
but maybe I missed some parts of the discussion 🙂
@dry sierra I converted your message into a file since it's above 15 lines :+1:
If I define a template sensor in configuration.yaml using a trigger (platform: state), should I be able to reference trigger.from_state and trigger.to_state?
`template:
- trigger:
- platform: state
entity_id: device_tracker.niro_ev_19_location
binary_sensor: - name: "Is GPS Active"
state: >
"{{
(state_attr('trigger.from_state', 'latitude')
!= state_attr('trigger.to_state', 'latitude'))
or
(state_attr('trigger.from_state', 'longitude')
!= state_attr('trigger.to_state', 'longitude'))
}}"`
- platform: state
yes, you should be able to do that
yep, it works now as I was aiming for
trigger.from_state is an object, it's not in the state machine. Use it as trigger.from_state, if you want attributes trigger.from_state.attributes.latitude
btw, 1 of my alerts was binary_sensor.meteoalarm_brabant, which is a core integration binary. It does not have a unique_id, so I can not set a lable on it.. funny we now need to make a template duplicate for that to be able to do so
but after you fixed what petro mentioned the binary sensor above will basically always be true, because it will trigger on a state change of the device tracker, indicating it changed positition so at least longitude or lattitude changed
unless you change the name of the entity or something like that
check the integration and make sure it still doesn't allow unique_id's
I went back through all my 'old' entities that didn't allow unique_ids, turns out in the past few years unique_ids were added to all of the yaml configurations.
no, unfortunately not https://www.home-assistant.io/integrations/meteoalarm/#configuration
Ive asked Joost and he did have a look, but the integration requires a config flowe to be able to add unique_id (or so I remember)
@sleek trail looks like you have another candidate for UI integration https://www.home-assistant.io/integrations/meteoalarm/#configuration
I can't remember you asked this
would really be great if that would migrate
i think I listed a few integrations I use that didnt have UID yet....
Schrodinger's conversation
heavily stressing the 'think' there
You dont have an active recollection of that.....
it's a Dutch inside joke....
maybe even copied from abroad, since it was used by our heavily politically spinned Prime Minister some time ago, and everybody is using that now
Currently new features are just on a low burner atm
anyways, back to the topic of template copying another entity: do we have a fixed stategy for that? or should I simply do state: > {{states('binary_sensor.meteoalarm_brabant')}} and for the attributes list (which is rather extensive) simply refer to the original. How would I otherwise do that without hardcopying all attributes
a bit silly but it does the job (for now)
currently still yaml only:
Alert,
File,
(old) Group,
Local file,
Manual alarm control panel,
Meteoalarm,
Mold indicator,
Nederlandse spoorwegen,
Nmbs,
Sun
you were already active in this FR so I know you've seen it, but being able to define labels in YAML would allow you to label those entities until the time where they get converted
https://community.home-assistant.io/t/labels-allow-defining-in-yaml/712673?u=mekaneck
Nederlandse Spoorwegen is one that gets relevant soon
ha, that is a PoV I did not think of yet in regards to it indeed...
Alert is all but deprecated it won't be converted.
why is that? tbh, its quite active in guarding the mem %... had it kick in regularly, to safe the instance
or warning for the obvious low mem on our devices
I guess because its a blueprint in disguise
From Frenck:
The core team has discussed the alert integration and related PRs recently. We don’t want to expand the alert integration any further. Our future plans for this integration are to replace it with blueprinted automations. Once we have evolved our blueprint feature we plan to deprecate this integration.
ok, well, thats cool. if the Blueprint would provide the same options (or better), that would probably be my first time to test that. Still have no use for any of the BP's floating around so far.
If I read the alert docs, you can already migrate this to a blueprint
I'd wager they need to move away from notification services and move to notification entities, that's why it's not a blueprint replacement yet
Blueprint doesn't provide the helper entity though
you can always create an automation yourself, it's not so hard to replicate an alert in an automation
You can add an input_boolean yourself, but it's a bit extra work
helper entity?
alerts create an alert. entity
@marble jackal yeah, but why, if we have the dedicated integration do it 😉 Ive never given that any thought
can put em on your dashboard
aah right
because soon you maybe not have it anymore 😛
sure, then we must, would be very very breaking though....
you can trigger on home assistant start and on the trigger entity going to the wanted state, and then use a repeat to send a notification every x minutes
a little bit more work is needed if you want different times between the notifications
the problem that yall are glossing over is that the only way to use a notification in a blueprint currently is to have the user type out the notification service manually or use a device_action
major changes to notifications need to happen in order to replicate alerts in blueprints
specifically, we need a generic notification service and a notification selector
oh yeah, I'm not talking about the blueprint now, more like how I should tackle it in an automation
because our current course (device selector) is extremely limited
for a blueprint you could use an action selector
Given the current complex options of the Alert integration, and Frencks quote there, I think it is safe to assume it is going to be a while before Alert is deprecated... lot of 'future', 'once', 'plan', 'evolve'..
Yeah I didn't mean it was imminent, what I meant was that they aren't accepting enhancements anymore.
sure.
it does make it a bit more versatile, now you have to create a tts notify service if you want to send a tts using an alert.
besides that, it is such a fundamental integration, that it would take a very well implemented replacement to not have the community go revolting 😉
well, it has been in my system from the beginning, and I suppose many use it?
No?!?
wow, I never would have expected that
haha, well, the way I did it, when starting HA, was walking the list of core Integrations alphabetically, checking what I could use 😉
lol, I would love if people did that
sadly, people now plug it in and immedately ask questions here or on reddit, completely skipping the website
guess I am not a true heavy user of complex Alerts, and smth like this could be worth the trouble of migrating to a triple state binary template sensor and automation```
alert:
ram_too_high:
name: Ram Usage > 85%
entity_id: binary_sensor.ram_too_high
can_acknowledge: True
repeat:
- 5
- 30
- 60
notifiers:
- mobile_app_marijn```
maybe even combine that with a trend sensor, (which btw should be added to the list of non UID...)
btw, Ive just found out that reload all Yaml does not reload Alert. Does it only reload Yaml with unique_id....?
It's misleading. Reload all is equivalent to clicking each of the reload buttons on the yaml page. It only reloads things that can be reloaded.
I actually tried to add reload for alerts, and it was denied 😢
without adding config_flow, or just because they want it to die?
I wrote it once, and then in feedback got asked to rewrite the entire thing using helpers/collections. Then after rewriting it all, I was then told, nevermind they just want it to die 😂
Then someone else came along 3 months later and rewrote that exact same PR again 😂, and denied again.
Oh, you want to get started with HA development? Here's your first exercise...
you not only get to learn how HA integrations are structured, but you're also introduced to the somtimes arbitrary and capricious decisions from core 🙂
yeah, I figured it would reload all yaml that did Not have a UI just now.... apparently not. It did blow up the mem% again, so that issue is still alive.
would be a nice touch to add that very useful (dare I say crucial) info to the otherwise obvious text in the Reload panel. It's just a guess now (some can be reloaded), unless you know it does what it does.
I've defined a binary_sensor with two attributes that I expect to be decimal numbers, but looking at them in Developer Tools they seen to be double double quoted:
d_lat: "\"-0.036740999999999246\"" d_long: "\"-0.0014339999999999353\""
The attributes are defined like this:
attributes: d_lat: > "{{ trigger.to_state.attributes.latitude - trigger.from_state.attributes.latitude }}" d_long: > "{{ trigger.to_state.attributes.longitude - trigger.from_state.attributes.longitude }}"
How can I make the values just be numbers?
when you're using multi-line yaml strings with the > or |, you shouldn't quote them
the > or | acts like quotes, so any quotes you put inside them are included in the resulting string
Thx - trying now!
attributes: d_lat: > {{ trigger.to_state.attributes.latitude - trigger.from_state.attributes.latitude }} d_long: > {{ trigger.to_state.attributes.longitude - trigger.from_state.attributes.longitude }}
Always Save File + Restart Home Assistant if I change configuration.yaml?
Thx - numbers now as expected 🙂
You can reload template entities from developer tools > YAML
How can add 120 seconds to the current time? I know I can do {{ now() }} to get the current time, but how can I add time to it? I'd like to abe able to use this value to set a calendar event start time as the now() value and the now() + time as the ending time.
You can add a timedelta object to a datetime object.
now() + timedelta(hours=2, minutes=30)
Rock on! Thanks
usecase: need to condition/wait_template that 2 windows (label) in 2 different areas in the same floor are closed before continuing. There is no way we can use the label entities directly in the floor, nor is there floor_entities. What am I missing here.. I might be better off hard coding those 2 windows....
I have these```
{{floor_areas('woongedeelte')}}
in 'woongedeelte' there are 2 areas:
{{area_entities('woonkamer')}}
{{area_entities('eetkamer')}}
in those areas, I need to find the state of
{{label_entities('schuifpui')}}
should I simply do {{['binary_sensor.schuifpui_groot_contact', 'binary_sensor.schuifpui_klein_contact'] |select('is_state','on')|list|count == 0}}..... and forget about all new options?
{{ floor_areas('woongedeelte') | map('area_entities') | sum(start=[]) | select('in', label_entities('schuifpui')) | list }}
yes, thank you. that lists the 2 entities correctly. have to consume that though.... and, I've seen the | sum(start=[]) more frequently recently, what exactly does that do
seems a terribly convoluted way to find the label_entities('schuifpui') in the floor 'woongedeelte'
{{ floor_areas('woongedeelte')
| map('area_entities')
| sum(start=[])
| select('in', label_entities('schuifpui'))
| select('is_state','on')|list|count == 0 }}``` does check correctly
this would be so much more obvious: {{label_entities('schuifpui') |select('in',floor_areas('woongedeelte'))|list}}
it combines lists
can also do {{label_entities('schuifpui') |select('in',area_entities('woonkamer')+ area_entities('eetkamer'))|list}} but that too is a but hacky (and still requires me to hard code the area names)
guess it would also be nice if we could do area_entities('living','dining') or maybe in the list. that would allow us to do in area_entities(floor_areas('woongedeelte'))... hope these functions will see some development in the future
I expect floor_entities() will be added
would that expand the entities in the areas inside that floor? I mean we dont have floor entities? only areas...
{{ now () }} produces output 2024-04-13 08:53:00.413137-05:00 I am trying to use this to set a calendar event and would like the format in yyyy-mm-dd hh:mm:ss format. I see this referenced in the docs:
https://docs.python.org/3.8/library/datetime.html#datetime.datetime
But I'm not sure how to format. Is this the way or is there some other way (fstring?) to output in that shortened form?
{{ now().strftime('%Y-%m-%d %H:%M:%S') }}
Keep in mind now() returns a datetime object and when you convert it to a string it is shown that way you displayed. But it is not actually a string itself. The strftime() method will convert it to a string in the format you specify.
Yes
but for the time being, this is a substitute:
{{ floor_areas('floor') | map('area_entities') | sum(start=[]) }}
@bronze prawn just output the DT object to the datetime field. It doesn't need to be formatted with anything special.
it's smart enough to handle datetime objects
so when I set them, e.g. 2 hours in the future {{ now() + timedelta(hours=2) }}
Thanks. I had tried that and my automation did not trigger. I was thinking it may be because of the date format but it may be that it is not as percise as I am wanting. I was trying to do a 90 second timer with the start set as now and the end as now + 90 seconds. I could see that the calendar had the right time in it though it did not list seconds. The service call does allow for setting seconds but maybe it is not actually using them.
I think this calendar method can be used for things like "Remind me at 6:30pm to leave for dinner" and "Set an alarm for 5:00am tomorrow" but maybe not these timers.
Great to know. So the two use cases above can be done using the calendar. I'm sure it'll be fun to get assist output into the correct day/time format I'll need to feed to calendar but technically it should work.
The timers are a different story. I had a chance to talk to Mike about it and he said they are wanting to create a way to have timers without the need of helpers. I think lots of folks use timers with their current voice assistants. I know we do.
{% endif %}```
I am getting the mode value from a custom sentence. I am wanting to compare if the variable being entered matches any of the three above and if so then this condition is true in a template value condition. This does not equal true when I use any of the above. I have an else that returns what I said. I am receiving back the 'normal', 'music', 'hold' from that else condition.
Am I comparing these incorrectly?
{% if (mode == 'normal') or (mode == 'night') or (mode == 'hold') %}
true
{% endif %}
I made an assumption that this would return true if it was true but it wasn't. Adding true fixes it
You could do {{ mode == 'normal' or mode == 'night' or mode == 'hold' }} - that will result in either a true or false value.
(assuming mode is set)
or even shorter, {{ mode in ['normal', 'night', 'hold'] }}
Now we're talking! Thank you!
Please understand why. You explicitly weren't returning anything at all in your original version
Yep. I realized it after a bit. The condition within the block was true but I wasn't doing anything with it so the automation was not getting the true back that it needed.
So this is really cool and I'm already trying to extend it. I'm trying to add functionality for voice to remove an item from the shopping list. Using this I can ensure that the item is in the shopping list. Assume that 'Eggs' was spoken:
And this returns true. The problem is matching the case. Is there a way to do a compare like this but make it case insensitive? What I really need is to check if the item is in the list regardless of case, and if so, return that value because I need to match exactly for the todo list service remove.
{{ 'Eggs'|lower in ['foo', 'bar', 'eggs']|map('lower')|list }}
-> True
in other words, make everything one case
Ah yes. Works for sure. How what about getting the 'true' value out? Case sensitive to pass to the service?
I guess I can figure out what element it is and then return that one?
you mean "true" instead of "True"?
it's just a boolean
oh, you mean the value without converting the case
I apologize. No I mean if the item is stored as 'Eggs' in the list. I know if we put input match to lower and whole list to lower we know it is in the list. How do I get the real name out
Correct. I'd like it as two steps. Is it in the list? if so, then get the stored value out to send to remove
{% set items = ['foo', 'bar', 'eggs'] %}
{{ items[(items|map('lower')|list).index('EGgs'|lower)] }}
-> eggs
Wow. That is REALLY cool!
Let me make sure I understand. You are doing a return like items[2] but it is evaluating the part between the [] to get the index value right?
Yes
really cool
I'm getting the index based on the lowercase comparison and then returning the real value at that location
You probably want a |default() in there to catch the case where it doesn't exist
And I guess it gets the first one if there are two of the same
@forest ferry I converted your message into a file since it's above 15 lines :+1:
without bot conversion....
Hi, I'd like to apply my auto-entities template below to 6 sensors (number.doorlock_front_user1, number.doorlock_front_user2, etc)
could you assist with the loop syntax I should be using? Thank you!
code above.
BTW Newbie to Discord, any way to avoid the Bot conversion for code over 15 lines? thx
@forest ferry I converted your message into a file since it's above 15 lines :+1:
use https://dpaste.org/ or similar to paste long code and then share the link
Does anyone know how I can create a template sensor based on any of a number of other sensors being in a particular state? Basically I want to do the following, but I know the asterisk wildcard doesn’t actually work:
Problem
{%- else -%}
OK
{%- endif %}```
You better use a template binary sensor with device class problem.
{{ states.plant | selectattr('state', 'eq', 'problem') | list | count > 0 }}
{{ states.plant
|selectattr('state', 'eq', 'problem')
|list
|count > 0 }}
Oh...
Well...
Too late 
The problem is that the plant. devices provided by the Plant Monitor custom integration does not seem to provide binary sensors for the overall plant state. The device itself seems to get set to the state “problem” if any of the device’s entities are outside specified thresholds.
You create a binary sensor. And with device class problem, it will show OK or Problem automatically
Yeah I just didn’t know how to pull the states from all plant. entities until @marble jackal and @marsh cairn provided the above code. 🙂 I try to read the Jinja instructions for templates, but without a background in programming, it all kind of melts my brain. I’m slowly, slowly starting to improve at this stuff… Many thanks for the help!
If you TheFes' template directly behind the state:, you need to put quotation marks around it.
Or a > behind the state:, if you prefer the multi line one.
@marsh cairn my apologies; I don’t quite understand what you’re saying
Example 1:
template:
- binary_sensor:
- name: "Dead Plant"
state: "{{ states.plant | selectattr('state', 'eq', 'problem') | list | count > 0 }}"
device_class: problem
Example 2:
template:
- binary_sensor:
- name: "Dead Plant"
state: >
{{ states.plant
|selectattr('state', 'eq', 'problem')
|list
|count > 0 }}
device_class: problem
So far @marble jackal ‘ code seems to sort of work in the binary sensor template, except it evaluates the same whether I leave it as > 0, < 1, or == 0. It always shows “OK” in the preview.
Are pictures prohibited here? Tried sharing a screenshot but no dice.
Please use imgur or other image sharing web sites, and share the link here.
Image posting is blocked in most channels to discourage people from sharing text as images. Sharing text as images assumes that everybody sees the world as you do, which isn't the case. Some people are colour blind, or have visual impairment that means they can't make sense of an image of text.
Ah. You are using the helper
As Home Assistant moves more and more to the UI, I’m trying to keep everything as vanilla as I can.
Is there currently a plant with a problem?
Oh FFS the tick marks from the markdown got pasted into the template box 🤦♂️
I removed the tick marks and it works now.
👍
There isn’t a plant without a problem. There’s a reason I’m using plant sensors. 😆
Thank you so much folks. I really appreciate the help with learning stuff.
Mine would always just say 'problem'
You can fix it with a template 
I know that you can take time and put it into the am/pm format like:
{% now "%B %-d, %Y %-I:%M" %}
But is it possible to do the reverse? I have time as 6:00 PM and want to get it into the military time hh:mm:ss format to feed it to a service call to make a calendar event
Old chatgpt gave me this:
{{ "%02d" % ((time.split(':')[0]|int + (12 if "PM" in time else 0)) % 24) }}:{{ time.split(':')[1] }}```
but it returns:
```18:00 PM```
The time part appears to be working but I don't know why it's adding that PM portion
if you split on the ":", then split[0] will be 6, and split[1] will be 00 PM
Use strptime()
{{ strptime("6:00 PM", "%I:%M %p") }} -> 1900-01-01 18:00:00
{{today_at(strptime("6:00 PM", "%I:%M %p").strftime("%H:%M")) }} -> 2024-04-13 18:00:00-07:00
Via any method you’ll have to add todays date if the intent is to get a datetime object
{{ strptime(today_at().date() ~ " " ~ "6:00 PM", "%Y-%m-%d %I:%M %p") }}
That's super handy. So to finish I need the date. I think I can pull that from now() as the user won't supply it. I am trying to get it so that someone says "Set a reminder to walk the dog at 6:00 PM", I can convert that time text like you are showing but I'll need to get the current date and have it all formatted like:
service: calendar.create_event
data:
summary: test
start_date_time: "2024-04-13 18:00:00"
target:
entity_id: calendar.assist
You are one step ahead of me. That is absolutely perfect. Let me see if I can make this happen now. Thanks to you all.
I think karwost’s edit is cleaner
Do I want/need to have that ending offset value in there?
service: calendar.create_event
target:
entity_id: calendar.assist
data:
summary: "{{trigger.slots.action}}"
start_date_time: "{{today_at(strptime(trigger.slots.time, "%I:%M %p").strftime("%H:%M"))}}"
end_date_time: "2024-04-13 20:00:00"
I'm scratching my head. I have the response showing me the template value being used for start_date_time and it appears like this:
Please remember to take out the trash at 5:30 pm 2024-04-13 17:30:00```
But yet the calendar event is being set for tomorrow instead of today at:
April 14, 2024 at 12:00 AM - April 15, 2024 at 12:00 AM
It's like it is setting it to an all day event but I am not specifying that option.
service: calendar.create_event
target:
entity_id: calendar.assist
data:
start_date_time: "2024-04-13 20:00:00"
end_date_time: "2024-04-13 20:30:00"
summary: test
This one works when setting from dev tools. The only thing different is the use of the template ohhhhhhhhhhhhhhhhhhhhh
single/double quotes
Nope. That did not fix it
service: calendar.create_event
target:
entity_id: calendar.assist
data:
summary: "{{trigger.slots.action}}"
start_date_time: "{{today_at(strptime(trigger.slots.time, '%I:%M %p').strftime('%H:%M'))}}"
end_date_time: "2024-04-13 20:00:00"
Now it does not set the event at all and gives the 'Done' response which is an indicator that something is wrong
I'm not sure the reason but your version works without problem.
How can I make a home assistant sensor to make the states of an input select more readable. I want: unplugged, idle, paused, detached_overload, job_ongoing, job_completed = Unplugged Idle Paused Overload Running Completed
You can make the options whatever you want. Why did you choose the ones you don't want?
There are many ways to create a template sensor to transform the state
I am using a blueprint that required this syntax, But I don't want to see it this way in the ui
@quiet creek I converted your message into a file since it's above 15 lines :+1:
You won't be able to fix that
Why is that? Is it because I can't combine multiple entities? Maybe I could use a conditional card
Because you're just setting the time as a string
The frontend only displays timer values by playing games and only with actual timer entities
I don't even see where you would expect the remaining time to be shown based on your template
hey all, I am trying to measure water usage for watering my plants/lawn. My current setup is that I have a moen flo to measure my total water usage and then i have a smart valve outside my house to automatically water the plants. I was thinking that I could use a utility meter to only record the water usage while the state of my valve was 'on' but I'm not exactly sure how to accomplish that. Any help would be greatly appreciated!
@fresh pulsar I converted your message into a file since it's above 15 lines :+1:
can I access from_state on a template light? Or any other way to access the previous state
You can use this to access the current state (which will be the previous state after the template is rendered)
Mmm I don't think that's gonna work then. I'm making 2 separate lights each using 2 channels of an rgbw light. To turn the first light off but not the other, I use turn_on with rgbw_color command: 0,0,current,current. This way the first light that uses red and green is turned to 0, but the original light is still on and the values for the second light (blue and white) don't change. Problem with this is that when I try to turn the first light back on it sets r and g to the last known value, which is 0
I could default to a higher brightness but ideally I'd restore the previous value
Only way might be a helper I guess
Unless there's a way to arbitrarily access previous states (e.g. state(2) returns the third last known state)
yeah, for that you'd need a helper to store the last used "on" state/level.
Hello all, I am sure this may have been asked a million times... but, I am trying to add a custom sensor template to the energy "individual devices" list and it does not appear there
I have compared the states of the entity with the ones working, and the only difference I can see is that the one I created does not have the "state_class: total_increasing"
this is the definition:
pool_summation_delivered_corrected:
friendly_name: "Pool Energy usage"
unit_of_measurement: "kWh"
value_template: "{{ (states('sensor.pool_summation_delivered') | float / 1000) | round(2) }}"
device_class: energy
you need to add a state_class
yeah, but it does not allow me
I think you're using legacy template configuration format, you'd need to use the new format
one second...
Invalid config for "template" from integration "sensor" at configuration.yaml, line 120: "state_class" is an invalid option for "sensor.template"
yes, I am aware that I need the state_class: total_increasing, but how do I add it??
You put all that under sensor:
It belongs under template:
See all the examples below
Hello, another person on reddit made me notice that I am using the legacy format in my configuration.yaml
that's why it was not taking the options
I am formatting the configuration to the new one... but although HA accepts the config without errors, I have lost all my custom sensors 😕
and the question is… [?]
no question for now, I am reviewing my configuration, removing tabs, checking spacing...
and, yes, now it's giving several errors
it's giving me an error on line 2:
default_config:
¿?¿?
ok, how can I have an error in the first line of my configuration.yaml? my first line is just:
homeassistant:
I am checking some configurations examples on github, and also checking with chatgpt, is it required now to split the config in several files for each section?
No
then I do not know why it is erroring on the first sentence already
what exactly is the error? how exactly your config file looks?
I am rewriting the whole thing from scratch... it's gonna take me a bit of time
ok, I am starting to feel like an idiot, the examples of the configuration.yaml I am looking at in the github are using the legacy format
I would have thought all the examples would be updated
Those are links to configurations of persons, in most cases probably their production system.
And it's a huge list
But focus on your own config, how did you add your own template sensors now
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.
Share what you have now
Looks like you have a space before template: (remove it) and you didn't follow the format from the docs for the sensors
Look again, specifically at the -
I am editing the whole thing, obviously the sensors are the most important right now
why do I get an error on column 1 line 2?
expected block end but found block mapping start
Just compare with the examples
u cant have comment on first line - idk why - it happened to me before - i guess some kind of parser quirk nvm, i see i do have comments on first line xd i guess it was something different…
really? I think I removed it before and the error just went to 1, 1
let try again
let me try again
(also, I did not include the comment, it was part of the original file)
Same error on line 1, column 1 with this:
default_config:
I am guessing it wants it to be included under some branch
the error disappeared when I corrected the spacing in the template/sensor section
have i ever mentioned my strong dislike for jinja
what other templating engine u like instead?
checking the logs now for errors: the option color is not accepted, and I believe the friendly name is also wrong
ok, so none of the sensors are working
I will try removing the color part first...
ok, the icon template is also wrong...
the problem with home assistant (among others), is that things change so fast, that most of the information in the forums become completely useless
friendly name is also gone
ok, it WORKED
I have to remove all the outdated tags, and I will have to check how to change the names now that there is no friendly name, but other than that the sensors are working, and more important, the stupid new sensor for the pool is now visible in the energy dashboard
Thanks a lot for the help!
I will keep checking the file and changing it all to the new format
Can you not template the entity_id in the target of a service?
target:
entity_id: {{ trigger.id }}
gives not a valid value for dictionary value @ data['action'][0]['target']['entity_id']
the value of trigger.id is a valid entity_id
yes, it's what I was checking now
If you surround it in quotes, yes
Like any single-line template
Hi guys, I really need help with the dashboard. How do I get it so I can get one dashboard to show to one user and a different one to show to another user
I had an idea, I can maybe use scene.create and scene.turn_on to store the last brightness on the fly
although I'm having issues applying scenes to the template light in general, not sure why
Hi guys, do i see it correctly that templated binary_sensors which are defined in the Web UI rather than in YAML are lacking the options for delay_on and delay_off ? I cannot find these options.
correct, if you want those more advanced options you'll have to create it using YAML
meh. i was hoping to streamline my config a bit more and migrate from YAML to the web UI
Hey
I need some help with template sensors and helpers.
I have a temp sensor for my pool. I would like a new sensor to show the temperature only when the pump is running (i have it on a switch entity) and keep the last value it had before I stopped the pump when the pump is off.
I found a few things on the forum but I'm too uncomfortable on these sensors to get through it. :/
Can anyone help me with it?
Post what you've tried
I tried to reproduce the post before last of this discussion:
I tried to build the template sensor from the helper UI but I cannot get the state part to be accepted
It seems i got it right this time:
{{ states('sensor.pool_water_temperature') }}
{% else %}
{{ states('input_number.end_of_day_pool_water_temperature') }}
{% endif %}```
On the automation I have:
description: ""
trigger:
- platform: state
entity_id:
- switch.shellyplus1_piscine_switch_0
to: "off"
condition: []
action:
- service: input_number.set_value
metadata: {}
data:
value: "{{states('sensor.pool_water_temperature')}}"
target:
entity_id: input_number.end_of_day_pool_water_temperature
mode: single```
My issue is that I cannot find the entity "input_number.end_of_day_pool_water_temperature"
Do I have to create it somewhere? if so, whith an helper?
that link will open to your HA page if you set up mylinks. The link should walk you through the process, and it's secure.
Thanks @mighty ledge
It will be a numer kind of helper?
Number seems not the right kind
number is correct
hello. question on how to add "attributes" to template sensors. this video i'm following is adding the template directly into the configuration.yaml file. is that recommended? or best to use the template sensor helper.
but when i try to add it via the template sensor, i'm not able to figure out how to add "attributes" to my sensor
You can't add attributes from the UI
you have to use YAML for the whole thing if you want attributes or any of the other more advanced features
got it. is it recommended to make the sensor directly in the config.yaml file or some other place? feel like over time its going to get messy to have some templates in the UI and some senors in config.yaml
Put it there or in an included file. Doesn't matter
for the templates created through the UI, are you able to edit the yaml?
No
@worn nova I converted your message into a file since it's above 15 lines :+1:
thanks!
last questions. if i want to use a seperate yaml file, including this "!include advanced_templates.yaml" in my main configuration.yaml is the correct syntax right?
or would it be "templates: !include advnated_templates.yaml"
- sensor:
- name: days_to_next_recycling_collection
state: >-
{{ min(((state_attr('calendar.recycling_collection', 'start_time') | as_timestamp - today_at('00:00') | as_timestamp) / 86400) | int,2) }}
attributes:
days: >-
{{ ((state_attr('calendar.recycling_collection', 'start_time') | as_timestamp - today_at('00:00') | as_timestamp) / 86400) | int }}
-name: days_to_next_trash_collection
state: >-
{{ min(((state_attr('calendar.trash_collection', 'start_time') | as_timestamp - today_at('00:00') | as_timestamp) / 86400) | int,2) }}
attributes:
days: >-
{{ ((state_attr('calendar.trash_collection', 'start_time') | as_timestamp - today_at('00:00') | as_timestamp) / 86400) | int }}
i'm getting a "duplicate key" error but not able to understand why
@lilac anchor To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks.
```yaml
example: here
```
Don't forget you can edit your post rather than repeatedly posting the same thing.
you're missing - name: days_to_next_trash_collection ?
oh it's there but it's not whitespace aligned correctly it seems
yes! thank you.
Hey, i try to count my persons there are at home, my try is the following but it does not work when i try to exclude some persones, can someone assist please?
{{ dict((states.person|filter(not person.martin))|groupby('state'))['home']|count }}
that's...an interesting attempt 🙂
{{ states.person|rejectattr('entity_id', 'eq', 'person.martin')|selectattr('state', 'eq', 'home')|list|length }}
or if you have more people you want to exclude:
{{ states.person|rejectattr('entity_id', 'in', ['person.martin', 'person.someoneelse'])|selectattr('state', 'eq', 'home')|list|length }}
Yeah when noobs are trying something 🤣
Thanks rob, yours are working great 👍🏻
@bold grotto I converted your message into a file since it's above 15 lines :+1:
@bold grotto I converted your message into a file since it's above 15 lines :+1:
try in #automations-archived ?
@bold grotto you have an error somewhere
{'apple_device': True, 'subtitle': 'the subtitle', 'push': {'interruption-level': Undefined}, 'actions': [{'option1': 'action_1'}, {'option2': 'action_2'}, {'option3': 'action_3'}], 'tag': 'the tag'}
notice the word Undefined for 'interruption-level'?
that won't translate to JSON
Is it possible to create a template with the number of add on updates that are pending? I have asked chat gpt and tested some that I found online but haven't got anything working.
Something alike to the Hacs sensor would be ideal.
I'm sure there are update.xxx entities that have some pattern to them
so then it's just counting the number of them with a state of 'on'
I can't find any pattern to them that fit just addons
I'm not seeing that
boo
I was thinking something along those lines. But as @mighty ledge says, there might be other stuff there as well :/
best case...
I thought I had a template sensor for this at some point, but I'm pretty far away from addons now
or maybe there was something in the supervisor integration
ya
{{ integration_entities('hassio') | select('is_state','on') | list | count }}
Also includes core though
Hmm... I am getting 2 back while no updates seems to be available to me. Did I miss something?
you can always filter it out
do this
{{ dict(integration_entities('hassio') | expand | groupby('state') | list)['on'] }}
Ah, it is because z2mqtt and moquitto is running
or that
I just removed the count part from the original and it printed the names of the ones set to on. So I guess it includes more than updates :/
Two of them I can filter out. That shouldn't be a problem.
oh
yeah, filter down to just update entities
{{ integration_entities('hassio') | select('match','^update.') | select('is_state','on') | list | count }}
{{ state_attr('zone.home', 'persons') | reject('in', ['person.martin', 'person.someone_else']) | count }} 😅
{{ answer | rejectattr('from', 'in', ['TheFes']) }}
I thought it would be actually good to use that attribute once, instead of incorrectly adding it to a state trigger
Can anyone confirm if I am doing something wrong here or if I'm right in thinking this is actually a bug? 😦
https://github.com/home-assistant/core/issues/115204
Those parenthesis are wrong
There is nothing wrong with your template, but if you're local settings are set to km, it will automatically show mile values as km
@bold grotto I converted your message into a file since it's above 15 lines :+1:
ok, after a restart now it seems to be working... thanks @mighty ledge for pointing out the Undefined variable
Yeah so this is just another example of the unit auto-conversion that wasn’t completely thought out. You’re not doing anything wrong. Fortunately the fix is easy
Just open up the entity and change the drop-down for units back into miles.
@bold grotto I converted your message into a file since it's above 15 lines :+1:
I would like to create a template sensor that states the number of open windows and doors in a group I have created with the entity id of binary_sensor.all_windows_and_doors. How would I create this count sensor so I can use it in my dashboard as a quick way to show how many open doors and or windows there are?
{{ state_attr('binary_sensor.all_windows_and_doors', 'entity_id') | select('is_state', 'on') | list | count }}
This would be an option
Huh. Thank you. I wonder why the original entity doesn’t have these drop downs.
It most likely doesn’t have a known unit of measurement
It does indeed, it's set to kilometers and kph and seems to be formatted correctly. The big difference I'm seeing is that my helper functions I've defined as measurement and speed type (device class?) and I suspect the integration does not do this. The primary dev for the integration is German so it's almost certainly not been an issue he's had to worry about. I'll try and submit a PR to add the device classes where appropriate and hopefully that'll fix it for everyone 🙂
Help with new weather templating
Your device class needs to match a valid u of m for it. Covered in sensor docs
Goodo, that would match what I suspected then so hopefully if I can provide the integration with a fix that'll help 🙂
you should probably add the state_class too so it can be used for statistics
if you're going to make a lib change
How do I force an update of a template sensor that triggers only once an hour?
Is there a service call that does that?
homeassistant.update_entity may work
you're better off just adding a second trigger
You might be able to add a device class to your existing sensor by using customize.yaml. That would then give the drop-down for you to change the unit of measurement and then you could get rid of your template sensor.
Update_entity doesn't do it unfortunately
Yes, it may not work for trigger based template entities
I did this and it asked what to display it as so I chose window. The new sensor is displaying a value of closed rather than a number of windows and doors that are open.
you made a binary_sensor, you should have made a sensor
having various formats (markdown, attribute, template filter..) of this {% set alert_level = states('input_number.battery_alert_level')|int %} {%- set ns = namespace(items=[]) -%} {% from 'batteries.jinja' import batteries %} {%- for b in batteries().split(',') if states(b)|int< alert_level -%} {%- set ns.items = ns.items + [ {'name': states[b].name, 'perc': states[b].state|int(-1)} ] -%} {% else %} Alles batterijen boven {{alert_level}}% {%- endfor -%} {% for i in ns.items|sort(attribute='perc') %} {{i.name}}: {{i.perc}}% {%- if not loop.last %}, {% endif -%} {% endfor %}