#templates-archived

1 messages Β· Page 108 of 1

inner mesa
#

I think either would be fine as far as that's concerned.

waxen rune
#

it seems like

{{ is_state('input_boolean.day' + d | string, 'on') }}
{{ states('input_boolean.day' + d | string) == 'on' }}

are the same number of characters πŸ™‚

inner mesa
#

perhaps preference, then πŸ™‚

waxen rune
#

not sure if widow9098 is here anymore, but it was a good exercise for me. thanks

crisp storm
#

i have a template sensor that returns a list. how can i reference that list in another template? ie how can i cast a string representation of a list into an actual list

#

perhaps i could parse the string as json.... doesn't seem to be possible...

dreamy sinew
#

What is the actual value?

crisp storm
#

"['2020-11-02T15:30:00.000Z', '2020-11-02T13:45:00.000Z', '2020-11-01T09:30:00', '2020-11-02T09:00:00']"

#

piping that into from_json gets JSONDecodeError: Expecting value: line 1 column 2 (char 1)

#

rofl ok if i string replace the single quotes into double quotes i can use from_json to deserialize the list

#

is there a less hacky way?

dreamy sinew
#

That might be the simplest

#

Are you generating the above list somewhere?

crisp storm
#

if i pipe the string into list i just get a list of each of the characters

#

yes, the list is the output of another template sensor and then two more template sensors parse that list in different waysa

dreamy sinew
#

Add a |tojson to the generator template

crisp storm
#

oooooo

#

good idea

#

nice

#

that is way cleaner than a replace, thanks

vagrant laurel
#

Hey guys,
trying to set an "input_number" to a value of a certian sensor. If I call the "input_number.set_value" service with the following data:

entity_id: input_number.tinte_schwarz
value: {{ states('sensor.canon_tr8500_series_black_bk') | float }}

I am getting this error message: "expected float for dictionary value @ data['value']". Any idea how to solve this?

inner mesa
#

you need to quote the template

#

and you won't be able to do that in the devtools, only in a script/automation

thorny snow
#

How do I get the area from a state trigger in automations?

vagrant laurel
#

@inner mesa Ah ok, then that's my fault. Tried it first in the dev tools

inner mesa
#

it should work there, and I filed an issue for it

vagrant laurel
#

@inner mesa Ah ok. Do I need a single " or "" to quote the template?

inner mesa
#

