#templates-archived

1 messages Β· Page 153 of 1

inner mesa
#

you can create a template sensor for the state and can return anything you want

#

Or, use a frontend card that lets you control how the state is displayed. That's what I do

rancid portal
#

What frontend card do you use if you don't mind me asking

inner mesa
#

custom button card

#

it'll even make you breakfast

rancid portal
#

haha, do you mind posting the code from that card when you get a chance so I can see how you implement it?

inner mesa
#

there are extensive docs with examples

rancid portal
#

That works! thanks for the help

mellow knot
#

hey guys. is there anyway to concatenate date(yy-mm-dd) format to a REST resource url.

exotic dirge
mellow knot
mellow knot
fossil venture
#

Try it in the developer tools template editor.

true nimbus
#

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"??

fossil venture
#

Do you actually have an idle time attribute?

inner mesa
#

You use two triggers and two conditions

true nimbus
true nimbus
fossil venture
#

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.

true nimbus
#

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?

fossil venture
#

Use a choose action. The conditions for the choose would be the playing state of the media player and the idle time.

true nimbus
#

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!

fossil venture
#

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.

true nimbus
#

Actually I think I just thought about how to do it... lemme create it and post it.

#

Using 'choose'

fossil venture
#

Yeah don't put the two conditions in the condition block. Put them in the choose action.

true nimbus
#

Bingo πŸ˜‰

silent barnBOT
true nimbus
#

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 πŸ™‚

marble jackal
floral shuttle
#

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?

rocky crypt
#

Hey there. Quick question. In Templates, is there a way to specify "for each device in group"?

topaz cave
#

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.

rocky crypt
#

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.

rocky crypt
#

@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 πŸ™‚

mighty ledge
mighty ledge
rocky crypt
#

@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.

mighty ledge
#

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

rocky crypt
#

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?

mighty ledge
#

wrap it in double quotes " or use the multiline indicator > and put it on a line below entity_id indented 2 spaces.

rocky crypt
#

Ok. Great. Let me see if I can get this...

mighty ledge
#

that looks correct

#

what does the template show in the template editor

rocky crypt
#

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
mighty ledge
#

you can't mix tabs and spaces in your text

#

spaces or tabs

#

indent with spaces

rocky crypt
#

Oh! Ok. Let me double check that πŸ™‚

mighty ledge
#

change the settings on whatever you're using to replace tabs with spaces

rocky crypt
#

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?

marble jackal
#

Use expand('group.your_group') instead of states.light

rocky crypt
#

@marble jackal That did it! πŸ™‚ Thank you!!!!!

marble jackal
#

Sorry, I see I forgot a quote, but I guess you noticed that

topaz cave
mighty ledge
#

you can use a state trigger pointing to the attribute entity_picture

marble jackal
#

You could just use the attribute entity_picture

trigger:
  - platform: state
    entity_id: your.entity
    attribute: entity_picture
molten chasm
#

@mighty ledge anyway you could help me with that same template? not sure what i am not putting in here!

marble jackal
#

And if you want to use a template, you'll need to add attributes (trigger.to_state.attributes.entity_picture)

topaz cave
#

Thanks so much @marble jackal you rock!

ionic cosmos
#

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...

https://www.codepile.net/pile/GA3VWOmr

marble jackal
#

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

ionic cosmos
#

oh so variables keep their states in different executions of the script?

marble jackal
#
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
ionic cosmos
#

oh great ... thanks

marble jackal
#

There might be a small portion of the tts sent with the old volume though

ionic cosmos
#

I'll give it a try, thank you

#

Nice, it worked! That's really great

marble jackal
#

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 πŸ™‚

ionic cosmos
#

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?

marble jackal
#

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

ionic cosmos
#

That are great hints... I'll try to get that doneπŸ‘

floral shuttle
#

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..

mighty ledge
#

nothing to do with your template

#

specifically, your script mode is restart or queued, and you're somehow calling it to run in itself

floral shuttle
#

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

mighty ledge
#

so, you can't tell if it's referencing itself

inner mesa
#

I don't know how it detects "bad" recursion, but it would look something like:

bad_script:
  sequence:
    - service: script.bad_script
mighty ledge
inner mesa
#

could be parallel

mighty ledge
#

