#templates-archived
1 messages Β· Page 10 of 1
thank you a lot!!!
Thanks Fes,
I thought about concatenation too but the parser really doesn't like the asterisk at the beginning...
If I remove it, no problem
maybe regex replace
beginner looking for some help building a script
Is there anyone around that would be willing to walk me through building an automation/script using a template that is probably not that complicated?
I have a button, when pressed starts an automation. I want the automation to grab the value of a field, and then add that value to a counter. I'm using the template developer and figured out how to get the value of the numerical field,.... but.. I can't figure out how to add that value to a counter.
I can add the increment counter service to the automation but it only adds one increment instead of a specific number of increments
Basically I got a value in a numerical field. when I push the button I want to take that number and add it to another field.. I gues it doesn't have to be a counter?
seems like a counter maybe isn't what you want
Ah ok
sounds like a job for an input_number
Thanks.
If I have a value how would I add it to an existing input_number?
I have the value in this string:
{{ (states('input_number.minutes_to_add') | float) + (states('input_number.hours_to_add') | float * 60) }}
That string ouputs the number that I want to add to
input_number.time_credits_personal_education
Oh. I need to google "how to set value of input_number from template
yes, you do π
Before I dig into this .. can you tell me if it's possible to directly set the value of a input_number from template code? Or do I need to set it up in the automation or something?
I dont even know if that question makes sense. I just meant that I think it woudl be easy if I could write it all out in the template code but I dont know if thats possible.
My questions probably dont make sense I'm such a noob.
What does the ``trigger.to_state.statedo in"{{ trigger.to_state.state if trigger.to_state.attributes.phone == number else this.state }}"`?
all you have to do is call the input_number.set_value service, and there's even an example on that page of using a template
@inner mesa Yes I ditched the script and did it in the automation. But I dont think this syntax is correct:
action:
- service: input_number.set_value
data:
value: {{ (states('input_number.minutes_to_add') | float) + (states('input_number.hours_to_add') | float * 60) + (states('input_number.time_credits_personal_education') | float) }}
target:
entity_id: input_number.time_credits_personal_education
mode: single
I think I can't just put template code into the value spot right?
it returns the new state of the entity that triggered the automation. see the third link in the channel topic
add quotes around the template and you're fine
ok, but why does it need to be there? Sorry if this is a dumb question, I'm thinking about this if statement for like half an hour
sry btw for ping
it sounds like you're just asking what that template does
"{{ trigger.to_state.state if trigger.to_state.attributes.phone == number else this.state }}"
I misspoke earlier because I misread it. it's the new state
oh, so it's the same as
{% if trigger.to_state.attributes.phone == number %}
trigger.to_state.state
{% else %}
this.state
{% endif %}
?
yes, if you added {{ }} to the values
uh, yes of course
it's just a shorthand way of doing that
it's just like reading a sentence
yeah, it's so easy and was right in front of me the whole time...
@inner mesa Is there a way to display a number on a dashboard instead of having it like an input field? I dont want to be able to change the value of the number unless it's the automation doing it.
I can display it like a gauge I guess. is that the only way?
Use a markdown card
Ohhhhhhhhhhhh snap. Thank you
@versed lava posted a code wall, it is moved here --> https://hastebin.com/xobunonoju
damn, that wasn't intentional
@inner mesa Thank you for your help. I made a rewards system where I can earn time to do things I want to do, by completing time doing things I dont want to do. https://ibb.co/98cYnJY Thank you I really do appreciate it π
Whatβs the yaml look like for all that?
hm. Well. Unfortunately theres a lot of automations. I should try to put it all in one file instead.
one sec lemme se if I can find it
I have the file editor I'm looking at the automations file.
Yea
I wish I had one big awesome automation instead of all these seperate ones, but here's basically how it works.
-
Helper button for task I dont like doing (i.e. Cleaning/Laundry).
-
Helper button for the task associated to Cleaning Laundry that I get as a reward (i.e. Watching TV)
-
input_number entity that holds reward minutes earned (i.e. Watching TV)
-
input_number for minutes
-
input_number for hours
-
Automation that takes input for time logged doing work task saves it as time for watching TV (i put in math rules so it's not always 1:1 sometimes it takes say 4 minutes of work task to achieve 1 minute of fun task) https://www.codedump.xyz/yml/Yy0dBQfwtiwknb2Y
-
Automation that lets me claim earned time credits https://www.codedump.xyz/yml/Yy0dTQfwtiwknb2Z
-
Code for markdown card https://www.codedump.xyz/csharp/Yy0daQfwtiwknb2a
So basically if you add minutes or hours together it converts the hours to minutes and adds them together.. also.. if you add some time logged but after conversion it outputs a decimal like 1.666666666 minutes it rounds the minute so that you get whole numbers for minutes.. or... only one decimal place, so that it doesnt give grief when claiming credits..
all in all it took me about 4 hours to do. worth it though.
Thank you for the write up man
No problem
Iβm gonna copy it all to play with later π
Yeah Maybe I should put it on github hey
and make a youtube video
I'm glad someone else finds it useful makes me feel like I'm not nuts haha
We are all nuts dude
ha
The next thing I have to add is day rewards.. like.. Every 5 days of eating clean I earn one treat
But thanks to @inner mesa I didn't know how to code it at all I would have been stuck without his help.
I'm gonna watch some TV just for you
Just so long as you're not taking my TV Watching credits I'm allllllll good with that
I could call this thing Virtual Parent 2022
"Do your homework and you can play call of duty"
except in my case it was "Do your homework and you can play Doom 2"
i copied and pasted it all here and included each of the yaml files copied/pasted so they are there if the links go bad https://gist.github.com/bharvey88/815b9c0436fdf95e7f927a0302b4b09c
π
Oh dang cool
gotta clean it up tomorrow i guess
Very cool
well geez. thats great.
I guess it was useful enough hey. I'm flattered.
i might not even use it or use most of it.. but now i have it to share with others lol
Thats very cool
Well yeah its helpful I know I spent the time and I forsure wont be the first or last person that is trying to solve this problem
Soon elon will have all our brains connected like borg and we wont need github anymore haha
Niiiiiiiice
I dont have one. But I would like one
I wish I had something that could print money, now that I'm thinking of 3d printers.
sensor:
- name: gpdlatitude
state: >-
{% if trigger.to_state.attributes.phone == number_sprinter %}
{% set value_json = trigger.to_state.state | from_json %}
{{ value_json["latitude"] }}
{% endif %}
BTW without the{% else %} {{ this.state }} the sensor will loose it's state on any new sms received in the sms sensor
what's the cleanest way to return true if an entity is part of a group?
'light.ceiling_light')|list }}```
this returns the light if it's part of the group and an empty list if not
I could check if the list is empty I guess
but was wondering if I could pipe the command into something else to return true directly
{{ 'light.ceiling_light' in state_attr('group.bedroom_lights', 'entity_id') }}
or
{{ 'light.ceiling_light' in expand('group.bedroom_lights') | map(attribute='entity_id') | list }}
thank you, was checking if length was 1 but this is better
Good morning. How can I store data to survive reboots. I want to store things like peak solar production and I want to store when that peak was reached. Something like "6594kW at 21.06.2022 14:23" How do I create, read and write a file in HA. I think that that file could be read and the entities restored at boot time. An update of the peak value could be done, whenever a peak is updated. I that a possible approach? Or are there other possibilities to do something like that?
trigger based template sensors will restore the state after reboot, or you can use an input_number to store the value
If I understand your question correctly, I would suggest a trigger based template sensor
Thanks, then I will start experimenting with trigger based template sensors. The input_number I got working, but they create sliders or input fields. The secondary_info: last-updated shows time since last update, not an absolute time and date. I don't know how to get rid of the sliders and how to set absolute time and date there...
Maybe a new template class "entity_storage" is a new idea for the future to really store such max/min data like all time high or low values, with the time and date they occurred? Sinds such a thing is beyond my current capabilities, maybe somebody else finds that idea attractive as wall and adds it to HA???
you can always add a feature request on the forum
but this should probably work:
trigger:
- platform: state
entity_id: sensor.power_production
sensor:
- unique_id: trigger_sensor_power_production_peak
name: Power Production Peak
state: >
{% set n = trigger.to_state.state %}
{% if n | is_number and n | float > this.state | float(0) %}
{{ n }}
{% else %}
{{ this.state }}
{% endif %}
unit_of_measurement: W
attributes:
datetime: >
{% set n = trigger.to_state.state %}
{% if n | is_number and n > this.state | float(0) %}
{{ trigger.to_state.last_changed }}
{% else %}
{{ this.attributes.get('datetime') }}
{% endif %}
if your entity has the right state_class (measurement) this is already stored in the long term statistics. You could see the max in a statistics graph
Perfect! Erg bedankt!
made a correction in the attributes template
and a correction in the state template π
sadly, this doesn't seem to work. (even with the added {% else %} and {{ this.state }} . The sensor just returns nothing
@versed lava sorry, you need to use from_json, not to_json
{% set test = '{"latitude":"1.000000","longitude":"1.000000"}' %}
{{ (test | from_json).latitude }}
returns: 1
you can make one automation that does all, would you like to know how?
OMG Thank you so much, it works now!
If I create a variable with a string that begins with an asterisks * the yaml parser blows chunks. e.g.:
dkim_line: "*@{{ dkim_domain }}"
This works:
dkim_line: " *@{{ dkim_domain }} " because of the space.
I've tried to escape with with both types of quotes and a backslash but no joy. Can this be done? It's like the parser is still seeing it as an anchor reference even when it's escaped..
I now tryed it out, but as soon as I copy these lines into templates.ymal all other templates stop working. Any idea what I do wrong. π€·ββοΈ
Yes, you should indent it two spaces and add a dash (-) before trigger:
Hi guys, i want to create a temperature sensor from a climate but the configuration.yaml reports an error.
https://hastebin.com/rutuhazeba.less
but its the correct climate ID
indentation is a bit too deep on that config
How to get it more shallow?
the other sensors working fine but they do not start with an integer
tempkiz1:
friendly_name: "Temperatur Kiz1"
unit_of_measurement: "Β°C"
value_template: '{{ states.climate.00201d89bc94c7.attributes.current_temperature }}'
what does that value_template show in developer tab?
the sensors.yaml is not valid like this
invalid template (TemplateSyntaxError: expected token 'end of print statement', got 'integer') for dictionary value @ data['sensors']['tempkiz1']['value_template']. Got '{{ states.climate.00201d89bc94c7.attributes.current_temperature }}'. (See ?, line ?).
because indents should be like documented https://www.home-assistant.io/integrations/template/#state-based-sensor-exposing-sun-angle
ok... But with this climate it is working https://hastebin.com/umujasodik.less
I think the code does not like the integer behind the climate "."
numbers in entities should be enclosed in []
and while your configuration works it has been not recommended for a while now https://www.home-assistant.io/integrations/template/#legacy-binary-sensor-configuration-format
same as the state template you're using https://www.home-assistant.io/docs/configuration/templating/#states
Hello respected members. I have created an automation with to get an alert through telegram bot whenever my camera stream is down. The issue is I have six cameras and I also want to get which camera is down. Is it possible? Plus I want the automation to stop once I have recieved an alert and again alert me when the stream is back online. Please help.
that doesn't matter as long as the indentation is constant. I.e. This is valid yaml:
this:
is:
valid: a
yaml: b
to fix, switch to the state_attr method
tempkiz1:
friendly_name: "Temperatur Kiz1"
unit_of_measurement: "Β°C"
value_template: "{{ state_attr('climate.00201d89bc94c7', 'current_temperature') }}"
got it
value_template: {{ state_attr('climate.00201d89bc94c7', 'current_temperature')}}
whenever you have numbers as the object_id starting character, it's suggested that you change the entity_id if you plan on using states.xxx.yyy.attributes.zzz
(and remove the numbers)
The entity_id comes from a integration
in the developer tools state?
π I can't find my fault... https://hastebin.com/ucaqulerug.yaml
Thanks Petro and blackadder
it doesn't go in the sensor section of your template
you have
template:
sensor:
... your other items ...
- trigger:
...
sensor:
...
it needs to be
template:
- sensor:
.... your other items ...
- trigger:
....
sensor:
....
you have to add a dash in front of your first sensor:, then indent all sensors under that (by 2). Then your second - will be the trigger.
Thanks, then I will clean that up... π
Please help
be prepared to share your current automation as well. People won't write these things from scratch for you.
Lol. Channel ping-pong Petro <#automations-archived message>
I'm sorry. I'm new to programming.
Please atleast give me a direction so that I can figure it out
This is what I have, but no joy. "PV max Tagesertrag" remains undefined. sensor.pv_ertrag_heute is increasing. To me all looks good. But maybe I messed it up somehow? .https://hastebin.com/yabifebowa.kotlin
entity_id:
- camera.192_168_29_100
- camera.192_168_29_101
- camera.192_168_29_102
- camera.192_168_29_103
- camera.192_168_29_104
- camera.192_168_29_105
- camera.192_168_29_106
from: idle
to: unavailable
for:
hours: 0
minutes: 0
seconds: 10```
Working now, thanks! Sometimes you simply don't see it yourself... (the templates.yaml, not the trigger by TheFes, yet to come...;-))
This is my trigger code
message: "{{ trigger.to_state.name }} is unavailable"
oops
This is my action code to send telegram message
data:
message: Camera stream is down
title: Alert```
replace your message with what tom posted
my bad, needs an float filter in the attribute template
attributes:
datetime: >
{% set n = trigger.to_state.state %}
{% if n | is_number and n | float > this.state | float(0) %}
{{ trigger.to_state.last_changed }}
{% else %}
{{ this.attributes.get('datetime') }}
{% endif %}
btw, if it's kWh you are interested in, the peak will always be at the end of the day, so it makes no sense to save the entire datetime
attributes:
date: >
{% set n = trigger.to_state.state %}
{% if n | is_number and n | float > this.state | float(0) %}
{{ now().date() }}
{% else %}
{{ this.attributes.get('date') }}
{% endif %}
So this will do fine as well
Oh, haven't thought about that, but you are right!
When is used message: "{{ trigger.to_state.name }} is unavailable" I got error saying "Error rendering data template: UndefinedError: 'trigger' is undefined"
You can not use the RUN ACTIONS button to test it, it relies on a trigger, so it needs a trigger
I then changed trigger to state and recieved the telegram message which says "none is unavailable" but the stream is down
The template is correct, but you can't test this using the RUN ACTIONS button
you can try to set the state in
>States for one of the cameras
The state is set as unavailable is the states tab under developer tools
was the state already unavailable? It needs to change from idle to unavailable as per the settings in your trigger
No it was first idle and then changes to unavailable
- remove the from, it's not needed. 2. If you reload the automation, it needs to change state for it to fire. It will not fire on it's own if it's already been unavailable after a reload.
Ran this command abut getting no alert
So changes trigger with state but then getting the same message none is unavailable
how are you running it? It's been stated many times that this can only be executed a specific way.
I saved the code
you can't use 'test actions'
you actually have to have a camera go from a different state to unavailable
I unplugged the cat 6 cable of one of the camera
Yes did that
how did you do that exactly?
I unplugged the cat 6 cable of the camera
and then you waited 10 seconds?
Yes
Shall I keep states instead of trigger in command?
no, you keep exactly what tom wrote
that's not what tom wrote
{{ trigger.to_state.name }}
he also has his whole message in quotes
which you have to do as well.
I'm sorry I wrote exactly this
I said in short to highlight the trigger or state before to_state
so back to my other questions...
and what does the automation trace say?
and what's the state of the camera?
Result:
params:
domain: telegram_bot
service: send_message
service_data:
message: 192_168_29_104 is unavailable
title: Alert
target: {}
running_script: false
limit: 10```
This is automation trace
I didn't recieve any alert this time
In trace it is showing the camera entity id but I didn't get alert on telegram
Feels weird
nothing wierd about it. It fired the message, however telegram didn't do what it should have. Look into why telegram failed.
I don't know what's happening
I restarted my system
But I'm not getting the telegram alert
From services under developer tools I'm able send a message service to send 'hii' message
post the yaml that you're using in the developer tools, there's a button to switch to yaml mode
I'm getting the following error "Error: Error rendering data template: UndefinedError: 'dict object' has no attribute 'to_state'" When click run actions for my automation under automation tab
Yaml for what @mighty ledge ?
configuration.yaml of home-assistant?
That will not work, there is no trigger then
the yaml of your automation
Just a minute
Please use a code share site to share code or logs, for example:
- http://pastie.org/ (select YAML for the language)
- https://dpaste.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.
the yaml for the service call you're using in the developer tools -> services page
data:
message: Hi ```
I'm using this to check whether the telegram service is fine
can you share the code of this specific automation? you can switch to yaml in the 3dot menu at the top
@silent cedar posted a code wall, it is moved here --> https://hastebin.com/ogasajegiv
that looks fine. Are your cameras plugged in again?
Yes
Gone through all that, the problem is with telegram at this point
I'm my configuration of telegram bot or it is something to do with telegram server
Because I can call basic send message service from services
And when hi I get the message I send using the service
Oh my god
Got it
I think the telegram is blocking ip address in messages
Shit
Which are in this format 192_168_29_104
But when I send a meesage 192.168.29.104 I'm able to receive it
Why don't you just name your cameras something other than the IP address
I don't have telegram
I use the mobile app to send myself notifications
I'm using this code to send message
data:
message: 192_168_29_104 is unavailable"
title: Alert```
Give me some time I will use code now
Where to do that my friend?
Works fine here.
Shall I replace name here with friendly_name?
No
no, that won't work
Can to change friendly_name to something to understand instead of xx_xx_xx_xx format?
Done! π Perfect. It now peak storage works. Actually I will use both power and energy. Thanks for your support!
@candid nacelle I kinda hoped I mentioned #templates-archived enough
service: select.select_option
data:
entity_id: select.thing
option: >
{% set options = state_attr('select.thing','options') %}
{% set current = states('select.thing') %}
{% set i = options.index(current) + 1 %}
{{ options[i % options | count] }}
You can rename the entity. Find the entity, click the settings tab.
see this post
This worked like butter. Thanks alot friend. ππ
Yes I would!
Thanks alot. This worked.
I changed the friendly_name from states under developer tab but after few seconds the name was back to ip address on overview screen. Your tip worked my friend. Thanks aton
One query
I want to implement scripts to make the automation smarter
The code you guys helped me with keeps sending the unavailable message
I want it to send me the message once it's down and once it's restored
What condition shall I use
Point me in the correct direction
copy the automation, change to: unavailable to from: unavailable
post a few example automations
@sage stirrup Please use a code share site to share code or logs, for example:
- http://pastie.org/ (select YAML for the language)
- https://dpaste.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.
@mighty ledge http://pastie.org/p/76VDtJBCXcAYb7VsA8T5TN
Here are four automations, two of each type.
1 automation to rule them all -> http://pastie.org/p/71EtqowcYIkoiEwfqyvZXi
Shall I paste the change automation just below the current one?
Hey guys in a script ive defined a variable UUID is it possible to change it from a template in sequence? I tried using set uuid = <value> but doesnt seem to work
or this, more templating, less services -> http://pastie.org/p/4pIymZk29x3NNtarctNfKS
wherever you want, if you use the UI, you can just duplicate it.
Is there a order in which these automation execute?
are you using the UI?
they run from top to bottom
Yes I used ui and copied the yaml code
no order, they execute when they trigger
if you use yaml, there's no order, they execute when they trigger, however when they are loaded into the system, they are loaded top of the file down.
Follow up on my lost message. Is this possible?
You can't overwrite variables
is there anyway i can define script variables from inside a wait template?
you can overwrite things you set, i.e. {% set xyz = 1 %} followed by a {% set xyz = 2 %}. However, if the variable already exists in your namespace, you cannot overwrite it. I.e. if it comes from another variable in the sequence
hmmm ok
My logic is I have a template to run some complex python code and then output somthing that a following if statement in the sequence will check if exists
{% set uuid = d_beacons.detected[d_beacons.distance.index(min(d_beacons.distance))] %} so this is the line that sets the variable uuid to something and then i have an if condition next is sequence checking if it was defined
- if: - condition: template value_template: "{{ uuid is defined }}" alias: Check if UUID was set
hope this makes sense
I'm not sure how you can run python code from a template
yeah, that's not correct
it's jinja, that's it
it has python objects
but the code is 100% jinja
anyways, make a variable and just call the uuid
- variables:
uuid: .... your complex code ...
... later on ...
- if:
- condition: template
value_template: "{{ uuid is defined }}"
alias: Check if UUID was set
and I quote "is a Python template engine" from https://www.fullstackpython.com/jinja2.html
and the syntax is python. Or inspired in python anyway thats besides the point
you're using jinja syntax
no
jinja syntax
it's similar to python, but it's not python
if you try pythonic expresssions, many of them do not work.
Thats true
Like many languages are similar to other languages
Ok ill call it by its name then jinja2
sure whatever
I'm reciveing camera restored alert even I haven't restored the camera.
just don't call it python because that confuses the experts π
dude what. Are we really getting mad cuz of this?
I'm getting unavailable and restored message alternatively
I'm not mad at all
Well im a python developer. 5 years and counting π
And each message I receive is after 10 sec not stopping
i'm saying 'sure whatever' as in call it whatever you want
just don't call it python, cause it's not python
ok
jinja, jinja2, templates, etc
but anyways, jinja is limited to scope, and to top it off, there's a restriction set in place on automations and scripts
anything output to a variable... i.e...
variables:
xyz: "{{ ... }}"
will be static from that point forward. You won't be able to call another...
variables:
xyz: "{{ ... }}"
to overwrite it
that worked @mighty ledge thanks for the help
np
And I wont call it python anymore π
lol, it was just confusing because we haven't added any way to execute python in jinja
so I was curious what you were doing to get that to happen
I know I recognize my mistake just messing with ya
I want to add a method to do that, but it's alot of work and we'd want to add macro support too
yeah, I'm sure there is, but we have to add it in a way that works with HA, so it's a whole 'situation'
well yeah, there's pyscript, but I'm specifically refering to adding a function into templates that are usable in all templates
are you a developer for HA?
I add stuff here and there, but not on the dev team
the way i see it rn would be to make the code ran in the server in some sort of container and return to the runner
something like that
I wanted to get more envolved cuz i use HA a lot but im really busy with work, and my projects
yeah then just volunteer once and a while
that's all I do
I'm in the same boat as you
I dev fulltime and when I get home, I usually don't want to dev
unless I really want a feature
then I add it
the open source project i currently support is alexa-actions
which allows for actinable notifications with alex
if you know python, adding or updating integrations is super easy
how do you test stuff?
there's a developers document section, it shows you how to create a dev environment
using vscode
makes sense
it's easy, although some people screw it up. If you've used vscode, you'll have no troubles. Also, if you understand the python build process, you'll have no troubles.
not a fan of vs but ill give it a try one day
im a jetbrains kinda guy
@mighty ledge mind sharing you github?
I have tried playing with to and from but still getting unavailable and restored alerts alternatively
Please help
what are you trying to do @silent cedar ?
With the help og members I created an automation to recieve an telegram alert when my camera is down
And to receive an alert when camera is restored
But when I remove the cat 6 cable of my camera I also recive the alert that camera is restored even if it is unavailable
youre using home assistant i suppose? Why not use phone notifications?
I only want to receive msg once
But im getting msg continously until the camera is restored
Will search for it
How does it work?
you have the companion app for home assistant
and you can use the notify service to send push notifications to phones
I'm using telegram because it's linked to a tool Im currently using
But it will also need automation configuration
Yes
@silent cedar posted a code wall, it is moved here --> https://hastebin.com/atejaqadur
This is yaml for alert when camera is restored
Yes
@silent cedar posted a code wall, it is moved here --> https://hastebin.com/edesawajiz
can you check device change log or history and send a print?
I want to check if any of the devices are jumping from states
which could be the cause of the issue
which to fix this would be to increate the for time
Yes I checked in nvr and overview tab of home-assistant
Device is indeed changing states
do the devices like power down to save energy?
No
or disable wifi when there is no movement?
No
does the state jumping only occur during the beggining of removing the cat6 cable
or is it something that happens on a regular basis?
As of now on removing of cable
then the thing i can recomend is increasing the time to like 30 seconds see if its enough
But why even the camera is not restored I'm getting restored alert
Plus I want to fix a bigger issue first
How to avoid the automation to stop after sending one message
I want only one message you once the camera is unavailable
you can create an auxiliar entity an then in the conditions say only if 5 minutes passed since the last trigger
Thank you!!!!!!!
ooh you guys improved it
@dull burrow much improved yea!
I can't wait to get this all into a single automation. that'll be nice!
It was @mighty ledge that helped make it one automation
I clearly do not know what I am doing, but I do know what I'm trying to do.
I'm trying to create a simple graph that will show when my HVAC system is either, heating, cooling, or idle. I was able to locate the proper values but I don't know how to make it an actual sensor.
Invalid config for [sensor.template]: expected dictionary for dictionary value @ data['sensors']['friendly_name']. Got 'HVAC Status'
expected dictionary for dictionary value @ data['sensors']['value_template']. Got '{% if is_state_attr (\'climate.hallway\', \'hvac_action\', \'cooling\') %}\n "Cooling"\n{% elif is_state_attr (\'climate.hallway\', \'hvac_action\', \'heating\') %}\n "Heating"\n{% else %}\n "Idle"\n{% endif %}'. (See ?, line ?).
- platform: template
sensors:
friendly_name: "HVAC Status"
value_template: >-
{% if is_state_attr ('climate.hallway', 'hvac_action', 'cooling') %}
"Cooling"
{% elif is_state_attr ('climate.hallway', 'hvac_action', 'heating') %}
"Heating"
{% else %}
"Idle"
{% endif %}
Can I name it w/e I want?
For example
- platform: template
sensors:
hvac_status:
friendly_name: HVAC Status
value_template: >-
Ah I see now, god yaml is so bad.
Thank you for your help!
hi @mighty ledge not sure if you're there, but I tried to save the one script to rule them all and got this message
Message malformed: required key not provided @ data['trigger'][0]['platform']
I tried saving the code but it didn't work. I can't stay online much longer tonight I have a bad injury and it's acting up. Hopefully Petro will be around to lend a hand sometime. Looks much simpler than what I was doing I spent a lot of time duplicating and copying automations.
line 5 (typo in platform - platfrom)
np
Hey guys im looking for some help and I think you guys might know a little more about it
I have MQTT setup to where it can push a message to each of my devices and open apps / run programs / etc. But I can't figure out how to configure a front end card to where I can make the payload variable.
Like a textbox for payload "Text Goes Here" that uses a template to send the string to my service
Anyone know what I'm missing?
@cerulean blaze https://www.home-assistant.io/integrations/input_text/
Im using that im just having an issue sending that to a script and to mqtt
share what you have so far?
Ok I got it partially working in parts lol
So here is what is working and will open discord on the desired pc:
type: button tap_action: action: call-service service: script.mqttalexis service_data: whatever: open discord
This has a text box that I can use AND DOES SET THE INPUT_TEXT CORRECTLY but it still will send "input_text.mqttpayload" as the payload...
- type: entities entities: - entity: input_text.mqtt_payload type: custom:text-input-row - type: call-service name: ' ' icon: mdi:voice action_name: Send service: script.mqttalexis service_data: whatever: input_text.mqtt_payload
Thanks @slim elk
whatever: "{{ states('input_text.mqtt_payload') }}"
Executed: September 23, 2022 at 8:54:07 PM Result: params: domain: mqtt service: publish service_data: topic: alexispc payload: '{{ states(''input_text.mqtt_payload'') }}' target: {} running_script: false limit: 10
@slim elk did I do something wrong?
should I just do "{ {{ states('input_text.mqtt_payload') }} }" instead of whatever ion the script and not even pass the data directly?
payload: '{{ states("input_text.mqtt_payload") }}' or payload: "{{ states('input_text.mqtt_payload') }}"
@slim elk I just changed the script to payload: '{ {{ states(''input_text.mqtt_payload'') }} }' and that worked
thank you so much!
np glad I could help
@slim elk I sent a pm of nitro gift lol I really do appreciate the help
wow, thank you. Much appreciated π
What am I missing here? color_temp is an attribute of the light.workshop entity.
{% if state_attr('light.workshop', 'color_temp') = 365 %}
scene.scene_workshop_white
{% elif state_attr('light.workshop', 'color_temp') = 153 %}
scene.scene_workshop_yellow
{% endif %}
Or because it's a numeric value do I need to use this instead?
{% if numeric_state('light.workshop', 'color_temp') = 365 %}
scene.scene_workshop_white
{% elif numeric_state('light.workshop', 'color_temp') = 153 %}
scene.scene_workshop_yellow
{% endif %}
No, that last one is not correct
That first one could work, but you only take into account 2 of many possible color temperatures
@abstract sapphire How are you using this template?
Also take into account that that current color_temp is not known if the light is turned off
Yeah it's only for light when on
Using it in an automation, when a zha_event is triggered
service: scene.turn_on
target:
entity_id: >-
{% if state_attr('light.workshop', 'color_temp') = 365 %}
scene.scene_workshop_white
{% elif state_attr('light.workshop', 'color_temp') = 153 %}
scene.scene_workshop_yellow
{% endif %}
metadata: {}
Well, like I said, there are many color temperatures possible, and you only take two into account
So this will fail when it's any of the other possibilities
Oh, and you need to use == instead of =
This will work for all temperatures
service: scene.turn_on
target:
entity_id: >-
{% if state_attr('light.workshop', 'color_temp') >= 200 %}
scene.scene_workshop_white
{% elif state_attr('light.workshop', 'color_temp') < 200 %}
scene.scene_workshop_yellow
{% endif %}
metadata: {}
I'm having it activate one scene of temp 365 and another of 153 so that's all it'll ever be.
Ahh bugger I did try == as well but must've had something else buggered. Thanks.
Hi all. I've been searching this for a week or so and I just can't come up with a solution. I have an apex chart that shows my daily energy usage for the last 7 days. I would like to overlay this with a running average of the max consumption for the time period. (TotalDay1+TotalDay2+TotalDay3)/3 (for three days). I know there is a weekly power meter but that always restarts on Monday not constantly rotating for the previous 7 days. Can anyone point me to and example template of summing the last x days total consumption? I feel I just need to rotate through the max of daily bins but for the life of me I can't wrap my head around how to do it.
you can't do that in a template.
Maybe with a trigger based template sensor, which stores the pevious_period attribute of a daily utility meter sensor in the attributes, and had the average of the last 3 values in the state
@mighty ledge is there any advantage of using is sameas instead of == besides maybe this particular case
{{ 1 == true }} # True
{{ 1 is sameas true }} # False
never seen sameas
odd, i would assume it would be the same as {{ 1 is True }}
it's about the memory address, so it's like is. I don't see a reason to use it
You'll rarely want the same memory address
It could be useful for checking state objects only
like, the entire object
other than that, there's better checks for simple objects
if I wanted to have this: https://pastebin.com/CpywY45N result in a No items being delivered, if all sensors answer No... is that possible? Currently that looks like No pieces of mail will be delivered. No USPS packages are in transit. No Fedex packages are in transit. No UPS packages are in transit. No Amazon packages are in transit.
and I was hoping to get 'No mail, and No Packages will be delivered'...
Thanks. Any thoughts on how I could go about this outside of templates? I thought about getting "yesterdays value", which is an attribute of the utility meter, just after midnight and storing it each day but even then I don't know how to sum up the last 7 values that I stored. How are all the chart packages doing the binning? Is it all javascript in the background?
whatever you can dream up using the statistics sensor in combinations with other sensors
templates don't look at history so templates aren't an option
Thank you
I have created an automation where I get an alert when the camera is down and an alert once again once the stream is restored but my automation keeps continuously sending me alert "Alert
The camera stream for camera Shed2MainGate is None." once the camera is down. The camera name received in the alert is correct. Why is it sending me none instead on "unavailable" (state)? Plus why not it is sending me "idle" (state) once the camera is restored.
My yaml
@silent cedar posted a code wall, it is moved here --> https://hastebin.com/atiruqipil
I made a change in the yaml file. Now i'm the getting state names (resolved the issue where I recieved "none" instead of current state). The only issue now is that still the camera is down but I'm getting "idle" Alert.
Alternate idle and unavailable alerts
Updated yaml code
@silent cedar posted a code wall, it is moved here --> https://hastebin.com/geqedixono
When the second iteration of automation starts will the to_state become from_state?
There is no attribute state
So state_attr(entity_id, 'state') isn't going to work
Use states(entity_id) or trigger.to_state.state like you do in the condition
Btw, the condition is not needed when you add to: ~ to your trigger
I had changed the and also posted the new yaml please check
This is the updates file
It will now trigger on any state change, so also when it changes to idle
hi guys. i'm trying to do something i didn't know if it's possible. I want to have a boolean switch in my sister's dashboard that enables or disables a "Maintenance" user. I already have a dashboard button that navigates to /config/users but she will have to click the "Maintenance" user, enable it and update, with a few more clicks... i was trying to automate that process so she could easily enable or disable that specific user with a single click at the boolean switch. Can that be done?
Yes I will also play with this
What do you mean with the 2nd iteration
By that I mean the second time the automation executes
And could you stop posting text-walls and use a code website yourself instead of letting the bot do it for you
[Rule #6](#rules message): Spam will not be tolerated, including but not limited to: self-promotion, flooding, text walls (longer than 15 lines) and unapproved bots.
Please take the time now to review all of the rules and references in #rules.
For sharing code or logs use a code share site such as https://dpaste.org/ (pick YAML for the language) or http://pastie.org/ (pick YAML for the language).
I'm sorry. Will do from now onwards.
The trigger object is created at the moment of the trigger, it will not change while the automation runs. If the automation is triggered again, there will be a new trigger object
Thats what I'm asking my friend. This new trigger object will assume "unavailable" as its from_state. Correct?
If it changes from unavailable to something else it will have unavailable as trigger.from_state.state
What change shall I make in my yaml?
For this to happen
I'm unable to think of any possible solution
Ohh. I got it. The from_state is alternating in each iteration
First idle then unavailable then again idle and so on
Thats why I'm getting alternating state alerts
What condition, script or any other property can I use to stop this alternating of states
?
Your cameras shouldn't alternate between idle and unavailable that much
I would start there
Why is that happening?
No they are not alternating
I have removed the cat 6 cable of one of my camera to test automation.
Okay, then I don't understand what the issue is now
You made an automation to inform you on every state change
It is doing that
This
This
Thats the issue
The camera is still down but I'm getting idle alert
I will share the screenshot of the alert
Just a minute
Well, apparently it became idle, otherwise the trigger object will not have that to_state
Are you from programming background my friend?
No
This is what I get
Yes, which shows that Home Assistant received an event that the camera changed state to idle
If it did not do that, because it has unplugged, and had not been plugged in, the problem is in the integration, and not in the automation
You mean the generic camera integration?
I don't know what you are using
This is 5th day of me playing with home-assitant. I'm new to programming and automation stuff.
I don't know what I'm that failing to explain
Can you be please more specific?
I feel the issue is with my yaml
Because when I plug the cat 6 cable I stop getting the alerts
If I understand correctly, you constantly receive alerts while the cable is unplugged
Yes
Alternating between unavailable and idle
Correct
This means the integration is reporting the camera as such
You will also see that if to look at the history of the camera
This is for example the history of the motion sensor in my toilet
How does that look for your camera?
Okay, so that confirms what I was saying, the camera is reported as idle and unavailable by the integration
How can I solve this Integration issue?
Not in the automation, that would be something for #integrations-archived
As a work around you could use a ping sensor
I want to control a dimmer via a motion sensor. Move hand close for bright, away to dim. I'm no programmer, but this sounds cool...in theory. Any thoughts on how to do this in Home Assistant?
Is this the right syntax?
{% set heat1 = states('binary_sensor.call_heat_woonkamer_0_3') %} {% set heat2 = states('binary_sensor.call_heat_keuken_0_3') %} {{ heat1 or heat2 }}
Right now it seems to respond to the first sensor, but not to the second one.
no, because states are strings
{% set heat1 = is_state('binary_sensor.call_heat_woonkamer_0_3', 'on') %}
{% set heat2 = is_state('binary_sensor.call_heat_keuken_0_3', 'on') %}
{{ heat1 or heat2 }}
That makes no sense to me whatsoever, which is presumably why google didn't tell me about it. But okay, it's a design choice I can handle. Thank you!
Yup, that indeed does what I was expecting, not that I had any doubts it would.
Any reason why this template is working:
- service: notify.mobile_app_{{'galaxy_a32' if trigger.event.data.device_id == markus_nfc_reader else 'pixel_3a'}}
But this one is not? - service: input_boolean.turn_on
entity_id: input_boolean.{{'markus' if trigger.event.data.device_id == markus_nfc_reader else 'jessica'}}_asleep
hard to say without knowing what "markus_nfc_reader" is
it looks like an undefined variable
you haven't said how it isn't working, either
Sorry, the markus_nfc reader is defined as a variable.
If I have the lower part in the automation I get the following log:
Invalid config for [automation]: not a valid value for dictionary value @ data['action'][1]['entity_id']. Got None. (See /config/configuration.yaml, line 165).
You could have used the bool filter on your version
{% set heat1 = states('binary_sensor.call_heat_woonkamer_0_3') | bool(false) %}
{% set heat2 = states('binary_sensor.call_heat_keuken_0_3') | bool(false) %}
{{ heat1 or heat2 }}
but a very similar template is working i.e. the one in the first line
I think I see what youβre saying, but if binary_sensor states are strings (of all different kinds depending on the type of binary sensor it happens to be) that seems like youβd be relying on the bool filter to know which of those strings corresponds to true for all of those pairs of values. I donβt think Iβm ready to trust to that in the general case, and I think Iβd be flummoxed if I ever accidentally ran into a counterexample, so Iβm going to stick RobCβs version into my mental toolkit.
It's all documented here: https://www.home-assistant.io/docs/configuration/templating/#numeric-functions-and-filters
The version Rob suggested is fine as well, just wanted to offer aan alternative
I learn with every message! Itβs justβ¦ wow, the learning curve is steep for this stuff. I feel like Iβm getting there, but I donβt yet fully grok the system.
BTW, it's not that all binary sensor states are strings. The states of ALL entities are strings. So also numeric states are strings, so you need the float or int filter there to convert them to a number
I have some plugs that only have current/power/voltage. I've started to look into getting consumption from that but would appreciate any pointers
Right. I now remember youβve said that before and clearly I hadnβt retained it as a generalized thing. Thank you.
Energy is power times time, and I believe the magic search word was Riemann integration.
Thanks, Riemann was something I had come across. I'll keep on that path.
On ^ that url turning power into energy is a literal example, btw.
Using a template to set the for: seconds amount, but it's erroring out and thinking I'm not setting the seconds amount. I tested the template and it works fine. How do I apply the template to the blueprint seconds attribute correctly? (seconds_delay is a valid variable)
for:
hours: 0
minutes: 0
seconds: >
{% if is_state('binary_sensor.night_mode', 'on') %}
180
{% else %}
{{ seconds_delay }}
{% endif %}```
What is the error you get?
expected float for dictionary value @ data['for']['seconds']. Got None
assuming that means the template isn't evaluating to anything consumable by the seconds field
Please use a code share site to share code or logs, for example:
- http://pastie.org/ (select YAML for the language)
- https://dpaste.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.
sure. http://pastie.org/p/0fqCPy2qGdbLUj0AF5Wcb6 note the variables: and trigger: section
And the automation created using this blueprint?
automation and the full error it gives: http://pastie.org/p/3h6LE0gOWUWVkp5v1zSa2b thanks for takin a look
I don't know what's wrong, maybe something specific to #blueprints-archived ?
Anyone have any thoughts why something as simple as {{ state_attr('weather.vancouver', 'forecast')[0] }} will sometimes return None? Is there a way to work around this other than adding default()? I have a bunch of automations that rely on weather attributes and at least a couple times a month this call returns None. I don't know if it's transient or how long it lasts.
(Although I question if this is a #templates-archived question or an #integrations-archived question)
state_attr() will return none when the attribute doesn't exist (or when it is none of course)
yes for sure
Adding [0] to it will result in an error then
so I guess the question I'm really asking is: How do people deal with the Weather integration not returning data reliably?
I combined 8 different weather integrations into one using a template weather
lol. the belt and suspenders and an extra 6 sets approach? π
Maybe, but I always have a forecast available
wanna share your template? π
It uses a template sensor to determine which integrations to use
You might want to change the units
What happens when one says rain and the other says sun? That's more of a philosophical question than a practical I suppose since I can read the source.
It takes the one which is the most frequent option in the list
And mentions the others (in the forecast)
Example:
- datetime: '2022-09-28T00:00:00+02:00'
condition: rainy
condition_all:
- partlycloudy
- pouring
- rainy
precipitation_probability: 89
wind_bearing: 252.1
temperature: 14.2
templow: 6.3
wind_speed: 12.4
precipitation: 6.4
entities:
- list of entities used for this forecast```
- {{trigger.to_state.state.attributes.rgb_color[0]}}
is this the correct way to extract the value for red on the trigger light?
Looks fine
getting an error
'str object' has no attribute 'attributes'
got it
no need for '.state'
Hello, how to create an template for the download speed, upload speed en ping for speedtest integration please. Want to add it in the mushroom template card. Thx
This template is giving me the time in HH:mm:ss: {{ timedelta(hours=(states('sensor.dishwasher_runtime_today')|float)) }}. Is it possible to convert it to HH:mm?
Is there a "best" way to get multiple values from an entity's attributes, or do I just have to template up a bunch of new sensors?
Depends on what you want to do with them. You can often use attributes directly in cards
Ooh, any suggestions on how to do so?
Do what exactly?
Test out cards that fetch attributes as opposed to main data
Review the docs for the card you want to use
The entities card supports attributes
Lots of custom cards do. The markdown card does
Ah, you're right! I'll take a look at that for sure! ππΏ
Also, is it suggested to edit cards the Studio Code server if possible?
Only if you're using YAML mode for your dashboard
Is the dashboard yaml outside of config?
The directory? No
Try {{ (timedelta(...) | string)[:5] }}
I am trying to figure out the "best" way to create a history stats sensor for "Last week". (As in Mon -> Sun). But, i just end up with ridiculously complex expressions. So, what shortcut am I missing here?
Quick one, i am trying to send an MQTT template topic {"warning": {"duration": 2, "mode": "emergency", "strobe": false}} this is fully copied from the zigbee2mqtt example. When it try to run this in Home Assistant call service MQTT i get the following error. failed to call service mqtt.publish value should be a string for dictionary value @daring linden[payload_template]. Got none.. any pointers?
EXACTLY how are you calling it?
Not loading, and looks like a video site? Why not just post the code?
not sure why it is not loading, should be a picture, since i am using the gui for this call service i can not show the code. once sec ill find a way to share the picture.
Goedemorgen. All worked fine, but when I reloaded the templates, all values were lost. So the function works fine, but does not survive reload templates in "YAML configuration reloading" π’
Any idea?
Is the source sensor a template sensor as well?
@slender whale Your message has been deleted as it contains a link or a domain name 'pasteboard_dot_co' that is on the blocked list because of: 'Virus detected!'.
Please re-post by removing/changing the domain name/link. Your original message has been DM'ed to you.
yes it is.
It looks like the sensor is triggered by the new state of the source template sensor when it didn't recover it's state yet. That trigger writes unknown or unavailable to the state, and then won't recovery the old state anymore
The above is just my assumption by the way
Sound reasonable, so a racing condition kills the value. Can you think of another approach to that? I have no idea how that could be handled.
how can I make this work```
if:
- condition: numeric_state
entity_id: media_player.nest_mini
attribute: volume_level
above: "{{ input_number.nest_default_volume_level - 0.01 }}"
below: "{{ input_number.nest_default_volume_level + 0.01 }}"
then: - service: media_player.volume_set
target:
entity_id: media_player.nest_mini
data:
volume_level: "{{ input_number.nest_default_volume_level }}"
You can not use templates voor above and below in a numeric state condition
Use a template condition instead
Not in a template sensor, maybe using an input number to write the value to, and then use that
I tried it with input number, but it generates e.g. a input/slider field...
Use the input_number as value for a template sensor
And put the template sensor on your dashboard
There is a feature request for conditions in the trigger based template sensor which would help in this case
Okay, that is worth a try. But maybe I need some links to examples to handle it in a python script. I have no idea yet how to interface with ha's entities. So I am open to learn that as well. Maybe a little piece of demo code that you could send me a link of?
OR, maybe others are interested in an feature addition to HA, to keep max/min values on a permanent basis. I don't think that I am the only one with that need. The usage of input_number for that, seems to be a currently widely just tweak to do exactly that. I think that should be added to ha. My knowledge is not yet enough to generate a feature request that really to the point of it. How can we generate attention to such an addition?
These min/max templates could have an attribute min/max that makes them "immune" of becoming overwritten with a lower or higher value, depending on min or max...
In addition to that we would need a function to reset these specificaly..
Can I change the sequence in the recovery, by changing the sequence in the recovery file?
If not, what is the key the recovery file is sorted by. Entity-ID or any other data that I could influence to reorder the recovery file?
That I don't know
how come I can get this to work in an automation service: media_player.volume_set target: entity_id: media_player.nest_mini data: volume_level: "{{ states('input_number.nest_default_volume_level')|float / 100 - 0.01 }}"
but it works in the Template editor
@sacred sparrow what is the error you see in the logs?
Hi all - looking for some assistance in creating an automation that triggers based on values being equal to or between 2 numbers. I am using OpenWeatherForecast to pull the precipitation probability (sensor returns % - sensor.openweathermap_forecast_precipitation_probability). I would like to create an automation with a trigger that is:
"If sensor.openweathermap_forecast_precipitation_probability is between 10-50% (or equal to 10 or 50%) then...." - any help with this would be greatly appreciated!
and what tinkerer wrote didn't work?
it's pretty much a copy/paste into a template trigger.
Meh, why try when you can just repeat the question
I did try, Rob. It is failing for some reason so I figured I would ask here if anyone had input.
Then I would start with what didn't work
Probably because it is currently alreadye between 10 and 50, triggers have to become true to trigger, they won't trigger if they are already true
Ah that makes sense, so I then tried pasting the template as a condition (just for testing) and it did return that it is valid and true - so I assume that if the value were to drop to 9% and then come back between 10-50, it would trigger?
yep, that's how template triggers work
basically it needs to resolve false at one moment
then resolve true the next
Sweet, thanks guys! I've never used a template trigger before so this is all new to me! lol
it'll only fire when the resolution changes from false to true, not true to true, etc
if you want it to resolve true -> true, you have to get inventive
the same principle applies to all triggers types, they have to become true
service: notify.mobile_app_phone_2
data:
title: >-
{% set lock_status = trigger.to_state.attributes.lock_status %}
{% set lock_status = lock_status|replace(" by RF", "by Home Assistant") %}
{% set lock_status = lock_status|replace(" by Key Cylinder or Inside thumb turn","") %}
{% set lock_status = lock_status|replace(" by user 0", "") %}
{% set lock_status = lock_status|replace("user 1", "Joe") %}
{% set lock_status = lock_status|replace("user 2", "Chance") %}
{{ trigger.to_state.attributes.friendly_name }}
{{ lock_status }}
message: TTS
data:
channel: alarm_stream
priority: high
ttl: 0
Hi All.... this stopped working recently, and I don't know why.
I am on 2021.5.4 Docker/supervisor
I didn't update, and nothing seems to have changed. I get an error saying "PLEASE SET A TITLE FOR TEXT TO SPEECH TO PROCESS"
When I look in the variables section of the trace, the variables are all there (to_state.attributes etc)
You probably updated to iOS 16
Thatβs an old version
And yeah, that
Bad boy
You really went for the S in IoT security lol
But youβre expecting help from a version with a shitload of known bugs
Is one of the known bugs that templates that worked for a year suddenly stop working?
With you being that far behind you canβt make any assumptions about what should be working correctly
The presumption is that if nothing changed, it should still work the same.
That is a valid presumption, but unfortunately that is often NOT true in the case of technology.
Ok, I feel sufficiently chastised. Any help with the template?
the TTS bit has changed in the app
you can try updating it based on https://companion.home-assistant.io/docs/notifications/notifications-basic#text-to-speech-notifications
That's got me in the right direction. Thank you!
might work might not due to the older HA, but give it a shot
Yeah.. I may have to give up on these notifications or update my ZWave finally :/
are you on the old zwave?

Yes... the reason I am still on 2021.5.4
the old zwave sucks π
ouchies
I am sure. Updating it all sucks more right now.
it's not tooooooooo bad
but it's completely different for the most part
as for your template, no clue why it stopped. can you post the real error?
and possibly a line or 2 before it
not the abbreviated Stolid error
LOL I think it's the App complaining about the old TTS format. That makes sense. I only get an audible error, from what I have seen...
Yeah, no errors at all.
that's an odd situation
I'm not sure what would work
sounds like it's time to................... update
While you may not want to, the new zwave integration is worlds better than the old one
WORLDS
Things work, it's odd.
But, it can be confusing
What I have currently works basically perfectly... I haven't found the time to break it in order to upgrade.
- service: notify.mobile_app_phone_2
data:
message: TTS
data:
tts_text: >-
{% set lock_status = trigger.to_state.attributes.lock_status %}
{% set lock_status = lock_status|replace(" by RF", "by Home Assistant") %}
{% set lock_status = lock_status|replace(" by Key Cylinder or Inside thumb turn","") %}
{% set lock_status = lock_status|replace(" by user 0", "") %}
{% set lock_status = lock_status|replace("user 1", "Joe") %}
{% set lock_status = lock_status|replace("user 2", "Chance") %}
{{ trigger.to_state.attributes.friendly_name }} {{ lock_status }}
media_stream: "alarm_stream"
I am going to attempt this when I get home to test the lock.
hello again i have two helpers saving times, as example 6:42Am and 4:40pm i want to create an entity showing the resulting duration.
http://pastie.org/p/31cke2EWC4hkmkiwlPGD07 but the sensor still unavailable... Anybody has an idea?
post the state of the sensors please
from a screenshot in the developer tools states page. Do not copy/paste it here.
@vocal agate can you send a screenshot from the developer tools -> states page, not the history tab
send it in private
workingtime:
friendly_name: "AZ"
value_template: "{{ (states('sensor.arbeit_start') | today_at - states('sensor.arbeit_ende') | today_at).seconds / 60 }}"
its stays unavailable
ValueError: could not convert str to datetime: 'unknown'
maybe it is because german international time format?
ok, so you're restarting and the sensor doesn't have a time on startup
workingtime:
friendly_name: "AZ"
value_template: >
{% set start = states('sensor.arbeit_start') %}
{% set end = states('sensor.arbeit_ende') %}
{% if 'unknown' not in [ start, end ] and 'unavailable' not in [ start, end ] %}
{{ (today_at(start) - today_at(end)).seconds / 60 }}
{% else %}
none
{% endif %}
if they are input_datetimes, just
workingtime:
friendly_name: "AZ"
value_template: "{{ (states('input_datetime.arbeit_start') | today_at - states('input_datetime.arbeit_ende') | today_at).seconds / 60 }}"
well it is in minutes
so divide by 3600^^
if you want hours, yes
to german time yes
what does {{ today_at() }} return in template editor?
what does {{ now().tzinfo }} return?
the funny thing is when i substract to timestamps from the inputdatetimes and divide it by 3600 the result is 9,05
2022-09-26 00:00:00+02:00 Today at
Europe/Berlin
makes no sense why it's not working.
sure you don't have them reversed?
because start - end is 9.05, but end - start would be 14.95
if the start of your day is before the end, then you should be subtracting start from end, not end from start
value_template: "{{ (states('input_datetime.arbeit_ende') | today_at - states('input_datetime.arbeit_start') | today_at).seconds / 60 }}"
i copy pasted. π
of course now it is working properly
simple math is to much after a 9 hour work day
but however, after updating the sensor it stays unavailable
do i need the convert the values to integer?
what do you mean?
i think i need to reinitialize the sensors.yaml
now the sensor shows correct data. Thanks for your assistance petro
could you suggest a course to learn the language of Hass or it is learning by doing?
uh, learn by doing... i guess
really not many resources to learn jinja unfortunately
That's how I did it
and ask questions here
π Interesting.
I'm also having the issue with a sensor of mine that is blank.
It works fine in the template editor.
But doesn't work in my sensor.
I created a sensor that subtracts time off my son's school schedule.
And compares that to real time to determine what he should be doing prior to going to school.
(For instance, start getting ready an hour before school starts)
But while it works perfectly fine in the template, and will give me the proper value for what the state should be...
The sensor remains blank.
.share the code of the sensor @open hound
@open hound Please use a code share site to share code or logs, for example:
- http://pastie.org/ (select YAML for the language)
- https://dpaste.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 have a roku device that never "turns off"... but, I want to use it's status as presence, is there a way for me to make a binary sensor where active app home = off and any other active app = on?
so far, what I'm trying is: Create an input_boolean.
Create an automation to set the input_boolean on state change of the roku. seems to work good enough...
Is there a better way, or is this a good method?
Shared it ------^
Meh... my logic was stupid. π
Now it says "Nothing" like it should.
I'll just have to come up with a way to get it so it doesn't register every single minute as a state change. It causes my automations to go nuts. π
I don't understand some of the choices you made here
And it looks like you are comparing a string and a datetime
Ah no, skip that last comment
But now() is already in local time
And even if it was not, you can compare datetimes in different timezones
{% if states('sensor.startGettingReady') != "Nothing" %} this will never be true, entity_ids are lowercase
I removed the comparisons to "Nothing."
π
I realized they'd never evaluate to true for a different reason.
It was contradictory to logic.
But I didn't know about the entity_ids only being lowercase.
Well, actually it would always be true
anyone have any example of a sensor template for the average of a sensor value over the past X days?
example, average humidity in a room over 7 days. i'm seeing some mention of history stats but not clear how it should look
You should look at the statistics sensor https://www.home-assistant.io/integrations/statistics/
@marble jackal that one looks like it will work, thanks!
There. I have a revised version, that should work.
(Since it checks every minute (as it uses now() ), I had to add checks to keep it from assigning a state to it if it already has one assigned). π
Otherwise, it will keep re-writing the state, and falsely triggering other automations every single minute (as they check for state_changed triggers) π
I'll just have to check it tomorrow to make sure it is working all right. π
Thanks for the eyes π @marble jackal
does this look right? {{ state_attr('media_player.nest_mini', 'volume_level')|float != states('input_number.nest_default_volume_level')|float / 100 and not state_attr('media_player.nest_mini', 'volume_level') == none }}
Is the volume_level ever none?
when the nest is off yes
The template will fail when that happens
Goedenmorgen, sorry to bother you again. I did some reading in the developers corner. The description of the statistics of sensor entities suggest, that it could be possible to handle min/max data. Since your little template just works perfectly, I was wondering if you would be willing to refine it in a way, to use the statistic functions? As far as I understand min/max values are stored if it is e.g. a measurement. How about the long-term-statistic? https://developers.home-assistant.io/docs/core/entity/sensor So, if that data is there, we would need a template that extracts the maximum or minimum state or native value, together with the datetime. What do you think? Possible?
jinja templates don't have access to the statistics data
and I haven't eaten cheese of python π
What a pitty... π So I will keep on learning until - somewhere in a far away future in a far away galaxy - will master the force of HA. π€£
what check sorry?
states('input_number.nest_default_volume_level')|float / 100 }}``` ?
can anyone give me a hint how to best debug a mqtt sensor where the template is somehow wrong but I can not figurre out what
yep, like that, first check if it is not none. If it is it will immediately stop there
not without seeing the template
@ionic dagger posted a code wall, it is moved here --> https://hastebin.com/tagecaragi
Hello - I hope theres a jinja-ninja-guru soul in here, that can help me with my template
I am trying to get a script working, that will give me the most expensive time periods of the day.
I would like to use it to control my heatpump. The best way to do it, from a heatpump pov, is 2 x 3 hours of shutdown, with a minimum of 6 hours in between.
This fits with the usual wave-high of electricity prices in the morning and evening.
A kind soul on the forums has helped me with the first timeslot, and I have been trying to engineer a way for a 2nd timeslot - but my attempts have failed as of this far.
See the hastebin for the code
I have tried doing for loops and if statements, so that I could compare the results one by one, but I must achknowledge that my jinja skills aren't good enough for the task.
The code gives a list of summed prices for all the 3 hour windows of the day, so the data is there - I just have a hard time finding the result that is;
The largest value, that is also more than 6 hours from most_expensive_hours value
I have a couple of heaters and iβd like to make a template that reports their state. Like if all are heating it should say βAll Heatingβ but if only one is on and the other two are off it should say βMaster Bedroom Heatingβ (name of heater + state). If can probably coble it together using a lot of if and else statements but wondering if thereβs a smarter way to do it.
not without seeing the template
first step I would suggest is to put them in a group, eg group.heaters
{% set heaters = expand('group.heaters') %}
{% if heaters | selectattr('state', 'eq', 'heating') | list | count == heaters | list | count %}
All Heating
{% elif heaters | selectattr('state', 'eq', 'heating') | list | count == 0 %}
None Heating
{% else %}
{{ heater | selectattr('state', 'eq', 'heating') | map(attribute='name') | join(', ') | replace(',',' Heating,') ~ ' Heating' }}
{% endif %}
Great! That will get me started! Will experiment with that and see what i get!
Is here the place where I can ask a question about lambda usage in esphome?
I guess #diy-archived or maybe on the ESPHome Discord server
what's the question
@small rock posted a code wall, it is moved here --> https://hastebin.com/ogocefuhux
How can I add a value to a array? https://hastebin.com/ejakuqurim.csharp
{% set ignore_entities = [] %}
{% set entities = states.sensor
| selectattr('attributes.device_class', 'defined')
| selectattr('attributes.device_class', 'eq', 'battery')
| rejectattr('entity_id', 'in', ignore_entities)
| selectattr('state', 'is_number') %}
{% set ns = namespace(entities = []) %}
{% for entity in entities if entity.state | int < 30 %}
{% set ns.entities = ns.entities + [ entity.entity_id ] %}
{% endfor %}
{{ ns.entities }}
Thanks it works now!
How do i change so that the else diplays the attribute hvac_action next to their names instead of a generic βheatingβ in this sensor
{% if heaters | selectattr('state', 'eq', 'heat') | selectattr('attributes.hvac_action', 'eq', 'idle') | list | count == heaters | list | count %}
Radiators Idle
{% elif heaters | selectattr('state', 'eq', 'heat') | selectattr('attributes.hvac_action', 'eq', 'heating') | list | count == heaters | list | count %}
Radiators Heating
{% elif heaters | selectattr('state', 'eq', 'heat') | list | count == 0 %}
Radiators Off
{% else %}
{{ heaters | selectattr('state', 'eq', 'heat') | map(attribute='name') | join(', ') | replace(',',' Heating,') ~ ' Heating' }}
{% endif %}```
what
I'm creating Template sensors for areas in my home. So, count all the lights on, count all the doors open, etc. for each area.
- sensor:
- name: "All Kitchen Lights On"
state: >
{{ expand(area_entities('Kitchen') | select('match', 'light')) | selectattr('state','eq','on') | list | count }}
- sensor:
- name: "Kitchen Doors Open"
state: >
{{ expand(area_entities('Kitchen') | select('search', 'door')) | selectattr('state','eq','on') | list | count }}
I'm wondering if it's best practice to combine these into a single sensor per room
Eventually it will be Lights, Doors, Windows, Devices
Was this in regards to what I wrote?
Basically the last else statement displays the heaters that are turned on but it just says the name of the heater and a generic heating. I would like to change it so that it displays the name of the heater + whatever is in the attribute.hvac_action at the time
But they are all heating based on the selector
The state can be heat of off, but the hvac_action can be heating or idle
{% set heaters = expand( ['climate.master_bedroom', 'climate.adina_bedroom'], ['climate.isac_bedroom']) | selectattr('state', 'eq', 'heat') | map(attribute='entity_id') | list %}
{% for heater in heaters -%}
{{ state_attr(heater, 'friendly_name') }} {{ state_attr(heater, 'hvac_action') ~ " " }}
{%- endfor %}
that's poorly optimized
can likely be cleaned up, but maybe a starting point
you're mapping the state objects to list of entity_id's then you get the states from the state machine after you already had the state objects
sorry, I'm still learning
state objects contain the state and attributes
Id like it to work with the rest of the sensor
{% set heaters = expand( ['climate.master_bedroom', 'climate.adina_bedroom'], ['climate.isac_bedroom']) %}
{% if heaters | selectattr('state', 'eq', 'heat') | selectattr('attributes.hvac_action', 'eq', 'idle') | list | count == heaters | list | count %}
Radiators Idle
{% elif heaters | selectattr('state', 'eq', 'heat') | selectattr('attributes.hvac_action', 'eq', 'heating') | list | count == heaters | list | count %}
Radiators Heating
{% elif heaters | selectattr('state', 'eq', 'heat') | list | count == 0 %}
Radiators Off
{% else %}
{% set ns = namespace(values=[]) %}
{% for h in heaters | selectattr('state', 'eq', 'heat') %}
{% set ns.values = ns.values + [ h.name ~ '(' ~ h.attributes.hvac_action ~ ')' ] %}
{% endfor %}
{{ ns.values | join(', ') }}
{% endif %}
or you can use groupby
Sounds like some radiator-based version of the 12 days of Christmas
is the hvac_action of your radatiors off when all are off?
if yes, you can simplify that
{% set groups = expand('climate.master_bedroom', 'climate.adina_bedroom', 'climate.isac_bedroom') | groupby(attribute='attributes.hvac_action') %}
{% if groups | length == 1 %}
Radiators {{ groups[0][0].title() }}
{% elif groups | length > 1 %}
{% set ns = namespace(values=[]) %}
{% for k, values in groups %}
{% set ns.values = ns.values + [ k.title() ~ ': ' ~ values | map(attribute='name') | list | join(', ') ] %}
{% endfor %}
{{ ns.values | join(' | ') }}
{% endif %}
No unfortunatley not
Giveβs me this output Adina Bedroom(idle), Isac Bedroom(heating)
... is that what you want?
Yes! The ( was unnessecary but i could fix that. Thank you!
Maybe if i can get the attribute capitalized? I
Heating vs heating
.title()
Worked with just | title
I've the following sensor that sometimes produces unwanted spikes:
- sensor:
- name: "kamstrup totalt forbrug stat" # total usage for energy tab
availability: "{{ states('sensor.kamstrup_kwh') | float > 1000 }}"
unit_of_measurement: kWh
state: "{{ states('sensor.kamstrup_kwh') }}"
attributes:
device_class: energy
state_class: total_increasing
I have tried editing the values in the developer tools > statistics page, but the history and energy tab doesn't respect the new values. Does it have something to do with how I defined the sensor?
Your sensor will show the exact same state of sensor.kamstrup_kwh unless that sensor is below 1000 (or when it is not having a numeric state, eg when it's unavailable)
Does this source sensor reset on a daily/weekly/whatever basis?
Hello I have setup a sensor with Tasmota and yould like to invert the state of this Tasmota switch in Home Assistant. This is my sensor:
binary_sensor:
# Sensor Tasmota Heizung/Brenner
- name: "Heizung Brenner Status"
unique_id: "heizung_brenner_status"
state_topic: "tele/Brenner/SENSOR"
value_template: "{{ value_json.Switch1 }}"
icon: mdi:fire
No, the kamstrup_kwh is the total reading of my energy meter increasing every day.
But it not being a statistics sensor means I cannot edit the source sensor
Could I add state_class: total_increasing to the modbus source sensor?
- name: Kamstrup kWh
unit_of_measurement: kWh
address: 8267
slave: 1
device_class: energy
scale: 0.001
precision: 2
count: 2
data_type: int32
Hi all, this may fall under automations but I think my issue will be more to do with the formatting of the yaml. I have been trying to implement a script and automation originally created by Speek to the Geek article, https://www.speaktothegeek.co.uk/2022/04/money-saving-automations-1-heating/ but I am having issues with the script side of it. When I change the temperature thresholds in the input number helper and adjust the date to summer I expect the thermostat to switch to off however it just stays on eco. Looking at the traces for the script, it is definitely that which is causing the problem. I have linked my current yaml here for reference and would be very greatful.for any suggestions anyone may have, https://pastebin.com/uCxzyuhf -script
https://pastebin.com/76PYye2K - automation (that calls the script). Current forecast high and low is 15 and 5 degC with my set thresholds at high 30 and low 20. Winter date starts at 25th October.
Is there a function to grab entity_id or state by unique_id ?
That would be helpful to bind my template entities to specific device entities
(better then through device id that is auto generated it)
I don't understand your availability template then
Sometimes the meter fucks up and shows 0-3 kwh for a split second and then goes back to the total consumption for the house since we moved in. I need to filter out these values, which is what I tried with the availability condition. We are currently up to 8k kwh, so I just put in 1000 to be safe.
Quick question... I am running into a template loop issue. Can self-referencing the state in a comparison cause that?
Basically, the sensor updates every minute (due to using now() )
However, it has a state assigned to it from the previous iteration.
I am wanting to do a comparison that stops it from assigning the same state to the sensor, if it already has that state.
ah okay, that makes sense, but you should at least at a default to the float filter in the availability template then, to avoid errors when the source sensor is not a number
maybe that is causing the spikes
You can't not assign a state, you can only assign the state it already had
to not assign a state, you would need to have conditions like in automations, there is a feature request open for that on the forum
vote for it if you want π
It was referring back to the yaml templating I was working on earlier.
Where I was creating a custom sensor. (Still debugging it)
Finally figured out how to get it so the sensor wasn't blank (or null) by assigning an initial value...
Well... an if state that says that if it is blank, give it a value.
And hopefully, the state changes properly when it hits my schedule for it.
The goal of my sensor was to give a custom state to it at a certain time before an event (my son's school starts).
So, an hour before school starts "Start Getting Ready"
25 minutes before school starts "Wait for Bus"
Etc.
I use the state of the sensor in a Node Red flow to trigger events to happen.
when I do this:
target:
entity_id: media_player.nest_mini
data:
volume_level: "{{ states('input_number.nest_default_volume_level')|float / 100 - 0.04 }}"```
the volume changes to 0.7099999785423279
instead of 0.71
input_number.nest_default_volume_level = 75
I understand that, but a state based template sensor is evaluated on every state change, or every minute if you use now().
You can assign the same state using this.state but the template is still evaluated. There is no way to avoid this.
{{ states('input_number.nest_default_volume_level')|float / 100 - 0.04 }} shows up as 0.71 so I am not sure why it doesnt work when setting volume
that's because of floating point errors. just round the result to 2 decimals
Yeah, as I was made abundantly aware earlier. That is fine. I'll just have to come up with a work around to ignore the state change if the state hasn't changed on Node Red's end.
Because it repeating the same message through tts every single minute is annoying. π
But, I've done it before... I'll just do it again. (Just not as elegantly)
volume_level: "{{ (states('input_number.nest_default_volume_level')|float / 100 - 0.04) | round(2) }}"
Trigger on a state change of the sensor then? If the template renders to the same result it is not considered a state change
what do you use for the TTS?
google cloud
ah that makes sense - thank you π
no for the automation I meant
Oh sorry I totaly missed this, thanks!
make sure it triggers on on actual state changes, not on attributes or whatever
I noticed in #automations-archived you came to a similar template
Yeah, I am not using an automation with it.
Why would it send a TTS every minute then?
Not sure, something with Node Red (which I'll figure out there).
that's also an automation then (in the broader sense of the word)
As of right now, I finally got the sensor so it isn't null.
but that would be something for #node-red-archived then
And hopefully, with the checks I put in place, I don't start getting the same state tacked on to itself.
(I have a state of "Nothing") when there is no event going on.
And for a while there, I was getting "Nothing Nothing Nothing" because it kept appending Nothing onto itself. π
(So, hopefully, the additional checks prevent that from happening)
ah, that can be prevented
Yeah, now, if the state is already Nothing, and the state isn't supposed to change, then no state change.
So, I'll just have to check and make sure that is working later on (when it is time for my son to go to school again)
And then to my next project... scraping data off of Tuya's IoT debug pages. π
Because I will not rest until I get my door/window sensor to work within Home Assistant without having to read notifications off of my phone. Too unreliable.
And while the door window sensor integration is non-functional in Home Assistant... the debug logs do update when the sensor is triggered. π
Within the IoT on Tuya's site.
Anyways, 4:55 AM here. I'm off to bed.
why this template doesnt work (errors):
{% if ((trigger.event.data.entity_id == 'sensor.ebusd_bai_currenterror_error') OR (trigger.event.data.entity_id == 'sensor.ebusd_bai_currenterror_other_error')) %}
while this works fine:
{% if (trigger.event.data.entity_id == 'sensor.ebusd_bai_currenterror_error') %}
Your 'OR' should be 'or'
Always state what errors you're seeing, don't just say '(errors)'
ahh thanks!
@elder moon You could also use {% if trigger.event.data.entity_id in [ 'sensor.ebusd_bai_currenterror_error', 'sensor.ebusd_bai_currenterror_other_error'] %}
Anyone know how to get the number of days in the current month?
you mean 30 for this month for example?
state: >
{% set month = now().month %}
{% if month in [1,3,5,7,8,10,12] %} 31
{% elif month in [4,6,9,11] %} 30
{% else %} {{'29' if states('sensor.year')|int//4 == 0 else '28'}}
{% endif %}``` although some comments have been made in the past this will derail in 70 years....
{{ ((now().replace(day=1) + timedelta(days=31)).replace(day=1) - timedelta(days=1)).day }}
nice, that is what I saw for python just could not find the right jinja things π
Do you guys think there will be a more noob friendly way to do advanced automations and templating if we donβt have calculator brains like thefes?
nope
Some of the shit you guys come up with here is wild
time is hard, no matter what way you look at it
the problem is, there's 1000s of wrong examples on the forums that people just use
Is that a life lesson or about hass?
no, its a life lesson about dealing with time across all timezones
I was/am generating a rough electricity consumption forecast
{% set hours = (now().day * 24) + now().hour %}
{% set consumption = states('sensor.energy_month') | float(0) %}
{% set maxHours = (((now().replace(day=1) + timedelta(days=31)).replace(day=1) - timedelta(days=1)).day) * 24 %}
{% if consumption > 0 %}
{{ ((consumption / hours) * maxHours) | round(2) }}
{% endif %}
there's a whole time thread on the forums...