double (") in your case. just make sure that you use different quotes outside from what you use inside

chilly magnet
#

I am using a template to combine multiple motion sensors into one. I then use NodeRed to turn lights off based upon the one sensor. My question is, why doesn't the template "reset" or start over again once the delay off has been satisfied? Snip it of code:

  • platform: template
    sensors:
    motion_hall_bath:
    friendly_name: "Hall Bath"
    delay_off:
    minutes: 3
    entity_id: binary_sensor.wyzesense_77a64a20,binary_sensor.hall_bath
    device_class: motion
    value_template: >-
    {{ is_state('binary_sensor.wyzesense_77a64a20', 'on')
    or is_state('binary_sensor.hall_bath', 'on') }}

Need to add that the reset should occur due to the sensor triggering a timer in NodeRed prior to turning off the lights. I would think that if motion is detected prior to the timer expiring, it would start over again.

silent barnBOT
inner mesa
#

why would it "reset"? I'm not following what you're looking for

#

BTW, the entity_id: line should be removed. It's no longer supported

#

that template should turn on immediately when either of those sensors reports on, and wait for 3 minutes of evaluating "false" before turning off

chilly magnet
#

After the 3 minutes and before my timer in NodeRed has expired, if motion is sensed again, I want the template to start timing again and turn to on.

ivory delta
#

The template isn't timing, the sensor is.

#

And it'll reset only when the template evaluates to 'off' for 3 full minutes.

inner mesa
#

Taking node red out of this, delay_off only starts when it evaluates false

ivory delta
#

So any motion detected within the 3 minutes on either of the sensors in your template will reset the 3 minute delay_off.

chilly magnet
#

Sensors are all off, delay_off timer starts. At the end of the delay_off should any motion, assuming all of the sensors are still off, restart the template?

ivory delta
#

The template is evaluated every time either of the entities it references change state (or attributes, but you don't care about that).

#

The template doesn't have any notion of a timer. It doesn't 'restart'.

chilly magnet
#

If motion should activate the template, I have another problem then.

inner mesa
#

Templates aren’t activated or restarted

chilly magnet
#

I think I got it. I will look at what is happening during the state change. Thanks for the help.

inner mesa
#

at any given moment, they evaluate to something

cinder basin
#

hi. I'm looking for right syntax for strftime. I have date and i want to extract name of the day from the date. {{ state_attr('weather.home', 'forecast')[0].datetime }} is returning me 2020-11-03T11:00:00+00:00 is it possible to get a name of the day from this form. I tried : {{ {state_attr('weather.home', 'forecast')[0].datetime}.strftime("%a") }} , {{ (state_attr('weather.home', 'forecast')[0].date).timestrftime("%a") }} , but this is not working. Is my syntax wrong, or the format of date is wrong

#

oh. found the solution

#

{{ as_timestamp(state_attr('weather.home', 'forecast')[0].datetime) | timestamp_custom('%A', False) }}

charred dagger
#

{{state_attr('weather.home', 'forecast')[0].datetime | as_timestamp | timestamp_custom("%A", false)}} works too if you prefer that format.

cinder basin
#

Now I want to create for loop to create multiple sensors, so i don't have to configure them one by one. I put this together, but i have a feeling that, this won't do the trick. So i want to create sensors day_0, day_1, day_2, day_3

charred dagger
#

Yeah, that won't work.

#

The backend configuration does not process jinja

cinder basin
#

I have to define every sensor in config then, no soulution via for loop?

charred dagger
#

Not built-in. You could use an external preprocessor for the config file, but what's saved would be the same as if you did it yourself.

cinder basin
#

ok, notepad++ it is then:)

austere isle
#

Hi all, anyone available to help out? I'm completely stuck with the new templating-stuff.

#

It's probably something silly...

charred dagger
#

Just ask your question, and if someone can answer they will.

silent barnBOT
austere isle
#

sigh HassBot is removing my code

#

I'm currently using this: {% if states('sensor.time') <= "10:30" %}

#

To check if it's before 10.30 obviously.
This however gives an error now.

Error executing script. Invalid data for call_service at pos 1: template value should be a string for dictionary value @ data['attributes_template']

charred dagger
#

It does that to stop too long messages from filling up the chat

austere isle
#

attributes_template: >
{
{% if states('sensor.time') <= "08:30" %}

#

(( etc ))

charred dagger
#

I don't think you can template a whole block of attributes like that.

austere isle
#

Let me try to put the whole thing in here in parts so that Hassbot won't bug me πŸ™‚

#
  • service: variable.set_variable
    data:
    variable: verlichting_woonkamereethoek_waarden
    value: true
#

attributes_template: >
{
{% if states('sensor.time') <= "08:30" %}
"doelhelderheid": "80",

#

"doelkleurtemperatuur": "400"
{% else %}
"doelhelderheid": "40",

#

"doelkleurtemperatuur": "400"
{% endif %}
}

#

This used to work.

#

When I user legacy_templates: true it still does

charred dagger
#

Try yaml attributes_template: doelhelderheid: "{% if states('sensor.time') <= '08:30' %}80{% else %}40{%endif%}" doelkleurtemperatuur: 400

austere isle
#

(( will try - How do you get the nice formatting?? ))

#

Nope. Same error

deft timber
#

Looking at https://github.com/rogro82/hass-variables, the attributes_template should return a json object, therefore the correct synthax would be

attributes_template:
    {
      "doelhelderheid": "{% if states('sensor.time') <= '08:30' %}80{% else %}40{%endif%}",
      "doelkleurtemperatuur": 400
    }
austere isle
#

I think it has to do with the sensor.time thing. (it is explicitly mentioned release notes of 0.117)

#

Same error

#

Invalid data for call_service at pos 1: template value should be a string for dictionary value @ data['attributes_template']

deft timber
#

what does return {% if states('sensor.time') <= '08:30' %}80{% else %}40{%endif%} when you evaluate it in the template tool ?

austere isle
#

40

#

It does work in the templating-tool

#

But so did my original code

deft timber
#

in my code I forgot the > :

attributes_template: >
    {
      "doelhelderheid": "{% if states('sensor.time') <= '08:30' %}80{% else %}40{%endif%}",
      "doelkleurtemperatuur": 400
    }
#

same error?

austere isle
#

Yup

#

Templates - Auto-updating now()

deft timber
#

don't think so

austere isle
#

πŸ™‚

#

As I said. My original code works fine if I use the 'legacy templating'

#

Any other ideas?

deft timber
#

they use attributes instead of attributes_template, but I don't know with which version

rugged laurel
#
attributes_template:
    doelhelderheid: "{% if states('sensor.time') <= '08:30' %}80{% else %}40{%endif%}"
    doelkleurtemperatuur: 400
deft timber
austere isle
#

Yup. That is it.... Thanks loads! πŸ™‚

#

I don't think I would have thought on looking at the Variables addon. (especially with the remarks in the changelog about the now() ).

marble jackal
#

@austere isle are you sure this works?
{% if states('sensor.time') <= '08:30' %}80{% else %}40{%endif%}
It's 12:08 here (and based on your attribute names I guess it's the same for you) and the template below gives 40 in the checker, I would expect 80 then
{% if states('sensor.time') <= '14:30' %}80{% else %}40{%endif%}

#

Oh, nevermind, I guess I don't have sensor.time enabled. {{ states('sensor.time') }} gives status unknown for me

austere isle
#

Yes it works fine:
{% if states('sensor.time') <= '14:30' %}80{% else %}40{%endif%} ## >> 80
{% if states('sensor.time') <= '08:30' %}80{% else %}40{%endif%} ## >> 40

#

(( I may have copy-pasted it incorrectly ))

#

I'm using the code for about half a year now. But since 0.117 it failed with the new template-engine

#

but slashback pointed me to the right direction πŸ™‚

marble jackal
#

you could also use

 {{ 80 if states('sensor.time') <= '08:30' else 40 }}```
#

ey @silent barn, I've corrected it!

austere isle
#

True. But the original code has more times and loads of items using that. So for readability, my original code looks like:

      value: true
      attributes: >
        {
          {% if states('sensor.time') <= "08:30" %}
          "doelhelderheid": {{ "80" | int }},
          "doelkleurtemperatuur": {{ "400" | int }}
          {% else %}
          "doelhelderheid": {{ "40"| int }},
          "doelkleurtemperatuur": {{ "400"|int }}
          {% endif %}
        }
    service: variable.set_variable
#

(pff don't look at the spaces. copy-paste error)

#

Anyway.. Thanks again all πŸ™‚

dreamy sinew
#

hmm, now that templates will return native types could probably simplify

#
      attributes: >
        {% states('sensor.time') <= "08:30" %}
          {{ {
            "doelhelderheid": 80,
            "doelkleurtemperatuur": 400 
          } }}
        {% else %}
          {{ {
            "doelhelderheid": 40,
            "doelkleurtemperatuur": 400 
          } }}
        {% endif %}
worn lintel
#

is it possible to create a template sensor that returns the current logged in user? I was using custom header for this with the following code but when I try this as a temple it does not return the Username:

{%- if now().hour < 12 -%}Good Morning {{user}}!{%- elif now().hour < 18 -%}Good Afternoon {{user}}!{%- else -%}Good Evening {{user}}!{%- endif -%}

frank lynx
#

For some reason this code is not loading, but works fine in the developer tools/templates... any suggestions?

    sensors:
      marco_in_gti:
      friendly_name: "Marco in GTI"
      value_template: "{% if '48:F0:7B:2C:7F:4A' in state_attr('sensor.marco_cell_bluetooth_connection', 'connected_paired_devices')  %}true{% else %}false{% endif %}"```
dreamy sinew
#

@worn lintel no. Unless the front end templating enviro is configured differently, the standard template environment doesn't have access to that info

#

"{{ '48:F0:7B:2C:7F:4A' in state_attr('sensor.marco_cell_bluetooth_connection', 'connected_paired_devices') }}"

frank lynx
#

Thanks for that, had been messing with it for hours...

dreamy sinew
#

the in test already returns true/false. no need to wrap it

sonic nimbus
#

hello, how can I check if some sensor triggered in some specific timeframe? For example I have a tag at the door, and I have xiomi motion sensor outside of the door.

#

scenario: user with phone scan tag, but condition is if movement sensor last triggered 15 seconds ago

#

if not, that means that user is planning to leave the house

#

if last triggered motion sensor is triggered in that specific time frame (less then 15 seconds), that means that users is entering into the house

#

so tag reading would have 2 automations: left_house and welcome_house based on that last triggered sensor

ivory delta
#

This sounds like an automation

sonic nimbus
#

yes but I need just a template for service_template part

#

do I use something like this {{ now().timestamp() - as_timestamp(states.DOMAIN.OBJECT_ID.last_changed) > 20*60 }}

ivory delta
#

Sure

sonic nimbus
#

now().timestamp ?

#

I wanted just to check in some of the last version of HA bunch of things are changed, added new timers etc

#

maybe is there a cleaner way Idk

ivory delta
#

If you want to check that it's been at least 15 seconds since something triggered, comparing the current time to the last_changed value is the best way.

#

Alternatively, you could have a timer that restarts every time there's motion detected. If the timer has run down, that means there's been no motion.

#

If you want to avoid templates, that's probably the next best option.

sonic nimbus
#

{{as_timestamp(states('sensor.frontdoor_last_movement_time'))}} Im getting the result None

#

{{states('sensor.frontdoor_last_movement_time')}} => Monday 02-Nov-20, 20:23:07

ivory delta
#

What's the config for that sensor?

#

If that sensor is just giving a string, you might have to use strptime. I don't know Python well enough to know when as_timestamp works and when strptime is needed.

#

I'm guessing that the former needs a datetime object to operate on.

sonic nimbus
#

well, Im having just a date in this format

#

{{ ( as_timestamp(now()) - as_timestamp(state_attr('sensor.frontdoor_last_movement_time', 'last_triggered')) |int(0) ) < 15 }}

#

I found something like this

#

but its always false πŸ˜„

dreamy sinew
#

timedelta is a thing

deft timber
#

you are searching for last_triggered on a sensor

#

It doesn't exist. last_triggered is for automation

#

if your are looking for the last change of the sensor, you should use states.sensor.frontdoor_last_movement_time.last_changed

quaint pond
#

Can someone help me to figure out how to make this better and/or make it work at all? It kinda works but not really. This is what I have below but I get the following error from the template tools: TypeError: '>' not supported between instances of 'str' and 'int'

#
{% if now().strftime("%B") == "October" %}
  HALLOWEEN
{% elif now().strftime("%B") == "November" and now().strftime("%-d") > 27 %}
  CHRISTMAS
{% elif now().strftime("%B") == "December" %}
  CHRISTMAS
{% else %}
  NONE
{% endif %}
dreamy sinew
#

...time("%-d")|int > 27 ...

quaint pond
#

@dreamy sinew You rock!!! That was easy πŸ˜›

trail estuary
deft timber
#

I'd say you just need to put something like {{ is_state("sensor.your_door_sensor", "on") }} in the value_template (if your door sensor is on when the door is open)

trail estuary
#

OK. Something that evaluates to true when it is open...

deft timber
#

yes

granite steppe
#

Morning Team! I am trying to create a 'fake switch' that will allow me to expose it to homekit and turn on / off when i am home / away. This will essentially become my presence detector. How do i create a 'fake switch' that turns on / off but not send any data. I attempted it . but not sure this is right?

#
  - platform: template
    switches:
      homekit_presence:
        friendly_name: Away Mode
        turn_on:
          service: switch.turn_on
        turn_off:
          service: switch.turn_off```
coarse tiger
#

why not just use a input_boolean: ?

deft timber
granite steppe
#

ahh okay cool - thank you! That works perfectly

viral latch
#

Hi, i'm trying to make a notification group that will send notification to the person who is at home. If none of us are at home, it should send it to us both.

In my notifications.yaml i have the following:

- name: athome
  platform: group
  services:
    - service: "{% if states('input_boolean.person_2_home') == 'on' and states('input_boolean.person_1_home') == 'on' or states('input_boolean.person_2_home') == 'off' and states('input_boolean.person_1_home') == 'off' %}all{% elif states('input_boolean.person_1_home') == 'on' %}sander{% elif states('input_boolean.person_2_home') == 'on' %}kirsten{% endif %}"

but when i run an config check, i get an Invalid config for [notify.group]: invalid slug, is there anyway to use template stuff here?

inner mesa
#

I don’t know that you can use a template there

#

You may need to put that logic in a script instead. It would be pretty similar with a choose: block

viral latch
#

How does that work?

#

platform: block ?

inner mesa
#

No, choose: is a way to do an if/then/else construct in a script

inner mesa
#

You can’t do what you want in a notify group be sure it’s trying to construct a notify service out of your template without evaluating it

viral latch
#

Strange it should be supported?

inner mesa
#

I suspect that that’s an exception

viral latch
#

πŸ˜…

#

How does this choose thing work?

inner mesa
#

It’s a different use case than the typical service template

viral latch
#

Ghehehe

inner mesa
viral latch
#

Can i pass data from the existing notifications to a script?

austere relic
#

a few months ago I created a sensor template so I can see in lovelace how long ago a automation was run ( device_class: timestamp; value_template: '{{ states.automation.muffin_essen_start.attributes.last_triggered }}' ). Is there now a cleaner solution?

viral latch
#

@inner mesa Got it almost working, only the actions don't show up:

    - service: "notify.{if here}"
      data:
        title: "{{title}}"
        message:  "{{message}}" 
        data: 
          image: "{{data.image}}"
          actions:  >
            {% for action in data.actions %}
              - action: {{ action.action }}
                title: {{ action.title }}
            {% endfor %}

Image does work, just need to pass the array in data.actions to the service

ivory delta
#

Templates can only be used for values, not for keys.

viral latch
#

So it's not possible?

ivory delta
#

That's what I just said

dreamy sinew
#

hmm, couldn't you output a full dict if you constructed it properly with the new typing?

ivory delta
#

Hmm, maybe. I wouldn't like to try πŸ˜„

#

I thought the main problem would be that the integration itself needs to know which fields to validate and then which fields can accept templates.

dreamy sinew
#

i think anything under the top level data key could be templatized

ivory delta
#

But does the validation of the structure occur before or after the evaluation of the templates?

#

If it's before, you're missing most of the structure still.

dreamy sinew
#

should be easy enough to test

#
actions: >
  {{ [{"action": "action", "title": "title"}] }}
ivory delta
#

Makes sense. @viral latch, try that (without your loop for now)

dreamy sinew
#

if that works i have an idea for the loop

#
actions: >
  {%- set ns = namespace(actions = []) -%}
  {%- for action in data.actions -%}
    {%- set ns.actions = ns.actions + [{"action": action.action, "title": action.title}] -%}
  {%- endfor -%}
  {{ ns.actions }}
ivory delta
#

This stuff makes me grateful to be a JS dev, not a Python dev. Concatenating arrays like that feels dirty πŸ˜„

dreamy sinew
#

that's a jinja thing

#

you can't modify lists after they're created

ivory delta
#

Ah

dreamy sinew
#
l = list()
l.append("foo")
l.append("bar")
l.extend(["blah", "mono"])
#

-> ['foo', 'bar', 'blah', 'mono']

ivory delta
#

Yeah, that syntax is fine. It's the + that upsets me πŸ˜„

#

I'm used to Array.push() in JS.

dreamy sinew
#

apparently jinja supports that too but the env that is enabled in HA restricts that out

ivory delta
#

I wonder if you can unpack them too or if the env blocks that.

dreamy sinew
#

unpack how?

ivory delta
#

set ns.actions = [ *ns.actions, {"action": action.action, "title": action.title}]

#

If I've understood the syntax correctly.

dreamy sinew
#

i'm not aware of that syntax

ivory delta
#

It doesn't like it 😦

#

TemplateSyntaxError: unexpected '*'

dreamy sinew
#

you can do this in python but not in jinja

[{"key1": x['a'], "key2": x["b"]} for x in l]


[{'key1': 'foo', 'key2': 'bar'}, {'key1': 'bar', 'key2': 'foo'}]```
ivory delta
#

That's neat

dreamy sinew
#

"list comprehension"

inner mesa
#

coming from C, list comprehensions blow my mind.

#

they're at once both awesome and terrifying

dreamy sinew
#

lol they're kinda dangerous if you're not careful

plucky musk
#

Not sure if this is the right channel. I'm trying to figure out how to convert an analog value from soil moisture sensor to human readable percentage. Is template the right place to do it?

plucky musk
#

Okay so if I want to create a percentage value for sensor.tasmota_analog_a0 entity, would this be the right approach?

sensor:
  - platform: template
    sensors:
      plant_soil1:
        friendly_name: Schefflera
        unit_of_measurement: percentage
        value_template: '(100 - ((states.sensor.tasmota_analog_a0.state_with_unit|int - 456) * 100) / (846 - 456))|round'
dreamy sinew
#

needs to be a valid template

#
        value_template: "{{ (100 - ((states('sensor.tasmota_analog_a0')|int - 456) * 100) / (846 - 456))|round }}"
plucky musk
#

Ah there. That wasn't difficult

#

Thanks

dreamy sinew
#

if you want to start diving deep on templates it might behoove you to go have a look at the jinja2 docs

silent barnBOT
plucky musk
#

I've done jinja2 in the past, thanks tho!

inner mesa
#

states('xxx') vs. states.xxx.state, for isntance

plucky musk
#

ah okay

#

thanks

dreamy sinew
#

yeah, i flipped that and didn't explain it

#

states.xxx.state throws an exception if it's unavailable, states('xxx') does not

small rock
#

How can I add a leading zero if the value < 10?

{{ (states('input_number.oprit_last_motion_event') | int) }}
deft timber
#

If the value is > 10 or <10 ? makes more sens if < 10 no ? If < 10 try this {{ "%02d" % (states('input_number.oprit_last_motion_event') | int) }}

small rock
#

@deft timber indeed, less then < 10

somber radish
#

Hi, i would like to create a template sensor that holds the average temperature. I thought of using https://www.home-assistant.io/integrations/min_max but next to entities, i also have some temperatures as an attribute on an entity. How can i point to those in the entity_ids list | string ?

somber radish
#

of course i can use value_template: >- {{ ((float(states('sensor.flora01_temperature')) + float(states('sensor.flora02_temperature')) + float(states('sensor.hallway_pir01_temperature_air')) + float(states('sensor.livingroom_pir02_temperature_air')) + float(state_attr('climate.kitchen_thermostat01_thermostat', 'current_temperature') + float(state_attr('climate.livingroom_thermostat02_thermostat', 'current_temperature') ) / 6) | round(1) }} but would be nice i dont have put that hard coded 6 there.

nocturne sleet
#

Hey everyone! I'm looking for someone who's good with math, 'cause my head hurts thinking about this:

I'm looking for a template that calculates a value based on the sun.suns' azimuth attribute. First going up, and then going down again. So when the azimuth is 90; the value should be 1, when it's 180; the value should be 100, and when it's 270; the value should be back at 1.
I want to use this to set the starting brightness_pct (and color_temp) when I turn on a lamp.
It's maybe a lot to ask for this formula, but if there's any math geniuses here that find this easy or fun (or both), feel free to give it a shot!
Thanks!

#

I found this on StackOverflow, but it's not quite right as it just keeps getting brighter up until azimuth 270:

brightnessPct = (((azimuthCurrent - azimuthMin = 90) * (brightnessPctMax = 100 - brightnessPctMin = 1)) / (azimuthMax = 270 - azimuthMin = 90)) + brightnessPctMin

If possible, it should peak at azimuth 180 and start going down again.

somber radish
#

@nocturne sleet in excell i come to this formula =100-ABS(((A1-90)/90*100)-100)

#

but with 0 instead of 1 at the extremities

deft timber
#

in excel too I got it with =MAX(-(COS(azimutCurrent/180*PI())*99-1);0)

deft timber
#

I'm using a cosinus to have a smoother formula, not a linear one

#

and it returns 0 if azimut is below 90 or above 270

somber radish
#

yep

#

works indeed

#

orange are @deft timber 's values, blue are mine

deft timber
#

In a template, my version gives {{ -(((azimutCurrent / 180 * pi)| cos) * 99 - 1) | max(0) }}

nocturne sleet
#

Wow! That's great!!

#

Could it be tweaked so that it returns 1 instead of 0 when azimuth <= 90 or azimuth >= 270

deft timber
#

replace max(0) with max(1)

nocturne sleet
#

Beautiful!

#

Thank you so much guys!

#

Really!

cloud tangle
#

Hi huys. I'm new to home assistant.
I'm trying to configure a custom rest notify service, where I want to send to state of all person in my config into the data_template field.
I can do it adding lines manually, but I would like to extract all users (some kind of for loop) .
Is this something possible?

deft timber
#

yes you can loop on the person

{% for p in states.person -%}
{{p.entity_id}}: {{p.state}}
{%endfor%}
nocturne sleet
#

@deft timber Sorry to bother again, but could the function be tweaked to do the same thing with color temperature? In Kelvin?
At azimuth 90 and 270 the colorTempKelvin == 2200 and at azimuth 180 (peak) the colorTempKelvin == 4000.
I tried tweaking the values in the formula, but could only get it working correctly with numbers sub 100

deft timber
#

I'm busy right now, I can watch that in 2h

somber radish
#

=2200+MAX(-(COS(A3/180*PI())*(4000-2200));0)

cloud tangle
#

thanks @deft timber but I'm not sure I get how I can do that in a data_template field

#

it's an object in yaml

deft timber
#
data: >
    {% for p in states.person -%}
    {{p.entity_id}}: {{p.state}}
    {%endfor%}
native pilot
#

How can I add 5 min offset to this template?
'''
{{
as_timestamp(states('sensor.redmi_note_7_next_alarm')) |
timestamp_custom('%H:%M')
}}
'''

inner mesa
#

+ timedelta(mins=5) I think

native pilot
#

+ timedelta(mins=5) I think
@inner mesa TypeError: 'mins' is an invalid keyword argument for new()

#

😫

inner mesa
#

looks like it's "minutes"

#

it's also in the docs

#

{{ now() + timedelta(minutes=5) }}

native pilot
#

well it returens a string.. what am i missing?

#

TypeError: can only concatenate str (not "datetime.timedelta") to str

small rock
#

I want to implement a loop until an other automation is started by a webhook, how can I manage that? What template should I use?

dreamy sinew
#

gotta format it

inner mesa
#

@small rock Sorry, I think you'll need to create an input_boolean to indicate that the webhook triggered and use that as the condition in a repeat: block

#

I keep forgetting that we have no break-like statement to get out of a loop

small rock
#

Ok thanks

#

I'll need to figure something out then

native pilot
#

UndefinedError: 'datetime.timedelta object' has no attribute 'strftime'``` {{ (now() + timedelta(minutes=5)).strftime('%H:%M') }}

@dreamy sinew I am getting there but can't combine it with the sensor :/

inner mesa
#

@native pilot the alternative is to just to add 5mins (5 * 60) to the timestamp

dreamy sinew
#

show what you are actually doing then

inner mesa
#

decide whether you want to work with datetime or timestamp and do the right thing

native pilot
#

Do you mind explaining the diff like I'm a five year old.?

#

I have basic knowledge in python but some things I just can get right

small rock
#

I have a camera (motioneye) sends a webhook and want to do image_processing until the webhook motion ended

#

For each webhook I have an automation

inner mesa
#

datetime is an object and timestamp is a number representing the number of seconds since Jan 1 1970

#

both are perfectly valid ways to represent the same info

native pilot
#

so if i am getting the sensor value as a timestamp like I have now - the reasonable choice will be to add a seconds like your example above?

inner mesa
#

@small rock then you can use input_select to represent which automation fired, or a series of input_boolean

#

sure, you can do that. +300

#

I just immediately jumped to timedelta, which was probably not the best option for you

#

you can try this all in devtools -> Templates to see what each part is spitting out and make sure you get the result you want

native pilot
#

@inner mesa Thanks!! figured it finally.. took some time to get it right (int and str and the formatting in general are pain)

#

Life saver

inner mesa
#

np, I hate time/date stuff and usually have to play around with it until I get it right

buoyant pine
#

I hate anything time/date related with templating

native pilot
#

yeah, because every sensor is returning a string, then you have to convert it to a time object to get the numbers, then to int to manipulate, and to time object again - and at the end it is always a string

small rock
#

@ robc I was thinking something like this:

{{ as_timestamp(states.automation.motioneye_oprit_webhook_off.attributes.last_triggered) - as_timestamp(states.automation.motioneye_oprit_webhook_off.attributes.last_triggered) | int > 0 }}
inner mesa
#

does it work?

small rock
#

I have tested in template editor and seem to be

#

Still need to test for details

inner mesa
#

you should use state_attr('automation.motioneye_oprit_webhook_off', 'last_triggered')

#

aren't you subtracting the same thing from itself?

#

you want webhook_on or something?

small rock
#
{{ as_timestamp(state_attr('automation.motioneye_oprit_webhook_off','last_triggered')) - as_timestamp(state_attr('automation.motioneye_oprit_webhook_on','last_triggered')) | int > 0 }}
small rock
#

@inner mesa I have done it like this:

{{ (as_timestamp(state_attr('automation.motioneye_oprit_webhook_off','last_triggered')) - as_timestamp(state_attr('automation.motioneye_oprit_webhook_on','last_triggered')) | int > 0) or is_state('binary_sensor.oprit_motion','on') }}
#

Is there a way to use secret in templates?

waxen rune
#

yes, at least you can put your whole template in to a secret

#

a little backwards, but it works fine

#

(I haven't read your whole conversation, just answering "Is there a way to use secret in templates?")

small rock
#

@waxen rune also in automation or secrets? Or do I need to make a sensor out of it?

waxen rune
#

hmm.. probably a sensor. I haven't read what you actually try to fix, I just read the last line πŸ™‚

small rock
#

It's just that one line

#

I just fixed what I wanted and it was more like a additional question

waxen rune
#

ok. if you want to create a sensor that's using a parameter you don't want visible, you can put the whole sensor in secrets, I have an example in link link above. just tried it the other day

#

I don't know if that's a good way, but it worked fine when I tried it.

small rock
#

Thanks I'll check it out later

hollow obsidian
#

can someone help me with a syntax problem?

silent barnBOT
#

@hollow obsidian Don't ask to ask, just ask your question. Then people can answer when they're around.

When you do ask a question, try to provide as much background detail as possible. Ask yourself these questions first so that others don't have to:

  1. What version of the Home Assistant are you running? (remember, last isn't a version)
  2. What exactly are you trying to do that won't work?
  3. Is the problem uniform or erratic?
  4. What's the exact error message?
  5. When did it arise?
  6. What exactly don't you "get"?
  7. Can you share sample code, ideally with line errors where the error occurs?
hollow obsidian
#

ok! I build an entity scraped from web with - platform: scrape and it works (called entity.first), then I build another one (called entity.second) and this is ok. Now i want to build another entity (called entity.diff) that is the different among the two. What is the way to build entity.diff? What sintax?

waxen rune
#

@hollow obsidian Generally, it no harder than the math you need for your operation. Can you share your config? Otherwise it's hard to help.

hollow obsidian
#

yes, let me try

#
  • platform: scrape
    name: press bz
    resource: http://meteo.provincia.bz.it/stazioni-meteo-valle.asp?stat_stid=1242
    select: "div#content:nth-child(4) > section > div.lv_grid_container > div.weather_box_lightest:nth-child(2) > div.station-data.row:nth-child(2) > div.station_sensor_values.col-sm-8:nth-child(2) > ul.station-values:nth-child(2) > li:nth-child(4) > strong"
#

an this build entity.press_bz

#

the other is:

#
  • platform: scrape
    name: Max VENTO
    resource: https://meteopassione.com/stazioni/toscolano
    select: "#col-dati.col.col-12.col-sm-3.col-md-3.col-lg-3.col-xl-3:nth-child(6) > div#box-dati > div.col.col-xs-12.col-sm-12:nth-child(3) > div.row.sfondo-stazione.bg-5 > div.col.col-xs-12.col-sm-5.footer:nth-child(1) > p:nth-child(1)"
waxen rune
#

and the states (values) of those?

hollow obsidian
#

an this build the second called entity.max_vento

#

ok, to extract the value I use this: (wait 1 sec I need to rewrite)

#
  • platform: template
    sensors:
    pressione_bz:
    value_template: "{{ states('sensor.press_bz') | string() | trim() | truncate(4,true,'') | round(2) | float()}}"
waxen rune
#

ok, does that work as expected? what is the state right now for example?

hollow obsidian
#

this give back a number, for example now it's 1027.0

waxen rune
#

ok, so far, so good

#

and now you want to..?

hollow obsidian
#

but now I want to subtract another variable and give the result to another entity

#

it's only a sintax error my mistake

waxen rune
#

ok, that should be fine. this is an example a template sensor that calculates (x + y) / 2 :
like value_template: "{{ (((states('sensor.pressione_bz')|float|round(1)) - (states('sensor.max_vento_nodi') |float|round(1))) /2) | round (1)}}"

hollow obsidian
#

The other entity is this:

  • platform: template
    sensors:
    max_vento_nodi:
    friendly_name: "MAX vento in nodi"
    unit_of_measurement: "kn"
    value_template: "{{ states('sensor.max_vento') | string() | trim() | truncate(3,true,'') | float()/1.8 | round() }}"
waxen rune
#

It can be made simpler, I just copied that as an example

hollow obsidian
#

yesssssss

waxen rune
#

does that answer your question?

hollow obsidian
#

1 second I need to understand

#

((states('sensor.pressione_bz')|float|round(1))

#

is the first argument

waxen rune
#

yep, the state, made to a float number and rounded of to one decimal

hollow obsidian
#

so after the {{ i can use the ( as typical sintax

#

ok perfect I will try

#

another , please πŸ™‚

#

...

#

is "TRUNCATE" the best way to get data from a serie?

#

(i think ther is a better way)

#

let me explain better: I scrape a data from a website, it give back an entity that seems like "10.4","km/h","EWE","17.5","Β°C","","","Italy"

#

so I need to extract the 4Β° data, 17.5, the temperature

#

what is the right command to get the 4th data?

ivory delta
#

Does it return an array ([a,b,c])?

waxen rune
#

From that example, I'd guess you could go for a json template.

hollow obsidian
#

yes it seems an array

ivory delta
#

For arrays, you can use [index] to get something back from that position. So if you have an array called list, list[1] gets the second item back from that array (it counts from 0).

tulip flare
#

Hi what is the best way to update the status of a switch without actually doing a service call?

ivory delta
#

Walk up to the switch and press it πŸ™‚

tulip flare
#

well I got three buttons, fan speed, i just want each time i press a one button, other two get reset to default.

ivory delta
#

Are you talking about Lovelace?

tulip flare
#

buttons are on lovelace, but can status be modified through switch templates?

ivory delta
#

If you have 3 'radio buttons' on your Lovelace and only one should ever be active, you have a couple of options. How you do it depends on what those buttons represent.

#

What are they for? What do they do when they're pressed?

tulip flare
#

okie may be the way I implement is incorrect, at the moment, i got three buttons as lovelace button card, so each button press, it send a RF call via broadlink, so just as old school fan switch, each time one speed is pressed, i just want other one to be off state, without sending a command. Maybe my method of attack to this issue is not so good 😦

ivory delta
#

So... I'd recommend using an input_select (a dropdown) with 3 modes and automations that respond to the new value each time it changes.

#

Having 3 'buttons' for it seems overcomplicated. If you want that because of the way it looks, I understand... if you just wanted it because you didn't know there were other options, consider the dropdown πŸ™‚

hollow obsidian
#

@waxen rune From that example, I'd guess you could go for a json template

#

what did you mean?

tulip flare
#

thanks @ivory delta I will give it a try

hollow obsidian
#

my sensor "sensor.vento_tosko" contain "10.4","km/h","EWE","17.5","Β°C","","","Italy"

waxen rune
#

I thought it looked like a json response, but it isn't. I think mono's way with index is the way to go.

hollow obsidian
#

when I arrange the value template with
value_template: "{{ states('sensor.vento_tosko') | string() | trim() | truncate(4,true,'') | float()/1.8 | round() }}"

#

How can i get the 4th value?

#

(instead of using TRUNCATE)

ivory delta
#

I'm bad with templates... but I'd guess something like this: {{ (states('sensor.vento_tosko') | string() | trim() | truncate(4,true,'') | float()/1.8 | round())[3] }}

#

Extra parentheses around the whole expression (because you're already returning a list/array), then pick an index from that list.

#

Someone else might suggest a more elegant way.

hollow obsidian
#

@waxen rune any more elegant way?

waxen rune
#

I think you could do something like this:

#
{% set foo = ["10.4","km/h","EWE","17.5","Β°C","","","Italy"] %}

{{ foo[0] }} 
#

where foo[0] will give you the first value (10.4), foo[3] should give you the fourth

#

haven't really tried it, but I think it should work. gonna test in dev tools

ivory delta
#

That's what my suggestion does, bonehead πŸ™‚

#

No need to set it to a variable before doing the index. Just use the index.

waxen rune
#

sorry, didn't see your response

ivory delta
#

Intermediary variables are almost always a bad idea unless they're going to be used more than once.

waxen rune
#

i was tagged and responded..

hollow obsidian
#

ok i go to test the position of []

hollow obsidian
#

!

#

it was not an array but this '\n 0.0\r\n Km/h - SSW\r\n\n'

#

and i need to get the 0.0

charred dagger
#

{{your_thing.split()[0]}}

grim geyser
#

Hello. How can I make this template round to 2 decimals points? "{{ states('sensor.server_monthly_energy') | float + states('sensor.work_laptop_monitor_monthly_energy') | float }}"

#

preferable that its fixed at 2 decimals even if the last digit is a 0

nocturne kiln
grim geyser
#

Oh ok thanks

#

I got another question.

#

Im trying to add 2 sensors but im getting a value way higher than it should be.

#

"{{ (states('sensor.server_monthly_energy') | float + states('sensor.work_laptop_monitor_monthly_energy') | float) | round(2) }}"

#

this is saying that 0.46 + 0.00 = 2.55

#

any idea why i have wrong? Tried changing parts but either it doesnt work or doesnt load

nocturne kiln
#

If you try {{ (states('sensor.server_monthly_energy')|int + states('sensor.work_laptop_monitor_monthly_energy')|int) | round(2) }} ?

grim geyser
#

nope. now gives me 2

#

I will keep trying it has work haha its simple math haha

#

im sure its something dumb im not seeing

nocturne kiln
#

Can you give the output of {{ (states('sensor.server_monthly_energy') }} and states('sensor.work_laptop_monitor_monthly_energy') ?

grim geyser
#

that fixed it. With what you said I realized that one of the sensors wasnt what I thought it was.

#

thanks

#

i knew it was something dumb. Sorry about that

nocturne kiln
#

Great it works! πŸ™‚

acoustic ridge
coarse tiger
#

try position: absolute; in the image style attribute

acoustic ridge
#

you mean like this? <img width="200" height="200" src='/local/bilder/unifi/ap.png' style='position: absolute;' />

nocturne kiln
#

How should I write a template sensor that have state 0 for example if power consumption is under 3w on an entity and state 1 if its above 3w ?

deft timber
#

{{ 0 if states('sensor.power_consumption') | float < 3 else 1 }}

nocturne kiln
#

oh, thanks.

trail estuary
#

I am trying to create a template message. Is it possible to filter entities somehow? I have 4 temp sensors, and want to include the entity name and lowest reading the last month, only if has been below 0 degrees....

north acorn
#

Can someone let me know what I'm missing here? The goal is to create a binary_sensor that turns on when there is an event with a specific location (in this case 'Thuis'. It turns on, but stays on, causing it to not trigger again the next day.

  - platform: template
    sensors:
      alisina_werk_thuis:
        friendly_name: Alisina Werk Thuis
        value_template: "{{ is_state_attr('calendar.werk', 'location', 'Thuis') }}"

Maybe I'm not using it correctlt or I'm missing something obvious.

mighty ledge
#

@north acorn is the attribute always set to Thuis?

#

it needs to change from Thuis to something else in order for it to turn off

#

if that never happens, it will always be on and therefore never trigger again

#

@trail estuary yes that's possible

north acorn
#

@mighty ledge hmm I see. Then I need to maybe create something that turns it off. Because it's a calendar event that is either on 'Thuis' or 'Kantoor'. But it can happen that it's 4 days in a row at 'Thuis'. I understand that the binary sensor does not update if the event is ended (since the event itself is not changed, but just stopped).

mighty ledge
#

make a timed automation that checks the binary_sensor

#

if the binary sensor is on... trigger, otherwise don't

north acorn
#

well the problem is that the binary sensor remains on

#

after the event is over

#

so it's on all the time

mighty ledge
#

yeah, but if you do this at a set time every day....

north acorn
#

maybe I'm making it more complicated than needed with a binary sensor template. I think it might be easier to use the calendar itself as an event trigger and then check the attribute state to call for action or not (I use Node-RED).

robust saffron
#

How do I force my template platform sensors and switches to refresh? I can't get HA to read updated sensor.yaml or switch.yaml files unless I select "reboot host system" from the supervisor tabs. None of the "YAML configuration reloading" option under the configuration tabs seem to do anything. I've check all the forums and google, but there seem to be lots of wishes and complaints but no answer....

north acorn
#

I'll ask there, thanks @mighty ledge !

mighty ledge
#

np

#

@robust saffron check your logs, are there errors?

#

the problem with most of those 'complaints' is that people don't check the logs for errors

#

they blindly assume the file is good

#

rule #1, if something isn't working, check the logs.

#

Do not rely on 'configuration check' either.

robust saffron
#

Thanks. Is that the Supervisor Log? I don't see any errors there.

mighty ledge
#

No, the normal home assistant logs. Located in your config folder.

#

I believe they are in the UI under configuration -> logs

robust saffron
#

This is going to take a few minutes to load and scan as I have a known MQTT problem with an integrated device that creates an error message every minute 😦

mighty ledge
#

you should look into learning how to suppress messages from the logs with logger

silent barnBOT
robust saffron
#

Yes. And I don't need so much debug info for stuff that is working either. OK nothing obvious there, but of course this is post a successful reboot. I'll sort out the log supression, excessive debug logging, then try to repeat my previous error, check the logs and come back here. Thanks.

mighty ledge
#

I only have logs for critical issues

#

my logs are empty after days of running without restarts

robust saffron
#

If my repeated error message is 2020-11-05 13:17:21 ERROR (MainThread) [homeassistant.components.mqtt.climate] Could not parse temperature from Then I need to add homeassistant.components.mqtt.climate: fatal to my configuration looger: logs: and then reboot?

ivory delta
#

What's the full error message?

#

Also, what's your config for that integration?

robust saffron
#

That is the ful error message. Nothing after "from". The error is arriving from an MQTT audo-discovered device which is actually an ESP286 talking to a Bosch central heating controller where I don't have a Room Temperature thermostat fitted. There is an Issue and a solution developing over here https://github.com/proddy/EMS-ESP/issues/582

trail estuary
#

@mighty ledge How would I approach that?

mighty ledge
#

@trail estuary What templates have you tried so far?

trail estuary
#

@mighty ledge Sent you a DM

dreamy sinew
#

Please don't send unsolicited PMs. That comes across as rude and demanding of attention and tends to result in you getting blocked by the one you messaged

compact spoke
#

anyone know how to invert a binary sensor status? I've seen some forums about using a template but then it duplicates my sensor. I just want to modify the current binary sensor
wanting to invert a wyze contact sensor

coarse tiger
#

thats definitely a job for a template, no other way I believe

compact spoke
#

@coarse tiger is there a way to use template but not duplicate the sensor?

brisk temple
#

how can I check if there's a value/string at blah[47].name i tried {% if blah[47].name is defined %}

coarse tiger
#

not that I know of, the template gets it's reading from a entity and creates its own based on the template

#

@brisk temple is .name a attribute or the state?

dreamy sinew
#

and is there always an item at index 47

brisk temple
#

it's a json, so it would be attribute?

#

and no

#

that's my error, there's nothign there

#

UndefinedError: list object has no element 47

rugged laurel
#

bla[47].name if (bla | count >= 46)

dreamy sinew
#

so you should check that it exists there before trying to access something below

#
{{ l[3] is defined }}```
#

-> False

brisk temple
#

the issue is i'm trying to loop through 2 arrays and the length is longer on one than the other

brisk temple
#

{% if blah[47] in blah %} fixed it

grim geyser
#

Hello. In a template can i round then keep adding more? for exampe. ((((1.7+1.2) round) + ((0.6+0.3) round))) round

dreamy sinew
#

sure, but why?

#

that's a lot of precision loss

grim geyser
#

because of percentages

#

money is only 2 decimals but percent can give you lots of decimals on each calculation when it needs to be roudned

dreamy sinew
#

eh, i think you're over thinking it

grim geyser
#

On paper I tried it with only 1 round at the end and it was off

#

It was only 3 cents but since I’m building it for the first time I might as well get it exact. If I had to modify an existing template to correct it I would just leave it as is.

ivory delta
#

Rounding multiple times = bad

grim geyser
#

That’s how they do it on my bill

#

But it’s until mid next year

#

Because of the pandemic we are getting discounts on our electric bill. But not off the total, only certain parts

#

For example on the per kWh we are getting 22.86 percent off but just on that part

ivory delta
#

I still don't understand the need to round multiple times. But if it works for you...

grim geyser
#

Let’s see what happens. I’m going to use the template builder

#

And try with various of my bills and see if it works out. Then change the variable for the sensors

neon coyote
#

Hi there!
Can anyone tell me how to passthrough secret into template?
For example, I have secret foo: 'bar' and I want to test if state of my sensor is equal foo. So I want something like:

{%  set foo_var = !secret foo -%}
{{ is_state('sensor.foo_sensor', foo_var)}}

But that doesn't work obviously.
And I would prefer to escape creating input_text that contains secret like in this solution: https://community.home-assistant.io/t/how-to-use-secret-in-sensor-template/110510/4?u=hepoh

deft timber
#

in short, either you use an input_text, which you don't want, or you put the template in the secret file

neon coyote
#

I see, thank you!

teal cove
#

Is this error because of the subtraction or because the templates dont result in real floats or whats the issue here?
TypeError: unsupported operand type(s) for -: 'NoneType' and 'float'
for the template
{{ ((as_timestamp(states('sensor.one_a2003_next_alarm')) - as_timestamp(now())) /60) |round(1) }}

charred dagger
#

Try this part in developer-tools/template and make sure you actually have the right entity id as_timestamp(states('sensor.one_a2003_next_alarm')

teal cove
#

thanks @charred dagger , thats what I always do and it works there. Still logs an error sometimes. Maybe the entity doesnt exist consistently? Idk... But what is the actual error message? I dont get what it actually complains about

charred dagger
#

It means as_timestamp(states('sensor.one_a2003_next_alarm') returns None but as_timestamp(now())) returns a number, and hass doesn't knowwhat none minus a number means.

#

I didn't read your entire message. Sorry.

brisk temple
#
{% set test = [1, 2, 3, 4, 5] %}
{% set n = 0 %}
{% for i in range (test | length) %}
  {% if i + 1 <= test | length %}
    {{ n }}
    {% set n = n + 1 %}
  {% endif %}
{% endfor %}
#

how come n = 0 in the for?

#

all 5 times

rugged laurel
#

because logic

brisk temple
#

which i don't have

rugged laurel
brisk temple
#

i'll check it out thx

mighty ledge
#

@brisk temple what are you actually trying to do outsdie the test? There's very few cases where you need a for loop to count things

brisk temple
#

i have two rest sensors that are pulling json data, each of these have almost the same .name in it, but 1 is missing 3. I wanted to reference data from both of them so I was trying to increment n when the if the name isn't the list so it still pulled the correct information

mighty ledge
#

@brisk temple can you just show the 2 objects? and point out the data?

brisk temple
#

of course, sec

#

there are 3 ppl in the second that aren't in the first, want to just ignore them

mighty ledge
#

and they are in the same order? I doubt that

brisk temple
#

i put it in name order

#
{% set dd = state_attr('sensor.death_dealers_member_list', 'items') | sort(attribute='name') %}```
mighty ledge
#

either way, just filter the second list to only contain the names of the first list

brisk temple
#

i have a filter for those names, but not sure how to take out the other data as well

mighty ledge
#
{% set available = state_attr('sensor.riverrace', 'clan')['participants'] | map(attribute='name') | list %}
{% set dd = state_attr('sensor.death_dealers_member_list', 'items') | selectattr('name', 'in', available) | list %}
#

or you could just iterate through the list using available

#
{% for name in available %}
#

but even then, can you assure that the second list and first list agree on available names?

brisk temple
#

well, i think that first list will at some point have people who aren't on that second list

#

the API outputs all that have participated (first list) and resets on Monday morning

#

whether they have been kicked from second list or not

mighty ledge
#

Ok, so do this

#
{% set participants = state_attr('sensor.riverrace', 'clan')['participants'] | map(attribute='name') | list %}
{% set items = state_attr('sensor.death_dealers_member_list', 'items') | map(attribute='name') | list %}
{% set available = participants | select('in', items) | list %}
{% set dd = state_attr('sensor.death_dealers_member_list', 'items') | selectattr('name', 'in', available) | sort(attribute='name') %}
{% set rr = state_attr('sensor.riverrace', 'clan')['participants'] | selectattr('name', 'in', available) | sort(attribute='name') %}
silent barnBOT
#

@mighty ledge To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks. Here's an example

buoyant pine
#

πŸ˜‚

mighty ledge
#

both dd and rr will have the same names and order

#

missed a command in the middle

brisk temple
#

the available?

mighty ledge
#

yea

#

it's in there now

brisk temple
#

awesome

#

works great, thanks!

mighty ledge
#

np

silent barnBOT
thorny snow
buoyant pine
#

Your automation doesn't have a trigger. Triggers are what cause actions to happen

thorny snow
#

service: automation.trigger
data:
entity_id: automation.svetla_podla_jasu

buoyant pine
#

Then you're just manually triggering the automation which eliminates the point of an automation

#
trigger:
- platform: state
  entity_id: light.obyvacka_svetlo
  to: 'off'
thorny snow
#

yes I will run it manually I need to turn the light on and off with the same automation

buoyant pine
#

Ah, you actually want a script then

thorny snow
#

this automation will turn on my light but he doesn't know how to turn it off

buoyant pine
#

Yes, the syntax is wrong for that. You'll want to use choose: (and you really want to make this into a script since an automation without a trigger is pointless)

thorny snow
#

I start automation with this on_multi_click:

`- timing:
    - ON for at most 1s
    - OFF for at least 0.2s
  then:
    - homeassistant.service:
        service: automation.trigger
        data: 
          entity_id: automation.svetla_podla_jasu      `
buoyant pine
#

Yes, what I'm saying is what you really have here is a script. You can turn what you have into a script and call the script instead in that code

#

What you have works (once the syntax is fixed), but it's better suited for a script

teal cove
#

I'm trying to get the time when a binary_sensor was 'on' the last time.
Using states.---.last_changed includes the state being unavailable which I don't want. Whats the cleanest way to do this? πŸ™‚

buoyant pine
#

Make an automation that records the current time to an input_datetime when the binary sensor goes to on

thorny snow
#

I need a condition

when turned off, perform the action

when turned on, perform the action

in one automation

buoyant pine
teal cove
#

Make an automation that records the current time to an input_datetime when the binary sensor goes to on

Oh, that makes sense. Is there no default state object for this? I don't want to have too many automations

buoyant pine
#

No such thing as too many automations πŸ˜‰

teal cove
#

hahaha

buoyant pine
#

There's nothing specific like that for the last time it was in a certain state, no

teal cove
#

oh, okay. Thank you very much!

#

Uhh, I want use that time to have an automation condition like only trigger when sensor was 'on' in the last 3 minutes.
I'm writing an automation atm but I'm wondering whether putting the time into a input.datetime is the best idea here. Isn't a UNIX Timestamp (that is seconds since 1970 right?) better suited for this?

#

coz I could simply subtract the seconds? or am I overseeing something?

thorny snow
buoyant pine
teal cove
#

@buoyant pine I'm gonna tag you really cheekily, sorry in advance. 😬 What do you think about my idea?

buoyant pine
#

You can convert it to a timestamp and find the difference in seconds, yes

teal cove
#

ahhhh πŸ€¦β€β™‚οΈ thank you

teal cove
#

It's me again!
I'm stuck! I want a template to check whether it is currently between input_datetime.bedtime and input_datetime.wakeup .
Google and the forums didnt help, because both input_datetime entities are obviously time-only, no date!

buoyant pine
#

@teal cove does it need to be a template? what is the ultimate goal?

teal cove
#

Yes, I want a template but its hard to explain haha. Yes, conditions are easy (as I found out today)
But I think this template would be WAY too complex, as it would need to get either yesterdays bedtime and todays waketime or todays bedtime and yesterdays waketime depending on whether it is currently before/after midnight.... 😳 πŸ₯΄ way to complicated

buoyant pine
#

why does it need to be a template?

teal cove
#

Simply put, because I want a template sensor to carry a different number, depending on time of the day ^^

buoyant pine
#

for what purpose? i'm trying to see if there's another solution here

#

and making sure this isn't an example of the XY problem...

silent barnBOT
#

The XY problem is asking about your attempted solution rather than your actual problem.

This leads to enormous amounts of wasted time and energy, both on the part of people asking for help, and on the part of those providing help.

The problem occurs when people get stuck on what they believe is the solution and are unable to step back and explain the issue in full.

teal cove
#

Yes, I see what youre asking :D lemme explain

#

To be exact, I want the sensor to be 'input_number.volume_nighttime' at night (duh) and 'input_number.volume_daytime' at day.

#

Then I want to use that volume in an automation: media_player.set_volume to the volume saved in the sensor

#

But I think I'm on to something here πŸ˜‚ I got a clue

inner mesa
#

You may be trying to put automation logic into a template

teal cove
#

yuh 😬 😬 😬

buoyant pine
#

yeah, just use templating to determine which input_number value to use

teal cove
#

wait that totally makes sense ? omg

#

if I can put a template in a template, yes

buoyant pine
#

why would you need to put a template in a template?

teal cove
#

well idk

#

yeah, just use templating to determine which input_number value to use
@buoyant pine what would that look like?

#

schematically

buoyant pine
#
- service: media_player.set_volume
  entity_id: media_player.whatever
  data:
    volume_level: "{{ states('input_number.daytime') | float / 100 if YOUR TEST FOR DAYTIME HERE else states('input_number.nighttime') | float / 100 }}"
teal cove
#

yes, but my test for daytime is what I cant come up with :D

#

within a template

buoyant pine
#
is_state('sun.sun', 'above_horizon')
```?
teal cove
#

thank you for putting this much effort into my stuff :D

#

ugh no it's not really "day"time but rather the timespan between my bedtime input_datetime and my wakeup input_datetime

buoyant pine
#

how much precision do you need there? you could check if now().hour is between the hours in those input_datetimes

teal cove
#

that is TOTALLY fine

#

i mean, half hours would be cool but thats really it

#

/not neccessary

buoyant pine
#

so, make a test that converts the input_datetimes to just the hour and compare that to now().hour

teal cove
#

but I'm afraid that the problem is gonna be that bedtime is on e.g. May 4 but wakeuptime is on May 5, you know?

buoyant pine
#

ah yeah, that is a bit tricky

#

how much variation is there, and how important is it that it's close to that?

teal cove
#

I dont understand

buoyant pine
#

i'd almost say just make a time of day sensor (which has a fixed start/end time) and be done with it lol

silent barnBOT
buoyant pine
#

or if you really want to, make an automation that turns a boolean on/off based on the input_datetimes

#

and use the boolean in the automation

teal cove
#

if I could set the TOD starts/ends with an input number, nice, but thats not happening I guess :D

#

Good Idea!

#

I'll first try to have two input_datetimes with date+time and have an automation set the date every day. (time staying the same)
Then convert the two input_datetimes to unix timestamps and check if timestamp.now is in between

#

Man, PITA and I ain't talking about bread

buoyant pine
#

actually yeah, you can just compare raw timestamps. not sure why i said to compare hours only

#

that'd do it

#
as_timestamp(states('input_datetime.bedtime')) < as_timestamp(now()) < as_timestamp(states('input_datetime.wakeup'))
teal cove
#

yeah that was my Idea in the first place BUT
if you have an input_datetime with only the time specified, the associated timestamp is not from 1970 but from today....

buoyant pine
#

true

teal cove
#

then I tried adding the timestamp from today(midnight)

#

then I realised that that is dumb, because if it is after midnight, I need to add the timestamp of yesterday

buoyant pine
#

tbh i'd say just use the automation idea with flipping a bool

teal cove
#

haha

buoyant pine
#

then it doesn't matter that it only has a time

teal cove
#

thank you, honestly

#

:D

buoyant pine
#

no prob

#

no sense in trying to over-complicate things

teal cove
#

I'll try my version with input_datetimes with both date+time specified

buoyant pine
#

automation + bool == profit

teal cove
#

and if it doesnt work out, I'll do bools :D

#

got it
{{ (state_attr('input_datetime.nighttime_start', 'timestamp')) < as_timestamp(now()) < (state_attr('input_datetime.nighttime_end', 'timestamp')) }}

#

evaluates True if its nighttime

#

hence

{% if (state_attr('input_datetime.nighttime_start', 'timestamp')) < as_timestamp(now()) < (state_attr('input_datetime.nighttime_end', 'timestamp')) -%}
  Night vol: {{ states('input_number.volume_nighttime') }}
{%- else -%}
  Day vol: {{ states('input_number.volume_daytime') }}
{%- endif %}
sonic nimbus
#

hello, why this is not working

#
      entity_id: media_player.livingroom_tv
      data:
        source: "{{ input_select.livingroom_tv_source }}"```
#

I have a valid input_select values

#

but it wont change on my TV source

waxen rune
#

does it work if you replace the template with a static value? just to rule out other errors

sonic nimbus
#

it doesnt πŸ™‚

sonic nimbus
#

I have another question

#

is there a way to declare variable in the script itself?

#

what Im trying to accomplish: if "{{ states('input_select.livingroom_tv_source') == "SBB BOX" }}" => then set source SBB BOX

#

else set source for TV Audio

ivory delta
#

You want to detect changes in the input_select and change something else based on the result?

sonic nimbus
#

please view my updated pseudo code

#

yes, basically if one option selected (SBB BOX)

ivory delta
sonic nimbus
#

then set SBB BOX for the source

#

everything else is set in input_select, set TV AUDIO

#

well, actually I wanted to do that like template

#

I think I just need an if statement?

#

but Im not sure if I can put template into variables: section

#

as input param to another script?

blissful copper
#

Hi guys!
I'm using this template is_state_attr("media_player.chromecast", "app_name", "Netflix") as a condition and it's working. But this one is_state_attr("trigger.from_state.state", "app_name", "Netflix") doesn't work (with state-change of media_player.chromecast as trigger), even when configuration says it's ok. Is it just buggy or isn't this working in general as a condition?

ivory delta
#

trigger is a variable, not a string. Try is_state_attr(trigger.from_state.state, "app_name", "Netflix")

#

Thinking about it... you probably don't want the .state either, since that represents the state value, not the state object.

blissful copper
#

ah ok, makes sense. But media_player.chromecast is a string? Ok.
Just tried both versions, without quotation marks and without .state, neither of them worked...hmm.

ivory delta
#

When you know the name of the thing, you give it as a string.

#

If you don't know the name and you're using a reference to a variable, there are no quotes.

blissful copper
#

true, thats a general principle. but as media_player.chromecast has also attributes my IT-mind would assume, that it is also some kind of variable πŸ˜„ but I think I understand as what it serves in this context.

so it seems like I can't archieve what I want. probably I but the app_name into an input_text-helper or something like that...

ivory delta
#

Where are you testing this?

blissful copper
#

in an automation directly, as the trigger.from_state-stuff doesn't work in the template-tester-devTool. Or what do you mean?
currently looking like this: https://hastebin.com/ufeteriqow.yaml
(the elevation-condition is currently given ;))

#

I also just made attempt3 like you may see: without .state but with quotation marks

ivory delta
#

The quotes will not work.

blissful copper
#

ok. but without it didn't work, too.

#

haha

ivory delta
#

So something else is wrong. Stop adding quotes.

#

This is an example from one of my automations:

action:
  service: "homeassistant.turn_{{ trigger.to_state.state }}"
  data:
    entity_id: group.landing_switches```
#

Actually, a better one that uses the helper functions:

  - wait_template: "{{ is_state(trigger.to_state.entity_id, 'home') }}"```
#

Use that... trigger.from_state.entity_id instead of a specific name with quotes.

blissful copper
#

ok, is think i understand what you mean. Then I I'll try that now: is_state_attr(trigger.from_state.media_player.wohnzimmer, "app_name", "Netflix")

ivory delta
#

No...

#

trigger.from_state.entity_id is the name

blissful copper
#

Yup, "no" πŸ˜„ Error during template condition: UndefinedError: 'homeassistant.core.State object' has no attribute 'media_player'

#

ahhh click-noise

ivory delta
blissful copper
#

that's it πŸ₯°! Thanks a lot. And learned again something...great.

lofty orchid
#

Need some help: I'm running a templated switch that is controlling a garage door relay. I've got all the logic right, but when I call for "switch.turn_off" on the template, it runs the turn_off function regardless of whether or not the switch is already off. I need it to run only when the switch is truly on, because if I hit the turn_off service, it triggers the relay to fire and will open it.

silent barnBOT
lofty orchid
#

Figured it out, code is in the paste. If someone would look it over, I'd appreciate it. I know lots changes over time.

thorny snow
#

can I list who are currently in a zone with a template?

velvet glen
#

Hi all - on reflection, I think this is a template question - hopefully just a quick steer needed to the right template, card etc.. I've got Hue lights in every room and I've got a tab in Home Assistant for each room in the house. I have made picture buttons for quickly setting the scenes in each room which works great, however given the scenes are standard across the whole house, is there a way to have a single place for these template elements and then just load them into entity cards dynamically

floral lichen
#

How could I change this command to show Power on Years instead of hours? (Hours / 24 / 365 = Years)

for drive in $(ls -la /dev | grep -Ev 'sda|sd[a-z][0-9]' | grep sd[a-z] | awk '{print $10}'); do hours=$(smartctl --all /dev/${drive} | grep Power_On_Hours | awk '{print $10}'); echo "Power on Hours for ${drive}: ${hours}"; echo ''; done
lusty forge
#

Ehlo, I guess I found a bug in the template engine. I got the following template:

{{ (('group.climate_ripoux' | expand | sum(attribute='attributes.current_temperature')) / ('group.climate_ripoux' | expand | length)) | round(precision=1) }}

It works inside the template tester in the UI but not in a template sensor. I got the error:

invalid template (TemplateAssertionError: no filter named 'expand') for dictionary value @ data['sensors']['ripoux_avg_target_temperature']['value_template']

Should I open an issue in Github ?

thorny snow
#

Hi All, I'm quite new in HassIO and trying to automate my heaters. They are using a pilot wire, I want to manage 4 states (so I need two relays). I so declared several switch (from raspi gpio port) 2 per heater. Then I created one input_select per heater with 4 states (comfort, eco, antifreeze and off), I created then 4 automations per heater (one per state) with two actions on each (two service: switch.turn_[on|off]. I've got 5 heater in my house; so this method implies to generate 5x4=20 automation for now, just to switch states; on top of that I want to have an "away" mode to set all heater to unfreeze; then I want to change heater on some different triggers : time of the day, day of the week, if I am consuming too much electricity at a specific moment (eg deactivate one of two heater when using my oven and baking tray at the same time etc)
I have the feeling that template could help me to minimize automations to create in my context and simplify my configuration. Can I create a "super automation" for each heater/input_select that depending on the "to" value could set the relays (switch) like this :

  • Comfort = switch 1 off; switch 2 off
  • Eco = switch 1 on; switch 2 off
  • Antifreeze = switch 1 off; switch 2 on
  • Off = switch 1 off; switch 2 off
lusty forge
#

Make a climate for each switch and use an automation to switch to heat mode for the eco and antifreeze mode maybe ?

ivory delta
#

@thorny snow Look up Schedy

thorny snow
#

@lusty forge and @ivory delta thx a lot, I'll have a look closer on the doc for these topic !

lusty forge
#

@thorny snow You're welcome ! I read a bit closer on your ask and I think you should use a generic thermostat with a script with parameters. That would make one script and make the rest very simple.

thorny snow
#

@lusty forge got it, will test.

ivory delta
#

Even with a generic thermostat, automating anything beyond a very simple 'on/off mode' is going to be complex. Schedy takes care of all the stuff you'd have to consider in automations (missed triggers, presence detection, seasonal modes, etc).

thorny snow
#

@ivory delta; I do not think wanted to managed individually all my heaters using a pilot wire is something unusual. I mean I should not be the only one wanted to schedule this kind of stuff (except maybe regarding the total house consumption). My feeling, is that HA is really wonderfull tool and full of capabilities, I am maybe not taking the problem in the right way... If my request feel strange, please let me know, I am not yet good engouht in HA to be sure thinking my need in the right way.

lusty forge
#

@thorny snow No, your issue is super normal and quite frankly HA should be able to handle that. Having only two switch per thermostat is normal and if HA can't handle it I would personally prefer to suggest an improvement in the core or in a custom component to handle that.

#

I was in the middle of handling two installation on a piped circuitry with one burner and 7 radio thermostat with lag and Schedy looked cool but overkill even in my case

ivory delta
#

HA handles most of your situation. It allows you to integrate devices and control them in one place (instead of loads of different apps). I'm just suggesting that there are better tools for climate schedules than HA automations.

#

HA automations are trigger-based. Schedules aren't.

#

But it's your choice... build it with HA automations if you want, just don't be surprised when it's not reliable.

thorny snow
#

@lusty forge ok, sure, I am totally sure that HA can do it, and if not, I will directly raise an issue and wok on a patch ^^
My reflexion was more about my way of think with homeassistant. I think since there is 2 relays, I need to declare two switch (no other way), then to have a selector between 4 choices, I only see inpu_select; then everything is working for me now, but with a huge amount of automation on-top, my question right now was is there a way to generate some "generic" automation based on templates to avoid having too much automations declared in conf

#

In my need, I do not need some temperature sensor to act as a thermostat. I "just" to play with my heater modes and change them with one button, of automate some basic schedule on it.

#

I do not really understand well how template is working... IIUC I cannot generate some automation in jinja, but need to create an automation for an heater then I would like to have some "if" to take differents actions regarding which "to" value has been set in the input_select.

#

I'd like to change two inputs regarding the "to" value of one input_select

lusty forge
#

Oh I understand now ! Just a simple operation. Use the new switch-case thing they added recently. That can be easy

thorny snow
#

ok, ^^ thx will have a look on that now

thorny snow
#

@lusty forge Yep, thx a lot this fit exactly my need for now !!! I should have more RTFM ! sry @ivory delta I will continue to check Schedy; I have a feeling that you are too far ahead of my need for me to understand now ^^

velvet glen
#

Quick question - is there a way to create a dynamic variable in templates? I'm creating some that are getting pretty long and reference an element multiple times, so I'm conscious it'll be a pain to manually update if these change, eg the lounge_pair name here: https://paste.ubuntu.com/p/cn46CCVZpg/

#

Ideally I'd just add a reference at the top of the template and then use this throughout - this'd mean I could just update in one place in future?

brisk temple
#

which version of jinja is HA based on?

#

so i can see which filters i can use

ivory delta
#

I think it's Jinja 2

brisk temple
#

ya it's 2, but not the latest 2 iirc

#

2.11.2

ivory delta
#

Then those docs are valid. Patch versions usually don't change functionality.

brisk temple
#

i see my problem, I was trying to use an ansible function

teal cove
#

I have an entity attribute which gives out its information as a list like this

[{'direction': 'Stuttgart', 'departure_time': datetime.datetime(2020, 11, 8, 21, 29), 'product': 'S', 'minutes': 28, 'line': 'U1'}, 
 {'direction': 'Stuttgart', 'departure_time': datetime.datetime(2020, 11, 8, 21, 44), 'product': 'S', 'minutes': 43, 'line': 'U1'}]

How Do I convert this so that I can use these values as usual? Actually, I only need the time (21:29 and 21:44) and/or the 'minutes' value (28,43)
Glad for any help! πŸ˜‹

brisk temple
#

try state_attr('sensor.sensorname', 'minutes')[0]

teal cove
#

no no, the thing itself is an attribute.
I get this list when I do {{ state_attr("sensor.departures", "next_departures") }} ...

brisk temple
#

{{ state_attr("sensor.departures", "next_departures")['minutes'][0] }}

teal cove
#

ohh that breaks it down to one list

brisk temple
#

[1] for the second line

teal cove
#

yes of course :D

#

but that still gives me one line of list, which I dont know how to handle

#

{'direction': 'Stuttgart', 'departure_time': datetime.datetime(2020, 11, 8, 21, 29), 'product': 'S', 'minutes': 28, 'line': 'U1'}

brisk temple
#

what are you looking to do? i thought you wanted the minutes

teal cove
#

oh wait I didnt read properly

#

If I do what you said it says UndefinedError: 'list object' has no attribute 'minutes'

inner mesa
#

something like this:

#
 {% set ns = namespace(minutes=[]) %}
 {% for element in data %}
   {% set ns.minutes = ns.minutes + [element["minutes"]] %}
 {% endfor %}
 {{ ns.minutes }}
#

[28, 43]

teal cove
#

ughh I'm not sure how to use this Rob

#

😬

inner mesa
#

what were you looking for?

teal cove
#

youre on the right track, I just dont know how :D

inner mesa
#

you asked for a template that returned that πŸ™‚

teal cove
#

do I copy paste that below this
{{ state_attr("sensor.departures_to_marienplatz", "next_departures") }}

#

?

inner mesa
#

replace data in the second line with state_attr("sensor.departures_to_marienplatz", "next_departures")

teal cove
#

Thats IT

inner mesa
#

I just created a variable with your data

#

test in devtools -> Templates

teal cove
#

TemplateSyntaxError: expected token ':', got '}'

#

wait

#

maybe add [0]

#

nah, that didnt do anything

inner mesa
#

I don't know what to do with datetime.datetime in there, so I just removed them. I don't know if that would be a problem outside of the template editor

#

paste this into devtools -> Templates:

#
{% set data = [{'direction': 'Stuttgart', 'departure_time': (2020, 11, 8, 21, 29), 'product': 'S', 'minutes': 28, 'line': 'U1'}, 
 {'direction': 'Stuttgart', 'departure_time': (2020, 11, 8, 21, 44), 'product': 'S', 'minutes': 43, 'line': 'U1'}] %}
 
 {% set ns = namespace(minutes=[]) %}
 {% for element in data %}
   {% set ns.minutes = ns.minutes + [element["minutes"]] %}
 {% endfor %}
 {{ ns.minutes }}
teal cove
#

SORRY

#

IM so stupid xd

#

1 sec

#

AHH its working

#

Thank you so much guys @inner mesa @brisk temple !

#

If I want the actual departure time, is it easier to add the 'minutes' to the current time? or am I better of using 'departure_time' some how (I don't know how)

#

I always wondered how to extract numbers out of a string properly...

#

To address the XY problem:
Ultimately I want a sensor carrying the information:

sensor.blabla        state 21:29        attributes:
                                              time_1:    21:30
                                              minutes_1: 6
                                              line_1:    U1
                                              time_2:    21:45
                                              minutes_2: 21
                                              line_1:    U2

etc

inner mesa
#

yeah, was about to ask what you were planning to do with it

teal cove
#

😬 populate a card with it

inner mesa
#

there's undoubtedly a better way, but:

#
{% set data = [{'direction': 'Stuttgart', 'departure_time': 'datetime.datetime(2020, 11, 8, 21, 29)', 'product': 'S', 'minutes': 28, 'line': 'U1'}, 
 {'direction': 'Stuttgart', 'departure_time': 'datetime.datetime(2020, 11, 8, 21, 44)', 'product': 'S', 'minutes': 43, 'line': 'U1'}] %}
 
 {% set ns = namespace(minutes=[]) %}
 {% for element in data %}
   {% set time = element["departure_time"].split(',') %}
   {% set hour = time[3].strip() %}
   {% set min = time[4].strip().strip(')') %}
   {% set ns.minutes = ns.minutes + [hour + ':' + min ] %}
 {% endfor %}
 {{ ns.minutes }}
#

['21:29', '21:44']

#

I'm really just hacking around in the template tool and googling, BTW

teal cove
#

I'm trying to understand the magic you put in there, gimme a sec

#

thank you so much

#

okay I think I understand

inner mesa
#

if there was a way to turn that datetime.datetime(xxx) into an actual datetime object, this would be much easier

teal cove
#

yes, but If you dont know a way, I sure dont

#

but yours looks quite clean

#

okay If I put this into a template sensor, for each attribute I paste the whole thing but in the last line I do {{ ns.minutes [0/1/2/3...] }} right?

inner mesa
#

for the state?

teal cove
#

for the attributes. I can template attributes I think

inner mesa
#

yes, but you can also use native data types in attributes. So you should be able to just set the attribute to the output of that

teal cove
#

googling that

inner mesa
#

the met.no weather forecast is like that

teal cove
#

the docs only say that this integration is available from the UI now :D

inner mesa
teal cove
#

yes

inner mesa
#

I'm just giving that as an esamle

#

example

#

point is, you can have a list in an attribute

teal cove
#

but I dont want it as a list, I want it as "clean" states

inner mesa
#

I think you'll have to play around with it

teal cove
#

Okay, will do! Thank you!
One more thing tho: If I do
{% set data = state_attr("sensor.departures_to_marienplatz", "next_departures") %} instead of the text like you did, it says UndefinedError: 'datetime.datetime object' has no attribute 'split'

#

same thing if I just replace data with the state_attr

inner mesa
#

if you want them as separate attributes, then yes, just create additional attributes with different indicies

silent barnBOT
teal cove
#

Thank you so much again! Just the one thing with replacing data ... 😬

inner mesa
#

it looks like it is interpreting datetime.datetime(xx) as an object

#

where are you testing that?

teal cove
#

in devtools -> Templates

#

haha

#

I hope thats what you were asking...

inner mesa
#

yes

#

the problem is that I don't have your actual attribute, so I'm winging it

teal cove
#

thats what I thought

#

I'm just gonna try it for real, maybe its a template tester bug πŸ€·β€β™‚οΈ

#

but is {% set data = state_attr("sensor.departures_to_marienplatz", "next_departures") %} the correct syntax?

inner mesa
#

I'm really just Googling at this point. If you have access to a real datetime object, then you can call things like .hour .minute, etc.

teal cove
#

I'm just gonna try it for real, maybe its a template tester bug πŸ€·β€β™‚οΈ
nope, test_attribute: null

#

but its not a real datetime obj but just a string?

inner mesa
#

not based on the error you provided

teal cove
#

or are you saying I should test .hour etc?

inner mesa
#

this is becoming much harder for me to guess at what's happening on your system

teal cove
#

yeah

inner mesa
#

see the docs above

teal cove
#

πŸ˜”

#

will do

#

Thank you so much tho, can I 'buy you a coffee' for your help? It would have taken me days and hours to get this far alone....

inner mesa
#

nope, happy to help. but I just can't easily reproduce your system and I'm spending more time trying to do that than actually solving the problem at this point

teal cove
#

hahaha

#

I imagine

#

It doesnt eat ``` {% set ns = namespace(minutes=[]) %}
{% for element in state_attr("sensor.departures_to_marienplatz", "next_departures") %}
{% set time = element["departure_time"].hour %}
{% endfor %}
{{ ns.minutes }}````

inner mesa
#

my guess is that if you're getting that error, then rather than treating the datetime object as a string, you should treat it as a datetime object

#

at some point, I would just write a python script for it

teal cove
#

I can barely handle yaml and magic is not my type of soup

#

should element["departure_time"].hour work? or am i off the tracks

inner mesa
#

that's what I would have tried

teal cove
#

wait it does something, If I'm not stupid

#
 {% set ns = namespace(minutes=[]) %}
 {% for element in state_attr("sensor.departures_to_marienplatz", "next_departures") %}
   {% set time = element["departure_time"].minute %}
 {% endfor %}
 {{ time }}

prints 7

#

(I had {{ ns.minutes }} before πŸ€¦β€β™‚οΈ)

inner mesa
#

you need to use a namespace to use a variable in and out of a loop

#

like I did

teal cove
#

I dont get it at ALL haha

inner mesa
#

ok

teal cove
#

oh wait

#

I'll just use ns.minutes

#

YEEEEEEES

#

HECK YES

inner mesa
#

if that works, it's a much better solution than trying to dissect the string

teal cove
#

yes!

#

ty

#

now the adding of hour and min doesnt wanna work

#
 {% set ns = namespace(minutes=[]) %}
 {% for element in state_attr("sensor.departures_to_marienplatz", "next_departures") %}
   {% set hour = element["departure_time"].hour %}
   {% set min = element["departure_time"].minute %}
   {% set ns.minutes = ns.minutes + [hour + ':' + min ] %}
 {% endfor %}
 {{ ns.minutes }}
inner mesa
#

"doesn't wanna work" is too vague

teal cove
#

ofc, sorry

#

TypeError: unsupported operand type(s) for +: 'int' and 'str'

inner mesa
#

then fix that πŸ™‚

teal cove
#

Youre teaching me, I like that

inner mesa
#

hour|string + ':' + minute|string

teal cove
#

almost what I thought of :D

inner mesa
#

or do that in the initial assignment

teal cove
#

['22:52', '22:55', '23:7', '23:10', '23:22']

#

yeeeeeeeeeees

inner mesa
#

you can add a format to fix 23:7, but I'd have to look it up

teal cove
#

doesnt say anything on the blogpost

#

but honestly, I'll take anything that works at this point πŸ˜…

teal cove
#

did that, tahnks!

inner mesa
#

something like: {% set min = "%02d" % element["departure_time"].minute %}

teal cove
#

nevermind lol

inner mesa
#

then it's already a string

teal cove
#

no no it was working, I thought the 07 value went to 10

#

and I couldnt see if it worked

#

but the 07 is still there, I'm just blind

#

thanks!

#

I'm soo close to getting it

#

thank you Rob, youre the man!

teal cove
#

or does one just stitch them together e.g. with .hour + .minute

inner mesa
teal cove
#

yes, thats what I'm looking at

#

but

#

there is datetime to UNIX and the other way around

#

but datetime to datetime is missing, or isnt it?

#

basically 2020-11-08 23:07:00 to 23:07

inner mesa
#

this is probably the closest: timestamp_custom(format_string, local_time=True)

#

you just need to turn it into a timestamp (as_timestamp())

teal cove
#

ah, to timestamp and then back again

inner mesa
#

strftime() can do what you want, but I don't think we have that

teal cove
#

yes, i think so. whats the syntax on that?

inner mesa
#

I'm certain that

#

Google knows

teal cove
#

you got me

#

sorry

inner mesa
#

but like I said, I don't think we have that

teal cove
#

ok

#

when using local_time=True it says TypeError: timestamp_custom() got an unexpected keyword argument 'local_time'

#

even though thats exactly what the docs say

#

it seems like local time is the default anyway tho

fast mason
#

I am trying to make a template for calculating how long my burner is running for between three different floors. I have the math formula but haven't been able to implement it as a template with the actual entities. Is there like a tutorial on how to do this. I was trying with float options but I keep getting errors while trying to build the full template

#

What I need is a xzKa/(a+b+c)* where almost all variable will be entities in HA

waxen rune
#

@fast mason I would suggest something like this. If you make sure that all your values evaluate in Dev Tools, it should be rather straight forward doing the math.

      value_template: >-
          {% set t1 = (states('sensor.burner1') | float ) %}
          {% set t2 = (states('sensor.burner2') | float ) %}
          {% set t3 = (states('sensor.burner3') | float ) %}
          # And then the actual math, not your case below
          {{ ((t2-t1)/(t3-t1) * 100) | round(2) }}
fast mason
#

Wow that is so much more elegant than what I've been trying to write

#
             states('input_number.hourly_burner_consumption') | float * 
             states('sensor.burner_hours') | float * 
             states('sensor.ground_floor_hours') | float) / 
             (states('sensor.ground_floor_hours') | float + 
             states('sensor.first_floor_hours') | float + 
             states('sensor.second_floor_hours') | float))}}
