#templates-archived

1 messages · Page 86 of 1

queen meteor
fast vigil
#

ok changed it to custom_components.rest.sensor: debug

#

what the heck, still nothing in the logs 2020-02-21 12:42:28 DEBUG (SyncWorker_1) [homeassistant.components.rest.sensor] Updating from http://192.168.2.253:1400/DeviceProperties/Control 2020-02-21 12:42:29 DEBUG (SyncWorker_5) [homeassistant.components.rest.sensor] Updating from http://192.168.2.253:1400/DeviceProperties/Control 2020-02-21 12:42:29 WARNING (SyncWorker_5) [homeassistant.components.rest.sensor] JSON result was not a dictionary or list with 0th element a dictionary 2020-02-21 12:43:00 DEBUG (SyncWorker_16) [homeassistant.components.rest.sensor] Updating from http://192.168.2.253:1400/DeviceProperties/Control 2020-02-21 12:43:00 WARNING (SyncWorker_16) [homeassistant.components.rest.sensor] JSON result was not a dictionary or list with 0th element a dictionary 2020-02-21 12:43:31 DEBUG (SyncWorker_3) [homeassistant.components.rest.sensor] Updating from http://192.168.2.253:1400/DeviceProperties/Control 2020-02-21 12:43:31 WARNING (SyncWorker_3) [homeassistant.components.rest.sensor] JSON result was not a dictionary or list with 0th element a dictionary

#

have both custom_components.rest.sensor: debug custom_components.sensor.rest: debug

queen meteor
#

it is still loading homeassistant.components.rest.sensor and not your local custom_component

fast vigil
#

yeah

#

let me copy all the files to the rest folder

#
2020-02-21 12:49:37 DEBUG (SyncWorker_6) [custom_components.rest.sensor] update 2: <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"><s:Body><u:GetZoneInfoResponse xmlns:u="urn:schemas-upnp-org:service:DeviceProperties:1"><SerialNumber>5C-AA-FD-31-EA-80:1</SerialNumber><SoftwareVersion>54.2-72160</SoftwareVersion><DisplaySoftwareVersion>10.6.1</DisplaySoftwareVersion><HardwareVersion>1.14.1.11-1</HardwareVersion><IPAddress>192.168.2.253</IPAddress><MACAddress>5C:AA:FD:31:EA:80</MACAddress><CopyrightInfo>© 2003-2019, Sonos, Inc. All rights reserved.</CopyrightInfo><ExtraInfo></ExtraInfo><HTAudioIn>21</HTAudioIn><Flags>0</Flags></u:GetZoneInfoResponse></s:Body></s:Envelope>
2020-02-21 12:49:37 DEBUG (SyncWorker_6) [custom_components.rest.sensor] update 3: {"s:Envelope": {"@xmlns:s": "http://schemas.xmlsoap.org/soap/envelope/", "@s:encodingStyle": "http://schemas.xmlsoap.org/soap/encoding/", "s:Body": {"u:GetZoneInfoResponse": {"@xmlns:u": "urn:schemas-upnp-org:service:DeviceProperties:1", "SerialNumber": "5C-AA-FD-31-EA-80:1", "SoftwareVersion": "54.2-72160", "DisplaySoftwareVersion": "10.6.1", "HardwareVersion": "1.14.1.11-1", "IPAddress": "192.168.2.253", "MACAddress": "5C:AA:FD:31:EA:80", "CopyrightInfo": "\u00a9 2003-2019, Sonos, Inc. All rights reserved.", "ExtraInfo": null, "HTAudioIn": "21", "Flags": "0"}}}}
2020-02-21 12:49:37 WARNING (SyncWorker_6) [custom_components.rest.sensor] JSON result was not a dictionary or list with 0th element a dictionary```
queen meteor
#

yup

#

the json conversion seem to have failed.

fast vigil
#

why failed

#

it worked

queen meteor
#

looking at last line - warning

fast vigil
#

well, that is json_attributes_path: '$.response.body.getzoneinforesponse' value_template: '{{ ok }}'

#

some of those need to be changd

#

it is not correctly specified

queen meteor
#

yes

fast vigil
#

value_template: '{{ value["s:Envelope"]["s:Body"]["u:GetZoneInfoResponse"]["HTAudioIn"] }}'?

#

may be

queen meteor
#

try pasting that json output in jsonlint.com and verify the path

#

yes - exactly

fast vigil
#

no error, but the sensor is not getting the value

#
  - platform: rest
    method: POST
    resource: http://192.168.2.253:1400/DeviceProperties/Control
    name: Sonos Stereo
    headers:
      SOAPACTION: "urn:schemas-upnp-org:service:DeviceProperties:1#GetZoneInfo"
      Content-Type: text/xml; charset="utf-8"
    payload: '<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"><s:Body><u:GetZoneInfo xmlns:u="urn:schemas-upnp-org:service:DeviceProperties:1"></u:GetZoneInfo></s:Body></s:Envelope>'
    value_template: '{{ value["s:Envelope"]["s:Body"]["u:GetZoneInfoResponse"]["HTAudioIn"] }}'```
#

unknown

#

ok it should be value_json

#

now it works

queen meteor
#

yes

fast vigil
#

man, we definitely need debug there. There is no way for anyone to figure it out otherwise

#

thanks @queen meteor

acoustic yarrow
#

nice!

queen meteor
#

lol - you are welcome! glad you got it working!

fast vigil
#

well after lot of help 🙂

queen meteor
#

I'm sure it will be a big breaking change for many - that's what I am afraid of... some of them will have no clue how to fix it

acoustic yarrow
#

this is supposed to make stuff easier right?

fast vigil
#

well, it was 😂

queen meteor
#

if you are knowledgeable enough

acoustic yarrow
#

because i've read that janja2 has to_json

queen meteor
#

that is from string to json, not xml to json

acoustic yarrow
#

parse_xml ?

queen meteor
#

if you have json as string, you can convert that string into json object by using that filter. comes in handy when you need to pass json and you only have string at hand

acoustic yarrow
#

In order to make that work, you should place that xml arsaboo had into a string and then go to json?

queen meteor
#

nope - it doesn't work that way. xml is still xml. there is no easy conversion.

acoustic yarrow
#

hmm okay

queen meteor
#

the new PR converts xml elements into json dictionary, but kind of maintains hierarchy, and you need to know how it is formed, so that you can parse effectively

#

what arsaboo did is debug print that json, so that he knows exactly how to parse it

acoustic yarrow
#

Yes

#

makes sense 🙂

pliant night
#

@queen meteor Did some more testing on the MQTT. I created a "fake" TestLight and with the same template I was having issues with. And of course it works. The state_topics values are the same of the devices having issues and the TestLight fake device I created. I'm assuming this might be a issue with the device?

queen meteor
#

possibly - at least that gives you an idea on whats happening with the device

pliant night
#

@queen meteor Do you know what group or if you know how to dump a device config that wouldn't exist in the entities since mqtt discovery doesn't appear in there?

queen meteor
#

@pliant night not so sure - what device is it specifically? You can try posting in #hardware-archived

quiet niche
#

Hey everybody, I'm having a real braindead moment here, trying to do an is_state on the fan_mode from my climate.radio_thermostat_company_of_america_ct32_thermostat_mode but after 20 minutes, I'm punting my question to the crowd. I can't figure out how to format it!

#

like... value_template: "{{ is_state('climate.radio_thermostat_company_of_america_ct32_thermostat_mode.fan_mode', 'on low') }}"

queen meteor
#

@quiet niche post your code?

#

ok - are you familiar with template editor?

quiet niche
#

a bit, yes

queen meteor
#

ok - go in there, clear the text, and paste the following and see what it gives```
{{ states('climate.radio_thermostat_company_of_america_ct32_thermostat_mode') }}

quiet niche
#

Tried that, yes, it's off

#

there's these sub-attributes for that device

#

I want to test one of THOSE

#

I want to test fan_mode

queen meteor
#

ok - try ```
{{ states.climate.radio_thermostat_company_of_america_ct32_thermostat_mode }}

#

that should give you a bit more information

quiet niche
#

ah that barfs up a big string

queen meteor
#

yup - now, you can access anything and everything you see there using templates.

#

you just need to know which state/attribute you want to access

quiet niche
#

I want to pull out fan_mode - Do I need to parse that string ?

queen meteor
#

can you paste what you saw in there?

quiet niche
#

<template state climate.radio_thermostat_company_of_america_ct32_thermostat_mode=off; hvac_modes=['heat', 'off', 'heat_cool', 'cool'], min_temp=45, max_temp=95, fan_modes=['On Low', 'Auto Low'], preset_modes=['Cool Econ', 'Heat Econ', 'none'], current_temperature=70, temperature=None, target_temp_high=None, target_temp_low=None, fan_mode=Auto Low, hvac_action=idle, preset_mode=none, node_id=9, value_index=0, value_instance=1, value_id=72057594194165764, fan_action=Idle, friendly_name=Thermostat, supported_features=27 @ 2020-02-21T12:34:30.913380-08:00>

