#templates-archived
1 messages Β· Page 153 of 1
Or, use a frontend card that lets you control how the state is displayed. That's what I do
What frontend card do you use if you don't mind me asking
haha, do you mind posting the code from that card when you get a chance so I can see how you implement it?
That works! thanks for the help
hey guys. is there anyway to concatenate date(yy-mm-dd) format to a REST resource url.
Not sure if you can use a template string here or not but you might want to try that.
checking out template strings.
can you possibly share an exmaple or a link. i dont see any references anywhere.
Well for a start you have to use resource_template: not resource: https://www.home-assistant.io/integrations/rest/#resource_template Then it will be ```
resource_template: "{{ 'http-yada-yada-url' ~ now().strftime('%Y-%m-%d') }}"
Try it in the developer tools template editor.
Hey. I am trying to create some template code that continuously runs all the time. I'm not understanding how I fit this into HA. The syntax I understand fine.
Here is the pseudo code for what I'm trying to do
{% if (media player is not playing) and (media player idle time > 60)}
{turn on switch}
{else}
{turn off switch}
How would I do this since automations cannot have two triggers as an "and"??
Do you actually have an idle time attribute?
You use two triggers and two conditions
But two triggers are an OR condition correct?
I do. I created it.
But the conditions are AND
So either will trigger but both conditions must be true
You should be able to use state triggers and conditions then. No templates required.
OK I see what you mean. My triggers and conditions would literally be the same. That make sense. But then how would I make the 'else' statement to turn the switch off?
Use a choose action. The conditions for the choose would be the playing state of the media player and the idle time.
Straying into #automations-archived territory here...
Oh! I see. That is so obvious now that you say it. Thank you so much!
Sorry for the crossover. I thought I was going to do this with templates
I honestly didn't think automations were an option!
I'm actually thinking you might need another automation for the off case.
As it wont trigger (and pass the conditions) except for the on case.
Actually I think I just thought about how to do it... lemme create it and post it.
Using 'choose'
Yeah don't put the two conditions in the condition block. Put them in the choose action.
Bingo π
@true nimbus posted a code wall, it is moved here --> https://hastebin.com/ropodihuma
This works. Thank you for the help.
And since this is indeed the templates chat... here is what I am using to prevent the automation from triggering every single time the media_player leaves a 'playing' state which happens ALL THE TIME when you are browsing netflix...
value_template: >-
{%- set rokubedroom = states.media_player.roku_bedroom -%}
{%- set time = (as_timestamp(now()) - as_timestamp(rokubedroom.last_changed)) | int -%}
{%- set minutes = ((time % 3600) // 60) | int -%}
{%- set seconds = ((time % 3600)) | int -%}
{{seconds}}
That's my 'idle time'
Anyway I love HA and I'll stop spamming the chat now π
The second can be done a lot easier by doing:
{{ ( now() - states.media_player.roku_bedroom.last_changed ).seconds }}
for my Owntracks templates, I now use {% if value_json is defined and value_json.cog is defined %} {{value_json.cog}} {% else %} Not yet initialized {% endif %} but I was wondering if we couldnt somehow use a 'default' like {{value_json.cog, default='Not yet initialized')}}
is there a way to do that?
Hey there. Quick question. In Templates, is there a way to specify "for each device in group"?
Hi there, I would like to create a sensor template that updates when an entityβs entity_picture is change, what would be the best way to do it? Thanks in advance.
I am wanting to turn all lights on in a group EXCEPT for one. I'm wanting this in Automation.yaml. That's why I'm asking if you can do "For each device in group".
I know I can list each device separately, but was hoping not to do it this way because if I add a new light, then I have to change the automation.
@noble fern Yes! Perfect! That's what I'm wanting. And this can go in action correct?
Ok, and -entity_id is the second line. What exactly does that do? Is that where I would put the service? Sorry, I'm not really sure how to so this π¦ Can you post a more detailed example lets say don't turn on "switch.exclude"?
Yes. I think so π Thank you for your assistance! It gets me in the right direction π
| default("blah")
What are you trying to do? You typically don't need for loops in jinja.
by default, your sensor should update when any attribute updates, so you may not even need the template sensor. What's your actual usecase?
@mighty ledge I want an automation for "dinner time". So, when I say dinner time, it'll turn off ALL lights in my house EXCEPT for the kitchen. I want kitchen to be turned on. Now, I know I can tell it to turn the whole group of lights off, then turn the one on, but then the light turns off then back on if it's already on. Didn't want that effect.
ok so use selectattr and rejectattr to filter your lights down to what you want to turn off
or turn on
{{ states.light | rejectattr('entity_id', 'eq', 'light.kitchen') | rejectattr('state', 'eq', 'off') | map(attribute='entity_id') | list }}
That's a list of entity_ids that excludes light.kitchen and lights that are off. You'd turn off those lights.
Then just turn on your kitchen
Ok. Yes. That sounds good, but I don't know how I would put that in an action π¦ Could you assist? What would I put for service:? I then think I need data_template? Correct?
that goes in your
target:
entity_id:
field with your turn off service
wrap it in double quotes " or use the multiline indicator > and put it on a line below entity_id indented 2 spaces.
Ok. Great. Let me see if I can get this...
Hmm.. Not working π¦ This is what I have... https://hatebin.com/gdnhmofgev
This is the error I'm getting in check config
Error loading /config/configuration.yaml: while scanning for the next token
found character '\t' that cannot start any token
in "/config/automations.yaml", line 1496, column 5
Oh! Ok. Let me double check that π
change the settings on whatever you're using to replace tabs with spaces
That worked π
Perfect! Thank you !petro
Thank you @mighty ledge I meant π
One more question though. I think I turned off my outside lights... Is there a way to limit it to my group of lights I have setup?
Use expand('group.your_group') instead of states.light
@marble jackal That did it! π Thank you!!!!!
Sorry, I see I forgot a quote, but I guess you noticed that
I have a eufy doorbell and Iβm trying to create an automation that saves its entity picture if it has changed - would adding something like {{ trigger.to_state.entity_picture != trigger.from_state.entity_picture }} as a condition be a better approach?
you can use a state trigger pointing to the attribute entity_picture
You could just use the attribute entity_picture
trigger:
- platform: state
entity_id: your.entity
attribute: entity_picture
@mighty ledge anyway you could help me with that same template? not sure what i am not putting in here!
And if you want to use a template, you'll need to add attributes (trigger.to_state.attributes.entity_picture)
Thanks so much @marble jackal you rock!
Can I use variables in state_attr function?
I have a Script, where I want to store some input_number, from the state_attr of another entity ... this other entity is a field in my script ... so I try to pass a field to state_attr...
Thanks dude.
yes you can, just like you are doing here
If you want to store the volume and restore it later, you don't need to do that in in input_number, just use a variable
oh so variables keep their states in different executions of the script?
sequence:
- send tts
- wait_template: "{{ not is_state(entity_id, 'off') }}"
- variables:
volume_old: "{{ state_attr(entity_id, 'volume_level') }}"
- set volume for message
- restore volume using variable
oh great ... thanks
There might be a small portion of the tts sent with the old volume though
If your next goal is to also resume audio streams (Spotify/TuneIn) when sending a TTS, there is a script I created which I shared on the community forum
It also does the volume restore π
oh great π I'll have a look at it .. but my next task would be to support a list of entity ids in my script π
can I create a list of old volume variables? or an array or something like this?
I used the target field to enter the the entity_id's instead of the entity_id field as it is limited to only one item
And if you have multiple targets, you might want to make a list with dictionaries, in which you combine the entity_id and the volume_level, als you need to match the right volume level with the right entity_id
That are great hints... I'll try to get that doneπ
have an automation with action: service: input_select.set_options target: entity_id: input_select.hue_dynamic_scene data: options: > {% set hue_group = states('input_select.hue_group') %} {{states.scene |selectattr('attributes.group_name','eq',hue_group) |selectattr('attributes.is_dynamic','eq',true) |map(attribute='name')|list}} which is probably causing '[homeassistant.helpers.script] Disallowed recursion detected' why would that be? never saw the warning before but did update to latest nightly..
realize this si an automation and script error, but the main reason is the template, since there is no other action..
you have a script that will ultimately call itself at somepoint
nothing to do with your template
specifically, your script mode is restart or queued, and you're somehow calling it to run in itself
Ok thanks . Will post it in automation later on, have to go now. Can I tag you then?
btw this is the beginning, so no self reference at all. only thing can think of is the 2nd trigger also triggers during startup. but I used the mode:restart for that....
id: Auto populate Hue dynamic scene input select
mode: restart
trigger:
- platform: event
event_type: delayed_homeassistant_start
- platform: state
entity_id: input_select.hue_group```
anyways, be back later
uh, you aren't posting the script, i.e. action section
so, you can't tell if it's referencing itself
I don't know how it detects "bad" recursion, but it would look something like:
bad_script:
sequence:
- service: script.bad_script
more specifically, it needs to be mode: restart or mode: queued
could be parallel
that's why I'm saying that I don't know how they detect bad recursion
It knows by knowing the status of itself
max integer (optional, default: 10)
Controls maximum number of runs executing and/or queued up to run at a time. Only valid with modes queued and parallel.
yep
so queued looks like it will also stop
queued will stop if it calls itself
Basically it tracks the stack of calls
that if statement checks to see if itself is in the stack and says "no-bueno"
The action was couple posts upβ¦
I took out the second trigger and the warning disappeared.
I guess another automation also triggering on the delayed startup , initializes the input_select.hue_group.
Apparently that causes a race.
I'd say that's a bug then
Itself shouldn't be in the call stack because it's not calling itself
it should be restarting IMO
hey guys. i have an json api im using in REST platform. The api offers data just fine however it gives a cursor position as the first result, then a second call with the cursor position renders the data. I can use REST to grab the cursor key however how can i use that state_attr or state value as a variable in the next REST call. for example first call would return cursor=1234567889, next REST call with url https:/someurlhere.tld/api/data?cursor=sensor.cursor(state attr or state val). any pointers appreciated.
So today I learned something so hilariously hacky that I wanted to share it. I have like 6 template sensors that are all basically the same thing. There is one per room and the only difference is that the room name changes in each of the entities they look at. So here's an example of one of the templates:
{% set lux = states('sensor.' ~ room ~ '_illuminance_lux_stats') | float(-1.0) %}
{% set threshold = state_attr('light.' ~ room ~ '_front', 'brightness') | int(0) / 5 * light_factor + 75 %}
{% set daytime = is_state('binary_sensor.daytime', 'on') %}
{% if daytime and lux >= 0 %}
{{ lux >= threshold }}
{% else %}
{{ is_state('binary_sensor.bright_inside', 'on') }}
{% endif %}
and room would then be one of family_room, bedroom, etc.
@toxic dome posted a code wall, it is moved here --> https://hastebin.com/kovoyokuho
aw but I counted! that was 15 lines lol
oh I guess it counts the text around the code block. ugh
well anyway what I said was "I found a bug in this template which meant I was going to have to fix it 6 times. I decided this was unacceptable so I set out to figure out a way to DRY it up. I realized creative use of a trigger sensor, a disabled sensor and YAML anchors does the trick:". See the link above for how
obviously super hacky. can't say I recommend it if you want readable config. But does work and definitely amusing
I have been struggling for hours now without success to set up a template binary sensor using a trigger(for auto_off to work) based on state_attr. the Binary sensor keeps returning unknown state. Could someone point out where I'm going wrong?
- trigger:
- platform: template
value_template: >
{% if 'car' in state_attr('image_processing.doods_gate_snap','summary') %}true{% else %}false{% endif %}
binary_sensor:
- name: "Gate Car"
auto_off: 5
state: "{{ trigger.to_state.state }}"```
auto_off requires a time. A time takes one of two forms:
- A string like
HH:MM:SSwhere H = hours, M = minues and S = seconds - A dictionary like so:
auto_off:
hours: 0
minutes: 0
seconds: 0
I honestly have no idea what happens if you just give it 5. Maybe its picking 5 hours?
This is kind of a doc fail though. time should link to something which explains it like template does. I'm struggling to find a link right now
I'll give the above a try. though i dont think it would have an impact in the sensor returning an unknown state?
interesting, I didn't know that worked
oh wait
I see the issue
You are using trigger as if its a state trigger, like to_state.state is going to hold the result, its not
Here's the doc on trigger when the trigger type is template: https://www.home-assistant.io/docs/automation/templating/#template
So based on this what is going to happen is to_state is going to be equal to the state of image_processing.doods_gate_snap since that is what triggered the change
which I don't think is what you want
I believe you just want to say state: "{{ true }}"
The way trigger template works is it triggers if the template evaluates to true and previously evaluated to false. So any time your state template is run that means the template evaluated to true. So you just want the sensor to be on and then turn off again 5 seconds later
probably don't even need the template actually, just state: 'on'
I have tried state: "true" and just now tried state: "{{ true }}" as suggested. both results in an unknown state unfortunately.
Just to be clear, trigger template sensors always start in state unknown. They remain in state unknown until they are triggered. So in other words every time you restart HA or reload templates the state of binary_sensor.gate_car will be unknown until the next time image_processing.doods_gate_snap changes and that template evaluates to true after having previously evaluated to false
then this is most likely where I am fumbling.
yea its a bit unintuitive in that way. One way to fix it would be like this:
template:
- trigger:
- id: car
platform: template
value_template: >
{% if 'car' in state_attr('image_processing.doods_gate_snap','summary') %}true{% else %}false{% endif %}
- platform: homeassistant
event: start
binary_sensor:
- name: "Gate Car"
auto_off: 5
state: "{{ trigger.id == 'car' }}"
now what will happen is it will evaluate your template on start-up and default it to off. Then it will flip on and off according to the template trigger
yep. so this ended up being the case. Thanks for pointing this out.
This works like a charm. Thanks.
You can declare yaml anchors in line without needing that dump sensor
You can yes but you can only anchor an entire object, you can't pick and choose which fields to anchor. And if I anchor the first sensor then that anchor also includes name and unique_id which then causes a duplicate key error later
no
...
state: &state >
{{ template }}
... later ...
state: *state
you can do that anywhere with any object or value
oh! that's neat, I didn't know that one
it's no different than what you're doing
does that work with arrays too? or only objects and strings
yea I know I just didn't know you could anchor something which wasn't a dictionary
<< only works with keyed items
good to know, thanks!
getting back to this, all templates work except this one:{{value_json.created_at|float|timestamp_local(0)|default('Not yet initialized')}} guess the order is too non-deterministic for filtering correctly? even with extra () around the bit before the |default() it shows unknown, instead of the default string
you need defaults all the way through
i'm not sure why you'd need to make created_at a float
that makes no sense to me
it should already be a float if it's a timestamp
and the default for timestamp_local shoud be 'Not yet initialized'
So making the modifications petro suggested just now I realized a flaw. Listening for the homeassistant start event ensures they are set to off after a restart but doesn't cover the template integration being reloaded. So when you click "reload templates" from the server controls page then everything goes back to unknown. To fix that, add this to the list of triggers:
- platform: event
event_type: event_template_reloaded
If created_at is either a number or non-existent then I think you can just do this:
{{ value_json.created_at | timestamp_local('Not yet initialized') }}
If created_at is a string and you have to make it a number first then I think this works:
{{ value_json.created_at | int(-1) | timestamp_local('Not yet initialized') }}
At least based on my reading of the doc on timestamp_local. Says it returns the default if it fails and -1 should induce a failure. Or you could use float but I'm also confused by that
EDIT: Nope, ignore all that. Apparently timestamp_local's default is different and errors on undefined things. Also it apparently is ok with -1. Bad idea, sorry!
haha, well things get even sillier.... as it turns out the whole topic created_at isnt created anymore in Owntracks.... Dont know how this happened, or if this has been going on for a longer time (I dont use it particularly often tbh)... but, even this {{value_json.created_at|timestamp_local('Not yet initialized')}} produces Unknown.
cause you need a default in there
{{ value_json.created_at | default | timestamp_local('Not yet initialized') }}
accessing an item that doesn't exist will return an exception
this does: {{value_json.created_at|default('Not yet initialized')}}, as does this indeed! {{value_json.created_at|default|timestamp_local('Not yet initialized')}} thanks!
Hey guys. How can I skip the zero devision error? This is my code:
- condition: template
value_template: >
{% if states('input_number.masodperc')|int == 0 %}
{% set valtozo = 1 %}
{% else %}
{{ now().second % states('input_number.masodperc')|int == 0 }}
{%endif%}
@cold crater posted a code wall, it is moved here --> https://hastebin.com/ucirajonah
May I know what is going wrong?
@cold crater posted a code wall, it is moved here --> https://hastebin.com/azegamevaz
Rule #6: Please do not post codewalls (text longer than 15 lines) - use sites such as https://www.codepile.net/ (pick YAML for the language) or https://paste.debian.net/ (pick YAML for the language).
Please take the time now to review all of the rules and references in #rules.
solved. thanks.
Can I make a template showing the last two timestamps of a door sensor?
With a template sensor with a trigger, where the current one is the state and the last one is an attribute, I guess
Or I suppose you could refer to existing attributes of a template sensor and build a list of previous time stamps
template:
- trigger:
platform: state
entity_id: switch.fr_table_lamp
sensor:
- name: fr_table_lamp_timestamps
state: "{{ trigger.to_state.last_updated }}"
attributes:
last_updated: "{{ trigger.from_state.last_updated }}"
Thanks. I guess in rare circumstances i would need more than the last two. Then I suppose building a list is better. It's really just to display on my phone's home screen when my toddler began his daytime sleep.
- trigger:
platform: state
entity_id: switch.fr_table_lamp
sensor:
- name: fr_table_lamp_timestamps
state: "{{ trigger.to_state.last_updated }}"
attributes:
last_updated: "{{ trigger.from_state.last_updated }}"
last_five_updated: "{{ ([trigger.to_state.last_updated|string] + state_attr('sensor.fr_table_lamp_timestamps', 'last_five_updated')|default([], True))[:5] }}"
well, that was fun @distant plover
Haha. Thank you.
I'm a bit new to the HA and jinja2 templating syntax. I am creating a template sensor that does some math on its value, however I get errors when the input sensor is unavailable. What's the approach I should make in my template to prevent that?
I have a template for a sensor that updates on the top of the hour (using time_pattern trigger). When starting up HA, the state is unfortunately unknown. How may I use the last value it had before the HA restart?
Add an availability_template so your template sensor is unavailable when the source sensor is
You can add a trigger on the Home Assistant start event and template sensor reload, so it also updates the state then
See the last two triggers here for an example https://github.com/TheFes/HA-configuration/blob/main/include/template/trigger/martijn_house_state.yaml
I'm trying to compare dates but I cant get it to work:
{{ states('input_datetime.abit_date') <= now() | timestamp_custom('%Y-%m-%d') }}
What am I doing wrong here?
Do it the other way around, convert your input_datetime to an datetime object:
{{ as_local(as_datetime(states('input_datetime.abit_date'))) <= now() }}
Hey, I done that with minutes and hours too but It isn't working
.share what you did @stable gazelle
@stable gazelle Please use a code share site to share code or logs, for example:
- https://www.codepile.net/ (select YAML as the language)
- https://paste.debian.net/ (select YAML as the language)
- https://dpaste.org/ (you guessed it, select YAML)
Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.
Trigging on ha start is simple enough. It's getting the previous state value which I haven't figured out. I do not want the value to change except on the top of the hour.
Sounds like your better off with an automation writing the value to an input_number
Ah, yes, that might work. Thanks. -- It's not easy for a n00b to catch all these nuances
not sure what you're trying to do
Execute every input_number.masodperc seconds, every input_number.percminutes and every input_number.ora hours
checkout a timer
I'm not sure what you're doing with the max() part in your conditions, but the main problem is that you're explicitly using "and" and not "or"
and you would need some trigger to actually get the automation to run
is there a template filter to change 0:3 to 0:03?
the value to the right of the colon is 3
3 minutes
{{ ((diff.seconds % 86400) / 3600) | int }}:{{ ((diff.seconds % 3600) / 60) | int }} is my current code, after setting some variables
yes, you can format it to zerofill
that's what you're asking for - add zeroes
that's crazy looking. is that string required? or just format(my_int)?
hmm
it's a format string
{{ (diff.seconds % 86400) / 3600) }}:{{ "%02d"|format((diff.seconds % 3600) / 60) }}
thank you - i was just going to ask how that could be merged with my code. you're a champ
it's from the first link when Googling "jinja zero padding"
ah. thank you. i always seem to have trouble finding things in the jina(2) docs.
%02d sounds like "2 [d]igits minimum, otherwise add zeros the left"
yes
very cool.
Is this good?
timer:
ido:
alias: "Megadott idΕ"
duration: "{{states('input_number.masodperc')|int + states('input_number.perc')|multiply(60)|int + states('input_number.ora')|multiply(3600)|int}}"
I see no issues with the template itself. Not sure if you can use it this way π
but I don't see how it accomplishes the goal of triggering every x seconds, y minutes, and z hours
Interesting, multiply(x) casts incoming strings. the |int parts are unnecessary
second question: is there a function like is_state() that takes 3 arguments? where if it's false, you provide a default value?
{{ is_state("input_boolean.mail", true, "it was false") }}?
eh, that won't help, nevermind. guess i'm looking for an elegant way to say if x == true, y, else, z
a one liner
Because I saw I can use 00:00:00 format or seconds
iif(test,if_true,if_false) was just added
it's a Jinja function, so yes
'1.23456' | multiply(60) has a different result as ``1.23456' | multiply(60) | int` though
yeah, fair enough. it does truncate
it would be weird to represent hours, minutes, and seconds as floats with fractional parts, though π
maybe that's some weirdo metric system thing
well, guess I just came barging in, and didn't know the background
crap. iff doesn't work in the Apple Watch complication template
And didn't recognize the input_number names π
templates are templates are templates
ora makes sense as hours though
Undefined 'iff' when editing the template on my iPhone. It's fine - I'll just create the logic as a new template sensor and ask for that. Thanks for your help
it's iif not iff
Or should I do this?
timer:
ido:
alias: "Megadott idΕ"
duration: "{{states('input_number.masodperc')|int}}:{{states('input_number.perc')|int}}:{{states('input_number.ora')|int}}"
It still doesn't meet the requirements as I understood them. first, they seem to be backwards
second, do you want to do something every input_number.masodperc seconds, and another thing every input_number.perc minutes, and another thing every input_number.ora hours?
what you've constructed is seconds:minutes:hours, which is backward, but the timer you're creating will fire once when that duration expires
it will not fire every so many seconds, and again every so often minutes, and again every so often hours. That would be three timers
my aging eyes - you're right i missed that multiple times. thanks.
So I need to do 3 timers?
Like
timer:
second:
duration: "00:00:{{states('input_number.masodperc')|int}}"
minutes:
duration: "00:{{states('input_number.perc')|int}}:00"
and so on?
You can't use a template like when the timer is defined. You can use one when calling timer.start
Then how should I do that?
define the timer without a duration (it's optional) and start it with the duration you want when home assistant starts or whenever you want
Thank you so much, it worked!
I'm sorry maybe I'm stupid but I don't get it. I should use 3 timer and 3 template or what?
you will need to read that page about how to define timers and start them
here:
timer:
second:
then this automation:
trigger:
- platform: homeassistant
event: start
action:
- service: timer.start
target:
entity_id: timer.second
data:
duration: "00:00:{{ "%02d"|format(states('input_number.masodperc')) }}"
then somewhere else
The "%02d" means seconds?
trigger:
- platform: event
event_type: timer.finished
event_data:
entity_id: timer.second
action:
- do some stuff
- service: timer.start
target:
entity_id: timer.second
data:
duration: "00:00:{{ "%02d"|format(states('input_number.masodperc')) }}"
doesn't "masodperc" mean seconds?
Yes
is there any way to chech if a value is in a list of values by template?
something like: {{ trigger.id in ['time','ampere'] }}
but don't how to do this correctly in jinja
It will add a zero if it is lower than 10, so 2 will become 02
Exactly how you did there
It will return true or false
Do note that referring to the trigger will only work if there is an actual trigger. Not if you test your automation actions from the GUI
Ohh okay, thank you!
hi!
how do i have to filter for a random item in this example list?
{'entity_id': ['scene.a', 'scene.b', 'scene.c']}
Solution π
{{ {'entity_id' : ['scene.a', 'scene.b', 'scene.c']}.entity_id |Β random }}
How do I get the number of seconds of a timedelta object in a template? method or filter?
Well, I can avoid the timedelta thing by going straight to float:
{{ (as_timestamp(now())-as_timestamp(now().replace(minute=0,second=0))) }}
I'm trying to find all entity_id's in an area that start with something, such as light. I know about area_entities() , but I don't know how to use a filter to trim that down to a list of entities that start with "light"
Is there a way to set ELSE IF conditions in a template?
like this?
{{ states.light|selectattr('entity_id', 'in', area_entities('Family Room'))|map(attribute='entity_id')|list }}
Ah I didn't think I could use selectattr. I thought that was for attributes (e.g. friendly_name) and entity_id isn't one of those
Yes, the terminology is confusing. It accesses properties of the state object, and HA attributes can be referred to by "attributes.friendly_name"
Oh that isn't even a HA specific thing, that's just a jinja builtin
the real point is that you don't need to filter entities in the light domain later, you start with them
I was also approaching it from a different direction, starting with expand(area_entities('bedroom')) and then trying to filter from there
Yeah exactly
You can do that as well, I just prefer the other way
selectattr('domain', 'eq', 'light')
Ahh domain. Bleh, that's what I wanted
but you have to start with something, so might as well start with states.light
anyway, there are many ways to address this
Thanks @inner mesa. Playing around with a few different approaches to get a better understanding. Every time I feel like I've finally gotten templates down I try to do something and get stuck lol
I guess this is what my version would have been "{{ expand(area_entities('bathroom'))|selectattr("domain", "eq", "light")|map(attribute="entity_id")|list }}"
Any reason you'd go with yours where you start with states.light vs what I have here? I guess the way I see it is with my solution you're iterating over a shorter list?
Not that that really matters but it's the dev in me thinking that π
Anytime you do expand() you're creating a list, and that can take time and memory if it ends up being a big list. If you start with states.xxx, you're essentially starting with a list that already exists and just iterating over it
it usually won't matter
i get a warning message about the use of float in this template, but i can't see what is wrong with it. am i not implementing it correctly?
the warning is:
Template warning: 'float' got invalid input 'unknown' when rendering template '{% if states("sensor.dryer_power")|float == 0 %} Off {% elif states("sensor.dryer_power")|float <= 4 %} Standby {% else %} Drying {% endif %}' but no default was specified. Currently 'float' will return '0', however this template will fail to render in Home Assistant core 2022.1
Well, according to this warning, your template (states.dryer_power) is/was not a number, so it could not be converted to a float
You probably got this right after a reboot of HA, you can avoid it by using availibilty, in this case availibilty: "{{ states('sensor.dryer_power') | is_number }}" would do the trick
Right now float will default to 0 when it is not a number, but in the future (should already be the case according to the warning), the template will just fail to render
i see. where am i inserting the availability template? as that part of the template sensor? the examples i saw in the documentation were only showing availability, not as part of a bigger template
is this correct?
- sensor: - name: Dryer state: > {% if states("sensor.dryer_power")|float == 0 %} Off {% elif states("sensor.dryer_power")|float <= 4 %} Standby {% else %} Drying {% endif %} availability: "{{ states('sensor.dryer_power') | is_number }}"
template:
- sensor:
- name: Dryer
availibilty: "{{ states('sensor.dryer_power') | is_number }}"
state: >
{{ iif(states("sensor.dryer_power")|float == 0, 'Off', iif(states("sensor.dryer_power")|float <= 4, 'Standby', 'Drying')) }}
also fine π I edited the template to be sure I did not reach the line limit π
thanks!
Is there a possibility to write into the log file? Like for debugging I don't want to spam persistent messages all the timeπ
there is a service for that
I got it working by the way... Your script was a great help... Thanks alot
Oh ok... I'll have a look for this service
My action in my automation seems to be broken, but I've validated the template in the dev tool:
service: tts.google_say
data:
entity_id: media_player.kitchen_speaker
message: >
{% if is_state('binary_sensor.wyzesense_7799a14c', 'on') %}
'Front door was opened'
{% elif is_state('binary_sensor.wyzesense_2', 'on') %}
'Garage door was opened'
{% else %}
'No issues to report'
{% endif %}
cache: true
Originally i had no else text, but included it just for testing and still nothing is played.
system_log.write
I see no issue with it, besides that the quotes around the messages are not needed.
I'll keep trying, thanks!
I might be wrong, but isn't it tts.cloud_say instead of tts.google_say ?
cloud_say is the service which comes with Nabu Case
google_say is the natural voice tts service of, you guessed it, Google
Oh OK... Thanks
Still struggling with an automation. I've checked the template in the developers tools, and with an online json validator and it returns a number, but in the automation, I get "Error while executing automation automation.thermostat: Error rendering data template: UndefinedError: 'dict object' has no attribute 'slots'"
Here's the JSON I'm getting from the MQTT message:
https://pastebin.com/7TLNm08c
service: climate.set_temperature
data:
temperature: '{{trigger.payload_json.objects.slots.[0].value.value}}'
target:
entity_id: climate.z_wave_thermostat
I've tried '{{trigger.payload_json.objects.slots[0].value.value}}' at Tinkerer's suggestion, but no joy.
Any help would be greatly appreciated!!
Well that indicates your payload_json doesn't have slots when it comes in there.
Have you tried a default?
Hi Rosemary, thanks for the help. It sure seems like it has "slots" (excerpt for json below) How would I try a default?
{
"input": "set the temperature to 58 degrees",
"intent": {
"intentName": "SetTemp",
"confidenceScore": 1
},
"siteId": "default",
"id": "549511af-7dc2-46a1-ae14-243da6c4aab8",
"slots": [
{
This error says slots are not present.
So either, they're not in the JSON that HA is getting, or nothing is working the way you expect it.
π I'm going to go with nothing is working the way I expect it! Just found a really cool site: https://jsonpathfinder.com/ and I've pasted the mqtt json in it, and it comes back with
x.slots[0].value.value
so I definitely have slots. I'm just going to keep banging away. Thank you so very, very much for your help
But it's not there when the trigger is triggered.
Have you tried just outputting the whole sensor data there to verify the input?
I've listened to the MQTT topic, but I haven't built a sensor to display what the automation may be seeing, Great idea! I'll give that a go.
You can see the payload in the automation trace
need help with a JS template:
type: custom:button-card
icon: mdi:map
tap_action:
action: url
url_path: >-
https://google.com/maps/@[[[ return
${states.device_tracker.david_phone.attributes.latitude}; ]]],[[[ return
${states.device_tracker.david_phone.attributes.longitude}; ]]],19.5z?hl=no
i know this template is wrong because it just gives me https://www.google.com/maps/@[[[%20return%20$%7Bstates.device_tracker.david_phone.attributes.latitude%7D;%20]]],[[[%20return%20$%7Bstates.device_tracker.david_phone.attributes.longitude%7D;%20]]],19.5z?hl=no when i click the button lol
but i don't know how JS templates work lol
I am having an odd issue with a trigger template sensor not being updated. I've verified that entities are switching to state "on" with the template editor, but the states of the sensors never change (from None, None, and 0 respectively).
https://www.codepile.net/pile/olMzBwRW
Any suggestions on what to troubleshoot next would be greatly appreciated!
Is there a variable I can use to obtain the start time of the automation or would I need to store the time somewhere on start?
I think you mean trigger.entity_id in your templates instead of trigger.id
Yourtrigger.id is 0 as you did not provide one
I did the latter in one of my scripts
but looking at the trace, yo can also use as_datetime(trigger.now)
for an automation that is
considering https://next.home-assistant.io/docs/configuration/templating/#using-value-templates-with-mqtt what would be the correct way to use entity_id and name in the templates? is it {{ value_json.entity_id}} or just the known {{states(entity_id)}}. Docs aren't really concise here, and might benefit from an example... tbh, I dont understand why the former is new, while https://www.home-assistant.io/integrations/sensor.mqtt/#usage-of-entity_id-in-the-template has already been provided for? is there any difference between those?
@silent seal Thefes is right, this is what I use - unique_id: last_motion_seen_in_area name: Last motion seen in area icon: mdi:sofa state: > {{area_name(trigger.entity_id)}} attributes: entity_id: > {{trigger.entity_id}} only wish we could set a default, preventing the ugly 'unknowns' on startup...
No need to tag me, I posted that at 2am and went to sleep.
And if you need to save something, put it in a helper variable and use that as your default.
Thanks, that was it! 2am brain.
have another issue with those though, any idea why: - entity: sensor.last_motion_seen_in_area secondary_info: last-triggered shows 'Never triggered' ?
how to put in condition if binary sensor is off for 5 seconds?
conditions: "{{is_state('binary_sensor.kitchen_stove_state', 'off')}}"
Why not just use a state condition check?
That would be a lot easier indeed
condition: state
entity_id: binary_sensor.kitchen_stove_state
state: 'off'
for: "00:00:05"
If you really want it in a template, you can compare last_changed with now()
You could however do something like
{{ is_state('binary_sensor.kitchen_stove_state', 'off') and (now() - states.binary_sensor.kitchen_stove_state.last_changed).seconds >= 5 }}
Though it's a terribly ugly approach
Thanks guys!\
guess I was confused too... adding attributes: last_triggered: > {{trigger.to_state.last_changed.isoformat()}} makes an attributes . This is a sensor, not an automation/script...
entity_id: all```
this works, but I wondering, how to write exception for couple of lights?
I know that except: is not yet introduced although it has high votes on community forum π
- variables:
reject_list:
- light.light_1
- light.light_2
- service: light.turn_off
target:
entity_id: >
{{ states.light | rejectattr('entity_id', 'in', reject_list) | map(attribute= 'entity_id') | list }}
You can also define the reject_list variable in your template, but this might be easier to maintain
And you could add a check if the light is on
I can't get it working. The balkong_dorsensor_timestamps is unknown: ```# Logge balkongdΓΈr
template:
- trigger:
platform: state
entity_id: binary_sensor.balkong_dorsensor
sensor:- name: balkong_dorsensor_timestamps
state: "{{ trigger.to_state.last_updated }}"
attributes:
last_updated: "{{ trigger.from_state.last_updated }}"
last_five_updated: "{{ ([trigger.to_state.last_updated|string] + state_attr('sensor.balkong_dorsensor_timestamps', 'last_five_updated')|default([], True))[:5] }}"```
- name: balkong_dorsensor_timestamps
What is the error you get?
he would get failures on startup with the default he chose.
change your + sign to ~
and remove the []
unless you're trying to keep it a list
I think he does.
But the sensor will be unknown after a reboot or template reload until it is triggered. A reboot or template reload will also cause the data to be lost. If you want to store it permanently, you will need to store it in an input_text
Not sure what I'm doing wrong here
"{{ (now() - states.cover.living_room_shade_1_window_covering.last_updated).seconds > 14400 or (now() - states.cover.dining_room_shade_1_window_covering.last_updated).seconds > 14400 or (now() - states.cover.breakfast_room_shade_2_window_coveringlast_updated).seconds > 14400 }}"
TypeError: unsupported operand type(s) for -: 'datetime.datetime' and 'NoneType'
I'm trying to make sure a few shades opened more than 4 hours ago.
you are missing a . before last_updated in the last part
Wow thank you not sure how I didn't see that
fyi, you can make this more manageble:
{% set t = now() - timedelta(seconds=14400) %}
{% set entities = 'cover.living_room_shade_1_window_covering', 'cover.dining_room_shade_1_window_covering', 'cover.breakfast_room_shade_2_window_covering' %}
{{ expand(entities) | selectattr('last_updated', '<', t) | list | count > 0 }}
then you just add an entity to the list if you get another cover
thank you that looks a lot better
I don't see any errors.
The idea was to have a template widget show the last 5 times I opened a door.
As fes said, the way it's coded, it will only populate 5 times and then reset after a restart
so, you need to have 5 updates before it will fill up with updates
why do you even want this btw? What's the point of knowing the last 5 updates?
Oh. As in opening the door 5 times?
It'll be the times my toddler went to sleep and then awoke.
I can then quickly see how long it has been since he fell asleep.
why don't you just use the history stats integration and count the number of times the door is opened
It might be that i have yet to have the morning coffee, but i cant wrap my head around how to make this a binary sensor. It is bluetooth beacon being used to tell if someone is "home". I want to add all the people into a group, but from my understanding i need this sensor to be binary for the group to display as 'home' and 'not_home' for automations sake.
- platform: template
sensors:
matthew_home:
friendly_name: Matthew Home
# entity_id: sensor.mt_bc
value_template: "{% if is_state('sensor.mt_bc', 'garage') %}Home{% else %}Away{% endif %}"
That is the current sensor set up, could someone help me out with making it into a binary sensor?
binary sensors can only be on or off, not home or away
Didn't know about that one but when I tried now I don't see how I can use it. Its current state is 10 and value: 2m. I need the timestamps from the times the door is opened.
You're better off with an automation and writing the values in a input_text
Or maybe a SQL sensor with this? SELECT state, last_updated FROM "states" where entity_id = 'binary_sensor.balkong_dorsensor'
might also be a good idea, take them from the database. I'm not that familiar with SQL though, so I can't help you with the right query
I can test both. Is there a service to write to input_text? EDIT: Found it. Thanks.
But I would have to append values X times... ?
The set service only asks for value.
So I would have to read initial state and add that + the new value?
{% set example_state = 'a, b, c, d, e' %}
{% set new = 'f' %}
{{ (example_state.split(', ')[-4:] + [new]) | join(', ') }}
if he's using sql he doens't even need to do that. Just split the values or leave it as is in the template sensor, both resolve to a list
True, automation might give the opportunity to filter out updates after a reboot though
That's fine, so long as the I can get the group working correctly, I don't care what it reports as because I can template another sensor for other uses as needed.
You'd have to make a device_tracker out of it, not a binary_sensor
or make all your people into binary sensors and look for on/off
or make a template sensor that does what you want the group to do
you have many options
anyone that could comment on what I'm doing wrong here?
you can't execute js templates like that, everything needst o be in one [[[ ]]]
url_path: |
[[[
return `https://google.com/maps/@${states.device_tracker.david_phone.attributes.latitude},${states.device_tracker.david_phone.attributes.longitude},19.5z?hl=no`;
]]]
might be easier to manage if you use var too
url_path: |
[[[
var lat = states['device_tracker.david_phone'].attributes.latitude;
var lon = states['device_tracker.david_phone'].attributes.longitude;
return `https://google.com/maps/@${lat},${lon},19.5z?hl=no`;
]]]
Meh... the SQL sensor was silly. Could only take one row. Had to GROUP_CONCAT the last 10 of the last_updated. So I guess I have to template out the values I need based on the ; separator I used. π
yes, that's expected
but you can plop the results into an attribute
in a separate template sensor
hehe... that's funny. But I guess there's a way to extract the values by separator with templating as well?
Yeah, {{ state_attr('sensor.balkongdor_apnet', 'last_updated').split(';')[0]}}
Five of those and I have my pretty little list of the 5 last times the door was closed π
Update [Solved] : Hi all! I'm having trouble with an oddly formatted php widget. I'm looking to create a scrape sensor for the top right cell of that page but I have only managed to scrape the whole row so far. Can anyone help?
- platform: scrape
name: Nameday
resource: https://www.eortologio.net/widget.php
select: "tr:nth-child(1) > td:nth-child(2)"
scan_interval: 86400
{{ state_attr('sensor.balkongdor_apnet', 'last_updated').split(';')[:4]}} will give the the first 5 entries as a list
hey guys, completely new to home assistant. Is there an easy way to add a template that I found online that is supposed to make one of my devices perform as expected?
there are so many ways to screw that up and that's assuming your terminology is correct. How about you describe your situation and link what you found
sure, I have one of the hampton bay zigbee fan controllers hooked up to one of my fans. successfully got it added in HA, but noticed I am missing a fan speed setting. This particular model has 4 speeds, and HA only gives me access to 3. A kind gentleman posted his workaround with templates and scripts on this forum
https://community.home-assistant.io/t/king-of-fans-mr101z-missing-max-setting/267131/13
you copy the template directly into configuration.yaml and the scripts go in your scripts file or you can add each one in the UI
@mighty ledge and I assume that I change a couple of variables referencing my device name and ID to correspond to my actual device?
@blazing echo posted a code wall, it is moved here --> https://hastebin.com/savedavaha
Hi, sorry forgot hassbot.
all you have to update is the entity_id for the fan that you're fixing. It's inside a template for the template fan and it's inside all the scripts
@mighty ledge Thank you!
you won't be able to give it a state on startup because it doesn't have a previous state
states are cleared on restart
you have to wait for a webhook to come in
adding a home assistant trigger will not make it magically know a state unless you're going to hardcode it to off or on
yep, thanks, can I not use the homeassistant start trigger as a second trigger for it then? and then edit my binary sensor state template there?
yes I'm looking to hardcode it to off on hass start
then add trigger id's to each trigger and add an ifstatement to your template to handle each trigger id
this sensor detects if im on a teams call - if im restarting HA I'm def not on a work call!
OK I was trying that, I got this but it didn't work:
state: >-
{% if 'provider' in trigger.json %}
on
{% if trigger.id == 'ha_start' %}
off
{% else %}
off
{% endif %}
Not sure what I'm getting wrong?
you have two "if"s
ok yes, thanks! elif
it's bad syntax
sorry that was re-written in discord - i did use elif in HA a few mins ago!
Or maybe - would I be able to just drop the elif? as its either on if from a webhook (with 'provider', or its off otherwise?
that seems rational
I'll try that now!
you're also not outputting anything
check the trigger id first
you can do that much more succinctly and actually output something with {{ iif(your_test, 'on', 'off') }}
this didn't work
Sorry, not sure what you mean. I've also tried this: https://www.toptal.com/developers/hastebin/yilejimaqe.yaml
{{ trigger.id == 'webhook' and 'provider' in trigger.json }}
order of operations with and statements
if the first part of the and fails, it doesn't touch the second
thanks - thats useful to know. I'm still struggling though - and sorry @inner mesa couldn't get my head around that either! I've tried this https://www.toptal.com/developers/hastebin/iferapejey.yaml
but the binary sensor is now unavailable
HA start does not mean template reload π
yep good to check, i am definitely feeling a bit dense tonight, i DID do a ha reload!
also, the template I provided is all you need
you don't need to specify the other conditions as true/false represents on/off
true, I keep forgetting that it accepts a boolean value
Oh right - of course, right I get it cos if it falls down before the and it knows the sensor should be off! So sorry! Wow thats really cool isnt it!
it pays to write lazily because then you don't have to edit much
Ah.... well now restarting HA it goes to unavailable... but then reloading template entities it goes to unknown (as expected)
both from restart or reload - the webhook correctly sets the state....
follow up question, and I apologize if this is better suited for a different channel, is there a way to get my fan to either default to the highest setting when being powered on, or have it remember what setting it was on before being powered off?
Why does 2022-03-15 15:42:58.152704 become 14:42 and not 15:42? {{as_datetime(as_timestamp(state_attr('sensor.balkongdor_apnet', 'last_updated').split(';')[0])).strftime('%H:%M') }}
what timezone is last_updated in?
if it's UTC, then it's applying your local TZ
if it's coming from the database, it's utc
Hm. It's a query on the database: SELECT state, GROUP_CONCAT(last_updated, ';') last_updated FROM (select * from states WHERE entity_id = 'binary_sensor.balkong_dorsensor' and state = 'off' ORDER BY last_updated DESC LIMIT 10);
+1, CET
yah, then 14 makes sense
How to fix? π
what's there to fix
that's the correct time in your timezone
15 UTC is yourtime 14
so the actual event occured at 14 your time, but it stored it as utc
so nothing to fix
I'm confused. 2022-03-15 15:42:58.152704 is correct. That matches when door was opened. Even though history on the door says 15:47 and not 15:42
So a SQL select on the database gives me the time in CET it seems? Or perhaps my query is wrong somehow?
Wait... I think it's the use of last_updated that confuses me. When I check the door sensor the last_updated is 16:42 and that at least matches 15:42 I get from the query. But the logbook says door sensor was last opened and closed 15:47.
this worked beautifully!!! Thank you so much :) It solved a big problem for me!!!
How can I check if availability of my template sensor works ok? I wrote this availability_template: "{{ (states('binary_sensor.sensor_1') not in ['unknown', 'unavailable'] and states('binary_sensor.sensor_2') not in ['unknown', 'unavailable']) }}", but how can I see if it works (without disabling both sensors)? Or, some of the experts can tell me if this will work? Thanks!
Developer Tools / Templates, looks ok to me (other than not needing the parentheses outside everything).
If they want to verify the behaviour themselves and it's difficult to genuinely trigger those binary sensors, you can also use Dev Tools / States to fake a state change
Yes, that might do it, thanks!
Not sure if it's more or less lazy, but sometimes I'll just make dummy input booleans so I can make a nice little testing panel in Lovelace.
π€ Also not a bad idea!
Is this normal behaviour or it just doesn't make sense to me? If I use "and", and only 1 sensor is unavailable, template sensor is unavailable. But if I use "or", template sensor becomes unavailable only when BOTH sensors are unavailable?? π
Apparently availability uses some sort of inverted logic π
In the actions of an automation, is there a way to throw an if then template with multiple service calls?
Yes, the service: action accepts templates. Or you can use a choose: action.
@fossil venture This is what I'm trying to do: https://paste.debian.net/1234316/
As you have more than one service for each condition you would be better off with a choose: action. See https://www.home-assistant.io/docs/scripts#choose-a-group-of-actions
Otherwise it would be two templates, one for the entity id to unlock and one for the scene to activate.
Thank you.
not sure if this is the right place to post, but i'm trying to figure out what is causing this warning in my logs:
WARNING (MainThread) [homeassistant.helpers.template] Template variable warning: 'dict object' has no attribute 'click' when rendering '{{ value_json.click }}'
i'm guessing its something related to an ikea remote but i can't seem to figure out what is causing it. its all over my log
I don't think template sensors are available in statistics graphs by default. Is there a way to get statistical data (e.g. mean, min, max, etc) out of template sensors?
If you use the new template sensor integration add state_class: measurement if you are still using the legacy template sensor platform you will have to add this option to your sensor using Customize.
is there an easy way to track who was last in a zone, i.e. home? I'd like to leverage this in some logic for automations that include mobile push notifications. for example
IF garage door left open
THEN notify all who are home. If no one is home, notify whoever was last home
Not sure if #templates-archived are the best solution, if I can use another automation to set & update the value of another sensor based on zone changes.
What would be the best way for device tracker since the main entity is based off mqtt_room and doesnt include device tracking..
Im thinking that templating them into a binary sensor and then into a group might be the easiest way to get this done?
you can use the device_tracker.see service to create a device tracker and/or update its state
.see?
@lyric socket posted a code wall, it is moved here --> https://hastebin.com/detomemepu
hardly a code wall, but ok i get it.
Hmm that seems to only be available with a time trigger. I'm trying to setup a sunrise effect based on when it receives a webhook. So I'm thinking either 1) create some datetime entity to store the initial webhook time and use that to determine what the color temp/brightness should be, 2) use some internal automation specific variable (is that possible?) to store the progress of the effect, 3) use a simple input number entity to store progress. What sounds like the best option?
If you don't use delays or wait in your automation, you can just use the current time at that moment, either using time conditions or using now() in a template
And you can always store the value of now() in a variable at the start of your automation
G'day! I've a sensor that is being fed info and I have a template sensor that changes it from kW to W. Problem is, that the template sensor is being refreshed once a second because of the original sensor. Is there a way to tell it to only do it once a minute without having to resort to the long way around with automations? Surely, there's an easier way. Have I missed something in the docs?
why are you trying to throttle it?
I have it in an apex chart and it's constantly updating every second which prevents me from clicking on things in the view or looking at graphs etc, I have to jump in in-between reads.
It seems to be taking up resources the way it is
apex card has an update_interval you can apply
always take the easiest route first π
It does? Bloody hell, I have missed that. Thanks. Will go and test it now.
Bloody brilliant. Thank you. That's just the ticket. I'd been looking at it for too long and didn't want to have to go down the re-inventing the wheel route with extra sensors and automations etc.
if one was looking for template tutorials for dummies, where would one look? π I'm trying to sort sensors from the "Afvalbeheer" hacs integration by date... eventually to trigger a notification the day (at 7pm) before the waste that needs to be taken out (if that makes sense)....
Some kind of way to check if a forecast will contain a specific attribute condition n hours in the future?
Trying to check if the wind matches and will continue to match between a range for a couple hours.
What's the difference between
message: >-
{{ 'Volume: ' ~ entities[repeat.index-1].old_volume ~ ', Entity: ' ~ entities[repeat.index-1].entity_id ~ ', Message: ' ~ message }}
and
message: >
{{ 'Volume: ' ~ entities[repeat.index-1].old_volume ~ ', Entity: ' ~ entities[repeat.index-1].entity_id ~ ', Message: ' ~ message }}
When using this in a script, both seems to work the same way π€
I think this belongs in #templates-archived ....
I am starting to get into more advanced automation and would like to trigger an HA Automation 15 minutes prior to my Google Home's next alarm. I have a Sensor I've created to track the status as True/False if the current time matches the alarm time, but I'm having trouble walking it back 15 minutes. I figured I'd store this in a input_datetime and I've found a couple posts on this but I'm having a hard time getting started as I'm new to this whole side of HA outside the GUI.
Anyone have a minute to help a newbie out?
how is next alarm represented in your entity? Take a screenshot of the entity & it's attributes in the developer tools -> states page
the current value of sensor.nesthub7ae3_alarms is 2022-03-16T09:40:00-04:00
@lavish marlin posted a code wall, it is moved here --> https://hastebin.com/fozoforire
@mighty ledge
how are you identifying the alarm currently?
that value is the next alarm
just off the state?
so the current value of sensor.nesthub7ae3_alarms always shows the timestamp of the next alarm
yeah
ok
lol it just occurred to me that you're the one writing the post im trying to follow
this trigger will trigger 15 minutes before your next alarm
- platform: template
value_template: "{{ now() >= states('sensor.nesthub7ae3_alarms') | as_datetime - timedelta(minutes=15) }}"
ah
if you want it as a binary sensor
template:
- binary_sensor:
- name: Next Alarm Grace Period
state: >
{% set alarm = states('sensor.nesthub7ae3_alarms') | as_datetime %}
{% if alarm is not none %}
{{ alarm - timedelta(minutes=15) <= now() <= alarm }}
{% else %}
False
{% endif %}
wait, hold up, how do I use that code? Where do I actually put it? In my automation in the GUI?
i understand what a trigger is as in an event that triggers something, but not in terms of HA
im assuming this is https://www.home-assistant.io/docs/automation/trigger/
?
Having issue with a template.
if ( bearing | float >= 0 ) and ( bearing | float <= 160 )
TemplateError('TypeError: '<=' not supported between instances of 'str' and 'float'')
ok so I add this to my config.yaml?
trigger: !include triggers.yaml```
according to https://www.home-assistant.io/docs/automation/trigger/ i need to include that code in my config
Yeah
ok, so how do you normally add triggers for your automation?
Oh derp. It's something else having issue.
that line wouldn't produce that error
Yeah I'm realizing that.
ohhhh
if ( 0 <= (bearing | float) <= 160 )
I'm asking because I don't know how you use HA, so you have to explain how you normally create automations
I normally create them in the GUI
Which I'm seeing now... Triggers > Template > Value Template
I'm assuming thats where {{ now() >= states('sensor.nesthub7ae3_alarms') | as_datetime - timedelta(minutes=15) }} goes?
yes
This seems to be where the issue lies then.
set bearings = state_attr('weather.XXX_hourly', 'forecast') | selectattr('datetime','<=', end) | map(attribute='wind_bearing') | list
that would do it on startup
what is end?
'round 6 hours
it can't be that because your error is stating it's a float
what's the value of end in your template
i.e. post the whole template
Moment, sure.
Good extension for the code fence or there no extension for the kind of templating we're using?
what do you mean code fence?
{% set end = now().timestamp() + (6 * 60 * 60) | int %}
{% set bearings = state_attr('weather.xxxx_hourly', 'forecast') | selectattr('datetime','<=', end) | map(attribute='wind_bearing') | list %}
{% set bearingsOK = true %}
{% for bearing in bearings %}
{% if ( 0 <= (bearing | float) <= 160 ) %}
{% set bearingsOK = false %}
{% endif %}
{% endfor %}
{{
bearingsOK
}}
thank you sir!
Syntax highlighting for code-blocks I guess.
ah, the code is jinja but the extensions for it suck
Ah
if you're referring to vscode extensions
Oh I meant to highlight it here. After ``` you can specify an extension/language.
I forget what I use, i'll have to look when I get home
ooooh, yeah no, don't worry about that
anyways, change end to
{% set end = (now() + timedelta(hours=6)) | str %}
or
{% set end = (now() + timedelta(hours=6)).isoformat() %}
it depends on the format of datetime in forecast
Example datetime: 2022-03-16T09:00:00-04:00
you may actually have to use utcnow() too, depending on the tiemzone of datetime in forecast
ok
The dash/hyphen is used to truncate whitespace. https://jinja.palletsprojects.com/en/2.10.x/templates/#whitespace-control
And that timezone matches mine.
ok thanks π makes sense
to make it compare best....
{% set end = (now().replace(microsecond=0) + timedelta(hours=6)).isoformat() %}
Cool. Seems to have done it.
Hm. Seems like something is going wrong. I'm guessing the set bearingsOK = false is in the wrong scope.
Ergo it's always true. I've set the invalid bearings to 0-360, aka every direction, and it's still valid.
Apparently set ns = namespace(foo=false) can be used. e.g. set ns.foo = true
just filter your list more
no need for namespace
{% set end = (now().replace(microsecond=0) + timedelta(hours=6)).isoformat() %}
{% set bearings = state_attr('weather.xxxx_hourly', 'forecast') | selectattr('datetime','<=', end) | map(attribute='wind_bearing') | list %}
{{ bearings | select('>=', 0) | select('<=', 160) | list | length == 0 }}
Sorry, i appear to have linked an old version. For the sake of completeness, here's the current one: https://jinja.palletsprojects.com/en/3.0.x/templates/#whitespace-control
The bearing check got funner given I have to check other bearings and how I declared the device_class. I can't exactly share the actual numbers because it's specific.
(
(bearings | select('>=', X) | select('<=', Y) | list) +
(bearings | select('>=', A) | select('<=', B) | list) +
(bearings | select('>=', G) | select('<=', F) | list)
) | length > 0
I could get the length of each of the sub-lists, chain them, or anything else, but this was the least effort.
what's your endgoal here?
are you just tring to get wind direction so you can shut blinds or something?
@fickle gale
Avoid blowing smoke over neighbors, ourselves, or the interstate.
We'd like to not incinerate our garbage but every once in a rare while we exceed what we can shove into our trash cans.
But we'd like to avoid burning if it's going to hit ourselves, the interstate, or neighbors.
Plus this is a fun exercise in working with lists and whatnot.
Hi,
Have some templates for weather (temp, humidity, pressure) sensors. All is working fine, but I am seeing warnings in log. Please take a look and suggest what is to be done.
code: https://dpaste.org/JFnk
log: https://dpaste.org/UBew
Thanks.
Just after a reboot HA tries to render the templates when your source sensors are not available yet. So it tries to create a float out of unknown
This now still results is 0 but in the future this will make the template run in error, unless your provide a default yourself
Even better is to provide an availlibility_template so your template sensor returns unavailable when the source sensors are not reporting an expected state.
Hi everyone.
I'm a beginner.
I would like a card that changes the image based on whether an automation is running or not.
I understand that to see if an automation is running, I need to monitor the current attribute
https://www.codepile.net/pile/RrP3pl8x
But what is the right syntax?
got it, thanks
please don't edit your post to bypass the line limit. Thanks.
use
Please use a code share site to share code or logs, for example:
- https://www.codepile.net/ (select YAML as the language)
- https://paste.debian.net/ (select YAML as the language)
- https://dpaste.org/ (you guessed it, select YAML)
Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.
and post your code there so it has proper formatting, then paste the link here.
check this out https://github.com/custom-cards/button-card
your state coloring should be in a states list, you have:
states['automation.pump'].attributes.current:
- value: 1
entity_picture: /local/My_icons/Irrigazione_ON.png
- value: '0'
entity_picture: /local/My_icons/Irrigazione_OFF.png
it should be something like:
state:
- value: '1'
entity_picture: /local/My_icons/Irrigazione_ON.png
- value: '0'
entity_picture: /local/My_icons/Irrigazione_OFF.png
Yes, the other buttons I've created are made as indicated by you but refer to the state of the entity.
How can I refer to the 'current' attribute of the entity: automation.pump?
Youβll have to make a state template extracting the attribute, like this example
This is the template youβd use for value
value: "[[[ return states['automation.pump'].attributes.current == 0; ]]]"
I have issue with this template,
TRUE {{ state_attr('sensor.sms_parsed', 'number') }}
{% else %}
FALSE {{ state_attr('sensor.sms_parsed', 'number') }}
{% endif %}```
It is forwarding incomming SMS to Telegram, but I want to have filter for number. I have double checked, that attribude number is in format "number=countrycodephonenumber" but still it always end with false state
here is screenshot from template editor
Remove the quotes around the number in your check
is there a way to add current date (YYYY-MM-DD) to a REST url.
Thanks, that was the issue, it was int not string.
Yes, use the resource template option. Something like this, resource_template: "{{ http...url-yada-yada ~ now().strftime('%Y-%m-%d') }}"
fyi, ~ now().date() does the same thing without needing to format it
I have a variable that is defined in a script... can i modify this variable in a repeat loop that is one level below?
sequence:
- variables:
entity_volume_dict: >
[ SOME CODE TO CREATE A DICTIONARY ]
- repeat:
count: "{{ entity_volume_dict | count }}"
sequence:
[ HERE I WANT TO MODIFY AN ENTRY OF entity_volume_dict ]
no, you have to make a new variable that you modify in the loop
you should never have to do that anyways
that's a no no in most languages
ok ... so I try to describe what I'm trying to do:
I have a list of smart speakers ...
then i want to go through every speaker, play some silent music and obtain the current volume level ... and i want to create a dictionary that has the volume level and the entity combined ...
ok, you can do taht in a single template prior to the loop
should I post what I have till now?
sure
So this is my current approach:
https://www.codepile.net/pile/L2XRgNo9
at the point where the temp variable is defined, I'd like to store the current volume in the dictionary I created above
oh really?
you can access the volume levels in 1 variable
you can play a song on all of them at once
can you hint me how?
you feel entity_id a list of entities...
same as every service call
the only time you'd need to loop is if you want to set them to different volume levels
otherwise you're muting them all, so they are all getting true -> 1 service call
you're playing the same sound on all of them -> 1 service call
can I pass a list of entity ids to the mute and the play service calls?
you can pass a list of entity_id's to every single service
oh ... that's something I must have missed ... ok that makes everything much more easy π
thanks
you've never turned on multiple lights?
sure ... but somehow I was thinking that this only woks with switches or lights ... not with every service π
uh ... yeah makes sense somehow π
only time you need to separate it per entity_id is when the data you're setting differs
I see
I guess I don't understand what you're doing anyways still
you make that dictionary wihtout grabbing the old volume
also, that volume grabbing template can be simplified to
{% set entities = entity_id | default([]) %}
{% set ns = namespace(info=[]) %}
{% for e in expand(entities) %}
{% set ns.info = ns.info + [ dict(old_volume=e.attributes.volume_level, entity_id=e.entity_id) ] %}
{% endfor %}
{{ ns.info }}
without all the safety checks
yes ... I wanted to "prepare" the dictionary and modify it later ... but I understood the right approach is creating the dictionary later, where every information is available
thanks alot
Seems like you are still rebuilding my script π
BTW you don't need to play a silent mp3, just turning your media_player on will make the volume_level attribute available
Made the same mistake at first π
That's what it's doing?
ffs, lol
i was going to add a selectattr('state','eq','on') to ensure the media_players were on
but I didn't know what the intentions were
I assume (based on earlier posts) that he wants to send a TTS (or similar) and then resume the music which was playing, or restore the old volume
But if media_players are off there is no volume_level attribute. Sending a silent mp3 will work, but turning them on is enough
I was very happy when the in 2022.2 all Google Cast devices remained idle and never turned off. But that was removed in 2022.2.4
For some reason I can't get spotcast working when I run cast as custom_component, so now I just change 2 lines in the cast integration after every update of HA π
Exactly what @marble jackal is saying π and thanks for the hint with setting the device to on π
and yes I'm rebuilding the script to understand what you are doing ... and later I might just use your script as it also has the possibility to resume the stream that was playing π
Hehe, okay! Good learning experience π
thanks
thank you and sorry for late reply. i will have to format it as such {{ now().strftime("%Y-%m-%d") }} however my next question being, how can i get date for the day before a lets say 5 days back from now.
pfft, faster than I could get to a laptop to type that π
lol
so {{ now().strftime("%Y-%m-%d") - timedelta(days=1) }}
sorry i didnt understand your question. property of being too noob at all this π
how do you get the current date/time out of a template?
im using {{ now().strftime('%Y-%m-%d') }} to get just the date in format YYYY-MM-DD
you're using it in your template already, so the answer should be quick. But you need to understand this, otherwise you'll be here every day
yes, but what gets you the current date AND time
use the template editor if you have to in order to answer the question
{{ now().strftime('%Y-%m-%d %H:%m') }}
try just using now() in the template editor
got it. so using just now im getting date/time in format 2022-03-17 10:27:03.845775-05:00
alright, so now you know the answer to my question
that's a datetime object. It represents the current day and time
in code
you can do all sorts of things with it, one of them being subtracting a timedelta
if you subtract 2 datetime objects, you'll also get a timedelta
gotcha
i know i have a lot of reading to do. def working on reading up the docs as much as i can do im not posting already answered questions.
fyi, stftime is a function on a dtatetime object
so, if you subtract a timedelta from a datetime object, you'll get another datetime object
then you can use .strftime on that datetime object to get whatever info you want out of it
i.e. (a - b).stfttime(....
so, hopefully you can drum something up and post it here, i'll help with corrections
thank you for explaining this.
this is what i pieced together and tested in dev/templates to be working
{{ (now() -timedelta(days=5)).strftime('%Y-%m-%d') }}
yep, that's it
thank you for the help. i cant say i wont bother you guys again lol but it will def be for something other than time π
It's not a bother, but I've seen you here a lot recently and an explanation is probably better than just giving you the answer
im 100% for learning because it just helps develop further understanding. sometimes i do however look for an example or approach so i can then connect the pieces.
Any pointers to how i can count all my updates ? if i use version then i can only see one update for core but what about addons ?
The "Hassio" integration has entities for that:
i run Ha OS , it says its auto installed
i only have the Binary sensor for update /yes/no and what version
I am looking to make a template binary sensor that tells me if my robot vacuum has cleaned today. I want to do this by creating a template that looks at today's history and reports back if the state has been "cleaning" for atleast 30 minutes.
I know how to do this, but I am unsure of how to reset this template at the end of the day. Do I -have- to use an automation for this reset?
good , found those. let me enable some and ill see if what i can see
got a small brain buster situation lol. have a REST platform resource url that requires date format YYYY-MM-DD. i can validate the date format via dev/templates just fine, the url is good as i can simply add in todays date 2022-03-17 and it returns data however using date function {{ now().strftime("%Y-%m-%d") doesnt work. https://www.toptal.com/developers/hastebin/govinucele.yaml
ok got what i need , thanks.
now just need to make a counting template and done π
mine:
# True if there's updates available for any addons
- name: "Updater Supervisor"
device_class: problem
state: "{{ states.binary_sensor|selectattr('entity_id', 'search', 'update_available$')|rejectattr('object_id', 'match', 'syn_nas')|selectattr('state', 'eq', 'on')|list|length > 0 }}"
{{ states.binary_sensor|selectattr('entity_id', 'search', 'update_available$')|rejectattr('object_id', 'match', 'syn_nas')|selectattr('state', 'eq', 'on')|list| count }}
works for me
you can get rid of the "rejectattr('object_id', 'match', 'syn_nas')" part if you don't own a Synology NAS and it's not a problem here π
Hello. Will this work?
{ % if states('sensor.time') | float > 12:00 and states('sensor.time') | float < 20:00 % } {{ states('sensor.office_desk_energy_today') | float * (0.081700 + 0.120881 + 0.072282 + 0.010463 + 0.048039 + 0.002809 + (12.84/30.4375) - 0.000254) }} { % else {{ states('sensor.office_desk_energy_today') | float * (0.081700 + 0.072282 + 0.010463 + 0.002809 + (12.84/30.4375) - 0.000254) }} % } { % endif % }
I put it in the developer tool but all it shows me is the if/else statement with the value of the sensor
{% else %}{{ stuff }}{% endif %}
converting time to float probably won't do what you want
{{ stuff }}
{% else %}
{{ other stuff }}
{% endif %}```
Oh, thank you. I think that did it.
${{ states('sensor.office_desk_energy_today') | float * (0.081700 + 0.120881 + 0.072282 + 0.010463 + 0.048039 + 0.002809 + (12.84/30.4375) - 0.000254) | round(2) }}
{% else %}
${{ states('sensor.office_desk_energy_today') | float * (0.081700 + 0.072282 + 0.010463 + 0.002809 + (12.84/30.4375) - 0.000254) | round(2) }}
{% endif %}```
gives me a result of `$0.0`
Because I don't have any data yet. Tomorrow I will
The built in temperature sensor for my aircon is inaccurate and I am trying to replace the attribute in the climate entity with the value another sensor. I can never figure out what the required format is. This template works in developer tools.
climate.daikin_ac:
current_temperature:
platform: template
{{ states('sensor.art_room_temperature') | round }}```
This just removes the current temperature value instead of replacing it.
I thought customize was used to modify an entity
I can use customize to set it to fixed value (which is obviously of no use)
You can't change the state of an entity like that
You can create another entity based on it, as shown at the link
You can only set static attributes like that
ok thanks
I guess it must be only evaluated at startup or reload
I would personally use today_at('12:00') < now() < today_at('20:00') because then you are actually comparing datetime objects
Would you consider to use the generic thermostat integration to get your Daikin AC into HA instead? In that integration, there is a target_sensor setting in the yaml where you can just specify sensor.art_room_temperature. Then the climate entity will just use that sensor's reading as the temperature attribute.
I used the UI to set up the integration.
So...using the Daikin AC integration?
Heh if everything else is working fine, I would say...just tolerate the inaccuracy if it is not super off? Otherwise, if you integrate it by a generic thermostat, you can specify a different temperature sensor but it would also mean you need to manually set up all the other functionality that the Daikin AC integration currently handles for you.
You can go totally into the weeds with generic thermostat though.
Was trying to avoid that. I have some other generics but it makes my system messier than Iβd like. I might just add a second (more accurate) temperature display next to it.
Anyway -definitely off topic now for template group
Yup that's a good idea...handle it through frontend. Then maybe set up an automation to convert between the actual temperature and what your AC thinks it is.
π
you need to use resource_template, not resource
@mighty ledge I need ur genius
selectattr('state','eq','on')|
rejectattr('attributes.type','eq','browser_mod' ) | map(attribute='entity_id') | join("\n")
%}```
How do i put this inside a list
{% set lights_on = expand(states.light) |
selectattr('state','eq','on')|
rejectattr('attributes.type','eq','browser_mod' ) | map(attribute='entity_id') | join("\n")
%}
{{ list.append(lights_on) }}
{{ list }}
I did this
@inner mesa
data:
title: Popup example
card:
type: entities
entities:
- {%expand(states.light) | selectattr('state','eq','on')| rejectattr('attributes.type','eq','browser_mod' ) | map(attribute='entity_id') | join("\n") %}```
Like is this possible?
Just don't use join and use list instead
And don't tag people, just ask and wait until someone helps you
And you don't need to expand states.light
Hi,
Pls help me with right formatting. I want to set icon when my robot vacuum is charging depending on the charge state. In this example I want to set icon when the battery is equal or more than 50% and less than 75%.
Thanks!
{% if (is_state_attr('select.p2028_2418c6162245_a_l','vacuum_status', 'Charging') and state_attr('select.p2028_2418c6162245_a_l','battery_battery_level') >= 50) and state_attr('select.p2028_2418c6162245_a_l','battery_battery_level') < 75)%}
you don't need the surrounding parentheses, but otherwise it looks fine
it has to be part of a larger template and part of an icon_template
hi all! I am having some trouble to join some entities in a template also adding some text and validation
Currently, this is the template:
{% for i in range(0, 9) %} {% if is_state('sensor.ical_loy_ical_event_' + i|string,'unavailable') %} {% elif as_timestamp(state_attr('sensor.ical_loy_ical_event_' + i|string, "start"))|timestamp_custom('%-d') == as_timestamp(now())|timestamp_custom('%-d') %} {{ as_timestamp(state_attr('sensor.ical_loy_ical_event_' + i|string, "start")) | timestamp_custom('%H:%M') }} {{ state_attr('sensor.ical_loy_ical_event_' + i|string, "summary") }} {% endif %} {% endfor%}
I would like to check for duplicated state_attr summary and also add some text between the hours
hello
how do i get the state before the last_changed state ?
I have an rf based binary sensor, that goes to the unkown state on restart
I'd like to make an automation that returns that sensor that returns it to the state before the unkown state on HA start
when i try states.entity it just shows me the current state it's in which on restart would be unkown
?
trigger.from_state The previous state object of the entity
you can debug it by starting an event listener in events under developer tools
Won't work after a restart of Home Assistant, it will not be known them.
Easiest is to copy the change of the binary sensor to an input_boolean and use the state of the input boolean to retrieve the last state after a restart
Alternative is to get the last known state out of the database using an SQL sensor or similar (based on your database type)
If you go for the first option it is probably easier to just use the input_boolean and toggle that based on the rf commands
Very thorough nice π
Got any ideas on this one mate ?: https://community.home-assistant.io/t/use-variable-in-kodi-call-method/402636
is_kitchen is defined inside the script, not in the automation. I think youβre miss understanding how variables work. They need to be declared inside what youβre using.
Hi dude π
It's quite possible...But when looking in the event debug and the error in the homeassistant.log in the terminal I can see the variable is_kitchen is set
Itβs not in the automation
The automation has no concept of it
Youβre attempting to use a variable that doesnβt exist in the context youβre using it in. That will cause errors in your template
I thought the issue was i was trying to pass the variable through - service: kodi.call_method but it doesn't support it as it tries to pass it through event_type: kodi_call_method_result which spews a kodi json api error.
one sec gotta go to the other room, woman is using this tv
The issue is your automation template is invalid syntax due to the variable not being declared
Also, your script isnβt built to accept variables either.
Put your logic in the script and your automation will send yes to is_kitchen
@fresh yoke posted a code wall, it is moved here --> https://hastebin.com/uqupixeciv
(: it was a message with an embedded code wall but whatever
When running the script: ERROR (MainThread) [homeassistant.components.kodi.media_player] Run API method media_player.bhtpc.Player.GetItem({'playerid': 1, 'properties': ['file'], 'variables': {'is_kitchen': 'yes'}}) error: {'code': -32602, 'data': {'message': 'Too many parameters', 'method': 'Player.GetItem', 'stack': {'name': 'Item.Fields.Base', 'property': {'type': 'string'}, 'type': 'array'}}, 'message': 'Invalid params.'}β¨Do I have to pass the variable through service: kodi.call_method otherwise how else will the automation event event_type: kodi_call_method_result see it ?β¨Or am I way offβ¦?
ffs sorry about the formatting , pasted from a file
Please use a code share site to share code or logs, for example:
- https://www.codepile.net/ (select YAML as the language)
- https://paste.debian.net/ (select YAML as the language)
- https://dpaste.org/ (you guessed it, select YAML)
Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.
I guess the question simplified is how do a pass a variable through or from service: kodi.call_method so that it is seen by the automation event event_type: kodi_call_method_result and use it there. Because the event result is needed the logic needs to be applied in the automation not the script. I think.
Petro already said
If i put the logic in the script then it would still have to assign the entity_to variable. How would that variable be passed to the automation instead of being used at part of the kodi api call? the only way the automation can see it is through the service: kodi.call_method right ?
I know i'm grasping at straws but it's what i've got stuck in my noodle...
Your script should have the variables that are passed to it. Not the variables that the automations trying to use.
kodi_get_playing_from_bedroom:
alias: "kodi get playing from bedroom"
sequence:
- service: kodi.call_method
data:
method: Player.GetItem
playerid: 1
properties:
- file
target:
entity_id: "{{ entity_to }}"
And your logic just makes no sense, no matter what I see
there's nothing coming from your automation trigger that will specify that "This is the kitchen"
so even if you plop the logic into the script, it's not going to do anything
your event has an entity_id in it, but you aren't using it
Unless your'e trying to apply this to the other media_players, but you haven't described the intent
So how about we back up and you explain what you're trying to do. When I get back from my run I'll respond
Explain the overall picture, not this narrow view into your single script
fair enough, i'll update the ha forum page with that info and report back. cheers
alright here's a more descriptive post of what i'm trying to achieve, what i've done and why: https://community.home-assistant.io/t/use-variable-in-kodi-call-method/402636/2
Anyone have an example of templating an attribute of a sensor?
Yeah i just found that as you were typing and giving it a shot, its a ways down on that page for sure.
fyi, replied
Have you switched to #449717345808547842 yet?
hahaha

Yup thats what i was looking for. Now to find out a way to use a sensor as a value for a config entry
you can't unless it allows templates
Seems that my end goal is going to be hard then I anticipated...
Is it possible to use the Time Templates for other time zones, or just the one HA is registered in?
If you construct a string with the time, you can make the time zone offset whatever you want
What might that look like, i cant wrap my ead around how that would work
overly complex, but :
{{ ((now()|string).replace('-07:00', '-08:00')|as_datetime|as_local).strftime("%H:%M") }}
changing the 7 or the 8 doesnt change the time (when using dev tools template at least)
does for me
{{ now().strftime("%H:%M") }}
{{ ((now()|string).replace('-07:00', '-08:00')|as_datetime|as_local).strftime("%H:%M") }}
->
This template updates at the start of each minute. might be why π
12:20
13:20
hmmm nope. very weird
{{ now().strftime("%H:%M") }}
{{ ((now()|string).replace('-07:00', '-08:00')|as_datetime|as_local).strftime("%H:%M") }}
{{ ((now()|string).replace('-07:00', '-0:00')|as_datetime|as_local).strftime("%H:%M") }}
returns
13:21
13:21
13:21
disregard. figured it out.
Now, i need to figure out the -07:00 as we do stupid DST and that number will change
Hi, how can i write thsi with state_attr()?
states.sensor.swx1_sensor.attributes['extruder']['target']
state_attr('sensor.swx1_sensor', 'extruder')['target']
or probably state_attr('sensor.swx1_sensor', 'extruder').target
Thanks!
And I have a problem with REST & resource_template
I would like to kinda nest it. 1st request into second.
https://pastebin.com/2Km580CJ
state_attr('sensor.swx1_sensor', 'print_stats').filename is succesful when used in a template like:
- platform: template
sensors:
swx1_filename:
unique_id: sensor.swx1_filename
friendly_name: "Filename"
icon_template: mdi:layers
value_template: >-
{{ state_attr('sensor.swx1_sensor', 'print_stats').filename }}
but not in the rest-request
rest request in the template should look like this http://192.168.178.66/server/files/metadata?filename=PETG_Retraction_1.5-4.0.gcode2
you need two REST sensors
Hmm but still not working. How can I ensure, that the second REST sensor (named sensor 2:) is using the right values?
oops passed out at 3.30am. Thanks for taking a look mate, that's great. I'll update as test as soon as i'm functionally conscious again. yee ha!
Hmm, request is empty all the time.
Seems, like this is not working, file is empty
resource_template: >
{% set file = state_attr('sensor.swx1_sensor', 'print_stats').filename %}
{{ 'http://192.168.178.66:7/server/files/metadata?filename={}'.format(file) }}
But when i evaluate state_attr('sensor.swx1_sensor', 'print_stats').filename i got a filename.
okay after some waiting i got this in my swx1_file:
<template TemplateState(<state sensor.swx1_file=OK; friendly_name=SWX1_file @ 2022-03-19T22:47:09.633892+01:00>)> But no real data. although I have a GET request with the correct filename now http://192.168.178.66:4444/server/files/metadata?filename=PETG_Retraction_1.5-4.0.gcode
working with 1 now (y)
{{ now().tzinfo('Israel') }} Why is this wrong/gives the error its not callable?
I am lost at how to phrase this for you to be able to help as you have yet to help in a useful way that helps to attain the end goal.
Hey,
Whats the correct way of getting ints of the values ( Trying to do: value_template: "{{ states('sensor.multisensor_cleaning_room_humidity') > (states('sensor.multisensor_6_humidity') + 5) }}"
)
What do you want to actually print out/do with this information?
I want a bool, so basicly when the humidity in the basement is higher then rest of the house, start the ventilation
Thats why im adding the +5 for some margin of error
I am wanting to grab either Time Zone ID attribute (America/Denver), the Time Zone Short (MDT) or the UTC Offset (-21600000) from my phone and displays the timezone my phone is in using a MD card, entity card, doesnt really matter the card at this point as long as it updates with the time my phone is in.
Is it possible to simplyfy this double asignment of layer and layers?
sensors:
swx1_layer_count:
unique_id: sensor.swx1_layer_count
friendly_name: >-
{% set layers = state_attr('sensor.swx1_file', 'result').layer_count %}
{% set layer = (state_attr('sensor.swx1_sensor', 'toolhead').position[2] | round(2) / state_attr('sensor.swx1_file', 'result').layer_height) | round() %}
Layer{{ [" (of ", layers, ")"] | join if layer < layers else "s" }}
icon_template: mdi:layers
value_template: >-
{% set layers = state_attr('sensor.swx1_file', 'result').layer_count %}
{% set layer = (state_attr('sensor.swx1_sensor', 'toolhead').position[2] | round(2) / state_attr('sensor.swx1_file', 'result').layer_height) | round() %}
{% if layer > layers %}
{{ layers }}
{% else %}
{{ layer }}
{% endif %}
I'd look into custom #frontend-archived cards that can use one of the many JS libraries out there to do this for you.
The sensor exists, so you'll be able to read the data, it's just a question of doing something with it.
And take a look at this forum thread, instead of setting the time_zone as a string, set it from a variable. https://community.home-assistant.io/t/its-all-about-time-which-we-have-plenty-of/186577
So to summarise: Use the World Clock integration (https://www.home-assistant.io/integrations/worldclock/), and set your time_zone to "{{ state_attr('device_tracker.your_device_id', 'Time Zone') }}" or whatever is appropriate.
Let me give that a shot, it errored out earlier, but i may have missed something
It'll be something like sensor.mobile_device_geocoded_location actually, had a brain moment
The worldclock integration isn't dynamic
Darn, I thought it would be as the full config check didn't fail
Sounds like that's something someone could add though π€
Aha, and now it fails. Dang it!
Could be modified to accept a select entity
That sounds pretty handy
Yeah same error, as you found too.
- platform: worldclock
time_zone: "{{ state_attr('sensor.tristan_s_s21_current_time_zone', 'time_zone_id') }}"
Invalid config for [sensor.worldclock]: Invalid time zone passed in.
Which is a shame as it would be a brilliant hack
right, which would be simple too.
I have been trying to template a Date & Time entity for a timezone (dynamically pulled from the attribute), but no luck on that either even though the functions are baked into HA Core to pull time zones.
How so?
For the time being, this might fit the bill. You'll need to install it via HACS.
https://github.com/wassy92x/lovelace-digital-clock
Invalid DateTime Invalid DateTime
type: 'custom:digital-clock'
timeZone: "{{ state_attr('sensor.tristan_s_s21_current_time_zone', 'time_zone_id') }}"
with or with out the quotes gives same error
Darn it, worth a try at any rate
A simple Python script will do it, but you can't template a command line sensor
β config git:(main) β cat tzconvert.py
from datetime import datetime
import pytz
import sys
print(datetime.now(pytz.timezone(sys.argv[1])).strftime('%H:%M'))
β config git:(main) β python3 tzconvert.py 'America/New_York'
20:16
Not dynamic though
I have this that works:
{{ (as_timestamp(now()) - as_timestamp(states('sensor.nas_last_boot'))) // 60| round(1) }}
but when I try and remove .0 it can't get it to work:
{{ (as_timestamp(now()) - as_timestamp(states('sensor.nas_last_boot'))) // 60| round(1)| replace('.0','') }}
That's because it's a number, and you're trying to treat it as a string
If you want an integer, try | int perhaps
{{ (as_timestamp(now()) - as_timestamp(states('sensor.nas_last_boot'))) // 60| round(1)| int }}
?
Yes, though technically that would make the rounding unnecessary
ohai it works
the docs are wrong
sensor:
- platform: command_line
name: Other Timezone
command: >-
python3 tzconvert.py "{{ states('input_text.test') }}"
We are really freaking getting somewhere!!
So i would need to make an auto with the trigger of the attribute changing to then update the command line entity correct
You are only rounding the number 60, order of operations error. Put some parentheses around the whole thing then round or use the |int filter. {{ ((as_timestamp(now()) - as_timestamp(states('sensor.nas_last_boot'))) // 60)| int |}}
the way I wrote it, you just update an input_text to reflect whatever timezone you want the time of the command_line sensor reported in
and it updates every minute (and can be configured)
hmm templates arent my strong suit when I tried that I get an error
There's an errant | at the end.
Left over from cutting out the unnecessary round()
Try this: {{ ((as_timestamp(now()) - as_timestamp(states('sensor.nas_last_boot'))) // 60)| int }}
amazing! thank you so much π
Is there a way to call just that sensor to be reloaded via automation?
yes, via homeassistant.update_entity
Duh of course, its just a sensor
and using this as the command_line sensor will just grab whatever time zone the phone reports:
- platform: command_line
name: Other Timezone
command: >-
python3 tzconvert.py "{{ state_attr('sensor.robs_iphone_13_geocoded_location', 'Time Zone') }}"
What would be the better way...
python3 tzconvert.py "{{ state_attr('sensor.robs_iphone_13_geocoded_location', 'Time Zone') }}"
or updating a input text?
python3 tzconvert.py "{{ states('input_text.test') }}"
that's for you to decide
I thought that you wanted the time to reflect the timezone of wherever you happen to be, so the phone seems to be the source of that info
but whatever you want
if you understand what it's doing...
One is less "steps" than the other. If setting by attribute, then it would be every minute it would check correct?
it's not a matter of steps, but where you want the info to come from