#

round() didn't seem to round anything. I had 10+ decimals. But this thing in the beginning seems to work instead

#

I'll try converting what I have to the way your example is. It's a lot easier to read πŸ™‚

mellow knot
#

hello guys. i have a led light connected via my esp32/gpio. i am using homeassistant automation to increase/decrease its brightness throughout the day. i am trying to figure out a way to read off current brightness of my led and use in a template sensor such that i can then maybe graph that value in lovelace or do other functions with it. as far as the template help page on homeassistant website, it is very well documented and self explinatory but i myself am falling short of being able to implement using the exmaple for my specific scenario. Any help would be apprecaited.

fast mason
#

Unfortunately not sure about that. Although I am interested to see how you increase/decrease it the brightness throughout the day

#

I only have a very simple thing to turn on the lights if brightness goes bellow a set value

mellow knot
#

you can use automation and use the device brightness on property. let me post an example.

#

but i think i should send you a pm instead because this room is for template convo

mellow knot
#

so here is what i have guys but i am unable to see the brightness value:

  • platform: template
    sensors:
    blue_brightness_value:
    friendly_name: "Blue Brightness Value"
    unit_of_measurement: '%'
    value_template: "{{ state_attr('light.blue_spectrum_brightness', 'brightness_pct') }}"

Anyone can give me hints on what am i doing wrong.