parallel is perfectly fine

#

it'll recurse until it hits the limit

inner mesa
#

that's why I'm saying that I don't know how they detect bad recursion

mighty ledge
#

It knows by knowing the status of itself

inner mesa
#

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.

mighty ledge
#

yep

inner mesa
#

so queued looks like it will also stop

mighty ledge
#

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"

inner mesa
#

recursion isn't inherently bad

#

unbounded recursion is

mighty ledge
#

right, which this fixes

#

parallel allows recursion up to the limit

floral shuttle
#

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.

mighty ledge
#

Itself shouldn't be in the call stack because it's not calling itself

#

it should be restarting IMO

mellow knot
#

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.

toxic dome
#

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.

silent barnBOT
toxic dome
#

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

slender agate
#

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 }}"```
toxic dome
#

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

slender agate
#

I'll give the above a try. though i dont think it would have an impact in the sensor returning an unknown state?

toxic dome
#

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

#

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'

slender agate
#

I have tried state: "true" and just now tried state: "{{ true }}" as suggested. both results in an unknown state unfortunately.

toxic dome
slender agate
#

then this is most likely where I am fumbling.

toxic dome
#

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

slender agate
slender agate
mighty ledge
toxic dome
mighty ledge
#

no

#
...
  state: &state >
    {{ template }}
... later ...
  state: *state
#

you can do that anywhere with any object or value

toxic dome
#

oh! that's neat, I didn't know that one

mighty ledge
#

it's no different than what you're doing

toxic dome
#

does that work with arrays too? or only objects and strings

mighty ledge
#

the difference is <<: means merge this dictionary inward

#

it works with anything

toxic dome
#

yea I know I just didn't know you could anchor something which wasn't a dictionary

mighty ledge
#

<< only works with keyed items

toxic dome
#

good to know, thanks!

floral shuttle
# mighty ledge `| default("blah")`

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

mighty ledge
#

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'

toxic dome
# slender agate This works like a charm. Thanks.

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
toxic dome
# floral shuttle getting back to this, all templates work except this one:```{{value_json.created...

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!

floral shuttle
#

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.

mighty ledge
#
{{ value_json.created_at | default | timestamp_local('Not yet initialized') }}
#

accessing an item that doesn't exist will return an exception

floral shuttle
#

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!