queen meteor
#
{{ state_attr('climate.radio_thermostat_company_of_america_ct32_thermostat_mode', 'fan_mode') }}
``` should give you fan_mode value
quiet niche
#

frikkin' syntax, gets me every time

#

thank you

#

ah HAH, OK so this is what got it. {{is_state_attr('climate.radio_thermostat_company_of_america_ct32_thermostat_mode', 'fan_mode', 'Auto Low')}}

#

that attr was critical. Not exactly crystal clear in the docs

#

man, I'd a been hours at that. Thanks again

pliant night
#

@queen meteor sigh.... well i'm so glad my month long pain is done... the answer was delete all the MQTT devices using publish of the a blank template code and publish the same template code after the devices were deleted. I guess this process causes HASS to clean up the object instead of doing updates. Thanks again for the help and totally insane

sterile storm
#

Just noticed there's a channel specific for templates 😂 So I'm moving my message here

#

Is there a way to get all the events from the calendar in a template? I want to display the events in a more natural language way, for example: Today is John Doe and Mary Smith's birthday

This is the closest I've got

    {% if is_state('calendar.birthdays', 'on') %}
        {{ states.calendar.birthdays.attributes.message }}
    {% endif %}

Which returns only one event, of course. Will print Jane Doe's birthday

I know calendars integration has an endpoint, like https://github.com/ljmerza/calendar-card/blob/master/src/event.tools.js#L107

🤔

queen meteor
#

@sterile storm depends on calendar you use. typically you only see the next event.

sterile storm
#

I'm using Google Calendar in this case

queen meteor
#

you only get one event at a time.

#

it is not a limitation on HASS, That's how Google Api works

sterile storm
#

But how did they manage this call? http://hassio.local:8123/api/calendars/calendar.birthdays?start=2020-02-21T00:00:00Z&end=2020-02-28T00:00:00Z (From the repo I shared)

queen meteor
#

must be a custom card. I don't see more than one entry in the states tab - I have 3 google calendars

proud cradle
#

Quick question - what exactly does > and >- mean when calling a template?

wise arrow
#

so, I think I have it correct, if I want the lights to turn off when a door sensor has been closed for 10 minutes AND there is no movement sensed by the motion sensor for 5 minutes this should work right ? 🤔 https://hastebin.com/tuwukijufa.cs

arctic sorrel
#

Of course, you need two conditions and two triggers

wise arrow
#

but doesn't that just do the same check twice ? 🤔

#

oh

arctic sorrel
#

😄

wise arrow
#

I see it now

arctic sorrel
#

Yeah, with yours it'll only turn it off if the motion sensor has been off for 5 minutes 10 minutes after the door was closed

#

Which may be valid, but ... 🤷

wise arrow
#

I'm still quite new to conditions

#

I should implement more of them

arctic sorrel
#

I think I've very few automations without them

wise arrow
#

I moved my whole basement to zigbee2mqtt yesterday

arctic sorrel
#

👍

wise arrow
#

now I just have two rooms left to move yikes

rare panther
#

I do conditions a lot. Since I keep most through state change and check on conditions for filters. is it more inefficient in terms of cpu usage? I haven't notice any increase or decrase in CPU while normal usage - sits at 8% throughout

queen meteor
#

I only use conditions conditionally

#

@rare panther using conditions will not increase cpu usage. It is a drop in the ocean.what ticks CPU is when you try to process millions/billions of conditions all at once. Let’s just say we will never get there with home assistant. Not even for Tony Stark.

rare panther
#

Cool. Thought so. Since i.use lot of templating the conditions help. I could have used multiple triggers, but in some cases i required AND conditions, multiple triggers operate on OR as i understand

arctic sorrel
#

Triggers do, yes, but that's why you have conditions 😉

#

I'd also expect that simple conditions will be less intensive than a poorly written template

queen meteor
#

Yes. Triggers are OR, conditions by default are AND. You can have conditional trigger using templates, conditions in conditions, and conditions in action part of automations.

buoyant pine
#

On one condition.

rare panther
#

Yep. when I started this Automation stuff, the realization of the power of conditions ushered me the path of right conditions 🙂

#

I am just drunk at this point. Hopefully nothing back home gets awkwardly triggered with my condition 🙂

queen meteor
#

No CUI allowed here. (Coding Under Influence) - it only means we have to support more 😛

rugged laurel
#

Most I do is CUI 🤔

queen meteor
#

No wonder! 😎

queen meteor
#

@buoyant pine technically you can have as many conditions as you want in action part of automations. The moment first condition fails, rest is ignored 😊

buoyant pine
#

Oh I was just making a dumb joke lol

ionic karma
#

I am trying to do something very basic. I have a sensor that has a time (e.g., "07:15") and I want to convert it to a datetime object of that time today.
For example, I tried: {{ strptime("07:15", '%H:%M').timestamp() }}, which returns Unknown error rendering template

#

Or

{% set t_alarm = now().strftime("%Y-%m-%d") + " " + states("sensor.ten_minutes_before_alarm") %}
{% set t_alarm = as_timestamp(t_alarm) | timestamp_local %}
{{ as_timestamp(t_alarm) }}

(where t_alarm is that "07:15" string.)
There as_timestamp(t_alarm) seems 600 seconds off from the actual time for some reason.

rugged laurel
#

Don't mix " & '

weary jasper
#

^^^^^^

ionic karma
#

Somehow that doesn't work for me...

weary jasper
#

works on my machine 🤣

ionic karma
#

Been trying this for an hour 😛

#

It seems like strptime returns a str in my case, and not for you.

#

@weary jasper, which HA version are you on?

rugged laurel
#

the best

weary jasper
#

103.5

rugged laurel
#

I'm on 12h old dev branch, works there

ionic karma
#

I am on 0.105.5...

weary jasper
#

does a simple {{ now() }} work

ionic karma
#

Yes

rugged laurel
#

is the backend running?

ionic karma
#

Yes, also

rugged laurel
#

give up

ionic karma
#

I am restarting, maybe that helps

#

Could it be a processor architecture thing? Maybe ARM can't count before timestamp 0 (1970-01-01)?

weary jasper
#

i will try on my fish tank server its a pie but a really old version of ha ....60 i think

ionic karma
#

Oh, yeah, I have another Pi on which it also doesn't work.

weary jasper
#

no go on pi

ionic karma
#

That is super strange...

queen meteor
#

It must be the session issue. When the session is timed out, it won’t work. Refresh the page to make sure you are still connected

meager orchid
#

Would someone be willing to help me with a template? I am "simply" trying to create a button that will change my theme to a random one of the theme I have. I have this script:

#
    alias: Theme Set2
    sequence:
    - data:
        name: '{{ ["Amoled - MOD", "Amoled - Teal", "Amoled - Blue", "Amoled - Green",
          "Light - Orange", "Light - Green", "Gray & Green", "default"] | random  }}'
      service: frontend.set_theme```
#

But get an error that says Theme {{ ["Amoled - MOD", "Amoled - Teal", "Amoled - Blue", "Amoled - Green", "Light - Orange", "Light - Green", "Gray & Green", "default"] | random }} is not defined.

queen meteor
#

@meager orchid use data_template instead of data.

meager orchid
#