buoyant pine
#

brightness_pct is not an attribute

#

brightness is

#

Also...

silent barnBOT
#

To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks. Here's an example

Don't forget you can edit your post rather than repeatedly posting the same thing.

mellow knot
#

oh ok but how is it possible to set a value for brightness_pct in automations etc.

#

is there another way to grab this value. like on_update or something and then pass on to a tempalte sensor.

buoyant pine
#

You can just convert the brightness attribute to percent by dividing it by 2.55

#

Or just use brightness in the service call

#

What are you ultimately trying to do here though?

mellow knot
#

bascially my lights are connected pwm via my esp32. i am using automation to set brightness values through the day. i want to be able to read those same brightness values such that i can use them to graph in lovelace

#

sorry didnt see your messges above. changing it to brightness as attribute works. thank you for the hint

#

much appreciated.

prime sphinx
#

Hi iΒ΄m trying to use the mobile app as an input for an alarm clock that turns on the light iΒ΄m currently stuck on the comparism of the values
How do i convert from Mon Nov 09 20:00:00 GMT+01:00 2020 to xxxx-xx-xx xx:x

so i can compare it to the date_time ?

dreamy sinew
#

how are you getting the value?

#

best method would be to convert both of them to python datetime objects and compare that way

mellow knot
#

whats the best way to not show decimal values for value_template: i tried 'round' attribute but that does not work.

