#templates-archived
1 messages · Page 99 of 1
Bad paste...
tcm_starttimestamp:
friendly_name: Start Timestamp
value_template: '{{ as_timestamp(states.sensor.tcm.attributes["timestamp"])|int - 7200 }}'
That was my intention.... Making it its own.
But you’re using it as though it’s an attribute of sensor.tcm
yeah it's being called like an existing attribute
Ahh, ok. So what would be the correct way to do that?
Replace that block with sensor.tcm_starttimestamp
states(‘sensor.tcm_starttimestamp’)
try it
Tried it. Error rendering template: TemplateSyntaxError: unexpected char '‘' at 10
K. One moment.
Some smart quote
That was it. However, it's still coming over as integer time.
{{ states('sensor.tcm_starttimestamp') | timestamp_custom("%H:%M", 0) }}
1596412800
You may also need to filter the state with ‘|int’ before passing it to time stamp_custom
ctime
Better....
I have a quick question @north helm you said you're pulling the time from API? but it comes back EST And not MT?
@cerulean cipher That is correct.
That worked in Templates, but when I add it to sensors.yaml, I get.
because with Ctime there is raw offset and DST offset
tcm_realtime:
friendly_name: Start Time
value_template: '{{ states('sensor.tcm_starttimestamp'') |int | timestamp_custom("%H:%M", 0) }}'
Dangit
Sorry
Error loading /config/configuration.yaml: while parsing a block mapping
in "/config/sensors.yaml", line 42, column 9
expected <block end>, but found '<scalar>'
in "/config/sensors.yaml", line 43, column 37
Not following about Ctime...
CTime aka unix time
Ahh
is what you're getting your time from the API in
No, coming out of the API it's timestamp: '2020-08-02T21:49:28'
where did 1596412800 come from then
You’re also using the same quotes inside and out
@cerulean cipher That's coming from
tcm_starttimestamp:
friendly_name: Start Timestamp
value_template: '{{ as_timestamp(states.sensor.tcm.attributes["timestamp"])|int - 7200 }}'
@inner mesa Yes, I see that now in the editor.
Just changed to double quotes and it checks properly now. Reloading
Interesting. It's coming out at 02:00. I wonder if I'm subtracting 7200 minutes rather than seconds.
You should be able to work out the math in dev->templates
Agreed.
I would just bumble around until I got it right
I won't take up any more of your time. I appreciate your help and your patience, @inner mesa and @cerulean cipher!!!!
Np, glad to help
{{ states("sensor.tcm_starttimestamp") |int | timestamp_custom("%H:%M") }} works like a beauty. There was an extra ,0 in the timestamp_custom
Excellent. Yeah, was wondering what that was doing, but figured you knew 🙂
Copying and pasting blindly. 🙂 It's what happens when a guy's native platform is "codeless coding"
Cherwell Service Management, actually.
Mapp?
I use mApps all the time.
Was just involved in writing an integration with cherwell, was interesting
Cmdb and incident
My project that is (FINALLY) about to deploy is redoing how CMDB and Incident and Approvals all interplay.
I'll be submitting our redesign and new Portal for consideration for awards this year.
Noice
I feel really silly when I can't do templating in HA, because I'm no dummy if I do say so myself.
It's just two completely different skillsets.
Templating is an interesting bird
Jinja is used by Home Assistant's template engine, see the Jinja Template Designer Documentation
I introduced jinja2 to my team and we've been using it all over our product now
I could've written the Turner Classic Movies web service call and presentation in ... an hour - tops ... in Cherwell.
we have our share of cough inexperienced cough users and it's a challenge to separate them from the folks who are this far away from figuring it out
Someone offhandedly said "We've got a new blank spot on the portal. Sure would be nice if we could have weather info there." "Hold my whiskey."
I'm old. I decided this morning that I was sick of going to the TCM site all the time on the weekend when deciding what to watch.
I'm basically to the "hold my beer" with jinja. Getting there with python too
@north helm I'm almost old. But trying!
My philosophy is that I can make Cherwell wash your car, but get me into the yaml world and I'm a total noob despite using HA for almost 5 years. I've got RF integrations, hacked blinds.
@cerulean cipher Got you beat. Turned 50 last month.
that's ok, you have a healthy lead but the trick is to not let me catch up
39 in January here
Just a pup.
but it feels a lot older having a 14 year old kid
@north helm I have brothers older than you so I know 😛
IF there was a kid out there, he'd be 33 now.
Woke up at 3 last night and one of my boxes was going nuts. Couldn't figure out why, so I threw in a netdata docker and put it in HA and went back to sleep.
Isn't "woke up at 3" a fun thing to look forward to, kids?
I've done that most of my life
it's currently 12am and I haven't slept yet tho maybe if I had gone to bed 2 hours ago I'd be up at 3
I did it 17-35. Then I married a guy who does food for a living. I think his alarm is set for 01:30 tonight
We're getting off track a bit, though.
😄
So, in my world, hh is 12-hour time and HH is 24. This doesn't seem to apply in HA.
HA looks like it's either %H or more funky modifiers.
Hey guys, im trying to make a template binary sensor.
When i paste this: "{% if is_state('binary_sensor.server_zeus_ping', 'on') %}Online{% else %}Offline{% endif %}" into the dev tools template section it shows "Online" but when I add it into de configuration.yaml it always shows off. Any ideas?
@lapis quarry you copied that from the forums? It has the invalid quote type. Replace all your quotes with the non-fancy quotes
@mighty ledge That did it Petro, what an eye!! Now it works thanks very much, I copied it from RobC sugestions last night while editing the template
Quick help/scan of my sensors.yaml file? I'm 'trying' to tidy up by adding a secrets.yaml and pulling the sensors into a config.yaml. I've done this and syntax seems to pass, but my influxdb sensors have disappeared from frontend - so clearly something daft I'm doing. Would someone mind scanning this file and letting me know if there's something wrong here? https://paste.ubuntu.com/p/7v5NKkVrXp/
Hey guys, I am having an issue with a template.. and the issue seems to be in the "name" of the array in a json payload. This is the test I am doing on the template test page in HA: https://pastebin.com/82Y4dWQ4
And it is returning: Error rendering template: SecurityError: access to attribute 'update' of 'dict' object is unsafe.
If I change "update" to "whatever".. it works 😄
update is a built-in function of any object which can be used to update several keys at once.
Try value_json['update'].state.
Cheers!
Hey, quick one - configuring the inbuilt sun sensor and it's displaying by default in UTC - ie: 2020-08-03T04:21:19.050Z - do I need to configure a template for this to be human readable in the configuration.yaml or is there an 'in application' or 'in lovelace' way of doing this?
if you place it in an entities or entity card, it will display it as a relative time. You just need to set the device_class to timestamp in the customize section. If you want it as a time, like on a digital clock, then you need to make a template.
Ah ok, so if I wanted to convert it to display as: 'Monday, 3rd August' then it's a template job?
Any reason this can't be done in the frontend? (just usually something that's normally loaded on the client side to render - eg javascript, css, jquery, react etc) - would be miles quicker to debug without having to reboot each time!
You can test templates in the Dev Tools without rebooting.
Hi, if I need 2 conditions (and one needs delay_on) for a sensor, am I forced to built 2 binary_sensors for the conditions and a third one for combining those ?
you can use for: in conditions to replicate delay_on: and delay_off: in sensor definitions
and conditions are default "and", so just specifying more than one condition ensures that all are true before proceeding with the action
I guess for: doesn't "replicate" the others because the sensor will change state immediately, but you can choose not to act on that state change unless it's been in that new state for a while
hi
i can't find how to make {{ expand('group.battery') | selectattr('state', 'lt', '15') | list | count > 0 }} work, because my state return an string but i need an int to compare number :(
any idea ? i have try a lot of stuff :(
"|int"
I always have to play around with stuff like that in
-> Templates to get them to work, but that's how you turn a string into an int
sadly, i couldn't put the int in the selectattr
i have spend 4H in the templates menu yesterday trying any workaround i could think about.
any other idea @inner mesa ? or do you know where i could put it ?
selectattr('state|int', 'lt', '15') or selectattr('state'|int, 'lt', '15') doesn't work
unfortunately not. I'm sure a Jinja Ninja will be along shortly
i haven't touched groups in forever. let me make one
i hope, i am usealy pretty good at this, but home-assistant jinja is more limited that the one i'm use to (no do, no append ...) hard to find a workaround
you can always whip up a python_script
this is a template trigger for an automation, i'm not sure i can use a python_script that way ... can i ?
(and it look a bit overkill)
no, you could use a python_script to set an input_boolean or something. But better if you can figure out the template
why not ? doesn't group trigger when an entity state inside change ?
i have no way to build an array with condition if selectattr doesn't allow me this, and var.append('foo') is locked for security reason 😞
states('sensor.guest_bedroom_temperature'),
states('sensor.izzys_room_temperature'),
states('sensor.living_room_temperature')
]|map('int')|list %}
{{ sensors }}
{{ sensors|select('lt', 78)|list|count }}```
You might want to take a different tack. E.g., you could use an event trigger looking for a state_changed event. Then in the conditions check if the entity is in the group, and if the old value of its state, when converted to an int, is 15 or more, and if the new value of its state, when converted to an int, is less than 15.
hum ... i need to look what map do but this is intresting
simplified
states('sensor.guest_bedroom_temperature'),
states('sensor.izzys_room_temperature'),
states('sensor.living_room_temperature')
]|map('int')|select('lt', 78)|list|count %}
{{ sensors }}```
you could single line it if you want
looking for a state_changed event
@chrome temple
I'm always worry about the load issue by listening to all state change and then dooing a condition
You need to find something else to worry about. 😜
the template listener is looking for state.domain.entity and/or states()/state_attr() stuff specifically
if that's not there, it might not trigger or update
I think a template trigger, if it can't find entity IDs, evaluates on any state change.
what do you use ? nodered ? appdaemon ?
appdaemon
But I'm not sure what happens when using expand('group.x'). I know there was some work done to try and figure out what entities that relies on, but not sure what the status is. I heard there were issues.
well {{ expand('group.battery') | selectattr('state') |list }} don't return what i expected :
[<template state sensor.aeotec_limited_zwa003_nanomote_quad_battery_level=100; node_id=20, value_index=0, value_instance=1, value_id=72057594379763713, unit_of_measurement=%, friendly_name=Aeotec Limited ZWA003 NanoMote Quad Battery Level, device_class=battery @ 2020-08-02T22:53:17.416003+02:00>,...]
not realy the state
and because i can't have a hard coded list {{ expand('group.battery') | selectattr('state') | map('int') | select('lt', 50)|list }} don' t work
Remove the first selectattr.
it have the full object to map on then {{ expand('group.battery') | map('int') | list }} [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Actually replace it with map(attribute='state')
So, {{ expand('group.battery') | map(attribute='state') | map('int') | select('lt', 50)|list }}
damn !
that work
thank's ! i realy need to take a deeper dive into 'map'. never use it at work
now to try if it does trigger automation :)
Hey I'm kind of new to templates so I'm hoping for a gentle hand holding here... I am trying to set up a sensor for my security panel door... It's not a binary sensor because it can be one of several states: secure, not_ready, bypassed, tripped, etc.... I'm trying to find out how to build the template to read the state and make the display values more user friendsly... Secure -> Closed (for doors), not_ready -> Open, etc.... Should be simple (I think)
is it just state.state == "secure" or something like that?
what i would do, is in the template do a set foo={'Secure': 'Closed', 'not_ready':'Open ...} and then use door is {{ foo[sensor] }}
probably need to add a reject for unav and unk
@sinful bison you probably still need the > 0 part, because a template trigger basically needs a boolean expression. More specifically, when the template is rendered, stripped of leading & trailing spaces, and converted to lower case, it has to result in exactly the word true to fire.
yea un foo[sensor]|default('doomed') should work i think
foo.get(sensor, 'doomed')
better, and i should have think about it
@chrome temple yea thank's i've added that already but it was kind to remind me
@dull bloom is that understandable, or do you need something more "finished" to understand ?
I understand what you're saying but I only want to change "Secure" and "Not Ready" since "Bypassed" "Triggered" and any other states are exception states that I would want to see the true value of... So I'm wondering if an if else would be better since I don't want to change the value for every state, just two
and no, I don't want something more "finished" -- I'm brute forcing myself to learn this so as little help as possible is what I want 😄
foo.get(sensor, sensor)
you can then alway use the default value to return you... damn he is fast
haha
thank's
i made an horible wind compass that way ... and i do mean horible https://paste.ubuntu.com/p/dJntFmkQjf/
and can I save this as a global template so I don't have to retype this code for every door in my security panel?
ok
I was trying to model like the {{ value_json.door }} idea where I could use {{ value_json.secure_door }}
this is sadly something i miss, making fully templatised yaml file :(
the capability to exange variable between the trigger and action template is a roadblock i've hit a lot :(
and i've been use to have that ... it's hard to not think with it after having it
ok new help... I have this as a sensor:
- platform: mqtt
state_topic: "omnilink/zone23/state"
name: "Office Door"
icon: mdi:door
value_template: >-
{% if (state.state == "secure") %}
Closed
{% elif (state.state == "not_ready") %}
Open
{% else %}
Current state is {{ state.state }}
{% endif %}
returning a value of "Unknown" -- what did I do wrong?
and could I have cleaned it up? I tried the way you said but it returned an error
I'm thinking state.state doesn't work per the instructions
yeah... that's assuming state is previously defined... Trying to find a way to get the state of the current entity rather than having to spell out the entity name in the template
can we use templates in custom components?
ie:
type: "custom:clock-card"
title: "{{sensor.date}}"
Typically not in cards unless they specifically say they support them
I don't see "title" as an option for that card, either
@rough lark posted a code wall, it is moved here --> https://paste.ubuntu.com/p/w3NN2fD5rd/
I have a question on regarding template locks. I have a z-wave lock and a door sensor that I have combined into a single template lock. Now every time I unlock and open the door, I get multiple notifications. Is there a way to add a delay so I get a notification only once ?
value_template: >-
{%if is_state("lock.front_door_lock","locked") and is_state("binary_sensor.front_door","off") -%}
locked
{%- else -%}
unlocked
{%- endif %}
the notifications are coming from an automation?
it sounds like your issue isn't with the template, but with some automation
@rough lark I agree with @inner mesa, it sounds like the automation is the issue. If you shared it we could take a look. But making some assumptions, maybe something like this would work for you:
- trigger:
- platform: state
entity_id: lock.front_door_lock, binary_sensor.front_door
mode: single
action:
# Your notification goes here
- delay: 5
That will prevent the automation from triggering again for 5 seconds.
https://github.com/home-assistant/core/blob/dev/homeassistant/helpers/template.py#L984
how can I use the base64_encode filter in a template?
nvm it was just confused with ints
Hey guys, I'm trying to output the brightness value returned by an IKEA E1744 "dimmer" (through zibgee2mqtt) using system_log.write but either I generally don't understand how to output sensor values or I'm not using the right path but this only output the string itself. Can anyone please shed some light on this for me?
- entity_id: binary_sensor.0xccccccfffe98fb45_update_available
platform: state
condition: []
action:
- data:
message: '{{ states.sensor.0xccccccfffe98fb45_linkquality.brightness}}'
service: system_log.write
mode: single
When working with templates, don't forget:
- You can test them in Developer tools -> Templates
- Rule 1 and rule 2 (https://www.home-assistant.io/docs/automation/templating/#important-template-rules)
Damn, I went through the triggers and actions doc pages but never got to this one. Thanks for your help!
Replacing "data:" with "data_template:" and the message value to what you suggested gets me a "Error rendering data template: UndefinedError: 'attr' is undefined" error. Any idea?
it should be state_attr()
I haven't looked at the actual issue that you're trying to solve, but that was a typo above
Thanks @inner mesa, that was it!
Ah sorry, on mobile
typing proper YAML formatting on a keyboard while also adhering to discord code blocks is a challenge
need a YAML keyboard with Discord extension
yeah
Hey guys, what would be the correct way to write this in a more compressed way?
@lapis quarry posted a code wall, it is moved here --> https://paste.ubuntu.com/p/JTfdpyDhWH/
can it be written as a list as we do when using entity_id?
Just have a list of entities that act as triggers, then a condition that checks the new state is 'offline'.
But that's an #automations-archived question.
thanks mono, makes sense, going to try rewrite it
@lapis quarry posted a code wall, it is moved here --> https://paste.ubuntu.com/p/b7gzScgfSG/
@lapis quarry Rule #6: Spam will not be tolerated, including but not limited to: self-promotion, flooding, text walls (longer than 15 lines) and unapproved bots.
Please take the time now to review all of the rules and references in #rules.
something like the above makes more sense, right?
Please follow the rules. That's not your first codewall.
very sorry
trying to compress it removing a lot of stuff before posting it
my bad
Just use a sharing tool like the bot did, and as described in the topic of many channels including this one.
sure, noted
I get this error in the template: (TemplateSyntaxError: expected token ':', got '}') for dictionary value @ data['action'][1]['data_template']['message']. Got None.
can somebody point me in the right direction about what im missing
At which line?
Never mind, it's clear enough
It's the bit you missed out of your paste by trying to 'remove a lot of stuff'...
Share complete code if you expect help. People here are good but they're not mind readers.
Please use https://paste.ubuntu.com/ or https://www.hastebin.com/ to share code or logs.
I'm not sure this is even possible:
{{ {{ trigger.to_state.state }} if trigger.to_state.state == 'offline' else "is in an" }}
It's going to see the first pair of closing braces and think that's the end of the template.
You want something like this instead:
{{ {% trigger.to_state.state %} if trigger.to_state.state == 'offline' else "is in an" }}
Gotta escape them braces.
what does the % do in this scenario?
does that even work? I would have expected to need an {% if xxx %} xxx {% else %} xxx {% endif %} block
I could be wrong, Rob 😄 I'm weak at templating.
let me try
Do it Rob's way. But don't nest templates within templates.
Oh, and I think it'd be more like this:
{{ trigger.to_state.state if trigger.to_state.state == 'offline' else "is in an" }}
I'm a dumb dumb.
{{ trigger.to_state.state if trigger.to_state.state == 'offline' else "is in an" }}
Yeah, saw my own mistake. Not often I beat you or petro for template stuff.
{{ trigger.to_state.state if trigger.to_state.state == 'offline' else "is in an" trigger.to_state.state "state" }}
this also correct?
Looks right, try it out.
no, that won't really work
else "is in an {} state".format(trigger.to_state.state)
{% sensor = trigger.to_state.state %}
{{ sensor if sensor == 'offline' else 'is in an {} state'.format(sensor) }}
message: >
Keyring Receiver
{% sensor = trigger.to_state.state %}
{{ trigger.to_state.name[7:9] }} is {{ sensor if sensor == 'offline' else 'is in an {} state'.format(sensor) }}, it might have been disconnected or needs to be reset
Invalid config for [automation]: invalid template (TemplateSyntaxError: Encountered unknown tag 'sensor'.) for dictionary value @ data['action'][1]['data_template']['message']. Got None.
need to set sensor
isnt that what this line does:?
{% sensor = trigger.to_state.state %}
{% set sensor = trigger.to_state.state %}
You should hydrate.
yes that did the trick
thanks guys, this templating stuff is very usefull
many possibilities, wish I had known all this earlier, learned a lot from you guys last few days
You should hydrate.
Nah, need a nap
hello, there are some things that I still do in CostumUI because is faster and easy to set that in Lovelace, une is the icon color, when I what it to be in all the place. Now I would like to do this:
customize_glob:
"*":
templates:
icon_color: >
if(attributes.config.autoon === true)
return 'rgb(0,0,255)';
Any entity with atrribute config.autoon === true, should set the icon to blue. I know that with states I can use if (state === 'on')
and it works, but I cant make it work with atrributes. Can any one help me?
@hollow girder is the attribute named 'config' or 'autoon'?
config.autoon
I think that the problem is related with costumize_glob, because a normal configuration to the entity is working
@hollow girder I could see you getting exceptions with your code with a glob. Because 'config' will not exist on all entities, but you're going a step further and asking for 'autoon' on config. That will cause an exception when 'config' doesn't exist.
@rough lark I agree with @inner mesa, it sounds like the automation is the issue. If you shared it we could take a look. But making some assumptions, maybe something like this would work for you:
- trigger: - platform: state entity_id: lock.front_door_lock, binary_sensor.front_door mode: single action: # Your notification goes here - delay: 5
@chrome temple @inner mesa - Thanks for the response and sorry for the delay. In my case, it's actually not notifications via Automation. I use HomeKit support in HomeAssistant and the notifications are from HomeKit. The notification happens because the state of the template_lock entity changes quickly. On a similar note, is there a delay option we can add for the template sensors so that there are no immediate state changes say for 5 seconds?
@hollow girder I could see you getting exceptions with your code with a glob. Because 'config' will not exist on all entities, but you're going a step further and asking for 'autoon' on config. That will cause an exception when 'config' doesn't exist.
@mighty ledge yes, that is happening, HA will not even boot! Can I get pass this? like, if config exists and autoon exists, and autoon === true? 😩
@hollow girder
if("config" in attributes && "autoon" in attributes.config && attributes.config.autoon === true)
return 'rgb(0,0,255)';
@rough lark what are you using for value_template in the template lock? And what do you have optimistic set to?
@hollow girder
if("config" in attributes && "autoon" in attributes.config && attributes.config.autoon === true) return 'rgb(0,0,255)';
@mighty ledge worked 100%.. tks
np
@chrome temple - Optimistic is set to default. I tried setting it explicitly to false as well as removing it, but no change.
Here;s the value template.
value_template: >-
{%if is_state("lock.front_door_lock","locked") and is_state("binary_sensor.front_door","off") -%}
locked
{%- else -%}
unlocked
{%- endif %}
@rough lark posted a code wall, it is moved here --> https://paste.ubuntu.com/p/JHWqvj9md4/
It's not completely clear why you're wrapping this template lock around lock.front_door_lock. Can you explain what you're trying to achieve, and what binary_sensor.front_door indicates and why you're using it here? It would seem if the state of lock.front_door is changing quickly, it's not because of lock.front_door_lock but because of binary_sensor.front_door.
And is it even appropriate to use a template lock here instead of a template sensor???
Hello, I'm new to templating in HA. I was wondering if it was possible to use the output of a sensor as an input for something like a Gauge which has min and max attributes. Does it have to allow being templated in order to do this?
You mean use a sensor value for the min/max values?
no that's not possible
Oh ok. Thanks for the reply
@chrome temple - Good question and I see I was not clear. For my front door, I have a z-wave lock (lock.front_door_lock) as well as a open/close sensor (binary_sensor.front_door) .
So in essence, I want to combine "Is the Door Unlocked ?" and "Is the Door open ?" in a single sensor.
I think template lock is required here because I want the ability to remotely lock and unlock this door.
how to count time interval between two states?
9:00:08 PM ac turned off 8:50:56 PM ac turned on
@rough lark you can remotely lock & unlock the lock (i.e., lock.front_door_lock), but you can't remotely open & close the door, can you? (Or maybe you can???) I don't think a template lock makes sense here. The actual lock is locked or not independent of whether the door is open or closed. I think you should use a template sensor that tells you if the door is closed an locked, or not.
I'd have to agree. You're not going to get a 1 entity solution here. You'd want to maybe use a custom lovelace card to handle the look in the UI
@chrome temple @mighty ledge - Thanks. That's what I was using for some time now. I figured I could consolidate both of these into a single entity (that works in HomeKit as well as HomeAssistant UI. I am not sure a template sensor would work either
Here's what happens. Let us say, the door is closed and locked. I would unlock the door (Notification #1) and open it (Notification #2). I think the template sensor would run into the same issue. This might also be because of HomeKit triggering notifications.
Maybe an option might be to create a template lock (with a static value) and use automations to update the status of the template lock. I haven't tried it, but would that work ?
I guess I don't see why you're getting multiple notifications. With the way you have the template lock configured (and assuming you're not using optimistic mode), if either the underlying lock was unlocked, or the door was opened, the state of the template lock should change to unlocked. Now if the other is done (i.e., so that both the underlying lock is unlocked and the door is opened), that should not change the state of the template lock.
@young shadow What does that template say if you try it in
> Templates?
Also, it looks like you have a typo in there:
{{ states('sensor.polcz_garage_distance_sensor')|float > 0.1 or is_state('sensor.polcz_garage_distance_sensor', 'nan') }}
Your closing parenthesis for is_state was in the wrong place.
@ivory delta i get this in at Templates: Unknown error rendering template i will try with the fixed typo
@ivory delta it was the typo, it works now. thanks!
Hello! I have a template for a sensor with names on who last unlocked my doorlock. I want to display the latest sensor value (name) on a card. how?
after searching on google for almost 2 hours i have to ask here. I'm too new to this xD
Have you created a template sensor (https://www.home-assistant.io/integrations/template/) using that template? If not, create that first. Either way, just display the template sensor entity like you would any other entity in HA.
And if you don't know how to do that last part, then ask in #frontend-archived .
@daring musk where are you getting those times from?
from logbook
you can try writing last_triggered or last_changed to 2 separate input_datetimes then do a comparison of the input_datetimes using as_timestamp(state('input.datetime.1')
Yeah, that's way over complicated. 😄 So you only want it updated when it turns on, right?
yeah
i wanna know how long it takes to cool down the room, and based on interval change fan speed (low, med, high)
So you want to know how long it was off basically?
it is a MULTILINE WITH AN IF
And if you don't know how to do that last part, then ask in #frontend-archived .
@chrome temple
Yes i did! 🙂 this type : MULTILINE EXAMPLE WITH AN IF TEST
@daring musk have you looked at: https://www.home-assistant.io/integrations/history_stats/?
@silver pewter sorry, I'm not following you. What is "MULTILINE EXAMPLE WITH AN IF TEST"?
@silver pewter posted a code wall, it is moved here --> https://paste.ubuntu.com/p/dkDxxkN5C9/
Please use https://paste.ubuntu.com/ or https://www.hastebin.com/ to share code or logs.
So you have a template sensor. Ok. So do you still have a question? Or did you get your answer in the other channel?
I want to display the latest sensor value (name) in a card, is it possible?
name on the person who last unlocked door, next to door lock icon 😛
I guess I'm confused because you started by saying, "I have a template for a sensor with names on who last unlocked my doorlock." Now it seems you're saying you don't have that.
Wait, or is that the template sensor you shared? If so, then, again, if you're just asking how to display an entity (in this case a template sensor) in the frontend, then that's a question for #frontend-archived .
ok thank you 🙂
@silver pewter posted a code wall, it is moved here --> https://paste.ubuntu.com/p/q56tXVQNbz/
@silver pewter Rule #6: Spam will not be tolerated, including but not limited to: self-promotion, flooding, text walls (longer than 15 lines) and unapproved bots.
Please take the time now to review all of the rules and references in #rules.
That's not your first codewall. Please respect the rules.
Is it possible to hide "0" (Master) ?
I dont want want it in my sensor
oh, ok sry !
I am using the basic Entities card, how do I go about changing what 'on' and 'off' mean? I am using the Mikrotik Router add-on to do device tracking, but its showing 'Home' and 'Away' for 'online' status
Just take out lines 8 and 9 and it won't ever show 'Master'
is tehre a way to change what 'on' and 'off' mean? 😕
What do you think they should mean instead?
haha is it so simple! Thank you !! 🙂
even a basic "on" and "off" would be better
'on' and 'off' is easy to achieve. Wrap the sensors you don't like in a binary_sensor.
Changing what's shown for other things is a UI choice - you're probably going to want to change that in your #frontend-archived
If you check in
> States, is the actual state 'on' or 'off'?
its on
Yeah, so it's the integration that's deciding to show 'Home', you don't get any control over that.
You either want to customise it in a Lovelace card somehow if you care about what it shows in cards or set up another integration to wrap it. binary_sensor for plain on/off, and a template sensor if you want to decide on the text yourself.
Just take out lines 8 and 9 and it won't ever show 'Master'
@ivory delta this is what happens when i did like u said 😛 see image. Sry for my bad english!
https://imgur.com/2NCn0vq
on the first pic i want the name of the latest person who unlocked the door. When someone unlocks the lock, it automatically locks by itself. and that is 0 master xD
not sure why a networking addon would chose "Home" and "Away" for device tracking status ?
is it possible to do something like (if state is 0, show the state that was before 0) 😛
Not the way you're doing it, no.
Use an automation to save that 'name' to a helper whenever it changes (but only when the new value isn't 'master'). Use the value of that helper wherever you need to see the name.
Not everything is documented. The documents are a toolkit, you still have to build the finished product with those tools.
okey i see. Thank you
This is where you'd save the text: https://www.home-assistant.io/integrations/input_text/
You can figure the rest out or ask in #automations-archived
pnbruckner post here saved me! ! 😄 https://community.home-assistant.io/t/binary-sensor-last-known-state-when-unavailable/59967
thank you mono!
@dreamy epoch all location tracking devices are home/away. People use network connection to determine if they are home or not when gps fails.
ahh. do i have to order devices for a person in a particular way or HA figures it out based on most recent or something?
It’s always the most recent
thnx
hi, anyone want to assist me in a (for me) strange behavior of a binary sensor template?
i'm using the Developer - Template debugging, which shows a relative simple operation : {{ ( as_timestamp(now()) - as_timestamp(states.binary_sensor.slaapkamer_veluxraam_links.last_changed) ) < 60 }} , as True for the first 60seconds, and afterwards as False.
WARNING (MainThread) [homeassistant.bootstrap] Waiting on integrations to complete setup: person
My home-assistant seem to be stuck at this
so, I should think that this operation would result in : 'on' state for a binary_sensor for the first 60sec and afterwards as : 'off' .. but it doesn't .. ?
my complete binary_sensor :
- platform: template
sensors:
slaapkamer_veluxraam_links_last60s:
device_class: window
value_template: >-
{{ ( as_timestamp(now()) - as_timestamp(states.binary_sensor.slaapkamer_veluxraam_links.last_changed) ) < 60 }}
@zenith fractal iirc now() doesn't cause updates, you'll need to use time & date sensor
Any one know why
{{ is_state_attr('light.tv_lamp','flowing','true') }} returns false
https://hastebin.com/buhuziseja.makefile
'true' is a string
Because the attribute is a bool, not a str. Remove the quotes around the word true.
Hey guys, im trying to make a template binary sensor.
When i paste this: "{% if is_state('binary_sensor.server_zeus_ping', 'on') %}Online{% else %}Offline{% endif %}" into the dev tools template section it shows "Online" but when I add it into de configuration.yaml it always shows off. Any ideas?
I would like it to show online or offline instead of home / away or connect or something other
Oh so you want the actual state to be Online or Offline?
Yeah
Ok so make a regular template sensor then, not a binary template sensor
Could even do
@warped hornet posted a code wall, it is moved here --> https://paste.ubuntu.com/p/nbN8QjCDbK/
Any suggestions? Sorry for large code
Or any way to do a forloop for every key in json string?
Could even do
@buoyant pine that worked. Thank you 🙏
@zenith fractal iirc now() doesn't cause updates, you'll need to use time & date sensor
@brisk temple Thanks, I'll look into this
@warped hornet what's the end goal?
hi, new to HA, i know about selectattr to filter based off attr value, but is there a way to filter based off logic, ie can i do selectattr('...', 'gte', 80) or something?
Jinja is used by Home Assistant's template engine, see the Jinja Template Designer Documentation
'gt', 80 worked i guess
search for tests
ahh thnx 🙂
alright one more, in either a autoamtion or script, can i wait until a specific timestamp (coming from sensor state attribute) i see you can wait for a state change but not a specific timestamp?
or i need to do some timestamp math
im guessing im goin to have to write a sensor or two to automate this
@warped hornet what's the end goal?
@dreamy sinew To have a list that I can iterate over instead of a big json tree
that is a mid goal, what is the end goal of the list?
To use it in auto entities together with multiple-entity-row
The json string is in an attribute of a sensor. And I would like to create a entity row for each key in that json structure
what is the platform of your sensor?
you can use attribute_templates and map ur json there no?
The sensor is from the transmission integration
And it's torrent status is a long json string with every torrent name as a key. For each key is there som meta about the torrent
Very impractical I think
you can iterate over dictionaries
Yea, I found the method 🙂
I am trying to add an html wrapper to a template. How would I wrap the 'AM' and 'PM' in a <span> so I can style it?
{{ '{:02d}:{} {}'.format(hour if hour == 12 else hour % 12, time[3:5], 'PM' if hour>11 else 'AM') }} .
I tried a few options with Markup but nothing seemed to work. Any help?
try to get it rendering in the template tester first
once you get there, you can try adding the spans
we'd need to see the full thing you're trying too
Thanks @dreamy sinew I tried entering in the markup in the tester in a few spots but it just renders as a string and not html. Basically in a card, I have the time and AM/PM after it. I want to style the AM/PM to be smaller but it just renders the time and pm without any markup to be able to style it.
gotcha. i haven't touched the cards at all
I'm trying to make a template to select all my sensors of a certain 'device class' e.g. motion for a template automation.
Tried something like: {{ states|selectattr('device_class','in',['motion'])
|list|join(', ') }}
but without success
Any ideas what I'm doing wrong?
selectattr('attributes.device_class',...
should it be preceded by the states| ?
Everything else you had was ok as far as I could see. You just need to add attributes. into the selectattr().
selectattr() looks at the "attributes" of the State Object -- https://www.home-assistant.io/docs/configuration/state_object/ -- like state, last_changed, etc., so to get to what is usually called "attributes" in HA you need to use attributes.ATTRIBUTE_NAME (because attributes is an "attribute" of a State Object. Yeah, I know.)
Hi, I'm trying to subtract two sensors. I don't understand why this is giving me an error:
{{ states('sensor.br_temperature') - states('sensor.bedroom_temp')}}
I'm getting "Unknown error rendering template"
Had to convert to float, it's working now.
Hey guys, had this template that I thought was working but I rebooted HA and saw a error in the log file:
Error executing script. Unexpected error for call_service at pos 1: Error rendering data template: UndefinedError: 'dict object' has no attribute 'to_state'
Well it's telling you the answer. Whatever entity triggered the automation apparently doesn't have a 'to_state'
Check that entity in
> States
That'll do it 😉
I understand, any tips on how to get this to work when im reebooting HA all the time? I found the automation doesnt execute many times because of this
Well your question isn't actually about the templates, so head over to #automations-archived to pick up the rest.
thanks mono
back to templating, trying to figure this one out:
Living Room Motion DateTime Update: Error executing script. Invalid data for call_service at pos 1: extra keys not allowed @ data['data']
any tips on how to write it correctly?
managed to get this to work: https://hastebin.com/likomozodi.cs
but would like to pass the triger name to the template value output, something in this fashion: https://hastebin.com/faxabokaxi.cs
invalid template (TemplateSyntaxError: expected name or number) for dictionary value @ data['action'][0]['data_template']['value']. Got None.
off to bed, will be back tomorow
😴
@lapis quarry if trigger.platfrom == ‘state’ and...
Sorry Petro, I know and apreciate you are just trying to get me to learn and think but I dont get it..
this is the latest I came up with but still doesnt seem to work: https://hastebin.com/kovifefivo.bash
anyone know why this binary_sensor stays off?
gym_shield_plex_in_use:
entity_id:
- media_player.gym_shield_plex
value_template: >-
{{ states.media_player.gym_shield.state not in ["off","idle","unavailable"] }}
the template evaluates to False when i put it in developer-tools/template (because the shield is unavailable)
tried all these combinations: https://hastebin.com/oteheziher.bash
and this example works, with or without quotes https://hastebin.com/abiweyedop.cs 🤔
trigger.to_state.name returns the friendly name of the trigger entity
You'd need to reference the friendly name, or use trigger.to_state.object_id (probably) instead
Ah
anyway thanks for that tip, changed it to object_id as it makes more sense and something good to know for the future
still same behaviour though 😦
having a hard time figuring out what's wrong, but honestly what you could do instead is just write a timestamp to an input_datetime (or that input_text, even) instead of using the template and referencing last_changed @lapis quarry
or, rather, just use {{ now() }} as the value
yes that works
good idea
data_template:
entity_id: >
input_text.{{ trigger.to_state.object_id }}
value: >
{{ now()}}
a lot simpler 👍
Hi
@gleaming urchin posted a code wall, it is moved here --> https://paste.ubuntu.com/p/3wd3x64ypp/
I currently have this as a rest_command - https://paste.ubuntu.com/p/3wd3x64ypp/
And I have this as a light (platform template)
@gleaming urchin posted a code wall, it is moved here --> https://paste.ubuntu.com/p/jg2bP36Ffj/
brightness works, as does on/off, but struggling with set_color
Please could someone nudge me in the right direction 🙂
@gleaming urchin Rule #6: Spam will not be tolerated, including but not limited to: self-promotion, flooding, text walls (longer than 15 lines) and unapproved bots.
Please take the time now to review all of the rules and references in #rules.
Use a code sharing tool for anything longer than a few lines please. There are links in the topic.
When you say you're struggling, what's the problem?
So I'm unsure in the template how to read the color and how to put it in the rest_command :/ (also sorryyy for wall spam)
{{ (brightness /255*100) | int | round(0) }}
``` should be
{{ (state_attr('light.stairs_strip_strip', 'brightness') | int /255*100) | int }}
https://community.home-assistant.io/t/govee-home-products-dreamcolor-led-strip/127979/67 - I've been using this code
btw | round(0) after | int is useless since | int already makes the number an integer (that is, no decimal places)
Sorry by the way, very new to all this :/
did you see what i wrote above?
Thank you, applying that now 🙂
Brilliant, so I have the color wheel now! Now, when I change the brightness, the light turns off completely
This is the config at the moment: https://paste.ubuntu.com/p/HbxDwKCjCb/. The issue is now how to I read the rgb a put it into the restful command, and how do I do the same with brightness
In short, the body of the request to the API should be the following. It's just how do I read that information, and then put that into restful:
"device": "C7:FD:A4:C1:38:BD:34:94",
"model": "H6159",
"cmd": {
"name": "color",
"value": {
"r": 0,
"g": 255,
"b": 255
}
}
}```
I think for now, I'll have it as a brightness and on/off in HA, and can look at color in the future when I'm a bit more used to home assistant. Thanks!
how did you get their api? emailed them?
It's in the app, you go to about, and you can request an API key
it instantly emails it to you
thanks
If you get it working @brisk temple, please let me know!
i'd assume it would be states.sensor.sensorname.attributes["cmd"]["value"]["r"] to get the info
hi all - is it possible to access the last time a state changed from a template?
id like to try do some similar work in templates that you see in the state trigger
ie: if last change was 10 min ago, do this
Yes, you can do something like {{ states.switch.some_switch.last_changed }}
hi all! Why is this temple not working for me with the icon state? what am i doing wrong ? 🙂 https://hastebin.com/odokipefut.cs
i see i forgot to add switch at "{% if is_state('SWITCH.auto_lock_dag', 'on') %}" but still not working 😛
does it work in
->Templates?
What do you mean ? i am new to this
copy and paste exactly that into
->Templates
Looks like it always returns mdi:lock-open-alert-outline. Did you expect something else?
Now you have ‘On’ where you want ‘on’
Pay attention to case
👆
ok, it as "on" before. I try again 😄
Randomly changing things won’t help 🙂
true true !
When in doubt, watch the state in
->States and make sure you’re matching that
ok! it is "on" there 🙂
still wrong icon :/
Can it show the icon from the template there?
and that switch temple text is in this .yaml file : home-assistant\hass.io\homeassistant\paket\idlock.yaml ( packages: !include_dir_named paket . in comfiguration.yaml)
If you see the icon flipping back and forth in
->Template when you manipulate the lock, I dunno what’s wrong
Are you sure that’s the same entity? It doesn’t show your friendly_name
ok i will try that
yes same entity
template in developer tools showing right icon when it is on/off
where did you get "lock-open-alert-outline" from? I don't see it in the Material Design icon list
found code there
mdi:lock-reset works but not lock-open-alert-outline
so maby thats why xD
it didn't show up in VSCode, so that was a clue. there's a lock-open-alert, which maybe has an "outline" variant
if you're referencing a non-existent icon, that would probably show up in your HA log
changed icon and rebooted, still wrong icon. i dont have to add anything on the card itself ? like "icon :mdi..." ?
I believe that HA is using v5.3.45 of the icons, and you may be looking at 5.4.55
shouldn't need to. I'm hacking something together now
ok, now i changed both icons to mdi:baby / mdi:bulb i tested them both on another card and i can see them. rebooted now and still wrong icon
mdi:baby / mdi:home **
Thank you for trying to help me 🙂
i have to seep now, thank you Rob! bye 🙂
seems like maybe it's the lack of a value_template
if you don't include one, it reverts to "optimistic" mode, which means that it just assumes that the device controlled by the switch actually changes state
if I give the switch a value_template, it changes the icon as I expect
you could do the same with the same template you're using for the icon
Can u please tell me what to add o value_template? 😄
{{ states('switch.auto_lock_dag', 'on') }}
ok i try 🙂
my example:
auto_lock_dag:
value_template: >-
{{ states('switch.fr_table_lamp') }}
turn_on:
service: switch.turn_on
entity_id: switch.fr_table_lamp
turn_off:
service: switch.turn_off
entity_id: switch.fr_table_lamp
icon_template: >-
{% if is_state('switch.fr_table_lamp', 'on') %}
mdi:thermometer-minus
{% else %}
mdi:thermometer-plus
{% endif %}
works fine
np, I learned something as well 🙂
Hello again @inner mesa The icon changed with that template but now i cant toggle it on/off . Do you know why ? :p
is it possible to access an add-ons log from a template? I want to monitor the last received date/time on my Tellstick sensors.
I can manually run hassio.addon_stdin with {"addon":"core_tellstick","input":{"function":"list"}} to get a list of all sensors and their values and last received date/time. But that info doesn't appear in the HA log.
Any tips how I could automate and template the actual last updated-value from the Tellstick add-on?
Not likely
@silver pewter Nope, worked fine for me.
@wispy bay
"{{ '-{}'.format(states('sensor.sensor_2')) if states('sensor.sensor_2')|float > 0 else '+{}'.format(states('sensor.sensor_3')) }}"
feel free to flip the sensor order around but that's the jist
@dreamy sinew Thanks! Im going to work on that right now!
oh oops. states('sensor.sensor_2) etc
alternatively, you can do math to flip the sign
-1 * states('sensor.sensor_2')|float if ... else states('sensor.sensor_3)|float
tweaked the full template again, wanted float instead of round
@dreamy sinew absolutely prefect! Thanks so much!
I'm trying to create a sensor from some data. The data is in this format: {"dump" : "Aircraft:20\nPosition:14\nMsg/\s:49"}
this is my config: - platform: mqtt name: "ADSB Sensor" state_topic: "abc/def/ADSB" value_template: "{{ value_json.dump }}"
but my sensor keeps showing "unknown"
are you sure that's the output of that topic?
Please use imgur or other image sharing web sites, and share the link here.
that renders fine when tested
yeah, it worked fine when I tested it, but it doesn't appear to be working in my configuration file
try subscribing to the topic manually in HA
how do I do that?
Go to configuration > integrations > click on configure for the mqtt integration
and it will give you an option to listen to a topic
well, there's my problem. I'm not getting anything...
sounds like either a problem with your mqtt integration config or you're mistyping the topic
probably the mqtt integration...I've tripled checked the topic
anonymous: true
customize:
active: false
folder: mosquitto
certfile: fullchain.pem
keyfile: privkey.pem
require_certificate: false```
that's my config
for the broker
That looks like an addon config. You still have to integrate it into HA
I have this in my config file, too
broker: core-mosquitto
username: xyz
password: 123
discovery: true
discovery_prefix: homeassistant
birth_message:
topic: 'hass/status'
payload: 'online'
qos: 0
retain: false```
broker is supposed to be an ip address
weird, I had it as core-mosquitto there and the addon-config (I guess from the guides?), but it was working fine for my Ring MQTT integration
it seems to be reading the topic now
let me check the sensor
seems to be working now, thank you!
Is there a way to further separate the data? Right now, my single sensor shows: Aircraft:8 Position:8 Msg/s:64. I'd like to separate each into it's own sensor so I can graph them.
Make three sensors that refer to that sensor's state with .split(' ')[0] at the end (use 1 and 2 for the other two sensors)
hmmm...this is weird. It was working fine for a while and now it hasn't updated in 15 minutes
it was updating once every 10 seconds
I should probably move this to another channel since this is getting out of templating. Which channel is best to discuss MQTT issues?
Can someone take a look at this and explain to me why my script isn't restarting? After 10 minutes the light goes off
I've confirmed the fibaro is sensing motion during the 10 minutes, going from off to on
I had to put restart in the automation as well, not sure why it felt it was still running as the delay was in the script
calling a script as you did now waits for the script to complete before returning to the automation
if you call it like this:
- entity_id: script.nightlight
service: script.turn_on
it will go run it separately and immediately return to process the next part of the sequence/action
@brisk temple
Ah, I saw that piece in the script page, thanks for the explanation
I believe the behavior of service: script.xxx changed with the latest additions
The bug fix, broke my work around hah
yeah, I had some like that as well. I started out by going through all my scripts and automations and transforming them to the new "parallel" version, and then I realized that I actually rely on the sequence in some cases 🙂
I have to say that everything is quite speedy now. Faster than it was before
except startup. since the changes to startup i've seen slower overall startup times (but the frontend is available more quickly than before)
around 0.111 or so i saw 20 second startup times
35 seconds now. not really an issue though lol
the improvements came about the same time I moved to the OZW Beta, so it's practically light speed now
I wouldn't notice 10s here or there, it was the 3-4mins that I'm glad is gone
my startup times still take awhile but are MUCH faster
but that's my own fault for being on a rpi
Is there a way to use a variable when trying to access an object? I feel like I am doing something stupid...this isnt working
{{ states.sensor. ~ entity_id ~ .last_changed }}```
ultimately where I am setting entity, im actually trying to simulate entity being passed from trigger trigger.entity_id
Try
states.sensor.get(entity_id).last_changed
@dreamy sinew
Unknown error rendering template
unfortunately no luck
Hmm
{{ states.sensor.get(entity_id).last_changed }}``` does this look right?
assuming I didnt butcher using your suggestion
sec, let me test something
{{ states[entity_id.split('.')[0]][entity_id.split('.')[1]].last_changed }}```
since trigger.entity_id will have the domain
so you'll probably want
@trim leaf {% set entity = trigger.entity_id.split('.') %} {{ states[entity_id[0]][entity[1]].last_changed }}
Hello again, Template Gods! I've got another puzzle for you. Trying to put a line break between two sensor attributes entities like this:
`
{{ states.sensor.tcm.attributes["name"] }}{{" \n"}}({{ states.sensor.tcm.attributes["releaseYear"] }})
It works just fine in the template tool, but in an entities card, it still runs together.
You mean just throw the CR in between the lines? Tried that (because it worked in the tool too) but same effect.
card might be doing things weird
Well, POO! The vertical spacing is what I'm trying to avoid. Any suggestions?
i don't use that card so no ¯_(ツ)_/¯
I don't need to use an Entity Card if you hve a better idea.
haha
most of my stuff is either automation or voice commands
i'm the only one who looks at the ui
typical templates, i got you. UI stuff is its own beast
iirc that card re-implements jinja2 in JS and they do their own thing
Since the last time I was here, I've come to LOVE the template tool.
Maybe I'll try in #frontend-archived just for fun.
Remind me your day job? Wasn't it you who did an integration with Cherwell?
because of HA i added template support to my project
heh my company did. i looked at it though
i wrote our SNOW integration
hehe. Let's talk in #the-water-cooler to keep this one clear.
+1
Hey Everyone - new to the server. Trying to configure my first template for a GoControl WAPIRZ-1, and ive been struggling with getting it to function all night - here is what my template looks like: binary_sensor: - platform: template sensors: garage_motion: friendly_name: "Garage Motion" device_class: motion entity_id: sensor.garage_motion_alarm_level value_template: '{{ is_state("sensor.garage_motion_sensor_alarm_level", "255") }}'
@inner mesa thanks, ill fix that. The sensors is just constantly showing motion detected in the UI
So the sensor itself is reporting unexpected values or the template sensor is?
wait... its working now! only thing missing is the LED light on the sensor doesn't come on when motion is detected
it was the template sensor that was misbehaving
And not anymore
yeah, seems to be working now, just a 3 min delay clearing motion detected
which others have said can happen with this sensor + home assistant
Those are probably device parameters
Or maybe not. I know nothing about that device
yeah, its old and was cheap - not too worried
just moving things off smartthings to retire that hub
@trim leaf
{% set entity = trigger.entity_id.split('.') %} {{ states[entity_id[0]][entity[1]].last_changed }}
@dreamy sinew this works! it seems like we can just avoid splitting at all and doing somethign like this. The square brackets are key, im not totally sure what that syntax means but ill be reading up on it.
{{ states[entity_id].last_changed }}
I am puzzled as to why theres no need to put a . after states though. Either way thanks so much for your help!
a[b] is pretty much the same thing as a.b with the benefit that b can be a variable in the former.
The square brackets are a lookup, e.g. a[0] will get the first element of the list a ("zero indexed" - the element with 0 offset from the start), a[1] will get the second element etc.
a["hello"] will get the element designated "hello" from the object a.
Also, don't forget the cases where you must use the square brackets. HA doesn't like things that start with numbers like sensor.1234. In that case, you have to use sensor['1234'].
I see, thats where I was getting lost, why square brackets were necessary where normally I could just use the var name without any syntax
Why do I not have to include a . between sensor and ['111']
ohhhh because its an object...got it got it
👍
what kills me is lsat night I realized I dont need to specifcally do this because I can use the trigger to/from_state object. That being said this is still great learning of Jinja
If you ignore thomas's examples with indexes (a[1]), the rest are all just saying 'from object x, get the value of key y'.
So x.y and x['y'] are equivalent.
that makes total sense, and in this specific usecase the bracket notation actually works when i am trying to concat a object together from vars
You're technically not concatenating anything. You have a whole object already, you just want to access something by reference instead of knowing the name in advance.
Right got it, what is the technical reason why this:
{{ states.sensor.entity_id.last_changed }}```
does not work, but
{% set entity_id = "master_bedroom_thermostat_hvac_action" %}
{{ states.sensor[entity_id].last_changed }}
does work
Imagine you have an object like this:
myObject:
foo: 'bar'
fizz: 'buzz'```
`myObject['foo']` would be 'bar'
Now let's say you don't know what thing you're looking for until later. So you ask it to look for myObject[x] (important: no quotes around the x). x is a variable now, not a string.
If at the time it evaluates that, x = foo, then myObject[x] = 'bar'.
Likewise, if x was 'fizz', myObject[x] would have been 'buzz'.
In your examples... sensor.entity_id is equivalent to sensor['entity_id']. You're telling it to look for the key called entity_id, not for whatever the variable entity_id would be.
would you expect sensor.entity_id to work?
Not unless you have a sensor called sensor.entity_id...
Nope
yeah okay got it
You want to substitute that value and find the real name.
I was technically incorrect, by the way. As Mono said, a.b is equal to a["b"] with quotes, not .a[b]
Does anyone happen to have an "Average Power Usage per Day" calculation template? 🙂
I'm trying to have an icon changed based on the state of something. I have an MQTT device that sends either 1 or 0 if the device is running or not running. I've tried several different things, but I can't get it change icons like a light would if it were on or off. Any advice?
@small wolf is it a binary_sensor?
@small wolf binary_sensor was the way to go and customize it with a device_class of your choice. If you wanted custom icon's not available under device_class, then you'd have to go about it a different way
@mighty ledge I tried that, but I can't seem to get it to work. The devices show 'off' regardless if the input is 1 or 0.
- platform: mqtt
name: "READSB"
state_topic: "xyz/123/ADSB"
value_template: "{{ value_json.readsb }}"
binary_sensor:
- platform: template
sensors:
readsb2:
friendly_name: "READSB2"
value_template: "{{ states('sensor.READSB') }}"
device_class: power```
well yeah, you didn't specify what makes it on or off.
value_template: "{{ states('sensor.readsb') == '1' }}"
oh 😅
for what it's worth, you should have been able to just add device_class through customization on sensor.readsb without creating the second sensor
oh ok
Hey guys, I would like to store the time and date of an event in a input_text or input_date and compare it to actual time using the time sensor to know how much time has passed from one event compared to the current time. Been playing around in the template editor for the last few days but I cant seem to figure out how to write the template.
I have these 3 variables:
{{states('sensor.date_time')}} (Outputs 2020-08-11, 21:55)
{{states('input_text.motionlr01a')}} (Outputs 2020-08-11, 21:55)
{{states('input_datetime.motionlr01a')}} (Outputs 2020-08-11 21:55:06)
how can I substract one from another to get the time elapsed betwen them?
this is what im trying but doesnt seem to work:
"{{ ( as_timestamp(strptime(states('sensor.date_time'), '%Y/%m/%d %H:%M:%S')) - as_timestamp(strptime(states('input_datetime.motionlr01a'), '%Y/%m/%d %H:%M:%S')) ) }}"
try as_timestamp(states('sensor.date_time'))|float in the template tester and see what comes out
{{as_timestamp(states('sensor.date_time'))|float}} - Outputs: 0
{{ ( as_timestamp(states('sensor.date_time'))|float - as_timestamp(strptime(states('input_datetime.motionlr01a'), '%Y/%m/%d %H:%M:%S')) ) }}
Outputs: -1597168506.0
try using as_timestamp(now()) instead of sensor.date_time
(I also get 0 on as_timestamp(states('sensor.date_time'))
i want to use the result as a trigger so i need it to be evaluated regularly
that is why im trying to use the time sensor
can't do it on a state change of one of hte input_text?
no
im using the input text to store the time of an event, I want that time to be stored permanently and something else to trigger X amount of time after this event occurred, the reason to store it like this its so it trigger regardless of any HA reboot there has been in betwen
as_timestamp(states('sensor.date_time_iso')) seems to work
though the times are different than now()
slightly off i should say
doesnt work for me, output is: none
did you define it as a sensor? https://www.home-assistant.io/integrations/time_date/
yes
paste your automation?
have none, just playing with the template editor
what are you triggering then
dont know if this will help: https://hastebin.com/odigahuxik.pl
its to rewrite an automation im using For: hours to trigger something, but first i need to figure this out..
seems like you want to trigger on a motion detection? and see how much time since that motion was last detected?
yes in this scenario yes, I just want it reliable betwen HA reboots
want to store when motion was last detected, and even if i reboot HA still have that time stored so I can still trigger something X amount of time later
I also need it for another automation I want to trigger 3 days after an event has been detected
and I can be rebooting HA dozens of times in 3 days 😅
you ain't lyin
you can do a time_pattern to check every x second/minutes if your condition value is the time you want
I set timers and use this https://community.home-assistant.io/t/how-to-make-active-timers-survive-a-restart/146248
yes I saw I could do that also
to keep time across reboots
then on timer stop, execute what i want, it won't do over 24hrs though
n/m, he updated it to do over 24hrs
interesting
never used timers
was using For in my automations to count time
but this might make more sense, specially with what you just sent
thans PoPBox, I will give this a try, looks promissing, can a timer be used as a condition in a automation?
any entity can
With timers, you care about when they start/end/restart/cancel.
You can use those as triggers easily enough.
ok i need to give this a good thought as it means a big rewrite in a lot of code and I will brake many things along the way
regardless, would still like to figure my previous issue out, if anybody can point me in the right direction as to what im doing wrong and how to get that to work I would apreciate, this:
this is what im trying but doesnt seem to work:
"{{ ( as_timestamp(strptime(states('sensor.date_time'), '%Y/%m/%d %H:%M:%S')) - as_timestamp(strptime(states('input_datetime.motionlr01a'), '%Y/%m/%d %H:%M:%S')) ) }}"
@lapis quarry
need to go to bed, will be back tomorow, thanks so much!!
Syntax question with Templates. In the link below I have 2 examples of what I am trying to accomplish. Basically, I have a value in a sensor, and I want to math it into another value.
Top half of the example, have a value in hours in one sensor, and I want to make another sensor for the same value but in days. What I have is showing as invalid currently.
Bottom half of the example, I have a value for Total Memory of a machine, and Used Memory for a machine. Looking to do Total / Used * 100 = Percentage. What I have there is not working either, also invalid.
Can anyone take a look and tell me what I am doing wrong?
you're referencing a sensor that doesn't exist
Not as much of an expert in the syntax as others here, but shouldn't used % be used / total?
and you're multiplying hours by 7 to get days (?)
divide by 7, oops
still not right
there aren't 7 hours in a day
7 hours is a pretty short day
lol, math aside, @hollow bramble, using sensor that doesn't exist?
you defined the template sensor as plex_vm_uptime_hours but you're trying to get the state of sensor.plex_uptime_hours
well you're missing the actual states function in the last template
I dont have the skills to review the templates but i dont think you only need to write sensors once: https://pastebin.ubuntu.com/p/HfnJ5cWGgf/
you just wrapped sensor names in parentheses without the function and without quotes
@lapis quarry you can do it either way
👍
You lost me lol. Am I missing the "|int" thing?
you've written (sensor.plex_vm_memory_used_mb) instead of states('sensor.plex_vm_memory_used_mb')
actually, the same with your other template as well
the only ones you have correct are your state_attr templates
post what you have now
yes, and | int goes on the outside of the function
value_template: "{{ (states('sensor.plex_vm_uptime_hours')|int) *24)|round(1) }}"
Right?
Check your parentheses
value_template: "{{ ((states('sensor.plex_vm_uptime_hours')|int) *24)|round(1) }}"
Got it
Quite honestly, I am not even sure why I have the |int there at all
I have learned today that I was not meant to script or code lol
{{ states('sensor.plex_vm_uptime_hours')|int * 24|round(1) }} you can also just lose the logic-only parentheses. Your order of operations is linear
| int is necessary to be able to do math with it. Otherwise it will be a string
All states are strings, so in order to perform calculations with it, you need to convert it to a number via |int or |float.
I hope you're testing your templates before restarting home assistant 😉
Oh, I did know that. Dont know why I havent been using this lol
That seems like a success. But it is telling me 1632 Days online, and I know for a fact its been like 2
/24, not *24
Nailed it
Thank you all!!
{{ states('sensor.blah') is string}} is my go to
Crosspost from automations, since I think I'll need a template for this:
anyone can help me with the following:
I want to create a 'wait untill' automation, where a source_list is the variable. In this case I use node red, but a HA automation is also welcome.
Use case: I use Spotify Connect on my PS4. I'm building an automation where I want to continue Spotify on my PS4 once that is turned on. However, it takes a while untill the PS4 becomes an available source on the Spotify media player. This causes the automation right now to be incosistent. I figured: what if I can create a 'wait until' node. So once the PS4 is available in the source list, it should fire the action.
I tried with Node Red, but I can't get it to work with the 'wait until' node. Most likely since it's a list and JSON isnt my strong suit, so I don't know what to use there
@north acorn
wait_template: "{{ "SpongeBobburu's PS4" in states.media_player.spotify.attributes.source_list }}"
just add that in the HA automation before the action to select source and play
What would a template look like that counts how many device_tracker entities are home?
I've tried this
{{ states | selectattr('entity_id','in', ['device_tracker'])|selectattr('state','eq','home') | list | count }}
I'm using MQTT to report the status of a device. It sends "1" for healthy and "0" for unhealth. The problem is that the device needs to send the health. If I disconnect the device, the sensor I created in HA will keep the last known status (healthy) even if the server is disconnected. Is there a way to force a sensor to change state if it hasn't updated in X time?
@small wolf just change the template to include an unavailable state also
oh i see what you mean now
I think I may have figured it out - testing now
i do something kind of janky that may work for you. start/restart a timer when the mqtt message publishes then change the template to say if the timer is over X time it is unavailable
I just added expire_after: 10 to my MQTT sensor. That seemed to do the trick.
@north acorn
wait_template: "{{ "SpongeBobburu's PS4" in states.media_player.spotify.attributes.source_list }}"
@violet oyster Thanks alot! Is it also possible to inject this into Node-RED?
no clue unfortunately. I don't use it. but itll work for HA
that's fine, I'll just link something from Node-RED to kick in the automation in HA
that works too
what is wrong with this?
cc18323:
entity_id:
- sensor.caltex_gosford_west_pdl
value_template: "{{states('sensor.caltex_gosford_west_pdl')}}"
friendly_name_template: >
{%- if state_attr('sensor.caltex_gosford_west_pdl', 'station_id') == 18323 -%}
{{ Caltex 283 Manns Rd West Gosford }}
{% elif state_attr('sensor.caltex_gosford_west_pdl', 'station_id') == 874 -%}
{{ Caltex 30A Pacific Hwy West Gosford (From Gosford) }}
{% else %}
{{ Caltex 69-71 Pacific Hwy Gosford West (To Gosford) }}
{% endif %}
unit_of_measurement: ¢/L
nvm... don't need the {{ }}
entity_id: timer.geschirrspueler
duration: "11000" -> works
entity_id: timer.geschirrspueler
duration: "{{ states('sensor.siemens_sn678x36te_remaining') | int }}" -> doesn't
or | float
tinkerer... can't find your answer anymore... regardin #1
You have to use data_template: instead of data: when using templates. You can't use templates at developer tools > services (that field is data:)
so in template editor i get a value... but when I want to use it as service data it doesn't work...
oooh.... i'll check
like this:
data_template:
duration: '{{ states("sensor.siemens_sn678x36te_remaining")|int }}'
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
Assuming the indentation is right, yes. You still won't be able to use that at developer tools > services though
data_template:
duration: '{{ states("sensor.siemens_sn678x36te_remaining")|int }}'
thanks 🙂
hmmm... then i get "extra keys not allowed @ data['data_template']
looks like I am still in data mode... when testing it in the development area under services....
development area doesnt take templates
oh... but the syntax is right when using in automations?
Looks fine
I get the same error meesage under LOGS when I try to run the automation.... extra keys not allowed @ data['data_template']
it looks like service data under automations isn't allowing templates as well??
back to automations.yaml?
aaaah..... 🙂 now it is working!
perhaps a toggle switch would be nice, so that you can use the UI for creating automations and even test... to swtich between data and data_template?
I'm sending config topic to the MQTT broker with this payload:
{"name": "Shelly 1 87AA4499 Uptime", "stat_t": "~info", "exp_aft": 43200, "frc_upd": "False", "uniq_id": "shelly1-87aa4499-uptime", "qos": 1, "dev": {"ids": ["87aa4499"], "name": "Shelly 1 87AA4499", "mdl": "Shelly 1", "sw": "20190821-094851/v1.8.0@4148d2b7", "mf": "Allterco Robotics"}, "~": "shellies/shelly1-87AA4499/", "dev_cla": "timestamp", "avty_t": "~online", "pl_avail": "true", "pl_not_avail": "false", "val_tpl": "{{(as_timestamp(now())-value_json.uptime)|timestamp_local}}"}
Created sensor should show human-readable date, but shows timestamp. What is wrong with my template?
value_json.uptime is in seconds.
is uptime an integer or a string
integer
Funny thing, when I configure this sensor manually (via YAML), the sensor displays the date correctly. The problem is with discovery.
that will not work with templates
@daring musk that is 100% incorrect.
that will not work with templates
phnx is right, this statement is wrong fortemplateschannel tho
Is there anywhere that data: is compulsory even if there are no contents?
no, that would be invalid yaml typically
i didn't know sorry 😬
there another way to write this without the two ifs?
{%- for state in states.input_datetime -%}
{%- if not 'End' in state.name %}
{%- if not 'Start' in state.name %}
{{ state.name }}: **{{ state.state }}**
{%- endif %}
{%- endif %}
{%- endfor %}```
if not state.name in ['End', 'Start']
thanks!
Anybody have an example on how to cycle through media_player.source_list? All I found was this forum post but cannot get it to work :/ https://community.home-assistant.io/t/loop-through-media-player-source-list/94785
In a template am I able to find out what platform an entity Id belongs to?
Yes, it's the domain of the entity's state. https://www.home-assistant.io/docs/configuration/state_object/
Alternatively, just read the bit of the entity ID before the .. I.e. light.bedroom_light belongs to the light platform.
Should be able to split on . in Jinja easily enough.
Isn't that the domain not the platform? What I'm trying to do is is create a "Dim If On" script that will loop through the entities in a light.group and if the entity is a single light I want to dim it if on (that I've already created) but if it's a light.group it needs to iterate into all it'sa entity Ids
so I need to know if a given entity id is a light.group as opposed to a light.zha etc
I thought a light.group's platform was still light. The integration is different but the platform is the same.
I guess I might be able to check if the passed in light has the list of entity_ids that a light.group has
There's no way to know which integration created an entity, which I guess is what you want. But for the group stuff, looking for entity_ids kind of works.
yeah thanks. What I'm ultimately trying to do is to create an asymmetric light to use with Alexa. If I say "turn off downstairs" all downstairs lights need to turn off. However if I say "turn on" I only want a small subset to turn on. Then if I want to dim lights I only want to dim the ones I have on
There's no guarantee that no other integrations will add the entity_ids property to their entities, though.
I could create a PR to add something like hue does...
is_hue_group: true
I guess the other option is naming convention in my config make them all end in "_group"
Or adding a property attribute manually with customize.
interesting - never really used those - I'll check them out - thanks
Lets you do things like this: https://github.com/thomasloven/new-hass-config/blob/master/packages/lights.yaml#L110 which gets all lights that have night_light: true.
ooo interesting
oooooooooooooo very interesting
I'm trying to find an example how I can call the following Jinja (enriched with my own comments) from a script.
{% for state in state_attr('light.all_downstairs_lights', 'entity_id') %}
{% if state_attr(state, 'entity_id') == None %}
Call light.turn_on with entity_id from state and a brightness
{% else %}
Call script.dim_group_if_on with entity_id from state and a brightness
{% endif %}
{% endfor %}
(this snippet would be inside script.dim_group_if_on so the else would be a recursive call)
actually scratch that - it isn't light.turn_on I want but my own script so if they are both a script it should be easy using script.turn_on
oh not that easy actually as I need to do...
sequence:
- data_template:
dim_amount: '{{ dim_amount }}'
entity_id_to_dim: the entity we pulled out of entity_ids
entity_id: <EITHER script.dim_group_if_on OR script.dim_light_if_on> depending on entity_id_to_dim
service: script.turn_on
IS there a way to store a variable in entity_id_to_dim and use it later in a for loop in the same script?
Can't you use the new choose option to make that easier to read?
Don't try to put all the logic in the templates, move some out to the flow of the script instead.
true I should be able to do that
@dapper bridge should just be able to expand it {{ expand('light.all_downstairs_lights') | map(attribute='entity_id') | list | join(', ') }} and just use that in a few places. If you make it into a stand alone script, you can even pass 'light.all_downstairs_lights' as a variable.
the expand didn't work on the light group it seemed to return light.all_downstairs_lights
Just tried in template editor and it returns "light.all_downstairs_lights"
ok then change it to {{ states.light | selectattr('entity_id','in', state_attr('light.all_downstairs_lights', 'entity_id')) | map(attribute='entity_id') | list | join(', ') }}
had to edit, missed a )
thanks - that works and gives me a comma separated list but not sure what I can do with that over the list of entity IDs I already have. would seem the list is more useful for then calling another script with the entity id?
if you place that comma separated list into the entity_id inside data_template for a service, it will enact that on all lights included in said list
what exactly are you trying to do
end goal, not the gibberish you posted above
Which bit is gibberish and i'll expand...
What I'm ultimately trying to do is to create an asymmetric light to use with Alexa. If I say "turn off downstairs" all downstairs lights need to turn off. However if I say "turn on" I only want a small subset to turn on. Then if I want to dim lights I only want to dim the ones I have on
The dim bit is the bit i'm working on
I have light.all_downstrairs_lights which is a light group that has 4 other light groups and a single light in it. E.g. light.kitchen_group, light.living_room,group, light.toilet, light.hallway_group
I've got a script called "script.dim_if_on" that takes a entitiy_id_to_dim and a dimming_amount. So I just need to call that with all the individuals lights I have downstairs
Ok, then all you need for the dim the lights that are on:
- service: light.turn_on
data_template:
entity_id: >
{% set lights = state_attr('light.all_downstairs_lights', 'entity_id') %}
{{ states.light | selectattr('entity_id','in', lights) | selectattr('state','eq','on') | map(attribute='entity_id') | list | join(', ') }}
brightness: 20 # Change this to whatever you want here.
as for the the other stuff via alexa, I belive you're going to have a hard time getting that to work. Alexa is the problem there
turning on a subset without a keyword in alexa is pretty much impossible.
I'm using a light.template for that
unless you break it up into rooms or sets yourself
with an on script, off script and dimming script
so I have a light.downstairs_template_light but instead of listing out all the lights i'm trying to use it on light.group to make it easier. Then it will hopefully just be a case of changing the group
if I add new lights
yep, then all you need is the service I just provided
you just need to come up with how you dim it
but that entity_id list will only produce lights that are on. Filtering out the ones that are off
You'll have to copy/paste the code in different areas for the light template though. Can't use a variable for that unfortunately.
I think I still need a way to distinguish actual lights vs light groups
if I call light.turn_on with a brightness on a group it will turn all of the lights on
damn this is trickier than I hoped!
well, it would only do that if you nested your light groups...
yeah I do :S
the kitchen has 5 lights so there is a light.kitchen_group
and to avoid repition the "all_downstairs" uses the groups
I might just put this into app daemon or node red where I think it will be easier
just preferred to rely on something in core home assistant
{% set lights = state_attr('light.all_downstairs_lights', 'entity_id') %}
{{ states.light | selectattr('entity_id','in', lights) | rejectattr('attributes.entity_id', 'defined') | selectattr('state','eq','on') | map(attribute='entity_id') | list | join(', ') }}
that will reject light groups
but if you want it to recursively search into your light groups, then you need to use expand with groups. Or add a feature request to have expand work on light groups.
I understand you may not want to 'duplicate your efforts' but doing this will be painful in general with the configuration. You'd be better off using yaml anchors which does the duplication for you. And then just use easy templates.
what do you mean by yaml anchors?
a yaml anchor allows you to duplicate entries or combine things in yaml.
ah ok - do you know how to make expand work on a component?
at a high level that is
you'd have to add it to the core functionality by modifying HA code
or fork HA and make your own version with that change
either way, nothing easy.
This macro should recursively search light groups and return a list of lights without the group itself
try it out with light.downstairs. Ihaven't tested the code
Maybe this is really a python_script problem?
{{ light_expand('light.all_downstairs_lights') }}
yeah, that would solve it too because it doesn't need any imports
TBH, making expand work on light groups would be nice. But Might get into a 'political debate' if people don't want it to expand light groups.

Math is hard