stable gazelle
#

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%}
dreamy sinew
#
{{ now.second % valtozo == 0 }}```
#

@stable gazelle

silent barnBOT
cold crater
#

May I know what is going wrong?

silent barnBOT
silent barnBOT
#

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.

cold crater
#

solved. thanks.

distant plover
#

Can I make a template showing the last two timestamps of a door sensor?

inner mesa
#

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

inner mesa
#
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 }}"
distant plover
#

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.

inner mesa
#
- 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

distant plover
#

Haha. Thank you.

hushed bison
#

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?

hushed bison
#

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?

marble jackal
marble jackal
rigid hawk
#

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?

marble jackal
#

Do it the other way around, convert your input_datetime to an datetime object:
{{ as_local(as_datetime(states('input_datetime.abit_date'))) <= now() }}

stable gazelle
dreamy sinew
#

.share what you did @stable gazelle

silent barnBOT
#

@stable gazelle Please use a code share site to share code or logs, for example:

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.

hushed bison
marble jackal
#

Sounds like your better off with an automation writing the value to an input_number

hushed bison
dreamy sinew
#

not sure what you're trying to do

stable gazelle
#

Execute every input_number.masodperc seconds, every input_number.percminutes and every input_number.ora hours

dreamy sinew
#

than you want triggers, not conditions

#

you want to trigger on every <interval>?

stable gazelle
#

Yes

#

Every given seconds,minutes,hours

dreamy sinew
#

checkout a timer

silent barnBOT
inner mesa
#

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

torn meteor
#

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

inner mesa
#

yes, you can format it to zerofill

torn meteor
#

zerofill?

#

(googling)

inner mesa
#

that's what you're asking for - add zeroes

torn meteor
#

right. is there a filter for | zerofill?

#

or a func

inner mesa
#

no

#

{{ "%02d"|format(3) }} -> 03

torn meteor
#

that's crazy looking. is that string required? or just format(my_int)?

inner mesa
#

hmm

#

it's a format string

#

{{ (diff.seconds % 86400) / 3600) }}:{{ "%02d"|format((diff.seconds % 3600) / 60) }}

torn meteor
#

thank you - i was just going to ask how that could be merged with my code. you're a champ

inner mesa
#

it's from the first link when Googling "jinja zero padding"

torn meteor
#

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"

inner mesa
#

yes

torn meteor
#

very cool.

stable gazelle
# dreamy sinew checkout a timer

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}}"
marble jackal
#

I see no issues with the template itself. Not sure if you can use it this way πŸ˜…

inner mesa
#

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

torn meteor
#

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

stable gazelle
inner mesa
torn meteor
#

woot! right, i remember that from the notes. thanks!!

#

that works within {{}}?

inner mesa
#

it's a Jinja function, so yes

marble jackal
inner mesa
#

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

marble jackal
#

well, guess I just came barging in, and didn't know the background

torn meteor
#

crap. iff doesn't work in the Apple Watch complication template

marble jackal
#

And didn't recognize the input_number names πŸ™‚

inner mesa
#

templates are templates are templates

marble jackal
#

ora makes sense as hours though

torn meteor
marble jackal
#

it's iif not iff

stable gazelle
inner mesa
#

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?

stable gazelle
#

Yes

#

Oh yeah, I really done that is backwards

inner mesa
#

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

torn meteor
stable gazelle
#

Like

timer:
  second:
    duration: "00:00:{{states('input_number.masodperc')|int}}"
  minutes:
    duration: "00:{{states('input_number.perc')|int}}:00"

and so on?

inner mesa
#

You can't use a template like when the timer is defined. You can use one when calling timer.start

stable gazelle
#

Then how should I do that?

inner mesa
#

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

stable gazelle
inner mesa
#

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

stable gazelle
#

The "%02d" means seconds?

inner mesa
#
  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?

stable gazelle
#

Yes

inner mesa
#

then

#

I'm created a 0-filled string from the number you provided

stable gazelle
#

%02d means 0-filled string?

#

If I create my code, can you watch it?

shut silo
#

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

marble jackal
shut silo
#

exactly? i would swear i got errors rendering this template

#

i will try again. thanks

marble jackal
#

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

stable gazelle
young jacinth
#

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 }} 
hushed bison
#

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))) }}

atomic blade
#

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"

fringe temple
#

Is there a way to set ELSE IF conditions in a template?

inner mesa
atomic blade
inner mesa
#

Yes, the terminology is confusing. It accesses properties of the state object, and HA attributes can be referred to by "attributes.friendly_name"

atomic blade
#

Oh that isn't even a HA specific thing, that's just a jinja builtin

inner mesa
#

the real point is that you don't need to filter entities in the light domain later, you start with them

atomic blade
#

I was also approaching it from a different direction, starting with expand(area_entities('bedroom')) and then trying to filter from there

inner mesa
#

You can do that as well, I just prefer the other way

#

selectattr('domain', 'eq', 'light')

atomic blade
#

Ahh domain. Bleh, that's what I wanted

inner mesa
#

but you have to start with something, so might as well start with states.light

#

anyway, there are many ways to address this

atomic blade
#

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 πŸ™‚

inner mesa
#

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

wise sluice
#

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

marble jackal
#

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

wise sluice
#

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 }}"

marble jackal
#
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 πŸ˜‰

wise sluice
#

thanks!

ionic cosmos
#

Is there a possibility to write into the log file? Like for debugging I don't want to spam persistent messages all the timeπŸ˜…

marble jackal
#

there is a service for that

ionic cosmos
#

Oh ok... I'll have a look for this service

fringe temple
#

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.

marble jackal
marble jackal
ionic cosmos
marble jackal
#

cloud_say is the service which comes with Nabu Case

#

google_say is the natural voice tts service of, you guessed it, Google

ionic cosmos
#

Oh OK... Thanks

hot lodge
#

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!!

silent seal
#

Well that indicates your payload_json doesn't have slots when it comes in there.

#

Have you tried a default?

hot lodge
#

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": [
        {
silent seal
#

So either, they're not in the JSON that HA is getting, or nothing is working the way you expect it.

hot lodge
#

πŸ™‚ 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

silent seal
#

But it's not there when the trigger is triggered.

#

Have you tried just outputting the whole sensor data there to verify the input?

hot lodge
#

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.

marble jackal
#

You can see the payload in the automation trace

blazing burrow
#

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

silent seal
#

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!

raven token
#

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?

marble jackal
#

Yourtrigger.id is 0 as you did not provide one

marble jackal
marble jackal
#

but looking at the trace, yo can also use as_datetime(trigger.now)

#

for an automation that is

floral shuttle
#

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?

floral shuttle
#

@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...

silent seal
silent seal
floral shuttle
#

have another issue with those though, any idea why: - entity: sensor.last_motion_seen_in_area secondary_info: last-triggered shows 'Never triggered' ?

sonic nimbus
#

how to put in condition if binary sensor is off for 5 seconds?

#

conditions: "{{is_state('binary_sensor.kitchen_stove_state', 'off')}}"

arctic sorrel
#

Why not just use a state condition check?

marble jackal
#

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()

arctic sorrel
#

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

sonic nimbus
#

Thanks guys!\

floral shuttle
#

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...

sonic nimbus
#
    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 πŸ™‚

marble jackal
#
- 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

distant plover
# inner mesa well, that was fun <@!635393850546061331>

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] }}"```
marble jackal
#