#

my config does not pass when used.

inner mesa
#

~share your code

silent barnBOT
mellow knot
inner mesa
#

there's no such thing as round: xx, which is why it was failing config check

#

making stuff up πŸ™‚

#

value_template: "{{ (state_attr('light.blue_spectrum_brightness', 'brightness') / 2.55)|round }}"

mellow knot
#

gotcha. thank you

left fossil
#

First time using templates, so apologise in advance for whatever stupid simple wrong thing I have messed up here. I'm trying to use the London Air documentation and am following their guidance on setting up sensor data

#

Broken code there

#

Supposedly there's issues with multiple lines 😩

ivory delta
#

No issue with multiple lines. Your issue is that you need to mix quotes.

#

'{{state_attr('sensor.havering', 'data')[0].pollutants[0].summary}}' is bad. The second apostrophe closes the first, leaving the rest a steaming pile of gibberish.

#

"{{state_attr('sensor.havering', 'data')[0].pollutants[0].summary}}" is good, the closing speech marks are right at the end, and apostrophes in the middle don't matter.

left fossil
#

That makes loads of sense

ivory delta
#

Also, it doesn't matter which way round you do it. '{{state_attr("sensor.havering", "data")[0].pollutants[0].summary}}' is equally valid.

left fossil
#

Thanks

