#templates-archived
1 messages · Page 86 of 1
ok changed it to custom_components.rest.sensor: debug
what the heck, still nothing in the logs 2020-02-21 12:42:28 DEBUG (SyncWorker_1) [homeassistant.components.rest.sensor] Updating from http://192.168.2.253:1400/DeviceProperties/Control 2020-02-21 12:42:29 DEBUG (SyncWorker_5) [homeassistant.components.rest.sensor] Updating from http://192.168.2.253:1400/DeviceProperties/Control 2020-02-21 12:42:29 WARNING (SyncWorker_5) [homeassistant.components.rest.sensor] JSON result was not a dictionary or list with 0th element a dictionary 2020-02-21 12:43:00 DEBUG (SyncWorker_16) [homeassistant.components.rest.sensor] Updating from http://192.168.2.253:1400/DeviceProperties/Control 2020-02-21 12:43:00 WARNING (SyncWorker_16) [homeassistant.components.rest.sensor] JSON result was not a dictionary or list with 0th element a dictionary 2020-02-21 12:43:31 DEBUG (SyncWorker_3) [homeassistant.components.rest.sensor] Updating from http://192.168.2.253:1400/DeviceProperties/Control 2020-02-21 12:43:31 WARNING (SyncWorker_3) [homeassistant.components.rest.sensor] JSON result was not a dictionary or list with 0th element a dictionary
have both custom_components.rest.sensor: debug custom_components.sensor.rest: debug
it is still loading homeassistant.components.rest.sensor and not your local custom_component
yeah
let me copy all the files to the rest folder
2020-02-21 12:49:37 DEBUG (SyncWorker_6) [custom_components.rest.sensor] update 2: <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"><s:Body><u:GetZoneInfoResponse xmlns:u="urn:schemas-upnp-org:service:DeviceProperties:1"><SerialNumber>5C-AA-FD-31-EA-80:1</SerialNumber><SoftwareVersion>54.2-72160</SoftwareVersion><DisplaySoftwareVersion>10.6.1</DisplaySoftwareVersion><HardwareVersion>1.14.1.11-1</HardwareVersion><IPAddress>192.168.2.253</IPAddress><MACAddress>5C:AA:FD:31:EA:80</MACAddress><CopyrightInfo>© 2003-2019, Sonos, Inc. All rights reserved.</CopyrightInfo><ExtraInfo></ExtraInfo><HTAudioIn>21</HTAudioIn><Flags>0</Flags></u:GetZoneInfoResponse></s:Body></s:Envelope>
2020-02-21 12:49:37 DEBUG (SyncWorker_6) [custom_components.rest.sensor] update 3: {"s:Envelope": {"@xmlns:s": "http://schemas.xmlsoap.org/soap/envelope/", "@s:encodingStyle": "http://schemas.xmlsoap.org/soap/encoding/", "s:Body": {"u:GetZoneInfoResponse": {"@xmlns:u": "urn:schemas-upnp-org:service:DeviceProperties:1", "SerialNumber": "5C-AA-FD-31-EA-80:1", "SoftwareVersion": "54.2-72160", "DisplaySoftwareVersion": "10.6.1", "HardwareVersion": "1.14.1.11-1", "IPAddress": "192.168.2.253", "MACAddress": "5C:AA:FD:31:EA:80", "CopyrightInfo": "\u00a9 2003-2019, Sonos, Inc. All rights reserved.", "ExtraInfo": null, "HTAudioIn": "21", "Flags": "0"}}}}
2020-02-21 12:49:37 WARNING (SyncWorker_6) [custom_components.rest.sensor] JSON result was not a dictionary or list with 0th element a dictionary```
looking at last line - warning
well, that is json_attributes_path: '$.response.body.getzoneinforesponse' value_template: '{{ ok }}'
some of those need to be changd
it is not correctly specified
yes
value_template: '{{ value["s:Envelope"]["s:Body"]["u:GetZoneInfoResponse"]["HTAudioIn"] }}'?
may be
no error, but the sensor is not getting the value
- platform: rest
method: POST
resource: http://192.168.2.253:1400/DeviceProperties/Control
name: Sonos Stereo
headers:
SOAPACTION: "urn:schemas-upnp-org:service:DeviceProperties:1#GetZoneInfo"
Content-Type: text/xml; charset="utf-8"
payload: '<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"><s:Body><u:GetZoneInfo xmlns:u="urn:schemas-upnp-org:service:DeviceProperties:1"></u:GetZoneInfo></s:Body></s:Envelope>'
value_template: '{{ value["s:Envelope"]["s:Body"]["u:GetZoneInfoResponse"]["HTAudioIn"] }}'```
unknown
ok it should be value_json
now it works
yes
man, we definitely need debug there. There is no way for anyone to figure it out otherwise
thanks @queen meteor
nice!
lol - you are welcome! glad you got it working!
well after lot of help 🙂
I'm sure it will be a big breaking change for many - that's what I am afraid of... some of them will have no clue how to fix it
this is supposed to make stuff easier right?
well, it was 😂
if you are knowledgeable enough
because i've read that janja2 has to_json
that is from string to json, not xml to json
parse_xml ?
if you have json as string, you can convert that string into json object by using that filter. comes in handy when you need to pass json and you only have string at hand
In order to make that work, you should place that xml arsaboo had into a string and then go to json?
nope - it doesn't work that way. xml is still xml. there is no easy conversion.
hmm okay
the new PR converts xml elements into json dictionary, but kind of maintains hierarchy, and you need to know how it is formed, so that you can parse effectively
what arsaboo did is debug print that json, so that he knows exactly how to parse it
@queen meteor Did some more testing on the MQTT. I created a "fake" TestLight and with the same template I was having issues with. And of course it works. The state_topics values are the same of the devices having issues and the TestLight fake device I created. I'm assuming this might be a issue with the device?
possibly - at least that gives you an idea on whats happening with the device
@queen meteor Do you know what group or if you know how to dump a device config that wouldn't exist in the entities since mqtt discovery doesn't appear in there?
@pliant night not so sure - what device is it specifically? You can try posting in #hardware-archived
Hey everybody, I'm having a real braindead moment here, trying to do an is_state on the fan_mode from my climate.radio_thermostat_company_of_america_ct32_thermostat_mode but after 20 minutes, I'm punting my question to the crowd. I can't figure out how to format it!
like... value_template: "{{ is_state('climate.radio_thermostat_company_of_america_ct32_thermostat_mode.fan_mode', 'on low') }}"
a bit, yes
ok - go in there, clear the text, and paste the following and see what it gives```
{{ states('climate.radio_thermostat_company_of_america_ct32_thermostat_mode') }}
Tried that, yes, it's off
there's these sub-attributes for that device
I want to test one of THOSE
I want to test fan_mode
ok - try ```
{{ states.climate.radio_thermostat_company_of_america_ct32_thermostat_mode }}
that should give you a bit more information
ah that barfs up a big string
yup - now, you can access anything and everything you see there using templates.
you just need to know which state/attribute you want to access
I want to pull out fan_mode - Do I need to parse that string ?
can you paste what you saw in there?
<template state climate.radio_thermostat_company_of_america_ct32_thermostat_mode=off; hvac_modes=['heat', 'off', 'heat_cool', 'cool'], min_temp=45, max_temp=95, fan_modes=['On Low', 'Auto Low'], preset_modes=['Cool Econ', 'Heat Econ', 'none'], current_temperature=70, temperature=None, target_temp_high=None, target_temp_low=None, fan_mode=Auto Low, hvac_action=idle, preset_mode=none, node_id=9, value_index=0, value_instance=1, value_id=72057594194165764, fan_action=Idle, friendly_name=Thermostat, supported_features=27 @ 2020-02-21T12:34:30.913380-08:00>
{{ state_attr('climate.radio_thermostat_company_of_america_ct32_thermostat_mode', 'fan_mode') }}
``` should give you fan_mode value
frikkin' syntax, gets me every time
thank you
ah HAH, OK so this is what got it. {{is_state_attr('climate.radio_thermostat_company_of_america_ct32_thermostat_mode', 'fan_mode', 'Auto Low')}}
that attr was critical. Not exactly crystal clear in the docs
man, I'd a been hours at that. Thanks again
@queen meteor sigh.... well i'm so glad my month long pain is done... the answer was delete all the MQTT devices using publish of the a blank template code and publish the same template code after the devices were deleted. I guess this process causes HASS to clean up the object instead of doing updates. Thanks again for the help and totally insane
Just noticed there's a channel specific for templates 😂 So I'm moving my message here
Is there a way to get all the events from the calendar in a template? I want to display the events in a more natural language way, for example: Today is John Doe and Mary Smith's birthday
This is the closest I've got
{% if is_state('calendar.birthdays', 'on') %}
{{ states.calendar.birthdays.attributes.message }}
{% endif %}
Which returns only one event, of course. Will print Jane Doe's birthday
I know calendars integration has an endpoint, like https://github.com/ljmerza/calendar-card/blob/master/src/event.tools.js#L107
🤔
@sterile storm depends on calendar you use. typically you only see the next event.
I'm using Google Calendar in this case
you only get one event at a time.
it is not a limitation on HASS, That's how Google Api works
But how did they manage this call? http://hassio.local:8123/api/calendars/calendar.birthdays?start=2020-02-21T00:00:00Z&end=2020-02-28T00:00:00Z (From the repo I shared)
must be a custom card. I don't see more than one entry in the states tab - I have 3 google calendars
Quick question - what exactly does > and >- mean when calling a template?
so, I think I have it correct, if I want the lights to turn off when a door sensor has been closed for 10 minutes AND there is no movement sensed by the motion sensor for 5 minutes this should work right ? 🤔 https://hastebin.com/tuwukijufa.cs
https://www.home-assistant.io/docs/scripts/conditions/#state-condition if you wanted to do it the easy way
Of course, you need two conditions and two triggers
😄
Yeah, with yours it'll only turn it off if the motion sensor has been off for 5 minutes 10 minutes after the door was closed
Which may be valid, but ... 🤷
I think I've very few automations without them
I moved my whole basement to zigbee2mqtt yesterday
👍
now I just have two rooms left to move 
I do conditions a lot. Since I keep most through state change and check on conditions for filters. is it more inefficient in terms of cpu usage? I haven't notice any increase or decrase in CPU while normal usage - sits at 8% throughout
I only use conditions conditionally
@rare panther using conditions will not increase cpu usage. It is a drop in the ocean.what ticks CPU is when you try to process millions/billions of conditions all at once. Let’s just say we will never get there with home assistant. Not even for Tony Stark.
Cool. Thought so. Since i.use lot of templating the conditions help. I could have used multiple triggers, but in some cases i required AND conditions, multiple triggers operate on OR as i understand
Triggers do, yes, but that's why you have conditions 😉
I'd also expect that simple conditions will be less intensive than a poorly written template
Yes. Triggers are OR, conditions by default are AND. You can have conditional trigger using templates, conditions in conditions, and conditions in action part of automations.
On one condition.
Yep. when I started this Automation stuff, the realization of the power of conditions ushered me the path of right conditions 🙂
I am just drunk at this point. Hopefully nothing back home gets awkwardly triggered with my condition 🙂
No CUI allowed here. (Coding Under Influence) - it only means we have to support more 😛
Most I do is CUI 🤔
No wonder! 😎
@buoyant pine technically you can have as many conditions as you want in action part of automations. The moment first condition fails, rest is ignored 😊
Oh I was just making a dumb joke lol
I am trying to do something very basic. I have a sensor that has a time (e.g., "07:15") and I want to convert it to a datetime object of that time today.
For example, I tried: {{ strptime("07:15", '%H:%M').timestamp() }}, which returns Unknown error rendering template
Or
{% set t_alarm = now().strftime("%Y-%m-%d") + " " + states("sensor.ten_minutes_before_alarm") %}
{% set t_alarm = as_timestamp(t_alarm) | timestamp_local %}
{{ as_timestamp(t_alarm) }}
(where t_alarm is that "07:15" string.)
There as_timestamp(t_alarm) seems 600 seconds off from the actual time for some reason.
Don't mix " & '
Somehow that doesn't work for me...
works on my machine 🤣
Been trying this for an hour 😛
It seems like strptime returns a str in my case, and not for you.
@weary jasper, which HA version are you on?
the best
103.5
I'm on 12h old dev branch, works there
I am on 0.105.5...
does a simple {{ now() }} work
Yes
is the backend running?
Yes, also
give up
I am restarting, maybe that helps
Could it be a processor architecture thing? Maybe ARM can't count before timestamp 0 (1970-01-01)?
i will try on my fish tank server its a pie but a really old version of ha ....60 i think
Oh, yeah, I have another Pi on which it also doesn't work.
no go on pi
That is super strange...
It must be the session issue. When the session is timed out, it won’t work. Refresh the page to make sure you are still connected
Would someone be willing to help me with a template? I am "simply" trying to create a button that will change my theme to a random one of the theme I have. I have this script:
alias: Theme Set2
sequence:
- data:
name: '{{ ["Amoled - MOD", "Amoled - Teal", "Amoled - Blue", "Amoled - Green",
"Light - Orange", "Light - Green", "Gray & Green", "default"] | random }}'
service: frontend.set_theme```
But get an error that says Theme {{ ["Amoled - MOD", "Amoled - Teal", "Amoled - Blue", "Amoled - Green", "Light - Orange", "Light - Green", "Gray & Green", "default"] | random }} is not defined.
@meager orchid use data_template instead of data.
@queen meteor that worked - but I guess I have another problem (probably more suited for the #frontend-archived folks)...it's only applying the random theme to the cards, rather than the whole UI - any idea why?
nm, I had to manually set the theme to backend-selected, and it works perfectly - thanks!
Trying to do a simple new sensor using a template, but it's value is 0. I used another sensor as a starting point (for converting km to miles). Its probably the math piece being in the wrong syntax
- platform: template
sensors:
boiler_cost:
friendly_name: Boiler Cost £/day
unit_of_measurement: £
value_template: "{{ states('sensor.boiler_todays_power')|int*0.24 }}"
@charred badge test the template in the template editor...that should help you see what you need to adjust
instead of int maybe try float?
i thought i could just multiply my senosr.boiler_todays_power x 0.24 to get the cost
e.g 0.66 x 0.24
yea use float instead of int
ah ha! Float perfect
when you use int 0.66 converts to 0
thank you, ah didnt realise that
because integers are whole numbers only
You can round anything using a hammer
This seems to do the trick {{ (states('sensor.boiler_todays_power')|float*0.1838)|round(2) }}
Is it possible to use some kind of "entity template"? at the moment I 've 4 devices which three sensors different sensors. I'm getting the data via scrape. Which means that I need 4*3=12 scrape settings in the configuration.yml.
I would like to create a template for the device with 3 sensors and in the configuration.yml just 4 devices with different IP+Names.
not currently possible
okay thanks 🙂
Hi all, struggling with something if anyone can help? I am trying to create a template sensor to convert km into miles. I can get the sensor to display but the division doesn't work as intended. The result it gives is km divided by 2 (i.e half) rather than 1.609 as per my code. I just can't see what I cam doing wring here! The sensor code is:
milesleft:
friendly_name: "Range"
unit_of_measurement: 'miles'
value_template: "{{ states('sensor.420d_remaining_range_total')|float/1.609 |round}}"
round it to 2 decimals.
so round(2) at teh end?
yes, that should work. Test in template editor first
Cheers, I shall test it now
Ok that works well apart from the fact I have my miles to about 15dp now BUT it is now the correct figure 🙂 Thanks for the assistance on this
round(2) should work in the template sensor. See example https://github.com/arsaboo/homeassistant-config/blob/master/sensor.yaml#L459
I'll take a look at this this evening, should get back to work now. after my lunchtime tinkering with my setup:) round(1) is giving me 3 dp at the moment but I'm sure I'm not far off now. Thanks for the assitance
this:
{{ states('sensor.420d_remaining_range_total')|float/1.609 | round(2) }}
``` will only round the 1.609 to two places. you need to do this:
{{ (states('sensor.420d_remaining_range_total')|float/1.609) | round(2) }}
Cheers, staring at too many brackets, that makes total sense now!
Struggling to get a good icon for that template sensor now. I'm doing:milesleft:
friendly_name: "Range"
unit_of_measurement: 'miles'
value_template: "{{ (states('sensor.420d_remaining_range_total')|float/1.609) | round(0) }}"
icon_template: mdi:map-marker-distance
I did manage to get a battery icon up at some point but I can't get this one or milometer to work at all. I suspect I am being thoroughly dense again 🙂
that is not a template. You need to provide an icon_template or use customize to change the icon
I tried customize which seemed to work for a while. I see what you mean though I'm using the format from a straight sensor there. It's been a long day! Knew I was being stupid! Cheers and sorry for being so dense
Missing the mdi: from customize - doh! Thanks again
Hey all. Is the output on this page something that templates could help extract different values from?
Like if I just wanted the "EXIT CLOSED TO COUZENS" part?
Which is dynamically generated, so if you see this message later, it may be different.
Basically I want the part between <div class='dmsMessage'> and the first </div>.
regex is a thing
anyone knows if its possible to template the stream_source and still_image_url for cameras. I have two template sensors that "builds" the changing stream url. i want to use them as inputs to a camera.
- platform: generic
name: camera_dyn_url_test
stream_source: >-
{{ states("sensor.dyn_stream_test") }}
still_image_url: >-
{{ states("sensor.dyn_snap_test") }}
Possible?
You can’t use templates there unfortunately.
Whoa! No messages in here for more than 26+ hours. 😊
{{ whoa }}
everyone is an expert now, time to go home.
Let’s archive this channel. Looks like everyone is a template expert now. 😊
haha
yup
agreed ✅
We did it Reddit Discord!
How can I commify a number like 2304.45 -> 2,304.45? My current template is:
"{{ (((states('sensor.sw_office_p1_kb') | float) + (states('sensor.sw_office_p2_kb') | float) + (states('sensor.sw_office_p3_kb') | float) + (states('sensor.sw_office_p4_kb') | float) + (states('sensor.sw_office_p5_kb') | float) + (states('sensor.sw_office_p6_kb') | float) + (states('sensor.sw_office_p7_kb') | float) + (states('sensor.sw_office_p8_kb') | float))/1000)|round(3) }}"
Ooh, we got a customer! 😂
haha.... Sorry I guess not everyone is an expert.....
There is no simple way to comity a given number. The filter does not exist in home assistant at the moment.
Alright then, easy answer. hahaha. Thank you. Now you can archive the channel. 😜
@west dome here you go```
{{ "{:,.2f}".format(543921) }}
@queen meteor That worked great! Thank you
if you don't want trailing decimal points, you can use ```
{% set number = 12345 %}
{{ "{:,}".format(number) }}
Hi folks, i have a currentcost power meter, and I’m trying to figure out the best way to deal with its output. It emits an xml stanza every 6 seconds with a Watt reading for 3 phases, as well as a temperature value.
I have a tiny shell script reading each stanza, piping it through xml2json, then uses mosquitto_pub to send it to HA on a particular topic.
My question is: what is the best way to represent this in HA? I am currently extracting each phase into a separate entity using templates, but it feels clunky. Ideally, should it not just be a single entity with multiple attributes?
Pretty easy to just do a MQTT sensor and use the json_attributes_topic to feed the attributes?
I’ve not encountered that before, I’ll have to go google it. Thanks!
You can even auto create the entity from your script. I do the same things with my restic backup scripts
Scratching my head why this don't work...
- platform: template
sensors:
elpris:
friendly_name: "Elpris"
value_template: "{{ states('sensor.electricity_price.attributes.price_level') }}"
The atribute of the entity is:
price_level: VERY_EXPENSIVE
The template sensor is giving me unknown
"{{ state_attr('sensor.electricity_price', 'price_level') }}"
Thanks @buoyant pine
In the past i have used .attributes in the template.
Has something changed?
That's if you're accessing the state object directly like states.domain.object_id.attributes.whatever @thorny snow
io ti sento
I have a sensor that returns a filename :
```
{{ states("sensor.chf50_gv_lastfile") }}
Event20200227142438001.Avi
What string manipulations are available to help me convert the name into a date & time?
In the above example, the date & time would be 2020/02/27 14:24:38
well... {{ states.sensor.chf50_gv_lastfile.state[5:19] }} returns 20200227144437.
I'm close bois !
But now what... ?
strptime(states.sensor.chf50_gv_lastfile.state[5:19], '%Y%m%d%H%M%S') %}
embedded_time = {{ datetime_obj }}
``` returns `2020-02-27 14:44:37`
Thanks for all the input & ideas.
I'm trying to work out a template and I'm apparently less of a Jinja Ninja than I expected because I'm not finding what I need.
Here's the setup:
{% set hvacmodes=['auto', 'off', 'cool', 'heat', 'dry', 'fan_only'] %}
{% set hvacmode='cool' %}
I want to return the next item in a list, given one of the existing items.
So if hvacmode='cool', I want to return heat
The list is dynamic, I don't know the contents ahead of time.
rubber ducky debug to the resuce!
{% for mode in hvacmodes %}{% if mode == hvacmode -%}{{ hvacmodes[loop.index] }}{%- endif %}{% endfor %}
just stumbled on this by accident but it works great, jinja lists are zero indexed but loop.index isn't, so it's automatically one greater than the index of the current item being looped over
not as smart as i thought, now i need to loop back around to the beginning...
{% for mode in state_attr("climate.mqtt_hvac", "hvac_modes") %}{% if mode == states("climate.mqtt_hvac") %}{% if loop.last %}{{ state_attr("climate.mqtt_hvac", "hvac_modes")[0] }}{% else %}{{ state_attr("climate.mqtt_hvac", "hvac_modes")[loop.index] }}{% endif %}{% endif %}{% endfor %}
added a check to see if we're on loop.last, if so then go ahead and set the index to 0. now it works!
someone told me the other day how to convert the weird time format from the dark skies alert but I forgot, and now I got my entity filter/markdown card working
it was something like {{ states.sensor.dark_sky_alerts.attributes.time | something }}
I can't figure out the something lol
in the sensor it looks like 'time': 1582876800
so you have unix epoch time and you want to convert it to printable time?
define "normal" time
4:02pm
it's a surprisingly complicated question
let's try some things 😄
{{ 1582876800 | timestamp_local }}
to answer your question... something is timestamp_local
| please_do_it
this is your friend: https://www.home-assistant.io/docs/configuration/templating/
keep it bookmarked, refer to often when templating. in this case... https://www.home-assistant.io/docs/configuration/templating/#time
hmmm looks like I can change the order of the date and time too
you sure can!
time seems like a simple thing but it's preposterously complicated. strftime is available and I'd recommend getting familiar with it: https://strftime.org/
you can print out time in all sorts of ways!
ᕕ( ᐛ )ᕗ
@fossil totem will that last one work in a template though?
@velvet gate I mentioned earlier. That is a Unix time stamp, and you can convert to date time format easily using strftime
hmmm
you mean strptime(string, format)?
or this https://strftime.org/
lack of examples make this hard for non programmers lol
it's actually a python thing, not jina, and can only be used a some special cases (now().strftime('format'))
that how it seemed
so that's probably not so helpful to you right this moment 😄
sorry bout that
timestamp_custom might do it
which just implements strftime
yeah I started trying to play with it but I think I have the formatting wrong.
Time: {{ states.sensor.dark_sky_alerts.attributes.time | timestamp_custom(%a, local_time=True) }}
trying to add those % deals
I'm not totally dumb but it does help to have like 1 example of what things are supposed to look like.
put double quotes around your %a
{{ as_timestamp(states.sun.sun.attributes.next_rising)| timestamp_custom("%a") }}
ahhhh
I didn't need the local_time=true
haha
its working now
boom, thank you sir lol
I dunno if anyone else does that but I wanted any dark sky alerts to appear as a card on my dashboard and then vanish when there is no alert.
using markdown, its ugly, but I haven't bothered to look up how to format stuff yet
I rarely use the dashboard, if I keep clicking on the dashboard for everything, it is not really an automation.... is it?
I just like seeing the weather
and I have it show things that are left on, etc.
I'm also not the only one who uses it.
lol
although, all of the automations work fine so its not like lights are ever left on that shouldn't be and stuff.
I was able to get a countdown using as_timestamp in seconds, which I was them able to get down to fractions of days using templates. Is there a way to break it down to days, hours, minutes, seconds, and have those disappear as they run out?
I want to convert the player list attribute in the new minecraft server component into a comma seperated list of players with the word "and" before the last one, so I can put it through a TTS and it sound right. what's the best way to do that?
When I test {{ state_attr('sensor.minequestria_spigot_server_players_online', 'players_list') }} in template dev panel, it outputs ['MazzoManicotti', 'FocusForte']
This is what I'm working with https://i.imgur.com/wH9oSxQ.png
@oak summit that example is already there as the default code in the template editor
oh I must have overlooked it, I'll have to check that again.
something like this ```
{% for state in state_attr('sensor.minequestria_spigot_server_players_online', 'players_list') -%}
{%- if loop.first %}The {% elif loop.last %} and the {% else %}, the {% endif -%}
{{ state | lower }}
{%- endfor %}.
thank you!
just updated the code, try again
I am still totally new to templates, so I'm not sure I would have figured that out on my own 😅
lol - no worries!
best way to learn is to play in the template editor - try ```
{% for state in ['MazzoManicotti', 'FocusForte'] -%}
{%- if loop.first %}The {% elif loop.last %} and the {% else %}, the {% endif -%}
{{ state | lower }}
{%- endfor %}.
Yeah, I got it doing what I want now ^_^
@oak summit Template editor was huge in me starting to wrap my head around the template stuff.
Yeah, I understand it enough now to tweak and modify, but building more of the more advanced stuff like for loops, I'm still in a bit above my head lol
{% for state in state_attr('sensor.minequestria_spigot_server_players_online', 'players_list') -%}
{%- if loop.first %}{% elif loop.last %}, and {% else %}, {% endif -%}
{{ state | lower }}
{%- endfor %} are online right now.```
that does exactly what I want 😄
{{ state_attr('sensor.minequestria_spigot_server_players_online', 'players_list') | join(", and ") }}
that will give too many "and"s when you have more than 2 entries
And?
if you have ['a', 'b', 'c'], it gives a, and b, and c 🤢
And d ;)
lol
@ancient lynx here is a second to days, hours, minutes, and seconds example: ```
{% set seconds = 641200 %}
{%- set map = {'Week': (seconds / 604800) % 604800,
'Day': (seconds / 86400) % 7,
'Hour': (seconds / 3600) % 24,
'Minute': (seconds / 60) % 60,
'Second': (seconds % 60) } -%}
{%- for item in map if map[item] | int > 0 -%}
{%- if loop.first %}{% elif loop.last %}, and {% else %}, {% endif -%}
{{- map[item]|int }} {{ item -}} {{- 's' if map[item]|int > 1 -}}
{%- endfor -%}
@queen meteor If I want the seconds variable to be set by a sensor, then I can use a template to set that, correct?
yes
How else?
anything goes with 🍺
Cool. Any advantage to that solution vs the one in the forum thread?
it is essentially lifted from forum - and made it better.
Awesome. Thanks for the guidance.
#MTGA @rugged laurel
@queen meteor It broke everything.
Now the value_template doesn't even work. Returns unknown. And days_left returns none.
Template editor gives me Error rendering template: TemplateSyntaxError: expected token ':', got '}'
@ancient lynx you got line # 13 wrong
I tried every variation of that line I could think of, but never returned a valid response.
What's wrong with it?
Putting {{(as_timestamp(state_attr('calendar.2020_fia_formula_one_world_championship_race_calendar', 'start_time')) - as_timestamp(now())) }} in the template editor returns a valid value.
But putting it in line 13 never does.
@queen meteor
try this ```
{%- set seconds = (as_timestamp(state_attr('calendar.2020_fia_formula_one_world_championship_race_calendar', 'start_time')) - as_timestamp(now())) %}
{%- set map = {'Week': (seconds / 604800) % 604800,
'Day': (seconds / 86400) % 7,
'Hour': (seconds / 3600) % 24,
'Minute': (seconds / 60) % 60,
'Second': (seconds % 60) } -%}
{%- for item in map if map[item] | int > 0 -%}
{%- if loop.first %}{% elif loop.last %}, and {% else %}, {% endif -%}
{{- map[item]|int }} {{ item -}} {{- 's' if map[item]|int > 1 -}}
{%- endfor -%}
you don't put {{ inside {% and %}.
I'm trying to make the icon on a "Entity Button Card" change depending if the entity is "on" or "off" (its a zigbee door sensor) how can I accomplish this?
not sure that card supports it (I may be wrong), but the custom button card does at least
ok, let me try that one, the regular entity button card does not seem to like it
is ok if I paste the 12 lines here? (As in-line code)
going for it!
entity: binary_sensor.multipurpose_sensor
hold_action:
action: more-info
show_icon: true
show_name: true
tap_action:
action: toggle
type: entity-button
icon_template: "
{% if is_state('binary_sensor.multipurpose_sensor', 'on') %}
mdi:door
{% else %}
mdi:door-closed
{% endif %}"
name: Door
@rugged laurel I don't have a custom-button card, i assume its a HACS add-on?
hmm so I see it has a configuration section but not an installation section.
so, how do I get this installed?
NVM
odd to have installation AFTER configuration
sure, but you have to install it first
Not to read about what it does
most folks will browse for pics/tables etc to "see" what it does/looks like, so they will find that piece (IMO) but documentation should be sequential
anyways, thanks for pointing me in the right direction.
@queen meteor I broke it again, and I cannot figure out why.
Have two files, second one starts at line 15.
@ancient lynx I'm going to have to start charging you for screwing things up
I know. It's a problem.
I reconfigured, because I want to do an automation that starts when seconds reaches zero.
And with the formatting, the sensor kept reporting whatever number weeks there were left, or I suspect whatever the first digit is.
whats the error?
I can get the first file in just fine. But the second keeps giving an unkown result
I see. what do you see when you paste this in template editor? {{ state_attr('sensor.next_f1_event', 'seconds_left') }}
The correct amount of seconds until the event.
Big number at the moment.
Logs show TypeError: unsupported operand type(s) for /: 'NoneType' and 'int'
ok... try ```
{%- set seconds = state_attr('sensor.next_f1_event', 'seconds_left') | int %}
Will that get rid of the digits after the decimal?
Which, I suppose doesn't matter, since those are fractions of a second, if I'm thinking of that correctly.
Don't need to be that accurate.
no - that makes sure the seconds are in the numeric format, as you are using that value to multiply for seconds, hours...etc
if the value is not numeric, you get the error you shared above
Got it. I thought it also brought it to the next whole number as well.
That seems to have done it. Thank you again. I will stop futzing with it.
Next one I owe you a beer.
lol - you are fine! good luck!
not sure if this is a "templating" question, I've created a "Horizontal stack card" with 4 entities in it (they are temperatures) is there any way I can remote the small thermometer icon to the right of the title?
That sounds like a #frontend-archived topic
k
hello .. someone here who can help me to find out how to start and stp a kodi addon with call_method?
Wrong channel - try asking in #add-ons-archived
looking for a little assistance, i am really close to getting my light template working, however color is not working. I posted in the forums and also have a gist to help diagnose. https://community.home-assistant.io/t/advanced-light-template-help/175654 https://gist.github.com/roblandry/0dd1f252cd9d519fb723781562330b28
the issue lies somewhere in the way the list is being returned, or maybe double quotes
actually im making progress... this is where the error is coming from: Sending {'id': 176, 'type': 'event', 'event': {'event_type': 'call_service', 'data': {'domain': 'zha', 'service': 'issue_zigbee_group_command', 'service_data': {'group': 1, 'cluster_id': 768, 'command': 7, 'args': '"\n \n \n \n \n [30932, 20774, 5]"'}}
ok, i am down to this: 'args': '[9305, 10813, 5]'
i just need to figure out how to get an actual list instead of a string
can jinja output an actual list, or is it always going to be a string??
@hasty acorn lists are tricky in jinja because everything is treated as strings
that is what i have been fighting for hours
i have it functional as i was unable to create an actual list
seems like overkill
the macros are identical, with the exception of one outputs x value, and the other y
definitely not the issue with the macros.. It is how the lists are passed to the args.
args:
- "{{ color_temp }}"
``` is the problem.
that color_temp value will be treated as string and not as list
nah, thats not whats not working
@hasty acorn best I'd suggest is to use python_script or AppDaemon when it comes to this. You have much better control over there than jinja.
its the set_color values
yeah, but i was "trying" to get a light template working
just to see if it were possible
ok... what is the output of "{{ hs_to_xy(h, s, 100, 5) }}"
Irrespective, the only way out is using python_script or AD. It will save you a lot of headaches
the more up to date code is in post 2
that line was outputting "[#, #, #]"
also updated the gist
Again, unfortunately it will be treated as string. You could try adding individual list items using - by splitting the three values.
Right above - 5
are you saying like a ```
{% for v in value %}
- {{v}}
{% endfor %}
because i was worried it would not be properly indented
no dice: 'args': '- 45940- 19594- 5'
yup
trying it now
no dice, still a string
'args': '- 9305\n - 10813\n - 5'
im convinced jinja just cannot do it
you should be doing something like this: ```yaml
args:
- {{ xy[0] }}
- {{ xy[1] }}
- {{ xy[2] }}
yep
well... not quite
args: >-
macro stuff...
- {{ xy[0] }}
- {{ xy[1] }}
end macro
{{ call macro }}
like that
@hasty acorn that would muddy things... best way to do that is get a string from the macro, and parse it explicitly - that way no new lines, no spaces or unwanted white spaces
yeah, i think the way i have it in the post/gist is the only way to make it work with jinja
args:
- >-
macro stuff...
{{ xy[0] }}
end macro
{{ call macro }}
- >-
macro stuff...
{{ xy[1] }}
end macro
{{ call macro }}
the crappy thing is all the repeated code
yup - that's unfortunate!
either way, this is all proof of concept really, the zha group commands are still in the works
and you have to do a lot of digging to get the correct commands
lol
does this approach work?: ```yaml
args:
{%- macro x -%}
code here
{%- endmacro -%}
- {{ x(...)[0] }}
- {{ x(...)[1] }}
reduces duplicity, and still be able to return as list
yeah, but im not sure how to do it that way, a macro doesnt return anything... right?
so how would you get var[0] and 1?
afaik calling a macro just poops out values like a python print
"No, macros can only return template snippets (in the form of Markup objects), not Python objects like dictionaries."
but i do like the thought process...
macros can return data...
and, that approach fails in yaml lint... i was thinking if i could place the macro above like that, i could create a if you want x, poop out x, etc
ok.. give me 5 min... finisghing up lunch
ok
@hasty acorn what I do is have macros return string, and parse to my needs.
so 2 questions... how can you have the macro above the list and below the "args:" and it still be valid yaml, second how do you return and parse the string
I a trying locally in my template editor... what values do you pass for h and s?
360, 100 for red
we will get to both of your questions shortly
when I call {{ hs_to_xy(360, 100, 100) }}, it returns 45940
@hasty acorn something like this... https://paste.ubuntu.com/p/rsJXyPrxSb/
giving it a go now! 🤞
that code simplifies not having two exact macros in two different places, and still lets you access data the way you want. If that doesn't work, python_script would be the way to go!
nope... 'args': '- 45940 - 19594 - 5'
where are you seeing that output?
logs
hmm....well, good try! good luck with the python_script then! 😂
2020-03-01 14:03:35 DEBUG (MainThread) [homeassistant.components.websocket_api.http.connection.140694107990224] Sending {'id': 2, 'type': 'event', 'event': {'event_type': 'call_service', 'data': {'domain': 'zha', 'service': 'issue_zigbee_group_command', 'service_data': {'group': 1, 'cluster_id': 768, 'command': 7, 'args': '- 45940 - 19594 - 5'}}, 'origin': 'LOCAL', 'time_fired': datetime.datetime(2020, 3, 1, 19, 3, 35, 482984, tzinfo=<UTC>), 'context': {'id': '2f8ba74e1f8c42e2b86c16a92681cff3', 'parent_id': None, 'user_id': 'bcd35a1a6e6247958f1571cb62d460ff'}}}
nah, i think i am just going to have to have it split out for now with a LOT of redundant code
I don't think that will solve the issue. besides what you see in the logs is the json equivalent of generated yaml
nah, it works when split out
args:
- >-
macro stuff...
{{ xy[0] }}
end macro
{{ call macro }}
- >-
macro stuff...
{{ xy[1] }}
end macro
{{ call macro }}
works
an idea how I could template a telegram message?
https://hastebin.com/efobovejiz.coffeescript
Best I got now was like 5 under each other wich isnt ideal for a shopping list
@queen meteor this is a log with the split code:
it IS json, but the args are a true list
i appreciate the assistance, but i think this is as far as it can go in jinja.
BTW, what template editor are you using? the one in hass?
I see. try this one quickly https://paste.ubuntu.com/p/NSGDdkNQfs/ if this doesn't work, I give up
yes, I use the one in hass
giving it a go
my nuc took a poop, im restarting, itll take a few minutes to get it back up
ok.
ha! it is treating it as a string!
yeah, thats been my day thus far
the only thing i could figure it make the yaml list manually, and populate the values from the macro
yes, it sucks for sure!this is probably the biggest limitation I've seen with jinja so far.
yeah, as ive seen and read, {{}} always returns a string
actually i am not sure if the issue is with jinja or yaml
Anyone know if there's a way to combine these event triggers into one? Have like ~15 different event types.
- platform: event
event_type: automatic_update
event_data:
type: "notification:hard_brake"
vehicle:
id: "C_f0c25633155438cd"
- platform: event
event_type: automatic_update
event_data:
type: "notification:speeding"
vehicle:
id: "C_f0c25633155438cd"
hmm dont think ive seen any examples of event templates for the trigger itself...what I do know is the trigger template allows you to look at event data
@light flume I haven't tried multiple event triggers - it might require you to pass event_data. If it doesn't, you could try with something like this: ```yaml
trigger:
- platform: event
event_type: automatic_update
condition: - condition: or
conditions:- condition: template
value_template: "{{ trigger.event.data.event_data.type == 'notification:hard_brake' }}" - condition: template
value_template: "{{ trigger.event.data.event_data.type == 'notification:speeding' }}"
- condition: template
awesome, thanks guys
How would I adapt {{ states.light|selectattr("state", "equalto", "on")|list|length }} to exclude any lights where is_deconz_group = true ?
You could put a pipe and use reject filter
What am I doing wrong here?
- platform: rest
resource: "https://services1.arcgis.com/0MSEUqKaxRlEPj5g/arcgis/rest/services/ncov_cases/FeatureServer/1/query?f=json&where=(Country_Region%3D%27US%27)&outStatistics=%5B%7B%22statisticType%22%3A%22sum%22%2C%22onStatisticField%22%3A%22Confirmed%22%2C%22outStatisticFieldName%22%3A%22Confirmed%22%7D%2C%20%7B%22statisticType%22%3A%22sum%22%2C%22onStatisticField%22%3A%22Deaths%22%2C%22outStatisticFieldName%22%3A%22Deaths%22%7D%2C%20%7B%22statisticType%22%3A%22sum%22%2C%22onStatisticField%22%3A%22Recovered%22%2C%22outStatisticFieldName%22%3A%22Recovered%22%7D%5D"
name: Corona Virus US
value_template: "{{ value_json.features[0].attributes.Recovered }}"
json_attributes_path: "$.features[0].attributes"
json_attributes:
- Confirmed
- Deaths
- Recovered
Gives this error:
Failed config
sensor.rest:
- Invalid config for [sensor.rest]: [json_attributes_path] is an invalid option for [sensor.rest]. Check: sensor.rest->json_attributes_path. (See ?, line ?).
- platform: rest
json_attributes: [source /config/sensor.yaml:15]
@long basalt did you try this? https://community.home-assistant.io/t/help-with-corona-scrape-sensor/174973/13?u=dshokouhi
im about ot give it a shot in dev lol
Was about to go look to see if some features got deprecated in the rest sensor
Best way to troubleshoot the rest sensor is to enable debug love, get the actual json returned by the rear sensor, put it in template editor to access corresponding values.
@long basalt its working fine for me actually...no errors
resource: "https://services1.arcgis.com/0MSEUqKaxRlEPj5g/arcgis/rest/services/ncov_cases/FeatureServer/1/query?f=json&where=(Country_Region%3D%27US%27)&outStatistics=%5B%7B%22statisticType%22%3A%22sum%22%2C%22onStatisticField%22%3A%22Confirmed%22%2C%22outStatisticFieldName%22%3A%22Confirmed%22%7D%2C%20%7B%22statisticType%22%3A%22sum%22%2C%22onStatisticField%22%3A%22Deaths%22%2C%22outStatisticFieldName%22%3A%22Deaths%22%7D%2C%20%7B%22statisticType%22%3A%22sum%22%2C%22onStatisticField%22%3A%22Recovered%22%2C%22outStatisticFieldName%22%3A%22Recovered%22%7D%5D"
name: Corona Virus US
value_template: "{{ value_json.features[0].attributes.Recovered }}"
device_class: timestamp
json_attributes_path: "$.features[0].attributes"
json_attributes:
- Confirmed
- Deaths
- Recovered```
is taht the same thing lol
ah im on 0.106.2
but i tested in my dev instance which was just synced up with all the latest and greatest changes
hmm not sure if those sensors are something i want to stare at in my UI 🤣
Sadly, you can’t avoid hearing about it no matter where you go these days! You might as well give a big stare and move on 😊
hahahaha yea for sure its a hot topic anywhere
Right lads... I have this, but it's not working. Any ideas?
I can turn the light on and off, but it doesn't change the state of the switch.
light:
- platform: template
lights:
bedroom_leds:
friendly_name: "Bedroom LEDS"
value_template: "{{states('switch.bedroom_leds')}}"
turn_on:
service: switch.turn_on
data:
entity_id: switch.bedroom_leds
turn_off:
service: switch.turn_off
data:
entity_id: switch.bedroom_leds```
@charred haven Upgrading to 106.2 fixed my rest sensor template
@charred haven You see 106.3? we were too fast
oh wow lol
funny how they were adding it as we were discussing it
@unborn ore try value_template: "{{ is_state('switch.bedroom_leds', 'on') }}"
Huh, that fixed it @charred haven
Thanks mate
So the template only accepts true/false, no on/off?
its easier to do that for switch template and binary sensor templates as its either one or the other
Gotcha
that sensor not looking so good @charred haven -- 100 confirmed, 7 deaths
@long basalt official integration you mean?
Our rest one
ah it seems to be the same data actually i think
Also did this
aspect_ratio: 0
type: iframe
url: >-
https://gisanddata.maps.arcgis.com/apps/opsdashboard/index.html#/bda7594740fd40299423467b48e9ecf6
and added as a panel
(not looking so good from a humanitarian point of view )
oh yea
Is it possible to get the current theme name from Jinja2 templating?
nvm, found the solution myself
automation:
- alias: Register current theme
initial_state: true
trigger:
- platform: event
event_type: call_service
event_data:
domain: frontend
service: set_theme
action:
- service: input_text.set_value
data_template:
entity_id: input_text.current_theme
value: "{{ trigger.event.data.service_data.name }}"
that's a hokey way of doing it
@mighty ledge the best way would be using only Jinja2 but it's good way too IMO
well it won't work if you have 2 different users with 2 different themes
users always have backend-selected
the server chooses which theme is running
if user forces another theme, then this won't work
but never happens 🙂
yes but every user on every device on every browser has a different theme
they can choose different theme, but if it's on backend-selected, then it's all the same
ok, as long as you know that they all cause a set_teme event and 2 different users with different themes will cause that input_text to be out of sync
that's all I'm saying. You have 1 event pool going to 1 input_text with multiple users sending events to the single pool
Yes, I know what you mean. But as I said, all users use backed-selected and they don't mess with that. So it's ok in this case
No, but you could just use a template trigger for that
yeah will do. cheers mate.
Hi, I have this template: Emptying though {{ states.sensor.karl_1.attributes.days }} days, but if I want it to say Empting todaaay when state.sensor.karl_1.attributes.days is 0, is that possible?
yes
Do you mind help me out with such if/else template?
try first
https://www.home-assistant.io/docs/automation/templating/
https://www.home-assistant.io/docs/configuration/templating/
I'll check. Thanks!
{% if is_state_attr('sensor.karl_1', 'days', 0) %}
Emptying todaaaaay
{% else %}
Emptying though {{ states.sensor.karl_1.attributes.days }} days
{% endif %}
Think I solved it. Thanks @rugged laurel 🙂
yes
Thanks!
Is there a way to get this [template] (https://imgur.com/a/hRNGX2c) to render properly in the script editor?
IIRC the UI editors can't handle templates currently
@buoyant pine Thanks, I couldn't find anything that said that for sure.
Could be wrong though, I don't use the UI editors
Hello, I am trying to get the location of the calendar's next event
I have this right now: {{ state_attr('calendar.christoph', 'location') }}
but this template sensor always returns none, even though the next event has a location set
the calendar-card shows the events with their location
if I check the calendar entity in Dev Tools, I see that it only has the attribute offset_reached: false
but how does the calendar-card see the next events' location then?
I think this is more for #integrations-archived
@inland stag Mine worked here, can you try testing with Developer Tools > Services?
Service: persistent_notification.create
Service Data:
title: Location
message: "{{ state_attr('calendar.family', 'location') }}"
And have you validated that the calendar does in fact have a location attribute? (check it in Developer Tools > States)
Hi guys, is there a template I can use to retrieve the length of time an entity has been at it's current state? My example is a notification sent via the alert integration, every 30 minutes my garage door is open it sends a notification that I'd like to read "The garage door has been open for 'x' minutes" (or convert to hours if the number gets big enough). Thanks in advance guys!
@still harbor you can use teh last_changed attribute to get a timestamp
Thanks @charred haven! Is it {{ state_attr('cover.garage_door', 'last_changed') }} ? Because it's returning "none" for me
@still harbor try like {{ as_timestamp(states.cover.garage_door.last_changed) }}
Yes! And I can use relative_time as a human readable rounded number, which is exactly what I'm looking for! Thanks @charred haven
np!
https://www.home-assistant.io/docs/configuration/state_object/ has more cool stuff like that such last_updated
Can I also template with incoming json data wich isnt yet a sensor?
I get a object with the value false I try to disable the the info as long as it is false
{% set my_test_json = {"first":3,"seccond":6,"third":9,"fourth":12,"trafficjam":false,"trafficjam_1":false} %}
____
The thing is is {{ my_test_json.first }} {{ my_test_json.trafficjam }}. # output: " 3 false.
___ # try to accive
{% if is_state('my_test_json.trafficjam_0', 'false') %}
''
{%- else -%}
'STAU'
{%- endif %}
Take a look at the JSON section here: https://www.home-assistant.io/docs/configuration/templating/#processing-incoming-data
thanks - but I cant find something outside of the scope of filtering or mathematical operations in this section 😕
HA!
{{ value_json.trafficjam | replace(false, "")| replace(true, "STAU")}}
Is there a way to have regex remove double quotes without YAML freaking out?
I have this:
"{{ states('sensor.mi_drive_rest')|regex_replace(find='.*</div>', replace='')|regex_replace(find=',', replace='')|striptags|regex_replace(find='[[\"\]]') }}"
Which works perfectly fine in the template editor, but throws a bunch of errors in VSCode and YAMLLint.
I get unknown escape sequence on the line above that one, and missed comma flow between collection entries on the line the template is on.
Plus unexpected end of the stream within a double quoted scalar further down the file.
Code editor probably isn't aware of jinja2
Hey folks, I have an integration which returns a sensor. {{ states.sensor.dackeri.attributes }} in the template editor in developer tools returns a bunch of attributes which is great. One of them is "tier" and its value is "Gold", why might the below yaml for a template not work?
- platform: template
sensors:
tier:
friendly_name: "Tier"
value_template: "{{ state_attr('sensor.dackeri','tier') }}"
config checker returns:
Error loading /config/configuration.yaml: while scanning a simple key
in "/config/configuration.yaml", line 58, column 1
could not find expected ':'
in "/config/configuration.yaml", line 59, column 13
@royal raven To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks. Here's an example:
```
code here
```
Watch the animated gif here: https://bit.ly/2GbfRJE
DO NOT repeat posts. Please edit previously posted message, here is how -> https://bit.ly/2qOOf1G
Seems fine, is that the line number it's complaining about?
Let's see the surrounding code
Please use https://www.hastebin.com/ or https://paste.ubuntu.com/ to share code or logs.
Also common convention for indentation is 2 spaces. If you're using 4 it's fine as long as you're consistent
YAML != Python 😛
sensors:
- platform: template
sensors:
downstairs_avg_temp:
friendly_name: "Downstairs Average Temp"
device_class: 'temperature'
unit_of_measurement: '°F'
value_template: >-
{% set sensors = [
states('sensor.living_room_temperature')|float,
states('sensor.office_temperature')|float,
states('sensor.thermostat_temperature')|float
]
%}
{{(sensors|sum / sensors|length)|round(1)}}```
that's one of mine
YAML != Python 😛
@buoyant pine They're tabs, but they render differently in discord versus the config which does them as 2.
😱
oof, that's a whole 'nuther flame war
You should be using an editor with soft tabs
where the correct answer is "tab inputs <n> spaces"
An actual tab character will cause issues
That's why I asked to see the surrounding code 😛
I was convinced I finally had the syntax correct and when it didn't work I came crying in here but it was just that I had stuffed the next line
That's why I asked to see the surrounding code 😛
@buoyant pine Yeah and the polite thing would've been to show it but it gave me the idea to syntax check it before I embarrassed myself (which I have now done by being so honest but whatevs)
@royal raven oh you're good, just wanted to say I KNEW IT 
I have a template sensor that combines two thermometers to get an average. It seems to work fine - except there's something strange with how it reports last_updated / last_changed.
https://imgur.com/a/9RW5WkT shows the temperature was changed 10 minutes ago.
But according to "{{ as_timestamp(strptime(states.sensor.template_temperature_floor_1.last_changed | string | truncate(19,True,'',0),'%Y-%m-%d %H:%M:%S:%f')) | timestamp_custom('%Y-%m-%d %H:%M:%S') }}" it was changed "2020-03-05 12:34:01" which is 75 minutes ago.
I get the same result from {{{ states.sensor.template_temperature_floor_1.last_changed }} and {{ states.sensor.template_temperature_floor_1.last_updated }}
Any suggestions why it doesn't update its last_updated attribute?
@dreamy sinew ha core check doesn't pass either, tho. So it seems to not just be VSC.
So there is no way to match double quotes in regex then.
might be able to use something like [[:punct:]]
[[👊]]
Is there any benefit to using states['domain.entity_id'].state over states('domain.entity_id') ? Is it just leftover from old ways of doing things?
I've got mostly the latter, but a few of the former for some of my older stuff, and about to go through and standardize.
The second is better. Prevents errors when the entity isn't ready/available
awesome. i read that, but wondered if there was any reason to use the old nowadays. i've been posting the same other places ("don't use that") probably something along the lines of "it'll be deprecated soon™️" 🙂
don't think it'll get deprecated. they're just different. this explains the difference: https://www.home-assistant.io/docs/configuration/templating/#states
I've got a 3D printer hooked up into a TP-Link Kasa power switch to monitor power usage. I just called light.turn_off as I was writing an automation for my hue lights. As it turns out it also shut off my printer mid print.
Sad panda.
How can I tell HA not to treat this device as a light (switch)?
@wicked parrot list it as a switch not a light as per the docs https://www.home-assistant.io/integrations/tplink/
@bitter atlas Related question. I've got a pair of TP-Link Kasa dimmer switches hooked up to fans (basically remotely controller the fan speeds). Is there a way to have those not be related to the grouping of lights?
Or anyone?
Don't put them in the group of lights 🤷
@wicked parrot not sure it will work putting smart switch hosts under the switch in the config but you could try it.
@arctic sorrel Can I remove lights from entity_id: all for light.turn_off?
No, you'd said group... so I assumed you were using groups 🤷
The answer there is - don't do that 😛
Maybe use areas instead?
Ok.
Or create your own group
So there isn't a way to tell HA to consider a device something other than what it sees it initially as?
And I know about templating, but my understanding is that the original device still exists?
No, you can't pull a Jedi mind trick on HA like that
Womp womp.
@bitter atlas Telling HA to treat the dimmers as a switch, sadly prevents me from changing the brightness.
Just FYI.
well obviously
@bitter atlas @arctic sorrel Also for future reference, just got this setup... https://community.home-assistant.io/t/switch-everything-off-except-excluded-entities/80343
Now I just wish I understood templating enough to get these dimmer switches to also look like fans in HA.
@arctic sorrel Thanks!
How would I take the state from a binary sensor and have that get synced into the state for a camera?
Not sure what you mean by that - you want the state of the camera to match the sensor?
might be able to use something like
[[:punct:]]
@dreamy sinew Hmmm. That didn't work either.
I think I'm going to have to abandon it. Bummer.
Unless there's a better way to take ["<div class='dmsMessage'>TRAVEL TIME TO<br> I-94 9 MI 8 MIN</div><div class='dmstimeStamp'>Mar 6 2020, 10:31 AM</div>","EB I-696 @ Couzens"] and break it down to the Message div (TRAVEL TIME TO<br> I-94 9 MI 8 MIN) and the location div (EB I-696 @ Couzens).
@ancient lynx {% set raw_string = ["<div class='dmsMessage'>TRAVEL TIME TO<br> I-94 9 MI 8 MIN</div><div class='dmstimeStamp'>Mar 6 2020, 10:31 AM</div>","EB I-696 @ Couzens"] %} {% set regex_search_string = "dmsMessage..(.*)<.*dmstimeStamp..(.*)<" %} {{ raw_string[0]|regex_findall_index(find=regex_search_string, index=0) }}
Please use imgur or other image sharing web sites, and share the link here.
Because too many people think code should be posted as a screenshot
i bent the rules for a "show your work" situation
please share all the code and the expected output as text, i can try to replicate
and if you can send the raw sensor output too
just dump it all in hastebin or something
@ancient lynx try this:
{{ states('sensor.mi_drive_rest')|regex_findall_index(find='dmsMessage..(.*)<\/div><', index=0)|regex_replace(find='<br>', replace='\n')|striptags|title }}
Friendly Name:
{{ states('sensor.mi_drive_rest').split(',')[-1][0:-2] }}```
Ok, I have a binary sensor (curl command setting an on/off state). How can I have that state also be applied to another device like a camera?
?

You can't, not really
@dreamy sinew Wow. Much simpler than my solution.
Value came out perfect, freindly name just has one leading ".
Could I do a regex that removes the first character bs searching for a " specifically?
do [1:-2] then
Hurm.
@dreamy sinew Got it!! Thanks for your help!
I have a pair of Wyze cameras that I'm piping into HA through platform: ffmpeg, however the state for them is always idle. I want to derive the state from a different sensor.
i.e. running curl to see if the stream is up or not.
Does that make sense?
Yes, but I don't see any way to do that
You could just make a command line analog/binary sensor
sorry should have posted here first how do I use this message to show just the time is returned?
{
"title": "Event Ghost Fired",
"message": "{{ states.sensor.time }}"
}
{
"title": "Event Ghost Fired",
"message": "<template state sensor.time=18:56; friendly_name=System Time, icon=mdi:clock, haaska_hidden=True, homebridge_hidden=True, package=system @ 2020-03-06T18:56:01.012457-05:00>"
}
{
"title": "Event Ghost Fired",
"message": "<template state sensor.time=18:56; friendly_name=System Time, icon=mdi:clock, haaska_hidden=True, homebridge_hidden=True, package=system @ 2020-03-06T18:56:01.012457-05:00>"
}
@whole oracle ```
"message": "{{ states('sensor.time') }}"
@queen meteor thank you
Can I set the Theme of a Card via Templating?
Sounds like a #frontend-archived question
Hello, I keep getting this error: Invalid config for [script]: invalid template (TemplateSyntaxError: unexpected char '‘' at 3) for dictionary value @ data['script']['good_morning']['sequence'][0]['data_template']['message']. Got None. (See /config/configuration.yaml, line 156). Please check the docs at https://home-assistant.io/integrations/script/
This is the code: good_morning: alias: Godmorgonmeddelande sequence: data_template: language: sv message: >- {{[‘‘Godmorgon!’’, ‘‘Dags att vakna!’’, ‘‘Nu är det dags att vakna!’’, ‘‘Upp och hoppa!’’] | random }}. Klockan är{{states(‘‘sensor.alarm_clock_time’’)}}. Just nu är det {{states(‘‘sensor.smhi_home’’)}}. Temperaturen utomhus är {{state_attr(‘‘sensor.smhi_home’’, ‘‘temperature’’)}}grader Celsius. Todays high will reach {{state(‘‘sensor.smhi_home’’)}}degrees Celsius. Ha en underbar dag! entity_id: media_player.john_sonos service: tts.google_say
I've tried changing the order and type of quotes in a lot of different ways but i can't seem to find what the error is.
You've got what are called smart quotes in there (the curly ones) so whatever editor you're using is adding them. Are you using a text editor?
Actually just the file editor addon in hassio. I've copied the format of the template from a snipp of code I got on the forums, so my editor isn't adding them there.
Copy from the forum (if unformated there) will add those
Ok, so if I got it right I need to change them to normal double qoutes?
how can you do multiline stuff in jinja? every example i find online has {% %} around every line, but that seems a little rediculous when doing something like this:
{% for mower in mowers %}
{% set gps = state_attr('device_tracker.automower_' + mower,'latitude')|string + "," + state_attr('device_tracker.automower_' + mower,'longitude')|string %}
{% set status = state_attr('device_tracker.automower_' + mower,'status')|lower %}
{% set label = state_attr('device_tracker.automower_' + mower,'friendly_name')[0]|upper %}
{% set color = 'green' %}
{% if status in colors %}
{% set color = colors[status] %}
{% endif %}
{% set image_url.value = image_url.value + "&markers=color:" + color + "%7Clabel:" + "" + "%7C" + gps %}
{% endfor %}
Well, that's right, even if your formatting is odd
just seems like there should be an easier way of doing that...there's no "output" anywhere in that loop, i'm just preparing a variable for output later
and if it's odd...its the first jinja code i've written....I typically deal with c#
In HA the whole point is that you're using Jinja to output text, so 🤷
i do output text later on..
i'm building an image path with dynamic information...
{{ image_url.value }}¢er=33.252043,-96.527017
i mean, in the example earlier, I could have just output it directly there ...but it still doesn't change the fact that i had 7 lines of code above it calculating what I was going to output
🤷 That's the way it is
k, then i'm not going to f with templates for my other issue, i'll just code an appdaemon app....more simple I think
@merry ravine you are setting a value in a loop. Loops won’t maintain state. You need to use namespaces.
@queen meteor i'm not having a problem with it..the code i linked was for example only, it works just fine
Ok... 👍
Hi guys I'm trying to create a binary sensor that evaluates as true when the following is true... A cover is open, a binary sensor has not changed for 30 seconds, and three separate binary sensors have not changed to on for two minutes... Hope you guys can help, thanks!
@still harbor you need to investigate into template sensor.
@queen meteor yea I've got tons of them but this one is beyond me. Mostly due to having two device types and also not knowing how to write "hasn't changed states for x time or hasn't changed to a specific state for x time"
i need to get better at reading timestamps in templates
I am really not getting the templates through my brain
Can someone please show me how to create a NAND logic for two states?
I'm trying to automate with zones
@agile spear still struggling with the the above use case? Need hand?
{{ not (is_state("person.me","Home") and is_state("person.wife","Home")) }} is not working and I feel like I am fatally misunderstanding the templating syntax
are you aware of template editor?
are you using the UI to write this code or manually editing yaml code?
Yes, but it's hard to use on mobile
painful on mobiles for sure... I wouldn't do it on mobiles
Both, through the automation syntax
ok - what does the template editor give for the code above?
Let me try to copy/paste into it
Alright, fine, I'll pull out the dang laptop
Hrm
so {{ is_state("person.me","Home") and is_state("person.wife","Home") }} is showing as False even though we are both home...
I think it's actually working mostly correctly and I just have a typo
Dang it
turns out it was home not Home
Whelp, thanks for the help ayway @queen meteor, you did end up getting me there!
@agile spear did you figure out with checking time thingy?
" A cover is open, a binary sensor has not changed for 30 seconds, and three separate binary sensors have not changed to on for two minutes... Hope you guys can help, thanks!"
☝️ that's the one I'm talking about
Ah, that was @still harbor, not me! lol
@agile spear sorry! got confused. You both have red and black icons, didn't pay much attention 😂
@still harbor you can do something like ```
{{ (now() - states.switch.kitchen.last_updated).total_seconds() > 60 }}
Hahaha not a problem! I figured that might be it
lol wow! So easy! What about determining if a sensor has been changed to a specific state for a certain amount of time?
@lapis shuttle posted a code wall, it is moved here --> https://paste.ubuntu.com/p/h6QHyV5VNs/
Hi, im trying to make an automation with template but seems to making something wrong with my template :P
Basically i need to trigger a message when im pressing and receiving the message (11:19:31 MQT: sonoff_bridge/stat/RESULT = {"RfKey16":"Default sent"}) on my sonoff bridge.
Here is my automation:
- id: '1583656379474'
alias: test
description: ''
trigger:- platform: mqtt
topic: sonoff_bridge/stat/RESULT
condition: - condition: template
value_template: '{value_json == "RfKey16": "Default sent"}'
action: - data:
message: Test1
service: telegram_bot.send_message
- platform: mqtt
I want to run a scheduled MQTT script to 5 different hosts. Can I pass a variable to the script?
Like
script.mqtt_refresh_lovelace wallpanel1
script.mqtt_refresh_lovelace wallpanel2
or create a loop that matches a entity wildcard?
..or something else that avoids creating unique scripts for each device
https://www.home-assistant.io/integrations/script#passing-variables-to-scripts @waxen rune - more a question for #automations-archived though
I thought I posted in Automations. I searched first and I guess the matches took me here 🙂
hi i have this output and i want to parse it with json.
15:41:25 MQT: sonoff_bridge/stat/RESULT = {"RfKey16":"Default sent"}
i tried value_json[0] == '"RfKey16":"Default sent"'
but seems to not working
not very familiar with json anyway 😛
NOTE: the output its not like the
RfReceived":{"Sync":9550,"Low":320,"High":980,"Data":"68DA27","RfKey":"None"}}
that i can use value_json.RfReceived.Data == '68DA27'
@lapis shuttle what value are you trying to access?
@queen meteor the RfKey16 for example
@queen meteor i want to match this string in order to trigger a notification to know that key 16 is indeed triggered on my sonoff rf bridge
Can you post your whole code?
@lapis shuttle Please use https://www.hastebin.com/ or https://paste.ubuntu.com/ to share code or logs.
@queen meteor
- platform: mqtt
name: 'arm'
state_topic: 'sonoff_bridge/stat/RESULT'
value_template: >-
{% if value_json == '"RfKey16":"Default sent"' %}
{{'ON'}}
{% else %}
{{states('binary_sensor.arm') | upper}}
{% endif %}
off_delay: 15
device_class: motion
@lapis shuttle To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks. Here's an example:
```
code here
```
Watch the animated gif here: https://bit.ly/2GbfRJE
DO NOT repeat posts. Please edit previously posted message, here is how -> https://bit.ly/2qOOf1G
@lapis shuttle if the message in the topic 'sonoff_bridge/stat/RESULT' is json, you should be comparing with json string.
@queen meteor the output is
15:41:25 MQT: sonoff_bridge/stat/RESULT = {"RfKey16":"Default sent"}
then try value_json |string == '{"RfKey16":"Default sent"}'
instead of value_json == '"RfKey16":"Default sent"'
Or simply do this ```
{% if "16" in value_json |string %}
@lapis shuttle try the last option - much simpler and easier
@queen meteor the if 16 worked! thanks for your help (im not a json guy indeed :P)
Can anyone help me get my roomba_battery to show up as proper numeric data so it'll show in a graph, like my phone battery, rather than categorical data?
sensor:
- platform: template
sensors:
roomba_status:
friendly_name: "Roomba Status"
entity_id: vacuum.roomba
value_template: "{{ state_attr('vacuum.roomba', 'status') }}"
icon_template: "mdi:brush"
roomba_battery:
friendly_name: "Roomba Battery"
entity_id: vacuum.roomba
value_template: "{{ state_attr('vacuum.roomba', 'battery_level') }}"
icon_template: "{{ state_attr('vacuum.roomba', 'battery_icon')}}"
@rose reef add device_class: battery
amazing, thank you
or you can add unit_of_measurement: %
perfect!
@lapis shuttle that if "16" in value_json |string is a hack... more accurate way of doing it is: {{ 'RfKey16' in value_json |list }}
@queen meteor thanks you have already solved the issue in automations group 👍
@elder tartan posted a code wall, it is moved here --> https://paste.ubuntu.com/p/Bs4BWyky6Z/
The state of the entity is 'unknown', so i'm not extracting it correctly.
Does anyone know how I can template the currently logged in user to show in e.g. a markdown card?
Is it possible to store a variable on a Person? Looks like you can set name, device_trackers, image, and link an optional user.
The goal is to do something like this:
- Parent 1: bedtime == 10 PM
- Child 1: bedtiime == 8 PM
Create an automation which checks every Person's bedtime, then executes a Scene (say turn lights off)
High! I'm trying to add 2 vars together, after converting one to gallons - no matter how I put this together - i get "unknown template error"
{{(states('sensor.ro_system_1_liters')| int * 0.2641720524| round(2))}} {{(states('sensor.muh_meter_daily_water'))}}
@dense topaz are you trying this out in the template editor?
yes.
try to slowly build it out starting with dispalying the state then converting to int etc...
ok - I've been toying with it for over an hour. I can get both these number to display as seen above....
I try {{(states('sensor.ro_system_1_liters')| int * 0.2641720524| round(2)) + 1}} and that works
but when i do:
{{(states('sensor.ro_system_1_liters')| int * 0.2641720524| round(2)) + states('sensor.muh_meter_daily_water') }}
I get unknwon template error
you need to convert the second one to int as well
{{(states('sensor.ro_system_1_liters')| int * 0.2641720524| round(2)) + (states('sensor.muh_meter_daily_water') | int) }}
sometimes sensors come in as a string so always good to convert first lol
States are always stored as a string @dense topaz @charred haven
Ooohhhhhhh thank you 🙂
Anyway to understand why this isn't evaluating as true?
Trying to follow the automation example in which lights are turn off a specific time (by way of input_datetime.household_bedtime) outlined here: https://www.home-assistant.io/integrations/input_datetime/
Here's the template:
{{ states('sensor.time') == (state_attr('input_datetime.household_bedtime', 'timestamp') | int | timestamp_custom('%H:%M', True)) }}
sensor.time is returning in %H:%S, and I'm formatting input_datetime.household_bedtime to the same...
Have you tried in the template editor?
You can test individual pieces of code - easy way to debug
action:
- service: input_boolean.toggle
data:
entity_id: input_boolean.wakeup_active
- service: script.sonos_say
data_template:
where: bedroom
volume: 0.06
message: 'Wakeup clock {{ states("input_boolean.wakeup_active") }}.'
This toggles the input_boolean but the template always returns ON, if I run the same template manually both on and off is returned accordingly.
What's wrong?
Might be a race condition?
can you use templates for the offset value in triggers for the sun platform? i.e. use an input number to set the offset?
Counting the number of persons at home, could that be done with a template or would I need a script?
{# Set initial variable #}
{% set count = namespace(value=0) %}
{# For loop #}
{% for state in states.person %}
{% if state.state == "not_home" %}
{{ state.name }}
{% set count.value = count.value + 1 %}
{% endif %}
{% endfor %}
{# Print result #}
The number of people is {{ count.value }}.
That should work?
Yeah, but there is a better way.
If you ask again in about 6h our template experts should be awake
Hey guys - is there any way to capture the "last triggered" time of a motion sensor? I have a cheap IKEA motion sensor and would like to be able to display "last seen" time in a badge...
@jaunty citrus use a template sensor with value states.binary_sensor.ikea_motion.last_updated or last_changed
@jaunty harbor does this work even if neither "last_updated" nor "last_changed" appear as attribute in the "States" list?
Yep, those values aren't attributes but internal for the State Object, made that mistake today: https://www.home-assistant.io/docs/configuration/state_object/
ah, okay
Hmmm... Looks like this is indeed the way to go, however, both last_udpated and last_changed show the last HA start... is there any way to get to the "last time sensor had value X" point in time?
@jaunty citrus stuff it in a input text?
{{ dict((states.person)|groupby('state'))['not_home']|count }}
@jaunty harbor ☝️
Damn that's short 😮
That's what she said
🤣
@long basalt what do you mean by "stuff it in an input text"?
okay, I hoped there was some way to retrieve the last point in time state was "detected"...
Thanks, will give that a try.
can you also explain your answer you gave in #hardware-archived ?..
@rugged laurel Did you make it even smaller and dropped some list filters?
yeah, she said it was too big 😦
And you took her word for it?
I had a choice? 🤔
There's always a choice.
The question is whether it's a wise one...
I am trying to create a sensor indicating if a script has been run with the last 7200 seconds
I am trying this: {{ (now() - datetime.datetime.strptime(script.1582059418798.last_updated, '%Y-%m-%dT%H:%M:%S%z')).total_seconds() < 7200 }}"
You likely want https://www.home-assistant.io/integrations/time_date instead of now()
thank you @arctic sorrel
That template will update when the entities in it update, so when the script runs...
Thanks again Ludeeus! Playing with the Template Dev Tool and it's just awesome.
I was going with {{ states.person|selectattr("state","equalto","not_home")|list|count }} but that's 11 characters longer than yours.
Now only need to alter this stuff to get a list of people at home (comma-seperated).
map(attribute='name')|list|join(', ') instead of the count in my example
Or join(', ',attribute='name') instead of count, 10 characters less (and only a single filter).
How can I actually know which attribute it is? I was going with friendly_name but that's undefined
Look at the state object
<template state person.jorim_tielemans=not_home; editable=True, id=jorim_tielemans, latitude=52.9303699, longitude=7.407744, gps_accuracy=15, source=device_tracker.fig_lx1, user_id=b4mazi7skzr4dvjpe38olxuum8fx9hlv, friendly_name=Jorim Tielemans, icon=mdi:chess-queen @ 2020-03-11T07:22:22.647331+00:00>
D'oh, mixing up with attributes again.
HA attributes I mean 🤦
attribute='name' == attribute='attributes.friendly_name'
Yes, but if that is None, it fall backs to entity_id
hi guys! i want to ingest some json data from a web page into h-a
that page
@arctic sorrel in #integrations-archived suggested to import the totals into a state and the rest as attributes, but i don't know how to do that yet
i am using the sensor platform rest
@long basalt in case you're interested... I ended up accessing the "states" table in the HA database by the "sql" sensor platform. This allows mor eprecise and flexible selection, and does not require any additional data to be stored.
Nice @jaunty citrus -- You are doing that all with the native automation engine? Or triggering your SQL script another method? I use Node-RED and I'm in the process of moving my sensors that I want the data/time to persist past HA restart into the native NR sensor -- It also has a built in history function to access past states
Nah, I just needed a sensor showing when the last - real - motion was triggered on that sensor. So a "select max(created) from states where entity_id ='xxx' and state = 'on'" gives me exactly the data I need.
i want to get values through the template sensor platform.. but some of the values are not available yet, meaning it should be "unavailable".. is it possible to set these values to 0?
i tried value_template '{{ states.sensor.XXXXX | round(0) }}'
but i still get unavailable out
{% set value = states('sensor.whatever') %}
{{ value|float|round() if value != "unavailable" else 0 }}
@dreamy sinew is this inside the template sensor?
Yes
hm.. now i got "Unknown" instead of "Unavailable"
Something like {{ states('sensor.whatever') if states('sensor.whatever')|str()!="unavailable" else 0}} ?
It may need extra parenthesis
Also, I'm sure it was answered a lot but, what would be the simplest way to get the result of a service call from a template ? Do I need to do a dummy sensor for that ?
{% set value = states('sensor.whatever') %}
{{ value if str(value) != "unavailable" else 0 }}
will that work?
That's the spirit
you don't need to str(value) its already a str
I didn't know that one
What's the value of {{ value != "unavailable" }} ?
Maybe a case issue ?
Error rendering template: UndefinedError: 'dict object' has no attribute 'Test'
ah, because states() is returning unknown
that's what i'm getting when i'm running this in the template editor
{{ value|float|round if value not in ['unknown', 'unavailable'] else 0 }}```
you can test all of this in the template tester
i want to accumulate together a bunch of template sensors.. can this be done?
accumulate meaning that i want to add up all the ints from the individual (template) sensors into one common group sensor
With another template sensor, sure
how would that look?
{{ states('sensor.first')|int + states('sensor.second')|int + ... }}
is it possible with some kind of autosum against a group?
Not that I know of, but others may have a way
what is the difference between {{ and {% ?
First one for condition/expression evaluation and the other for everything else.
There's an example right at the top of https://www.home-assistant.io/docs/configuration/templating/
Hey guys, I'm trying to update one of my template sensors whenever one of my media_players changes.. This is what I came up with:
entity_id: >
[{{ states.media_player|map(attribute='entity_id')|join(',') }}]
Unfortunately it doesn't work and I cannot understand why, in the Dev Tools -> Template it looks fine
The template sensor will only update when one of the listed entities updates
HA will try to identify and extract the relevant entities, but in your case it has nothing to work with, so you have to tell it
Currently I don't have any entity_id set which makes it not update. I'm trying to generate a list automatically.. Is that possible or do I have to write them all manually?
Not possible there, that won't accept a template
If you look at the link, you'll see it takes (string | list)
Not (template)
The full sensor is like this:
media_players_active:
entity_id: >
[{{ states.media_player|map(attribute='entity_id')|join(',') }}]
value_template: '{{ (states.media_player|selectattr("state", "eq", "playing")|list|length + states.media_player|selectattr("state", "eq", "paused")|list|length) > 0 }}'
Do I have to use entity_id or should it automatically detect it?
It can't detect it, because you don't have any actual entities listed
So yes, if you want it to update you have two choices:
- Force update from an automation - brute force, but it'll work
- List the entities - efficient, but takes you a moment or two to list them
Ah okay, it doesn't detect the ones from the template?
There's no entities in the template
value_template: '{{ (states.media_player|selectattr("state", "eq", "playing")|list|length + states.media_player|selectattr("state", "eq", "paused")|list|length) > 0 }}'
``` Please point out any entity ID in that string 😉
Damn I thought totally wrong.. Sorry 😅
No worries
But there's no way to just say
entity_id: (list of all media_player entities), like a domain?
No
You can put your template in the Templates screen to get the list out, but that's it
I thought it works in the template so it should interpret the template.. Guess I'll have to list them manually :/ Anyway, thanks a lot for helping me out, now I understand why it didn't work
As I said, look at the link I posted - it tells you what works there, and it doesn't say template 😉
I read that, I thought.. "Well, the template puts out a list, so..." 😂
So close... 😄
Just listed them all and.. IT WORKS! Thanks a lot @arctic sorrel
hi guys, how i can get this value on template.
[{'name': 'hacs/integration', 'display_name': 'HACS (Home Assistant Community Store)', 'installed version': '0.20.9', 'available version': '0.23.2'}]
i want to get HACS
I stopped here: {{states.sensor.hacs.attributes.repositories
i tried {{states.sensor.hacs.attributes.repositories.display_name}} but no sucess
Have a look here @thick cipher https://hacs.xyz/docs/basic/automation#updates-pending
@thick cipher 👋 long time no see!
whats the easiest way to compare the current time to a preset time of day? for example, I want to check if the current time is earlier than say 11pm of that day
now().hour < 23 ?
that would work
I have a speedtest running on a machine that report the measurements to hass through the web-api to sensors. The sensors dont exist upon startup of hass so when I reboot I got "sensor.download dont exist" in the GUI, so I created a template-sensor with a value_template of a constant (500). Is there a way that instead read out from the history and take the last measurement the sensor had before reboot?
@pseudo musk 🙂 Here I am 😉
sry... didn't know which one would be the best.
Just one more thing.. how do I get the 2h20 from my json to here: {% set hours = "2h20".split("h")[0] %}.
So atm it is just '{{ value_json.ProgramEnd.End}}' ... so I think it should be something like {% set hours = value_json.ProgramEnd.End.split("h")[0] %} but I think this is wrong 😦 Because .split is not part of the json string.
if value_json.ProgramEnd.End has the "2h20" like value in it, then yeah that should work
value_template: '{{ value_json.ProgramEnd.End}}' this results in 2h20 (or whatever time it is at the moment).
So I think I've to use some kind of brackets?
here, try this, slightly cleaner
value_template: >-
{% set hours, mins = value_json.ProgramEnd.End.split("h") %}
{% set totalseconds = (hours | int*60*60) + (mins|int*60) %}
{{ totalseconds }}
Error rendering template: UndefinedError: 'value_json' is undefined
lol
I'm idiot
give me a second
it works!!!!
😄
can skip a line like this shrug ```
value_template: >-
{% set hours, mins = value_json.ProgramEnd.End.split("h") %}
{{ (hours | int6060) + (mins|int*60) }}
this works too.
Now I just need to look how I will display the entity... because seconds are not so nice ^^
Is there a nice way to show a time entity on lovelace?
Time as in timer?
Never mind me. I can't raise my eyes more than a single line of text.
this will give you the end time
{{ (now() | as_timestamp() + ((hours | int*60*60) + (mins|int*60))) | timestamp_local }}
@pseudo musk where can I put that line?
as i understand I can put this in just as the last line? 🙂
do you have an idea too for that... If the machine isn't running .. the reqeust is empty value_json.ProgramEnd.End. = Unknown
Is there a way to just use another Word/string if this happen?
Is there a way to build a binary template sensor around events?
@pseudo musk got it... with device_class: timestamp on restful sensor.
Not just to find out how to filter if device is not running 😛
@final mulch use an if in the value_template
yes... I just didn't get how ^^^
But acutally I'm facing another issue -.-
@pseudo musk timestamp isn't displayed propper on iOS App 😦
i have to use timestamp_custom now it shows the time but wrong -.- (it shows utc instead of utc+01:00)
add , local_time=True) to your timestamp_custom call
I mean, it should be doing that already, but idk
i already tried... but this doesn't help
the strange thing is that it does work on Chrome@Win10 but not on iOS
might be something weird with the ios app, could try #ios_and_mac-archived 🙂