What is the error you get?

mighty ledge
mighty ledge
#

and remove the []

#

unless you're trying to keep it a list

marble jackal
#

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

silent vector
#

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.

marble jackal
#

you are missing a . before last_updated in the last part

silent vector
#

Wow thank you not sure how I didn't see that

mighty ledge
#

then you just add an entity to the list if you get another cover

silent vector
distant plover
#

The idea was to have a template widget show the last 5 times I opened a door.

mighty ledge
#

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?

distant plover
#

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.

mighty ledge
#

why don't you just use the history stats integration and count the number of times the door is opened

silent barnBOT
lyric socket
#

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?

mighty ledge
distant plover
marble jackal
#

You're better off with an automation and writing the values in a input_text

distant plover
#

Or maybe a SQL sensor with this? SELECT state, last_updated FROM "states" where entity_id = 'binary_sensor.balkong_dorsensor'

marble jackal
#

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

distant plover
#

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?

marble jackal
#
{% set example_state = 'a, b, c, d, e' %}

{% set new = 'f' %}
{{ (example_state.split(', ')[-4:] + [new]) | join(', ') }}
mighty ledge
#

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

marble jackal
#

True, automation might give the opportunity to filter out updates after a reboot though

lyric socket
mighty ledge
#

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

blazing burrow
mighty ledge
#

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`;
    ]]]
distant plover
#

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. πŸ˜›

mighty ledge
#

but you can plop the results into an attribute

#

in a separate template sensor

distant plover
#

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 πŸ™‚

frigid marsh
#

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?

https://imgur.com/a/ZfJdkf6

marble jackal
idle marten
#

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?

mighty ledge
idle marten
mighty ledge
idle marten
#

@mighty ledge and I assume that I change a couple of variables referencing my device name and ID to correspond to my actual device?

silent barnBOT
blazing echo
#

Hi, sorry forgot hassbot.

mighty ledge
idle marten
#

@mighty ledge Thank you!

mighty ledge
#

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

blazing echo
#

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

mighty ledge
#

then add trigger id's to each trigger and add an ifstatement to your template to handle each trigger id

blazing echo
#

this sensor detects if im on a teams call - if im restarting HA I'm def not on a work call!

blazing echo
#

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?

inner mesa
#

you have two "if"s

blazing echo
#

ok yes, thanks! elif

inner mesa
#

it's bad syntax

blazing echo
#

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?

inner mesa
#

that seems rational

blazing echo
#

I'll try that now!

inner mesa
#

you're also not outputting anything

inner mesa
#

you can do that much more succinctly and actually output something with {{ iif(your_test, 'on', 'off') }}

blazing echo
blazing echo
mighty ledge
#

{{ 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

blazing echo
mighty ledge
blazing echo
#

yep good to check, i am definitely feeling a bit dense tonight, i DID do a ha reload!

mighty ledge
#

also, the template I provided is all you need

#

you don't need to specify the other conditions as true/false represents on/off

inner mesa
#

true, I keep forgetting that it accepts a boolean value

blazing echo
#

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!

mighty ledge
#

it pays to write lazily because then you don't have to edit much

blazing echo
#

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....

idle marten
#

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?

distant plover
#

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') }}

mighty ledge
#

if it's UTC, then it's applying your local TZ

#

if it's coming from the database, it's utc

distant plover
#

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);

mighty ledge
#

then what you see in there is UTC

#

is your TZ -1?

distant plover
#

+1, CET

mighty ledge
#

yah, then 14 makes sense

distant plover
#

How to fix? πŸ™‚

mighty ledge
#

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

distant plover
#

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.

fallen karma
odd condor
#

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!

fossil venture
bronze horizon
#

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

bronze horizon
#

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.

odd condor
#

πŸ€” Also not a bad idea!

odd condor
#

Apparently availability uses some sort of inverted logic 😐

wicked parrot
#

In the actions of an automation, is there a way to throw an if then template with multiple service calls?

fossil venture
#

Yes, the service: action accepts templates. Or you can use a choose: action.

wicked parrot
fossil venture
#

Otherwise it would be two templates, one for the entity id to unlock and one for the scene to activate.

wicked parrot
#

Thank you.

wise sluice
#

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

vivid horizon
#

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?

fossil venture
#

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.

fringe temple
#

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.

lyric socket
#

Im thinking that templating them into a binary sensor and then into a group might be the easiest way to get this done?

inner mesa
#

you can use the device_tracker.see service to create a device tracker and/or update its state

lyric socket
#

.see?

silent barnBOT
lyric socket
#

hardly a code wall, but ok i get it.

raven token
# marble jackal but looking at the trace, yo can also use `as_datetime(trigger.now)`

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?

marble jackal
#

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

noble fern
#

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?

mighty ledge
noble fern
#

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

mighty ledge
#

always take the easiest route first πŸ˜‰

noble fern
#

It does? Bloody hell, I have missed that. Thanks. Will go and test it now.

noble fern
fathom sentinel
#

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)....

fickle gale
#

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.

ionic cosmos
#

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 πŸ€”

lavish marlin
#

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?

mighty ledge
lavish marlin
#

the current value of sensor.nesthub7ae3_alarms is 2022-03-16T09:40:00-04:00

silent barnBOT
lavish marlin
#

@mighty ledge

mighty ledge
#

how are you identifying the alarm currently?

lavish marlin
#

that value is the next alarm

mighty ledge
#

just off the state?

lavish marlin
#

so the current value of sensor.nesthub7ae3_alarms always shows the timestamp of the next alarm

#

yeah

mighty ledge
#

ok

lavish marlin
#

lol it just occurred to me that you're the one writing the post im trying to follow

mighty ledge
#

this trigger will trigger 15 minutes before your next alarm

- platform: template
  value_template: "{{ now() >= states('sensor.nesthub7ae3_alarms') | as_datetime - timedelta(minutes=15) }}"
lavish marlin
#

ok and where does that go?

#

in my config? includes in a templates.yaml?

mighty ledge
#

it's a trigger

#

it goes in an automation

lavish marlin
#

ah

mighty ledge
#

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 %}
lavish marlin
#

wait, hold up, how do I use that code? Where do I actually put it? In my automation in the GUI?

mighty ledge
#

it's a trigger

#

do you know what a trigger is?

lavish marlin
#

i understand what a trigger is as in an event that triggers something, but not in terms of HA

#

?

mighty ledge
#

it's exactly what you described, but it's for automations in HA

#

yes

fickle gale
#

Having issue with a template.
if ( bearing | float >= 0 ) and ( bearing | float <= 160 )
TemplateError('TypeError: '<=' not supported between instances of 'str' and 'float'')

lavish marlin
mighty ledge
#

what? where'd you get that idea?

#

have you made an automation yet?

lavish marlin
#

Yeah

mighty ledge
#

ok, so how do you normally add triggers for your automation?

fickle gale
#

Oh derp. It's something else having issue.

mighty ledge
fickle gale
#

Yeah I'm realizing that.

lavish marlin
#

ohhhh

arctic sorrel
#
if ( 0 <=  (bearing | float) <= 160 )
mighty ledge
lavish marlin
#

I normally create them in the GUI

#

Which I'm seeing now... Triggers > Template > Value Template

mighty ledge
#

ok, then make a template trigger and use that value template

#

via the UI

lavish marlin
#

I'm assuming thats where {{ now() >= states('sensor.nesthub7ae3_alarms') | as_datetime - timedelta(minutes=15) }} goes?

mighty ledge
#

yes

fickle gale
#

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
lavish marlin
#

ah, sorry

#

newbiness 🀦

mighty ledge
#

what is end?

fickle gale
#

'round 6 hours

mighty ledge
#

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

fickle gale
#

Moment, sure.

#

Good extension for the code fence or there no extension for the kind of templating we're using?

mighty ledge
#

what do you mean code fence?

fickle gale
#
{% 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
}}
fickle gale
#

Syntax highlighting for code-blocks I guess.

mighty ledge
#

ah, the code is jinja but the extensions for it suck

fickle gale
#

Ah

mighty ledge
#

if you're referring to vscode extensions

fickle gale
#

Oh I meant to highlight it here. After ``` you can specify an extension/language.