#

I shall work out how to update the github page accordingly

prime sphinx
#

what would be the code for converting that Tempate String <template TemplateState(<state sensor.jkm_lx2_nachster_wecker=2020-11-10T19:00:00.000Z; Local Time=Tue Nov 10 20:00:00 GMT+01:00 2020, Package=Unknown, Time in Milliseconds=160503.... currently iΒ΄m getting 1970-01-01 , 00:01:00 but i need 2020-11-10, 19:00 iΒ΄m using {{ (states.sensor.jkm_lx2_nachster_wecker | int | timestamp_custom("%Y-%m-%d , %M:%H:%S")) }} Where is my Mistake ?

buoyant pine
#

states('sensor.jkm_lx2_nachster_wecker')

#

Or states.sensor.jkm_lx2_nachster_wecker.state but what I put is recommended

prime sphinx
#

Or states.sensor.jkm_lx2_nachster_wecker.state but what I put is recommended
@buoyant pine Better but still not perfect result is 2020-11-10T19:00:00.000Z need ist to be like : 2020-11-10 19:00:00

dreamy sinew
#

might need a strptime -> strftime sequence

waxen rune
#

@prime sphinx there is a good example in dev tools demo template:
{{ as_timestamp(strptime(state_attr("sun.sun", "next_rising"), "")) | timestamp_local }}
or another variant:
{{ state_attr("script.store_startup_time", "last_triggered").strftime("%Y-%m-%d %H:%M:%S")}}
https://strftime.org/ is a good place if you need other combinations.

prime sphinx
#

{{strptime(states('sensor.jkm_lx2_nachster_wecker'),"%d/%m/%Y")| timestamp_local }} has the same reesult 2020-11-10T19:00:00.000Z

with the {{ state_attr("script.store_startup_time", "last_triggered").strftime("%Y-%m-%d %H:%M:%S")}} iΒ΄m not getting any further looking on it all day without revelation...

waxen rune
#

@prime sphinx ok, can we try a few things?

prime sphinx
#

@waxen rune shure iΒ΄m happy to get help

waxen rune
#

{{ as_timestamp(strptime(states("sensor.jkm_lx2_nachster_wecker"), "")) | timestamp_local }}

#

if you test that in dev tools > template

prime sphinx
#

that hit the nail right on the head...

waxen rune
#

everything's fine?

prime sphinx
#

2020-11-10 21:00:00 yep perfect now i can work on the rest thank you so much πŸ™‚

sonic nimbus
#

Im curious

#

what is timestamp value

#

I mean like

#
    - platform: template
      value_template: >
        {{ now().timestamp() - as_timestamp(states.binary_sensor.motion_sensor_frontdoor.last_changed) < 45 }}```
#

I noticed while I was testing this template in templates tab that it doesnt represents seconds?

#

I need just to grab "timeframe" when sensor is triggered next 15 seconds

#

I put 45 just for testing purposes

ivory delta
#

It's epoch time

#

The number of milliseconds since the start of the year 1970. It's how computers track time.

#

If you're comparing two timestamps, you need to multiple your seconds by 1000.

charred dagger
sonic nimbus
#

{{ now().timestamp() * 1000 - as_timestamp(states.binary_sensor.motion_sensor_frontdoor.last_changed) * 1000 < 15 }}

#

like this?

ivory delta
#

No...

#

< 15000

sonic nimbus
#

oh yes

#

lol πŸ™‚

#

and famous problem for unix machines and dates for 2032

#

or 2034. year πŸ™‚

#

I forgot

ivory delta
#

Signed integers. D'oh.

charred dagger
ivory delta
#

There's an xkcd for everything

#

Your first one only really works for American English speakers though πŸ˜„

#

Real English speakers don't pronounce 'epoch' like 'epic' πŸ˜„

charred dagger
#

You mean ee-pic?

ivory delta
#

ee-pok

#

/ˈiː.pΙ’k/

#

Versus the American English /ˈep.Ι™k/

pure pulsar
#

Good day all. So I am in the template browser trying to formulate a calculation and it is almost working as expected. {{((states.sensor.us_coronavirus_deaths.state | int) / (states.input_number.us_pop.state | int)) | float }} <<< that works but it is giving me the output of 0.0007219727272727273 and I would like it to be a percentage value with maybe 5 decimal places Any tips for this?

#

reading the jinja2 page and the templates page and something is eluding me I am sure

charred dagger
#

| round(5)

rain condor
#

Hi im running homeassistant supervised on ubuntu and trying to fire a shell script on another machine. but get this error: 2020-11-10 15:15:46 ERROR (SyncWorker_0) [homeassistant.components.command_line] Command failed: ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -i /config/.ssh/id_rsa pi@192.168.1.57 /home/pi/scripts/get_kitchen_fan_light.sh

#

this is my yamL: - platform: command_line
name: kitchen_fan
command: "ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -i /config/.ssh/id_rsa pi@192.168.1.57 /home/pi/scripts/get_kitchen_fan_light.sh"

#

and from the terminal that works:

#

system@hass-dev:/usr/share/hassio/homeassistant$ ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -i /usr/share/hassio/homeassistant/.ssh/id_rsa pi@192.168.1.57 /home/pi/scripts/get_kitchen_fan_light.sh
Warning: Permanently added '192.168.1.57' (ECDSA) to the list of known hosts.
0

charred dagger
#

IIRC there's problems with ssh commands since hass runs as root within its container...

rain condor
#

so what should I do?

#

@charred dagger

charred dagger
#

I'm not sure. I solved it at some point by building my own container that runs as a user... but that's not really an option in supervised installs, I believe.
I just thought maybe knowing more about a potential cause of the problem could help in finding a solution.

coarse tiger
#

works fine for me in supervised

#
  - platform: command_line
    name: HostTemperature_Rpi4
    command: ssh -o ConnectTimeout=20 -i /config/ssh/id_rsa -o StrictHostKeyChecking=no pi@ip "/bin/cat /sys/class/thermal/thermal_zone0/temp"
    unit_of_measurement: "ΒΊC"
    value_template: '{{ value | multiply(0.001) }}'
    scan_interval: 600```
rain condor
#

hm looks like my config