@queen meteor that worked - but I guess I have another problem (probably more suited for the #frontend-archived folks)...it's only applying the random theme to the cards, rather than the whole UI - any idea why?

#

nm, I had to manually set the theme to backend-selected, and it works perfectly - thanks!

charred badge
#

Trying to do a simple new sensor using a template, but it's value is 0. I used another sensor as a starting point (for converting km to miles). Its probably the math piece being in the wrong syntax

#
  - platform: template
    sensors:
      boiler_cost:
        friendly_name: Boiler Cost £/day
        unit_of_measurement: £
        value_template: "{{ states('sensor.boiler_todays_power')|int*0.24 }}"
charred haven
#

@charred badge test the template in the template editor...that should help you see what you need to adjust

charred badge
#

yes i have been playing in there

#

either 0 or red error message 🙂

charred haven
#

instead of int maybe try float?

charred badge
#

i thought i could just multiply my senosr.boiler_todays_power x 0.24 to get the cost

#

e.g 0.66 x 0.24

charred haven
#

yea use float instead of int

charred badge
#

ah ha! Float perfect

charred haven
#

when you use int 0.66 converts to 0

charred badge
#

thank you, ah didnt realise that

charred haven
#

because integers are whole numbers only

charred badge
#

i should have known better

#

I can round it using Round

queen meteor
#

You can round anything using a hammer

charred badge
#

This seems to do the trick {{ (states('sensor.boiler_todays_power')|float*0.1838)|round(2) }}

fair hemlock
#

Is it possible to use some kind of "entity template"? at the moment I 've 4 devices which three sensors different sensors. I'm getting the data via scrape. Which means that I need 4*3=12 scrape settings in the configuration.yml.
I would like to create a template for the device with 3 sensors and in the configuration.yml just 4 devices with different IP+Names.

dreamy sinew
#

not currently possible

fair hemlock
#

okay thanks 🙂

slender urchin
#

Hi all, struggling with something if anyone can help? I am trying to create a template sensor to convert km into miles. I can get the sensor to display but the division doesn't work as intended. The result it gives is km divided by 2 (i.e half) rather than 1.609 as per my code. I just can't see what I cam doing wring here! The sensor code is:
milesleft:
friendly_name: "Range"
unit_of_measurement: 'miles'
value_template: "{{ states('sensor.420d_remaining_range_total')|float/1.609 |round}}"

fast vigil
#

round it to 2 decimals.

slender urchin
#

so round(2) at teh end?

fast vigil
#

yes, that should work. Test in template editor first

slender urchin
#

Cheers, I shall test it now

#

Ok that works well apart from the fact I have my miles to about 15dp now BUT it is now the correct figure 🙂 Thanks for the assistance on this

fast vigil
slender urchin
#

I'll take a look at this this evening, should get back to work now. after my lunchtime tinkering with my setup:) round(1) is giving me 3 dp at the moment but I'm sure I'm not far off now. Thanks for the assitance

buoyant pine
#

this:

{{ states('sensor.420d_remaining_range_total')|float/1.609 | round(2) }}
``` will only round the 1.609 to two places. you need to do this:

{{ (states('sensor.420d_remaining_range_total')|float/1.609) | round(2) }}

slender urchin
#

Cheers, staring at too many brackets, that makes total sense now!

slender urchin
#

Struggling to get a good icon for that template sensor now. I'm doing:milesleft:
friendly_name: "Range"
unit_of_measurement: 'miles'
value_template: "{{ (states('sensor.420d_remaining_range_total')|float/1.609) | round(0) }}"
icon_template: mdi:map-marker-distance

#

I did manage to get a battery icon up at some point but I can't get this one or milometer to work at all. I suspect I am being thoroughly dense again 🙂

fast vigil
#

that is not a template. You need to provide an icon_template or use customize to change the icon

slender urchin
#

I tried customize which seemed to work for a while. I see what you mean though I'm using the format from a straight sensor there. It's been a long day! Knew I was being stupid! Cheers and sorry for being so dense

#

Missing the mdi: from customize - doh! Thanks again

ancient lynx
#

Hey all. Is the output on this page something that templates could help extract different values from?

#

Like if I just wanted the "EXIT CLOSED TO COUZENS" part?

#

Which is dynamically generated, so if you see this message later, it may be different.

#

Basically I want the part between <div class='dmsMessage'> and the first </div>.

dreamy sinew
#

regex is a thing

blissful vapor
#

anyone knows if its possible to template the stream_source and still_image_url for cameras. I have two template sensors that "builds" the changing stream url. i want to use them as inputs to a camera.

  • platform: generic
    name: camera_dyn_url_test
    stream_source: >-
    {{ states("sensor.dyn_stream_test") }}
    still_image_url: >-
    {{ states("sensor.dyn_snap_test") }}
#

Possible?

queen meteor
#

You can’t use templates there unfortunately.

queen meteor
#

Whoa! No messages in here for more than 26+ hours. 😊

buoyant pine
#

{{ whoa }}

velvet gate
#

everyone is an expert now, time to go home.

queen meteor
#

Let’s archive this channel. Looks like everyone is a template expert now. 😊

charred haven
#

haha

velvet gate
#

yup

rugged laurel
#

agreed ✅

buoyant pine
#

We did it Reddit Discord!

west dome
#

How can I commify a number like 2304.45 -> 2,304.45? My current template is:
"{{ (((states('sensor.sw_office_p1_kb') | float) + (states('sensor.sw_office_p2_kb') | float) + (states('sensor.sw_office_p3_kb') | float) + (states('sensor.sw_office_p4_kb') | float) + (states('sensor.sw_office_p5_kb') | float) + (states('sensor.sw_office_p6_kb') | float) + (states('sensor.sw_office_p7_kb') | float) + (states('sensor.sw_office_p8_kb') | float))/1000)|round(3) }}"

queen meteor
#

Ooh, we got a customer! 😂

west dome
#

haha.... Sorry I guess not everyone is an expert.....

queen meteor
#

There is no simple way to comity a given number. The filter does not exist in home assistant at the moment.

west dome
#

Alright then, easy answer. hahaha. Thank you. Now you can archive the channel. 😜

queen meteor
#

@west dome here you go```

{{ "{:,.2f}".format(543921) }}

west dome
#

@queen meteor That worked great! Thank you

queen meteor
#

if you don't want trailing decimal points, you can use ```
{% set number = 12345 %}
{{ "{:,}".format(number) }}

oak juniper
#

Hi folks, i have a currentcost power meter, and I’m trying to figure out the best way to deal with its output. It emits an xml stanza every 6 seconds with a Watt reading for 3 phases, as well as a temperature value.
I have a tiny shell script reading each stanza, piping it through xml2json, then uses mosquitto_pub to send it to HA on a particular topic.
My question is: what is the best way to represent this in HA? I am currently extracting each phase into a separate entity using templates, but it feels clunky. Ideally, should it not just be a single entity with multiple attributes?

long basalt
#

Pretty easy to just do a MQTT sensor and use the json_attributes_topic to feed the attributes?

oak juniper
#

I’ve not encountered that before, I’ll have to go google it. Thanks!

long basalt
#

You can even auto create the entity from your script. I do the same things with my restic backup scripts

thorny snow
#

Scratching my head why this don't work...

  • platform: template
    sensors:
    elpris:
    friendly_name: "Elpris"
    value_template: "{{ states('sensor.electricity_price.attributes.price_level') }}"

The atribute of the entity is:
price_level: VERY_EXPENSIVE

The template sensor is giving me unknown

buoyant pine
#
"{{ state_attr('sensor.electricity_price', 'price_level') }}"
thorny snow
#

Thanks @buoyant pine
In the past i have used .attributes in the template.
Has something changed?

buoyant pine
#

That's if you're accessing the state object directly like states.domain.object_id.attributes.whatever @thorny snow

sudden anchor
#

io ti sento

coarse sable
#

I have a sensor that returns a filename :
templates ```
{{ states("sensor.chf50_gv_lastfile") }}
Event20200227142438001.Avi

#

What string manipulations are available to help me convert the name into a date & time?

#

In the above example, the date & time would be 2020/02/27 14:24:38

coarse sable
#

well... {{ states.sensor.chf50_gv_lastfile.state[5:19] }} returns 20200227144437.
I'm close bois !
But now what... ?

coarse sable
#
  strptime(states.sensor.chf50_gv_lastfile.state[5:19], '%Y%m%d%H%M%S') %}

embedded_time = {{ datetime_obj }}
``` returns `2020-02-27 14:44:37`
#

Thanks for all the input & ideas.

fossil totem
#

I'm trying to work out a template and I'm apparently less of a Jinja Ninja than I expected because I'm not finding what I need.

#

Here's the setup:

#
{% set hvacmodes=['auto', 'off', 'cool', 'heat', 'dry', 'fan_only'] %}
{% set hvacmode='cool' %}
#

I want to return the next item in a list, given one of the existing items.

#

So if hvacmode='cool', I want to return heat

#

The list is dynamic, I don't know the contents ahead of time.

#

rubber ducky debug to the resuce!

#

{% for mode in hvacmodes %}{% if mode == hvacmode -%}{{ hvacmodes[loop.index] }}{%- endif %}{% endfor %}

#

just stumbled on this by accident but it works great, jinja lists are zero indexed but loop.index isn't, so it's automatically one greater than the index of the current item being looped over

#

not as smart as i thought, now i need to loop back around to the beginning...

#

{% for mode in state_attr("climate.mqtt_hvac", "hvac_modes") %}{% if mode == states("climate.mqtt_hvac") %}{% if loop.last %}{{ state_attr("climate.mqtt_hvac", "hvac_modes")[0] }}{% else %}{{ state_attr("climate.mqtt_hvac", "hvac_modes")[loop.index] }}{% endif %}{% endif %}{% endfor %}

#

added a check to see if we're on loop.last, if so then go ahead and set the index to 0. now it works!

velvet gate
#

someone told me the other day how to convert the weird time format from the dark skies alert but I forgot, and now I got my entity filter/markdown card working

fossil totem
#

Success!

velvet gate
#

it was something like {{ states.sensor.dark_sky_alerts.attributes.time | something }}

#

I can't figure out the something lol

#

in the sensor it looks like 'time': 1582876800

fossil totem
#

so you have unix epoch time and you want to convert it to printable time?

velvet gate
#

is that what that is?

#

lol yes

#

why can't they use normal time

fossil totem
#

define "normal" time

velvet gate
#

4:02pm

fossil totem
#

it's a surprisingly complicated question

velvet gate
#

lol

#

I just want it to look like what I am used to

fossil totem
#

let's try some things 😄

velvet gate
#

haha

#

noice ps2 port

fossil totem
#

close, but not quite

#

my nick has a hint

velvet gate
#

ahh

#

boo

fossil totem
#

{{ 1582876800 | timestamp_local }}

#

to answer your question... something is timestamp_local

velvet gate
#

yesss

#

I tried time_date, date_time, time.date, date.time, all kinda stuff lol

buoyant pine
#

| please_do_it

fossil totem
velvet gate
#

hmmm looks like I can change the order of the date and time too

fossil totem
#

you sure can!

#

time seems like a simple thing but it's preposterously complicated. strftime is available and I'd recommend getting familiar with it: https://strftime.org/

#

you can print out time in all sorts of ways!

buoyant pine
#

ᕕ( ᐛ )ᕗ

velvet gate
#

@fossil totem will that last one work in a template though?

queen meteor
#

@velvet gate I mentioned earlier. That is a Unix time stamp, and you can convert to date time format easily using strftime

velvet gate
#

hmmm

#

you mean strptime(string, format)?

#

lack of examples make this hard for non programmers lol

fossil totem
#

it's actually a python thing, not jina, and can only be used a some special cases (now().strftime('format'))

velvet gate
#

that how it seemed

fossil totem
#

so that's probably not so helpful to you right this moment 😄

#

sorry bout that

#

timestamp_custom might do it

#

which just implements strftime

velvet gate
#

yeah I started trying to play with it but I think I have the formatting wrong.

Time: {{ states.sensor.dark_sky_alerts.attributes.time | timestamp_custom(%a, local_time=True) }}
#

trying to add those % deals

#

I'm not totally dumb but it does help to have like 1 example of what things are supposed to look like.

fossil totem
#

put double quotes around your %a

#

{{ as_timestamp(states.sun.sun.attributes.next_rising)| timestamp_custom("%a") }}

velvet gate
#

ahhhh

#

I didn't need the local_time=true

#

haha

#

its working now

#

boom, thank you sir lol

#

I dunno if anyone else does that but I wanted any dark sky alerts to appear as a card on my dashboard and then vanish when there is no alert.

#

using markdown, its ugly, but I haven't bothered to look up how to format stuff yet

queen meteor
#

I rarely use the dashboard, if I keep clicking on the dashboard for everything, it is not really an automation.... is it?

velvet gate
#

I just like seeing the weather

#

and I have it show things that are left on, etc.

#

I'm also not the only one who uses it.

queen meteor
#

lol

velvet gate
#

although, all of the automations work fine so its not like lights are ever left on that shouldn't be and stuff.

ancient lynx
#

I was able to get a countdown using as_timestamp in seconds, which I was them able to get down to fractions of days using templates. Is there a way to break it down to days, hours, minutes, seconds, and have those disappear as they run out?

oak summit
#

I want to convert the player list attribute in the new minecraft server component into a comma seperated list of players with the word "and" before the last one, so I can put it through a TTS and it sound right. what's the best way to do that?
When I test {{ state_attr('sensor.minequestria_spigot_server_players_online', 'players_list') }} in template dev panel, it outputs ['MazzoManicotti', 'FocusForte']

queen meteor
#

@oak summit that example is already there as the default code in the template editor

oak summit
#

oh I must have overlooked it, I'll have to check that again.

queen meteor
#

something like this ```
{% for state in state_attr('sensor.minequestria_spigot_server_players_online', 'players_list') -%}
{%- if loop.first %}The {% elif loop.last %} and the {% else %}, the {% endif -%}
{{ state | lower }}
{%- endfor %}.

oak summit
#

thank you!

queen meteor
#

just updated the code, try again

oak summit
#

I am still totally new to templates, so I'm not sure I would have figured that out on my own 😅

queen meteor
#

lol - no worries!

#

best way to learn is to play in the template editor - try ```
{% for state in ['MazzoManicotti', 'FocusForte'] -%}
{%- if loop.first %}The {% elif loop.last %} and the {% else %}, the {% endif -%}
{{ state | lower }}
{%- endfor %}.

oak summit
#

Yeah, I got it doing what I want now ^_^

ancient lynx
#

@oak summit Template editor was huge in me starting to wrap my head around the template stuff.

oak summit
#

Yeah, I understand it enough now to tweak and modify, but building more of the more advanced stuff like for loops, I'm still in a bit above my head lol

#
{% for state in state_attr('sensor.minequestria_spigot_server_players_online', 'players_list') -%}
  {%- if loop.first %}{% elif loop.last %}, and {% else %}, {% endif -%}
  {{ state | lower }}
{%- endfor %} are online right now.```
#

that does exactly what I want 😄

rugged laurel
#
{{ state_attr('sensor.minequestria_spigot_server_players_online', 'players_list') | join(", and ") }}
queen meteor
#

that will give too many "and"s when you have more than 2 entries

rugged laurel
#

And?

queen meteor
#

if you have ['a', 'b', 'c'], it gives a, and b, and c 🤢

rugged laurel
#

And d ;)

queen meteor
#

lol

#

@ancient lynx here is a second to days, hours, minutes, and seconds example: ```
{% set seconds = 641200 %}
{%- set map = {'Week': (seconds / 604800) % 604800,
'Day': (seconds / 86400) % 7,
'Hour': (seconds / 3600) % 24,
'Minute': (seconds / 60) % 60,
'Second': (seconds % 60) } -%}

{%- for item in map if map[item] | int > 0 -%}
{%- if loop.first %}{% elif loop.last %}, and {% else %}, {% endif -%}
{{- map[item]|int }} {{ item -}} {{- 's' if map[item]|int > 1 -}}
{%- endfor -%}

ancient lynx
#

@queen meteor If I want the seconds variable to be set by a sensor, then I can use a template to set that, correct?

queen meteor
#

yes

rugged laurel
#

How else?

queen meteor
#

anything goes with 🍺

ancient lynx
#

Cool. Any advantage to that solution vs the one in the forum thread?

queen meteor
#

it is essentially lifted from forum - and made it better.

ancient lynx
#

Awesome. Thanks for the guidance.

queen meteor
#

#MTGA @rugged laurel

ancient lynx
#

@queen meteor It broke everything.

#

Now the value_template doesn't even work. Returns unknown. And days_left returns none.

#

Template editor gives me Error rendering template: TemplateSyntaxError: expected token ':', got '}'

queen meteor
#

@ancient lynx you got line # 13 wrong

ancient lynx
#

I tried every variation of that line I could think of, but never returned a valid response.

#

What's wrong with it?

#

Putting {{(as_timestamp(state_attr('calendar.2020_fia_formula_one_world_championship_race_calendar', 'start_time')) - as_timestamp(now())) }} in the template editor returns a valid value.

#

But putting it in line 13 never does.

#

@queen meteor

queen meteor
#

try this ```
{%- set seconds = (as_timestamp(state_attr('calendar.2020_fia_formula_one_world_championship_race_calendar', 'start_time')) - as_timestamp(now())) %}
{%- set map = {'Week': (seconds / 604800) % 604800,
'Day': (seconds / 86400) % 7,
'Hour': (seconds / 3600) % 24,
'Minute': (seconds / 60) % 60,
'Second': (seconds % 60) } -%}
{%- for item in map if map[item] | int > 0 -%}
{%- if loop.first %}{% elif loop.last %}, and {% else %}, {% endif -%}
{{- map[item]|int }} {{ item -}} {{- 's' if map[item]|int > 1 -}}
{%- endfor -%}

#

you don't put {{ inside {% and %}.

ancient lynx
#

Ah. It was the brackets then.

#

@queen meteor That did it. Thanks for the help.

fiery sentinel
#

I'm trying to make the icon on a "Entity Button Card" change depending if the entity is "on" or "off" (its a zigbee door sensor) how can I accomplish this?

rugged laurel
#

not sure that card supports it (I may be wrong), but the custom button card does at least

fiery sentinel
#

ok, let me try that one, the regular entity button card does not seem to like it

#

is ok if I paste the 12 lines here? (As in-line code)

#

going for it!

#
entity: binary_sensor.multipurpose_sensor
hold_action:
  action: more-info
show_icon: true
show_name: true
tap_action:
  action: toggle
type: entity-button
icon_template: "
 {% if is_state('binary_sensor.multipurpose_sensor', 'on') %}
 mdi:door
 {% else %}
 mdi:door-closed
 {% endif %}"
name: Door
#

@rugged laurel I don't have a custom-button card, i assume its a HACS add-on?

rugged laurel
#

no

#

HACS Does not have add-ons

fiery sentinel
#

hmm so I see it has a configuration section but not an installation section.

#

so, how do I get this installed?

#

NVM

#

odd to have installation AFTER configuration

rugged laurel
#

Not really

#

The configuration aspact of that card is what it "sells"

fiery sentinel
#

sure, but you have to install it first

rugged laurel
#

Not to read about what it does

fiery sentinel
#

most folks will browse for pics/tables etc to "see" what it does/looks like, so they will find that piece (IMO) but documentation should be sequential

#

anyways, thanks for pointing me in the right direction.

ancient lynx
#

@queen meteor I broke it again, and I cannot figure out why.

#

Have two files, second one starts at line 15.

queen meteor
#

@ancient lynx I'm going to have to start charging you for screwing things up

ancient lynx
#

I know. It's a problem.

#

I reconfigured, because I want to do an automation that starts when seconds reaches zero.

#

And with the formatting, the sensor kept reporting whatever number weeks there were left, or I suspect whatever the first digit is.

queen meteor
#

whats the error?

ancient lynx
#

I can get the first file in just fine. But the second keeps giving an unkown result

queen meteor
#

I see. what do you see when you paste this in template editor? {{ state_attr('sensor.next_f1_event', 'seconds_left') }}

ancient lynx
#

The correct amount of seconds until the event.

#

Big number at the moment.

#

Logs show TypeError: unsupported operand type(s) for /: 'NoneType' and 'int'

queen meteor
#

ok... try ```
{%- set seconds = state_attr('sensor.next_f1_event', 'seconds_left') | int %}

ancient lynx
#

Will that get rid of the digits after the decimal?

#

Which, I suppose doesn't matter, since those are fractions of a second, if I'm thinking of that correctly.

#

Don't need to be that accurate.

queen meteor
#

no - that makes sure the seconds are in the numeric format, as you are using that value to multiply for seconds, hours...etc

#

if the value is not numeric, you get the error you shared above

ancient lynx
#

Got it. I thought it also brought it to the next whole number as well.

#

That seems to have done it. Thank you again. I will stop futzing with it.

#

Next one I owe you a beer.

queen meteor
#

lol - you are fine! good luck!

fiery sentinel
#

not sure if this is a "templating" question, I've created a "Horizontal stack card" with 4 entities in it (they are temperatures) is there any way I can remote the small thermometer icon to the right of the title?

arctic sorrel
fiery sentinel
#

k

olive moth
#

hello .. someone here who can help me to find out how to start and stp a kodi addon with call_method?

arctic sorrel
hasty acorn
#

the issue lies somewhere in the way the list is being returned, or maybe double quotes

hasty acorn
#

actually im making progress... this is where the error is coming from: Sending {'id': 176, 'type': 'event', 'event': {'event_type': 'call_service', 'data': {'domain': 'zha', 'service': 'issue_zigbee_group_command', 'service_data': {'group': 1, 'cluster_id': 768, 'command': 7, 'args': '"\n \n \n \n \n [30932, 20774, 5]"'}}

#

ok, i am down to this: 'args': '[9305, 10813, 5]'

#

i just need to figure out how to get an actual list instead of a string

hasty acorn
#

can jinja output an actual list, or is it always going to be a string??

queen meteor
#

@hasty acorn lists are tricky in jinja because everything is treated as strings

hasty acorn
#

that is what i have been fighting for hours

#

i have it functional as i was unable to create an actual list

#

seems like overkill

#

the macros are identical, with the exception of one outputs x value, and the other y

queen meteor
#

definitely not the issue with the macros.. It is how the lists are passed to the args.

#
            args:
              - "{{ color_temp }}"
``` is the problem.
#

that color_temp value will be treated as string and not as list

hasty acorn
#

nah, thats not whats not working

queen meteor
#

@hasty acorn best I'd suggest is to use python_script or AppDaemon when it comes to this. You have much better control over there than jinja.

hasty acorn
#

its the set_color values

#

yeah, but i was "trying" to get a light template working

#

just to see if it were possible

queen meteor
#

ok... what is the output of "{{ hs_to_xy(h, s, 100, 5) }}"

#

Irrespective, the only way out is using python_script or AD. It will save you a lot of headaches

hasty acorn
#

the more up to date code is in post 2

#

that line was outputting "[#, #, #]"

#

also updated the gist

queen meteor
#

Again, unfortunately it will be treated as string. You could try adding individual list items using - by splitting the three values.

#

Right above - 5

hasty acorn
#

are you saying like a ```
{% for v in value %}

  • {{v}}
    {% endfor %}
#

because i was worried it would not be properly indented

#

no dice: 'args': '- 45940- 19594- 5'

queen meteor
#

Not like that. Using indexing.

#

Give me 5 min.

hasty acorn
#

ok

#
  - xy[0]
  - xy[1]
  - xy[2]
queen meteor
#

yup

hasty acorn
#

trying it now

#

no dice, still a string

#

'args': '- 9305\n - 10813\n - 5'

#

im convinced jinja just cannot do it

queen meteor
#

you should be doing something like this: ```yaml
args:

  • {{ xy[0] }}
  • {{ xy[1] }}
  • {{ xy[2] }}
hasty acorn
#

yep

#

well... not quite

#
args: >-
  macro stuff...
    - {{ xy[0] }}
    - {{ xy[1] }}
  end macro
  {{ call macro }}
#

like that

queen meteor
#

@hasty acorn that would muddy things... best way to do that is get a string from the macro, and parse it explicitly - that way no new lines, no spaces or unwanted white spaces

hasty acorn
#

yeah, i think the way i have it in the post/gist is the only way to make it work with jinja

#
args:
  - >-
    macro stuff...
      {{ xy[0] }}
    end macro
  {{ call macro }}
  - >-
    macro stuff...
      {{ xy[1] }}
    end macro
  {{ call macro }}
#

the crappy thing is all the repeated code

queen meteor
#

yup - that's unfortunate!

hasty acorn
#

either way, this is all proof of concept really, the zha group commands are still in the works

#

and you have to do a lot of digging to get the correct commands

#

lol

queen meteor
#

does this approach work?: ```yaml
args:
{%- macro x -%}
code here
{%- endmacro -%}

  • {{ x(...)[0] }}
  • {{ x(...)[1] }}
hasty acorn
#

i know @jolly garden is working on making it more user friendly

#

hrmm....

queen meteor
#

reduces duplicity, and still be able to return as list

hasty acorn
#

yeah, but im not sure how to do it that way, a macro doesnt return anything... right?

#

so how would you get var[0] and 1?

#

afaik calling a macro just poops out values like a python print

#

"No, macros can only return template snippets (in the form of Markup objects), not Python objects like dictionaries."

#

but i do like the thought process...

queen meteor
#

macros can return data...

hasty acorn
#

and, that approach fails in yaml lint... i was thinking if i could place the macro above like that, i could create a if you want x, poop out x, etc

queen meteor
#

ok.. give me 5 min... finisghing up lunch

hasty acorn
#

ok

queen meteor
#

@hasty acorn what I do is have macros return string, and parse to my needs.

hasty acorn
#

so 2 questions... how can you have the macro above the list and below the "args:" and it still be valid yaml, second how do you return and parse the string

queen meteor
#

I a trying locally in my template editor... what values do you pass for h and s?

hasty acorn
#

360, 100 for red

queen meteor
#

we will get to both of your questions shortly

hasty acorn
#

actually any value 0-360, and 0-100

#

but those numbers represent red

queen meteor
#

when I call {{ hs_to_xy(360, 100, 100) }}, it returns 45940

hasty acorn
#

for one value it does

#

x[0]

#

and that is a good returned value

queen meteor
#

ok...

#

in your git code, both macros are exactly same... correct?

queen meteor
hasty acorn
#

giving it a go now! 🤞

queen meteor
#

that code simplifies not having two exact macros in two different places, and still lets you access data the way you want. If that doesn't work, python_script would be the way to go!

hasty acorn
#

nope... 'args': '- 45940 - 19594 - 5'

queen meteor
#

where are you seeing that output?

hasty acorn
#

logs

queen meteor
#

hmm....well, good try! good luck with the python_script then! 😂

hasty acorn
#

2020-03-01 14:03:35 DEBUG (MainThread) [homeassistant.components.websocket_api.http.connection.140694107990224] Sending {'id': 2, 'type': 'event', 'event': {'event_type': 'call_service', 'data': {'domain': 'zha', 'service': 'issue_zigbee_group_command', 'service_data': {'group': 1, 'cluster_id': 768, 'command': 7, 'args': '- 45940 - 19594 - 5'}}, 'origin': 'LOCAL', 'time_fired': datetime.datetime(2020, 3, 1, 19, 3, 35, 482984, tzinfo=<UTC>), 'context': {'id': '2f8ba74e1f8c42e2b86c16a92681cff3', 'parent_id': None, 'user_id': 'bcd35a1a6e6247958f1571cb62d460ff'}}}

#

nah, i think i am just going to have to have it split out for now with a LOT of redundant code

queen meteor
#

I don't think that will solve the issue. besides what you see in the logs is the json equivalent of generated yaml

hasty acorn
#

nah, it works when split out

#
args:
  - >-
    macro stuff...
      {{ xy[0] }}
    end macro
  {{ call macro }}
  - >-
    macro stuff...
      {{ xy[1] }}
    end macro
  {{ call macro }}
#

works

warm isle
hasty acorn
#

@queen meteor this is a log with the split code:

#

it IS json, but the args are a true list

#

i appreciate the assistance, but i think this is as far as it can go in jinja.

#

BTW, what template editor are you using? the one in hass?

queen meteor
#

yes, I use the one in hass

hasty acorn
#

giving it a go

#

my nuc took a poop, im restarting, itll take a few minutes to get it back up

queen meteor
#

ok.

hasty acorn
#

same...

#
'args': '[45940, 19594, 5]'
queen meteor
#

ha! it is treating it as a string!

hasty acorn
#

yeah, thats been my day thus far

#

the only thing i could figure it make the yaml list manually, and populate the values from the macro

queen meteor
#

yes, it sucks for sure!this is probably the biggest limitation I've seen with jinja so far.

hasty acorn
#

yeah, as ive seen and read, {{}} always returns a string

#

actually i am not sure if the issue is with jinja or yaml

charred dagger
#

Maybe the from_json filter could help you?

#

Though I doubt that in this case..

light flume
#

Anyone know if there's a way to combine these event triggers into one? Have like ~15 different event types.

      - platform: event
        event_type: automatic_update
        event_data:
          type: "notification:hard_brake"
          vehicle:
            id: "C_f0c25633155438cd"
      - platform: event
        event_type: automatic_update
        event_data:
          type: "notification:speeding"
          vehicle:
            id: "C_f0c25633155438cd"
charred haven
#

hmm dont think ive seen any examples of event templates for the trigger itself...what I do know is the trigger template allows you to look at event data

queen meteor
#

@light flume I haven't tried multiple event triggers - it might require you to pass event_data. If it doesn't, you could try with something like this: ```yaml
trigger:

  • platform: event
    event_type: automatic_update
    condition:
  • condition: or
    conditions:
    • condition: template
      value_template: "{{ trigger.event.data.event_data.type == 'notification:hard_brake' }}"
    • condition: template
      value_template: "{{ trigger.event.data.event_data.type == 'notification:speeding' }}"
light flume
#

awesome, thanks guys

pulsar glacier
#

How would I adapt {{ states.light|selectattr("state", "equalto", "on")|list|length }} to exclude any lights where is_deconz_group = true ?

queen meteor
#

You could put a pipe and use reject filter

long basalt
#

What am I doing wrong here?

- platform: rest
  resource: "https://services1.arcgis.com/0MSEUqKaxRlEPj5g/arcgis/rest/services/ncov_cases/FeatureServer/1/query?f=json&where=(Country_Region%3D%27US%27)&outStatistics=%5B%7B%22statisticType%22%3A%22sum%22%2C%22onStatisticField%22%3A%22Confirmed%22%2C%22outStatisticFieldName%22%3A%22Confirmed%22%7D%2C%20%7B%22statisticType%22%3A%22sum%22%2C%22onStatisticField%22%3A%22Deaths%22%2C%22outStatisticFieldName%22%3A%22Deaths%22%7D%2C%20%7B%22statisticType%22%3A%22sum%22%2C%22onStatisticField%22%3A%22Recovered%22%2C%22outStatisticFieldName%22%3A%22Recovered%22%7D%5D"
  name: Corona Virus US
  value_template: "{{ value_json.features[0].attributes.Recovered }}"
  json_attributes_path: "$.features[0].attributes"
  json_attributes:
    - Confirmed
    - Deaths
    - Recovered
#

Gives this error:

Failed config
  sensor.rest: 
    - Invalid config for [sensor.rest]: [json_attributes_path] is an invalid option for [sensor.rest]. Check: sensor.rest->json_attributes_path. (See ?, line ?). 
    - platform: rest
      json_attributes: [source /config/sensor.yaml:15]
charred haven
long basalt
#

That is the post I was looking at @charred haven

#

Not sure how I am goobering it up

charred haven
#

im about ot give it a shot in dev lol

long basalt
#

Was about to go look to see if some features got deprecated in the rest sensor

queen meteor
#

Best way to troubleshoot the rest sensor is to enable debug love, get the actual json returned by the rear sensor, put it in template editor to access corresponding values.

charred haven
#

@long basalt its working fine for me actually...no errors

#
    resource: "https://services1.arcgis.com/0MSEUqKaxRlEPj5g/arcgis/rest/services/ncov_cases/FeatureServer/1/query?f=json&where=(Country_Region%3D%27US%27)&outStatistics=%5B%7B%22statisticType%22%3A%22sum%22%2C%22onStatisticField%22%3A%22Confirmed%22%2C%22outStatisticFieldName%22%3A%22Confirmed%22%7D%2C%20%7B%22statisticType%22%3A%22sum%22%2C%22onStatisticField%22%3A%22Deaths%22%2C%22outStatisticFieldName%22%3A%22Deaths%22%7D%2C%20%7B%22statisticType%22%3A%22sum%22%2C%22onStatisticField%22%3A%22Recovered%22%2C%22outStatisticFieldName%22%3A%22Recovered%22%7D%5D"
    name: Corona Virus US
    value_template: "{{ value_json.features[0].attributes.Recovered }}"
    device_class: timestamp
    json_attributes_path: "$.features[0].attributes"
    json_attributes:
      - Confirmed
      - Deaths
      - Recovered```
#

is taht the same thing lol

long basalt
#

Hmmm. I goober somewhere then

#

Yes

#

I'm on 105.5 still though

charred haven
#

ah im on 0.106.2

#

but i tested in my dev instance which was just synced up with all the latest and greatest changes

charred haven
#

hmm not sure if those sensors are something i want to stare at in my UI 🤣

queen meteor
#

Sadly, you can’t avoid hearing about it no matter where you go these days! You might as well give a big stare and move on 😊

charred haven
#

hahahaha yea for sure its a hot topic anywhere

unborn ore
#

Right lads... I have this, but it's not working. Any ideas?
I can turn the light on and off, but it doesn't change the state of the switch.

#
light:
  - platform: template
    lights:
      bedroom_leds:
        friendly_name: "Bedroom LEDS"
        value_template: "{{states('switch.bedroom_leds')}}"
        turn_on:
          service: switch.turn_on
          data:
            entity_id: switch.bedroom_leds
        turn_off:
          service: switch.turn_off
          data:
            entity_id: switch.bedroom_leds```
long basalt
#

@charred haven Upgrading to 106.2 fixed my rest sensor template

long basalt
#

@charred haven You see 106.3? we were too fast

charred haven
#

oh wow lol

velvet gate
#

Lol

#

Another upgrade? Argh

charred haven
#

funny how they were adding it as we were discussing it

#

@unborn ore try value_template: "{{ is_state('switch.bedroom_leds', 'on') }}"

velvet gate
#

Wooo

#

Any interesting new things they are adding?

unborn ore
#

Huh, that fixed it @charred haven

#

Thanks mate

#

So the template only accepts true/false, no on/off?

charred haven
#

its easier to do that for switch template and binary sensor templates as its either one or the other

unborn ore
#

Gotcha

long basalt
#

that sensor not looking so good @charred haven -- 100 confirmed, 7 deaths

charred haven
#

@long basalt official integration you mean?

long basalt
#

Our rest one

charred haven
#

ah it seems to be the same data actually i think

long basalt
#

Also did this

aspect_ratio: 0
type: iframe
url: >-
  https://gisanddata.maps.arcgis.com/apps/opsdashboard/index.html#/bda7594740fd40299423467b48e9ecf6
#

and added as a panel

#

(not looking so good from a humanitarian point of view )

charred haven
#

oh yea

amber musk
#

Is it possible to get the current theme name from Jinja2 templating?

amber musk
#

nvm, found the solution myself

#
automation:
  - alias: Register current theme
    initial_state: true
    trigger:
      - platform: event
        event_type: call_service
        event_data:
          domain: frontend
          service: set_theme
    action:
      - service: input_text.set_value
        data_template:
          entity_id: input_text.current_theme
          value: "{{ trigger.event.data.service_data.name }}"
mighty ledge
#

that's a hokey way of doing it

amber musk
#

@mighty ledge the best way would be using only Jinja2 but it's good way too IMO

mighty ledge
#

well it won't work if you have 2 different users with 2 different themes

amber musk
#

users always have backend-selected

#

the server chooses which theme is running

#

if user forces another theme, then this won't work

#

but never happens 🙂

mighty ledge
#

yes but every user on every device on every browser has a different theme

amber musk
#

they can choose different theme, but if it's on backend-selected, then it's all the same

mighty ledge
#

ok, as long as you know that they all cause a set_teme event and 2 different users with different themes will cause that input_text to be out of sync

#

that's all I'm saying. You have 1 event pool going to 1 input_text with multiple users sending events to the single pool

amber musk
#

Yes, I know what you mean. But as I said, all users use backed-selected and they don't mess with that. So it's ok in this case

uneven wigeon
#

can the above/below filed in numeric_state triggers be a template?

#

field*

buoyant pine
#

No, but you could just use a template trigger for that

uneven wigeon
#

yeah will do. cheers mate.

nocturne kiln
#

Hi, I have this template: Emptying though {{ states.sensor.karl_1.attributes.days }} days, but if I want it to say Empting todaaay when state.sensor.karl_1.attributes.days is 0, is that possible?

rugged laurel
#

yes

nocturne kiln
#

Do you mind help me out with such if/else template?

rugged laurel
#

try first

silent barnBOT
nocturne kiln
#

I'll check. Thanks!

#
{% if is_state_attr('sensor.karl_1', 'days', 0) %}
  Emptying todaaaaay
{% else %}
  Emptying though {{ states.sensor.karl_1.attributes.days }} days
{% endif %}

Think I solved it. Thanks @rugged laurel 🙂

rugged laurel
#

That works 👍

#

no

#

is_state is for states, you want an attribute

nocturne kiln
#

uhm, yes. I keep on reading 🙂

#

That one above should work then.

rugged laurel
#

yes

nocturne kiln
#

Thanks!

wary cipher
buoyant pine
#

IIRC the UI editors can't handle templates currently

wary cipher
#

@buoyant pine Thanks, I couldn't find anything that said that for sure.

buoyant pine
#

Could be wrong though, I don't use the UI editors

inland stag
#

Hello, I am trying to get the location of the calendar's next event

#

I have this right now: {{ state_attr('calendar.christoph', 'location') }}

#

but this template sensor always returns none, even though the next event has a location set

#

the calendar-card shows the events with their location

#

if I check the calendar entity in Dev Tools, I see that it only has the attribute offset_reached: false

#

but how does the calendar-card see the next events' location then?

inland stag
nimble marsh
#

@inland stag Mine worked here, can you try testing with Developer Tools > Services?
Service: persistent_notification.create
Service Data:

title: Location
message: "{{ state_attr('calendar.family', 'location') }}"
#

And have you validated that the calendar does in fact have a location attribute? (check it in Developer Tools > States)

still harbor
#

Hi guys, is there a template I can use to retrieve the length of time an entity has been at it's current state? My example is a notification sent via the alert integration, every 30 minutes my garage door is open it sends a notification that I'd like to read "The garage door has been open for 'x' minutes" (or convert to hours if the number gets big enough). Thanks in advance guys!

charred haven
#

@still harbor you can use teh last_changed attribute to get a timestamp

still harbor
#

Thanks @charred haven! Is it {{ state_attr('cover.garage_door', 'last_changed') }} ? Because it's returning "none" for me

charred haven
#

@still harbor try like {{ as_timestamp(states.cover.garage_door.last_changed) }}

still harbor
#

Yes! And I can use relative_time as a human readable rounded number, which is exactly what I'm looking for! Thanks @charred haven

charred haven
#

np!

thorny snow
#

Can I also template with incoming json data wich isnt yet a sensor?
I get a object with the value false I try to disable the the info as long as it is false

{% set my_test_json = {"first":3,"seccond":6,"third":9,"fourth":12,"trafficjam":false,"trafficjam_1":false} %}
____
The thing is is {{ my_test_json.first }} {{ my_test_json.trafficjam }}. # output: " 3 false.
___ # try to accive
{% if is_state('my_test_json.trafficjam_0', 'false') %}
''
{%- else -%}
'STAU'
{%- endif %}
buoyant pine
thorny snow
#

thanks - but I cant find something outside of the scope of filtering or mathematical operations in this section 😕

HA!
{{ value_json.trafficjam | replace(false, "")| replace(true, "STAU")}}

ancient lynx
#

Is there a way to have regex remove double quotes without YAML freaking out?

#

I have this:
"{{ states('sensor.mi_drive_rest')|regex_replace(find='.*</div>', replace='')|regex_replace(find=',', replace='')|striptags|regex_replace(find='[[\"\]]') }}"

#

Which works perfectly fine in the template editor, but throws a bunch of errors in VSCode and YAMLLint.

#

I get unknown escape sequence on the line above that one, and missed comma flow between collection entries on the line the template is on.

#

Plus unexpected end of the stream within a double quoted scalar further down the file.

dreamy sinew
#

Code editor probably isn't aware of jinja2

royal raven
#

Hey folks, I have an integration which returns a sensor. {{ states.sensor.dackeri.attributes }} in the template editor in developer tools returns a bunch of attributes which is great. One of them is "tier" and its value is "Gold", why might the below yaml for a template not work?

  - platform: template
    sensors:
        tier:
            friendly_name: "Tier"
            value_template: "{{ state_attr('sensor.dackeri','tier') }}"
#

config checker returns:

Error loading /config/configuration.yaml: while scanning a simple key
in "/config/configuration.yaml", line 58, column 1
could not find expected ':'
in "/config/configuration.yaml", line 59, column 13

silent barnBOT
#

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

```
code here
```
Watch the animated gif here: https://bit.ly/2GbfRJE
DO NOT repeat posts. Please edit previously posted message, here is how -> https://bit.ly/2qOOf1G

dreamy sinew
#

Seems fine, is that the line number it's complaining about?

royal raven
#

yup

#

line 58 is the first line of the next YAML stanza

buoyant pine
#

Let's see the surrounding code

silent barnBOT
buoyant pine
#

Also common convention for indentation is 2 spaces. If you're using 4 it's fine as long as you're consistent

#

YAML != Python 😛

dreamy sinew
#
sensors:
  - platform: template
    sensors:
        downstairs_avg_temp:
          friendly_name: "Downstairs Average Temp"
          device_class: 'temperature'
          unit_of_measurement: '°F'
          value_template: >-
            {% set sensors = [
                states('sensor.living_room_temperature')|float,
                states('sensor.office_temperature')|float, 
                states('sensor.thermostat_temperature')|float 
              ]
            %}
            {{(sensors|sum / sensors|length)|round(1)}}```
#

that's one of mine

royal raven
#

YAML != Python 😛
@buoyant pine They're tabs, but they render differently in discord versus the config which does them as 2.

buoyant pine
#

😱

dreamy sinew
#

oof, that's a whole 'nuther flame war

buoyant pine
#

You should be using an editor with soft tabs

dreamy sinew
#

where the correct answer is "tab inputs <n> spaces"

buoyant pine
#

An actual tab character will cause issues

royal raven
#

ah I figured it out

#

I had stuffed up the next stanza

buoyant pine
#

That's why I asked to see the surrounding code 😛

royal raven
#

I was convinced I finally had the syntax correct and when it didn't work I came crying in here but it was just that I had stuffed the next line

#

That's why I asked to see the surrounding code 😛
@buoyant pine Yeah and the polite thing would've been to show it but it gave me the idea to syntax check it before I embarrassed myself (which I have now done by being so honest but whatevs)

dreamy sinew
#

lol the way to enlightenment is through pain

#
  • wayne gretzky
  • michael scott
buoyant pine
#

@royal raven oh you're good, just wanted to say I KNEW IT GWcorbinHolyFuck

waxen rune
#

I have a template sensor that combines two thermometers to get an average. It seems to work fine - except there's something strange with how it reports last_updated / last_changed.
https://imgur.com/a/9RW5WkT shows the temperature was changed 10 minutes ago.

But according to "{{ as_timestamp(strptime(states.sensor.template_temperature_floor_1.last_changed | string | truncate(19,True,'',0),'%Y-%m-%d %H:%M:%S:%f')) | timestamp_custom('%Y-%m-%d %H:%M:%S') }}" it was changed "2020-03-05 12:34:01" which is 75 minutes ago.

I get the same result from {{{ states.sensor.template_temperature_floor_1.last_changed }} and {{ states.sensor.template_temperature_floor_1.last_updated }}

Any suggestions why it doesn't update its last_updated attribute?

ancient lynx
#

@dreamy sinew ha core check doesn't pass either, tho. So it seems to not just be VSC.

ancient lynx
#

So there is no way to match double quotes in regex then.

dreamy sinew
#

might be able to use something like [[:punct:]]

buoyant pine
#

[[👊]]

nimble marsh
#

Is there any benefit to using states['domain.entity_id'].state over states('domain.entity_id') ? Is it just leftover from old ways of doing things?

#

I've got mostly the latter, but a few of the former for some of my older stuff, and about to go through and standardize.

buoyant pine
#

The second is better. Prevents errors when the entity isn't ready/available

nimble marsh
#

awesome. i read that, but wondered if there was any reason to use the old nowadays. i've been posting the same other places ("don't use that") probably something along the lines of "it'll be deprecated soon™️" 🙂

buoyant pine
wicked parrot
#

I've got a 3D printer hooked up into a TP-Link Kasa power switch to monitor power usage. I just called light.turn_off as I was writing an automation for my hue lights. As it turns out it also shut off my printer mid print.

#

Sad panda.

#

How can I tell HA not to treat this device as a light (switch)?

bitter atlas
wicked parrot
#

Ah!

#

Thank you.

wicked parrot
#

@bitter atlas Related question. I've got a pair of TP-Link Kasa dimmer switches hooked up to fans (basically remotely controller the fan speeds). Is there a way to have those not be related to the grouping of lights?

#

Or anyone?

arctic sorrel
#

Don't put them in the group of lights 🤷

bitter atlas
#

@wicked parrot not sure it will work putting smart switch hosts under the switch in the config but you could try it.

wicked parrot
#

@arctic sorrel Can I remove lights from entity_id: all for light.turn_off?

arctic sorrel
#

No, you'd said group... so I assumed you were using groups 🤷

#

The answer there is - don't do that 😛

#

Maybe use areas instead?

wicked parrot
#

Ok.

arctic sorrel
#

Or create your own group

wicked parrot
#

So there isn't a way to tell HA to consider a device something other than what it sees it initially as?

#

And I know about templating, but my understanding is that the original device still exists?

arctic sorrel
#

No, you can't pull a Jedi mind trick on HA like that

wicked parrot
#

Womp womp.

#

@bitter atlas Telling HA to treat the dimmers as a switch, sadly prevents me from changing the brightness.

#

Just FYI.

bitter atlas
#

well obviously

wicked parrot
#

Now I just wish I understood templating enough to get these dimmer switches to also look like fans in HA.

arctic sorrel
#

You can just use customizing to change the icon

wicked parrot
#

@arctic sorrel Thanks!

#

How would I take the state from a binary sensor and have that get synced into the state for a camera?

arctic sorrel
#

Not sure what you mean by that - you want the state of the camera to match the sensor?

ancient lynx
#

might be able to use something like [[:punct:]]
@dreamy sinew Hmmm. That didn't work either.

#

I think I'm going to have to abandon it. Bummer.

#

Unless there's a better way to take ["<div class='dmsMessage'>TRAVEL TIME TO<br> I-94 9 MI 8 MIN</div><div class='dmstimeStamp'>Mar 6 2020, 10:31 AM</div>","EB I-696 @ Couzens"] and break it down to the Message div (TRAVEL TIME TO<br> I-94 9 MI 8 MIN) and the location div (EB I-696 @ Couzens).

dreamy sinew
#

@ancient lynx {% set raw_string = ["<div class='dmsMessage'>TRAVEL TIME TO<br> I-94 9 MI 8 MIN</div><div class='dmstimeStamp'>Mar 6 2020, 10:31 AM</div>","EB I-696 @ Couzens"] %} {% set regex_search_string = "dmsMessage..(.*)<.*dmstimeStamp..(.*)<" %} {{ raw_string[0]|regex_findall_index(find=regex_search_string, index=0) }}

ancient lynx
#

@dreamy sinew Looking more for like this.

#

Ugh, can't import my photos here.

silent barnBOT
#

Please use imgur or other image sharing web sites, and share the link here.

arctic sorrel
#

Because too many people think code should be posted as a screenshot

dreamy sinew
#

i bent the rules for a "show your work" situation

dreamy sinew
#

please share all the code and the expected output as text, i can try to replicate

#

and if you can send the raw sensor output too

#

just dump it all in hastebin or something

ancient lynx
dreamy sinew
#

@ancient lynx try this:

{{ states('sensor.mi_drive_rest')|regex_findall_index(find='dmsMessage..(.*)<\/div><', index=0)|regex_replace(find='<br>', replace='\n')|striptags|title }}

Friendly Name:
{{ states('sensor.mi_drive_rest').split(',')[-1][0:-2] }}```
wicked parrot
#

Ok, I have a binary sensor (curl command setting an on/off state). How can I have that state also be applied to another device like a camera?

dreamy sinew
#

?

buoyant pine
arctic sorrel
#

You can't, not really

ancient lynx
#

@dreamy sinew Wow. Much simpler than my solution.

#

Value came out perfect, freindly name just has one leading ".

#

Could I do a regex that removes the first character bs searching for a " specifically?

dreamy sinew
#

do [1:-2] then

wicked parrot
#

Hurm.

ancient lynx
#

@dreamy sinew Got it!! Thanks for your help!

wicked parrot
#

I have a pair of Wyze cameras that I'm piping into HA through platform: ffmpeg, however the state for them is always idle. I want to derive the state from a different sensor.

#

i.e. running curl to see if the stream is up or not.

wicked parrot
#

Does that make sense?

arctic sorrel
#

Yes, but I don't see any way to do that

buoyant pine
#

You could just make a command line analog/binary sensor

whole oracle
#

sorry should have posted here first how do I use this message to show just the time is returned?

{
  "title": "Event Ghost Fired",
   "message": "{{ states.sensor.time }}"
}

{
"title": "Event Ghost Fired",
"message": "<template state sensor.time=18:56; friendly_name=System Time, icon=mdi:clock, haaska_hidden=True, homebridge_hidden=True, package=system @ 2020-03-06T18:56:01.012457-05:00>"
}

#
{
  "title": "Event Ghost Fired",
   "message": "<template state sensor.time=18:56; friendly_name=System Time, icon=mdi:clock, haaska_hidden=True, homebridge_hidden=True, package=system @ 2020-03-06T18:56:01.012457-05:00>"
}
queen meteor
#

@whole oracle ```
"message": "{{ states('sensor.time') }}"

whole oracle
#

@queen meteor thank you

patent sparrow
#

Can I set the Theme of a Card via Templating?

dreamy sinew
knotty berry
#

Hello, I keep getting this error: Invalid config for [script]: invalid template (TemplateSyntaxError: unexpected char '‘' at 3) for dictionary value @ data['script']['good_morning']['sequence'][0]['data_template']['message']. Got None. (See /config/configuration.yaml, line 156). Please check the docs at https://home-assistant.io/integrations/script/

#

This is the code: good_morning: alias: Godmorgonmeddelande sequence: data_template: language: sv message: >- {{[‘‘Godmorgon!’’, ‘‘Dags att vakna!’’, ‘‘Nu är det dags att vakna!’’, ‘‘Upp och hoppa!’’] | random }}. Klockan är{{states(‘‘sensor.alarm_clock_time’’)}}. Just nu är det {{states(‘‘sensor.smhi_home’’)}}. Temperaturen utomhus är {{state_attr(‘‘sensor.smhi_home’’, ‘‘temperature’’)}}grader Celsius. Todays high will reach {{state(‘‘sensor.smhi_home’’)}}degrees Celsius. Ha en underbar dag! entity_id: media_player.john_sonos service: tts.google_say

#

I've tried changing the order and type of quotes in a lot of different ways but i can't seem to find what the error is.

buoyant pine
#

You've got what are called smart quotes in there (the curly ones) so whatever editor you're using is adding them. Are you using a text editor?

knotty berry
#

Actually just the file editor addon in hassio. I've copied the format of the template from a snipp of code I got on the forums, so my editor isn't adding them there.

rugged laurel
#

Copy from the forum (if unformated there) will add those

knotty berry
#

Ok, so if I got it right I need to change them to normal double qoutes?

merry ravine
#

how can you do multiline stuff in jinja? every example i find online has {% %} around every line, but that seems a little rediculous when doing something like this:

    {% for mower in mowers %}
    {%      set gps = state_attr('device_tracker.automower_' + mower,'latitude')|string + "," + state_attr('device_tracker.automower_' + mower,'longitude')|string %}
    {%      set status = state_attr('device_tracker.automower_' + mower,'status')|lower %}
    {%      set label = state_attr('device_tracker.automower_' + mower,'friendly_name')[0]|upper %}
    {%      set color = 'green' %}
    {%      if status in colors %}
    {%        set color = colors[status] %}
    {%      endif %}
    {%      set image_url.value = image_url.value + "&markers=color:" + color + "%7Clabel:" + "" + "%7C" + gps %}
    {% endfor %}
arctic sorrel
#

Well, that's right, even if your formatting is odd

merry ravine
#

just seems like there should be an easier way of doing that...there's no "output" anywhere in that loop, i'm just preparing a variable for output later

#

and if it's odd...its the first jinja code i've written....I typically deal with c#

arctic sorrel
#

In HA the whole point is that you're using Jinja to output text, so 🤷

merry ravine
#

i do output text later on..

#

i'm building an image path with dynamic information...

{{ image_url.value }}&center=33.252043,-96.527017

i mean, in the example earlier, I could have just output it directly there ...but it still doesn't change the fact that i had 7 lines of code above it calculating what I was going to output

arctic sorrel
#

🤷 That's the way it is

merry ravine
#

k, then i'm not going to f with templates for my other issue, i'll just code an appdaemon app....more simple I think

queen meteor
#

@merry ravine you are setting a value in a loop. Loops won’t maintain state. You need to use namespaces.

merry ravine
#

@queen meteor i'm not having a problem with it..the code i linked was for example only, it works just fine

queen meteor
#

Ok... 👍

still harbor
#

Hi guys I'm trying to create a binary sensor that evaluates as true when the following is true... A cover is open, a binary sensor has not changed for 30 seconds, and three separate binary sensors have not changed to on for two minutes... Hope you guys can help, thanks!

queen meteor
#

@still harbor you need to investigate into template sensor.

still harbor
#

@queen meteor yea I've got tons of them but this one is beyond me. Mostly due to having two device types and also not knowing how to write "hasn't changed states for x time or hasn't changed to a specific state for x time"

charred haven
#

i need to get better at reading timestamps in templates

agile spear
#

I am really not getting the templates through my brain

#

Can someone please show me how to create a NAND logic for two states?

#

I'm trying to automate with zones

queen meteor
#

@agile spear still struggling with the the above use case? Need hand?

agile spear
#

{{ not (is_state("person.me","Home") and is_state("person.wife","Home")) }} is not working and I feel like I am fatally misunderstanding the templating syntax

queen meteor
#

are you aware of template editor?

#

are you using the UI to write this code or manually editing yaml code?

agile spear
#

Yes, but it's hard to use on mobile

queen meteor
#

painful on mobiles for sure... I wouldn't do it on mobiles

agile spear
#

Both, through the automation syntax

queen meteor
#

ok - what does the template editor give for the code above?

agile spear
#

Let me try to copy/paste into it

#

Alright, fine, I'll pull out the dang laptop

#

Hrm

#

so {{ is_state("person.me","Home") and is_state("person.wife","Home") }} is showing as False even though we are both home...

#

I think it's actually working mostly correctly and I just have a typo

#

Dang it

#

turns out it was home not Home

#

Whelp, thanks for the help ayway @queen meteor, you did end up getting me there!

queen meteor
#

@agile spear did you figure out with checking time thingy?

agile spear
#

time thingy?

#

It was a zone state, not time that I was dealing with 🙂

queen meteor
#

" A cover is open, a binary sensor has not changed for 30 seconds, and three separate binary sensors have not changed to on for two minutes... Hope you guys can help, thanks!"

#

☝️ that's the one I'm talking about

agile spear
#

Ah, that was @still harbor, not me! lol

queen meteor
#

@agile spear sorry! got confused. You both have red and black icons, didn't pay much attention 😂

#

@still harbor you can do something like ```
{{ (now() - states.switch.kitchen.last_updated).total_seconds() > 60 }}

agile spear
#

Hahaha not a problem! I figured that might be it

still harbor
#

lol wow! So easy! What about determining if a sensor has been changed to a specific state for a certain amount of time?

silent barnBOT
lapis shuttle
#

Hi, im trying to make an automation with template but seems to making something wrong with my template :P

Basically i need to trigger a message when im pressing and receiving the message (11:19:31 MQT: sonoff_bridge/stat/RESULT = {"RfKey16":"Default sent"}) on my sonoff bridge.

#

Here is my automation:

#
  • id: '1583656379474'
    alias: test
    description: ''
    trigger:
    • platform: mqtt
      topic: sonoff_bridge/stat/RESULT
      condition:
    • condition: template
      value_template: '{value_json == "RfKey16": "Default sent"}'
      action:
    • data:
      message: Test1
      service: telegram_bot.send_message
waxen rune
#

I want to run a scheduled MQTT script to 5 different hosts. Can I pass a variable to the script?

Like
script.mqtt_refresh_lovelace wallpanel1
script.mqtt_refresh_lovelace wallpanel2

or create a loop that matches a entity wildcard?
..or something else that avoids creating unique scripts for each device

arctic sorrel
waxen rune
#

I thought I posted in Automations. I searched first and I guess the matches took me here 🙂

lapis shuttle
#

hi i have this output and i want to parse it with json.

#

15:41:25 MQT: sonoff_bridge/stat/RESULT = {"RfKey16":"Default sent"}

#

i tried value_json[0] == '"RfKey16":"Default sent"'

#

but seems to not working

#

not very familiar with json anyway 😛

#

NOTE: the output its not like the
RfReceived":{"Sync":9550,"Low":320,"High":980,"Data":"68DA27","RfKey":"None"}}

#

that i can use value_json.RfReceived.Data == '68DA27'

queen meteor
#

@lapis shuttle what value are you trying to access?

lapis shuttle
#

@queen meteor the RfKey16 for example

#

@queen meteor i want to match this string in order to trigger a notification to know that key 16 is indeed triggered on my sonoff rf bridge

queen meteor
#

Can you post your whole code?

silent barnBOT
lapis shuttle
#

@queen meteor

  • platform: mqtt
    name: 'arm'
    state_topic: 'sonoff_bridge/stat/RESULT'
    value_template: >-
    {% if value_json == '"RfKey16":"Default sent"' %}
    {{'ON'}}
    {% else %}
    {{states('binary_sensor.arm') | upper}}
    {% endif %}
    off_delay: 15
    device_class: motion
silent barnBOT
#

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

```
code here
```
Watch the animated gif here: https://bit.ly/2GbfRJE
DO NOT repeat posts. Please edit previously posted message, here is how -> https://bit.ly/2qOOf1G

queen meteor
#

@lapis shuttle if the message in the topic 'sonoff_bridge/stat/RESULT' is json, you should be comparing with json string.

lapis shuttle
#

@queen meteor the output is
15:41:25 MQT: sonoff_bridge/stat/RESULT = {"RfKey16":"Default sent"}

queen meteor
#

then try value_json |string == '{"RfKey16":"Default sent"}'

#

instead of value_json == '"RfKey16":"Default sent"'

#

Or simply do this ```
{% if "16" in value_json |string %}

#

@lapis shuttle try the last option - much simpler and easier

lapis shuttle
#

@queen meteor the if 16 worked! thanks for your help (im not a json guy indeed :P)

rose reef
#

Can anyone help me get my roomba_battery to show up as proper numeric data so it'll show in a graph, like my phone battery, rather than categorical data?

sensor:
- platform: template
  sensors:
    roomba_status:
        friendly_name: "Roomba Status"
        entity_id: vacuum.roomba
        value_template: "{{ state_attr('vacuum.roomba', 'status') }}"
        icon_template: "mdi:brush"
    roomba_battery:
        friendly_name: "Roomba Battery"
        entity_id: vacuum.roomba
        value_template: "{{ state_attr('vacuum.roomba', 'battery_level') }}"
        icon_template: "{{ state_attr('vacuum.roomba', 'battery_icon')}}"
charred haven
#

@rose reef add device_class: battery

rose reef
#

amazing, thank you

charred haven
#

or you can add unit_of_measurement: %

rose reef
#

perfect!

queen meteor
#

@lapis shuttle that if "16" in value_json |string is a hack... more accurate way of doing it is: {{ 'RfKey16' in value_json |list }}

lapis shuttle
#

@queen meteor thanks you have already solved the issue in automations group 👍

silent barnBOT
elder tartan
#

The state of the entity is 'unknown', so i'm not extracting it correctly.

normal venture
#

Does anyone know how I can template the currently logged in user to show in e.g. a markdown card?

gloomy pulsar
#

Is it possible to store a variable on a Person? Looks like you can set name, device_trackers, image, and link an optional user.

The goal is to do something like this:

  1. Parent 1: bedtime == 10 PM
  2. Child 1: bedtiime == 8 PM

Create an automation which checks every Person's bedtime, then executes a Scene (say turn lights off)

dense topaz
#

High! I'm trying to add 2 vars together, after converting one to gallons - no matter how I put this together - i get "unknown template error"
{{(states('sensor.ro_system_1_liters')| int * 0.2641720524| round(2))}} {{(states('sensor.muh_meter_daily_water'))}}

charred haven
#

@dense topaz are you trying this out in the template editor?

dense topaz
#

yes.

charred haven
#

try to slowly build it out starting with dispalying the state then converting to int etc...

dense topaz
#

ok - I've been toying with it for over an hour. I can get both these number to display as seen above....

#

I try {{(states('sensor.ro_system_1_liters')| int * 0.2641720524| round(2)) + 1}} and that works

#

but when i do:
{{(states('sensor.ro_system_1_liters')| int * 0.2641720524| round(2)) + states('sensor.muh_meter_daily_water') }}

#

I get unknwon template error

charred haven
#

you need to convert the second one to int as well

#

{{(states('sensor.ro_system_1_liters')| int * 0.2641720524| round(2)) + (states('sensor.muh_meter_daily_water') | int) }}

dense topaz
#

boom

#

so intuitive.... NOT

#

lol

charred haven
#

sometimes sensors come in as a string so always good to convert first lol

dense topaz
#

Thank you! head banging over! wahoo!

#

the error message was so discriptive.... lol

buoyant pine
#

States are always stored as a string @dense topaz @charred haven

dense topaz
#

Ooohhhhhhh thank you 🙂

gloomy pulsar
#

Anyway to understand why this isn't evaluating as true?

Trying to follow the automation example in which lights are turn off a specific time (by way of input_datetime.household_bedtime) outlined here: https://www.home-assistant.io/integrations/input_datetime/

Here's the template:
{{ states('sensor.time') == (state_attr('input_datetime.household_bedtime', 'timestamp') | int | timestamp_custom('%H:%M', True)) }}

#

sensor.time is returning in %H:%S, and I'm formatting input_datetime.household_bedtime to the same...

queen meteor
#

Have you tried in the template editor?

#

You can test individual pieces of code - easy way to debug

proud cradle
#
  action:
    - service: input_boolean.toggle
      data:
        entity_id: input_boolean.wakeup_active
    - service: script.sonos_say
      data_template:
        where: bedroom
        volume: 0.06
        message: 'Wakeup clock {{ states("input_boolean.wakeup_active") }}.'

This toggles the input_boolean but the template always returns ON, if I run the same template manually both on and off is returned accordingly.
What's wrong?

dreamy sinew
#

Might be a race condition?

uneven wigeon
#

can you use templates for the offset value in triggers for the sun platform? i.e. use an input number to set the offset?

jaunty harbor
#

Counting the number of persons at home, could that be done with a template or would I need a script?

jaunty harbor
#
{# Set initial variable #}
{% set count = namespace(value=0) %}
{# For loop #}
{% for state in states.person %}
  {% if state.state == "not_home" %}
    {{ state.name }}
    {% set count.value = count.value + 1 %}
  {% endif %}
{% endfor %}
{# Print result #}
The number of people is {{ count.value }}.
#

That should work?

rugged laurel
#

Yeah, but there is a better way.
If you ask again in about 6h our template experts should be awake

jaunty citrus
#

Hey guys - is there any way to capture the "last triggered" time of a motion sensor? I have a cheap IKEA motion sensor and would like to be able to display "last seen" time in a badge...

jaunty harbor
#

@jaunty citrus use a template sensor with value states.binary_sensor.ikea_motion.last_updated or last_changed

jaunty citrus
#

@jaunty harbor does this work even if neither "last_updated" nor "last_changed" appear as attribute in the "States" list?

jaunty harbor
jaunty citrus
#

ah, okay

jaunty citrus
#

Hmmm... Looks like this is indeed the way to go, however, both last_udpated and last_changed show the last HA start... is there any way to get to the "last time sensor had value X" point in time?

long basalt
#

@jaunty citrus stuff it in a input text?

rugged laurel
#
{{ dict((states.person)|groupby('state'))['not_home']|count }}

@jaunty harbor ☝️

jaunty harbor
#

Damn that's short 😮

rugged laurel
#

That's what she said

queen meteor
#

🤣

jaunty citrus
#

@long basalt what do you mean by "stuff it in an input text"?

long basalt
#

Write an automation to save it to a input_text

jaunty citrus
#

okay, I hoped there was some way to retrieve the last point in time state was "detected"...

#

Thanks, will give that a try.

jaunty harbor
#

@rugged laurel Did you make it even smaller and dropped some list filters?

rugged laurel
#

yeah, she said it was too big 😦

queen meteor
#

And you took her word for it?

rugged laurel
#

I had a choice? 🤔

arctic sorrel
#

There's always a choice.

The question is whether it's a wise one...

sharp mirage
#

I am trying to create a sensor indicating if a script has been run with the last 7200 seconds

#

I am trying this: {{ (now() - datetime.datetime.strptime(script.1582059418798.last_updated, '%Y-%m-%dT%H:%M:%S%z')).total_seconds() < 7200 }}"

sharp mirage
#

thank you @arctic sorrel

arctic sorrel
#

That template will update when the entities in it update, so when the script runs...

jaunty harbor
#

Thanks again Ludeeus! Playing with the Template Dev Tool and it's just awesome.

#

I was going with {{ states.person|selectattr("state","equalto","not_home")|list|count }} but that's 11 characters longer than yours.

#

Now only need to alter this stuff to get a list of people at home (comma-seperated).

rugged laurel
#

map(attribute='name')|list|join(', ') instead of the count in my example

jaunty harbor
#

Or join(', ',attribute='name') instead of count, 10 characters less (and only a single filter).

#

How can I actually know which attribute it is? I was going with friendly_name but that's undefined

rugged laurel
#

Look at the state object

jaunty harbor
#

<template state person.jorim_tielemans=not_home; editable=True, id=jorim_tielemans, latitude=52.9303699, longitude=7.407744, gps_accuracy=15, source=device_tracker.fig_lx1, user_id=b4mazi7skzr4dvjpe38olxuum8fx9hlv, friendly_name=Jorim Tielemans, icon=mdi:chess-queen @ 2020-03-11T07:22:22.647331+00:00>

#

D'oh, mixing up with attributes again.

#

HA attributes I mean 🤦

#

attribute='name' == attribute='attributes.friendly_name'

rugged laurel
#

Yes, but if that is None, it fall backs to entity_id

ebon yoke
#

hi guys! i want to ingest some json data from a web page into h-a

#

that page

#

@arctic sorrel in #integrations-archived suggested to import the totals into a state and the rest as attributes, but i don't know how to do that yet

#

i am using the sensor platform rest

jaunty citrus
#

@long basalt in case you're interested... I ended up accessing the "states" table in the HA database by the "sql" sensor platform. This allows mor eprecise and flexible selection, and does not require any additional data to be stored.

long basalt
#

Nice @jaunty citrus -- You are doing that all with the native automation engine? Or triggering your SQL script another method? I use Node-RED and I'm in the process of moving my sensors that I want the data/time to persist past HA restart into the native NR sensor -- It also has a built in history function to access past states

jaunty citrus
#

Nah, I just needed a sensor showing when the last - real - motion was triggered on that sensor. So a "select max(created) from states where entity_id ='xxx' and state = 'on'" gives me exactly the data I need.

ebon yoke
#

i want to get values through the template sensor platform.. but some of the values are not available yet, meaning it should be "unavailable".. is it possible to set these values to 0?

#

i tried value_template '{{ states.sensor.XXXXX | round(0) }}'

#

but i still get unavailable out

dreamy sinew
#
{% set value = states('sensor.whatever') %}
{{ value|float|round() if value != "unavailable" else 0 }}
ebon yoke
#

@dreamy sinew is this inside the template sensor?

long basalt
#

Yes

ebon yoke
#

hm.. now i got "Unknown" instead of "Unavailable"

lusty forge
#

Something like {{ states('sensor.whatever') if states('sensor.whatever')|str()!="unavailable" else 0}} ?

#

It may need extra parenthesis

#

Also, I'm sure it was answered a lot but, what would be the simplest way to get the result of a service call from a template ? Do I need to do a dummy sensor for that ?

ebon yoke
#
{% set value = states('sensor.whatever') %}
{{ value if str(value) != "unavailable" else 0 }}
#

will that work?

lusty forge
#

That's the spirit

dreamy sinew
#

you don't need to str(value) its already a str

ebon yoke
#

then why isn't it working?

#

i'm getting unknown instead of 0

lusty forge
#

I didn't know that one

#

What's the value of {{ value != "unavailable" }} ?

#

Maybe a case issue ?

ebon yoke
#

Error rendering template: UndefinedError: 'dict object' has no attribute 'Test'

dreamy sinew
#

ah, because states() is returning unknown

ebon yoke
#

that's what i'm getting when i'm running this in the template editor

dreamy sinew
#
{{ value|float|round if value not in ['unknown', 'unavailable'] else 0 }}```
#

you can test all of this in the template tester

ebon yoke
#

i want to accumulate together a bunch of template sensors.. can this be done?

#

accumulate meaning that i want to add up all the ints from the individual (template) sensors into one common group sensor

arctic sorrel
#

With another template sensor, sure

ebon yoke
#

how would that look?

arctic sorrel
#
{{ states('sensor.first')|int + states('sensor.second')|int + ... }}
ebon yoke
#

is it possible with some kind of autosum against a group?

arctic sorrel
#

Not that I know of, but others may have a way

ebon yoke
#

what is the difference between {{ and {% ?

queen meteor
#

First one for condition/expression evaluation and the other for everything else.

ebon yoke
#

ok

#

and how do i create multi-line template sensors?

arctic sorrel
rancid elm
#

Hey guys, I'm trying to update one of my template sensors whenever one of my media_players changes.. This is what I came up with:

entity_id: >
        [{{ states.media_player|map(attribute='entity_id')|join(',') }}]

Unfortunately it doesn't work and I cannot understand why, in the Dev Tools -> Template it looks fine

arctic sorrel
#

The template sensor will only update when one of the listed entities updates

#

HA will try to identify and extract the relevant entities, but in your case it has nothing to work with, so you have to tell it

rancid elm
#

Currently I don't have any entity_id set which makes it not update. I'm trying to generate a list automatically.. Is that possible or do I have to write them all manually?

arctic sorrel
#

Not possible there, that won't accept a template

#

If you look at the link, you'll see it takes (string | list)

#

Not (template)

rancid elm
#

The full sensor is like this:

media_players_active:
      entity_id: >
        [{{ states.media_player|map(attribute='entity_id')|join(',') }}]
      value_template: '{{ (states.media_player|selectattr("state", "eq", "playing")|list|length + states.media_player|selectattr("state", "eq", "paused")|list|length) > 0 }}'
#

Do I have to use entity_id or should it automatically detect it?

arctic sorrel
#

It can't detect it, because you don't have any actual entities listed

#

So yes, if you want it to update you have two choices:

  1. Force update from an automation - brute force, but it'll work
  2. List the entities - efficient, but takes you a moment or two to list them
rancid elm
#

Ah okay, it doesn't detect the ones from the template?

arctic sorrel
#

There's no entities in the template

#
      value_template: '{{ (states.media_player|selectattr("state", "eq", "playing")|list|length + states.media_player|selectattr("state", "eq", "paused")|list|length) > 0 }}'
``` Please point out any entity ID in that string 😉
rancid elm
#

Damn I thought totally wrong.. Sorry 😅

arctic sorrel
#

No worries

rancid elm
#

But there's no way to just say
entity_id: (list of all media_player entities), like a domain?

arctic sorrel
#

No

#

You can put your template in the Templates screen to get the list out, but that's it

rancid elm
#

I thought it works in the template so it should interpret the template.. Guess I'll have to list them manually :/ Anyway, thanks a lot for helping me out, now I understand why it didn't work

arctic sorrel
#

As I said, look at the link I posted - it tells you what works there, and it doesn't say template 😉

rancid elm
#

I read that, I thought.. "Well, the template puts out a list, so..." 😂

arctic sorrel
#

So close... 😄

rancid elm
#

Just listed them all and.. IT WORKS! Thanks a lot @arctic sorrel

thick cipher
#

hi guys, how i can get this value on template.
[{'name': 'hacs/integration', 'display_name': 'HACS (Home Assistant Community Store)', 'installed version': '0.20.9', 'available version': '0.23.2'}]
i want to get HACS
I stopped here: {{states.sensor.hacs.attributes.repositories
i tried {{states.sensor.hacs.attributes.repositories.display_name}} but no sucess

rugged laurel
queen meteor
#

@thick cipher 👋 long time no see!

merry ravine
#

whats the easiest way to compare the current time to a preset time of day? for example, I want to check if the current time is earlier than say 11pm of that day

#

now().hour < 23 ?

dreamy sinew
#

that would work

nocturne kiln
#

I have a speedtest running on a machine that report the measurements to hass through the web-api to sensors. The sensors dont exist upon startup of hass so when I reboot I got "sensor.download dont exist" in the GUI, so I created a template-sensor with a value_template of a constant (500). Is there a way that instead read out from the history and take the last measurement the sensor had before reboot?

final mulch
#

@pseudo musk 🙂 Here I am 😉

#

sry... didn't know which one would be the best.

#

Just one more thing.. how do I get the 2h20 from my json to here: {% set hours = "2h20".split("h")[0] %}.
So atm it is just '{{ value_json.ProgramEnd.End}}' ... so I think it should be something like {% set hours = value_json.ProgramEnd.End.split("h")[0] %} but I think this is wrong 😦 Because .split is not part of the json string.

pseudo musk
#

if value_json.ProgramEnd.End has the "2h20" like value in it, then yeah that should work

final mulch
#

value_template: '{{ value_json.ProgramEnd.End}}' this results in 2h20 (or whatever time it is at the moment).

So I think I've to use some kind of brackets?

pseudo musk
#

here, try this, slightly cleaner

value_template: >-
  {% set hours, mins = value_json.ProgramEnd.End.split("h") %}
  {% set totalseconds = (hours | int*60*60) + (mins|int*60) %}
  {{ totalseconds }}
final mulch
#

Error rendering template: UndefinedError: 'value_json' is undefined

#

lol

#

I'm idiot

#

give me a second

#

it works!!!!

#

😄

pseudo musk
#

can skip a line like this shrug ```
value_template: >-
{% set hours, mins = value_json.ProgramEnd.End.split("h") %}
{{ (hours | int6060) + (mins|int*60) }}

final mulch
#

this works too.

#

Now I just need to look how I will display the entity... because seconds are not so nice ^^

#

Is there a nice way to show a time entity on lovelace?

charred dagger
#

Time as in timer?

#

Never mind me. I can't raise my eyes more than a single line of text.

pseudo musk
#

this will give you the end time
{{ (now() | as_timestamp() + ((hours | int*60*60) + (mins|int*60))) | timestamp_local }}

final mulch
#

@pseudo musk where can I put that line?

#

as i understand I can put this in just as the last line? 🙂

#

do you have an idea too for that... If the machine isn't running .. the reqeust is empty value_json.ProgramEnd.End. = Unknown
Is there a way to just use another Word/string if this happen?

barren cipher
#

Is there a way to build a binary template sensor around events?

final mulch
#

@pseudo musk got it... with device_class: timestamp on restful sensor.
Not just to find out how to filter if device is not running 😛

pseudo musk
#

@final mulch use an if in the value_template

final mulch
#

yes... I just didn't get how ^^^
But acutally I'm facing another issue -.-

#

@pseudo musk timestamp isn't displayed propper on iOS App 😦

#

i have to use timestamp_custom now it shows the time but wrong -.- (it shows utc instead of utc+01:00)

pseudo musk
#

add , local_time=True) to your timestamp_custom call

#

I mean, it should be doing that already, but idk

final mulch
#

i already tried... but this doesn't help

#

the strange thing is that it does work on Chrome@Win10 but not on iOS

pseudo musk