#templates-archived
1 messages · Page 65 of 1
Yes, do you expect that to work?
Yes it works
I thought you said it was timing out
But after he is done talking it causes the error.
He says "The back door was opened" then I see that error in HA logs.
It is probably a network loopback error so the data is getting in, butit can't send back to itself
Is there a method to handle that?
Not using Rest probably, why are you not simply using a bash command.
For which step? We were first trying to use command_line if that is what you are saying but it doesn't accept templating
You can but you need to use a sensor and not an Automation if you make it a switch you can turn on the switch to trigger the text and then turn the switch off ready for next time.
I recommend reading all the documentation for all the different command line options.
Another option would be to add the text you want to the end of a file and then set your script to read the last line from that file to send to the speach process.
@hybrid halo I converted your message into a file since it's above 15 lines :+1:
Crazy! I have a shelly 1PM template above that doesn't work?
A light.turn_on service will not work on a switch entity. Use switch.turn_on instead
Vice versa for light.turn_off
I think the problem is that when I look at the developer tools state, it shows (switch: false), but in the floor plan I call (service_data: switch-${entity.state})
Grr.
I'm too furious.
I want to write that on the floor plan card I call (service_data: switch-${entity.state})!
When I look at the status, in dev tools, it says (switch: false) and I have it set, (device_class: outlet).
And I came up with the idea to make a template like I did for the dimming switches, which seemed to me like a light because of the dimming!
By the way, I set it to switch.turn_on and it doesn't work!
This is when you want to squeeze more out of the devices than they are designed for. Shelly has a special input for the switch and in my opinion is the cause of the failure!
You don't mean the switch (binary sensor) states for decoupled switches, do you?
Does the 1pm support dimming? Only dimmers do if I call correctly and those are represented as light entities in HA
No, It is power meter.
So either way you are using the wrong service or the wrong entity
Are you trying to make a template switch based on the same switch?
Probably.
Obviously it's not a switch, this Shelly power meter. In my opinion, the reason is that it specifically has the option of connecting a switch. Can I post a question on github and copy the link here? I can add pictures there
I need to use the automation for the delay between the 3 http commands the first command takes control of the bot so you then can send your text string then you release the bot after.
it is a switch with power metering though
So put all the commands in a bash script?
with a delay in the script.
Sorry I was replying to NonaSuomy.
Just wondering if anyone knows a solution for: https://github.com/ExperienceLovelace/ha-floorplan/discussions/412
Here's a link if you can help with it: https://github.com/ExperienceLovelace/ha-floorplan/discussions/414
Could you please start explaining from the beginning? What do you try to achieve with the template switch? And what has that to do with the floorplan action?