mighty ledge
#

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

fickle gale
#

Example datetime: 2022-03-16T09:00:00-04:00

mighty ledge
#

you may actually have to use utcnow() too, depending on the tiemzone of datetime in forecast

#

ok

fickle gale
#

And that timezone matches mine.

ionic cosmos
mighty ledge
fickle gale
#

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

mighty ledge
#

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 }}
fickle gale
#

Oh neat.

#

Yeah that's much more cleaner.

noble fern
fickle gale
#

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.

mighty ledge
#

what's your endgoal here?

#

are you just tring to get wind direction so you can shut blinds or something?

#

@fickle gale

fickle gale
#

Avoid blowing smoke over neighbors, ourselves, or the interstate.

mighty ledge
#

fuck the interstate

#

but, yes, adding lists like that is fine

fickle gale
#

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.

astral turtle
#

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.

marble jackal
#

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.

marsh halo
#

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?

mighty ledge
#

use

silent barnBOT
#

Please use a code share site to share code or logs, for example:

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.

mighty ledge
#

and post your code there so it has proper formatting, then paste the link here.

mighty ledge
#
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
marsh halo
#

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?

mighty ledge
#

This is the template you’d use for value

  value: "[[[ return states['automation.pump'].attributes.current == 0; ]]]"
halcyon ridge
#

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

