#templates-archived
1 messages ยท Page 112 of 1
yes, I decided to waste a bunch of cash paying someone to install stuff I probably could have built myself for the convenience of having it done before the plaster went on the wall - I both regret and don't regret this at the same time
dynalite switches and apparently fan controllers
https://paste.ubuntu.com/p/9bStwgtjxt/ I did more typing than I'm proud of
yay! this one works, with non side effects so far (except the fan goes to "high" when switched off, but that's no worse than the wallplate does) https://paste.ubuntu.com/p/bWs9xQ5twK/
I have been using now().day in a dynamic link of a website. But the link needs 0 padding for 1-9 of the month like 01, 02, 03 rather than 1, 2, 3. now().day doesn't have padding. How do i add it?
i tried {{ now().strftime(โ%dโ) }} but its only outputting 01 everytime
It says 03 for me, which is correct
my rpi instance date is wrong i guess? how do i correct it. it says 01 for me . just checked again
What does now() say?
It uses NTP, so if the day is wrong like that, itโs probably your network
2020-12-01 19:22:16.183741 . weird. how to fix that? pi is connected fine with internet. It just did some web related scripts
๐คทโโ๏ธ
Thatโs not correct anywhere in the world, so youโve evidently invented a time machine
Thanks . i will file a patent soon after i fix the problem๐ . how do i fix time?
๐คทโโ๏ธ
I did that but its giving me the error Logger:ย homeassistant.config Source:ย config.py:415 First occurred:ย 3 december 2020 19:25:44ย (9ย occurrences) Last logged:ย 9:52:52 Invalid config for [automation]: Unexpected value for condition: 'None'. Expected numeric_state, state, sun, template, time, zone, and, or, not, device @ data['condition'][0]. Got None. (See /config/configuration.yaml, line 11).
Could you share your new automation? something is clearly wrong there
Something like that should be sufficient:
condition: "{{ is_state_attr('media_player.android_tv', 'app_name', 'Netflix') }}"
@amber zodiac , with smth like date --set="Fri Dec 04 10:25:59 CET 2020"
depending on the machine your HA is running on of course
I think i dont need to use value template i guess
not really sure how to clean up my code
https://pastebin.com/f2MDwPVw this gives the same error
it says that the output is none. and that could be the case. if i look at te attributes when google tv is off then this attribute isnt active. it becomes active when google tv is on. Not really sure if this has something to do with it?
yep you wrote "{% ... %}" instead of "{{ ... }}"
{% .. %} is for if, else, endif, and other logic statements. {{...}} is to actually returns something. Here you want to return the result of the is_state so you need to use {{ }}
oops my bad... i knew that but didnt see it. but with the {{ }} it gives the same error
It is condition: "{{ is_state_attr('media_player.android_tv', 'app_name', 'Netflix') }}"
and not ```
condition:
- condition: "{{ is_state_attr('media_player.android_tv', 'app_name', 'Netflix') }}"```
If I'm not mistaking
YES! that seems to work thanks a bunch! there are allot of forum posts with incorrect examples ๐
Thanks.
- Is this to be done in command panel after entering root in login ?
- CET is to be changed to my time zone right?
- Why do you think this problem still exists ? I mean I even restarted multiple times and pi is ofc connected to internet (static ip ) and executing web related scripts fine. Its weird because time is delayed by 3 days and there is no such time zone either
I just checked log and I see this error 3 times in 5 seconds
2020-12-01 21:35:53 WARNING (MainThread) [homeassistant.setup] Setup of input_datetime is taking over 10 seconds.
- i have homeassistant core, this command need to be executed on the linux machine. I have no knowledge over other installation methods
- CET can be replaced by your timezone (either search in internet, or get the current value with
timecommand) - maybe your ntp service is not up for some reason. It is the service having the role of getting the time from internet
This warning has nothing to do with your problem
Thanks
I used the same pi ( its a rpi0 w) for a week and time was fine. Never did any commands. The only thing that changed was I upgraded core and supervisor to 2 new versions I think.
Also If NTP is not working is there a way to troubleshoot? I am asking is because I think without NTP, if my pi has a downtime due to power or reboot, it will keep lagging. right?
Possible. I donโt know if the rasp has a little battery to keep the time during shutdown
About troubleshooting ntp, of course it is possible, but not in this chat room ๐
I'm very new to templates. I'm trying to add a condition to a webhook automation to check a query key for an auth code... I see that trigger.query is available as a template variable, but is it just {{ trigger.query.<keyname> == <authcode> }} ?
Do you know the name of the key it comes in on?
If so, yes... it's just like you said ๐
I can make it whatever I want
also, what's the difference between {{ and {% for templates?
{{}} returns something. {%%} just evaluates something.
It's all Jinja templating, their documentation covers that kinda stuff.https://jinja.palletsprojects.com/en/2.11.x/
Thanks but that command threw an error. Probably format is bit different . I could not find correct one on searching.
Anyway I asked in OS core section and cogneato suggested chrony addon. It solved the issue. As you yourself needed to do that everytime, that addon can help you too. Though ofcourse we could not find the reason of problem :)
I donโt have any issue on my side but thanks for the info ๐
hi. Im wondering how these templates are working. I really dont seem to get it. I made a mqtt sensor that reads my battery voltage. Sensor outputs milliVolts and i'd like to get it as volts. How would i suppose to do this? I understand that it might be possible with templates.
You'd multiply by 1000
{{ something x 1000 }} - I don't know what your something is.
https://hastebin.com/yepezuxuvu.properties my sensor is set up like this. I just dont know how im suppose to use templates.
And you likely need to cast it from a string to an int/float (number types).
variable_name / 1000. in that example template, in configuration? i mean developer tools.
Well if you're already using an MQTT sensor, you can include a value_template to do the math for you.
You probably just want {{ value | float / 1000 }}, where value is a variable that HA already has access to in that sensor.
The | float pipe is just to ensure that if you're given a string '5', it turns it into the number 5.
yes, that value_template is baffeling me, are those (for example) value_json.RSSI in that link something that is already in hassio or do i need to make it myself?
value is whatever was sent on that topic in MQTT.
value_json is the same thing parsed from JSON to an in-memory object.
If what you shared in your paste works to display mV, you just need what I said... value_template: "{{ value | float / 1000 }}" will do the trick.
ok, just value would be enough? I'v tried to use sensor.name etc.. as the value. ๐
yes i do, multiple languages ๐ understanding this is somehow hard for me.
just as a small time hobby, and i know also good deal about electricity ๐ i just feel so dumb with hassio alltogether.
Think of it like JavaScript... you might have var data;. Then something else does data = 'hi'. Now you can ask for data and it equals 'hi'.
Same thing with that value variable. Something else that you don't see assigns a value to it. You don't need to know where it came from, only where to find it.
yes. ๐
would i need to restart hassio from server control, every time i modify configuration.yaml ?
Depends what you're changing. Integrations, yes. Lots of other stuff, no.
wow. it actually worked ๐
If you see a button to reload it under server controls, a restart isn't necessary.
thank you.
The stuff at the bottom doesn't need a restart: http://prntscr.com/vw3zhv
No problem
what is that bottom part, some addon? i only got server managment.
Maybe you need advanced mode on for that ๐ It's not an add-on.
I want to make a condition that checks if a certain light has a certain rgb:
{{ is_state_attr('light._bedroom__bed', 'rgb_color', [255,159,39]) }}
When I check the entity of the light it is in this RGB mode:
rgb color
255, 159, 39
Any idea why the condition reports false?
Use ==
{{ is_state_attr('light.bedroom_bed' , 'rgb_color' , (255, 159, 39)) }}
I am guessing
Or do what petro just suggested...
{{ state_attr('light._bedroom__bed', 'rgb_color') == [255,159,39] }}
If is_state_attr performs strict equality checking, the two lists you were comparing weren't the same.
Somehow that returned a false while mine returned a true
Then why 'I am guessing' if you'd already confirmed it? ๐ค
Yeh edited my query later on, but it didn't work, but had to refresh the page, sorry ๐ฆ
I have a doorsensor, so it's a binary_sensor. I want the state to be different the 'stock'
Normal, because it's a device_class: door, the states are Open and Closed.
I want it to be 'Geopend' or 'Gesloten, but can't get it to work..
platform: template
sensors:
terrasdeur_status:
entity_id: binary_sensor.terrasdeuren
value_template: >-
{% if states.binary_sensor.terrasdeuren.state == 'off' %}
Gesloten
{% elif states.binary_sensor.terrasdeuren.state == 'on' %}
Geopend
{% else %}
n/a
{% endif %}
Also tried it with this one, but it results only in changing icons and no changed state. The state doesn't do anything at all
platform: template
sensors:terrasdeuren_status:
friendly_name: Terrasdeuren status
entity_id: binary_sensor.terrasdeuren
value_template: "{% if is_state('binary_sensor.terrasdeuren', 'on') %}Gesloten{% else %}Geopend{% endif %}"
icon_template: "{% if is_state('binary_sensor.terrasdeuren', 'on') %}mdi:face-woman{% else %}mdi:party-popper{% endif %}"
You have to follow the standard states for sensors. If you want them to show differently in Lovelace, that's another matter.
so, you're saying it's not possible what i want or am i in the wrong channel?
I'm saying what you're trying is the wrong approach.
You only care about the language it displays the state in when it's used in the UI. For everything else, use the standard values.
If your UI is set to use Dutch, Lovelace should be showing the state in Dutch.
Don't only care about the language, this is just an example..
Instead of the dutch 'Geopend', can also be the case i want i to be 'Vrij' (means 'Free')..
or that i use this binary_sensor device for something, while there isn't a device_class for.
But you're still talking about how it's displayed. That's a Lovelace problem.
Internally, binary sensors are all just on/off. The device class just helps Lovelace use the right terms.
Ok, but how is it possible that, the state isn't changing but the icon is?
Also a Lovalace thing?
No. For that, you probably broke your template ๐
But... if you just use the normal binary sensors, everything will 'just work'.
The icon is changing according the right state, so that shouldn't be broken?!
The icon is changing according to a binary sensor, right?
Yeah, it works with the normal stuff... But don't want to use the stock part..
correct
Binary = on/off, 1/0, True/False, etc.
How can something binary understand Geopend/Gesloten/etc?
If you're just trying to change the language that's displayed in Lovelace, change it there.
value_template: "{% if is_state('binary_sensor.terrasdeuren', 'on') %}Gesloten{% else %}Geopend{% endif %}"
icon_template: "{% if is_state('binary_sensor.terrasdeuren', 'on') %}mdi:face-woman{% else %}mdi:party-popper{% endif %}"
I mean, here above it won't change to 'Gesloten' or 'Geopend', but it changes icon from 'face-woman' to 'party-popper'
so, there i know for sure the template-part is correctly ?!
Test the template in
> Templates. It works for me.
At least partly... I don't have that sensor, so it does the 'else' and shows me 'Geopend'.
it works over there, but it won't change in the Lovalace part..
Also it won't change in Developer -> states..
Well your config looks okay based on what you've said. The only other thing I can suggest is to change the template to this:
{{ 'Gesloten' if is_state('binary_sensor.terrasdeuren', 'on') else 'Geopend' }}
Functionally equivalent but only uses the {{}} block.
Unfortunately, the state remains 'off'
Then I'll go back to my original point for the last time. This is better handled in Lovelace. Even if a native Lovelace card doesn't support templates, you can use this custom card to allow it: https://github.com/iantrich/config-template-card
Your choice what you do with it but I'm outta ideas on the backend. #frontend-archived if you want help with that.
in this post it works..
๐คทโโ๏ธ
I've told you the easy option. Your choice if you do it or not but I'm done here. Good luck.
okay, thanks for the help ๐
@ivory delta is that card much different from card-templater?
@spring path if lovelace doesn't show the correct state or icon, you're using the wrong entity_id. If the icon is correct but the state is not, clear your cache and refresh the page.
doens't work for me, it's not even changing in the deverlopers state page..
๏ฟผpost a screenshot of the entity you are using in the dev tools states page and the template you are using
Ohai! ๐ I'm trying to setup a light.template with the set_color option specified so I have a color-picker. However, whenever I select a color it's not stored in the attributes of this light. When I specify set_white_value and set_temperature they both set their respective options (color_temp & white_value). Is this intended?
This is the configuration I currently have where RGB is the only thing that's not stored in the attributes. https://pastebin.com/qUJ1J0Gp
@amber rose you havenโt implemented any of the fields that set the light information...
@mighty ledge That's correct, considering the attributes were still updating I figured it wasn't a big issue.
Because it looks like I can only add actions which is not really what I'm looking for
Mind you, I have also tried using an action to set the rgb_color using light.turn_on and the same entity_id but that wasn't setting the attributes either
Do you understand what the template is doing for the integration?
Also do you understand the point of the template light integration?
I think I do, yes.
Ok, so without implementing turn_on or turn_off, how would this new light that you're creating turn on or off?
without implementing a color template, how would the light know what color it is?
without implementing set_level, how would the light know what brightness it's at?
or level_template for that matter
Yeah I get your point, but in what I'm trying to achieve this wasn't relevant afaik
the only thing you implemented was value_template. So your light would only show a state and have nothing else
I think I try to do something hacky here
what are you trying to do exactly
Okay, here we go .. ๐
your original post doesn't really explain it
I understand ๐
I'm trying to create 6 different 'lights' which don't really exist, I only want to use the color-picker function to set an RGB value. The RGB value for each of those lights will then be used to add to an array that the new Lidl Christmas Tree lights support
what does the lidl christmast tree lights integration create?
can anyone help with a template that gives true when the day is an impair number?
Impair?
It's a zigbee device exposed through zigbee2mqtt, the only thing that works out of the box with HA light turn on/off, brightness and RGB for the whole led string
I'm using node-red to gather information on what I want to see for this led string and publish that in an mqtt topic for this light
Yes but does it create a light? or a switch?
It creates a light
Assuming you mean odd numbered days, something like this: {% if now().day % 2 == 1 %}. That would be True when the day of the week is an odd number.
it creates 1 light, but you want to separate that one light into 6 lights?
Yes, but only to use the RGB attributes. There are effects you can select (which are not exposed to HA but I added an input_select for that) which supports an array with 6 different RGB values to show on the strip. So I still use the original light to turn everything on and off
Maybe this is more clear: https://www.zigbee2mqtt.io/devices/HG06467.html
That is the actual device I'm talking about
is there a way to access these RGB values from zigbee?
or HA
like, can you look at a topic and see these 6 rgb values?
Yes
Ok, then light template is what you want
Let me pastebin it
You need to implement a turn_on, turn_off, value_template, color_template, and set color
Your color_template should get the rgb values out of that color list
the format should return [r,g,b]
your set color will call a service that SETS that color into that topic
or it will call whatever function your plan to use to push the color to the device.
Right
turn on and turn off are required, so you'll have to set something up for them
typically, i would just create a template looking at the main entity
{{ is_state('light.main', 'on') }} for value_template
nothing else
turn_on should probably just turn that main light on
you should probably implement a level_template as well that pulls the light level from the single light
and set level should do the same.
all 6 will have the same on/off state and have the same turnon/turn off implementation
whenever your main light is on, those other six should also be on
Is it a problem if not all of them were on? Some effects support max 3 different rgb values so my idea was to show the light is on (if it is) and if this Nth light is still usable for the rgb valus
For example, light 4 5 and 6 will be 'off' if I selected an effect which only supports 3 different rgb values
Yes
then you'd probably want to build that into your value_template
and if you don't want those individual lights to actually have a turn_on/off functionality, put a dump service in them.
Ah okay, yeah I might do that since my main goal is to only use the functionality to just pick a color for the led strip
Actually
you're going to need to make it a scrdipt
script*
and you'll need to conditionally run the script based on the number of available items in that list
because the only way to set color is through the light.turn_on service
so you have to implement that.
tha'ts the only way the color picker will work
np
now that I've thought about it some more... i don't think you need a turn_on service
just make it a dummy service
you do need a set_color service
Okay
I'm going to cook dinner now, watch F1 so I'll probably get to this later today or tomorrow, I'll let you know when I successfully implemented it ๐
Also, looking back I didn't 100% understand the integration ๐
it's all good, first template integrations always take extra time to fully learn
Hello, I want to extract only one value out of an attribute but I don't succeed... Can someone help me please? This is an example of the attribute of my vibration sensor: "orientation: 0, 77, 13". I want to extract the third value out of it.
I think I found your exact case right here: https://community.home-assistant.io/t/need-help-with-template-sensor-extracting-3rd-comma-seperated-value-of-an-attribute/138232
thx! ๐
Apoligize for the delay, Saint Nicholas was in town..
I can't upload it here, no rights for it.
https://paste.pics/AXBKA (Off status)
https://paste.pics/AXBLU (On status)
https://paste.pics/AXBL3
https://paste.pics/AXBLJ
The problem is that you're creating a template in the binary_sensor domian
binary_sensors can only be on or off
and the translation happens on the UI though changing your language in the main menu
If you want to set states that are not the same as your language, then you need to make a sensor, not a binary_sensor.
sensors can be set to any state
instead of making a template binary_sensor, make a template sensor...
Or customise in the front-end...
All of this was just to get different text on the front-end.
Not only, also having aan Toon (Thermostat) which is using the state..
Wanted to display a different state there also..
just move that template sensor from the binary_sensor section to the sensor section and it will work
you currently have...
binary_sensor:
- platform: template
sensors:
garagedeuren2_status:
...
change it to
sensor:
- platform: template
sensors:
garagedeuren2_status:
...
keep in mind that your automations will have to check for the state on the sensor now and not on/off
but you can just use the original binary_sensor for automations with on/off
np
I got the following template in a condition, however the condition should not run when this condition is true (light is on and in certain rgb mode), how can I change it around?
{{ is_state_attr('light.bedroom_bed' , 'rgb_color' , (255, 159, 39)) }}
Just put not at the beginning
{{ not is_state_attr('light.bedroom_bed' , 'rgb_color' , (255, 159, 39)) }}
ow wow, that's easier then I expected ๐
hi there
@young plank posted a code wall, it is moved here --> https://paste.ubuntu.com/p/5vxRcZZgTZ/
thank you Bot ๐
I have been using: https://github.com/rogro82/hass-variables
But I guess it doens't work anymore in the new HA version...
I got those variables, how to make it work again?
Hi Everyone. I need to create a sensor that shows time since last high value (temperature). Any pointers?
How can I check if there WAS motion (detected) in the last 5 minutes? I am trying this one, but this just checks the last update time of the motion group, which doesnt exactly check if there was motion detected?
- condition: template
value_template: <- {{ (as_timestamp(now())-as_timestamp(states.group.motion_bedroom.last_updated)) < 180 }}
Because it will also update when motion goes from detected to clear.
{{ now().strftime('%H:%M') }}
Trying to make a command_line sensor value that is a integer and will natively be graphed by Home Assistant
- platform: command_line
command: ./ezsp_counters.sh COUNTER_MAC_RX_BROADCAST
name: EZSP_COUNTER_MAC_RX_BROADCAST
The shell script returns 11 then ascends
Add value_template: '{{ value | int }}' enough to cast it?
^ Doesn't seem to be
Are you sure ./ is the right path ? And is your script executable by HA?
What is wrong exactly ? The cast in int? Or the execution of the command?
data is being returned fine, I was just hoping to have HA graph the value natively
Instead I get this: https://imgur.com/SC30yXU
Thatโs not linked to your cast. States in HA are always string
k, thank you
Maybe it is because in the historic at some point you have a non number value
I did nuke the sqlite db and restart a few times
Thanks -- is there a unit_of_measurement for a counter or integer?
You choose whatever you want, it is a free string
I'm attempting to implement fwd/rew for my chromecast and not having a lot of luck - time stamps seem somewhat arbitrary. Anyone tried something similar? ```chromecast_forward:
alias: Chromecast Forward
sequence:
- service: media_player.media_seek
data:
seek_position: >
{{ state_attr('media_player.chromecast', 'media_position') + 15 }}
entity_id: media_player.chromecast
mode: single```
(Implemented as a script)
I suggest you convert state_attr('media_player.chromecast', 'media_position')to an int before adding 15
{{ state_attr('media_player.chromecast', 'media_position') | int + 15 }}
That's interesting. What would be the gain there?
Attributes are strings. If you try to evaluate this {{"4"+2}} in the template testing screen, it will fail. I'm surprise it doesn't fail in your case but maybe HA is wrongly converting the string in unicode or something like that... Juste a tought ๐
which wouled give the impression of a random behavior
Ouch! Thanks ๐
String maths 
Hm. No change.
What did change things I think is pausing before running the seek. There is an odour about this integration.
๐ข
Type cast insight was excellent though ๐ No fan of dynamically typed adventures on this end ๐
I'm at pretty close now, so I'll use it for a bit and see if I can discern a pattern for a git issue / forum thread ๐
Attributes arenโt necessarily strings - they can have real types
Yes that's what I realized yesterday
Do I need the <- in this?
value_template: <- {{ (as_timestamp(now())-as_timestamp(states.binary_sensor.bedroom_door.last_updated)) < 60 }}
It seems this template is doing the opposite of what I want it to be doing, simply changing < to > gives a an error:
block scalar
in "/config/automations.yaml", line 594, column 25
expected a comment or a line break, but found '{'
Wirte it that way : value_template: "{{ (as_timestamp(now())-as_timestamp(states.binary_sensor.bedroom_door.last_updated)) < 60 }}"
you should use > if you have a multi-line template, which is not the case here
Other solution:
value_template: <
{{ (as_timestamp(now())-as_timestamp(states.binary_sensor.bedroom_door.last_updated)) < 60 }}
wrong carrot
lol, we've all been there
i'm using the following in a service call:
entity_id: camera.front_doorbell_cam
filename: "/media/local/camera/snapshots/{{ entity_id.name }}/{{ as_timestamp(now()) | timestamp_custom('%Y-%m-%d_%H-%M-%S') }}.jpg"
but the entity_id.name comes back as Front Doorbell Camera. Is there a way for me to get the entity_id itself which is camera.front_doorbell_cam ?
entity_id.entity_id
damn can't believe it was that simple
i was trying entity_id.id and getting nothing
lol
Im just guessing, but since name works, entity_id should be the state object
hello, need help on template to check multiple battery sensors at once?
Do i need to create template sensor or somehow can list them in automation condition?
idea is if i have sensor.*battery_level below 10% to fire notification
The <- also could have caused the opposite behavior? It did something it wasn't supposed to do.
opposite of what? The > indication just lets the field know that the following lines are included in this field, nothing more. It's not even for templates. It can be used in any field where you want to identify a multiline field.
field: single line
field: >
multiline
Some readings: https://www.baeldung.com/yaml-multi-line
aha!
change to >- to strip extra whitespace too
hi, i want to extract the minute value of a timer via a template
"{{ state_attr('timer.trockner','remaining') }}"
it would be 00:58:00 in this case. how do i have to modify the template?
to only get 58 out
{{ strptime(state_attr('timer.trockner','remaining'), '%H:%M:%S').minute }}
this is the solution for people that are interested!
Hello! I'm trying to write a template that gets an attribute from a sensor. That attribute is a list and I would like to get the item in the 4th index of the 0th index in that list. Here is my template so far: "{{ state_attr('weather.smhi_home', 'forecast') }}"What I get is: "[{'datetime': '2020-12-08T20:00:00', 'temperature': 3, 'templow': 3, 'precipitation': 0.2, 'condition': 'cloudy'}, {'datetime': '2020-12-09T12:00:00', 'temperature': 3, 'templow': 2, 'precipitation': 0.3, 'condition': 'cloudy'}, {'datetime': '2020-12-10T12:00:00', 'temperature': 3, 'templow': 2, 'precipitation': 0.3, 'condition': 'cloudy'}, ....................................................}]" So I want to choose today's forecast and then precipitation.
Looks like the list is in date order. Is it always sorted?
If so... {{ state_attr('weather.smhi_home', 'forecast')[0].temperature }}
Yes it is. So the 0th index will always be today's forecast.
Each item in that list is a dict (object), so you don't reference by index. Instead, reference by name using 'dot notation'.
Oh, I see. Thanks for the help!
Can someone who understands a bit of yaml help me understand this? https://pastebin.com/qFQLFt7d This is a script from CCOSTAN according speech processing & engine.
Help you understand what? What's the problem?
That part after "media_player:"
I can do and understand easy stuff like this:
media_player.echo_dot_wohnzimmer
{% else %}
media_player.echo_dot_schlafzimmer
{% endif %}```
But I pretty much dont understand what is done there and that pastebin after media_player
It's basically just returning a list of players unless there was already a single player specified.
Ahh. That makes sense. So Bascially when I would have that top part with ยดif group.computer.state == onยด I dont really need that?
Well since you haven't said what you're trying to achieve, no-one can say what you need to do.
I'd like to overlay today's temperature graph with yesterday's temperature graph. Ideally I'd like to use the same sensor and in the graphing card add some type of template conversion to offset the second display by -24 hours. Any recommendations on how I can do this?
guys
I have a question
about Trigger Data https://www.home-assistant.io/docs/automation/templating/#state
if an automation triggers after an entity changes its state from off to on, a test for the Trigger Data would be {{ trigger.to_state == 'on' }}
is that right?
@wet sail you could create an sql sensor that retrieve the temp of yesterday same time. So that you can display that sensor + todayโs temperature on the same graph
Some inspiration : #templates-archived message
is there an explanation why I need to put '.state' at the and? I saw just 'trigger.to_state' in the docs
trigger.to_statewill return the state object which contain the state, the attributes, and so on. So if you want the state string, you need to add .state at the end
state object which is actually a dict object
what would be the syntax for {{ is_state(A, x) AND (is_state(B, y) OR is_state(C,z)) }}
I hope you understand what I mean hahaha
Replace AND with and and you are good
are the parentheses right?
(is_state(B, y) OR is_state(C,z))
can I use 2 parentheses like that?
I'm not a programmer , don't know the syntax . tried to google but didn't find the answer for that
{{ is_state('sun.sun', 'below_horizon') and (is_state('switch.entrance_light', 'on') or is_state('switch.christmas_tree', 'on')) }}
yes that's correct
Thanks slashback
Hi Ho, hope this is the right place to ask. I tried to set the device_class for a door/window binary_sensor which is in that case on a window to the following:
binary_sensor.shelly_badfenster_links:
device_class: window
Problem is, icon doesnยดt change. Itยดs still a Door instead of a window. Reloaded the customize.yaml and triggered the sensor already but no change. Any idea why? thx.
Wrong channel, nothing to do with templates ๐
D'oh, ignore me. Head over to #integrations-archived and see what they say.
I have this code: {% if state_attr('weather.mylocation', 'temperature')|float <= 0 > -40 %} The temperature is between 0 and -40 degrees {%- else -%} The temperature is above 0 degrees {%- endif %}
when testing in the dev portal it seems to work... but it looks kinda strange. Can anyone confirm this is correct? I know in my php time you needed && between values but this is another language so this could be ok
If it works, it's correct ๐คทโโ๏ธ
I don't think you're accounting for the temperature being below -40 though. Looks like you're testing if 0 is more than -40.
Yes. You can prove it with this: {% if -60 <= 0 > -40 %}
You need to flip your logic around: {% if 0 >= -60 > -40 %}
And then you also need another return value for when the temp is under -40. Yours will tell you it's 'above 0 degrees'.
yeah well i dont think the temperature is gonna get below -40 any time soon here... maybe when an ice age happens
Then why bother specifying it?
i want to set the heater off half an hour later when the temp outside is below zero and above -10
{% if state_attr('weather.mylocation', 'temperature')|float <= 0 %}
and an hour later when it is below -10
the tricky part is to account for the fact that between half an hour and an hour the temp can change in which both dont apply
That's a good one. Thanks
hi, how do i get the state before the actual state of an entity like {{ states(''person.sam'') }}
What do you mean by "before"
the state before the actual state
like if person.sam is home now it was not_home before
So you want to get the info out of the history
yes
That's a good question. Never did something like that before. I guess it's possible.
https://www.home-assistant.io/integrations/history/ you can read this but this doesn't explain how to get old data out of it.
But I don't think this question belongs in #templates-archived
i like to do it with a template so i can paste the old state in a notification message
like
message: Sam left _the old location_
you can put the value of a state in a helper. And on it changing trigger an automation that posts the old one. And then update it to the helper
i was hoping that i can solve this without the use of a helper..
but good point i thought about that too
https://www.home-assistant.io/integrations/history_stats/ maybe this is something
no time to read it all
i tried to use an input_text helper at the end of the automation but they dont like templates i guess
entity_id: input_text.sam_old_zone
value: "{{ states('person.sam') }}"
tried it with this but nope does not work in automations
i just get {{ states('person.sam') }} in the text of input_text.sam_old_zone
this is weird
@young jacinth you need the trigger.from_state
https://www.home-assistant.io/docs/automation/templating/#trigger-state-object
thanks alot
this was what i have been looking for!
i hope this works out as it seems that i cant test this automation with a manual trigger
templates are great :)))))
I tried to use the example code but it appears addtime is not a supported function in HA's version of SQL?
It works for me...
platform: sql
db_url: !secret db_url
queries:
- name: "Test addtime"
query: 'select state from states where entity_id = "sensor.date_time" and last_changed < addtime(current_timestamp(), "-24:00:00") order by last_changed desc limit 1'
column: 'state'
sensor.test_addtime gives me 2020-12-08, 18:18
which is yesterday time
when running the query in sqlLite Web I get near "(": syntax error
if I remove () from current_timestamp() I get no such function: addtime
i'm on HA OS running on a RPI, I've never really considered what version of SQL I am running
I think I found the answer https://www.sqlitetutorial.net/sqlite-date-functions/sqlite-time-function/
The standard is sqlite. Use this instead DATETIME(..) fct instead
datetime('now', '-24 hours')
that works! Will I need to wait 24 hours before this new sensor has all the data or is it populated in real-time when queried?
you'll have to wait
- id: '1607529390367'
alias: test
description: ''
trigger: []
condition:
- condition: template
value_template: '{{ False }}'
action:
- service: light.toggle
data: {}
entity_id: light.wled_1
mode: single
Why does this automation still toggle the light? Even when I straight up made the condition False ??????
hi there!
I have got the following condition as part of an automation:
- condition: template
value_template: >
{%- set new_state = trigger.event.data.new_state %}
{{ new_state.object_id.startswith('l0') or new_state.object_id.startswith('l0') }}
My questions:
- how can this template be improved?
I am a newbie and have got the feeling that there is a better way to get the entity id of the object which triggered the automation. - how can I find out whether the entity id ends in 'pir 01'? as you might guess i tried ...endswith(... .
- where does one find such wonderful functions as startswith?
- you're doing it right already
- you're doing it right already
- have you looked at the pins in this channel?
I guess I don't know how to access the pins of the channel. I am on Linux in the app and on the top I can see the name of the channel and the hint on the docs at home-assistant.io
No push pin icon?
Ooops ... Just found them... ๐
Funny as it is - it looks as if my eyesight is still not good enough to find some pointer towards docs.
With the keyword 'jinya' from the template test page i found docs thanks to google.
Can you please point me where I can find pointers in the pins to do some RTFM on e.g. startswith?
Only if you stop tagging me ๐
There's quite a lot to their documentation, as you can see here: https://jinja.palletsprojects.com/en/2.10.x/templates/. However, the most commonly used bits are the built-in filters (https://jinja.palletsprojects.com/en/2.10.x/templates/#builtin-filters) and the fact that it understands native Python functions (like str.endswith())
You can also use regex: {{ entity_id|regex_match("\.l0.*pir01$")}}
Hello everyone, i had a working next alarm template now the entity_id: option is deprecated, iv deleted the entity id and have been trying to get it to work but the binary sensor just wont change from off to on. this is my old template # My next alarm
- platform: template
sensors:
ians_next_alarm:
entity_id:
- sensor.ians_mobile_next_alarm
- sensor.time
friendly_name: "Ians Next Alarm"
value_template: >-
{{now().strftime("%a %h %d %H:%M %Z %Y") == (((state_attr('sensor.ians_mobile_next_alarm', 'Time in Milliseconds') | int / 1000) + 0*60 ) | timestamp_custom('%a %h %d %H:%M %Z %Y'))}}
Any ideas why it would not work by just deleting entity_id:
- sensor.ians_mobile_next_alarm
- sensor.time
you should avoid the use of now() and create & use a datetime sensor instead https://www.home-assistant.io/integrations/time_date/
Why? I thought they changed it so now() properly evaluates templates.
Fewer things to get wrong if you don't need to introduce intermediary layers.
as far as I understood, a change in now() will not trigger a refresh of the templates. a change in the datetime sensors will do
That used to be true.
well apparently it is refreshed every minutes
Go put {{ now() }} into the Dev Tools. You'll see a note under the right hand side stating that it'll update once per minute. If that's good enough, there's no need to do anything else.
so, my bad
๐
It was a fairly recent change and advice had previously always been to use time_date, so don't worry ๐
Would you do it like this? - platform: template
sensors:
ians_next_alarm:
friendly_name: "Ians Next Alarm"
value_template: >-
{{ states('sensor.date_time') == (state_attr('sensor.ians_mobile_next_alarm', 'timestamp') | int | timestamp_custom('%Y-%m-%d, %H:%M', True)) }}
well apperently it won't change anything
BTW, you could have made a binary_sensor instead of a sensor
but in won't fix your issue though ๐
I'm not sure this belongs here, but is it possible to get the entity_id from the entity_registry if I have the device_id?
it does not matter which entity_id
the device name would be fine as well from the device_registry
hi people, i'm trying to do a phone template for my wall (replacing switchs) but i want to get ride of menu bar on top, how to do it?
@desert quail thats a #frontend-archived question
what? thats a template question
Become a real Jinja2 Ninja! Don't worry my Genin, we are here to help! You can find the docs at https://www.home-assistant.io/docs/automation/templating/ - and don't forget rule #1! Please use https://www.hastebin.com/ or https://paste.ubuntu.com/ to share code or logs
I'm trying to setup a very simple MQTT Fan. There is one MQTT topic (zway/livingRoom/ceilingFan) with a number from 0 to 99. How do I configure 'payload_on' to be any value greater than 0?
Don't think you can with the MQTT one. You probably need to wrap it in a template fan: https://www.home-assistant.io/integrations/fan.template/
As the name suggests, that allows the use of templates. You could have a template for value_template that simply checks it's greater than zero.
got it ... thanks a bunch
@scenic mica state_value_template: "{{ value_json > 0 }}"
Just in case anyone has the same problem with the template for next alarm, It is now working the solution is value_template: "{{((states('sensor.mobile_next_alarm')|as_timestamp|int - now()|as_timestamp|int)/60)|int}}"
availability_template: "{{ not is_state('sensor.mobile_next_alarm','unavailable') }}"
attribute_templates:
time: "{{ state_attr('sensor.mobile_next_alarm','Local Time') }}"
you got a few too many int casts in there
thanks i didnt see that would it create any problems in the back ground because it seems to be working well, iv sent two days on this one and finally got it to work
it won't, just making observations
Wh y do you want a sensor that outputs the next alarm in minutes anyways?
wouldn't you rather have a friendly format?
i would but no one could help me with it iv just struggled to get it all up and running, being a beginner at code like this
All you need to do is output the timestamp and change the device_class to timestamp and it wll have a freindly format like "in 4 hours"
and your mobile_next_alarm sensor looks like it's a formated timestamp already
so all you need to do is add device_class: timestamp to it in customizations and when you place it in an entities card it will give relative time
I see i get it now thankyou, it will be good to see it in a card also. Iv just been using it with automation and scenes, so when i plug my mobile in at night the pir and bedroom light goes off and when the alarm goes off in the morning the pir and bedroom light comes back on
you just need a template trigger for that, not a template sensor though
so if i put the template value into a automation trigger it will work without the template sensor
No, you'd need to tailor the template to return true when the alarm timestamp matches the current time
what's the format of your sensor.next_alarm_time state?
It looks like this 2020-12-10T06:30:00.000Z
{{ states('sensor.mobile_next_alarm')[:16] == as_timestamp(now()) | timestamp_custom('%Y-%m-%dT%H:%M') }}
Thanks you very much, I will give it a go when i get home tonight
I am playing around with templates and noticed that my lights have an attribute 'supported_features: 41' Is this another list of attributes I can access somehow?
Nevermind, found some good posts online that describes it: https://community.home-assistant.io/t/supported-features/43696/6
hey there. my input_boolean.last_changed time does not match what is in the UI for history. I am using astimestamp() to get the right time zone. Iโm getting 30 minutes ago (wrong) from this template. The history on the entity UI is 5 hours ago (correct)
Did you restart HA in that time period?
I donโt think the last_changed times survive a restart
Would anyone know why a simple template such as
action:
service: "{{ light.turn_off }}"
Results into this config check error:
Invalid config for [automation]: Service {{ light.turn_off }} does not match format <domain>.<name> for dictionary value @ data['action'][0]['service']. Got None. (See /config/configuration.yaml, line 9).
It seems like my Jinja is not evaluated at all
try with service_template instead
That actually worked. I am a bit confused, why do I need to use service_template instead of just service? Is there an x_template equivalent for all types?
By "it works" I mean, it doesn't throw a configuration error. I haven't tried using it yet.
@inner mesa so if last_changed times don't survive, what the heck is the UI in Lovelace using to accurately persist that correct time?
@daring tendon posted a code wall, it is moved here --> https://paste.ubuntu.com/p/jSZsHpTmJB/
@raw dust can you help me out on this one then? I am trying to populate the entity_id field in an action with a template as well. Getting a similar error. Link is above.
there is no such thing as entity_id_template, it's just entity_id: and template
Tried that as well, it threw me this:
Invalid config for [automation]: not a valid value for dictionary value @ data['action'][0]['entity_id']. Got None. (See /config/configuration.yaml, line 9).
But throwing my template into the Developer Tools > Template - It print out an entity ID
could you share the code for the second error?
action:
- service_template: >
{% set toState = (['on', 'off'] | random) %}
{{ 'light.turn_' + toState }}
entity_id: >
{{ states['light'] |
rejectattr('state','eq', 'unavailable') |
rejectattr('attributes.is_deconz_group') |
rejectattr('attributes.supported_features', 'eq', 0) |
map(attribute="entity_id") |
list |
random }}
try it with data_template like:
- service_template: >
{% set toState = (['on', 'off'] | random) %}
{{ 'light.turn_' + toState }}
data_template:
entity_id: >
@raw dust thank you! That worked!
You should update HA. It seems like youโre several versions behind
I'm looking for a means to read/write some settings to permanent storage (like write current state of this light, then read it back later) and while the File integration looks promising for the read part, it does not appear to support writing. So I was thinking maybe I am missing some other method for permanent settings storage? Or is that sort of thing just not available at this time?
hi,
data:
type: tts
message: test
target: >-
{% if is_state('binary_sensor.wz_besetzt', 'on') %}-
media_player.wohnzimmer_alexa {% endif %}{% if
is_state('binary_sensor.sz_besetzt', 'on') %} -
media_player.schlafzimmer_alexa {% endif %}
i want to use a template for the targets in this notify service call, but i cant get the syntax right
You could do something like this: https://github.com/CCOSTAN/Home-AssistantConfig/blob/master/config/script/speech_engine.yaml
It'll output a native list from the template, rather than you trying to write a list in plain text (which I don't think works).
mhh thanks, but how do it get the conditions in?
Almost like you're doing now. Just change it so you start with an empty list, add each target to the list if it's turned on, return the list at the end.
{% if media_player | length == 0 %}
{% set media_player = [
{% if is_state('binary_sensor.wz_besetzt', 'on') %}
media_player.wohnzimmer_alexa {% endif %}
] %}
{% endif %}
{% if media_player is not string and media_player is sequence %}
{% set media_player = media_player|join(', ') %}
{% endif %}
{{ media_player }}
this wont work
@deft timber Ah so I would be able to read/write the full state to input_text. Very cool.
Thanks ๐
i do not how i add something to a list
Here , try this:
http://letmegooglethat.com/?q=how+to+add+to+list+in+python
ehh adding things to a list in HA's implementation of jinja is kind of a thing
{% for thing in things %}
{% set ns.l1 = ns.l1 + [thing] %}
{% endfor %}
{{ ns.l1 }}
ehh ~~adding things to a list in HA's implementation of ~~ jinja is kind of a thing
that applies to me better
other jinja envs aren't as picky
list.append() is a thing in jinja but the specific env that HA uses disables that
TIL. Still, it's the right approach.
iam quite overhelmed with templates
i get basic ones going but that is to difficult for me
{{ states.binary_sensor|selectattr("state", "eq", "on")|map(attribute="entity_id")|list }}
@ivory delta ๐
or:
{{ ", ".join(states.binary_sensor|selectattr("state", "eq", "on")|map(attribute="entity_id")|list) }}
There are many ways to skin a cat
i usually try to avoid loops and namespacing whenever i can
Yeah, the pipes are probably easier to reason with and also result in more concise templates.
and that's all built in jinja filters. Nothing HA specific other than the states object
I love seeing the stuff people do with |map. I need to make better use of it.
I'm getting to the point where I have enough devices to justify custom attributes to map by room.
i had to look it up again for this. I can never remember how to use it properly
https://hastebin.com/ilihefegug.yaml the automation not work and I don't know why. can someone help me? it is a timer created with a slider to be able to choose the duration. Everything works except the trigger and the final action of turning off the light. In practice, everything works but the automation does not start or stop when the light status changes.
Keep it to English, please. And you're probably better off in #automations-archived
in automations they told me to ask for help here
They also suggested you test the template. Did you do that?
I don't understand how to do it
ok i tested now
UndefinedError: 'trigger' is undefined
And that only exists in an automation. Replace it with the real entity's name.
ok. thanks. i attempt
i modified it but the error persist. {{ trigger.entity_id == 'switch.sonoff_lucescale' + states('input_select.luci_timer')|lower }} https://hastebin.com/fubonokude.yaml
Yes... You can't use trigger outside of an automation.
In my automation I am picking a random light and turning it either on or off using templates. However, I would like to know what state my randomly picked entity is in so I can pick the opposite state from on to off and off to on. How do I get my randomly picked result for entity_id into the template for service_template?: https://pastebin.com/8QhcCLLj
Alright, good call I'll properly go with light.toggle. I wasn't aware of that! But lets just say, I still want to parse a variable from one template section to another. Does templates in the same configuration share scope? Would I be able to do something like this?
action:
- data_template:
entity_id: >
{% set randomEntity = pickRandomEntity() %}
service_template: >
{{ randomEntity }}
Just clarifying, above is just pseudo code.
Nope. Different scopes.
But you could possibly use variables.
Honestly... if you ever wanted to do something like that, just make it a script and pass the randomly selected entity in instead. Way less ugly, way easier to maintain.
I am not familiar with scripts yet so I am not exactly sure how that would look that.
Well I just linked the docs, have a read ๐
You've used scripts already (that's all the actions of an automation are). The bit you didn't realise is that you can define scripts that stand alone too.
How would a script be different from what I was already doing in my pastebin? Isn't it more of a tool to isolate your code pieces and reuse them?
Exactly my point. Your action in the automation would only be responsible for picking a random entity ID and calling a script with it. The script's responsibility would be to check the state of that entity and call the relevant service.
Isolation and reuse in a nutshell ๐
You've essentially just created a 'toggle entity X' script.
Oh, so my randomly picked entity_id becomes an input parameter for the script which is then accessible throughout the entire script?
Bingo
Neat, I'll try and take a stab at it. Thank you @ivory delta ๐ค
Just to clarify, I do still need to use variables? Even though I am moving my silly "toggle service" to a script, I still need to be able to parse my randomly selected entity_id to my custom script.toggle, right?
From what I can read this is how I invoke a custom script:
action:
- data_template:
entity_id: >
{% set randomEntity = pickRandomEntity() %}
service: script.toggle
entity_id: [[INSERT RANDOM ENTITY_ID]]
Nope
Just assign the template that picks a random entity to entity_id:
No need for the last line and also no need for data_template:, just use data:.
Some docs still need to be updated. No need for the _template suffix anymore.
I am not sure I follow. How does my script access my randomly selected entity_id if I don't parse it in as an input parameter?
This bit is gibberish and would fail validation:
service: script.toggle
entity_id: [[INSERT RANDOM ENTITY_ID]]```
This is good enough:
action:
- data_template:
entity_id: >
{% set randomEntity = pickRandomEntity() %}
service: script.toggle```
Well, move the entity ID under variables, as documented in the section I just linked.
I believe I follow you now.
We're into #automations-archived territory at this point as well. If you have any more questions about it, ask over there. I'm done for the night but someone else will help.
Alright, thank you so far @ivory delta
@blazing burrow posted a code wall, it is moved here --> https://paste.ubuntu.com/p/Q2NnsJdXG8/
trying to figure out why this isn't working... ^
this template: {{ states("input_number.wled_preset") | int }} does evaluate to the correct integer i've got selected by the input_number, and this call works in postman: curl -L -X POST 'http://192.168.1.189/json/state' -H 'Content-Type: application/json' --data-raw '{"psave": 16}'
but calling the rest_command doesn't actually save the preset
same call in postman does
so i'm thinking i've got formatted wrong?
but can't figure out what's wrong
ohh i need to pass the content type as header maybe
that didn't seem to help ๐ค
took it #integrations-archived, maybe it belongs better there
hey folks, having an issue with a value template as i am trying to build out an alarm using a SDR and Honeywell Door/Window sensors
value_template: '{% if value_json.id is equalto 860776 and value_json.event is equalto 160 %} {{value_json.state}} {% else %} {{value_json.state= "off"}} {% endif %}'
this is what i have and the open portion works, but the setting of the state to off is not working. i have tried a few ways to no avail
does anyone have any suggestions for me
its may look odd, but it works other than {{value_json.state= "off"}} which i know is wrong
i have poked at it, tried declaring the var etc
this is not expected to work but as an example of what im trying to do
value_template: '{{ "on" if value_json.id == 860776 and value_json.event == 160 else "off" }}'
something like that should do
well thats a nice simple way and it works, awesome thanks @blazing burrow
does someone have a good...idk blogpost or something explaining simple templating with examples? I've read the docs page several times but....some concrete examples would help. Mostly what I want is all my door sensors as triggers, and the body of the notify message to contain the sensor name and new state....at least I think templating is what I want for this?
node-red was suggested in automations but that doesnt really seem like the way i want to go, if templating or something similar would let me do that, i'd rather do that
that probably is a good use of templates yeah
in an automation, you could use {{ trigger.to_state.name }} for the name, and {{ trigger.to_state.state }} for the state
well, that's a good start. do you have pointers to something... a little more verbose than the template doc with more examples?
not really besides others examples
hm. ok...well i'll give starting off with that a shot
this is what you've seen? "Automation Templating - Home Assistant" https://www.home-assistant.io/docs/automation/templating/
yeah. which...has one okayish example towards the bottom...but then goes on that you should follow these 4 rules that are not clicking and also dont seem represented in the examples
follow up question: how do I abstract away open and closed to words? state 23 is closed and state 22 is open...at least so far as I've ever figured out with these zwave sensors
for your notification, or for some logic to see which state they're in?
for the notification. I'm not sure your to_state.state will be helpful but about to test
that same page goes on to talk about the trigger object btw, which is the important part here
trigger being the entity which triggered the automation, to_state being a representation of its state after whatever change made it trigger, and state being the actual state
to_state.name would be the name of the entity
those are in contrast to from_state, which would be the state of the trigger entity before the automation was triggered
is there a way to regexp/clean up strings? for instance this sensor ends up being called FrontDoor_accessControl when i grab the name from {{ trigger.to_state.name }}
each zwave sensor has like...5 things within it for whatever reason. tamper switch, access controll switch, battery level...and other things i've forgotten since i added them
sure
entities
each device can have multiple entities
my aqara zigbee temp/humidity sensor device, for example, has a sensor entity for each of temp/humidity/pressure/battery
hm ok the entities are different than i remembered...or did I hide some. for some reason i remembered it conflicting if i removed the accessControl from the sensor names
ah, i hid the overall sensor that contains the entities from the entities view. so...i'd rename FrontDoor to FrontDoorSensor, and then FrontDoor_AccessControl to just FrontDoor is how you'd solve this issue?
well. i mean, that's the sort of approach you're suggseting at least
I'm just saying it'd be faster, easier, and more consistent, to just rename the entity, instead of trying to manipulate the string inside your template
probably you're going to want to use whichever entity actually changes state whenever the sensor is triggered
it's state will probably show as either "open" or "closed"
right right, that part seems to work ok, just tested a door
maybe "on"/"off"
now i need to figure out how to change "22" and "23" to "opened" and "closed"
yeah, so name that entity whatever you want to show in your notification, and use it to trigger your automation
the state of your sensor is 22/23?
I'm not familiar with zwave, tbf
yeah. 22 means open, and 23 means closed...for whatever reason
hmm, well
ยฏ_(ใ)_/ยฏ
but this: message: '{{ trigger.to_state.name }} {{ trigger.to_state.state }}' title: FrontDoor Open now yeilds "frontdoor 22"
{{ map.get(states("sensor.whatever"), "unknown") }}```
{% if trigger.to_state.state == '22' %}
open
{% else if trigger.to_state.state == '23' %}
closed
{% endif %}
haha alright then I guess not
@dreamy sinew that works too I guess
seemed a bit overkill for just two cases
That covers 3 though
but mine didn't work so ๐คท๐ผโโ๏ธ lol
er...so i'm editing this in the automation ui right now...does that go in the action as yaml or somewhere else
ah yeah, good call
Eh, yours would work just isn't yaml as it is
And states are strings
good catch as well
@inner mesa might you take a look at my thing in #integrations-archived and see if you can see where I'm wrong?
so...like this?
'{% set map = {"22": "open", "23": "closed"} %}'
data:
message: '{{ trigger.to_state.name }} {{ map.get(states("trigger.to_state.state"), "unknown") }}'
title: FrontDoor Open
service: notify.notify
? or do i put that first line...somewhere else?
(ignore the title line for now, just working on the message line)
that first line has to go into the message as well
ah ok
@blazing burrow I think youโre missing quotes around the template, meaning that youโre not passing properly formatted JSON
You may need to assign the template to a variable first to get the quotes right
payload: '{ "psave": {{ states("input_number.wled_preset") | int }} }'
I feel like that's right?
or maybe the quotes inside states messing it up?
I know I've got something wrong...
it should be an integer there, as the value of psave
I can get it working via curl with postman
just {"psave":16} or whatever id
I just like the whitespace in yaml, easier to read later
hm. the set map thing seems to have broken it
{{ states("input_number.wled_preset") | int }} shows me an integer in the editor (whichever my input_number is on)
no quotes, but it also doesn't show quotes around strings lol
curl -L -X POST 'http://192.168.1.189/json/state' -H 'Content-Type: application/json' --data-raw '{"psave": 16}' this works from postman
What I tried to put in was this: and save...but after restarting hass and reloading the page, it has something very different saved in there so...uh, maybe i made a syntax error
data:
message:
'{% set map = {"22": "open", "23": "closed"} %}'
'{{ trigger.to_state.name }} {{ map.get(states("trigger.to_state.state"), "unknown") }}'
title: '{{ trigger.to_state.name }}'
service: notify.notify
do this
message: >
then, on the next line, indented two more spaces
put the three template lines, without the surrounding ' '
also make sure the third line is indented with the rest
oh wait, is it two lines? sorry, mobile lol
ok, on the second line remove the }} {{ in the middle
lemme try
data:
message: >
{% set map = {"22": "open", "23": "closed"} %}
{{ trigger.to_state.name map.get(states("trigger.to_state.state"), "unknown") }}
title: '{{ trigger.to_state.name }}'
service: notify.notify
?
data:
message: >
{% set map = {"22": "open", "23": "closed"} %}
{{ trigger.to_state.name + map.get(states("trigger.to_state.state"), "unknown") }}
title: '{{ trigger.to_state.name }}'
service: notify.notify
I think this
that second line of the message is on the same line as the one after it
ah, a plus. gotcha
you need a + in the middle ๐
add two strings
the > basically says, "up next is a multiline block"
tfw the automation gets disabled by something while testing and you're trying to debug something when it's disabled ๐ค
I use that same sort of thing for converting the selection from an input_select into the selected index instead:
preset: >
{% set idx = {"Juggle": 1, "Rainbow Twinkle": 2, "Rainbow": 3, "Night Rider": 4,
"Fire": 5, "Rainbow Juggle": 6, "Drywet": 7, "Drywet Juggle": 8,
"Magripple": 9, "Preset 10": 10, "Preset 11": 11, "Preset 12": 12,
"Preset 13": 13, "Preset 14": 14, "Preset 15": 15, "Preset 16": 16} %}
{{ idx[states('input_select.wled_preset')] }}
a bit different, but similar idea
ok, i get messages again, but the template map thing still isn't working quite right yet. I get "FrontDoorunknown"
@dreamy sinew I had been looking for a more efficient way, like a zip(a,b) -> {a[0]: b[0], ... a[n]: b[n]} method... but doesn't seem to be any way in jinja?
that means the state from the template isn't either 22 or 23
the map.get(..., "unknown")
means if it doesn't find something in the map, it gives you unknown
right, but this is what triggered the whole automation:
platform: state
entity_id:
- sensor.door_house_front_access_control
- sensor.door_garage_roll_access_control
from: '23'
to: '22'
so...seems like an issue with the map more than the states being wrong coming into the automation
what entities does your device give you, specifically?
uh, can you rephrase that? based on the trigger i know the state has to be from 23 to 22, so i'm not certain what the entities are...mattering?
ok, open up that device, and you said there's multiple entities there
what are they, and what are their current states?
the zwave device has 7 entities
yes, though the data is nowhere near as helpful as that pic heh
but let me pull that up on my phone and go open the door, because afaik, only teh 23 changes
can you show?
yeah only the 23 changes when I open the door...sec
..just as soon as i find a place to paste a picture
might be a question for #zwave-archived at that point... OR try removing the quotes around "22"/"23" in your map
imgur doesnt seem to like my adblock
just to see
would that make them integers isntead of strings or something?
yes
one simple question
"value_template: >-" what are '>' and '-' for at the beginning of a template?
that is basically, "up next is a multiline block"
I sent an example above
a couple
i thought for that I would be just ">"
what 's the difference between > and >-
lol
@blazing burrow question, am i passing the trigger.to_state.state correctly to the map? That's not just passing the literal string to it right...actually the contents of the variable?
{{ map.get(states("trigger.to_state.state"),"unknown") }}
๐คฆโโ๏ธ well that'd explain it lol
you COULD use
map.get(states("sensor.your_entity_id"))
but trigger.to_state.state is technically better
the former would be the CURRENT state
oh no that's miles better, the goal is to have many triggers
the latter would be the state that triggered the automation
still getting unknown however...
the latter is what you want for many triggers
go into the developer tools template tester and paste in your template
the lines after the >
I just replace the for loop at the bottom with my test code, or the whole thing?
or whatever
nothing in there is sacred
just scratch space for you to test
also the states tab can help you evaluate states at any given moment
then i'd have to know how to define trigger it seems
hmmm. result: closed
so right now on my phone i see:
FrontDoor unknown 22
generated from
message: >
{% set map = {'22': 'opened', '23': 'closed'} %} {{ trigger.to_state.name +"
"+ map.get(states(trigger.to_state.state),"unknown")+"
"+trigger.to_state.state }}
I have some binary sensors that I'd like to use as device_trackers. How do I map them to this purpose?
@blazing burrow derp. ok it works. i missed yet another typo on the trigger passing to the map ๐คฆ
@blazing burrow thanks for all the help
ok one final question, is it possible to have multiple "from" states and "to" states in the trigger?
i.e. could i make it so that this is triggered from 22 -> 23 and 23 -> 22 somehow?
platform: state
entity_id:
- sensor.door_house_front_access_control
- sensor.door_garage_roll_access_control
from: '23'
to: '22'
you can leave off the from and to, and it'll trigger on any state
I suppose that would work. i imagine it's not going to trigger on 22 -> 22 or 23 -> 23?
(i.e. just sitting there)
you'd then use conditions to figure if it's the change you're interested in
or chooses in the actions, to make different decisions
well...it seems to work as desired at the moment, so yay!
now I can start to slim down all my...idk 20 static rules (10 sensors, an open and close rule per sensor) to like...just a few
so, huzzah, that will accomplish everything I set out to do today. big thanks again @blazing burrow
yeah man ๐ I need to do the same lol
anyways, I'm probably going dark for the night lol but glad we got you figured out ๐๐
Attention, it can trigger if 22-> 22 or 23 -> 23. If you donโt set the from and to, it will also trigger if an attribute changes.
I know in the past, you would use entity_id for sensor templates, but I'm now seeing this message in my logs The 'entity_id' option is deprecated, please remove it from your configuration, does this mean that the option is entirely unneeded now or is there a replacement option? Do sensors now update automatically?
it is unnecessary now
they always updated automatically based on the entities that it could detect, but they now do a better job of it
Thanks
you can plug a template into
-> Templates and it will tell you what it's listening for on the right side
How do I escape None? I.e. This recently stopped working
{% if 1==1 %}
None
{% endif %}
it's probably returning the native type now. How is it not working?
I just want it showing None as the sensor value. Right now, it shows unknown instead.
Although I just changed it to Never instead since None was giving me problems.
But for future reference
I would like it as just to read None as just a string.
if putting it in quotes doesn't work, you may be able to add "|string" to it
results of tests in
-> Templates are confusing
I would have expected the native type to be converted to a string for the sensor value, but could be a corner case
Isn't None in python like null?
Yeah, don't use 'None', it'll always be cast to None.
The native type stuff is cool but there are edge cases like that which no longer work.
Yes it is, and thats precisely why its not working. I was looking for a way to hopefully escape it.
You don't. You change the name to something else that isn't a reserved word in Python.
Even if you convert it to a string it will still cast to None?
The casting is done after the template is evaluated.
I wasn't sure what to make of my tests in the dev tools
The template will, big. And then it'll be cast to None.
if I put "None", it tells me it's a string
Yeah but the string includes the quotes
The Dev Tools tell you what the template is doing. They don't tell you what HA does next.
Seriously. You've seen for yourself that it doesn't work and you're still questioning me?
wait, don't tell me!
Oh...
no spoilers
Yeah I did rename it to something else. Just weird that it used to work.
Not weird considering they changed how typing works
It used to work because HA didn't attempt to cast to native types after a template was evaluated. It does now.
Anyways, I am using some template that I wrote way back like 2 years ago. And haven't gotten around to changing it ever since
HA's changed a lot since then
Evaluate template > attempt to cast to native type > pass value to integration > integration may cast again (like string to number if a number is expected)
The second step is new and there's currently no avoiding it.
Bugs have been reported for cases just like yours. Time will tell if the devs find a workaround for people.
No its really unnecessary to fix
It's not though. What if you need to template something to generate a command and the command your integration expects is 'None'.
There's a strong argument to find a way to allow people to be in control of what their templates return... but it'll need to be done in a way that doesn't undo the amazing native type stuff.
But I'm not a Python dev and I barely understand HA code... so I'll leave that to the experts.
Hmm tbh though, with all the changes that HA has made over the years, templates have become less and less of a necessity.
For me at least.
Back then, it was practically required to do just about anything
Templates are almost essential to many people. The out-of-the-box solutions don't work for everything, hence the large number of integrations that allow templates.
Yeah its definitely not obsolete, just not nearly as necessary. I still use them for setting timers for my sprinklers, but people can get away with the same functionality now using automations
Maybe not as pretty but it totally works
Guys, I created a template sensor and used "is_state" instead of "states.xxx.xxx" to avoid an unknown state at start up https://www.home-assistant.io/integrations/template/#startup
But the sensor still gets an unknown state for few seconds at startup
any ideias why this is happening ?
that's not what the difference is - if it's unknown, it's unknown
it prevents errors from dereferencing something that doesn't yet exist
"For example, you would replace {{ states.cover.source.state == 'open' }} with this equivalent that returns true/false and never gives an unknown result:
{{ is_state('switch.source', 'on') }}"
that's what the doc says
That will return true or false
Thatโs doesnโt mean that the sensor canโt be unknown
{% if is_state('sun.sun', 'above_horizon') %} above_horizon {% else %} below_horizon {% endif %}
I was assuming the any other value different from 'above_horizon' would give me 'below_horizon'
it can return unknown but it won't throw an exception
what do you mean?
{{ 'above_horizon' if is_state('sun.sun', 'above_hroizon') else 'below_horizon' }}
if you try states.domain.entity for something that doesn't exist it'll throw an exception
say if the template starts up before the entity is ready
what throw an exception means? (sorry , I don't know)
a crash
thank you
@inner mesa @rugged laurel you guys had helped me with this before, but i've just cracked it!
{% set ns = namespace(zipped={}, options=['a', 'b', 'c']) %}
{
{% for i in (range(1, ns.options|length + 1) | list) %}
{% set key = ns.options[i-1] %}
{% set value = i %}
{{ key }}:{{ value }},
{% endfor %}
}
hmm
@blazing burrow posted a code wall, it is moved here --> https://paste.ubuntu.com/p/7fbPgJqhby/
for i in (range(0, ns.options|length)|list)
ns.options[i]
{
a:1,
b:2,
c:3,
}
to remove all that extra whitespace change your {% %} to {%- -%}
oooooh
also, if you're wanting a proper object/dict there, you need to wrap your keys in quotes
{{ '{}'.format(key) }}:{{ value }}
might work
either that or change the ' to "
{{ '{}'.format(key) }}:{{ value }}{{',' if not loop.last else '' }} iirc
holy crap
that totally seems to have done it
i don't even need the namespace
{
{%- for i in (range(1, ['a', 'b', 'c'] | length + 1) | list) -%}
"{{ ns.options[i-1] }}":{{ i }}{{ ',' if not loop.last else '' }}
{% endfor %}
}
i'm starting at 1 for a reason ๐
eh, different way to do it then
{%- for i in (range(0, ['a', 'b', 'c'] | length) | list) -%}
"{{ ns.options[i] }}":{{ i+1 }}{{ ',' if not loop.last else '' }}
{% endfor %}
}```
less mucking with the index that way
ah, got another snag
i want to use that in place of something like this:
value_template: >
{% set idx = {"Juggle": 1,
"Rainbow Twinkle": 2,
"Rainbow": 3,
"Night Rider": 4,
"Fire": 5,
"Rainbow Juggle": 6,
"Drywet": 7,
"Drywet Juggle": 8,
"Magripple": 9,
"RGB": 13,
"Ocean": 16} %}
{{ idx[states('input_select.wled_preset')] }}
to "generate" the map for me
non-consecutive indices are not required
but i basically need to replace the set idx block
oh, might not work that way then
ah yeah, i thought i'd cracked it lol
well this sure does look nice:
{% set ns = namespace(zipped={}, options=['a', 'b', 'c']) %}
{ {%- for i in (range(1, ns.options | length + 1) | list) -%} "{{ ns.options[i-1] }}":{{ i }}{{ ', ' if not loop.last else '' }}{% endfor %}}
{"a":1, "b":2, "c":3}
yeah, its valid yaml but it might not be usable if its a middle step
i've got an idea
.update() is locked out due to the jinja env setting
this works perfectly:
sensor:
- platform: template
sensors:
wled_preset:
friendly_name: WLED Preset
icon_template: mdi:heart-outline
value_template: >
{{ state_attr('sensor.wled_preset', 'map')[states('input_select.wled_preset')] }}
attribute_templates:
map: >
{% set ns = namespace(zipped={}, options=state_attr('input_select.wled_preset', 'options')) %}
{ {%- for i in (range(1, ns.options | length + 1) | list) -%} "{{ ns.options[i-1] }}":{{ i }}{{ ', ' if not loop.last else '' }}{% endfor %}}
hmm, ok
state of sensor.wled_preset is the integer index of the selected value of input_select.wled_preset
sweet, now I've even figured out how to make the map from wleds presets.json, so it can load the correct names and indices into HA
beauty
YES, works live when I add new presets and stuff
now I can just update MY input select, and it'll be perfect
Why using a namespace here?
{% set options = state_attr('input_select.wled_preset', 'options') %}
{ {%- for i in (range(1, options | length + 1) | list) -%} "{{ options[i-1] }}":{{ i }}{{ ', ' if not loop.last else '' }}{% endfor %} }
My attempt at storing state so far - not super successful in that the values don't seem to be read (returning "unknown") and that value seems to be written to all input_text fields ๐ Any glaring mistakes / suggestions?
alias: Store Settings
variables:
configuration_id: input_text.stored_state_1
lights: light.test_light
sequence:
- service: input_text.set_value
data:
entity_id: '{{ configuration_id }}'
value: '{{ lights.attributes }}'
mode: single```
working on an update to a binary door sensor that will retain the states. i have created the following https://pastebin.com/raw/91VTKEqe trying to read off of this mqtt json string {"time":"2020-12-12 20:16:02","model":"Honeywell-Security","id":860713,"channel":10,"event":160,"state":"open","alarm":10,"tamper":0,"battery_ok":1,"heartbeat":0} can someone give this a sanity check, i feel like im missing something but its not obvious to me
Im guessing i am in the roughly right channel, so here goes.
ive just added and flashed some ex-tuya Gosund energy moniroting plugs with Tasmota. Added to HA, I can see the watts used etc.
What I would like to do is create a mathematical entity which takes the amount of energy used x cost per unit and returns a total cost in ยฃ for the daily usage. I can do that in excel, but can it be done in HA ?
There are #integrations-archived that do stuff like that.
Well you start by looking out in the #integrations-archived channel and following the links in the topic there.
How in a template do I get the length of time a state was before the current template?
The logs do not appear on the state object.
how to get the value of the triggerd sensor
?
is there something like triggerd.sensor.state ?
You can get the current state of a sensor
but i want to know something about its history
my sensor is noisy
@fossil hearth states('<your.sensor>') should work for the current state
in an automation trigger.to_state and trigger.from_state are both things
should be more of an explanation in the template docs
Become a real Jinja2 Ninja! Don't worry my Genin, we are here to help! You can find the docs at https://www.home-assistant.io/docs/automation/templating/ - and don't forget rule #1! Please use https://www.hastebin.com/ or https://paste.ubuntu.com/ to share code or logs
@dreamy sinew i get that but the sensor jumps back and forth a bunch.
so just trying to maybe get a count of how many switches occursed in some time grame
kinda like I can see in the history of the sensor
@dreamy sinew that does not tell me how/if I can use it in a template.... I see the history in dev tools so it is enabled. Is there a way to run a query in a template?
ooo let me look into that
That one
ah
That closer to what you want?
Looks like it supports some templating
that is for the config of it
not something i could use in an automation config. At least these examples.
but let me enable these and maybe I get access within the templates!
thanks for the lead!
I'm trying to count how many of my steam sensors are "online"
I've found a few threads that show how to count all sensors or all "on" binary_sensors but can't quite find how to find count sensor.steam*
Closest I've got so far is:
{{ states.sensor
| selectattr('state', 'eq', 'Online')
| list
| count
}}
but this shows all other sensors that are Online too, not just my steam sensors
is there a way to narrow it down to just the steam sensors?
ok I got it for anyone interested. I a made a group with all my sensors in and used the following:
{{ states | selectattr('entity_id','in',state_attr('group.steam_friends','entity_id')) | selectattr('state','eq','online') | list | count }}
I feel like some variation on this would work without you having to create groups. I just can't get it to return the entity ID's at the end ๐คฆโโ๏ธ
{{ states | map(attribute="entity_id") | map('regex_search','switch\.bedroom.*') | select('true') | list }}
I get a list of booleans at the end instead of a list of names ๐ฆ
Oh... but you just want a count anyway...
{{ states | map(attribute="entity_id") | map('regex_search','switch\.bedroom.*') | select('true') | list | count }}
Tweak the regex as needed.
And if you don't want it to evaluate on every state change, narrow it down to states.sensor like in your version, @peak juniper
brilliant - thanks @ivory delta
No problem. It was a fun learning exercise for me. I need more practise with templates ๐
Hi all. I have a temperature sensor which always runs a little hot. If I want to drop it by say 7 degrees, what is the format for that if its current value template is:
value_template: '{{ value_json.temperature | round(1) }}' ?
Anyone know off-hand of a way to convert a timestamp to "minutes since timestamp was set"?
I have a ton of sensors/templates/automations that depend on the old Uptime sensor implementation, which just gave the number of minutes since HA was last restarted, so I need to emulate that prior to upgrading in order to keep everything from breaking the second I update.
Previously, it was just straight up number of minutes (which is what I need)
Like, my HA instance currently reports an uptime to "2136" minutes
After updating, HA will just timestamp when it started, and leave it at that. I still need to be able to find the number of minutes since the date/time in the timestamp, though
ok, you'll have to implement the uptime integration and perform this calc: "{{ (as_timestamp(now()) - as_timestamp(states('sensor.uptime'))) / 60 | round(0) }}"
I'll give that a test now ๐
Thankfully I can test this before the update by using a helper to store a static timestamp
Well, that works, but round(0) isn't rounding the number to 0 decimal places.
what version of HA are you on?
Getting a full 12 decimal places after the number
0.118.5
Last before the update that'll break the uptime sensor
Fixed it
{{ ((as_timestamp(now()) - as_timestamp(states('input_datetime.last_start'))) / 60) | round(0) }}
"{{ ((as_timestamp(now()) - as_timestamp(states('sensor.uptime'))) / 60) | round(0) }}"
Needed the extra parenthesis
This'll do the trick for now. I have a lot of stuff that has a "uptime > 3 minutes" condition built-in to keep things from triggering incorrectly while HA starts up.
Hmm...ok, so everything is working, but excluding the new "sensor.uptime_minutes" sensor from history/recorder doesn't work
Still recording the state every 60 seconds
if it's in the database you'll have to wait 24 hours before it's removed
Oh, it was excluded from the get-go
then you have a typo
Double-checked... nope...
Sensor entity name: sensor.uptime_minutes
Exclusion:
exclude:
entities:
- sensor.uptime_minutes
recorder:
exclude:
entities:
- sensor.uptime_minutes```
Still recording ๐
do you have duplicate recorder or history sections?
Restarting HA, one moment...
Nope, just those
There are other excluded entities in the lists, but I truncated them for the sake of brevity. The other exclusions appear to work.
not sure what to tell you. There's nothing special with that sensor.
Yeah, it's just a template sensor I created
if other things are excluded, then it should be as well is what I'm trying to say.
Yeah, not sure. All other entities in the list of exclusions aren't recording history, but this one still is..
you're not going to have an integration like that only work on a 'few' entities
what's your definition of recording history?
I click the entity, it shows a line graph that's updating every 60 seconds
Other excluded entities just show "No state history found."
so is it climbing or not?
it's climbing
Not sure what to tell you then
recorder handles the recording
history handles the display
Well, it should be excluded from both, but it's not ๐
Guess I'll update, see if it clears up, and if not start looking into bug-hunting
then it's one of the following issues: Spelling error (which you claim its not), bad configuration (which you claim its not)
I mean, i copy-pasted directly from the entity / config
So if it were a spelling error, it'd be there
paste bin the sensor config