The XY problem is asking about your attempted solution rather than your actual problem.
Can someone explain how to convert this to the new format? ```- platform: template
sensors:
number_lights_on:
friendly_name: "Count of lights on"
value_template: >-
{{ states.light
| selectattr('state', 'eq', 'on')
| list | count}}
icon_template: mdi:lightbulb-group
if I do this:```template:
sensors:
number_lights_on:
friendly_name: "Count of lights on"
value_template: >-
{{ states.light
| selectattr('state', 'eq', 'on')
| list | count}}
icon_template: mdi:lightbulb-group
Please look carefully to the documentation
template:
- sensor:
- name: number lights on
state: >
{{ states.light
| selectattr('state', 'eq', 'on')
| list | count}}
icon: mdi:lightbulb-group
Now I don't think I need a template, but somehow I need to call the state of the Shelly sensor in a different way in the floor plan card.
The problem is that I don't know how?
So you want to set a class within the floorplan to the switch entities?
Like this?
directly form the floor plan documentation
- entities:
- binary_sensor.kitchen
- binary_sensor.laundry
state_action:
action: call-service
service: floorplan.class_set
service_data:
class: '${(entity.state === "on") ? "motion-on" : "motion-off"}
Which is more #frontend-archived related btw
Yes. Thanks for the help.
I will wait for someone to respond to github, ha-floorplan, discussions where I asked the question and also added pictures and the like.
There is too little space here to attach everything that is needed.
I think the same.
I have that's why I asked...
did you tried this
state_action:
action: call-service
service: floorplan.class_set
service_data:
class: '${(entity.state === "on") ? "switch-on" : "switch-off"}'
as service_data: switch-${entity.state} does not make sense at all, it expects a mapping with the key class not a service
My configuration.yaml: sensor: !include sensors.yaml mqtt: !include mqtt.yaml
sensors.yaml ```template:
- sensor:
- name: number_lights_on
state: >
{{ states.light
| selectattr('state', 'eq', 'on')
| list | count}}
icon_template: mdi:lightbulb-group
- name: number_lights_on
- sensor:
- name: battery_status_kitchen
state: >
{{ "True" }}
- name: battery_status_kitchen
Check configuration says: required key 'platform' not provided.
So, I apparently have some sort of reading and learning disability. I have read those. I can't figure out what I don't see, what I don't undersatand.
template is a separate integration, it does not go in sensor
icon_template is only available on sensor: 's template platform (old style). It's not available in the template integration (new style)
This was in the file before: ```- platform: template
sensors:
number_lights_on:
friendly_name: "Count of lights on"
value_template: >-
{{ states.light
| selectattr('state', 'eq', 'on')
| list | count}}
icon_template: mdi:lightbulb-group
- platform: template
sensors:
battery_status_kitchen:
friendly_name: "Battery Status Kitchen"
value_template: >-
{{ "True" }}
only icon is available
Right, that's the old style
the new style is a separate integration
is there a reason you're changing this at all?
Because this is a new system and I am trying to learn the new and not garbage things with the old.
ok, then you should try to understand the difference between platform: template and the template integration
platforms are old, the are the way of the old
everything now is separated into their integration
So, there is an include for template in the configuration file? And where do sensors go?
e.g. you have (old style)
sensor:
- platform: template
sensors:
....
new style
template:
- sensor:
...
new style goes in sensors.yaml?
no, like I said above. They are in the template section of your configuration.yaml
you can make that a separate file or not
So the template section can't be split to a file and imported?
Here is how to split your configuration into multiple YAML files
so in configuration.yaml: ```template: !include template.yaml
you're missing the colon
what if I wanted to break templates into multiple files?
Check out this link and decide which version you want
My configuration has them split the best way IMO
Link?
Do you know why, when I paste into a vscode file it doubles the indents on each line?
Hi. I tried and it didn't work as you wrote! Then I looked at the rest of the settings and tried this: yaml service_data: > class: '${(entity.state === "on") ? "switch-on" : "switch-off"}
and it doesn't work. Any other ideas perhaps?
Why are you adding that multi line string notation mark (>)
Otherwise it won't let me save!
Unable to parse YAML: YAMLException: unexpected end of the stream within a single quoted scalar (294:1) 291 | c ... 292 | e ... 293 | } 294 | -------^
Because you have a single ' at the beginning of the class data, and not at the end
service_data:
class: '${(entity.state === "on") ? "switch-on" :
"switch-off"}'
Was just gonna suggest that
Thanks! Lots of good stuff there. But, now I'm confused. What is the difference between a sensor defined in the sensors.yaml and one defined in template.yaml?
the sensor section accepts platforms, which are old ways to set things up
you should be able to just output the string
'${`switch-${entity.state}`}'
Output to where or what?
I fixed it and added '
and it still doesn't show class in HTML DevTools
Also, why does templates.yaml need '- sensor:' and mqtt.yaml is ok with 'sensor' (i.e.in the first column)
because they are separate integrations with separate requirements
So, the integration defines the syntax of it's associate declarations and file?
Yes
That's why chatgpt and all other AI suck at configuring HA
each one is different
what did you mean here?
As the state?
Didn't catch that.
Now I just realized what it is for:
tap_action:
action: call-service
service: homeassistant.toggle
, which has nothing to do with class set
- entities:
- switch.tm_vh
- switch.tm_mi
- switch.tm_sp
- switch.tm_na
- switch.tm_di
- switch.tm_ko
state_action:
action: call-service
service: floorplan.class_set
service_data:
class: '${(entity.state === "on") ? "switch-on" : "switch-off"}'
tap_action: false
``` And now it works. Thank you very much.
You were right all along! I didn't understand everything correctly. Now everything works as it should. Thank you very much!
Is there an example of a template switch in the new format not the old? This is obviously wrong:```- switch:
- name: tpl_switch
turn_on:
service: switch.toggle
data:
entity_id: input_boolean.sillyswitch
turn_off:
service: switch.toggle
data:
entity_id: input_boolean.sillyswitch
Switch doesn’t have a new format
Can it live in the same template file?
No
Where does it go then?
In switch
So, some templates go in template.yaml, other templates go in switch.yaml.
No, switch template platforms go in switch
Then what is Template Switch integration?
Nothing, doesn’t exist
Its the switch template platform
The Template Switch integration was introduced in Home Assistant 0.13, and it's... from: https://www.home-assistant.io/integrations/switch.template/
That’s the platform
Notice how the documents show it goes in the switch integration, with the designation platform: template?
I'm lost.
The text is something misleading though by calling it an integration 😅
I don’t know why you’re trying to understand this. Just follow the documentation for the integration.
I set out to define an area. I defined an entity, it shows up in the area, but not on the card. That needs a switch that references the entity. But, iI'm lost in platforms and integrations, and whatever. And that's not even what I really want. I want to create a virtual something that I can put on a dashboard to be display the state of devices that aren't in this system yet, because I don't want to shutdown my old OH system and shutdown my automation while I learn HA and migrate my zwave network.
Then just follow the documentation and stop making up yaml. The template integration shows you how to configure the entities it supplies. Template switch shows you how to integrate them, it’s separate.
Add a unique id to your entities to be able to put them in areas.
They have unique id's AFAIK.
You haven’t posted a single configuration with unique_id yet
When did I post an entity?
You’ve posted multiple template (virtual) entities without unique_ids
Those aren't the entities in the area. I just went to entites and defined them.
The entityID field says input_boolean.sillyswitch
Sorry, I went to Helpers and defined that.
Notice the difference in the word unique_id and entity_id
I’m going for a run, good luck.
yah, thanks, enjoy the run.
you are defining an entity here, this will create swith.tpl_switch
and you didn't add a unique_id
But template switches are not changed to the new format yet, you can only use the legacy format for them
So, what I defined there goes into a file switch.yaml with unique_id: '0a7476cc-d6c1-40ba-8ae1-606518c3497f' added?
hi. I have dropdown i want to incorperate into a light template to control the effects (the dropdown being a list of the effects, and from there I have automations from changes to the dropdown....).
How can i do this?
You could try the effect_list_template: https://www.home-assistant.io/integrations/light.template/#effect_list_template
not the one I replied on, it should be like
- platform: template
switches:
some_switch:
unique_id: some_id
friendly_name: some name
value_template: "{{ a template }}"
turn_on:
- some actions
turn_off:
- some actions
similar as described in the docs
Thanks, but I've RTFM'd this all before. I just cant seem to connect the dots. But, with you example and reading the doc...again. I have the tpl_switch. Now How do I set an area for it.
I'm trying to use the gui for exploring templates, with the goal of getting the friendly_name of one of these:
<template TemplateState(<state light.garage_driveway_lights=off; supported_color_modes=[<ColorMode.BRIGHTNESS: 'brightness'>], color_mode=None, brightness=None, friendly_name= Garage Driveway Lights, supported_features=32 @ 2024-01-24T14:07:33.774485-08:00>)>
I can get all the lights which are on, via one of the examples ( states.light | selectattr(... ) | list
But I can't list / get the friendly_name attribute/slot/variable thing. To me it seems that the only queriable/selectable item is that first attribute.
I've tried various selectors from the jinja.palletsprojects.com doc to no avail.
what concept am I missing here?
I don't see any way to assign an area.
You need to use the state_attr most likely, you may want to use the device_attr
{{ state_attr('light.bathroom', 'friendly_name') }}
{{ device_attr('light.bathroom', 'name') }}
Assuming you're iterating through a list, it'll be something like:
entities | map('state_attr', 'friendly_name') | list
NVM, I found it. Thanks!
ah, ok. so I get a 'TemplateState' object has no attribute 'lower' which isn't what I would expect ( new to this lang )
What's your whole template so far?
{{ states.light | selectattr("state","eq","on") | map('state', 'friendly_name') | list }}
mentally should I be thinking with an XSLT hat on? or? edit: typo
I think you need to start with expand(states.light) instead of states.light, because otherwise you get a list of states instead of the actual entities
Why are you mapping the friendly name of the state though?
AH I was wondering if there was a way to see just what the heck these objs/entities were in the template explorer tool. I will give that a shot.
no joy, back to missing attribute on 'TemplateState'
So I am thinking of this stuff as getting an iterator, filtering ' the result' based on an attribute filter, extracting the friendly name and listing it.
am I on the wrong planet?
What is your end goal?
I'm trying to display a list of the lights which are on using the friendly name so the rest of the family understands. ideally as switches/controls somewhere. if this template language has a simple attribute accessor that would do it.
You could also use something like the auto entities card https://github.com/thomasloven/lovelace-auto-entities
But as a template, this should do the trick:
{{ expand(states.light) | selectattr('state', 'eq', 'on') | map(attribute='name') | list }}
thanks @silent seal I will go take a look at that card. but I'm still wondering what I conceptual baggage I have to jettison.
{typing yer example }. => huh?
um how does 'name' resolve values for something called 'friendly_name' - cuz it worked great. is there a doc on whatever syntactic shortcut this is?
The trick is knowing what you're dealing with. Are you already using the template editor in the developer tools inside HA?
thanks. I am only using the template editor / read-eval-loop / tool in the developer tools inside HA at the moment. execising discovery, if you will.
um how does 'name' resolve values for something called 'friendly_name'
Yes,namewill usefriendly_nameif it's defined
Without | map(attribute='name') this reveals that I am working with a list of TemplateState. I can add a | first after the list to trim it down to just the first one and make it easier to read. But as you noted, it shows a friendly_name there. The answer is actually "I took a guess and got lucky", because I don't remember where/if I learnt that mapping a name gets you the friendly name
it's explained here: https://www.home-assistant.io/docs/configuration/state_object/
That's the place, RobC saves my bacon once again 😛
and interestingly using 'friendly_name' returns Undefined. sort tricky that.
scooting over to read that state_object bit
Yeah, referencing the docs for things like that definitely helps. It's also worth knowing that devices have different attributes to entities.
I'm cool with docs. I just didn't really expect that a 'discovery' tool querying a state machine which returns data structures containing what look like member values in key:value pairs would have alternate ways to resolve the value from keys. via magical keys. and not the displayed keys.
I'll dork around with the other attributes on these things to see what happens.
@silent seal very helpful thanks, you too @inner mesa
Hello,
I have an issue with variables not showing.
Followed the instructions, but unfortunately no success.
Any obvious errors?
Using: Notifications: Send a notification with android_notify
service: notify.android_notify
data:
message: test
data:
fontsize: large
position: top
duration: 8
transparency: 45%
color: red
interrupt: 0
video:
path: >-
/config/www/nest/cam/camera_person.mp4
title: Doorbell
``` It returns with the message on my tv and android app. but no video or picture.
What's the full code of the automation?
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.
I just updated it to full code 🙂
The path at the top level looks broken. You have a video > path, which looks right, but the other one you had looked wrong
it was a typo with the path at the buttom.. but it dosent send the file..
But, you could also simplify things: https://companion.home-assistant.io/docs/notifications/dynamic-content#camera-stream
Well it can't send you a live stream file, the file isn't "finished". But it can send you a still and redirect you to the camera when you tap on the notification.
Yeah but i dont want it to stream, i want to send the clip that ha generates.
The file is there, and "finished" i just dosent send it..
I think your path is still wrong then: https://companion.home-assistant.io/docs/notifications/notification-attachments#www-folder
A file stored in
/www/file.jpgon-disk is represented by/local/file.jpgin the notification. Note the change of the local part of the path.
so what if the file are stored in the config folde? "config\nest\event_media"
No, the /config/www gets replaced with /local
thx, but the path im looking for is: config\nest\event_media
would that be: local/nest/event_media
Well then you can't share that file. If the file isn't in the www folder you can't send it to the device.
okay then that might be my issue 🙂 Can i add that folder i whitelist to make it accessible
No, you can only send the files in the www folder. You're not actually sending the file as an attachment to the device, you're sending a link to the file to the device, and that link needs to work, which requires it to be in the www folder. https://www.home-assistant.io/integrations/http/
okay because nest intergation saves the file in config\nest\event_media and not in www folder..
Then you'll have to try the API links: https://www.home-assistant.io/integrations/nest/#media-attachments
(Which were also mentioned in the companion app documents I linked 😉 )
So when i call this path it work just fine with a picture, but not with a mp4 file, so the path shows me it works but somethine else. :
image:
path: /config/nest/event_media/cam/dorbell.png
But when i call this no video:
video:
path: /config/nest/event_media/cam/camera_person.mp4
Are you on #android-archived or #ios_and_mac-archived? I have a feeling that Android doesn't support videos like that, but you'd have to check with them
@olive cape I converted your message into a file since it's above 15 lines :+1:
Yeah I'd actually prefer if you didn't bot lol
It works just fine if I manually specify entity ids, and the template works properly in the template dev tool section and an automation, but in set_rgb (using the one from turn_off also doesn't work)
if you're going to use a template for entity_id, it needs to be nested under data:
and data_template is years and years out of date
I also note that the error says lights->controller->set_rgbw->0->entity_id and you only have set_rgb, so I can't explain that
Aha, that works! I looked at that for way too long. Based on the example https://www.home-assistant.io/integrations/light.template/#make-a-global-light-entity-for-a-multi-segment-wled-light used both data-template and entity_id in that location
yeah, that example should be updated
Appreciate it
Trying to set up a single automation for all my timer.finished actions.
If I set the automation to trigger on all timers, what sort of variables are available for my logic to identify which timer triggered the automation?
Something like:
trigger:
- platform: event
event_type: timer.finished
action:
service: script.turn_on
target:
entity_id: '{{ trigger.device }}'
You can do something similar to see the full available trigger object #templates-archived message
In your case you need the entity_id, so it would be trigger.entity_id
I looked at that, but didn't see anything for timer. I"m somewhat expecting it to be handled as an event
But a timer entity will not work with the script.turn_on service
The available variables are anything in the timer.finished event... The entity ID of the timer would be available using {{ trigger.event.data.entity_id}}, but as Bas said the script.turn_on service will not act on a timer entity.
That wasn't a valid yaml, I'm sorry. I just cobbled together something to help get the point across.
from the traces, it appears it should be trigger.event.data.entity_id, as you said. Let me try again with the correct event data variables
Excellent! this now works as expected
Hey, can it be that binary_sensor dont have last_updated? he only show me the last changed date but i trigger it each 10 minutes
trigger:
- platform: time_pattern
minutes: /5
action:
- service: calendar.get_events
data:
start_date_time: "{{ now() }}"
end_date_time: "{{ now() + timedelta(minutes = 10) }}"
target:
entity_id:
- calendar.xxxxx
- calendar.feiertage
response_variable: termine
binary_sensor:
#Advanced Heating Control
- name: Advanced Heating Control Kalender
unique_id: advanced_heating_control_kalender
icon: mdi:palm-tree
state: >
{{
( termine['calendar.xxxxx'].events | regex_search('Urlaub', ignorecase=True) ) or
( termine['calendar.xxxxx'].events | regex_search('Krank', ignorecase=True) ) or
( termine['calendar.xxxxx'].events | regex_search('HomeOffice', ignorecase=True) ) or
( termine['calendar.feiertage'].events | count > 0 )
}}```
All the 4 conditions should end with | count > 0 to work correctly
okay i change it, but the binary should be updated than, each time when the trigger runs right?
I do think the state machine really does need an explicit state change to update that
hmm thats bad, you have any idea how i can solve this?
when i have overlayed events i have no trigger
last_changed and last_updated exist on all state objects
You could add an attribute which specifies what condition is true at the last trigger
That forces an update in the state machine by some changed conditions
I'm not sure why you'd want it to update, it's a binary sensor
this sensor does not update when i have overlayed events, all time true
but i need a trigger to change a sequenz behind
aah thats a good idea, i will try if i can made it
I'm not following you. If you want the binary sensor to change state so you can trigger, you need to change your logic
he does not change because it has sometimes overlayed events, so the state is always true in this moment
Right, but that's what you need to change
if you have overlaying events, you should figure out which event you want to track
in your logic
Or separate them into 3 separate binary sensors
Bas example is nice, i will try.
no idea how i can change it in a other way, only when i create more templates, and this i dont like 🙂
what do you mean "this I dont like", it takes 2 seconds with your current setup
#Advanced Heating Control
trigger:
- platform: time_pattern
minutes: /5
action:
- service: calendar.get_events
data:
start_date_time: "{{ now() }}"
end_date_time: "{{ now() + timedelta(minutes = 10) }}"
target:
entity_id:
- calendar.xxxxx
- calendar.feiertage
response_variable: termine
binary_sensor:
#Advanced Heating Control
- name: Advanced Heating Control Kalender
unique_id: advanced_heating_control_kalender
icon: mdi:palm-tree
state: >
{{
( termine['calendar.xxxxx'].events | regex_search('Urlaub', ignorecase=True) ) or
( termine['calendar.feiertage'].events | count > 0 )
}}
- name: Advanced Heating Control Kalender
unique_id: advanced_heating_control_kalender
icon: mdi:palm-tree
state: >
{{
( termine['calendar.xxxxx'].events | regex_search('Krank', ignorecase=True) ) or
( termine['calendar.feiertage'].events | count > 0 )
}}
- name: Advanced Heating Control Kalender
unique_id: advanced_heating_control_kalender
icon: mdi:palm-tree
state: >
{{
( termine['calendar.xxxxx'].events | regex_search('HomeOffice', ignorecase=True) ) or
( termine['calendar.feiertage'].events | count > 0 )
}}
but i need to edit the names right?
yeah, your completly right, but for noobs like me, many new entities make it hard to hold the overview.
maybe with time i change my mind :)^^
You're going to have a worse time with a single entity
hm okay, i will try, thanks bas and petro
hello dear community,
I need your help.
I get the following error in my HA log:
(I'll include the error code below)
I have installed 3 template.sensors under Helper, but unfortunately I don't know exactly which one (or all three?) produces this error.
Can you help me locate and correct this error?
@wispy ridge I converted your message into a file since it's above 15 lines :+1:
Part2
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 693, in async_render_to_info
render_info._result = self.async_render(
^^^^^^^^^^^^^^^^^^
File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 561, in async_render
compiled = self._compiled or self._ensure_compiled(limited, strict, log_fn)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 764, in _ensure_compiled
self.ensure_valid()
File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 513, in ensure_valid
raise TemplateError(err) from err
homeassistant.exceptions.TemplateError: TemplateSyntaxError: unexpected char '‘' at 9
.
.
.
The error tells you which template
maybe unexpected char '‘'?
petro one question again, i tried the trigger via service, he gives me now zero events but the binary_sensor don't goes to off, how i can now troubleshoot these?
can i test the binary somewhere?
on templates the response_variable is missing
You can call the service in the service caller
then copy the contents from the service caller, which will be yaml.
Then you can paste the yaml into a yaml to json converter
then copy the json and put the contents in a response variable like so...
{% set termine = '
{"myjson":"value"} <--- PUT JSON HERE
' | from_json
%}
ahh okay thank you
Then you can directly test the templates as is below that line
it's a pain in the ass
many thanks for your response. The error can then only be narrowed down to a template.sensor because I only used these lines of code there. What's strange, however, is that the syntax is correct. I have now copied the following code:
{% set gas = states('input_number.gaszaehler_sensor') | float %}
{{ ((gas) * 1) | round(2) }}
the syntax is not correct
you're using quotes that are not avialable for use in templates
the quotes MUST BE " or ', no other quote style.
literally only those 2 quote styles are acceptable.
You're using ‘ and ’
notice how they have a fancy twist to them
that means, they are bad
if you're using a phone, you have to hold down the quote key to bring up a list of quote options and choose the correct one.
Yes, the unusual use of the quotation mark cannot be recognized in the code I copied and pasted.
I'll just use it "
OK. I found it. it was an unused template card. The curved quotation mark was there.
Thank you!
I am getting stuck parsing json in a template. I can get it in dev tools|templates supplying the json manually, but when I try to parse it "live" its not doing what I expect
I want to get the count of elements within an array, what this would do jq '.cars | length' where the array is named "cars"
Can this be done in a template?
post the json
Are there any limitations in using the Helper UI to create a template vs the 'legacy' way?
You can't add triggers or actions
Ah okay, thanks
i am trying to turn off a set of lights with the entities coming from a template. if I try my service call in the services panel of developer tools, it works, but if i try the same call in an automation action i get errors (Error while executing automation automation.bp_test: must contain at least one of entity_id, device_id, area_id) and usually only one or two lights actually turn off..
service: light.turn_off
data: {}
target:
entity_id: >-
{{ expand(area_entities("Living Room")) | selectattr('domain',
'eq', 'light') | map(attribute = 'entity_id') | list }}
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.
Your entity_id template isn't outputting a formatted list of the entities.
But you could also just do this:
service: light.turn_off
target:
area_id: bedroom
Obviously with a different area id
@still plank I converted your message into a file since it's above 15 lines :+1:
and i still don't get why it works in one place and not the other
Your template can be more efficient, but I don't see why it wouldn't work in an automation. The template could just be this:
{{ area_entities('Living Room')|select('match', 'light.')|list }}
Maybe a missing space in front of the template?
The posted service call has 3 spaces
ultimately i want to make the template more complex - i.e. not all of the lights in the area
But you likely still dont need to expand the area entities and re-map them
There are lots of example templates in this channel
i think it might actually be the blueprint which triggers the action - it's mode = restart and the state changes that fire the actions come in very fast
That would probably be a problem, you might want it to be queued or single.
can i just edit a blueprint with studio code server? or does ha (re)download it?
seems you need to reload automations after. but changing it to queued has sorted my problem. thank you for your help all
am using the following action from double-take
@final trellis I converted your message into a file since it's above 15 lines :+1:
I want to add to this template an extra attribute
https://pasteboard.co/RumZtoLqtbip.jpg
if camera = frontdoor_camera2
(maybe it can be used from state)
How do I set the state of an input_boolean in the Developer tools> template editor? This is not doing it and I can't find an example.{%set 'input_boolean.driveway_lights_active' = 'on' %}
And, yes, I know I'm missing something obvious.
@loud ridge what do you need?
You can't. You need a service call.
I actually know that...obviously it can be set, I can set it in the Dev>Services. I can't find what the service is called, how to call it from in a template.
Actually "know" is the wrong word, suspect is better.
It's making a service call, called input_boolean.turn_on
I think you can't set the state from a template. You need a service call
Can someone please show me what to type in the Dev tools>Template? I'm sure it is not as simple as {%input_boolean.turn_on%} This has no reference to the entity to turn on.
So, I can't set the state of entities and devices from the template tool?
But, I can get the values of the same entity there.
Correct, or from templates in general
get yes, set no ...
I would suggest you read up on the templating documentation: https://www.home-assistant.io/docs/configuration/templating/
It's a fairly advanced topic
I guess I'm an idiot...I've read that, more than once.
No, it's a complicated topic, and especially if you've just started using HA
So, templates basically allow access or creation of information that be used in logic to take action on the information, but templates have no action capability.
is there a way to test if a string is valid json in a template so that | from_json doesn't fail?
Can someone please help me with this code? This code counts the lights that are on, it counts individual smart lights which I have no problem with but I also have multiple lights that aren’t smart that turn on with a single switch so it doesn’t give a true report of the amount of lights on. I would like to count the number of lights that are also on a single relay
template:
- sensor:
- name: "Total Lights Count Template"
state: "{{ states.light | rejectattr('attributes.entity_id', 'defined') | selectattr('state', 'eq', 'on') | list | count }}"
- name: "Total Lights Count Template"
Is this the right thread? Thanks.
So you just want to add some number to that?
Yes, for specific relays. So at the moment a relay can turn on 4 lights and it would show as 1 light on because obviously HA doesn’t know those lights except for the switch that’s on. This light count is shown on a card on my dashboard.
You could set up a template sensor for each relay and set the value to the number of lights or zero when the reply is off and add that number to your light count. Just give them a name which you can filter on. The other option is to use template lights and use the relay to control them, but you would need to set one up for everyblub rather than simply adding the count.
Another option depending on the number of relays would be something like this. With an if for each relay.
{%- set count = states.light | rejectattr('attributes.entity_id', 'defined') | selectattr('state', 'eq', 'on') | list | count %}
{%- if states('sensor.relay') == 'on' %}
{%- set count = count + 4 %}
{%- endif %}
{{count}}
I have made a template switch that does not work. I have a machine that has one sensor saying running or not running. And I have a button that is just "press" and it toggles the machine. I was hoping to make a button template that I can turn the machine on/off with automation ect. Can anyone see why this isn't working?
- platform: template
switches:
icemaker:
friendly_name: "Isbitmaskin"
unique_id: 21587211-7f99-4529-a2a4-6e34e1ce2da2
value_template: "{{ is_state('binary_sensor.isbitmaskin_ismaskin_status', 'on') }}"
turn_on:
service: switch.turn_on
target:
entity_id: button.isbitmaskin_isbitmaskin_avp
turn_off:
service: switch.turn_on
target:
entity_id: button.isbitmaskin_isbitmaskin_avp
Use the button.press service for button entities
Services are tied to a specific domain and will not work with other domains entities
That worked like a charm! Thank you! 🙂
I have setup a small face recognition automation which open a frontgate when a certain face is detected
it stops at the condition match = true
what I am doing wrong ?
kindly asking, please have a look
The attribute value is probably a boolean, and not a string. Remove the quotes around true
double-take publish results to mqtt and mqtt create a sensor called sensor.double_take_makis
I've tried that it still stops there
it creates this sensor
https://pasteboard.co/L3Zfy9qIRq0E.jpg
so basically, what am trying to do is, to be sure that it is me (match = true & confidence > 95) and then open the door
it stops on the conditions
also, please note on my screenshot that there are two "match"
Did you already try my suggestion?
Ok, so the problem is you're looking at thee attributes via the states page
it does not show nested values, I can tell immediately that there is a dictionary named match with a nested key also named match
Notice how you have an empty match: above match: true?
so the path would be `state_attr('blah', 'match').match
assuming match has a match
key
so Petro (thank you - you always help me the last 5 years) what is the best way to open the door with a positive match ?
press on the entity id to see the full overview with indentation
only the top level attributes can be used directly in a state condition
an automation that uses a template as a trigger or condition
because of what thefes just said
can you help me with it please?
You still need to look at the shape of your object
looking at it more, it looks like it would be state_attr('sensor.double_take_makis', 'zones').match.match
TheFes is right. there is indentation that you can't see on attributes column
press on the entity_id, scroll to the top of your screen, and copy the attributes
then paste that between code tags
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.
@final trellis I converted your message into a file since it's above 15 lines :+1:
Ok, nope, first one was correct
the confidence should also be checked using a template
trigger:
- platform: template
value_template: >
{% set attr = state_attr('sensor.double_take_makis', 'match') %}
{{ attr and attr.match }}
condition:
...
action:
...
if you want to add confidence...
and and attr.confidence > 95
I think the best option is to leave the trigger as the author says
trigger:
- platform: template
value_template: >
{% set attr = state_attr('sensor.double_take_makis', 'match') %}
{{ attr and attr.match and attr.confidence > 95 }}
condition:
...
action:
...
you can do it as a condition too
the thing, petro, is that this sensor, stays up only for 30''
then it reports Unavailable
trigger:
- platform: state
entity_id: sensor.double_take_makis
condition:
- condition: template
value_template: >
{% set attr = trigger.to_state.attributes.match %}
{{ attr and attr.match and attr.confidence > 95 }}
action:
...
that's not a problem
that's fine, the trigger will still work
I'd go trigger route myself.
ok this is perfect. Now i see it
but face recognition takes place on three cameras
I want only to run on frontgate
(we have this as a state and as an attrbute)
shall we use a template under condition ?
You can just use a state condition, regular no template state condition
you can also add the state to the template trigger
ok let me try it
or the attribute, doesn't really matter
as a trigger or as a condition?
a state condition
ok here is the final code
@final trellis I converted your message into a file since it's above 15 lines :+1:
correct right ?
I am so happy
It does work
It does work and is very impressive
thank you @petro, thank you @marble jackal
This will trigger on any state change, I thought you only wanted it to trigger on the frontgate camera?
I would say you should have kept your original trigger
- platform: state
entity_id:
- sensor.double_take_makis
to: frontgate
oh wait, I missed that second condition
but why add a condition if you can tackle it in the trigger
this is what @petro said
it doesn't make a difference
if it does, i will change it
what's your opinion?
TheFes, you confused me now - cause Petro said it's ok
It doesn't matter much, but I would say it's more efficient to only trigger when you want it to trigger
and not let it trigger on all state changes, and then check in a condition if it triggered on the right camera
platform: state
entity_id:
- sensor.double_take_makis
from: Unavailable
to: frontgate
so this says, that it will trigger on frontgate, when triggered. (the only minus is that it might also triggered with false matches)
Something like this TheFes?
I've got a restful sensor that I'm trying to get to fail gracefully. If the server is unresponsive, value_json is seemingly unknown or unavailable or undefined. This template doesn't seem to do anything: value_template: "{{ value_json.packs[0]['c1'] | replace('*','') if value_json not in ['unavailable', 'unknown', 'none'] else states('sensor.ldpp_p1c1') }}"
And I can't reference the value_json outside the sensor because it's a restful sensor
I really just want my entity to hold on to it's last known good state rather than every few seconds showing Unavailable for its state
That from: is not needed.
The difference between defining the to state in the trigger or in the condition part is that in the first one, it only triggers if the sensor corresponds to the correct camera and checks then the condition (e.q. less triggering, can improve performance/backend io).
Or the latter one that triggers on each state change before checking each condition (e.q more unneeded automation triggers)
i understant that
please give me a minute to explain something important
when double-take detects a face it publishes to mqtt
the first time confidence is 80% so it will stopped by condition
the second time, it publishes again, but this time the confidence is 97%% (bingo)
will it trigger on the second time ??? because state is already "frontgate"
it might remain frontgate and mqtt publishes new attributes
so yes, I totally undestand what are you saying about performance etc etc, but the 1 million question is if it will fire the second time, if the state hasn't change??
???
No it won't, but you can also trigger on the match attribute leaving both to and from empty. This ensures it only triggers when the dict in that attribute includes a change
Although the method by petro is also sufficient as the impact on performance on a modern cpu will not be significant
No leave the condition untouched, that filters for the needed values
so i have no option
i have to leave trigger with no definiton for from and to
unless if there is something else. Maybe petro can assist please?
what you originally had was fine
the template condition is needed, the state condition is not needed if you check on that in the trigger
i think i will stick with this
because now I'm having second thoughts it will have impact to the performance
Just stay with what you have. I was initially commenting on the from you added in the trigger
with 3 cameras and many people around the building
thank you guys - I really appreciate it!!
Performance is only impacted if you have 1000s of unoptimized triggers/conditions in other automations.
Any modern cpu could handle this
and I'm so exciting - it works very nice
would you please take a moment and have a look on my 2nd question about calculating water consumption ??
I already answered to impact and said that I don't want a database and long term data.
just sum water flow to a input number sensor and then be able to use it to an automation
here is the water sensor I want to use
I do not see a 2nd question in this channel?
trigger on that sensor changing from 0
then store the current total somewhere
when the sensor changes back to 0, calculate the difference between the total on that moment, and the total you stored
that's the water usage
@TheFes the instat flow sensor is dynamic
it changes constanly based on the water pressure - consumption
how to store this
?
Template-sensor
as long as the shower is running, it will be above 0
you only need it to determine if the shower started, and stopped (when it goes back to 0)
how to sum it ?
What do you have so far in the automation?
i dont have an automation yet cause i don't know how to start
TheFes said trigger to 0, ok I get this
but I can't understand how to sum the water
the consumption is eventually determined by:
{{states('sensor.total_liters')|float - states('input_number.shower')|float(0)}}
This is for the trigger part e.g. we need to known when the shower starts running
I thought will go through the instant water_flow
Yeah you need that as trigger as I explained above
your goal is to send a notification with the water usage right?
or do you also want to it in an entity state?
I posted an example in #automations-archived
Hope, someone can point me what I'm doing wrong.
I'm using almost decluttering cards to prevent multiple times repeating the layout.
For a variable I have the following:
- my-list:
- item: one
- item: two
Then further I will access the list items in a for-loop with
{% for item in '[[my-list]]' %}
- {{ item }} -
{% endfor %}
The output is: "-[--[--m--y-----l--i--s--t--]--]-"
Seems it iterates over the string, but not substitutes the variable.
decluttering cards is something for #frontend-archived
It has also something to do with templates, that's why I asked here
there are no jinja templates used in decluttering card, it's a subject for #frontend-archived
and you can't template yaml like that
TheFes would you be kind and have a look please?
for input number, to get just the number, I must template it ? or it can be done with other way?
?
I want your opinion for the following wind template
@final trellis I converted your message into a file since it's above 15 lines :+1:
what do you think?
I'll have a look later, dinner time here, and need to put the kids in bed after that
yes me too
whats the right (working) way to do this:
{{get_info_response | default('{cars: [{car_id:{}}]}')|from_json}}
I am trying to not get this error:
UndefinedError: 'dict object' has no attribute when is not the expected output.
post all your code and the error
{% set t = value.split('\r\n')[3] | float(0) %}
{% if t = 0 %} 0
{% else %} 5.5*t*1.5
{% endif %}```
This is my above value template, the error I'm getting is `line 8: invalid template (TemplateSyntaxError: expected token 'end of statement block', got '=') for dictionary value 'value_template', got "{% set t = value.split('\\r\\n')[3] | float(0) %} {% if t = 0 %} 0 {% else %} 5.5*t*1.5 {% endif %}\n"`
line 8 corresponds to the value_template: > line
You have = where you need ==
you're also going to need {{ around your equation }}
post all your code and the error
so value_template: > {% set t = value.split('\r\n')[3] | float(0) %} {% if t == 0 %} 0 {% else %} {{ 5.5+t*1.5 }} {% endif %}
indent your template
already done, the formatting here on discord doesn't carry it over with my clipboard
the next question is how to get that particular entity to show up in a universal media entity as a slider on the ui
i've already got it in the attribute as volume_level and declared its unit_of_measurement as "%"
No idea what you’re asking here
so that value template belongs to a tcp command I have to send to an extron media switcher. The value template gets the volume level for a particular output
https://www.home-assistant.io/integrations/universal/ using this integration, i'm attaching the value_template i wrote above to the volume_level attribute
That needs to have a volume that goes from 0 to 1
ah, so take my else statement and divide by 100
right, the documentation doesn't specify a format it should be in.
I still don’t know what you mean by sidebar
on my denon avr media card, i've got mute, volume up, and volume down, followed by a slider
i wonder if it needs both volume_level AND volume_set
gotcha. well back into the code we go
Heya, been sent here from the front door, they told me this is where the nerds hang around. 😉
I need to evaluate a value incoming from modbus, before it is finally appearing within an entity.
So I wonder if this is possible within the same entity that holds the value of the modbus register.
Is there any possibility to use state_attr() or similar for the 'own' value of an entity (if yes: how to reference it), or do I always have to put the evaluation into another entity?
Example - I would like to avoid the extra 'outsidetemp_final' entity, just work with 'outsidetemp' to keep it as compact as possible, as there will be hundreds of such modbus items:
outsidetemp:
# here all that is needed to get a register value from modbus
outsidetemp_final:
value_template: >-
{% if states('sensor.outsidetemp') | float == 3276.7 %}
# 7FFFh - sensor is 'off', replace with 0 for charts
0
{% elif states('sensor.outsidetemp') | float > 3276.7 %}
# below ZERO, INT16 to Signed INT
{{ states('sensor.outsidetemp') | float - 6553.6 }}
{% else %}
# all good, go ahead with sensor reading
{{ states('sensor.outsidetemp') }}
{% endif %}
(quite new to this, installed my first HA 2 days ago)
first, states are always strings, so things like {{ states('sensor.outsidetemp') - 6553.6 }} won't work. You need {{ states('sensor.outsidetemp')|float - 6553.6 }}
like you did earlier 🙂
ooops, over looked that one - thanks 🙂
I would tend to set a variable for the outside temp, to save looking it up 3 times. If you need to define lots of these don't forget you can set up a template macro.
{% set temp = states('sensor.outsidetemp') | float %}
I managed to read out the first registers in HA already; next step is to deal with what I've read.
I am not familiar with Modbus, so don't know what you need to get in and work with. I assume you are using the Modbus integration to work with this? Sorry to not be more help.
Yeah, using the standard Modbus implementation of Modbus. Got the first temperatures already in HA, that's not the point:
@eager yarrow I converted your message into a file since it's above 15 lines :+1:
This is how it's displayed so far:
ooops, no pic pasting, I see
What I need to do is post-processing after reading.
What about
{{ now().strftime("%m%d") > "1121" or now().strftime("%m%d") < "0109" }}
what is the best practice for sending a variable number over tcp or telnet? ideally i'd have something like service: telnet.send or tcp.send and put all the date in the data: value under it
Tom, do you need all the values all the time, if not if you only need them in automations you could use the Variable definition to compute them when you need them. Probably depends on if you want to track the refined values. Another "hack" could be to create a custom Integration based on the main one and use that to convert before the sensors are created.
Most people using my plugin have 50...70 variables (~25 out of that are the same for all of them). Therefore my aim is to have it as flexible as possible.
A few have 150-200 variables.
I'm trying to get as close as possible to my old plugin and visu - see screenshot here. Not sure if I can get close to that in HA, though - we will see. 😉
@lyric comet I've seen that thread before. I'm just not sure the best practice to get a value_template into the command_on line
or if thats even possible
There is an example in the thread. Sending TCP is a very outdated way to communicate, I assume what you are talking to is ancient.
Good luck with all that. One other thought might be a script of your own to write the yaml for the conversion templates. If you go the macro route it makes each new sensor very simple, just a couple of lines.
i've kinda thought about that too. its pretty simple.
"01*$VARV" is all I have to send, where $VAR is some number 0-64
converting 0-64 to 0..1 is easy
and the volume_set function already provides 0..1
i'd really prefer not writing an integration for this thing.
Zombie, you should be able to use the command line options as discussed in the Thread. One of the experts might be around in a while to help.
Yeah, it's a bit of stuff to do, and a steep learning curve in HA. Let's call it my winter project. 😉 Anyways, now I have a few more keywords for googling things together, thanks for the help! 🙂
@lyric comet I'm not sure the command line options are available in the container
can somebody explain me why following code returns True
{% if states('sensor.worktime') | is_number -%} True {% endif %}
but this code returns TypeError: '>' not supported between instances of 'str' and 'int'
{% if states('sensor.worktime') > 0 -%} True {% endif %}
{{ states('sensor.worktime') | float(0) > 0 }}
states are strings
{{ "5"|is_number }} -> True
lol, that's weird
just sayin'
it's how it was designed, and it's purpose
"can it be parsed as a number?"
I use HAOS and can do command line things, but I have not attempted anything too complex.
okay understood, but this macro doesn't work also
{{ states(entity_id) | float }}
{% endmacro %}
macros only return strings
Jinja is not meant to output anything other than a string. Any thing else you see w/ HA and templates returning "types" is all handled after the template is resolved.
if you use {{ }} anywhere, it's returning a string
that's just how Jinja works.
thanks.. that explains a lot
@marble jackal regarding the shower automation I have an error on option 2
Error while executing automation automation.shower_test: Error rendering data template: Result is not a Dictionary
service: input_number.set_value
target:
entity_id: input_number.last_shower_water_consumption
data: |
{{ usage | round(0) }}
that's not returing a dictionary, that's returning a single value
you forgot value:
that is what it says
wowwwwwwwwwwwww
service: input_number.set_value
target:
entity_id: input_number.last_shower_water_consumption
data:
value: |
{{ usage | round(0) }}
You did not like my answer then.
Hello everyone. Im trying to change this template to round to 0 decimals but havnt been able to get it to work. Is there a way? ${states['sensor.master_bedroom_broadlink_temperature'].state}°C
That's JavaScript and #frontend-archived
ok thanks
what would be the way to have a template select the state of the sensor one hour ago?
It's not possible
the easiest question you needed to respond to all night, 😛
makes sense why i couldn't find anything
I have a binary sensor template and alert.yaml for my freezer, and I have the alert give me current temp,
but was curious if every hour it could tell me if the temp is going down
You'd need to use an SQL sensor to query the database
thats to much work, I think I can remember if the freezer is getting colder again
Look at a trend sensor
yea
Or derivative
basement_freezer_temp: name: "Basement Freezer Temp" entity_id: binary_sensor.freezer_temp state: "on" # Optional, 'on' is the default value repeat: 60 can_acknowledge: false skip_first: true message: "Its getting hot in here: But I am a freezer you fucking idiot. Current freezer temp is {{ states('sensor.inkbird_freezer_thermostat_temperature') }} " done_message: "ICE ICE BABY!: The freezer is back below zero" notifiers: - mobile_app_andrew_phone - mobile_app_jessica
Alert.yaml is AWESOME btw
(have a binary_sensor template that trigger if above zero)
Its so rare it happens, and like today when it happened. I left the door open, I closed it. So I "knew" it was getting closer, but thank you
Second question, similarly, there is no way to make the weather entity a binary_sensor "Will it rain tomorrow"
"Will it rain today" Will it cloudy today? or is that possible?
@modest isle I converted your message into a file since it's above 15 lines :+1:
@modest isle - I think what you're probably missing is unit_of_measurement
However that value template looks strange, maybe it should be {{value_json.Elevation}} ?
Sensors generally need a unit to be plottable as a numeric graph. Otherwise they get the timeline style graph.
@lofty mason that could be it! I’ll have to mess with the unit_of_measurements option.
As for the value template, I changed it to your suggestion and seems to work the same - elevation is graphed in a “sensor card” yet flow rate is only displayed as the latest value in an “entity card”. How would I format the value_template to track both flow rate and elevation?
A sensor can only have one state (which is graphed). Attributes are more like seconary information, and you can't directly graph it.
You would want to create multiple sensors if you want multiple pieces of information.
You can either make 3 command_line sensors, or maybe better a single command line sensor with 3 attributes (as you currently have), and then additionally 3 template sensors, one for each attribute, so you can graph them.
Good morning
Now I found you, would you please help me correct the following error?
What are you trying to calculate there?
Can you share the complete config in which that template is used
How can I fix this error: expected float for dictionary value @ data['value'] in:
service: input_number.set_value
entity_id: input_number.home_solar_energy_total_production_last_value
data_template:
value: "{{ trigger.to_state.state }} | float"
Value of the sensor (sensor.home_solar_energy_total): 30750.1
It is so strange but I can't find this in my configuration
the only reference in my files is platform time_date
All states are strings, and it expects a float. So use the float filter/function to convert it
Did you maybe create a template helper in the GUI?
nope - no such entry
I removed this integration
I found it
it was a part of an automation
and it is part of a blueprint
line 122
It doesn't guard enough against unwanted states
It just isn't a correct template
"none" should be none
But a lot of other improvements could be made
I thought I was doing that already, but I think it is caused because the function is outside the {{ }}
Yep, it should be inside the curly brackets
I've got a restful sensor that I'm trying to get to fail gracefully. If the server is unresponsive, value_json is seemingly unknown or unavailable or undefined. This template doesn't seem to do anything: value_template: "{{ value_json.packs[0]['c1'] | replace('*','') if value_json not in ['unavailable', 'unknown', 'none'] else states('sensor.ldpp_p1c1') }}"
And I can't reference the value_json outside the sensor because it's a restful sensor
I really just want my entity to hold on to it's last known good state rather than every few seconds showing Unavailable for its state
I just realized. I would only want to recall the current value of a previous automation, or alert. Still no way when stating a sensor value, to store that as a template. I.E. I would basically be displaying previous state, and new state. does that make sense?
You can get the previous and current value of an entity in an automation when the state changes
including alert.yaml ?
you'd have to get someone smarter than me to look at the code, but I'm not sure that the value_template will even render if the server is unresponsive. If it does and just doesn't define value_json then you could check by using if value_json is defined but I doubt that will work
That does not work. That’s what I had initially but it didn’t do anything.
then you probably need to create a template sensor based off your rest sensor
why don't you try value_template: "{{ 1 }}" and see if that still becomes unavailable when the server is unresponsive
Interesting. What would that tell me?
if it remains 1 then it confirms that the template still renders when the server is unavailable. My bet is that it still becomes unavailable, which means there is nothing you can do inside the value_template to avoid the sensor being unavailable
I would say that it does not. I can see value_json is undefined and trying to reference the associated values nested fails because they don’t exist in that moment
It’s like there needs to be a way to say “if there isn’t valid json this time, just reference the last value and try again later”
is that what the log says? Can you post the error?
the template tool will definitely say that if you don't define value_json
I don't know what's in there. I'm talking about entities. Whatever entity you're using in your alert can be used as a state trigger in an automation.
so Petro, the automation worked yesterday. Today it was stopped by condition
I have mqtt sensors that send humidity. Unfortunately, some send, for example, 12% others send 12. What is the right way to deal with this? Some sort of template for the payload entry in the sensor definition? Basically looking for what to search for.
I just ran a couple tests:
- I used
http://www.google.comas the URL, which doesn't return valid JSON. I used the template{{ value_json is defined }}and the sensor state wasfalse. Therefore the template rendered and the variablevalue_jsonwas not defined - I did the same as above but used
http://date.jsontest.comas the URL. The sensor returnedtrueas expected - I did the same as above but used a non-existent URL
http://jsontestx.com. The sensor disappeared, and the following error was logged:
Platform rest not ready yet: [Errno -2] Name does not resolve; Retrying in background in 30 seconds
I'm not sure how to replicate the problem you are seeing.
@mighty ledge because you propose it here is the condition
condition: template
value_template: >-
{% set attr = trigger.to_state.attributes.match %} {{ attr and attr.match and
attr.confidence > 95 }}
would you please take a moment and have a second look?
here is the trace
https://pasteboard.co/gNRq2smd7Cj0.jpg
and here is the state attributes, when the automation was triggered and stopped by condition
https://pasteboard.co/YpAtzJTUzQdX.jpg
match was true and confidence was almost 100%. So why it was stopped???
Hi, I struggle with templates and I couldn't find an example template for what I'm looking for. In webcore, it was easy to conditionalize an automation if a script has ran in the last X mins/hours. Can somebody help me craft a template that will let me conditionalize an automation if a script has ran in the last 5 mins please? I thought I saw this in the docs before but I couldn't find it.
kindly asking, any one can have a look please?
I suggest that you review the "Changed Variables" section as shown here:
see if the values match what you think they are
Can you share the json of this trace?
You can download it in the top right corner
hello @marble jackal , here it is
https://pastebin.com/Rut2WmwP
all conditions met, but it was stoppped
so?
pls hold
can you please convert this time for me ?
the one on json file
so i check with double-take data?
the timestamp is not the same
on this, confidence is pretty high
(99,48%)
what is the time stamp please?
oooooooooooooo
It could be that it detected two people and that the state didn't change
Enable the condition, and remove the to and for from the trigger
That version was better after all 🙂
I figure it out
it didnt trigger at all!!
the screenshot was from 18.07 but json was for a previous trigger at 4
And why didn't it trigger?
The json is from the same moment
I guess your timezone is GMT +2..
Which would make the json from 18:07:08, which is the same time as your screenshot
but see the screenshot
the one i sent with the state attributes, confidence was 99%
so it can't be the same
I already explained a possibly cause for that. If it did two matches on the same camera after each other, and the first one is below 95% it won't trigger a second time, because the state doesn't change
I mentioned two people there, but it could also be a second match on the same person
got you
So i will leave the trigger as it was at the first place and add condition for the camera..
You can use a template condition like this; it will be true if the script ran in the past 5 minutes.
{{ state_attr('script.my_script', 'last_triggered') > now() - timedelta(minutes=5) }}
Correct me if i'm missing the channel, but i'm trying to offset some thermometers, found something on the forum but don't quite get it
https://community.home-assistant.io/t/adding-offset-to-sensor-data/20382/5?u=cristianmihai
Is the first bit(starting with homeassistant:) supposed to go into configuration.yaml ?
And..where should i put the second code block? it looks a bit like the config for ESPhome, with the pin defined and everything, however i don't think that's where it should go
is this an ESPhome device, and do you want to take care of the offset in the ESP device itself?
it is ESPhome, i don't quite care where i take care of the offset as long as i can get a working value
personally I would do it on the device itself, but it's up to you. You can't change the sensor in home assistant, but you can create a new sensor in home assistant with the corrected value. That is why I would recommend doing it on the device itself
on the device it is
filters:
- offset: -4.0
found this, not sure it will work but gonna try
if you need help with your esp device config they have their own discord server, or you can try in #diy-archived
got it. thanks!
that woked perfectly and gives me the structure for other projects. Thanks!
i need help with a template trigger:
if last day of month trigger at 23.55 else trigger at 00:10
this was a pain. Alexa Media has a string object array, and i needed a nested value:
{%- set json_string = states.sensor.library_dot_next_timer.attributes.sorted_active|from_json() -%}
{%- set data = namespace(vars=[]) -%}
{%- for item in json_string -%}
{%- for key, value in item[1].items() -%}
{%- if key == "version" -%}
{%- set data.vars = data.vars + [value|int] -%}
{%- endif -%}
{%- endfor -%}
{%- endfor -%}
{{ data.vars|first|default(0) }}
probably a better way but this gets around updating a variable from in a loop
anyone?
I was thinking something like
{{
(now().strftime("%d") | int) == states('sensor.days_in_current_month')
and
states('sensor.time') == "23:55"
}}
as trigger
@final trellis I converted your message into a file since it's above 15 lines :+1:
can someone confirm pls this is ok ?
@lament maple I converted your message into a file since it's above 15 lines :+1:
You have a sensor that tells you the number of days in the current month? And another sensor that has the time in 24hr format with only hours and minutes? If that is all true, then you are just missing the filter to convert of the number of days sensor from a string into an int
You could do the template without those sensors, but if you have them you might as well use them. I’d say it’s also generally a bad idea to do an == comparison using time but at least in your case it will be true for a full minute. It’s better to use >= or <=
You can also use now().day instead of using strftime() and converting to an int
The follow clause will not work:
(now().strftime("%d") | int) == states('sensor.days_in_current_month')
States are always strings... you can't compare an integer to a string. Remove the int filter:
now().strftime("%d") == states('sensor.days_in_current_month')
@final trellis did you could also do all this without the need for additional sensors
- platform: template
value_template: >
{{
(now() + timedelta(days=1)).day == 1
and now().strftime('%H:%M') == '23:55'
}}
- platform: template
value_template: >
{{
now().day != 1
and now().strftime('%H:%M') == '00:10'
}}
Your 00:10 trigger should also trigger on the last day of the month, and not on the first day of the month
You could combine the triggers above in one trigger, when you combine them with or (and add some additional parenthesis)
What i need is the following
all days of month trigger at 00.10
but the last day of month trigger at 23.55
am using the extra sensor to determine the last day and then do the comparison
If all triggers should be roughly 24 hours apart, you want to trigger twice on the last day of the month (at 00:10 and 23:55) and not at 00:10 on the first day of the month (that would have only have 15 minutes difference with the previous trigger)
last day must trigger before 0.00.
Yes, I get that
i have utility meters and they will reset. i want to avoid the extra helper
You know the utility meters store the previous period in an attribute right?
so i guess your implementation is wrong
and my version doesn't return an error
https://pasteboard.co/OudEDsHkUUwJ.jpg
check this out too please
https://pasteboard.co/aeSVMxkiriGr.jpg
here is the final implementation
https://pasteboard.co/t4GYOUzxGWOc.jpg
I am so stupid 🙂
I forgot about that
How would I get a list of just the entities exposed to a specific voice assistant from a template?
That's not possible using Jinja templates
Appreciate the reply, thanks. Is there a way to put all exposed entities in a group (the old style domain agnostic groups) without manually copying them all to yaml each time? - I am working on a daily briefing script for a local LLM, and am trying to feed it a list of states for analysis
You could have a look at how this integration does it
https://github.com/jekalmin/extended_openai_conversation
This looks interesting - thank you for your help.
am using the following code, which create a random sentence each time for my TTS automation
https://dpaste.org/ycv2V
can someone explain how the following works??
{{ "{} {} Celsius.. {}".format(rm1, states("sensor.temperature_outdoor"),
rm2) }}
you're providing a format string with {} as placeholders for the parameters that you pass to format()
you're providing a format string with {} as placeholders for the parameters that you pass to format()
yes, that's what I said
is there any documentation for this please? I use it in one automation, works but it was n't mine
that's clear
there are three links in the channel topic that explain Jinja templates
that example is using a Python method to format a string: https://www.w3schools.com/python/ref_string_format.asp
Jinja uses Python objects and supports the methods on those objects
ohhhhh it uses empty placeholders?
that just means that it fills them in the order you provide to format()
you can play with this in
-> Templates and see what happens
i got it now
Is there anything specific template in HA for converting seconds, e.g. 37,800 Seconds = 10h 30m ?
Managed to add my clothes dryer but it reports in seconds. Got to fix that. 😛
If it will never be longer than a day, you can use {{ 37800 | timestamp_custom('%-Hh %Mm', false) }}
Hi, I´m using the rest platform and then a template
device_class: temperature
unit_of_measurement: "°C"
value_template: '{{ value_json["eta"]["value"]["@strValue"] }}'
It works great for most of the valus, however for some the string has , instead of . and then I got an error. So the question, how do add to the template so it transform the , to an .
I find it a bit strange that it sometimes uses . as decimal seperator and sometimes ,
but if that is indeed the case, you can use
value_template: '{{ value_json["eta"]["value"]["@strValue"] | replace(",", ".") }}'
Hi!. What's the correct device_class to use for prices (prices per unit I guess)? I tried monetary, but this only accepts totals as state_class which is not appropriate. I'm tyring to use template sensors to calculate average gas prices or statistics about the cost of running my car.
A device_class is not required, you can just not provide the line
it's also not required for long term statistics, unit_of_measurement and state_class are
That works great, thanks
@marble jackal I 'made' this: {{ int(states.sensor.aeg_droger_appliancetotalworkingtime.state) | timestamp_custom('%d days and %-Hh', false) }}
How do i get that working inside the entity? e.g.:
type: entities
entities:
- entity: sensor.aeg_droger_appliancetotalworkingtime
name: Appliance total working time
oh you can turn them int 'function' like things i read
you can create a template sensor
@terse scarab what is your end goal here, you want to display the time on on your dashboard?
whats a good resource for writing a template, for example for a Title card in the UI, to say 'Currently its 22 degrees and sunny'
essentially it would be returning a state attribute from my weather entity no?
typically frontend can't handle templates, so you'd first need to find a card that accepts them
yeah the mushroom title card does accomodate that
am reading the Template docs on the HA Site but can't quite make sense of it (i am also burnt out lol)
I think I just got it...
Currently, it's {{ state_attr('weather.home', 'temperature') }}
you'd get the temperature using the same thing you did here #templates-archived message
yep
nice! funny pickup on my previous post haha
sometimes just have to type it out to realise what direction I need to be heading 🙂
@marble jackal Yes i want to show that in the dashboard.
You could create a template sensor then, or display it using a card which supports templates (a markdown card for example)
If you go for the template sensor route, you could create a sensor which shows the date and time it should be ready (so the current time + the number of seconds). That will be displayed on the frontend liek In 10 hours or In 46 minutes
(only the highest time fraction)
So an entities card is never gonna work for it?
ok works
(I added markdown card, works right away)
Yeah i think i prefer doing it straight in the card. Much less cumbersome and instantly see the result when trying stuff. Thank you 🙂
Everyone making wheels.
I used markup. Coz i can just template code straight into it.
Looks like this now. https://imgur.com/90l12LG.png
I can live with that.
@twin compass I converted your message into a file since it's above 15 lines :+1:
which is giving me this error:
Error rendering data template: TemplateRuntimeError: No filter named 'weekday_full_name' found.
is there something wrong in the elif statements? cause before the elif it was working
or in jinja is literally or
| is apply filter
with or statements, it's best to make that a list anyways
would that be 100% necessary?
{% if weekday_full_name in ["Monday", "Wednesday"] %}
ok i like that
I have a simple automation where 'When person enters Home zone' then 'Unlock front door'. I would like to add a condition where this were to only trigger if the Person has been 'Away' for at least 1minute.
Struggling to use templates to see previous states to make this work
Is there a way to display a duration sensor with days as the maximum unit instead of hours?
please can you help me with the following template
as soon as I insert the random function it crashes
I tried to create a template - please see attached. Any way to test it?
that template will only work in an automation
there should be no "crashing", that's not something HA would do. Are you saying it produces an error? If yes, post the error.
zone triggers do not have to_state or from_state
Ah damn, any other ideas on how I can set this automation up then please?
petro, i know it does.
it is the intentation on the random part
that part looks fine
They should create a replace binary_sensor with a trigger for 'not_home' and for: '00:01:00'. Then use the state of that sensor
working as expected
yes it does. but when it is inserted it within the if statement of the specific person it doesn't return an error
but it doesn't run either. I bet it has to do with intentation and quotes
Thanks for the advice RobC - how can I create this sensor please? I dont see it within Helpers
That all looks fine
i know it does
indentation only matters with yaml
what you're writing is jinja, that's all inside the yaml field
100% makes no difference
but it doesn't run.
if i delete the random function within the statement "makis" it will work for statement 'xxx'
I'm not sure what to tell you, there should be an error if it doesn't run
are you just saying "there's no error" but you aren't checking the logs?
it's not a yaml error. i think the tts engine doesn't parse it
ofcrouse not
Yeah, you aren't looking in the correct place for errors
you have to check homeassistant.log
for jinja errors
please accept my apologies - i will try once more
What if I use state trigger to home instead
no need to apologize, it's not straight forward. You'll learn where to check in time
Yep, that will work
Thank you all! Is there any way I can test it?
not without messing with your person
Ok thank you again, will try it tonight
the problem was n't in the action part
@final trellis I converted your message into a file since it's above 15 lines :+1:
thank you petro, once more you are more than expected ...!
Like a Transformer?
Bumblebee
please excuse a newbie question. I was experimenting with calendar events to TTS
although I have an event response this is not been announced. No errors
What I'm doing wrong ??
https://dpaste.org/yHG59
i get an error on jinja template
2024-01-29 23:13:51.692 WARNING (MainThread) [homeassistant.helpers.template] Template variable warning: 'dict object' has no attribute 'events' when rendering '"{% for event in agenda.events %}
{{ event.summary }}: at {{ as_timestamp(event.start) | timestamp_custom('%-I:%M %p') }}
{% endfor %}"'
The agenda doesn't have a property called events.
No it is calendar_personal.events.summary as far as I can see.
i dont want the summary only - i can get this from attrbute ...
i want a for loop
with all the information
i thought i could do a loop with the "events"
You can, but you only have one event in the result, try extending the amount of time to show more events.
Yeah, in my test the agenda object has a property called calendar.personal and then events is within that.
pls excuse my ignorance. I just started with calendar
🙂
I lost you
the problem is that I have no tts.
if i just a simple text before the start of the loop I hear it.
You need to change the start of the for loop:
{% for event in agenda['calendar.personal'].events %}
for daily events my service call is correct right ?
Well, yes and no. Assuming your trigger is only run once a day, then it will get all the events in the next 24 hours.
ok, however it starts from now() , correct?
Yes
But if it runs at 11pm, it'll tell you about the 7am event, and if it runs again at 6am, it'll tell you about the 7am event again.
It's up to you if that's really what you want.
so if a PIR triggers it at 08.00 am , I will get the events until next day at 08.00
Yes
what does it means? "Event end was adjusted to prevent negative duration"
when i add a new event with start 7/2/2024 it goes and adds end 08/02/2024
It's very likely something like:
- Event start 8pm
- Event end 2am
But if the dates are the same, then the event would "run backwards" from 8pm back to 2am the same day, which is what it's trying to fix.
going back in time requires additional hardware
hello, could someone please advise why i am unable to save this into an automation action:
service: "{{ service }}"
target:
entity_id: "{{ entity }}"
data:
{%- if brightness == 0 %}
brightness: "{{ brightness }}"
{% else %}
{}
{% endif %}
it's saying something about message malformed, could not determine action. template seems to work fine in template tool
Well, your automation doesn't know what service, entity, or brightness are
You'll need to figure out what you set those variables to in the template editor, and get the correct trigger variables/whatever it is you need to make it work.
it's defined in previous step (variable)
also, you can't template keys like that
so i'd need to make an if/then block?
Or a choose, but without seeing what your whole automation looks like, we're just taking guesses
ok, thank you.
about calendar, when the state changes ?
obviously when the event occurs, the state will change when the time of the event comes. correct?
am looking for a condition, before I execute the TTS action
to prevent an empty TTS ... announcement
the condition am looking is "if there is an event for the day"
You probably want an if or a condition with a template in it.
{% agenda['calendar.personal'].events != [] %}
Or similar.
maybe like this ??
{{ agenda['calendar.personal'].events | count > 0 }}
Should be okay
Hey guys, im trying to make a template sensor that is either off or on based on if the climate ac state is auto or off.
the helper does change but has the coding in the value
template:
- sensor:
- name: "Bedroom AC Power Status"
state: >
{% if is_state('climate.bedroom_ac', 'auto') %}
on
{% else %}
off
{% endif %}
Preview:
Bedroom AC Power Status
template: - sensor: - name: "Bedroom AC Power Status" state: > off
the helper has the code in the value
You likely just need {{ is_state('climate.bedroom_ac', 'auto') }}, but you should make sure it's a binary_sensor, not a sensor
And you should probably change the > to >- so that white space is removed in your output.
Thanks that did it. how do i add one more value for heat.
{% if is_state('climate.bedroom_ac', 'auto') or is_state('climate.bedroom_ac', 'heat') %}
{{ is_state('climate.bedroom_ac', 'auto') or is_state('climate.bedroom_ac', 'heat') }}
Thank you! been at it for a while
is it possible to do something like.
get an automation to count how long its on for the day and have a history of that value for the day ?
An automation itself shouldn't be on for that long, but you can use the history to see how long an entity is on for.
can this be done in ui or just yaml ?
YAML
- platform: history_stats
name: Bedroom AC Daily Usage
entity_id: binary_sensor.bedroom_ac_power
state: "on"
type: time
start: "{{ now().replace(hour=0, minute=0, second=0, microsecond=0) }}"
end: "{{ now().replace(hour=0, minute=0, second=0, microsecond=0) }}"
duration:
hours: 24
does that look right ?
The end is wrong
end: {{ now() }} is what you need
Otherwise it'll be really confused by the window being from midnight just done to midnight just gone
okay Thanks for the help! so i can use that as like an entity on my bedroom ui page ?
Once you have reloaded your config/restarted and it shows up, yes.
sweet restarting now so i'll test if it does anything 🙂
I would recommend adding a unique_id as well, it's good practice
unique_id: bedroom_ac_daily_usage ?
That would be a good one.
i got the graph up. but i dont understand what the value means at the top.
https://ibb.co/6J43QMS
17.291, but the graph shows 0.00480
17 seconds = .004 hours
the duration class sensor format is a little weird and not immediately intuitive :\
argh ok, so if its on for 1 hour it will be 3600
nah it will eventually show mm:ss and eventually hh:mm:ss
okay ill turn it on for a min to see how it changes the formatting
okay cool so it just changed to 1:15
thank you both! made this alot less complicated 🙂
are todo lists usable via template yet or is that still in development? Just trying to add some todos to my morning announcement and not able to find any docs on doing it
What do you mean "via template"? You can retrieve, add, update, and remove todos via service calls with or without templates. https://www.home-assistant.io/integrations/todo
I want to return a list of items to be read off by tts
ok thanks I'll take a look
Hello! I have a D1 mini device running esphome. In home assistant this is a "press" button to toggle on/off. I have a button template that should give me a "real" on/off button instead of a press. Which it does, but when I use button.turn on, if it's already on it then turns off.. Is there a way to fix this?
@sturdy yarrow I converted your message into a file since it's above 15 lines :+1:
That's because the template switch is trying to send the "on" command again. You probably need to use a script as an intermediary, and call script.icemaker_on and have the script check if the binary sensor if off before sending the button press, and the same for the inverse
(Usually devices are state aware, or can handle things like this themselves. E.g. if you tell a blind to open and it's already open, it will either ignore it, or make sure it is open by briefly running the motor)
Ah yeah, it kinda makes sense to me when you say it.. Can I maybe use an if statement inside the template? If I need to make a script too for this, it would probably be easier to find a way to change the code in the D1 mini running the icemaker 🤔
I was looking at making a binary sensor for bedtime. I was going to set this based on phone charging after 11.
Should I have 2 triggers, charging state and 11? Then the state is after 11 and state charging?
Additionally, how would I check for after 11pm and before 6am (to account for plugging it in after midnight)
Hello all
so I want to take my sensors and calc them together?
- name : "Mains_L3_watts"
state_topic: "***/*****/Mains_L3_watts"
value_template: "{{ value_json['****'].P004.get('R064', 0) / 1000 }}"
- name : "Mains_L2_watts"
state_topic: "***/*****/Mains_L2_watts"
value_template: "{{ value_json['*****'].P004.get('R062', 0) / 1000 }}"
- name : "Mains_L1_watts"
state_topic: "****/****/Mains_L1_watts"
value_template: "{{ value_json['****'].P004.get('R060', 0) / 1000 }}"```
please can someone help?
I'm currently (trying) to write a JSON sensor to pull data from a community wind farm i'm apart off, display it in home assistant. i have the figure i'm looking for in the dev-> template tab but my yaml sensor returns unknown, if anyone could take a look over what i've done i'd appreciate it, json sample and my yaml are here: https://bpa.st/X2VJCRLNEFNBK344BKLG2WKS7I. thanks in advance
@mighty ledge ? Sorry, are you busy ?
Generally, don't tag people to ask for help - it comes across as bad manners, you’re demanding somebody answers you. It’s different if you’re thanking somebody, obviously. If you do tag somebody keep it polite and respectful. Remember that everybody is a volunteer, and nobody has to help you, and people may block you.
Similarly, please don’t DM (direct message) people asking for help. It also comes across as demanding, and means that others can’t learn from what you do.
Finally, please keep tagging people in replies to a minimum. That too can become annoying very quickly and should be used only when it's necessary (such as if it's been a long time, or there's multiple conversations going on). When using Discord's new Reply feature it defaults to pinging the person you reply to, click @ ON to @ OFF to stop this - on the right side of the compose bar.
What's your log say
not in the log, grep'd for ripple
[lime@lime-82v6 hass_config]$ cat home-assistant.log.1 | grep ripple_sensor [lime@lime-82v6 hass_config]$ cat home-assistant.log | grep ripple_sensor [lime@lime-82v6 hass_config]$
I'd suggest restarting again and checking for errors in general, perhaps itll show under rest
i'll tail -f it, watch it as i restart
still not in it, not under rest, or sensor, or ripple
How is that config snippet included in your configuration
sensor: !include_dir_merge_list sensor then a local dir called sensor
Still think you're missing something in the log, but I'd probably enable debugging for rest and see what's up
homeassistant.components.rest: debug in your logger->logs
it is 2024-01-30 14:01:01.282 DEBUG (MainThread) [homeassistant.components.rest.data] Updating from https://rippleenergy.com/rest/member_data/3 api key removed
Yup... keep going, there should be more
but still
2024-01-30 14:01:01.457 DEBUG (MainThread) [homeassistant.components.rest.data] Data fetched from resource: {"error": "Not authenticated"}
There you go
almost certainly
if i;ve copied my api key in secrets wrong all this time and thats all thats wrong
thanks, copied and pasted the API wrong, must have included a trailing space or something
now i can play with the data i want to pull
is there a way to have the url hardcoded and only input the api into secrets ?