mighty ledge
mellow knot
#

is there a way to add current date (YYYY-MM-DD) to a REST url.

halcyon ridge
fossil venture
mighty ledge
ionic cosmos
#

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 ]
mighty ledge
#

you should never have to do that anyways

#

that's a no no in most languages

ionic cosmos
#

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 ...

mighty ledge
#

ok, you can do taht in a single template prior to the loop

ionic cosmos
#

should I post what I have till now?

mighty ledge
#

sure

ionic cosmos
#

at the point where the temp variable is defined, I'd like to store the current volume in the dictionary I created above

mighty ledge
#

but why

#

why even loop

#

you can mute them all in a single service call

ionic cosmos
#

oh really?

mighty ledge
#

you can access the volume levels in 1 variable

#

you can play a song on all of them at once

ionic cosmos
#

can you hint me how?

mighty ledge
#

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

ionic cosmos
#

can I pass a list of entity ids to the mute and the play service calls?

mighty ledge
#

you can pass a list of entity_id's to every single service

ionic cosmos
#

oh ... that's something I must have missed ... ok that makes everything much more easy πŸ˜‰

#

thanks

mighty ledge
#

you've never turned on multiple lights?

ionic cosmos
#

sure ... but somehow I was thinking that this only woks with switches or lights ... not with every service πŸ™ˆ

mighty ledge
#

πŸ€·β€β™‚οΈ

#

it's all the same thing

ionic cosmos
#

uh ... yeah makes sense somehow πŸ˜…

mighty ledge
#

only time you need to separate it per entity_id is when the data you're setting differs

ionic cosmos
#

I see

mighty ledge
#

you make that dictionary wihtout grabbing the old volume

mighty ledge
# ionic cosmos I see

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

ionic cosmos
marble jackal
#

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 πŸ˜›

