#templates-archived
1 messages Β· Page 115 of 1
Ok
As it is I already have an input_select that gets populated with all installed weather. entities, and the user can select from that list. Trying to keep within Home Assistant standards so it will work w/ any installed provider
From the discussions I've seen you have already around this project, it sounds like a mammoth undertaking and would be very fragile to any changes in HA.
lol, tell me about it
I'd even go so far as to suggest that instead of wrapping HA in something else, you'd be better off just making your own system...

breaking changes are a constant problem, i've learned strategies to dance around them where possible
HA isn't anywhere near the point where you can just plug and play. Attempting to force that square shape into a circle hole is futile.
that's part of what i'm working on at the moment, i've hard-coded weather providers but that isn't tenable for long term use. so, better approach is to create a UI element allowing the user to select which installed provider to use
I looked where fahrenheit is used. seems that it is used in 3-4 regions in the world, so if you dont care for the few exception outside these zones where you will have mistakes you can get away with 4 ifs
so comparisons with latitude and longitude
even then that's dicey. my project is primarily targeted at north america due to changing workbox sizes around the world
so, if i say "within some radius from a central point in the US", i'll still have some part of canada and mexico being covered as F
I'd sooner just give them an input_select, which is probably where I'll need to go w/ this
Yeah then there wont be a good solution i think and you have the user to manually select it πββοΈ
just wanted to check in here to see if i was missing something obvious. thanks to the both of you for your attention and ideas!
@fossil totem I don't know why you don't just make a custom integration for your hasp project. You keep running into issues that can be solved with access to the backend. Make a custom integration via yaml or the UI. The configuration would 'create your plates' like you do with lovelace, instead use the integration. Then you can grab anything you want from every entity willy nilly.
probably because i'm dumb and also don't know python at all
but your point is well taken
Well, you can't be that dumb because you created the hasp project
It's definitely not a short term solution
I didn't know Python before I wrote a custom component π€·ββοΈ
well i'll take that as a compliment coming from you my man!
Yeah, the python for a custom component isn't too bad. All the hard stuff is out of the way. Plus you can plagiarize from other integrations. In the end, you'll have a bunch of entities and you can do whatever you want with them
that very thought occurred to me last night, i'll have to dig into some examples and take a look at what i'm up against
get a linter that screams at you all day
my "problem" is that i've been able to push packages + automations + templates pretty damn far, and it's for sure not the way any of that stuff was intended to be used
It would probably remove the complexity of your packages + automations. It might completely remove the need for all of that
my original thought was it would allow new users the ability to fully customize everything, after all, it's all just automations and if you use HASS it's not much to ask that you use automations
just food for thought
however, with some 4k lines of YAML in the automations as of now... that's become less and less user accessible so the original reason isn't really holding up
I feel like most people are already using hacs so the experience would be more enjoyable for them as well not having to see all of the guts
Yeah, youβd be surprised at how few python lines you would need to do them now as well
Hi everyone, I have a bearded dragon that gets fed every couple days but I always forget when I fed her last. I'd like to be able to log when I last fed her and and have a card on LoveLace that displays when I fed her last. I've messed around with date and input booleans but I can't figure out how to create a script that logs the date and time and applies it to a boolean. Any help is appreciated!!
https://www.home-assistant.io/lovelace/logbook/ you can show logs for an entity like this and then just figure out how you're going to do your state
maybe a Timer card? https://www.home-assistant.io/integrations/timer/
I'd go with a button that sets a datetime to whatever the current time is, and a template binary sensor that's 'true' when the datetime is on the current calendar day.
Alternatively, a template sensor that displays 'days since last feed'.
@analog coral βοΈ
Iβll give it a try, thank you everyone!!
I just set up a toggle boolean, and set that as the only entity in a logbook. Have a button that toggles the boolean and shows me when I last toggled it. Doesn't look pretty, but whatever! Thanks for the tips!
@deft timber sorry for my stupidity, i finally got it working. thank you.
how can i use your template as an automation condition? i don't mind using separate automations for each sensor.
https://pastebin.com/9WvgquC4
i tried this, but it didn't work.
i also tried the condition's value_template as simply {% if value_json.device == "1P7T3" %}, but that also didn't work. guessing because the one liner doesn't quality as a template.
I donβt understand what your are doing. You put what should be put in the mqtt sensor (as it was in my code) in condition of an automation...
Hi #templates-archived! I'm sure you can help me, but as a hass newb, I'm not sure if what I'm doing is right. I have a binary sensor and associated automation. The automation has an action with a light.<stuff>. But the thing is, I have some zigbee stuff and some wifi stuff, and the wifi stuff uses switch.<blah> not light.<blah> . Can the service_template include both light.<blah> and switch.<blah>? https://pastebin.com/wZfqidv8 is the code
just call 2 services
switch.turn_on and light.turn_on
if you're just turning the lights on and don't have extra attributes to pass to the devices, you can use 1 service and call homeassistant.turn_on
but, just remember, hass will turn on lights and switches 1 by 1, so calling 2 separate services is almost identical to calling homeassistant.turn_on
Yeah, lights on and off, so I could do homeassistant.turn_{{ trigger.to_state.state }}, put the two different things (light.ewelinkwhatever and switch.whatever) in entity_id, and sorted.
Thanks.
if you check out developer tools -> services page, you can see all available services
Also, this kind of question is a #automations-archived question
Very nice. Thanks for that. Re #automations-archived, I'm never sure where to ask. Since it was related to service_template, that's why I came here.
I'm 0-4 for guessing the right channel
It's a common problem don't worry. I'm always asking in wrong channel even when I try to read the chan descriptions :/
Hello All,
I want to create an Automation that has an MQTT Trigger and Light Service Action. What's the best way to construct this so that I can forward selected json mqtt payload values to the light action. I'm not sure how to construct the template and the ha service for the light includes on or off in its name (and not the data section) so how can i overcome this (maybe an if condition). Any ideas?
neither are we since there are 0 specifics
for example:
- platform: mqtt
topic: 'A/B/C/D/X'
action:
- service: light.turn_on
data:
entity_id: light.X
brightness: {{ mqtt.topic.payload - value_json:brightness}}
rgb_color: {{ mqtt.topic.payload - value_json:rgb}}```
the {{}} parts are made up and what i need some help with. thanks!
its trigger.payload
- platform: mqtt
topic: 'A/B/C/D/X'
action:
- service: light.turn_on
data:
entity_id: light.X
brightness: {{ trigger.payload - value_json:brightness}}
rgb_color: {{ trigger.payload - value_json:rgb}}```
... how about the json part ... maybe if someone could edit the rgb part correctly so I can see the format
im very new to templates and had a quick q. If I have a temperature sensor in my template that I am augmenting by adding 3 to it, is there a way to hide the original sensor from showing up in HA? I basically want to pretend the original sensor doesnt exist and use the templated sensor exclusively
if you hide it from HA you can't get its values so no
you need a data origin for the template
what kind of sensors do you have that don't support offsets?
i have a philips hue motion sensor
it's temperature sensor is not as accurate as i would like it to be
so i have found a percent offset that ive established by comparing its values to my ecobee thermostat's readings
have found it to be about 9% off
so i templated the following
{{ (states('sensor.bedroom_sensor_2cef6608_temperature') | float * 1.092) | round(1) }}
what integration is that coming from?
zha
wow zha doesn't have offsetting... thats too bad
err it might, im just too noobie
then you'll have to template each sensor into a new one
where would i find it in other integrations? maybe i can try digging around for it
zigbee2mqtt has support for it
any guides or youtube videos you recommend?
im early enough in my setup to be able to switch between zha and Z2M
zigbee2mqtt.io is the guide
youtube is just a collection of heavily outdated guides some of which might still work
is the offset only numerical or does it support percentages as well for Z2M?
hmm tried starting Z2M and it fails, does it need to be exclusively run or can it exist beside zha?
hey, when it says default: optimistic in the docs for a state template, doesn't that mean that it assumes the last set state?
it assumes whatever command was sent was successful
I'm looking at https://www.home-assistant.io/integrations/light.template/#level_template, where it says this, and I assumed this means the brightness attribute will always be the last set brightness
but my entity doesn't have a brightness attribute at all :/
you're kind of making no sense because noone knows what you're trying to do exactly
Alright. I have a template light, where I have services that I call when I set the brightness. Problem is, I can't set a specific brightness, only increase or decrease it. So I used an if-statement to check if the current brightness is lower or greater than the new (requested) brightness.
But that comparator doesn't work, because I can't access the current brightness attribute
does that make it clearer?
not at all
wow. okay, let me try again
Forget about whether you can currently see a brightness attribute for the light, since it seems you're wrapping the light in a template light to make it easier to control.
The light clearly understands the concept of brightness if you can ask it to increase/decrease it.
You just need to set up templated commands that achieve the desired end result.
But I want to be able to control it from e.g. the Android 11 Power Menu. Lights there have a brightness slider, but no buttons for increasing or decreasing the brightness
So I was trying to convert the brightness slider command/value into a increase/decrease command, by comparing the previously set brightness with the new one
does that make sense now?
My answer is still the same. #templates-archived message
The moment you use your template light for the first time, it'll have a 'brightness'. It might be wrong, since it can't know what brightness value the bulb actually has, but it's a point of reference and disproves your argument that you can't do it because it doesn't exist.
Your template then has to consider which brightness level has just been requested and perform some operation to reach that new level... sounds like this would be a number of increase/decrease steps, your template needs to figure out this number.
No doubt you'll have scripts in the mix too for the repeated calls to increase the brightness level.
Honestly though... get a better bulb.
That means nothing to me
it show's the attributes of my light. no brightness there...
okay nevermind I figured it out
The original light or the template light (for which you've shown no config)?
the optimistic stuff works, but I have to set the brightness manually for the first time...
there is no original light ^^
the original light would be an ESP8266 running a web server accepting REST commands :)
there is only this template light, calling different rest_command services as needed
So expose a REST command that allows you to set brightness π€·ββοΈ
You're trying to do this the hard way when easier options likely exist.
what I did was enter brightness: 50 inside that state attributes box from the screenshot and then everything worked, because now the attribute existed and the if inside the template didn't throw an error anymore
So basically what I said here? #templates-archived message
doesn't work. the light's controller doesn't support setting the brightness level :)
If that was an option, I would've done that of course
you said 'the moment I first use it'. I tried to use it by setting the brightness. that didn't work. I had to manually alter the state, which is different from what you suggested. :)
but yes, you were, in a way, right.
thanks for your help :)
continuing template discussion started in integrations:
looking at one of the samples in I think i am getting close to it here..
- platform: template
sensors:
ht_uptime:
friendly_name: 'hasstst uptime'
value_template: "{{ relative_time(states.binary_sensor.hasstst.last_changed) }}"
Am i on the right track here? I'm assuming the above will get uptime as well as down time
my yaml coding is very weak! π
Using states.xxxx should be avoided. Use instead the template below. The template specific parts you can always test under developer settings --> templates and type it in to see if you get the right output
value_template: >
{% set state= state_attr('binary_sensor.hasstst','last_changed') %}
{{ relative_time( states ) }}
This is only for the template part, the creating template sensor part i have never done
@unreal salmon posted a code wall, it is moved here --> https://paste.ubuntu.com/p/2KmgfY4tvd/
Good evening all. Can I ask some question about templates with time formats π ?
I want to set a different time depending the season ( summer , winter ,etc )
This is set time is then used for different triggers.
But I'm not sure if I am doing it the right way. Or if it is even allowed likes this
value_template: >-
{% if is_state('sensor.season', 'spring') or is_state('sensor.season', 'summer') %}
'07:00:00'
{% elif is_state('sensor.season', 'autumn') or is_state('sensor.season', 'winter') %}
'06:00:00'
{% endif %}
I then want to use that template sensor value in this next template trigger:
or
states('sensor.time') == ((state_attr('input_datetime.uv_lamp_uit', 'timestamp') + (15*60)) | int | timestamp_custom('%H:%M', False)) }}"
But template trigger doesnt like the template sensor....
Remark : The last code snipped is how it currently is functioning
But what I want is that the input_datime.uv_lamp_aan is not static time like I have t now.
But it should vary depending on the season which we re in.
It doesn't like it, huh? What does it think about pineapple on pizza?
Your first template is more complicated than it has to be:
value_template: >-
{% if is_state('sensor.season', 'spring') or is_state('sensor.season', 'summer') %}
'07:00:00'
{% else %}
'06:00:00'
{% endif %}```
And if you copy/pasted that exactly, there's an error in your indentation on the last line.
Agreed !
I'll post my template value code which I used to check the outcome for what the calculated time should be
First, explain the error. 'it doesn't like it' doesn't help.
Yea sorry hehe
I tried this
Giving me this error back
TypeError: unsupported operand type(s) for -: 'str' and 'int'
You're trying to perform integer maths on a string and an integer:
(states('sensor.uv_lamp_aan' ) - (15*60))
You need to cast the string to an integer first:
(states('sensor.uv_lamp_aan' ) | int - (15*60))
Ok will that still work for the time trigger than?
Returns the value -900
Then whatever states('sensor.uv_lamp_aan' ) returns isn't a number. What is it?
Yes... you didn't say what that first template sensor was called π
It would be easier if you just made that value a number so you don't have to convert to a timestamp.
oeps that wasnt in the snipped...
{% if is_state('sensor.season', 'spring') or is_state('sensor.season', 'summer') %}
25200
{% else %}
21600
{% endif %}```
If you don't need to 'read' the value anywhere, just skip a conversion.
Not really needed but would be nice and understandable for in the future hehe
Also all my other triggers are based on timestamps so I would need to edit all those as wel
Instead of only replacing the input_datetime to a different sensor
If it's not visible, use the number of seconds. It makes everything else simple.
When you want to make it visible, there are other solutions in the UI.
Inside? No...
wutdefook
What are you trying to do?
If you mean like this, it would return the 'comment' too:
value_template: >-
{% if is_state('sensor.season', 'spring') or is_state('sensor.season', 'summer') %}
25200 # 7 hours
{% else %}
21600 # 6 hours
{% endif %}```
Hahah
It doesnt turn green commented in visual studio code
value_template: >-
{% if is_state('sensor.season', 'spring') or is_state('sensor.season', 'summer') %}
# 25200 = 07:00 uur
25200
Yeah, cos it's inside a Jinja template. You're telling it to return all of the stuff between the curly braces.
If you want to comment your code, put it on the line before value_template:
Ok so your option wont make it a comment part aswel?
I see what you are on about , checking it in the template editor returns the commented section aswell.
And how to reform this template trigger with the new given sensor which has an INT as value?
"{{ states('sensor.time') == ((state_attr('input_datetime.uv_lamp_aan', 'timestamp') - (15*60)) | int | timestamp_custom('%H:%M', False))
I dont have sensor which returns the time in an INT value ?
This answer to this part is still the same... you need to cast to an integer:
(state_attr('input_datetime.uv_lamp_aan', 'timestamp') | int
Although, you set the template sensor to a number already, so just this:
(states('input_datetime.uv_lamp_aan') | int
'input_datetime.uv_lamp_aan' would than be replaced by sensor.uv_lamp_aan' with an INT Vlaue
Ok , but looking at my entities the sensor.time returns the actual time in XX:XX
This isnt used by the template part than?
Everything in your template is used. Test it in Dev Tools and see what it does.
value_template: "{{ states('sensor.time') == ((states('sensor.uv_lamp_aan') | int - (15*60)) | int | timestamp_custom('%H:%M', False)) }}
This returns 'false' at this moment. So I guess that might do the trick
It could return false for a number of reasons π
I know hahaha
So you want it to equal true when it's exactly 900 seconds before the other sensor?
Yea
What format is the state for sensor.time?
sensor.time 22:19 friendly_name: Time
icon: mdi:clock
Yeah, so you'll have to make that into a timestamp too...
I think this is the standard time sensor within HA
Yes. You're writing a template, you can convert things π
as_timestamp(states('sensor.time'))
HAhah
thanks @vocal linden , That example helps alot!
@ivory delta think I will be going for a different approach then. Will be using a automation to set the input datetime difderntly
back again. I currently the following for the value_template:
- platform: template
sensors:
ht_uptime:
friendly_name: 'hasstst uptime'
value_template: >
{% set state= state_attr('binary_sensor.hasstst','last_changed') %}
{{ relative_time( states ) }}
and I am getting a result showing as <template AllStates> . I was hoping I would get a numeric value indicating the uptime. Any ideas?
Is it possible that would be the result since binary_sensor.hasstst hasn't changed?
You included the typo π
{{ relative_time( state ) }}
You're setting a variable called state in the first half.
I'm trying to create a rest sensor for the following URL
https://api.coronavirus.data.gov.uk/v1/data?filters=areaType=nation;areaName=england&structure={"date":"date","cumPeopleReceivingFirstDose":"cumPeopleReceivingFirstDose"}
- platform: rest resource: https://api.coronavirus.data.gov.uk/v1/data?filters=areaType=nation;areaName=england&structure={%22date%22:%22date%22,%22cumPeopleReceivingFirstDose%22:%22cumPeopleReceivingFirstDose%22} name: Vaccination Rest Test scan_interval: 3600 json_attributes: - date - cumPeopleReceivingFirstDose value_template: '{{ value_json.cumPeopleReceivingFirstDose }}'
but it's just returning nothing. I'm clearly doing something wrong (never done this before) but not sure what.
maybe you can do it via scrape integration to obtain that value
maybe, I can try that
{{ value_json['data'][0]['cumPeopleReceivingFirstDose'] }}
this returns the figure I'm looking for. woop
with rest ?
hi guys got sent over by Tinkerer in automation
trying to work out a template that fits the following
platform: mqtt
topic: tele/tasmota_765905/SENSOR
payload: '{{ ''"PAJ7620":{"Up"'' in trigger.payload }}'
This is the MQTT message
10:11:58 MQT: tele/tasmota_765905/SENSOR = {"Time":"2021-01-11T10:11:58","ANALOG":{"Illuminance":62},"DHT11":{"Temperature":33.5,"Humidity":19.0,"DewPoint":6.7},"PAJ7620":{"Up":2},"TempUnit":"C"}
10:12:02 MQT: tele/tasmota_765905/SENSOR = {"Time":"2021-01-11T10:12:02","ANALOG":{"Illuminance":61},"DHT11":{"Temperature":33.5,"Humidity":19.0,"DewPoint":6.7},"PAJ7620":{"Up":3},"TempUnit":"C"}
the PAJ7620 actually counts up with each consecutive swipe in the same direction.
at least in the tasmota implementation
why do you need to keep that number in a sensor?
how long does tasmota keep that value?
yeah
my json was just completely wrong, but i'm glad i dug in as it makes more sense to me now!
@jagged obsidian until you swipe in a different direction
might be simpler to build 4 different sensors for each direction
also has near and far, and the newer version of the sensor does clockwise and counter clockwise gestures
happy to do multiple sensors
my issue is how
regular mqtt sensor with value_template being {{ value_json['PAJ7620'].Up }}
ive tried binary and normal sensors but my templating is so bad i wouldn't know if it was my yaml or the json breaking it
sensor:
- platform: mqtt
state_topic: tele/tasmota_765905/SENSOR
value_template: {{ value_json['PAJ7620'].Up }}
???
look at mine
- platform: mqtt
name: "Energy Today"
state_topic: "tele/tasmota/SENSOR"
value_template: '{{ value_json["ENERGY"]["Today"] }}'
unit_of_measurement: "kWh"
it looks to me like value_json would return 1 or 2 etc...
so i would have to trigger the automation on a value of 1 or greater?
i don't know what you're triggering and why
if you want to trigger an automation do a simple mqtt trigger
swipe up and light turns on
with the template Tinkerer provided
unfortunately neither
platform: mqtt
topic: tele/tasmota_765905/SENSOR
payload: '{{ ''"PAJ7620":{"Up"'' in trigger.payload }}'
or
platform: mqtt
topic: tele/tasmota_765905/SENSOR/PAJ7620
payload: '{{ ''"Up"'' in trigger.payload }}'
seam to work
yes because that needs to be the condition
condition: template
value_template: '{{ '"Up"' in trigger.payload }}'
condition: template
value_template: '{{ ''"PAJ7620":{"Up"'' in trigger.payload }}'
Worked. So much thanks.
Hello! Can somebody help me with a "thing"? I want to publish a json value that includes 2 sensor values. I am using this in an automation, and things look something like this(part of it)? ```{% if targetTemp1|float > currentTemp1|float and window1 == 'off' %}
{% set result1 = targetTemp1 %}
{% endif %}
{% if result1 == [result1|float, result2|float]|min and result1 < 30 %}
{% set result = "{"ST":"targetTemp1", "CT":"currentTemp1|float"}" %}"
{% else %}
{% set result = 1.0, 20.0 %}
{% endif %}
{% endif %}
{{ result }}
I would like the result to be a json value(set result line), BUT at the moment I get exact text in the result, where as I want the values of targetTemp1 and currentTemp1 to be displayed.
Everything before this is set correctly, as I can get a string result, but when formatting json value I do not get the desired result.
I do not know how to format that line.
Just return a dict.
me || programming languages.
I do not know what you are saying π
I see it is a thing in python, I am searching more
@ivory delta , if you have a very short example how to return a dictionary, maybe I could edit it to fit my needs. Thank you.
Generally, don't tag people to ask for help - it comes across as bad manners, youβre demanding somebody answers you. Itβs different if youβre thanking somebody, obviously. If you do tag somebody keep it polite and respectful. Remember that everybody is a volunteer, and nobody has to help you, and people may block you.
Similarly, please donβt DM (direct message) people asking for help. It also comes across as demanding, and means that others canβt learn from what you do.
Finally, please keep tagging people in replies to a minimum. That too can become annoying very quickly and should be used only when it's necessary (such as if it's been a long time, or there's multiple conversations going on).
ok.
{% set result = {"ST": 1.0, "CT": 20.0} %} ? π
I need it to dislay the valuues foiund in targetTemp1 and currentTemp1
and {% set result = {"ST":targetTemp1|float , "CT":currentTemp1|float} %}"
greetings! Continuing my exploration of the uptime calculation from yesterday, I am now getting an Unknown value for the uptime. I am guessing it is because there hasn't been a change in the value being checked at HA startup. Here is my current value template:
value_template: >
{% set state= state_attr('binary_sensor.hasstst','last_changed') %}
{{ relative_time( state ) }}
I think what i need is to add an or clause to the set state portion when HA starts up. I am looking at the page https://www.home-assistant.io/integrations/template#startup , and I think this is what is happening to make it an Unknown value. Any ideas?
you can't access to last_changed using state_attr. You have to use states.binary_sensor.hasstst.last_changed
according to one of the people yesterday, the state_attr function was the preferable way to get info, and that states should be avoided... Yesterday at 1:13pm this post was added...
Using states.xxxx should be avoided. Use instead the template below. The template specific parts you can always test under developer settings --> templates and type it in to see if you get the right output
value_template: >
{% set state= state_attr('binary_sensor.hasstst','last_changed') %}
{{ relative_time( state ) }}
which way is correct? or is both correct?
Navigate to dev tool --> templates and copy the template part (only the ones with the braces) into it (you may have to activate advanced user mode under your profile if you havent yet). There you should see which of both ways are working and you can tinker around it π As a frist step you can remove there the relative_time part and see if it prints out an value or it prints "None"
last_changed is not an attribute. You indeed should use state_attr for attributes, but last_changed is not one.
just test it in the dev tool, and you will be convinced π
Oh thought last_changed was an attribute
interesting.. I have the output from the template editor on develope tools, and i get the following:
{% set state= states.binary_sensor.hasstst.last_changed %}
using the state. version: {{ state }}
uptime value: {{ relative_time( state ) }}
{% set state= state_attr('binary_sensor.hasstst','last_changed') %}
using the state_attr version: {{ state }}
uptime value: {{ relative_time( state ) }}
Results:
using the state. version: 2021-01-11 12:38:44.276852+00:00
uptime value: 5 hours
using the state_attr version: None
uptime value: None
The states. is what gives good data.
thanks both of you!
I have the states.version now in my configuration.yaml, and the uptime is working correctly
I now Understand what the attributes are versus states! ( I think ) . looks like as an example, for thermostats , all of the temperatures, modes, presets, etc are attributes, and states are HA metadata for the object.
basically entities can have one and only one state. But through attributes, they can expose out other properties that are useful to help expand on that state
so in the example above, last_changed can only be accessed by using
states.binary_sensor.hasstst.last_changed
maybe it is the word states that is confusing me in lieu of state. Is there only one state, but there can be many states?
maybe i am getting wrapped around an axle with terminology?
states is the entire states object that HA tracks (all domains). states.binary_sensor would represent the entire domain binary_sensor. states.binary_sensor.hasstst represents a single state object.
It's a data structure. Using that dot notation to navigate one level deeper by name just means you're accessing a specific part of that data structure.
Think of it like the folders on your hard drive. C:\Users\jr3us\Pictures isn't a place, it's instructions to reach a place.
ok. I think i understand now. when using states.sensor.entity.field would let you get the individual fields in the states table of the db then for that entity, or is there more?
Well... that depends π
states.domain.entity_name.state is the state.
states.domain.entity_name.attributes is the attributes (so you can drill one level deeper to get the specific attribute).
Then you have funky stuff like states.domain.entity_name.last_changed which is neither state not attributes.
The funky stuff isn't documented well but everything else is here: https://www.home-assistant.io/docs/configuration/state_object/
Ah, I lie. The funky stuff is there too.
π thanks!
guys am experiencing wired things with templates. please someone explain. i will provide the code and the results. sometimes it is accurate sometimes not.
{{ states|selectattr('entity_id','in',state_attr('group.powder_reffs','entity_id'))|selectattr('state','<','24' )|selectattr('state','!=','unknown' )|list}}
result:
[<template TemplateState(<state sensor.h10=26.57; unit_of_measurement=Β°C, friendly_name=H10 @ 2021-01-12T03:11:56.365172+08:00>)>, <template TemplateState(<state sensor.h11=26.42; unit_of_measurement=Β°C, friendly_name=H11 @ 2021-01-12T03:34:02.633711+08:00>)>, <template TemplateState(<state sensor.h12=26.32; unit_of_measurement=Β°C, friendly_name=H12 @ 2021-01-12T03:04:44.227730+08:00>)>, <template TemplateState(<state sensor.h13=4.6; unit_of_measurement=Β°C, friendly_name=H13 @ 2021-01-12T03:33:56.509913+08:00>)>, <template TemplateState(<state sensor.h16=3.48; unit_of_measurement=Β°C, friendly_name=H16 @ 2021-01-12T03:32:20.079499+08:00>)>, <template TemplateState(<state sensor.h2=3.11; unit_of_measurement=Β°C, friendly_name=H2 @ 2021-01-12T03:33:09.864162+08:00>)>, <template TemplateState(<state sensor.h4=3.14; unit_of_measurement=Β°C, friendly_name=H4 @ 2021-01-12T03:33:42.584087+08:00>)>, <template TemplateState(<state sensor.h8=3.74; unit_of_measurement=Β°C, friendly_name=H8 @ 2021-01-12T03:30:39.266513+08:00>)>, <template TemplateState(<state sensor.h9=26.69; unit_of_measurement=Β°C, friendly_name=H9 @ 2021-01-12T03:14:05.521887+08:00>)>]
as you observe H4, H16, H 2 , H18 and H8, should not be included
|selectattr('state','<','24' )
String comparison π€’
You could try this but it might fail because you're not casting the string to a float first:
|selectattr('state','<', 24 )
how can i do that ?
Try that one first, then we'll see
it looks the same to me .. wheres the difference ?
And string comparisons are dirty. Is 'three' less than 'one'? Is 'tree' less than 'toffee'?
haha
They're not the same. '24' isn't 24
One is a string, one is a number π And comparing strings is tricky in most languages... they don't work the way a human brain thinks π
i remember i tried this before
TemplateSyntaxError: expected token 'name', got '|' this is what i got
Then you have another error somewhere. Share the template that gives that error.
sorry my bad
TypeError: '<' not supported between instances of 'str' and 'int'
i had an extra |
this is the real error
This is the next thing I was worried about
we need to specify somehow that it is float ?
Somehow π I don't know how
the error clearly says whats happening lol .. but what to do haha
hi, im trying to convert a value in seconds to a day,hours,minutes,seconds value, i've read about relative_time
but it's still give me the initial value
{{ time }} // output: 781.2417459487915
{{ relative_time(time) }} // still output: 781.2417459487915
@ivory delta is there a way or this is an exploit\ limitation π ?
No need to tag. I'm thinking.
str with int error, convert the string value to int before doing the math operation
{% your_value_str | int %}
We know this. Just need to do it inside a Jinja test.
ok sorry
what's the challenge?
What information do you want from the template, Shant? A list of entities or just a list of values?
actually i wane count thats my target and i am able i just listed it so we can understand
i wanne count number of reffs above 24 for example or below 0
etc
Just counting should be easier...
yeah but the numbers didnt make sense thats why i listed ..
this is how i counted {{ states|selectattr('entity_id','in',state_attr('group.powder_reffs','entity_id'))|selectattr('state','>', '24' ) | list | count}}
Ah, I don't understand Jinja docs π
hehe
phnx will know this one... how do you perform integer comparison here?
|selectattr('state','>', 24)
Well, or float...
need to map it first i think
Ah, I'm getting there now...
Something like this?
| map(attribute='state') | int | select('lt', 24)
Shant - give this a try, let me know if there are errors:
{{ states|selectattr('entity_id','in',state_attr('group.powder_reffs','entity_id'))| map(attribute='state') | int | select('lt', 24) | list | count}}
ok
so relative_time only works with the 'last_updated' value from sensors right ?
yeah, this is what i have
{{ states.sensor|selectattr('entity_id', 'in', sensors)|map(attribute='state')|map('float')|select('gt', 70.0)|list }}```
@ivory delta i did the no errors.. results is 0 . but how can i say greater or less ?
That's what this bit is for: | select('lt', 24)
oh ok
Ah... you want greater than? | select('gt', 24)
less then greater than
worsk like magic!
Thanks you gentlemen you did it
β€οΈ
@ivory delta @dreamy sinew β€οΈ β€οΈ β€οΈ β€οΈ β€οΈ
Didn't need (much) help from phnx in the end π
too bad you can't do both those maps as one π¦
Yeah. I wondered about doing something like selectattr(float('state') > 24) but that's not valid syntax.
Would've been so handy to do it in one step.
but yeah, you were most of the way there
map is really handy but i usually forget about it
looks like anything "unknown" its listing it as 0.0
yup
which will add as a count now i can subtract it ...
or you can reject it out
but how to exculude it.
{{ states.sensor|selectattr('entity_id', 'in', sensors)|rejectattr('state', 'in', ['unavailable', 'unknown'])|map(attribute='state')|map('float')|list }}
or for slightly less text
cool ! β€οΈ
ima try
{{ states|selectattr('entity_id','in',state_attr('group.powder_reffs','entity_id'))|map(attribute='state')|reject('in', ['unavailable', 'unknown'])|map('float')|select('lt', 1 )| list | count}} Working
β€οΈ
(trigger.entity_id == sensor.harmony_hub and trigger.to_state.state != 'Playstation 4') or (trigger.entity_id == binary_sensor.ps4 and trigger.to_state.state == 'off')
i want to check that expression but get no output
{{ trigger.entity_id }} = sensor.harmony_hub and {{ trigger.to_state.state }} = off
i cant find my fault here
https://pastebin.com/5XdytcZt
this is the full service call. script.ps4_on does work as expected
i dont know if you saw that but the logic expression is in an if condition
hi, quick question: what's the syntax for a light template to make multiple service calls? ie:
lights:
test_virtual_light:
turn_on:
service: #SERVICE CALL 1
service: #SERVICE CALL 2```
nvmd, sorted
You need to quote entity ids as well: trigger.entity_id == 'sensor.harmony_hub' You probably have a bunch of errors in your log that look like "Cannot read property harmony_hub of undefined"
Also without an else clause, it's possible that you would end up calling "script.ps4_" which I doubt exists in your case?
Is it possible to create a template/condition that could filter triggers so that only triggers from a certain domain are acted upon? e.g. if trigger domain=device_tracker then true?
yup, you are right. I got it working
@quiet lagoon are you talking about a state trigger? You could create an event trigger on the event state_change, and in the condition, get the entity that triggers the event and test its domain in a template
- platform: rest
resource: http://www.meteoromania.ro/wp-json/meteoapi/v2/starea-vremii
name: bucmeteo
scan_interval: 3600
json_attributes_path: "$.[134]"
value_template: '{{ "$.[134].properties" }}'
This template does not listen for any events and will not update automatically.
π¦
You got the value_template wrong, that's not how I said to do it π
'{{ value_json[134].properties }}'
It doesn't use JSON Path syntax for value_template, only for json_attributes_path.
And remember that properties is still a really big object in your example, so you may still go over the 255 character limit for state.
UndefinedError: 'value_json' is undefined
Where are you seeing that? It should work fine in the sensor - it won't work in the Dev Tools.
It's a variable. It's only present inside the sensor itself. Like how trigger is only available inside an automation.
oki
If you want to test a variable in Dev Tools, do something like this to 'fake' the data first: https://paste.ubuntu.com/p/9hPVB5666k/
ok...so in my template i should write down level to properties
to not exceed 255
although this value i don't like it : "actualizat": "12-01-2021Β oraΒ 14:00",
If the sensor represents weather, I would make the state the current weather condition (rain, sun, etc).
The attributes give you all the extra detail.
u are right. maybe extra details are not needed
just wanted to remove external integrations and put a local source for weather
but ofr this i must put 10 value templates π¦
No...
value_template is how it finds the state. The rest should still be okay to find the attributes.
But I have to work again now, good luck.
Hello templates folks - what's the best way to debug / test value returns? I'm looking for something that allows me to experiment with a bunch, and ideally not have to keep validating/restarting configs until I'm pretty much where I want to be
what I have in mind is to build something that uses the hourly weather forecast to pick (and notify) the best time to when to air the rooms. But as this can be a complex problem, I'm expecting a lot of false roads in this
checking, thanks
- platform: rest
resource: http://www.meteoromania.ro/wp-json/meteoapi/v2/starea-vremii
name: bucmeteo
scan_interval: 3600
json_attributes_path: "$.[134]"
value_template: '{{ value_json[134].properties.fenomen_e }}'
but still cannot obtain value from the site
Yes, I want to trigger off the device_registry but only those from the device_tracker domain.
What I am not sure is how to test a trigger to create a condition and check for the device_tracker domain.
To be tested```yaml
trigger:
- platform: event
event: state_change
condition: "{{trigger.event.data.entity_id.split('.')[0] == 'device_tracker' }}"
action:
...
or {{ 'device_tracker.' in trigger.event.data.entity_id }}
hey ho,
maybe someone could help me. i cant get my template automation to work.
even less template'isch does not help.
i send an mqtt message with { "state": "on", "brightness": "128"} and want to turn my light on. but my automation does not get triggered.
https://paste.ubuntu.com/p/fTHgcgPjMr/
what am i missing?
Hey, same question here: I fiddling around with a template which should render multiple entity_id's based on input_boolean's. In the gist are two tries (input and output). The second gist contains the error
https://gist.github.com/Lyr3x/fe5980e91014c94a104dca33514488e3
https://gist.github.com/Lyr3x/1609e5013f7af63713a90d4c262dc000
Hopefully anyone can give me a good hint π
do you have multiple input bools you're looking at?
oh i see. input_bool.vaxerN_active or something
exactly. and vaexerN should render a switch.vaexerN if the boolean is on.
{% set inputs = states.input_boolean|selectattr('state', 'eq', 'off')|map(attribute='entity_id') %}
{% for input in inputs if 'vaexer' in input and input.endswith('active') %}
{% set ns.switches = ns.switches + ['switch.{}'.format(input.split('.')[-1])] %}
{% endfor %}
{{ ns.switches }}```
oh, flip the off to on in the select up there
i flipped it for my local testing
Looks nearly good, but how can trim the "active" part? switch.vaexer1_active without active π
{% set ns = namespace(switches=[]) %}
{% set inputs = states.input_boolean|selectattr('state', 'eq', 'on')|map(attribute='entity_id') %}
{% for input in inputs if 'vaexer' in input and input.endswith('active') %}
{% set ns.switches = ns.switches + ['switch.{}'.format(input.split('.')[-1]).split('_')[0]] %}
{% endfor %}
{{ ns.switches }}
Thank you very much π
would be this the correct template "{{ payload_json.state | lower == 'on' }}"?
for
{
"state": "on"
}
shouldn't need to lower it
in that case. yea.
i dont get it.
i try to debug my code from a few posts above.
trigger:
- platform: mqtt
topic: homeassistant/indoor/light/livingroom/ceiling_light/set
payload: '"{{ payload_json.state | lower == ''on'' }}"'
action:
- type: turn_on
device_id: adfd634395eb93cbe8bac3ba003541aa
entity_id: light.livingroom_ceiling_light
domain: light
step by step. but i think i even dont get the trigger definition right
what are you trying to get out of the payload?
that would render as "True" or "False"
atm i try to turn the light on if i publisch the state json.
i don't know enough about mqtt to know what you would need
that probably isn't correct though
originally i try to template my light automation.
not sure where payload_json is coming from either
on on mqtt side i got:
homeassistant/indoor/light/livingroom/ceiling_light/set
{
"state": "on",
"brightness": "128"
}
that schould pass the filter:
condition:
- condition: template
value_template: "{{ trigger.topic.split('/')[4] == 'set' }}"
- condition: template
value_template: "{{ trigger.payload_json.state | lower == 'on' }}"
- condition: template
value_template: "{% if trigger.payload_json.brightness is defined %}True{% else %}False{% endif %}"
to trigger the action:
action:
- service_template: "light.turn_{{ trigger.payload_json.state | lower }}"
data_template:
entity_id: "{{ trigger.topic.split('/')[2] }}.{{ trigger.topic.split('/')[3] }}_{{ trigger.topic.split('/')[4] }}"
brightness: "{{ trigger.payload_json.brightness }}"
developer tools i got it working by using "{% if "{{ trigger.payload_json.brightness }}" is defined %}True{% else %}False{% endif %}"
the configuration parse failed with that
these values (payload) is inside my mqtt message
but as i said. schould pass...
it does not trigger my automation.
Is there any chance to customize entity decimals number without creating new entity with template?
What sort of template would I need to use to enumerate through sensors and return a nicely formatted string of sensors that are still "on"?
E.g. "The laundry door, office window, and back door are still open."
Was thinking of using append when iterating through a manual list, but looks like append isn't allowed with HA.
Here's the start of what I have:
{% for sensor in sensors -%}
{%- if states(sensor) == 'on' %}{{ state_attr(sensor,'friendly_name') | lower }} {% endif -%}
{%- endfor %}```
The weather example in the demo template doesn't work, because not every entity should trigger the loop.first or loop.last condition (hence me trying to create a new list and append affected sensors).
When building a template called x with a template attribute y, is there a way to refer to attribute y inside this template by saying something like self.attribute.y instead of using state_attr('sensor.x', 'y')
is it possible to have a name of a button card with template. for example: button card name of a motion sensor changes depending on motion status? ({% if is_state('binary_sensor.hue_motion_sensor', 'on') %} open {% else %} closed {% endif %})
@ruby peak As well as the bits in the topic, you'll want to understand this: https://www.home-assistant.io/docs/configuration/state_object/. It describes the fields available on a state object, some of which don't have helper functions available.
OK. Will have to get my head around this as not sure how to implement it yet. I can see on a trigger, i can get the duration on the input_boolean, but not on a condition
Would I just have a template item, call it time since awake and then return the duration in there
morning. my dumb air conditioner wnet smart...but still doesn't want to cooperate with me π i want to see how much time is on and history stats doesn't return any graph. where i go wrong ? https://pastebin.ubuntu.com/p/9HvzBkTjsX/
is there a way to get the last_updated value of an input boolean?
{{ state_attr('input_boolean.greg_is_awake','last_updated')}} doesn't seem to work
ah, got a relative time {{relative_time(states.input_boolean.greg_is_awake.last_changed)}} but I trying to get it just as a number so I can do a condition if >= **template**
you can then use as_timestamp, which will convert time in second, and compare it with as_timestamp(now())
{{ as_timestamp(now()) - as_timestamp(states.input_boolean.greg_is_awake.last_changed) }}like that?
yes
hmm, any way to get that to the actual hours though? Thats coming back as 10665.243483781815 but its been 3 hours in relative_time
If you want the value of aer_azi to appear on a graph, you have to give a unit_of_measurement
https://www.home-assistant.io/integrations/template/#unit_of_measurement
thank you
thats now giving me 1610093123 π€£
{{ (as_timestamp(now()) - as_timestamp(states.input_boolean.greg_is_awake.last_changed)/60/60) | round }}
cannot give an unit of measurement for binary sensor
your parenthesis are wrong
{{ ((as_timestamp(now()) - as_timestamp(states.input_boolean.greg_is_awake.last_changed))/60/60) | round }}
aer_azi is not a binary_sensor ?!
binary sensor is conditioner_on
I was talking about aer_azi
It doesn't matter what the source is, that's just a regular sensor.
it is confusing, you have 2 aer_azi, as an history_stats and and a sensor π
ok..so the flow is... binary sensor template - history stats sensor - converting view for glance
and i give another name for conversion to hh:mm
and the graph is made based on which one?
on conditioner_on
i want to see how many hours my air conditioner was on π
well...i restarted after changinc name in glance card an i have a value, but not in history
it is not pretty but could you try creating a template sensor, with unit_of_measurement set, and just return the state of your conditioner_on ? and check if that one is appearing on a graph ?
not sure i follow
so give up to sensor from history stats and create a pure one
then display it on graph card
no, keep the existing one, create e new one that will just get the value from the history stat sensor, so the 2 sensors will have the same value, the idea is just to check if HA will display the template sensor in a graph
- platform: template
sensors:
sensair:
friendly_name: "Diferenta temperatura"
value_template: >
{{ (states('sensor.conditioner_on)
something like that?
yes, don't forget unit_of_measurement
Invalid config for [sensor.template]: invalid template (TemplateSyntaxError: unexpected char "'" at 11) for dictionary value @ data['sensors']['sensair']['value_template']. Got "{{ (states('sensor.conditioner_on)". (See ?, line ?).
pf...somebody ate }}
- platform: template
sensors:
sensair:
friendly_name: "Diferenta temperatura"
value_template: >
{{ states('sensor.conditioner_on') }}
unit_of_measurement: hours
ok....but not so ok. gauge shows 0.32 hours and glance 0.54
in gauge i put newly sensor
maybe 0.32 hours are 32 minutes and 0.54 are hours
exactly
You're welcome
don't know where to ask... how can i record the value for the sensor before it get reseted and to track it monthly?
what you could try is to
- create a sensor to store your data, a template sensor that gets the state of your sensor to follow,
- configure the sensor to not refresh manually (very high scan_interval),
- create an automation that will refresh your above sensor to run just before the reset
- potentially create a utility_meter https://www.home-assistant.io/integrations/utility_meter sensor to keep track of it
so if sensor adds at 24h, then i create a new sensor that is called collector and scan_interval 87000 (to exceed 86400 seconds/day) and an automation to refresh this at 23:59:58 then a utility meter
I don't now if the scan interval resets after a manual refresh so I suggest you use 315360000 which is, if I'm not mistaking, the biggest value you can set
i see. for the moment i will wait for pass this day to see that sensor is refreshed at midnight π
and store the conversation
how do i put an and statement in this one liner
{% if value_json.device == "1P7U5" %}
so both have to be true for processing.
just with and {% if value_json.device == "1P7U5" and xxx == "abc" %}
I'm converting a date to string on HASSOS, but it's using the US names for the month names. Is there a way for me to change the used locale?
I don't think there is
i have a value coming from a template sensor written like : 13-01-2021Β oraΒ 16:00 .... can i hide that &nsbp ?
{{ '13-01-2021 ora 16:00' | regex_replace(" ","")}} to remove the
how can i customize the a sensor's "Unknown" status to say something else instead?
Or {{ '13-01-2021 ora 16:00' | regex_replace(" "," ")}} to replace it by a space
- platform: template
sensors:
actualizat:
friendly_name: Actualizat
value_template: '{{ states.sensor.buc_meteo.attributes["actualizat"]}}'
and i put after | regex
'{{ states.sensor.buc_meteo.attributes["actualizat"] | regex_replace(" ","")}}' then
maybe u can share some paypal or anything π
π
I think you need to use a new sensor. Value would be
{{ "Whatever you want" if states('sensor.your_entity') == "Unknown" else states('sensor.your_entity') }}
@bright quarry
{{ "My other value" if state == "unknown" else state }}```
Or that π
both are functionally the same
where does that go?
as a template sensor
in a new template sensor
can i have separate, multiple template sensors that all address the same sensor name?
you can
man i don't even know how to write a template sensor.
example a bit above #templates-archived message
patience egon... i annoyed 2 guys and 7 days of trials before to have a clue about template π π
π€¦ββοΈ so they are
@dreamy sinew
{% set state = states('sensor.justin_east_window') %}
can i comma separate multiple sensors there to do more than one or does it not work that way?
Doesn't work that way
rats
what do you want to do exactly? You can create an array of values if you want to
i have like 15 sensors i want to change "unknown" to say something else, like "n/a"
like that:
{% set state = [states('sensor.justin_east_window') , states('sensor.justin_west_window')] %}
ok you need to create 15 sensors then
wait, value template can have tons of stuff, right?
Why bother though?
i already have a value template for this sensor that has some if/else statements, can i just put
{% set state = states('sensor.justin_east_window') %}
{{ "N/A" if state == "unknown" else state }}``` under it in the "value template" area?
I don't think you understand how it works. You can't change the value of a sensor. What we propose to you is to create a new sensor
not to create a template sensor to change the state of the original sensor
unless whatever he's doing is coming from something that's already a template
.share the full thing
Please use https://paste.ubuntu.com/ or https://www.hastebin.com/ to share code or logs.
yes of course
this takes some mqtt message of a door/window sensor and makes sensors out of the time it was triggered
so you're referencing the state of a sensor within itself
probably why you get unknown
but i just think "unknown" doesn't look as neat as just a null/empty string when viewed in my frontend
or "n/a"
you can't just like..define something in the card configuration that does this?
I guess you can with a custom card or so (see #frontend-archived)
christ, no changing system locale with hassos?
I'll drag in some python to create a non-US datetime string then
well....unfortunately us datetime bothers me especially on grafana, but nothing to avoid it
how do i get the following to work:
from entity_id: light.livingroom_ceiling_light to topic: homeassistant/indoor/light/livingroom/ceiling_light
trigger:
- platform: device
[...] ## useless informations
condition: []
action:
- service: mqtt.publish
data_template:
topic: "{{ 'homeassistant/indoor/' + entity_id.replace( '.' , '/' ).replace( '_' , '/', 1 ) }}"
payload: 'ON'
according to jinja2 syntax is this correct.
The jinja works (just tested it in my DevTools -> Template editor)
i want to have a state strem - and the provided mqtt function is kinda shitty to use - for debugging is this nice. but not for a state change report. IMHO
is there something different?
grr. nvm. got it. after editing it through the ui it changed my topic
In a way.
All entities have a display name ("friendly name"), which can be pretty much anything at all.
Technically, I'm pretty sure you could enter hours/day as a name as well in some cases, but the / would be automatically removed.
You probably don't need that. It will update when anything used in the template updates.
well..the problem is that i store the time for my air conditioner is on / day
and i want to gather data per month
and one of the guys said that i must set a sensor with high scan interval
in order not to be refreshed
then pull an automation before time/day is reset
to gather total value per day
Could this help? https://www.home-assistant.io/integrations/history_stats/
exactly
i set it up
but per day
and at 0:00 it's reset
i want at 23.59 to be re-evaluated and published in another place
then with utility meter i can put sensor to be tracked monthly
is this logic?
Hm...
So you want something like this? This is my power usage per day for the last six months
But with hours
i don't have smart plugs in the house for now
This is done with InfluxDB and Grafana.
I have a utility sensor which calculates the daily usage and that's stored in an external database.
Home Assistant isn't really ideal for collecting long term data like this, but what you could do is actually use an automation to set the state of say an input_number at 23:59 every night. Then you could use various operations on the history of that input...
hmm....if u have an example ... π
No, sorry. I'm just brainstorming.
only made a demo with input number...
idea is ho can i refresh the sensor that collected info in hist stats at 23.59 ?
to make sure that i collect indeed the value of today hours
That's what the automation would do.
Something like (just from the top of my head. No guarantees on the syntax)```yaml
trigger:
- time: 23:59
action: - service: input_number.set
data:
entity_id: input_number.hours_yesterday
value: "{{states('sensor.your_hours_per_day_sensor')}}"```
ok
Then it's comes down to your history settings for Home Assistant how long that data survives.
purge days set to 365
thanks for idea. gonna check input number
hours_yesterday is a sensor ?
You have to create one of those manually. They're supposed to be used for getting values from a user, but you can also set their value via a service call (e.g. in an automation). That value will then be stored in the input_numbers history.
oh...that's the name of the entity input....so for grafana i will call input number of hours for each day
because this value will be stored only once / day
i put the value from automation π
then template sensor with state of input number
How would I return a nicely formatted string from a custom list of entities that match a criteria? E.g. "The laundry door, office window, and back door are still open."
The weather example in the dev panel doesn't work because loop.first and loop.last are not necessarily matching the criteria.
{{ "The following are still open: {}".format(", ".join(open_list)) if open_list else "Nothing is open." }}
assuming you already have the list
I do not, I was trying to do that via template as well, with a for loop. But looks like the append function is disabled in HA for security reasons.
Here's the start that I have:
{% for sensor in sensors -%}
{%- if states(sensor) == 'on' %}{{ state_attr(sensor,'friendly_name') | lower }}{% endif -%}
{%- endfor %}```
If there's a way to construct a new list just based on a criteria, I can handle the rest easily enough π
What about {{ expand('goup.of_your_stuff') | selectattr('state', 'eq', 'on') | do_other_stuff }}?
You'd have to create a group though, but that's quite easy
Makes sense, can kinda get there with similar nesting. How do you handle the select_or_reject generator object though? Is it just an iterable?
| list :)
Returns an empty list :/
Did you create a group entity?
I use this to count opened windows for eg in a sensor, but the idea is the same {{ expand('group.living_room_windows_opening_sensor') | selectattr('state', 'eq', 'on') | list | count }}
I did not. Thought I could do it without a group and just a manual Jinja list. It kinda works with a group now.
Returning the entities in a list. How do I now get the friendly_name attribute for the do_other_stuff step?
A jinja list doesn't have a state. expand works because it outputs a list of state objects
i guess something like this would work:
{% for sensor in (expand('group.living_room_windows_opening_sensor') | selectattr('state', 'eq', 'on') | list) %}
{{ sensor.attributes.friendly_name | lower }}
{% endfor %}
Oooooh! And everything clicks into place. The first part is just to generate the list based on the criteria!
I've edited my message. sensor is an object, so that edit should work better π
Yep, works a charm now! Starting to get my head around Jinja schema/logic flow a bit better now.
{%- if loop.first %}The {% elif loop.last %} and the {% else %}, the {% endif -%}
{{ sensor.attributes.friendly_name | lower }}
{%- endfor %} is open. You may want to close it before heading out.```
Just need to use the count logic from before and a conditional to change the message if there's no open sensors.
since you're making a string you could do it that way
but if you actually want to build/return a list it gets wonky
So next question (that I'm not sure is even answerable/solvable with the current mobile app notify integration) - How can I determine (either with template or just normal automation) any notify entities that are/aren't home? I previously did it in AppDaemon with a dict which mapped person entities to the notify.mobile_app_* entities. Would similar logic apply here?
that gets harder i think
since they're multiple services
unless you make groups with the different combinations?
and make a map
service: >-
{%- set notify_map = {"person_1": "notify.person_1", "person_2": "notify.person_2", "person_1+person_2": "notify.group_both"} -%}
{%- set away = states.device_tracker |selectattr('state', 'not', 'home')|map(attribute='entity_id')|map('replace', 'device_tracker.', '')|list -%}
{{ notify_map["+".join(away)] if away|length > 1 else notify_map[away[0]] }}
something like that
@hexed galleon
Will that work though? Because it will effectively be calling multiple different notify services at once?
it'll only ever be calling one from the automation
if you have a notify group it'll do multiple that way
you just need to have groups for any combinations and populate that map
obnoxious, but it'll work
Bummer. Was hoping there would be some sort of template-based loop functionality in the automation engine. Perhaps I should stop trying to be so tricky and just use the python_script integration π
that could work
Feel like the architecture of the notify engine should probably be re-worked with apps in mind too, but that's something for #integrations-archived, #android-archived, and #ios_and_mac-archived π
haha
What causes this error
Error while processing template: Template("{{ state_attr('binary_sensor.protection_window', 'start_time').timestamp() | timestamp_custom('%R') }}")
binary_sensor.protection_window is from my OpenUV integration. Would the History Graph Card cause this error, and why?
Hi, is it possible to use a secret in a template?
No, you have to put the full template as a secret in this case. !secret only works if it's alone on its line
hi. from time to time the card display the sensor with many many decimals. the sensor is built as value_template: >
{{ (states('sensor.immax_temperature'))|float - (states('sensor.openweathermap_temperature'))|float}}
both temps are with 2 decimals. why i see now 20 decimals ?
putting the secret (that contains the template) back in the value_template of a template sensor wont work i guess?
nevermind that was idiotic π
what i want to do is using multiple values from different secrets in a template sensor
i abused the secret function to store some global values
You can use them all. Just expose them as individual sensors first.
You could use the variables custom-component maybe for that? https://github.com/snarky-snark/home-assistant-variables
But secrets as global variables is usually a bad pattern. Just use the input helpers.
Or just input_text
@young jacinth Why don't you just use variables ? Something like:
variables:
secret1: !secret secret1
secret2: !secret secret2
And then use secret1and secret2in your template
hi. from time to time the card display the sensor with many many decimals. the sensor is built as value_template: >
{{ (states('sensor.immax_temperature'))|float - (states('sensor.openweathermap_temperature'))|float}}
both temps are with 2 decimals . again wierd display: 19.880000000000003
IT does strange things sometimes, just add a |round(2) π
{{ (states('sensor.immax_temperature'))|round(2) |float - like this ?
for each state
value_template: >
{{ (states('sensor.immax_temperature')|float - states('sensor.openweathermap_temperature')|float) | round(2)}}
Hey Guys,
I'm trying to create a Rest-Sensor from an JSON-Output.
My Sensor is created but the Value is empty.
Here is the Rest-Output and the config for the sensor.
https://pastebin.com/v3BKrh0W
any hints?
I'm trying to get the value from the first attribute 1.8.0
It should work... nothing in the log ?
Nothing regaring the REST-Sensor
Well there we go - another Restart of HA has fixed it... Strange....
Me again...
anyone why this is not rounded to two decimals?
{% set value_json=
{"1.7.0": 22345456 }%}
"{{ value_json['1.7.0'] / 1000 | round(2) }}"
Value is: "22345.456"
"{{ (value_json['1.7.0'] / 1000) | round(2) }}"
in your template you are rounding the 100. You need to add parenthesis
π© maths is way to long ago... Thanks again
π
i want to use the secrets in a template sensor. variables are limited to scripts or am i wrong?
i dont want to use helpers as the integration (adaptive lighting) iam using does not support templates but secrets
oh ok, didn't get it was in a sensor
Is there a way to use something like this:
{{ is_state_attr('binary_sensor.mailbox_sensor', 'tiltangle', < 24) }}
this gives an error but i would like to check if a value of an attribute is below a value and then give true
so i can use it in a condition
{{ state_attr('binary_sensor.mailbox_sensor', 'tiltangle') | int < 24 }}
can i also use this as a trigger. i need this as a trigger π
That would be an #automations-archived topic but... yes.
ello fellas.. I was wondering if it is possible somehow to use a template to get an url for an image using lovelace pictire element or Picture card?
something like:
type: picture
image: 'sensor.xmpp_picture_box'
tap_action:
action: none
hold_action:
action: none
the sensor has an url with a pix as state
probably more of a #frontend-archived question
data:
value: >-
Justin East Window, {{ as_timestamp(strptime(datetime, '%Y-%m-%d %H:%M:%S'))
| timestamp_custom('%a, %b %d at %I:%M %p') }}
entity_id: input_text.lastusedss
how do i parse the current time like this? it's not working. is it because i need to use value_template? can i use value_template instead of value in this service?
According to the example on https://www.home-assistant.io/integrations/input_text/, you can put a template in value
look at the bottom of the page.
i think you need "SOMETHING.as_timestamp" or "SOMETHING | as_timestamp", but I'm not sure. Google could probably help.,
is wait.remaining gonna be in seconds or which format?
Should prolly use that instead
where i go wrong ? https://pastebin.ubuntu.com/p/F9Qm7GqsyV/
yesterday value is not written by the input_number automation ,
although the value is changed and displayed by the cumulative senso
You have double single quotes in this line value: '{{states(''sensor.durata_ore_aer'')}}' instead of double quotes around the sensor entity_id
''(wrong) vs " (correct) ... Not very visible π
Can't see how a double quote can be transformed into a double single quote during a copy / paste, but you know probably better ;)
Not all editors (or languages) are created equal.
If you've ever used MS Word, you will have come across the stylised quotation marks.
If the issue was with Adrian's quotation marks, the sensor wouldn't work at all π
The automation doesn't work, not the sensor π this line is in the automation section.
@glossy viper - any issues when you run the config check?
Likely a very simple question - can I only get the friendly name of a trigger object from the from_state/to_state objects? Is it just {{ trigger.from_state/to_state.attributes.friendly_name }}?
state.name Name of the entity. Based on friendly_name attribute with fall back to object ID. Example: Kitchen Ceiling.
Cool, but still need to reference a state object, right? So has to be from_state or to_state?
{{ trigger.from_state.name }}
Bingo
Thanks!
Hi everyone. I've got a IR-controlled DAC set up as a light to control the volume in HomeKit. There's an annoying issue: when a scene is called twice in the Home app, it is actually toggled, and this makes HomeKit turn off the "light" which mutes the DAC.
I've got a value template like so:
value_template: >-
{% if is_state('switch.antimode_mute', 'off') %}
{% if (states('input_number.antimode_volume')|int ) > 0 %}
on
{% else %}
off
{% endif %}
{% else %}
off
{% endif %}
And I'm hoping someone might have an idea how to un-mute if a volume state is received. I believe if I only check for > 0 the mute state wouldn't persist at all.
can you somehow get the last X values of a sensor in a temeplate?
Nope. Sensors only have their current state. What are you trying to do?
i am feeding sudo journalctl -n 1 -p 0..4 --no-pager -q to a sensor
and would be nice to show more than 1 line
if I go over one line with the -n value it won't register at all
What are you trying to get out of this? What's the end goal?
exactly
Well if your sensor can't read more lines, make more sensors.
π
Templates can only work with data you already have. If you need more data, that's an #integrations-archived problem.
the values are stored in the history component though, must be a way to access them
No
Or get several lines, in the command line replace \n with # for instance, and in the gui replace the # with \n
its easy to get json output from journalctl too, but anything that isnt a sensor is not updated immediately in the GUI
I suggest
sudo journalctl -n 5 -p 0..4 --no-pager -q | tr '\n' '#'
And in your markdown
{{ states("sensor.your_sensor") | regex_replace("#", "\n")}}
aah, clever! gonna give this a shot
hmm, doesnt pick up the state. is there a limit on max length of a state?
i'm thinking of adding it in an attribute instead
got the wanted result, thanks @deft timber {{ state_attr('sensor.cube_syslog', 'log') | regex_replace("#", "\n") }}
π
the state is the timestamp of the poll
is there any templates that returns true or false for my condition-template like if all meida_players are turned off?
somehing like {{ media_players.*}}
?
you could loop through all of them with a for device in devices loop, bu not sure if there is a smarter way
{{ not states.media_player|rejectattr('state', 'eq', 'off')|list|length > 0 }}
that seems to be smarter π
wow π thanks! I will try
I had to add idle and unavailable for that to work though:
{{ not states.media_player|rejectattr('state', 'eq', 'off')|rejectattr('state', 'eq', 'unavailable')|rejectattr('state', 'eq', 'idle')|list|length > 0 }}
oh, I forgot to mention, I want to turn off the media_player
so, if all media_players are off, except media_player.ABC, then turn off media_player.ABC
basically ABC player is my 2-zone AVR and Im listen spotify, watch movies, etc
so I need to ask if all media_players are off in order to turn off my avr
give this as the entity_id to the turn off service : {{ states.media_player|rejectattr('state', 'eq', 'off')|rejectattr('state', 'eq', 'unavailable')|rejectattr('state', 'eq', 'idle')|map(attribute='entity_id')|list}}
this will turn off all the media player that are not off
can shorten that
or unavailable or idle
no, no, I want to just turn my avr if and only if all my other media_players are set to off
or unavailable
ah ok
{{ states.media_player|rejectattr('state', 'in', ['off', 'unavailable', 'idle'])|map(attribute='entity_id')|list}}
should probably include unav regardless
with this syntax Im getting listed all my media_players..how to exclude ones..for example chromecast?
oh, if you're getting choosy you probably should just create a group and key off of that
I heard that it cant be created group of media_players?
How do I use a !secret tag inside a template sensor's result? NVM: Looks like it's not possible, solved with a second template sensor
yes I will try
and how to shorthand write this
or
is_state('input_select.livingroom_tv_source', 'HEOS Music')
or
is_state('input_select.livingroom_tv_source', 'SBB BOX')
or
is_state('input_select.livingroom_tv_source', 'TV Audio')
}}```
like this {{ states.media_player('state', 'in', ['HDMI 3 (eARC/ARC)', 'HEOS Music', 'SBB BOX','TV Audio'])}}
?
Close
I use something like this:
In Teams meeting: {{ states('sensor.microsoft_teams_activity') in busy_statuses }}```
Im just trying to add to mediaplayer.source
Test: {{ states('media_player.avr_zone1.source') in sources }}```
{{ states('media_player.avr_zone1.source') }} but this is unknown
quick other question π how do I reject on the existance of the entity_id attribute, rather then the states entity_id:
<template TemplateState(<state light.lampen=on; min_mireds=153, max_mireds=500, effect_list=['colorloop', 'random'], brightness=191, color_temp=365, effect=none, entity_id=['light.hue_lightstrip_plus_1', 'light.staande_lamp', 'light.hue_color_pendant_down_1', 'light.hue_color_pendant_up_1', 'light.computer', 'light.hal', 'light.reserve', 'light.sk_ceiling', 'light.sk_duo_spot_1', 'light.sk_duo_spot_2', 'light.overloop', 'light.keuken_1', 'light.keuken_2', 'light.keuken_3', 'light.trap_hal'], friendly_name=lampen, icon=mdi:lightbulb-group, supported_features=63 @ 2021-01-15T15:29:47.241841+01:00>)>]
light without the entity_id attribute:
<template TemplateState(<state light.computer=on; min_mireds=153, max_mireds=500, effect_list=['colorloop', 'random'], brightness=191, color_temp=365, effect=none, friendly_name=Computer, supported_features=63 @ 2021-01-15T15:29:47.237368+01:00>)>
rejectattr('attributes.yourattribute', 'eq', 'abc')
hi!
are we not allowed to use {% set sun = state_attr('sun.sun','elevation') %}
"{% set ... " in a template sensor?
yes you are
made it possible to replace:
{% for device in dict(states.light|groupby("state"))["on"] %}
{%- if state_attr(device.entity_id , 'entity_id') != None %}
{%- if loop.first %}{%set ns.first =true %}{% endif %}
{%- else %}
{%- if loop.first or ns.first %}{%set ns.first =false%}{% else %},{% endif %}
{{- device.entity_id | lower }}
{%- endif %}
{%- if loop.last %}{% endif %}
{%- endfor %}
```
with:
`{{states.light|rejectattr('state', 'eq', 'off')|selectattr('attributes.entity_id', 'undefined')|map(attribute='entity_id')|list}}`
much better!
indeed π
https://pastebin.com/rs2Q3THB this is my sensor but it wont work
thanks Slashback and phnx
@young jacinth replace && with and
value_template: >
{% set sources = ['HDMI 3 (eARC/ARC)', 'HEOS Music', 'SBB BOX','TV Audio'] %}
{{ states.media_player.avr_zone1.attributes["source"] not in sources
and
states.media_player.avr_zone2.attributes["source"] not in sources
}}```
but I ahve error on this
Invalid config for [automation]: expected str for dictionary value @ data['condition'][0]['state']
aww man i step away and all the fun ones come in
hehehe
- condition: template
value_template: >-
{%- set sources = ['HDMI 3 (eARC/ARC)', 'HEOS Music', 'SBB BOX','TV Audio'] -%}
{{ state_attr('media_player.avr_zone2', 'source') not in sources
and
state_attr('media_player.avr_zone2', 'source') not in sources
}}
yeah, i try to avoid actual for loops whenever possible. Its not always possible though
native typing made things better though
yes. I've tried to pass xy colors a while back and then gave up as they're always passed as strings.
that's fixed now though
yep
I saw that, so next time I'll play with that I can now π But since then, blueprints also came out so I used those, making it easier not to pass these things between an automation and a script, bu just put it in the blueprint, no need for the script part anymore
I still have error
i don't really mess with built in automation Β―_(γ)_/Β―
might need to check the docs for template conditions
let me see if I have a similar condition template, as I use them a lot
hehehe yeah it's sometimes not very clear in the debugs which term it actually giving the error on
yeah..once I edited multiple script/automations, and left it like that, tomorrow, I checked config, and some script/automation was giving the error in the logs
So I had to comment one by one each automation file, to locate my error π
I use set in conditions a lot, so I knew it had to work. for example:
value_template: >
{% set tz = as_timestamp(now())|timestamp_custom('%z') %}
{% if state_attr('calendar.2020_fia_formula_one_world_championship_race_calendar', 'start_time') == None %}
False
{% else %}
{{ now().strftime('%D %H:%M') == ( (as_timestamp(state_attr("calendar.2020_fia_formula_one_world_championship_race_calendar", "start_time") + tz )-600) | timestamp_custom('%D %H:%M', 1)) }}
{% endif %}```
I do alot with google calendar, but that's giving times back in gmt...
nice
using the set there to make it just a bit more readable
and another question - is there some "hack" through templating to do a following
I have ofc tag reader
and I want to trigger automation when I scan twice same tag
in interval no longer than 5 seconds
so I was thinking to create input_boolean when first scanning occuer
occured*
and some helper automation to countdown 5 seconds
than to ask through template if still input_booleon is true
but Im missing the second scanning the tag
not really a template hack, but you could do a wait for triggere in the automation to wait for the 2nd scan
Idk how to implement that
but that's more a question for #automations-archived then π
If you mean your device isn't scanning the tag the second time, this is normal. You don't want hundreds of events fired while your phone is still near the tag, so there's a cooldown.
Hey guys, I am trying to add a binary sensor which is true depending on the state of another sensor, but for some reason it doesn't seem to work.
- platform: template
sensors:
e3dc_emergency_power_available:
friendly_name: "E3DC Emergency Power Available"
value_template: "{{ is_state('sensor.e3dc_emergency_power_state', 1) or is_state('sensor.e3dc_emergency_power_state', 2) }}
The other sensor is derived from Modbus and has an int value, so I suppose my current code is correct. But apparently it's not, because it currently has the value 2 but the binary sensor is still off. What did I do wrong?
using is_state('sensor.e3dc_emergency_power_state', '1') (and '2' respectively) also doesn't work.
Test the templates in the Dev Tool and see what it says.
ah, totally forgot that this panel existed. Thanks. When using a string comparisson it returns true, yet my sensor is still off. I'll reboot once more (need to update HA anyways for the security update)
For future reference, you don't need to restart to reload template integrations. There should be an option to reload those.
my entity_id: light.bedroom_hue_color_ceiling_light should match my topic.
how do i achieve this?
topic: homeassistant/indoor/light/bedroom/hue_color/ceiling_light
i got following jinja2
{{ 'homeassistant/indoor/' + entity_id.replace( '.' , '/' ).replace( '_' , '/', 1 ) }}
now i need to skip one _ and replace the 3rd _ with a / how do i do this?
atm, i get homeassistant/indoor/light/bedroom/hue_color_ceiling_light
do you need it to be generic or are you always targeting that one?
i want to be generic for ~~every ~~ all rooms.
i have hue_color and hue lights and think i need to seperate those
are your naming conventions consistent?
jeah. my template schould work with every light.
indoor / outdoor/light/room/hue / hue_color/ceiling_light / couch_light / etc./cmd
but this should only effect indoor lights
/cmdending is not the problem here. π i just dont included this here
well. i just can rename my lights. HAHA
there is no need for ceiling_LIGHT
thanks anyway. π
yeah, parsing all that out would be kinda rough to make it generic
Just set custom attributes on those devices. Turns the template into one simple | select_attr.
try to find a way to replace the "last" _ with an /
this would solve my problem.
mono how do i do this?
configuration.yaml
light.bedroom_hue_color_ceiling_light:
entity_topic: homeassistant/indoor/light/bedroom/hue_color/ceiling_light
something like this?
ahhhh.
Then to find them:
{{ states | selectattr('attributes.room', 'equalto', 'study') | list }}
π‘
A little bit more setup, way less of a headache to work with.
it is kinda win-win...
need to learn jinja2 for work. π
is Area: not already a valid attr?
oh. i see. its not?
Areas are things in HA but I don't know if they're an actual attribute of entities.
Either way, I'd recommend avoiding any custom attribute names that could collide with either native HA stuff or any integrations.
How do I combine a string and state template together? This doesn't work:
color_extract_url: 'https://homedomain.com{{ states.media_player.spotify.attributes.entity_picture }}'```
It throws this error in the log:
External URL 'https://homedomain.com{{ states.media_player.spotify.attributes.entity_picture }}' is not allowed, please add to 'allowlist_external_urls'
Even though I've added the url to allowlist_external_urls, but it doesn't convert the states template?
When I try it in Developer > Templates the resulted string is https://homedomain.com/api/media_player_proxy/media_player.spotify?token=8b369cea0db0a806148xxxxxx and that URL shows the album art perfectly fine.
Not every field in HA accepts templates.
What does the documentation say for the integration you're trying to use?
Docs aren't actually that great... code suggests no templates allowed: https://github.com/home-assistant/core/blob/dev/homeassistant/components/color_extractor/__init__.py#L30-L39
Relative still isn't templated π
Failed to call service color_extractor/turn_on. invalid url for dictionary value @ data['color_extract_url']
Because you're still using a template...
Hmm, is there any other way you think? This is basically what the docs do too, am I wrong?
Well is this you setting it up in configuration.yaml or calling the service?
Calling the service via developer tools > services. The plan is to make an automation out of it.
Ok. Templates aren't rendered in calls made from there.
Make an automation, try it for real.
So I basically plan to change the color of a led strip to the color that the color_extractor returns every time a song changes in Spotify
Okay, will do!
What's the best practice for validating a sensor's value like in a template switch. For example, I have this:
office_tv:
friendly_name: "Office TV"
icon_template: mdi:television
value_template: >-
{% if states('sensor.office_tv_plug') | float < 5 %}
off
{% else %}
on
{% endif %}
It seems like during HA shutdown, states('sensor.office_tv_plug') is something like "unavailable" and {{ "unavailable" | float }} == 0.0
So it's causing an automation to trigger during shutdown even though the TV is still on.
I've got an integration that is returning a time as a string in the format "5:00PM". I can't seem to get strptime to convert it into a timestamp (I'm trying to have that time, minus 5 minutes, be a trigger for an automation). Any tips on how to template this?
Well if it's unavailable, it's not on either.
That's true, but I don't want my "The TV is off" automation to trigger because HA restarted.
Basically, I have an automation on my TVs such that if they turn off, the roku stops playback. So if we're watching something and the sleep timer engages, whatever we were watching doesn't keep playing.
that works beautifully, but when HA restarts, it triggers this automation (and I don't want that).
HDMI-CEC does other unexpected crap, so I turn that off where I can. I want HA to handle that stuff.
@alpine pelican why not use a condition in the automation that limits it to when the state is "on"?
(sorry; "off")
currently the automation is for when switch.office_tv goes from on to off.
i go the other way, i'd much rather use CEC where i can as that is a local network of devices talking to each-other
I appreciate that, but CEC is not consistent across all of my TVs.
And some don't have it at all.
Β―_(γ)_/Β―
A handy solution to that problem would be to not restart HA π€·ββοΈ
It was recommended that I check in here for a best practice for validating that a sensor is available. I'll figure that out.
it should still work; I have conditions that are the same as a couple of my triggers. If there's a bug between on or off, then use the or condition
If only there weren't ever any HA updates or changes to my system, that'd be perfect. π
there are automation ways of handling that
Don't apply them during movie nights π€·ββοΈ
handling in the template isn't the right place
Whatever you come up with for a template binary sensor, you'll be in the wrong state some of the time.
Handle those checks in your automations.
sounds good.
Alternatively, you can lengthen the template to use an and to verify that the state is "on" or "off"
Fair enough. he was looking for a template solution. I agree it's not the best way but it's doable.
I think I'll put a condition that sensor.office_tv_plug is not "unavailable"
just because you can doesn't mean you should and we're saying you shouldn't
Or as Tinkerer would put it, there's more than one way to skin a cat.
I wasn't looking for a template solution. I was looking for a solution. And was directed here.
We're not mad at you. But if you could tell us who directed you here, we'll organise the kill squad.
...or crash a home assistant instance, at least before all the checks and upgrades
LOL. Given that they helped me find my issue, I think I'll protect the names of the innocent.
Got it to work, thanks for the tip. Didn't know there was a difference there.
On my question, anyone have any tips? I'm currently sitting on {{ strptime(state_attr('sensor.leafs_game','next_game_time' ), '%H:%M:%S') }} but that returns "5:00PM"
Template sensors have a availability_template config so you could carry over the unavailable from office_tv_plug to office_tv. You still need to handle that in your automation tho
Awesome. Thanks, Chris!
The 'Not sensor.office_tv_plug == "unavailable"' solved the problem. Thanks, all!
I have a sensor with an attribute called data queries as {{ state_attr('sensor.recording_schedule', 'data') }} return for example
- name: Some Show She Likes
duration: 60
_id: 6001e88ccb5cd777ffe4b3de
channel: tv3
startAt: '2021-01-23T20:00:00.000Z'
addedOn: '2021-01-15T19:10:04.410Z'
__v: 0
- name: Some Show She Likes
duration: 15
_id: 6001f16fab49e4bac92acda2
channel: tv3
startAt: '2021-01-23T20:00:00.000Z'
addedOn: '2021-01-15T19:47:59.707Z'
__v: 0
how do I loop only the names from this
{{ state_attr('sensor.recording_schedule', 'data')|map(attribute=name)|list }}
sorry
lots of undefineds now, I guess its not really a map?
even more undefineds returned in an array
what is the return type of just the state_attr() statement?
@deft night posted a code wall, it is moved here --> https://paste.ubuntu.com/p/v2mQY56W4s/
check out the template tester and lets see what comes out
removed all the other templates first, its a string
now I got a list, added a json to string flow infront of it
an that helps
so how do I get it back to a string so it renders π
from {{ state_attr('sensor.recording_schedule', 'data')|map(attribute='name')|list }}
depends. what do you want it to look like?
seems to be fine with the last example in the demo template looping over the list
there are a few ways to do that but it depends on what you're trying to accomplish
The "Some Show She Likes" and the "Some Show She Likes.
its perfectly fine for this, just want a confirmation list after clicking a button in the GUI
its a small PoC to port over some old jquery TV recorder I made for my wife 10 years ago to pure HA
(and some Node Red to handle the logic)
noice
hi..to avoid asking simple questions please point me where i can find how to compose a syntax like {{ states | selectattr('attributes.room', 'equalto', 'study') | list }} π
eq
Jinja Template Designer Documentation
For more examples and samples, visit see this page
it'll be under "built in tests"
ty
As an update on my question, I've figured out that strptime() requires the time to be in the format, e.g. "5:00 PM". So, now that part is working. Of course, as a timestamp just feeding 5:00 PM in goes back to 1900. Is there a way to change the date returned to today's date with the time as formatted?
{{ strptime(state_attr('sensor.leafs_game','next_game_time'), '%I:%M %p') }}
> templates