mighty ledge
#

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

marble jackal
#

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 πŸ™‚

ionic cosmos
#

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 πŸ‘Œ

marble jackal
#

Hehe, okay! Good learning experience πŸ™‚

ionic cosmos
#

thanks

mellow knot
mighty ledge
#

subtract a timedelta

#

- timedelta(days=1)

inner mesa
#

pfft, faster than I could get to a laptop to type that πŸ™‚

mighty ledge
#

lol

mellow knot
mighty ledge
#

i'm at a keyboard

#

no

#

what's the current date/time in jinja (templates)?

mellow knot
mighty ledge
#

how do you get the current date/time out of a template?

mellow knot
#

im using {{ now().strftime('%Y-%m-%d') }} to get just the date in format YYYY-MM-DD

mighty ledge
#

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

mellow knot
#

{{ now().strftime('%Y-%m-%d %H:%m') }}

mighty ledge
#

try just using now() in the template editor

mellow knot
#

got it. so using just now im getting date/time in format 2022-03-17 10:27:03.845775-05:00

mighty ledge
#

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

mellow knot
#

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.

mighty ledge
#

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(....

mellow knot
#

got it.

#

so stfttime() as like a way to format it

mighty ledge
#

so, hopefully you can drum something up and post it here, i'll help with corrections

mellow knot
#

this is what i pieced together and tested in dev/templates to be working

#

{{ (now() -timedelta(days=5)).strftime('%Y-%m-%d') }}

mighty ledge
mellow knot
# mighty ledge 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 πŸ˜‰

mighty ledge
mellow knot
bitter stag
#

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 ?

inner mesa
#

The "Hassio" integration has entities for that:

bitter stag
#

i run Ha OS , it says its auto installed

inner mesa
#

ok

#

and?

bitter stag
#

i only have the Binary sensor for update /yes/no and what version

snow laurel
#

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?

inner mesa
#

perhaps you need to enable more of the entities, then

bitter stag
mellow knot
#

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

bitter stag
# inner mesa

ok got what i need , thanks.
now just need to make a counting template and done πŸ™‚

inner mesa
#

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 }}"
bitter stag
#

{{ states.binary_sensor|selectattr('entity_id', 'search', 'update_available$')|rejectattr('object_id', 'match', 'syn_nas')|selectattr('state', 'eq', 'on')|list| count }}
works for me

inner mesa
#

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 πŸ™‚

stuck bone
#

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

dreamy sinew
#

{% else %}{{ stuff }}{% endif %}

#

converting time to float probably won't do what you want

#
{{ stuff }}
{% else %}
{{ other stuff }}
{% endif %}```
stuck bone
#

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

native sparrow
#

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.

inner mesa
#

That doesn't belong there

#

None of that belongs under customize:

native sparrow
#

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)

inner mesa
#

You can't change the state of an entity like that

#

You can create another entity based on it, as shown at the link

native sparrow
#

Was trying to avoid that

#

It's an attribute I'm changing - not the state

inner mesa
#

You can only set static attributes like that

native sparrow
#

ok thanks

native sparrow
#

I guess it must be only evaluated at startup or reload

marble jackal
rose scroll
native sparrow
#

I used the UI to set up the integration.

rose scroll
#

So...using the Daikin AC integration?

native sparrow
#

Yes

#

Can’t find any docs yet for yaml config

rose scroll
#

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.

native sparrow
#

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

rose scroll
#

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.

native sparrow
#

πŸ‘

mighty ledge
obsidian lintel
#

@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?

marble jackal
#

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

astral turtle
#

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)%}

inner mesa
#

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

zenith oak
#

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

fresh yoke
#

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

#

?

tepid onyx
#

trigger.from_state The previous state object of the entity

#

you can debug it by starting an event listener in events under developer tools

marble jackal
marble jackal
#

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

mighty ledge
tepid onyx
mighty ledge
#

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

tepid onyx
#

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

mighty ledge
#

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

silent barnBOT
fresh yoke
#

(: it was a message with an embedded code wall but whatever

tepid onyx
# mighty ledge The issue is your automation template is invalid syntax due to the variable not ...

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

silent barnBOT
#

Please use a code share site to share code or logs, for example:

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.

tepid onyx
#

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.

tepid onyx
#

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...

mighty ledge
#
 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

tepid onyx
#

fair enough, i'll update the ha forum page with that info and report back. cheers

tepid onyx
lyric socket
#

Anyone have an example of templating an attribute of a sensor?

buoyant pine
#
"{{ state_attr('sensor.whatever', 'attribute') }}"
lyric socket
#

Yeah i just found that as you were typing and giving it a shot, its a ways down on that page for sure.

buoyant pine
mighty ledge
#

hahaha

buoyant pine
lyric socket
mighty ledge
#

you can't unless it allows templates

lyric socket
#

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?

inner mesa
#

If you construct a string with the time, you can make the time zone offset whatever you want

lyric socket
#

What might that look like, i cant wrap my ead around how that would work

inner mesa
#

overly complex, but :
{{ ((now()|string).replace('-07:00', '-08:00')|as_datetime|as_local).strftime("%H:%M") }}

lyric socket
#

changing the 7 or the 8 doesnt change the time (when using dev tools template at least)

inner mesa
#

does for me

#
{{ now().strftime("%H:%M") }}
{{ ((now()|string).replace('-07:00', '-08:00')|as_datetime|as_local).strftime("%H:%M") }}
#

->

lyric socket
#

This template updates at the start of each minute. might be why πŸ˜†

inner mesa
#
12:20
13:20
lyric socket
#

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

spare vector
#

Hi, how can i write thsi with state_attr()?
states.sensor.swx1_sensor.attributes['extruder']['target']

inner mesa
#

state_attr('sensor.swx1_sensor', 'extruder')['target']

#

or probably state_attr('sensor.swx1_sensor', 'extruder').target

spare vector
#

Thanks!

spare vector
#

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

inner mesa
#

you need two REST sensors

spare vector
#

Hmm but still not working. How can I ensure, that the second REST sensor (named sensor 2:) is using the right values?

tepid onyx
# mighty ledge fyi, replied

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!

spare vector
#

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.

spare vector
#

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

spare vector
lyric socket
#

{{ now().tzinfo('Israel') }} Why is this wrong/gives the error its not callable?

inner mesa
#

because it's not callable

#

{{ now().tzinfo }} gives you your timezone

lyric socket
#

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.

olive lagoon
#

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) }}"
)

silent seal
olive lagoon
#

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

lyric socket
spare vector
#

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 %}
silent seal
#

The sensor exists, so you'll be able to read the data, it's just a question of doing something with it.

silent seal
lyric socket
silent seal
#

It'll be something like sensor.mobile_device_geocoded_location actually, had a brain moment

inner mesa
#

The worldclock integration isn't dynamic

silent seal
#

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!

inner mesa
#

Could be modified to accept a select entity

silent seal
#

That sounds pretty handy

lyric socket
#

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.

silent seal
#

Which is a shame as it would be a brilliant hack

lyric socket
#

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.

lyric socket
silent seal
lyric socket
#
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

silent seal
#

Darn it, worth a try at any rate

inner mesa
#

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
lyric socket
#

Not dynamic though

sacred sparrow
#

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','') }}
silent seal
#

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

sacred sparrow
#

{{ (as_timestamp(now()) - as_timestamp(states('sensor.nas_last_boot'))) // 60| round(1)| int }}

#

?

silent seal
#

Yes, though technically that would make the rounding unnecessary

sacred sparrow
#

it still shows up as 79.0

#

I want to remove the .0

inner mesa
#

ohai it works

#

the docs are wrong

#
sensor:
- platform: command_line
  name: Other Timezone
  command: >-
    python3 tzconvert.py "{{ states('input_text.test') }}"
lyric socket
#

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

fossil venture
inner mesa
#

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)

sacred sparrow
fossil venture
#

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 }}

sacred sparrow
#

amazing! thank you so much πŸ™‚

lyric socket
inner mesa
#

yes, via homeassistant.update_entity

lyric socket
#

Duh of course, its just a sensor

inner mesa
#

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') }}"
lyric socket
#

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') }}"

inner mesa
#

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...

lyric socket
#

One is less "steps" than the other. If setting by attribute, then it would be every minute it would check correct?

inner mesa
#

it's not a matter of steps, but where you want the info to come from