#templates-archived

1 messages Β· Page 115 of 1

fossil totem
#

so i try to avoid anything fragile like that. my fall-back is to create an input_select w/ C or F or similar

ivory delta
#

Ok

fossil totem
#

As it is I already have an input_select that gets populated with all installed weather. entities, and the user can select from that list. Trying to keep within Home Assistant standards so it will work w/ any installed provider

ivory delta
#

From the discussions I've seen you have already around this project, it sounds like a mammoth undertaking and would be very fragile to any changes in HA.

fossil totem
#

lol, tell me about it

ivory delta
#

I'd even go so far as to suggest that instead of wrapping HA in something else, you'd be better off just making your own system...

fossil totem
#

breaking changes are a constant problem, i've learned strategies to dance around them where possible

ivory delta
#

HA isn't anywhere near the point where you can just plug and play. Attempting to force that square shape into a circle hole is futile.

fossil totem
#

that's part of what i'm working on at the moment, i've hard-coded weather providers but that isn't tenable for long term use. so, better approach is to create a UI element allowing the user to select which installed provider to use

vocal linden
#

I looked where fahrenheit is used. seems that it is used in 3-4 regions in the world, so if you dont care for the few exception outside these zones where you will have mistakes you can get away with 4 ifs

#

so comparisons with latitude and longitude

fossil totem
#

even then that's dicey. my project is primarily targeted at north america due to changing workbox sizes around the world

#

so, if i say "within some radius from a central point in the US", i'll still have some part of canada and mexico being covered as F

#

I'd sooner just give them an input_select, which is probably where I'll need to go w/ this

vocal linden
#

Yeah then there wont be a good solution i think and you have the user to manually select it πŸ’β€β™‚οΈ

fossil totem
#

just wanted to check in here to see if i was missing something obvious. thanks to the both of you for your attention and ideas!

mighty ledge
#

@fossil totem I don't know why you don't just make a custom integration for your hasp project. You keep running into issues that can be solved with access to the backend. Make a custom integration via yaml or the UI. The configuration would 'create your plates' like you do with lovelace, instead use the integration. Then you can grab anything you want from every entity willy nilly.

fossil totem
#

probably because i'm dumb and also don't know python at all

#

but your point is well taken

mighty ledge
#

Well, you can't be that dumb because you created the hasp project

#

It's definitely not a short term solution

ivory delta
#

I didn't know Python before I wrote a custom component πŸ€·β€β™‚οΈ

fossil totem
#

well i'll take that as a compliment coming from you my man!

mighty ledge
#

Yeah, the python for a custom component isn't too bad. All the hard stuff is out of the way. Plus you can plagiarize from other integrations. In the end, you'll have a bunch of entities and you can do whatever you want with them

fossil totem
#

that very thought occurred to me last night, i'll have to dig into some examples and take a look at what i'm up against

timid osprey
#

get a linter that screams at you all day

fossil totem
#

my "problem" is that i've been able to push packages + automations + templates pretty damn far, and it's for sure not the way any of that stuff was intended to be used

mighty ledge
#

It would probably remove the complexity of your packages + automations. It might completely remove the need for all of that

fossil totem
#

my original thought was it would allow new users the ability to fully customize everything, after all, it's all just automations and if you use HASS it's not much to ask that you use automations

mighty ledge
#

just food for thought

fossil totem
#

however, with some 4k lines of YAML in the automations as of now... that's become less and less user accessible so the original reason isn't really holding up

timid osprey
#

I feel like most people are already using hacs so the experience would be more enjoyable for them as well not having to see all of the guts

mighty ledge
#

Yeah, you’d be surprised at how few python lines you would need to do them now as well

analog coral
#

Hi everyone, I have a bearded dragon that gets fed every couple days but I always forget when I fed her last. I'd like to be able to log when I last fed her and and have a card on LoveLace that displays when I fed her last. I've messed around with date and input booleans but I can't figure out how to create a script that logs the date and time and applies it to a boolean. Any help is appreciated!!

timid osprey
fossil totem
ivory delta
#

I'd go with a button that sets a datetime to whatever the current time is, and a template binary sensor that's 'true' when the datetime is on the current calendar day.

#

Alternatively, a template sensor that displays 'days since last feed'.

#

@analog coral ☝️

analog coral
#

I’ll give it a try, thank you everyone!!

#

I just set up a toggle boolean, and set that as the only entity in a logbook. Have a button that toggles the boolean and shows me when I last toggled it. Doesn't look pretty, but whatever! Thanks for the tips!

bright quarry
#

@deft timber sorry for my stupidity, i finally got it working. thank you.

how can i use your template as an automation condition? i don't mind using separate automations for each sensor.
https://pastebin.com/9WvgquC4
i tried this, but it didn't work.

#

i also tried the condition's value_template as simply {% if value_json.device == "1P7T3" %}, but that also didn't work. guessing because the one liner doesn't quality as a template.

deft timber
#

I don’t understand what your are doing. You put what should be put in the mqtt sensor (as it was in my code) in condition of an automation...

white adder
#

Hi #templates-archived! I'm sure you can help me, but as a hass newb, I'm not sure if what I'm doing is right. I have a binary sensor and associated automation. The automation has an action with a light.<stuff>. But the thing is, I have some zigbee stuff and some wifi stuff, and the wifi stuff uses switch.<blah> not light.<blah> . Can the service_template include both light.<blah> and switch.<blah>? https://pastebin.com/wZfqidv8 is the code

mighty ledge
#

just call 2 services

#

switch.turn_on and light.turn_on

#

if you're just turning the lights on and don't have extra attributes to pass to the devices, you can use 1 service and call homeassistant.turn_on

#

but, just remember, hass will turn on lights and switches 1 by 1, so calling 2 separate services is almost identical to calling homeassistant.turn_on

white adder
#

Yeah, lights on and off, so I could do homeassistant.turn_{{ trigger.to_state.state }}, put the two different things (light.ewelinkwhatever and switch.whatever) in entity_id, and sorted.

#

Thanks.

mighty ledge
#

if you check out developer tools -> services page, you can see all available services

white adder
#

Very nice. Thanks for that. Re #automations-archived, I'm never sure where to ask. Since it was related to service_template, that's why I came here.

#

I'm 0-4 for guessing the right channel

ancient garnet
ivory pawn
#

Hello All,
I want to create an Automation that has an MQTT Trigger and Light Service Action. What's the best way to construct this so that I can forward selected json mqtt payload values to the light action. I'm not sure how to construct the template and the ha service for the light includes on or off in its name (and not the data section) so how can i overcome this (maybe an if condition). Any ideas?

jagged obsidian
#

neither are we since there are 0 specifics

ivory pawn
#

for example:

    - platform: mqtt
      topic: 'A/B/C/D/X'
  action:
    - service: light.turn_on
      data:
        entity_id: light.X
        brightness: {{ mqtt.topic.payload - value_json:brightness}}
        rgb_color: {{ mqtt.topic.payload - value_json:rgb}}```
the {{}} parts are made up and what i need some help with. thanks!
jagged obsidian
#

its trigger.payload

ivory pawn
#
    - platform: mqtt
      topic: 'A/B/C/D/X'
  action:
    - service: light.turn_on
      data:
        entity_id: light.X
        brightness: {{ trigger.payload - value_json:brightness}}
        rgb_color: {{ trigger.payload - value_json:rgb}}```
... how about the json part ... maybe if someone could edit the rgb part correctly so I can see the format
jagged obsidian
#

its trigger.payload

#

maybe your discord is inserting mqtt everwhere?

signal canopy
#

im very new to templates and had a quick q. If I have a temperature sensor in my template that I am augmenting by adding 3 to it, is there a way to hide the original sensor from showing up in HA? I basically want to pretend the original sensor doesnt exist and use the templated sensor exclusively

jagged obsidian
#

if you hide it from HA you can't get its values so no

signal canopy
#

right

#

so i have to have duplicated sensors for everything i template?

jagged obsidian
#

you need a data origin for the template

#

what kind of sensors do you have that don't support offsets?

signal canopy
#

i have a philips hue motion sensor

#

it's temperature sensor is not as accurate as i would like it to be

#

so i have found a percent offset that ive established by comparing its values to my ecobee thermostat's readings

#

have found it to be about 9% off

#

so i templated the following

#

{{ (states('sensor.bedroom_sensor_2cef6608_temperature') | float * 1.092) | round(1) }}

jagged obsidian
#

what integration is that coming from?

signal canopy
#

zha

jagged obsidian
#

wow zha doesn't have offsetting... thats too bad

signal canopy
#

err it might, im just too noobie

jagged obsidian
#

then you'll have to template each sensor into a new one

signal canopy
#

where would i find it in other integrations? maybe i can try digging around for it

jagged obsidian
#

zigbee2mqtt has support for it

signal canopy
#

any guides or youtube videos you recommend?

#

im early enough in my setup to be able to switch between zha and Z2M

jagged obsidian
#

youtube is just a collection of heavily outdated guides some of which might still work

signal canopy
#

is the offset only numerical or does it support percentages as well for Z2M?

signal canopy
#

hmm tried starting Z2M and it fails, does it need to be exclusively run or can it exist beside zha?

warm dust
#

hey, when it says default: optimistic in the docs for a state template, doesn't that mean that it assumes the last set state?

jagged obsidian
#

it assumes whatever command was sent was successful

warm dust
#

but my entity doesn't have a brightness attribute at all :/

jagged obsidian
#

you're kind of making no sense because noone knows what you're trying to do exactly

warm dust
#

Alright. I have a template light, where I have services that I call when I set the brightness. Problem is, I can't set a specific brightness, only increase or decrease it. So I used an if-statement to check if the current brightness is lower or greater than the new (requested) brightness.
But that comparator doesn't work, because I can't access the current brightness attribute

#

does that make it clearer?

jagged obsidian
#

not at all

warm dust
#

wow. okay, let me try again

ivory delta
#

Forget about whether you can currently see a brightness attribute for the light, since it seems you're wrapping the light in a template light to make it easier to control.

#

The light clearly understands the concept of brightness if you can ask it to increase/decrease it.

#

You just need to set up templated commands that achieve the desired end result.

warm dust
#

But I want to be able to control it from e.g. the Android 11 Power Menu. Lights there have a brightness slider, but no buttons for increasing or decreasing the brightness

#

So I was trying to convert the brightness slider command/value into a increase/decrease command, by comparing the previously set brightness with the new one

#

does that make sense now?

ivory delta
#

The moment you use your template light for the first time, it'll have a 'brightness'. It might be wrong, since it can't know what brightness value the bulb actually has, but it's a point of reference and disproves your argument that you can't do it because it doesn't exist.

#

Your template then has to consider which brightness level has just been requested and perform some operation to reach that new level... sounds like this would be a number of increase/decrease steps, your template needs to figure out this number.

#

No doubt you'll have scripts in the mix too for the repeated calls to increase the brightness level.

#

Honestly though... get a better bulb.

ivory delta
#

That means nothing to me

warm dust
#

it show's the attributes of my light. no brightness there...

#

okay nevermind I figured it out

ivory delta
#

The original light or the template light (for which you've shown no config)?

warm dust
#

the optimistic stuff works, but I have to set the brightness manually for the first time...

warm dust
ivory delta
#

So expose a REST command that allows you to set brightness πŸ€·β€β™‚οΈ

#

You're trying to do this the hard way when easier options likely exist.

warm dust
#

what I did was enter brightness: 50 inside that state attributes box from the screenshot and then everything worked, because now the attribute existed and the if inside the template didn't throw an error anymore

ivory delta
warm dust
warm dust
#

thanks for your help :)

mellow pulsar
#

continuing template discussion started in integrations:
looking at one of the samples in I think i am getting close to it here..

  - platform: template
    sensors:
      ht_uptime:
        friendly_name: 'hasstst uptime'
        value_template: "{{ relative_time(states.binary_sensor.hasstst.last_changed) }}"

#

Am i on the right track here? I'm assuming the above will get uptime as well as down time

#

my yaml coding is very weak! πŸ™‚

vocal linden
#

Using states.xxxx should be avoided. Use instead the template below. The template specific parts you can always test under developer settings --> templates and type it in to see if you get the right output

value_template: >
  {% set state= state_attr('binary_sensor.hasstst','last_changed') %}
  {{ relative_time( states ) }}
#

This is only for the template part, the creating template sensor part i have never done

silent barnBOT
opal dawn
#

Good evening all. Can I ask some question about templates with time formats πŸ˜„ ?

#

I want to set a different time depending the season ( summer , winter ,etc )
This is set time is then used for different triggers.
But I'm not sure if I am doing it the right way. Or if it is even allowed likes this

#
value_template: >-
           {% if is_state('sensor.season', 'spring') or is_state('sensor.season', 'summer') %}
             '07:00:00'
           {% elif is_state('sensor.season', 'autumn')  or is_state('sensor.season', 'winter') %}
             '06:00:00'                                 
          {% endif %}
#

I then want to use that template sensor value in this next template trigger:

                    or 
                    states('sensor.time') == ((state_attr('input_datetime.uv_lamp_uit', 'timestamp') + (15*60)) | int | timestamp_custom('%H:%M', False)) }}"
#

But template trigger doesnt like the template sensor....

#

Remark : The last code snipped is how it currently is functioning
But what I want is that the input_datime.uv_lamp_aan is not static time like I have t now.
But it should vary depending on the season which we re in.

ivory delta
opal dawn
#

I'm more of a pizza man , you ?

#

πŸ˜„

ivory delta
#

Your first template is more complicated than it has to be:

value_template: >-
           {% if is_state('sensor.season', 'spring') or is_state('sensor.season', 'summer') %}
             '07:00:00'
           {% else %}
             '06:00:00'                                 
           {% endif %}```
#

And if you copy/pasted that exactly, there's an error in your indentation on the last line.

opal dawn
#

Agreed !

#

I'll post my template value code which I used to check the outcome for what the calculated time should be

ivory delta
#

First, explain the error. 'it doesn't like it' doesn't help.

opal dawn
#

Yea sorry hehe

#

I tried this

#

Giving me this error back
TypeError: unsupported operand type(s) for -: 'str' and 'int'

ivory delta
#

You're trying to perform integer maths on a string and an integer:
(states('sensor.uv_lamp_aan' ) - (15*60))

#

You need to cast the string to an integer first:
(states('sensor.uv_lamp_aan' ) | int - (15*60))

opal dawn
#

Ok will that still work for the time trigger than?

ivory delta
#

I have no idea... but that's your first issue πŸ˜‰

#

Fix it and see what happens.

opal dawn
#

Returns the value -900

ivory delta
#

Then whatever states('sensor.uv_lamp_aan' ) returns isn't a number. What is it?

opal dawn
#

sensor.uv_lamp_aan 06:00:00

#

I gave it the state 06:00:00 through the template value

ivory delta
#

Yes... you didn't say what that first template sensor was called πŸ™‚

#

It would be easier if you just made that value a number so you don't have to convert to a timestamp.

opal dawn
#

oeps that wasnt in the snipped...

ivory delta
#
           {% if is_state('sensor.season', 'spring') or is_state('sensor.season', 'summer') %}
             25200
           {% else %}
             21600                                 
           {% endif %}```
#

If you don't need to 'read' the value anywhere, just skip a conversion.

opal dawn
#

Not really needed but would be nice and understandable for in the future hehe

#

Also all my other triggers are based on timestamps so I would need to edit all those as wel

#

Instead of only replacing the input_datetime to a different sensor

ivory delta
#

If it's not visible, use the number of seconds. It makes everything else simple.

#

When you want to make it visible, there are other solutions in the UI.

opal dawn
#

Clear

#

Is is possible to put comment text in side template value?

ivory delta
#

Inside? No...

timid osprey
#

wutdefook

ivory delta
#

What are you trying to do?

#

If you mean like this, it would return the 'comment' too:

value_template: >-
           {% if is_state('sensor.season', 'spring') or is_state('sensor.season', 'summer') %}
             25200 # 7 hours
           {% else %}
             21600 # 6 hours                                
           {% endif %}```
opal dawn
#

Hahah

#

It doesnt turn green commented in visual studio code

#
value_template: >-
        {% if is_state('sensor.season', 'spring') or is_state('sensor.season', 'summer') %}
        # 25200 = 07:00 uur
        25200 
ivory delta
#

Yeah, cos it's inside a Jinja template. You're telling it to return all of the stuff between the curly braces.

#

If you want to comment your code, put it on the line before value_template:

opal dawn
#

Ok so your option wont make it a comment part aswel?

#

I see what you are on about , checking it in the template editor returns the commented section aswell.

#

And how to reform this template trigger with the new given sensor which has an INT as value?

"{{ states('sensor.time') == ((state_attr('input_datetime.uv_lamp_aan', 'timestamp') - (15*60)) | int | timestamp_custom('%H:%M', False)) 

I dont have sensor which returns the time in an INT value ?

ivory delta
#

This answer to this part is still the same... you need to cast to an integer:
(state_attr('input_datetime.uv_lamp_aan', 'timestamp') | int

#

Although, you set the template sensor to a number already, so just this:
(states('input_datetime.uv_lamp_aan') | int

opal dawn
#

'input_datetime.uv_lamp_aan' would than be replaced by sensor.uv_lamp_aan' with an INT Vlaue

#

Ok , but looking at my entities the sensor.time returns the actual time in XX:XX
This isnt used by the template part than?

ivory delta
#

Everything in your template is used. Test it in Dev Tools and see what it does.

opal dawn
#
value_template: "{{ states('sensor.time') == ((states('sensor.uv_lamp_aan') | int - (15*60)) | int | timestamp_custom('%H:%M', False)) }}

This returns 'false' at this moment. So I guess that might do the trick

ivory delta
#

It could return false for a number of reasons πŸ˜‰

opal dawn
#

I know hahaha

ivory delta
#

So you want it to equal true when it's exactly 900 seconds before the other sensor?

opal dawn
#

Yea

ivory delta
#

What format is the state for sensor.time?

opal dawn
#

sensor.time 22:19 friendly_name: Time
icon: mdi:clock

ivory delta
#

Yeah, so you'll have to make that into a timestamp too...

opal dawn
#

I think this is the standard time sensor within HA

ivory delta
#

Yes. You're writing a template, you can convert things πŸ˜‰

#

as_timestamp(states('sensor.time'))

opal dawn
#

value_template: {{ as_timestamp(states('sensor.time')) }}

returns : None

#

huh πŸ˜„

ivory delta
#

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

#

I don't do templates.

#

The experts are away.

opal dawn
#

HAhah

mellow pulsar
#

thanks @vocal linden , That example helps alot!

opal dawn
#

@ivory delta think I will be going for a different approach then. Will be using a automation to set the input datetime difderntly

mellow pulsar
#

back again. I currently the following for the value_template:

  - platform: template
    sensors:
      ht_uptime:
        friendly_name: 'hasstst uptime'
        value_template: >
          {% set state= state_attr('binary_sensor.hasstst','last_changed') %}
          {{ relative_time( states ) }}
#

and I am getting a result showing as <template AllStates> . I was hoping I would get a numeric value indicating the uptime. Any ideas?

#

Is it possible that would be the result since binary_sensor.hasstst hasn't changed?

ivory delta
#

You included the typo πŸ˜‰

#

{{ relative_time( state ) }}

#

You're setting a variable called state in the first half.

thorny snow
#

I'm trying to create a rest sensor for the following URL
https://api.coronavirus.data.gov.uk/v1/data?filters=areaType=nation;areaName=england&structure={"date":"date","cumPeopleReceivingFirstDose":"cumPeopleReceivingFirstDose"}

- platform: rest resource: https://api.coronavirus.data.gov.uk/v1/data?filters=areaType=nation;areaName=england&structure={%22date%22:%22date%22,%22cumPeopleReceivingFirstDose%22:%22cumPeopleReceivingFirstDose%22} name: Vaccination Rest Test scan_interval: 3600 json_attributes: - date - cumPeopleReceivingFirstDose value_template: '{{ value_json.cumPeopleReceivingFirstDose }}'

but it's just returning nothing. I'm clearly doing something wrong (never done this before) but not sure what.

glossy viper
#

maybe you can do it via scrape integration to obtain that value

thorny snow
#

maybe, I can try that

thorny snow
#

{{ value_json['data'][0]['cumPeopleReceivingFirstDose'] }}

this returns the figure I'm looking for. woop

glossy viper
#

with rest ?

robust tartan
#

hi guys got sent over by Tinkerer in automation

#

trying to work out a template that fits the following

platform: mqtt
topic: tele/tasmota_765905/SENSOR
payload: '{{ ''"PAJ7620":{"Up"'' in trigger.payload }}'
#

This is the MQTT message

10:11:58 MQT: tele/tasmota_765905/SENSOR = {"Time":"2021-01-11T10:11:58","ANALOG":{"Illuminance":62},"DHT11":{"Temperature":33.5,"Humidity":19.0,"DewPoint":6.7},"PAJ7620":{"Up":2},"TempUnit":"C"}
10:12:02 MQT: tele/tasmota_765905/SENSOR = {"Time":"2021-01-11T10:12:02","ANALOG":{"Illuminance":61},"DHT11":{"Temperature":33.5,"Humidity":19.0,"DewPoint":6.7},"PAJ7620":{"Up":3},"TempUnit":"C"}
#

the PAJ7620 actually counts up with each consecutive swipe in the same direction.

#

at least in the tasmota implementation

jagged obsidian
#

why do you need to keep that number in a sensor?

#

how long does tasmota keep that value?

thorny snow
thorny snow
robust tartan
#

@jagged obsidian until you swipe in a different direction

jagged obsidian
#

might be simpler to build 4 different sensors for each direction

robust tartan
#

also has near and far, and the newer version of the sensor does clockwise and counter clockwise gestures

#

happy to do multiple sensors

#

my issue is how

jagged obsidian
#

regular mqtt sensor with value_template being {{ value_json['PAJ7620'].Up }}

robust tartan
#

ive tried binary and normal sensors but my templating is so bad i wouldn't know if it was my yaml or the json breaking it

#
sensor:
  - platform: mqtt
    state_topic: tele/tasmota_765905/SENSOR
    value_template: {{ value_json['PAJ7620'].Up }}
    ???
glossy viper
#

look at mine

#
  • platform: mqtt
    name: "Energy Today"
    state_topic: "tele/tasmota/SENSOR"
    value_template: '{{ value_json["ENERGY"]["Today"] }}'
    unit_of_measurement: "kWh"
robust tartan
#

it looks to me like value_json would return 1 or 2 etc...

#

so i would have to trigger the automation on a value of 1 or greater?

jagged obsidian
#

i don't know what you're triggering and why

robust tartan
#

oh yes that would help

#

a light\

jagged obsidian
#

if you want to trigger an automation do a simple mqtt trigger

robust tartan
#

swipe up and light turns on

jagged obsidian
#

with the template Tinkerer provided

robust tartan
#

unfortunately neither

platform: mqtt
topic: tele/tasmota_765905/SENSOR
payload: '{{ ''"PAJ7620":{"Up"'' in trigger.payload }}'

or

platform: mqtt
topic: tele/tasmota_765905/SENSOR/PAJ7620
payload: '{{ ''"Up"'' in trigger.payload }}'

seam to work

jagged obsidian
#

yes because that needs to be the condition

robust tartan
#
condition: template
value_template: '{{ '"Up"' in trigger.payload }}'
#
condition: template
value_template: '{{ ''"PAJ7620":{"Up"'' in trigger.payload }}'

Worked. So much thanks.

tardy patio
#

Hello! Can somebody help me with a "thing"? I want to publish a json value that includes 2 sensor values. I am using this in an automation, and things look something like this(part of it)? ```{% if targetTemp1|float > currentTemp1|float and window1 == 'off' %}
{% set result1 = targetTemp1 %}
{% endif %}
{% if result1 == [result1|float, result2|float]|min and result1 < 30 %}
{% set result = "{"ST":"targetTemp1", "CT":"currentTemp1|float"}" %}"
{% else %}
{% set result = 1.0, 20.0 %}
{% endif %}
{% endif %}
{{ result }}

#

I would like the result to be a json value(set result line), BUT at the moment I get exact text in the result, where as I want the values of targetTemp1 and currentTemp1 to be displayed.

#

Everything before this is set correctly, as I can get a string result, but when formatting json value I do not get the desired result.

#

I do not know how to format that line.

ivory delta
#

Just return a dict.

tardy patio
#

me || programming languages.

#

I do not know what you are saying πŸ™‚

#

I see it is a thing in python, I am searching more

#

@ivory delta , if you have a very short example how to return a dictionary, maybe I could edit it to fit my needs. Thank you.

silent barnBOT
#

Generally, don't tag people to ask for help - it comes across as bad manners, you’re demanding somebody answers you. It’s different if you’re thanking somebody, obviously. If you do tag somebody keep it polite and respectful. Remember that everybody is a volunteer, and nobody has to help you, and people may block you.

Similarly, please don’t DM (direct message) people asking for help. It also comes across as demanding, and means that others can’t learn from what you do.

Finally, please keep tagging people in replies to a minimum. That too can become annoying very quickly and should be used only when it's necessary (such as if it's been a long time, or there's multiple conversations going on).

tardy patio
#

ok.

ivory delta
#

I also can't give an example from my phone πŸ˜‰

#

I'm sure someone else can help.

deft timber
#

{% set result = {"ST": 1.0, "CT": 20.0} %} ? πŸ™‚

tardy patio
#

I need it to dislay the valuues foiund in targetTemp1 and currentTemp1

deft timber
#

and {% set result = {"ST":targetTemp1|float , "CT":currentTemp1|float} %}"

tardy patio
#

hmmm wait a sec.

#

Muchas gracias as Mr. Bean would say.

#

πŸ™‚

mellow pulsar
#

greetings! Continuing my exploration of the uptime calculation from yesterday, I am now getting an Unknown value for the uptime. I am guessing it is because there hasn't been a change in the value being checked at HA startup. Here is my current value template:

        value_template: >
          {% set state= state_attr('binary_sensor.hasstst','last_changed') %}
          {{ relative_time( state ) }}

I think what i need is to add an or clause to the set state portion when HA starts up. I am looking at the page https://www.home-assistant.io/integrations/template#startup , and I think this is what is happening to make it an Unknown value. Any ideas?

deft timber
#

you can't access to last_changed using state_attr. You have to use states.binary_sensor.hasstst.last_changed

mellow pulsar
#

according to one of the people yesterday, the state_attr function was the preferable way to get info, and that states should be avoided... Yesterday at 1:13pm this post was added...

Using states.xxxx should be avoided. Use instead the template below. The template specific parts you can always test under developer settings --> templates and type it in to see if you get the right output

value_template: >
{% set state= state_attr('binary_sensor.hasstst','last_changed') %}
{{ relative_time( state ) }}

#

which way is correct? or is both correct?

vocal linden
# mellow pulsar which way is correct? or is both correct?

Navigate to dev tool --> templates and copy the template part (only the ones with the braces) into it (you may have to activate advanced user mode under your profile if you havent yet). There you should see which of both ways are working and you can tinker around it πŸ˜‰ As a frist step you can remove there the relative_time part and see if it prints out an value or it prints "None"

deft timber
#

just test it in the dev tool, and you will be convinced πŸ™‚

vocal linden
#

Oh thought last_changed was an attribute

mellow pulsar
#

interesting.. I have the output from the template editor on develope tools, and i get the following:

{% set state= states.binary_sensor.hasstst.last_changed %}
using the state. version: {{ state }}
uptime value: {{ relative_time( state ) }}
{% set state= state_attr('binary_sensor.hasstst','last_changed') %}
using the state_attr version: {{ state }}
uptime value: {{ relative_time( state ) }}

Results: 

using the state. version: 2021-01-11 12:38:44.276852+00:00
uptime value: 5 hours

using the state_attr version: None
uptime value: None
#

The states. is what gives good data.

#

thanks both of you!

#

I have the states.version now in my configuration.yaml, and the uptime is working correctly

#

I now Understand what the attributes are versus states! ( I think ) . looks like as an example, for thermostats , all of the temperatures, modes, presets, etc are attributes, and states are HA metadata for the object.

dreamy sinew
#

basically entities can have one and only one state. But through attributes, they can expose out other properties that are useful to help expand on that state

mellow pulsar
#

so in the example above, last_changed can only be accessed by using
states.binary_sensor.hasstst.last_changed
maybe it is the word states that is confusing me in lieu of state. Is there only one state, but there can be many states?

#

maybe i am getting wrapped around an axle with terminology?

ivory delta
#

states is the entire states object that HA tracks (all domains). states.binary_sensor would represent the entire domain binary_sensor. states.binary_sensor.hasstst represents a single state object.

#

It's a data structure. Using that dot notation to navigate one level deeper by name just means you're accessing a specific part of that data structure.

#

Think of it like the folders on your hard drive. C:\Users\jr3us\Pictures isn't a place, it's instructions to reach a place.

mellow pulsar
#

ok. I think i understand now. when using states.sensor.entity.field would let you get the individual fields in the states table of the db then for that entity, or is there more?

ivory delta
#

Well... that depends πŸ˜„

#

states.domain.entity_name.state is the state.
states.domain.entity_name.attributes is the attributes (so you can drill one level deeper to get the specific attribute).
Then you have funky stuff like states.domain.entity_name.last_changed which is neither state not attributes.

#

Ah, I lie. The funky stuff is there too.

mellow pulsar
#

πŸ™‚ thanks!

fossil hearth
#

guys am experiencing wired things with templates. please someone explain. i will provide the code and the results. sometimes it is accurate sometimes not.

{{ states|selectattr('entity_id','in',state_attr('group.powder_reffs','entity_id'))|selectattr('state','<','24' )|selectattr('state','!=','unknown' )|list}}

result:

[<template TemplateState(<state sensor.h10=26.57; unit_of_measurement=Β°C, friendly_name=H10 @ 2021-01-12T03:11:56.365172+08:00>)>, <template TemplateState(<state sensor.h11=26.42; unit_of_measurement=Β°C, friendly_name=H11 @ 2021-01-12T03:34:02.633711+08:00>)>, <template TemplateState(<state sensor.h12=26.32; unit_of_measurement=Β°C, friendly_name=H12 @ 2021-01-12T03:04:44.227730+08:00>)>, <template TemplateState(<state sensor.h13=4.6; unit_of_measurement=Β°C, friendly_name=H13 @ 2021-01-12T03:33:56.509913+08:00>)>, <template TemplateState(<state sensor.h16=3.48; unit_of_measurement=Β°C, friendly_name=H16 @ 2021-01-12T03:32:20.079499+08:00>)>, <template TemplateState(<state sensor.h2=3.11; unit_of_measurement=Β°C, friendly_name=H2 @ 2021-01-12T03:33:09.864162+08:00>)>, <template TemplateState(<state sensor.h4=3.14; unit_of_measurement=Β°C, friendly_name=H4 @ 2021-01-12T03:33:42.584087+08:00>)>, <template TemplateState(<state sensor.h8=3.74; unit_of_measurement=Β°C, friendly_name=H8 @ 2021-01-12T03:30:39.266513+08:00>)>, <template TemplateState(<state sensor.h9=26.69; unit_of_measurement=Β°C, friendly_name=H9 @ 2021-01-12T03:14:05.521887+08:00>)>]

as you observe H4, H16, H 2 , H18 and H8, should not be included

ivory delta
#

|selectattr('state','<','24' )
String comparison 🀒

#

You could try this but it might fail because you're not casting the string to a float first:
|selectattr('state','<', 24 )

fossil hearth
#

how can i do that ?

ivory delta
#

Try that one first, then we'll see

fossil hearth
#

it looks the same to me .. wheres the difference ?

ivory delta
#

And string comparisons are dirty. Is 'three' less than 'one'? Is 'tree' less than 'toffee'?

fossil hearth
#

haha

ivory delta
#

They're not the same. '24' isn't 24

fossil hearth
#

oh

#

ok

#

got it

#

tryin now

ivory delta
#

One is a string, one is a number πŸ™‚ And comparing strings is tricky in most languages... they don't work the way a human brain thinks πŸ˜‰

fossil hearth
#

i remember i tried this before

#

TemplateSyntaxError: expected token 'name', got '|' this is what i got

ivory delta
#

Then you have another error somewhere. Share the template that gives that error.

fossil hearth
#

sorry my bad

#

TypeError: '<' not supported between instances of 'str' and 'int'

#

i had an extra |

fossil hearth
ivory delta
fossil hearth
#

we need to specify somehow that it is float ?

ivory delta
#

Somehow πŸ˜„ I don't know how

fossil hearth
#

the error clearly says whats happening lol .. but what to do haha

crisp snow
#

hi, im trying to convert a value in seconds to a day,hours,minutes,seconds value, i've read about relative_time

#

but it's still give me the initial value

#

{{ time }} // output: 781.2417459487915

{{ relative_time(time) }} // still output: 781.2417459487915

fossil hearth
#

@ivory delta is there a way or this is an exploit\ limitation πŸ˜› ?

ivory delta
#

No need to tag. I'm thinking.

fossil hearth
#

haha ok sorry lol

#

you got this man i belive in you πŸ†

crisp snow
#

str with int error, convert the string value to int before doing the math operation

#

{% your_value_str | int %}

ivory delta
#

We know this. Just need to do it inside a Jinja test.

crisp snow
#

ok sorry

dreamy sinew
#

what's the challenge?

ivory delta
#

What information do you want from the template, Shant? A list of entities or just a list of values?

fossil hearth
#

actually i wane count thats my target and i am able i just listed it so we can understand

#

i wanne count number of reffs above 24 for example or below 0

#

etc

ivory delta
#

Just counting should be easier...

fossil hearth
#

yeah but the numbers didnt make sense thats why i listed ..

#

this is how i counted {{ states|selectattr('entity_id','in',state_attr('group.powder_reffs','entity_id'))|selectattr('state','>', '24' ) | list | count}}

ivory delta
#

Ah, I don't understand Jinja docs πŸ˜„

fossil hearth
#

hehe

ivory delta
#

phnx will know this one... how do you perform integer comparison here?
|selectattr('state','>', 24)

#

Well, or float...

dreamy sinew
#

need to map it first i think

ivory delta
#

Ah, I'm getting there now...

#

Something like this?
| map(attribute='state') | int | select('lt', 24)

#

Shant - give this a try, let me know if there are errors:
{{ states|selectattr('entity_id','in',state_attr('group.powder_reffs','entity_id'))| map(attribute='state') | int | select('lt', 24) | list | count}}

fossil hearth
#

ok

crisp snow
#

so relative_time only works with the 'last_updated' value from sensors right ?

dreamy sinew
#

yeah, this is what i have

#
{{ states.sensor|selectattr('entity_id', 'in', sensors)|map(attribute='state')|map('float')|select('gt', 70.0)|list }}```
fossil hearth
#

@ivory delta i did the no errors.. results is 0 . but how can i say greater or less ?

ivory delta
#

That's what this bit is for: | select('lt', 24)

fossil hearth
#

oh ok

ivory delta
#

Ah... you want greater than? | select('gt', 24)

fossil hearth
#

less then greater than

fossil hearth
#

worsk like magic!

#

Thanks you gentlemen you did it

#

❀️

#

@ivory delta @dreamy sinew ❀️ ❀️ ❀️ ❀️ ❀️

ivory delta
#

Didn't need (much) help from phnx in the end πŸ˜„

dreamy sinew
#

too bad you can't do both those maps as one 😦

ivory delta
#

Yeah. I wondered about doing something like selectattr(float('state') > 24) but that's not valid syntax.

#

Would've been so handy to do it in one step.

dreamy sinew
#

but yeah, you were most of the way there

#

map is really handy but i usually forget about it

fossil hearth
#

looks like anything "unknown" its listing it as 0.0

dreamy sinew
#

yup

fossil hearth
#

which will add as a count now i can subtract it ...

dreamy sinew
#

or you can reject it out

fossil hearth
#

but how to exculude it.

dreamy sinew
#

{{ states.sensor|selectattr('entity_id', 'in', sensors)|rejectattr('state', 'in', ['unavailable', 'unknown'])|map(attribute='state')|map('float')|list }}

#

or for slightly less text

fossil hearth
#

cool ! ❀️

#

ima try

#

{{ states|selectattr('entity_id','in',state_attr('group.powder_reffs','entity_id'))|map(attribute='state')|reject('in', ['unavailable', 'unknown'])|map('float')|select('lt', 1 )| list | count}} Working

#

❀️

young jacinth
#

(trigger.entity_id == sensor.harmony_hub and trigger.to_state.state != 'Playstation 4') or (trigger.entity_id == binary_sensor.ps4 and trigger.to_state.state == 'off')
i want to check that expression but get no output
{{ trigger.entity_id }} = sensor.harmony_hub and {{ trigger.to_state.state }} = off

i cant find my fault here
https://pastebin.com/5XdytcZt
this is the full service call. script.ps4_on does work as expected

dreamy sinew
#

mangling the syntax is your problem

young jacinth
#

i dont know if you saw that but the logic expression is in an if condition

ember cliff
#

hi, quick question: what's the syntax for a light template to make multiple service calls? ie:

  lights:
    test_virtual_light:
      turn_on:
        service: #SERVICE CALL 1
        service: #SERVICE CALL 2```
ember cliff
#

nvmd, sorted

serene mortar
#

Also without an else clause, it's possible that you would end up calling "script.ps4_" which I doubt exists in your case?

quiet lagoon
#

Is it possible to create a template/condition that could filter triggers so that only triggers from a certain domain are acted upon? e.g. if trigger domain=device_tracker then true?

young jacinth
deft timber
#

@quiet lagoon are you talking about a state trigger? You could create an event trigger on the event state_change, and in the condition, get the entity that triggers the event and test its domain in a template

glossy viper
#

This template does not listen for any events and will not update automatically.

#

😦

ivory delta
#

You got the value_template wrong, that's not how I said to do it πŸ˜‰

#

'{{ value_json[134].properties }}'

#

It doesn't use JSON Path syntax for value_template, only for json_attributes_path.

#

And remember that properties is still a really big object in your example, so you may still go over the 255 character limit for state.

glossy viper
#

UndefinedError: 'value_json' is undefined

ivory delta
#

Where are you seeing that? It should work fine in the sensor - it won't work in the Dev Tools.

glossy viper
#

aaaa

#

somebody wise said that everytemplate must be checked there :))

ivory delta
#

It's a variable. It's only present inside the sensor itself. Like how trigger is only available inside an automation.

glossy viper
#

oki

ivory delta
glossy viper
#

ok...so in my template i should write down level to properties

#

to not exceed 255

#

although this value i don't like it : "actualizat": "12-01-2021Β oraΒ 14:00",

ivory delta
#

If the sensor represents weather, I would make the state the current weather condition (rain, sun, etc).

#

The attributes give you all the extra detail.

glossy viper
#

u are right. maybe extra details are not needed

#

just wanted to remove external integrations and put a local source for weather

#

but ofr this i must put 10 value templates 😦

ivory delta
#

No...

#

value_template is how it finds the state. The rest should still be okay to find the attributes.

#

But I have to work again now, good luck.

unreal merlin
#

Hello templates folks - what's the best way to debug / test value returns? I'm looking for something that allows me to experiment with a bunch, and ideally not have to keep validating/restarting configs until I'm pretty much where I want to be

dreamy sinew
#

the template tester is a thing

#

devtools > templates

unreal merlin
#

what I have in mind is to build something that uses the hourly weather forecast to pick (and notify) the best time to when to air the rooms. But as this can be a complex problem, I'm expecting a lot of false roads in this

#

checking, thanks

glossy viper
quiet lagoon
#

What I am not sure is how to test a trigger to create a condition and check for the device_tracker domain.

deft timber
dreamy sinew
#

or {{ 'device_tracker.' in trigger.event.data.entity_id }}

glossy viper
subtle shore
#

hey ho,
maybe someone could help me. i cant get my template automation to work.
even less template'isch does not help.
i send an mqtt message with { "state": "on", "brightness": "128"} and want to turn my light on. but my automation does not get triggered.
https://paste.ubuntu.com/p/fTHgcgPjMr/
what am i missing?

feral ginkgo
dreamy sinew
#

do you have multiple input bools you're looking at?

#

oh i see. input_bool.vaxerN_active or something

feral ginkgo
#

exactly. and vaexerN should render a switch.vaexerN if the boolean is on.

dreamy sinew
#
{% set inputs = states.input_boolean|selectattr('state', 'eq', 'off')|map(attribute='entity_id') %}
{% for input in inputs if 'vaexer' in input and input.endswith('active') %}
{% set ns.switches = ns.switches + ['switch.{}'.format(input.split('.')[-1])] %}
{% endfor %}
{{ ns.switches }}```
#

oh, flip the off to on in the select up there

#

i flipped it for my local testing

feral ginkgo
#

Looks nearly good, but how can trim the "active" part? switch.vaexer1_active without active πŸ˜„

#
{% set ns = namespace(switches=[]) %}
{% set inputs = states.input_boolean|selectattr('state', 'eq', 'on')|map(attribute='entity_id') %}
{% for input in inputs if 'vaexer' in input and input.endswith('active') %}
{% set ns.switches = ns.switches + ['switch.{}'.format(input.split('.')[-1]).split('_')[0]] %}
{% endfor %}
{{ ns.switches }}
#

Thank you very much πŸ™

subtle shore
#

would be this the correct template "{{ payload_json.state | lower == 'on' }}"?
for

{
  "state": "on"
}
dreamy sinew
#

shouldn't need to lower it

subtle shore
#

in that case. yea.

#

i dont get it.
i try to debug my code from a few posts above.

trigger:
  - platform: mqtt
    topic: homeassistant/indoor/light/livingroom/ceiling_light/set
    payload: '"{{ payload_json.state | lower == ''on'' }}"'
 action:
  - type: turn_on
    device_id: adfd634395eb93cbe8bac3ba003541aa
    entity_id: light.livingroom_ceiling_light
    domain: light

step by step. but i think i even dont get the trigger definition right

dreamy sinew
#

what are you trying to get out of the payload?

#

that would render as "True" or "False"

subtle shore
#

atm i try to turn the light on if i publisch the state json.

dreamy sinew
#

i don't know enough about mqtt to know what you would need

#

that probably isn't correct though

subtle shore
dreamy sinew
#

not sure where payload_json is coming from either

subtle shore
#

on on mqtt side i got:
homeassistant/indoor/light/livingroom/ceiling_light/set

{
  "state": "on",
  "brightness": "128"
}
#

that schould pass the filter:

  condition:
  - condition: template
    value_template:  "{{ trigger.topic.split('/')[4] == 'set' }}"
  - condition: template
    value_template:  "{{ trigger.payload_json.state | lower == 'on' }}"
  - condition: template
    value_template:  "{% if trigger.payload_json.brightness is defined  %}True{% else %}False{% endif %}"
#

to trigger the action:

  action:
    - service_template: "light.turn_{{ trigger.payload_json.state | lower }}"
      data_template:
        entity_id: "{{ trigger.topic.split('/')[2] }}.{{ trigger.topic.split('/')[3] }}_{{ trigger.topic.split('/')[4] }}"
        brightness: "{{ trigger.payload_json.brightness }}"
#

developer tools i got it working by using "{% if "{{ trigger.payload_json.brightness }}" is defined %}True{% else %}False{% endif %}"

#

the configuration parse failed with that

subtle shore
subtle shore
wraith blade
#

Is there any chance to customize entity decimals number without creating new entity with template?

hexed galleon
#

What sort of template would I need to use to enumerate through sensors and return a nicely formatted string of sensors that are still "on"?

#

E.g. "The laundry door, office window, and back door are still open."

#

Was thinking of using append when iterating through a manual list, but looks like append isn't allowed with HA.

#

Here's the start of what I have:

{% for sensor in sensors -%}
  {%- if states(sensor) == 'on' %}{{ state_attr(sensor,'friendly_name') | lower }}  {% endif -%}
{%- endfor %}```
#

The weather example in the demo template doesn't work, because not every entity should trigger the loop.first or loop.last condition (hence me trying to create a new list and append affected sensors).

unreal salmon
#

When building a template called x with a template attribute y, is there a way to refer to attribute y inside this template by saying something like self.attribute.y instead of using state_attr('sensor.x', 'y')

median mason
#

is it possible to have a name of a button card with template. for example: button card name of a motion sensor changes depending on motion status? ({% if is_state('binary_sensor.hue_motion_sensor', 'on') %} open {% else %} closed {% endif %})

ivory delta
ruby peak
#

OK. Will have to get my head around this as not sure how to implement it yet. I can see on a trigger, i can get the duration on the input_boolean, but not on a condition

#

Would I just have a template item, call it time since awake and then return the duration in there

glossy viper
#

morning. my dumb air conditioner wnet smart...but still doesn't want to cooperate with me πŸ™‚ i want to see how much time is on and history stats doesn't return any graph. where i go wrong ? https://pastebin.ubuntu.com/p/9HvzBkTjsX/

ruby peak
#

is there a way to get the last_updated value of an input boolean?
{{ state_attr('input_boolean.greg_is_awake','last_updated')}} doesn't seem to work

ruby peak
#

ah, got a relative time {{relative_time(states.input_boolean.greg_is_awake.last_changed)}} but I trying to get it just as a number so I can do a condition if >= **template**

deft timber
ruby peak
deft timber
#

yes

ruby peak
#

hmm, any way to get that to the actual hours though? Thats coming back as 10665.243483781815 but its been 3 hours in relative_time

deft timber
#

/60/60 to get hours

#

and (.../60/60)| round to round

deft timber
glossy viper
#

thank you

ruby peak
# deft timber /60/60 to get hours

thats now giving me 1610093123 🀣
{{ (as_timestamp(now()) - as_timestamp(states.input_boolean.greg_is_awake.last_changed)/60/60) | round }}

glossy viper
#

cannot give an unit of measurement for binary sensor

deft timber
#

{{ ((as_timestamp(now()) - as_timestamp(states.input_boolean.greg_is_awake.last_changed))/60/60) | round }}

deft timber
glossy viper
#

binary sensor is conditioner_on

ivory delta
#
  - platform: history_stats
    name: aer_azi```
#

Not a binary sensor.

deft timber
#

I was talking about aer_azi

ivory delta
#

It doesn't matter what the source is, that's just a regular sensor.

deft timber
#

it is confusing, you have 2 aer_azi, as an history_stats and and a sensor πŸ™‚

glossy viper
#

ok..so the flow is... binary sensor template - history stats sensor - converting view for glance

#

and i give another name for conversion to hh:mm

deft timber
#

and the graph is made based on which one?

glossy viper
#

on conditioner_on

#

i want to see how many hours my air conditioner was on πŸ™‚

#

well...i restarted after changinc name in glance card an i have a value, but not in history

deft timber
#

it is not pretty but could you try creating a template sensor, with unit_of_measurement set, and just return the state of your conditioner_on ? and check if that one is appearing on a graph ?

glossy viper
#

not sure i follow

#

so give up to sensor from history stats and create a pure one

#

then display it on graph card

deft timber
#

no, keep the existing one, create e new one that will just get the value from the history stat sensor, so the 2 sensors will have the same value, the idea is just to check if HA will display the template sensor in a graph

glossy viper
#
  • platform: template
    sensors:
    sensair:
    friendly_name: "Diferenta temperatura"
    value_template: >
    {{ (states('sensor.conditioner_on)
#

something like that?

deft timber
#

yes, don't forget unit_of_measurement

glossy viper
#

oh...luckly i didn't restart

#

'hours' is enough?

deft timber
#

yes

#

can be whatever you want

glossy viper
#

Invalid config for [sensor.template]: invalid template (TemplateSyntaxError: unexpected char "'" at 11) for dictionary value @ data['sensors']['sensair']['value_template']. Got "{{ (states('sensor.conditioner_on)". (See ?, line ?).

#

pf...somebody ate }}

deft timber
#
- platform: template
  sensors:
    sensair:
      friendly_name: "Diferenta temperatura"
      value_template: >
          {{ states('sensor.conditioner_on') }}
      unit_of_measurement: hours

glossy viper
#

ok....but not so ok. gauge shows 0.32 hours and glance 0.54

#

in gauge i put newly sensor

#

maybe 0.32 hours are 32 minutes and 0.54 are hours

deft timber
#

exactly

glossy viper
#

πŸ™‚ now history graph based on new sensor works

#

thank you for patience

deft timber
#

You're welcome

glossy viper
#

don't know where to ask... how can i record the value for the sensor before it get reseted and to track it monthly?

deft timber
#

what you could try is to

  • create a sensor to store your data, a template sensor that gets the state of your sensor to follow,
  • configure the sensor to not refresh manually (very high scan_interval),
  • create an automation that will refresh your above sensor to run just before the reset
  • potentially create a utility_meter https://www.home-assistant.io/integrations/utility_meter sensor to keep track of it
glossy viper
#

so if sensor adds at 24h, then i create a new sensor that is called collector and scan_interval 87000 (to exceed 86400 seconds/day) and an automation to refresh this at 23:59:58 then a utility meter

deft timber
#

I don't now if the scan interval resets after a manual refresh so I suggest you use 315360000 which is, if I'm not mistaking, the biggest value you can set

glossy viper
#

i see. for the moment i will wait for pass this day to see that sensor is refreshed at midnight πŸ™‚

#

and store the conversation

bright quarry
#

how do i put an and statement in this one liner
{% if value_json.device == "1P7U5" %}

so both have to be true for processing.

deft timber
#

just with and {% if value_json.device == "1P7U5" and xxx == "abc" %}

twin jewel
#

I'm converting a date to string on HASSOS, but it's using the US names for the month names. Is there a way for me to change the used locale?

deft timber
#

I don't think there is

glossy viper
#

i have a value coming from a template sensor written like : 13-01-2021Β oraΒ 16:00 .... can i hide that &nsbp ?

deft timber
#

{{ '13-01-2021&nbsp;ora&nbsp;16:00' | regex_replace("&nbsp;","")}} to remove the &nbsp;

bright quarry
#

how can i customize the a sensor's "Unknown" status to say something else instead?

deft timber
#

Or {{ '13-01-2021&nbsp;ora&nbsp;16:00' | regex_replace("&nbsp;"," ")}} to replace it by a space

glossy viper
#
  • platform: template
    sensors:
    actualizat:
    friendly_name: Actualizat
    value_template: '{{ states.sensor.buc_meteo.attributes["actualizat"]}}'
#

and i put after | regex

deft timber
#

'{{ states.sensor.buc_meteo.attributes["actualizat"] | regex_replace("&nbsp;","")}}' then

glossy viper
#

maybe u can share some paypal or anything πŸ™‚

deft timber
dreamy sinew
#

@bright quarry

{{ "My other value" if state == "unknown" else state }}```
deft timber
#

Or that πŸ™‚

dreamy sinew
#

both are functionally the same

bright quarry
#

where does that go?

dreamy sinew
#

as a template sensor

deft timber
#

in a new template sensor

bright quarry
#

can i have separate, multiple template sensors that all address the same sensor name?

dreamy sinew
#

you can

bright quarry
#

man i don't even know how to write a template sensor.

deft timber
glossy viper
#

patience egon... i annoyed 2 guys and 7 days of trials before to have a clue about template πŸ™‚ πŸ™‚

ruby peak
bright quarry
#

@dreamy sinew
{% set state = states('sensor.justin_east_window') %}
can i comma separate multiple sensors there to do more than one or does it not work that way?

dreamy sinew
#

Doesn't work that way

bright quarry
#

rats

deft timber
#

what do you want to do exactly? You can create an array of values if you want to

bright quarry
#

i have like 15 sensors i want to change "unknown" to say something else, like "n/a"

deft timber
#

like that:
{% set state = [states('sensor.justin_east_window') , states('sensor.justin_west_window')] %}

#

ok you need to create 15 sensors then

bright quarry
#

wait, value template can have tons of stuff, right?

dreamy sinew
#

Why bother though?

bright quarry
#

i already have a value template for this sensor that has some if/else statements, can i just put

          {% set state = states('sensor.justin_east_window') %}
{{ "N/A" if state == "unknown" else state }}``` under it in the "value template" area?
deft timber
#

I don't think you understand how it works. You can't change the value of a sensor. What we propose to you is to create a new sensor

#

not to create a template sensor to change the state of the original sensor

dreamy sinew
#

unless whatever he's doing is coming from something that's already a template

#

.share the full thing

silent barnBOT
deft timber
#

yes of course

bright quarry
#

this takes some mqtt message of a door/window sensor and makes sensors out of the time it was triggered

dreamy sinew
#

so you're referencing the state of a sensor within itself

#

probably why you get unknown

bright quarry
#

but i just think "unknown" doesn't look as neat as just a null/empty string when viewed in my frontend

#

or "n/a"

#

you can't just like..define something in the card configuration that does this?

deft timber
twin jewel
#

christ, no changing system locale with hassos?
I'll drag in some python to create a non-US datetime string then

glossy viper
#

well....unfortunately us datetime bothers me especially on grafana, but nothing to avoid it

subtle shore
#

how do i get the following to work:
from entity_id: light.livingroom_ceiling_light to topic: homeassistant/indoor/light/livingroom/ceiling_light

  trigger:
  - platform: device
[...] ## useless informations
  condition: []
  action:
  - service: mqtt.publish
    data_template:
      topic: "{{ 'homeassistant/indoor/' + entity_id.replace( '.' , '/' ).replace( '_' , '/', 1 ) }}"
      payload: 'ON'
#

according to jinja2 syntax is this correct.

alpine pelican
#

The jinja works (just tested it in my DevTools -> Template editor)

subtle shore
#

i want to have a state strem - and the provided mqtt function is kinda shitty to use - for debugging is this nice. but not for a state change report. IMHO

#

is there something different?

#

grr. nvm. got it. after editing it through the ui it changed my topic

glossy viper
#

can i name a sensor with / ?

#

"hours/day" like ?

charred dagger
#

In a way.

#

All entities have a display name ("friendly name"), which can be pretty much anything at all.

glossy viper
#

understood

#

as a friendly name yes...as name no

#

πŸ™‚

charred dagger
#

Technically, I'm pretty sure you could enter hours/day as a name as well in some cases, but the / would be automatically removed.

glossy viper
#

i see. ty

#

hm...scan interval cannot be set for template....

charred dagger
#

You probably don't need that. It will update when anything used in the template updates.

glossy viper
#

well..the problem is that i store the time for my air conditioner is on / day

#

and i want to gather data per month

#

and one of the guys said that i must set a sensor with high scan interval

#

in order not to be refreshed

#

then pull an automation before time/day is reset

#

to gather total value per day

charred dagger
glossy viper
#

exactly

#

i set it up

#

but per day

#

and at 0:00 it's reset

#

i want at 23.59 to be re-evaluated and published in another place

#

then with utility meter i can put sensor to be tracked monthly

#

is this logic?

charred dagger
#

Hm...

#

So you want something like this? This is my power usage per day for the last six months

#

But with hours

glossy viper
#

i don't have smart plugs in the house for now

charred dagger
#

This is done with InfluxDB and Grafana.

#

I have a utility sensor which calculates the daily usage and that's stored in an external database.

glossy viper
#

ook...so your sensor how is setup ?

#

i have sql and grafana

charred dagger
#

Home Assistant isn't really ideal for collecting long term data like this, but what you could do is actually use an automation to set the state of say an input_number at 23:59 every night. Then you could use various operations on the history of that input...

glossy viper
#

hmm....if u have an example ... πŸ™‚

charred dagger
#

No, sorry. I'm just brainstorming.

glossy viper
#

only made a demo with input number...

#

idea is ho can i refresh the sensor that collected info in hist stats at 23.59 ?

#

to make sure that i collect indeed the value of today hours

charred dagger
#

That's what the automation would do.

#

Something like (just from the top of my head. No guarantees on the syntax)```yaml
trigger:

  • time: 23:59
    action:
  • service: input_number.set
    data:
    entity_id: input_number.hours_yesterday
    value: "{{states('sensor.your_hours_per_day_sensor')}}"```
glossy viper
#

ok

charred dagger
#

Then it's comes down to your history settings for Home Assistant how long that data survives.

glossy viper
#

purge days set to 365

#

thanks for idea. gonna check input number

#

hours_yesterday is a sensor ?

charred dagger
glossy viper
#

don't understand

#

i call a service to put a value from states....where?

charred dagger
#

You have to create one of those manually. They're supposed to be used for getting values from a user, but you can also set their value via a service call (e.g. in an automation). That value will then be stored in the input_numbers history.

glossy viper
#

oh...that's the name of the entity input....so for grafana i will call input number of hours for each day

#

because this value will be stored only once / day

#

i put the value from automation πŸ™‚

#

then template sensor with state of input number

hexed galleon
#

How would I return a nicely formatted string from a custom list of entities that match a criteria? E.g. "The laundry door, office window, and back door are still open."

#

The weather example in the dev panel doesn't work because loop.first and loop.last are not necessarily matching the criteria.

dreamy sinew
#

{{ "The following are still open: {}".format(", ".join(open_list)) if open_list else "Nothing is open." }}

#

assuming you already have the list

hexed galleon
#

I do not, I was trying to do that via template as well, with a for loop. But looks like the append function is disabled in HA for security reasons.

#

Here's the start that I have:

{% for sensor in sensors -%}
  {%- if states(sensor) == 'on' %}{{ state_attr(sensor,'friendly_name') | lower }}{% endif -%}
{%- endfor %}```
#

If there's a way to construct a new list just based on a criteria, I can handle the rest easily enough πŸ™‚

junior hamlet
hexed galleon
#

Makes sense, can kinda get there with similar nesting. How do you handle the select_or_reject generator object though? Is it just an iterable?

junior hamlet
#

| list :)

hexed galleon
#

Returns an empty list :/

junior hamlet
#

Did you create a group entity?

#

I use this to count opened windows for eg in a sensor, but the idea is the same {{ expand('group.living_room_windows_opening_sensor') | selectattr('state', 'eq', 'on') | list | count }}

hexed galleon
#

I did not. Thought I could do it without a group and just a manual Jinja list. It kinda works with a group now.

#

Returning the entities in a list. How do I now get the friendly_name attribute for the do_other_stuff step?

junior hamlet
#

A jinja list doesn't have a state. expand works because it outputs a list of state objects

#

i guess something like this would work:

{% for sensor in (expand('group.living_room_windows_opening_sensor') | selectattr('state', 'eq', 'on') | list) %}
  {{ sensor.attributes.friendly_name | lower }}
{% endfor %}
hexed galleon
#

Oooooh! And everything clicks into place. The first part is just to generate the list based on the criteria!

junior hamlet
#

I've edited my message. sensor is an object, so that edit should work better πŸ™‚

hexed galleon
#

Yep, works a charm now! Starting to get my head around Jinja schema/logic flow a bit better now.

#
  {%- if loop.first %}The {% elif loop.last %} and the {% else %}, the {% endif -%}
  {{ sensor.attributes.friendly_name | lower }}
{%- endfor %} is open. You may want to close it before heading out.```
#

Just need to use the count logic from before and a conditional to change the message if there's no open sensors.

dreamy sinew
#

since you're making a string you could do it that way

#

but if you actually want to build/return a list it gets wonky

hexed galleon
#

So next question (that I'm not sure is even answerable/solvable with the current mobile app notify integration) - How can I determine (either with template or just normal automation) any notify entities that are/aren't home? I previously did it in AppDaemon with a dict which mapped person entities to the notify.mobile_app_* entities. Would similar logic apply here?

dreamy sinew
#

that gets harder i think

#

since they're multiple services

#

unless you make groups with the different combinations?

silent barnBOT
dreamy sinew
#

and make a map

#
service: >-
{%- set notify_map = {"person_1": "notify.person_1", "person_2": "notify.person_2", "person_1+person_2": "notify.group_both"} -%}
{%- set away = states.device_tracker |selectattr('state', 'not', 'home')|map(attribute='entity_id')|map('replace', 'device_tracker.', '')|list -%}
{{ notify_map["+".join(away)] if away|length > 1 else notify_map[away[0]] }}
#

something like that

#

@hexed galleon

hexed galleon
#

Will that work though? Because it will effectively be calling multiple different notify services at once?

dreamy sinew
#

it'll only ever be calling one from the automation

#

if you have a notify group it'll do multiple that way

#

you just need to have groups for any combinations and populate that map

#

obnoxious, but it'll work

hexed galleon
#

Bummer. Was hoping there would be some sort of template-based loop functionality in the automation engine. Perhaps I should stop trying to be so tricky and just use the python_script integration πŸ˜›

dreamy sinew
#

that could work

hexed galleon
dreamy sinew
#

haha

viral aurora
#

What causes this error
Error while processing template: Template("{{ state_attr('binary_sensor.protection_window', 'start_time').timestamp() | timestamp_custom('%R') }}")
binary_sensor.protection_window is from my OpenUV integration. Would the History Graph Card cause this error, and why?

young jacinth
#

Hi, is it possible to use a secret in a template?

junior hamlet
glossy viper
#

hi. from time to time the card display the sensor with many many decimals. the sensor is built as value_template: >
{{ (states('sensor.immax_temperature'))|float - (states('sensor.openweathermap_temperature'))|float}}

#

both temps are with 2 decimals. why i see now 20 decimals ?

young jacinth
#

nevermind that was idiotic πŸ˜†
what i want to do is using multiple values from different secrets in a template sensor
i abused the secret function to store some global values

ivory delta
#

You can use them all. Just expose them as individual sensors first.

junior hamlet
ivory delta
#

But secrets as global variables is usually a bad pattern. Just use the input helpers.

junior hamlet
#

Or just input_text

ivory delta
#

Yeah... input helpers. Which I also said.

deft timber
#

@young jacinth Why don't you just use variables ? Something like:

variables:
  secret1: !secret secret1
  secret2: !secret secret2
#

And then use secret1and secret2in your template

glossy viper
#

hi. from time to time the card display the sensor with many many decimals. the sensor is built as value_template: >
{{ (states('sensor.immax_temperature'))|float - (states('sensor.openweathermap_temperature'))|float}}
both temps are with 2 decimals . again wierd display: 19.880000000000003

deft timber
#

IT does strange things sometimes, just add a |round(2) πŸ™‚

glossy viper
#

{{ (states('sensor.immax_temperature'))|round(2) |float - like this ?

#

for each state

deft timber
#
value_template: >
          {{ (states('sensor.immax_temperature')|float - states('sensor.openweathermap_temperature')|float) | round(2)}}
glossy viper
#

ah...all syntax

#

ty

stray merlin
#

Hey Guys,

I'm trying to create a Rest-Sensor from an JSON-Output.
My Sensor is created but the Value is empty.
Here is the Rest-Output and the config for the sensor.
https://pastebin.com/v3BKrh0W
any hints?

I'm trying to get the value from the first attribute 1.8.0

deft timber
#

It should work... nothing in the log ?

stray merlin
#

Nothing regaring the REST-Sensor

#

Well there we go - another Restart of HA has fixed it... Strange....

stray merlin
#

Me again...
anyone why this is not rounded to two decimals?

{% set value_json=
{"1.7.0": 22345456 }%}

"{{ value_json['1.7.0'] / 1000 | round(2) }}"

Value is: "22345.456"

deft timber
#

"{{ (value_json['1.7.0'] / 1000) | round(2) }}"

#

in your template you are rounding the 100. You need to add parenthesis

stray merlin
#

😩 maths is way to long ago... Thanks again

deft timber
#

πŸ‘

young jacinth
#

i dont want to use helpers as the integration (adaptive lighting) iam using does not support templates but secrets

deft timber
#

oh ok, didn't get it was in a sensor

grim flicker
#

Is there a way to use something like this:
{{ is_state_attr('binary_sensor.mailbox_sensor', 'tiltangle', < 24) }}

#

this gives an error but i would like to check if a value of an attribute is below a value and then give true

#

so i can use it in a condition

alpine pelican
#

{{ state_attr('binary_sensor.mailbox_sensor', 'tiltangle') | int < 24 }}

grim flicker
#

can i also use this as a trigger. i need this as a trigger πŸ˜…

ivory delta
olive moth
#

ello fellas.. I was wondering if it is possible somehow to use a template to get an url for an image using lovelace pictire element or Picture card?

#

something like:

#
type: picture
image: 'sensor.xmpp_picture_box'
tap_action:
  action: none
hold_action:
  action: none
#

the sensor has an url with a pix as state

dreamy sinew
bright quarry
#
data:
  value: >-
    Justin East Window, {{ as_timestamp(strptime(datetime, '%Y-%m-%d %H:%M:%S'))
    | timestamp_custom('%a, %b %d at %I:%M %p') }}
entity_id: input_text.lastusedss

how do i parse the current time like this? it's not working. is it because i need to use value_template? can i use value_template instead of value in this service?

alpine pelican
#

look at the bottom of the page.

#

i think you need "SOMETHING.as_timestamp" or "SOMETHING | as_timestamp", but I'm not sure. Google could probably help.,

teal cove
#

is wait.remaining gonna be in seconds or which format?

silent barnBOT
dreamy sinew
#

Should prolly use that instead

glossy viper
#

yesterday value is not written by the input_number automation ,

#

although the value is changed and displayed by the cumulative senso

junior hamlet
#

''(wrong) vs " (correct) ... Not very visible πŸ˜…

ivory delta
#

That's most likely a copypaste thing.

#

We see it a lot.

junior hamlet
#

Can't see how a double quote can be transformed into a double single quote during a copy / paste, but you know probably better ;)

ivory delta
#

Not all editors (or languages) are created equal.

#

If you've ever used MS Word, you will have come across the stylised quotation marks.

#

If the issue was with Adrian's quotation marks, the sensor wouldn't work at all πŸ˜‰

junior hamlet
#

The automation doesn't work, not the sensor 😊 this line is in the automation section.

ivory delta
#

@glossy viper - any issues when you run the config check?

timid osprey
#

yaml does not abide by your rules

#

I learned this recently, again.

hexed galleon
#

Likely a very simple question - can I only get the friendly name of a trigger object from the from_state/to_state objects? Is it just {{ trigger.from_state/to_state.attributes.friendly_name }}?

ivory delta
#

state.name Name of the entity. Based on friendly_name attribute with fall back to object ID. Example: Kitchen Ceiling.

hexed galleon
#

Cool, but still need to reference a state object, right? So has to be from_state or to_state?

#

{{ trigger.from_state.name }}

ivory delta
#

Bingo

hexed galleon
#

Thanks!

clever pelican
#

Hi everyone. I've got a IR-controlled DAC set up as a light to control the volume in HomeKit. There's an annoying issue: when a scene is called twice in the Home app, it is actually toggled, and this makes HomeKit turn off the "light" which mutes the DAC.

#

I've got a value template like so:

#
        value_template: >-
          {% if is_state('switch.antimode_mute', 'off') %}
            {% if (states('input_number.antimode_volume')|int ) > 0 %}
              on
            {% else %}
              off
            {% endif %}
          {% else %}
            off
          {% endif %}
#

And I'm hoping someone might have an idea how to un-mute if a volume state is received. I believe if I only check for > 0 the mute state wouldn't persist at all.

deft night
#

can you somehow get the last X values of a sensor in a temeplate?

ivory delta
#

Nope. Sensors only have their current state. What are you trying to do?

deft night
#

i am feeding sudo journalctl -n 1 -p 0..4 --no-pager -q to a sensor

#

and would be nice to show more than 1 line

#

if I go over one line with the -n value it won't register at all

ivory delta
#

What are you trying to get out of this? What's the end goal?

deft night
#

the markdown box to the right

ivory delta
#

You have a markdown box. What are you trying to do?

#

You just want more lines?

deft night
#

exactly

ivory delta
#

Well if your sensor can't read more lines, make more sensors.

deft night
#

πŸ™‚

ivory delta
#

Templates can only work with data you already have. If you need more data, that's an #integrations-archived problem.

deft night
#

the values are stored in the history component though, must be a way to access them

ivory delta
#

No

deft timber
#

Or get several lines, in the command line replace \n with # for instance, and in the gui replace the # with \n

ivory delta
#

Templates read state. State is current, not historic.

deft night
#

its easy to get json output from journalctl too, but anything that isnt a sensor is not updated immediately in the GUI

deft timber
#

I suggest
sudo journalctl -n 5 -p 0..4 --no-pager -q | tr '\n' '#'
And in your markdown
{{ states("sensor.your_sensor") | regex_replace("#", "\n")}}

deft night
#

aah, clever! gonna give this a shot

#

hmm, doesnt pick up the state. is there a limit on max length of a state?

#

i'm thinking of adding it in an attribute instead

deft timber
#

yes there is a limit

#

255 I think

#

I confirm, that's the size of the DB column

deft night
#

got the wanted result, thanks @deft timber {{ state_attr('sensor.cube_syslog', 'log') | regex_replace("#", "\n") }}

deft timber
#

πŸ‘

deft night
#

the state is the timestamp of the poll

sonic nimbus
#

is there any templates that returns true or false for my condition-template like if all meida_players are turned off?

#

somehing like {{ media_players.*}}

#

?

thin vine
#

you could loop through all of them with a for device in devices loop, bu not sure if there is a smarter way

dreamy sinew
#

{{ not states.media_player|rejectattr('state', 'eq', 'off')|list|length > 0 }}

thin vine
#

that seems to be smarter πŸ™‚

sonic nimbus
thin vine
#

I had to add idle and unavailable for that to work though:
{{ not states.media_player|rejectattr('state', 'eq', 'off')|rejectattr('state', 'eq', 'unavailable')|rejectattr('state', 'eq', 'idle')|list|length > 0 }}

sonic nimbus
#

oh, I forgot to mention, I want to turn off the media_player

#

so, if all media_players are off, except media_player.ABC, then turn off media_player.ABC

#

basically ABC player is my 2-zone AVR and Im listen spotify, watch movies, etc

#

so I need to ask if all media_players are off in order to turn off my avr

deft timber
#

give this as the entity_id to the turn off service : {{ states.media_player|rejectattr('state', 'eq', 'off')|rejectattr('state', 'eq', 'unavailable')|rejectattr('state', 'eq', 'idle')|map(attribute='entity_id')|list}}

#

this will turn off all the media player that are not off

dreamy sinew
#

can shorten that

deft timber
#

or unavailable or idle

sonic nimbus
#

no, no, I want to just turn my avr if and only if all my other media_players are set to off

#

or unavailable

deft timber
#

ah ok

dreamy sinew
#

{{ states.media_player|rejectattr('state', 'in', ['off', 'unavailable', 'idle'])|map(attribute='entity_id')|list}}

#

should probably include unav regardless

sonic nimbus
dreamy sinew
#

oh, if you're getting choosy you probably should just create a group and key off of that

sonic nimbus
#

I heard that it cant be created group of media_players?

pliant viper
#

How do I use a !secret tag inside a template sensor's result? NVM: Looks like it's not possible, solved with a second template sensor

dreamy sinew
#

you can use it for your purposes i think

#

if the group isn't off

sonic nimbus
#

yes I will try

#

and how to shorthand write this

#
  or 
  is_state('input_select.livingroom_tv_source', 'HEOS Music')
  or
  is_state('input_select.livingroom_tv_source', 'SBB BOX')
  or
  is_state('input_select.livingroom_tv_source', 'TV Audio')
}}```
#

like this {{ states.media_player('state', 'in', ['HDMI 3 (eARC/ARC)', 'HEOS Music', 'SBB BOX','TV Audio'])}}

#

?

ivory delta
#

Close

#

I use something like this:

In Teams meeting: {{ states('sensor.microsoft_teams_activity') in busy_statuses }}```
sonic nimbus
#

Im just trying to add to mediaplayer.source

#
Test: {{ states('media_player.avr_zone1.source') in sources }}```
#

{{ states('media_player.avr_zone1.source') }} but this is unknown

thin vine
#

quick other question πŸ™‚ how do I reject on the existance of the entity_id attribute, rather then the states entity_id:
<template TemplateState(<state light.lampen=on; min_mireds=153, max_mireds=500, effect_list=['colorloop', 'random'], brightness=191, color_temp=365, effect=none, entity_id=['light.hue_lightstrip_plus_1', 'light.staande_lamp', 'light.hue_color_pendant_down_1', 'light.hue_color_pendant_up_1', 'light.computer', 'light.hal', 'light.reserve', 'light.sk_ceiling', 'light.sk_duo_spot_1', 'light.sk_duo_spot_2', 'light.overloop', 'light.keuken_1', 'light.keuken_2', 'light.keuken_3', 'light.trap_hal'], friendly_name=lampen, icon=mdi:lightbulb-group, supported_features=63 @ 2021-01-15T15:29:47.241841+01:00>)>]

light without the entity_id attribute:
<template TemplateState(<state light.computer=on; min_mireds=153, max_mireds=500, effect_list=['colorloop', 'random'], brightness=191, color_temp=365, effect=none, friendly_name=Computer, supported_features=63 @ 2021-01-15T15:29:47.237368+01:00>)>

deft timber
#

rejectattr('attributes.yourattribute', 'eq', 'abc')

thin vine
#

ah

#

thanks that works

young jacinth
#

hi!
are we not allowed to use {% set sun = state_attr('sun.sun','elevation') %}
"{% set ... " in a template sensor?

deft timber
#

yes you are

thin vine
#

made it possible to replace:

            {% for device in dict(states.light|groupby("state"))["on"] %}
              {%- if state_attr(device.entity_id , 'entity_id') != None  %}
                {%- if loop.first %}{%set ns.first =true %}{% endif %}
              {%- else %}
                {%- if loop.first or ns.first  %}{%set ns.first =false%}{% else %},{% endif %}
                {{- device.entity_id | lower }}
              {%- endif %}
                {%- if loop.last %}{% endif %}
              {%-  endfor  %}
              ```
with:
`{{states.light|rejectattr('state', 'eq', 'off')|selectattr('attributes.entity_id', 'undefined')|map(attribute='entity_id')|list}}`
#

much better!

deft timber
#

indeed πŸ™‚

young jacinth
thin vine
#

thanks Slashback and phnx

deft timber
#

@young jacinth replace && with and

young jacinth
#

ouch

#

that worked thanks alot

sonic nimbus
#
      value_template: >
        {% set sources = ['HDMI 3 (eARC/ARC)', 'HEOS Music', 'SBB BOX','TV Audio'] %}
        {{ states.media_player.avr_zone1.attributes["source"] not in sources
          and
          states.media_player.avr_zone2.attributes["source"] not in sources
        }}```
#

but I ahve error on this

#

Invalid config for [automation]: expected str for dictionary value @ data['condition'][0]['state']

dreamy sinew
#

aww man i step away and all the fun ones come in

thin vine
#

hehehe

dreamy sinew
#
    - condition: template
      value_template: >-
        {%- set sources = ['HDMI 3 (eARC/ARC)', 'HEOS Music', 'SBB BOX','TV Audio'] -%}
        {{ state_attr('media_player.avr_zone2', 'source') not in sources
          and
          state_attr('media_player.avr_zone2', 'source') not in sources
        }}
#

yeah, i try to avoid actual for loops whenever possible. Its not always possible though

#

native typing made things better though

thin vine
#

yes. I've tried to pass xy colors a while back and then gave up as they're always passed as strings.

dreamy sinew
#

that's fixed now though

thin vine
#

yep

#

I saw that, so next time I'll play with that I can now πŸ™‚ But since then, blueprints also came out so I used those, making it easier not to pass these things between an automation and a script, bu just put it in the blueprint, no need for the script part anymore

sonic nimbus
dreamy sinew
#

i don't really mess with built in automation Β―_(ツ)_/Β―

#

might need to check the docs for template conditions

thin vine
#

let me see if I have a similar condition template, as I use them a lot

sonic nimbus
#

its ok, another condition was causing the issue πŸ™‚

#

thanks

thin vine
#

hehehe yeah it's sometimes not very clear in the debugs which term it actually giving the error on

sonic nimbus
#

yeah..once I edited multiple script/automations, and left it like that, tomorrow, I checked config, and some script/automation was giving the error in the logs

#

So I had to comment one by one each automation file, to locate my error πŸ˜„

thin vine
#

I use set in conditions a lot, so I knew it had to work. for example:

      value_template: >
        {% set tz = as_timestamp(now())|timestamp_custom('%z') %}
        {% if state_attr('calendar.2020_fia_formula_one_world_championship_race_calendar', 'start_time') == None %}
          False
        {% else %}
          {{ now().strftime('%D %H:%M') == ( (as_timestamp(state_attr("calendar.2020_fia_formula_one_world_championship_race_calendar", "start_time") + tz )-600)   | timestamp_custom('%D %H:%M', 1)) }}
        {% endif %}```
#

I do alot with google calendar, but that's giving times back in gmt...

sonic nimbus
#

nice

thin vine
#

using the set there to make it just a bit more readable

sonic nimbus
#

and another question - is there some "hack" through templating to do a following

#

I have ofc tag reader

#

and I want to trigger automation when I scan twice same tag

#

in interval no longer than 5 seconds

#

so I was thinking to create input_boolean when first scanning occuer

#

occured*

#

and some helper automation to countdown 5 seconds

#

than to ask through template if still input_booleon is true

#

but Im missing the second scanning the tag

thin vine
#

not really a template hack, but you could do a wait for triggere in the automation to wait for the 2nd scan

sonic nimbus
#

Idk how to implement that

thin vine
ivory delta
placid kindle
#

Hey guys, I am trying to add a binary sensor which is true depending on the state of another sensor, but for some reason it doesn't seem to work.

- platform: template
  sensors:
    e3dc_emergency_power_available:
      friendly_name: "E3DC Emergency Power Available"
      value_template: "{{ is_state('sensor.e3dc_emergency_power_state', 1) or is_state('sensor.e3dc_emergency_power_state', 2) }}

The other sensor is derived from Modbus and has an int value, so I suppose my current code is correct. But apparently it's not, because it currently has the value 2 but the binary sensor is still off. What did I do wrong?

#

using is_state('sensor.e3dc_emergency_power_state', '1') (and '2' respectively) also doesn't work.

ivory delta
#

Test the templates in the Dev Tool and see what it says.

placid kindle
#

ah, totally forgot that this panel existed. Thanks. When using a string comparisson it returns true, yet my sensor is still off. I'll reboot once more (need to update HA anyways for the security update)

ivory delta
#

For future reference, you don't need to restart to reload template integrations. There should be an option to reload those.

placid kindle
#

even as binary sensors?

#

wow, seems to work. Nice. Thanks for the tip

subtle shore
#

my entity_id: light.bedroom_hue_color_ceiling_light should match my topic.
how do i achieve this?
topic: homeassistant/indoor/light/bedroom/hue_color/ceiling_light

i got following jinja2
{{ 'homeassistant/indoor/' + entity_id.replace( '.' , '/' ).replace( '_' , '/', 1 ) }}
now i need to skip one _ and replace the 3rd _ with a / how do i do this?

#

atm, i get homeassistant/indoor/light/bedroom/hue_color_ceiling_light

dreamy sinew
#

do you need it to be generic or are you always targeting that one?

subtle shore
#

i want to be generic for ~~every ~~ all rooms.
i have hue_color and hue lights and think i need to seperate those

dreamy sinew
#

are your naming conventions consistent?

subtle shore
#

jeah. my template schould work with every light.
indoor / outdoor/light/room/hue / hue_color/ceiling_light / couch_light / etc./cmd

#

but this should only effect indoor lights

#

/cmdending is not the problem here. πŸ™‚ i just dont included this here

#

well. i just can rename my lights. HAHA

#

there is no need for ceiling_LIGHT

#

thanks anyway. πŸ˜„

dreamy sinew
#

yeah, parsing all that out would be kinda rough to make it generic

ivory delta
#

Just set custom attributes on those devices. Turns the template into one simple | select_attr.

subtle shore
#

try to find a way to replace the "last" _ with an /
this would solve my problem.

mono how do i do this?
configuration.yaml

light.bedroom_hue_color_ceiling_light:
entity_topic: homeassistant/indoor/light/bedroom/hue_color/ceiling_light
something like this?

ivory delta
#

entity_topic? πŸ€”

#

Something like this:

  room: "study"```
subtle shore
#

ahhhh.

ivory delta
#

Then to find them:
{{ states | selectattr('attributes.room', 'equalto', 'study') | list }}

subtle shore
#

πŸ’‘

ivory delta
#

A little bit more setup, way less of a headache to work with.

subtle shore
#

it is kinda win-win...
need to learn jinja2 for work. πŸ˜„

#

is Area: not already a valid attr?

#

oh. i see. its not?

ivory delta
#

Areas are things in HA but I don't know if they're an actual attribute of entities.

#

Either way, I'd recommend avoiding any custom attribute names that could collide with either native HA stuff or any integrations.

magic pike
#

How do I combine a string and state template together? This doesn't work:

color_extract_url: 'https://homedomain.com{{ states.media_player.spotify.attributes.entity_picture }}'```
#

It throws this error in the log:
External URL 'https://homedomain.com{{ states.media_player.spotify.attributes.entity_picture }}' is not allowed, please add to 'allowlist_external_urls'
Even though I've added the url to allowlist_external_urls, but it doesn't convert the states template?

#

When I try it in Developer > Templates the resulted string is https://homedomain.com/api/media_player_proxy/media_player.spotify?token=8b369cea0db0a806148xxxxxx and that URL shows the album art perfectly fine.

ivory delta
#

Not every field in HA accepts templates.

#

What does the documentation say for the integration you're trying to use?

magic pike
#

Hmm, docs do a relative url, I'll try that.

ivory delta
#

Relative still isn't templated πŸ˜‰

magic pike
#

Failed to call service color_extractor/turn_on. invalid url for dictionary value @ data['color_extract_url']

ivory delta
#

Because you're still using a template...

magic pike
#

Hmm, is there any other way you think? This is basically what the docs do too, am I wrong?

ivory delta
#

Well is this you setting it up in configuration.yaml or calling the service?

magic pike
#

Calling the service via developer tools > services. The plan is to make an automation out of it.

ivory delta
#

Ok. Templates aren't rendered in calls made from there.

#

Make an automation, try it for real.

magic pike
#

So I basically plan to change the color of a led strip to the color that the color_extractor returns every time a song changes in Spotify

#

Okay, will do!

alpine pelican
#

What's the best practice for validating a sensor's value like in a template switch. For example, I have this:

    office_tv:
      friendly_name: "Office TV"
      icon_template: mdi:television
      value_template: >-
        {% if states('sensor.office_tv_plug') | float < 5 %}
          off
        {% else %}
          on
        {% endif %}
#

It seems like during HA shutdown, states('sensor.office_tv_plug') is something like "unavailable" and {{ "unavailable" | float }} == 0.0

#

So it's causing an automation to trigger during shutdown even though the TV is still on.

gloomy horizon
#

I've got an integration that is returning a time as a string in the format "5:00PM". I can't seem to get strptime to convert it into a timestamp (I'm trying to have that time, minus 5 minutes, be a trigger for an automation). Any tips on how to template this?

ivory delta
alpine pelican
#

That's true, but I don't want my "The TV is off" automation to trigger because HA restarted.

dreamy sinew
#

"unavailable" | float -> 0

#

oh

#

already said

alpine pelican
#

Basically, I have an automation on my TVs such that if they turn off, the roku stops playback. So if we're watching something and the sleep timer engages, whatever we were watching doesn't keep playing.

#

that works beautifully, but when HA restarts, it triggers this automation (and I don't want that).

dreamy sinew
#

HDMI-CEC should handle that

#

maybe you're missing a setting on the roku

alpine pelican
#

HDMI-CEC does other unexpected crap, so I turn that off where I can. I want HA to handle that stuff.

gloomy horizon
#

@alpine pelican why not use a condition in the automation that limits it to when the state is "on"?

#

(sorry; "off")

alpine pelican
#

currently the automation is for when switch.office_tv goes from on to off.

dreamy sinew
#

i go the other way, i'd much rather use CEC where i can as that is a local network of devices talking to each-other

alpine pelican
#

I appreciate that, but CEC is not consistent across all of my TVs.

#

And some don't have it at all.

dreamy sinew
#

Β―_(ツ)_/Β―

ivory delta
#

A handy solution to that problem would be to not restart HA πŸ€·β€β™‚οΈ

alpine pelican
#

It was recommended that I check in here for a best practice for validating that a sensor is available. I'll figure that out.

gloomy horizon
alpine pelican
dreamy sinew
#

there are automation ways of handling that

ivory delta
#

Don't apply them during movie nights πŸ€·β€β™‚οΈ

dreamy sinew
#

handling in the template isn't the right place

ivory delta
#

Whatever you come up with for a template binary sensor, you'll be in the wrong state some of the time.

#

Handle those checks in your automations.

alpine pelican
#

sounds good.

gloomy horizon
#

Alternatively, you can lengthen the template to use an and to verify that the state is "on" or "off"

ivory delta
gloomy horizon
alpine pelican
#

I think I'll put a condition that sensor.office_tv_plug is not "unavailable"

dreamy sinew
#

just because you can doesn't mean you should and we're saying you shouldn't

ivory delta
#

Or as Tinkerer would put it, there's more than one way to skin a cat.

alpine pelican
#

I wasn't looking for a template solution. I was looking for a solution. And was directed here.

ivory delta
gloomy horizon
alpine pelican
magic pike
gloomy horizon
#

On my question, anyone have any tips? I'm currently sitting on {{ strptime(state_attr('sensor.leafs_game','next_game_time' ), '%H:%M:%S') }} but that returns "5:00PM"

serene mortar
alpine pelican
#

Awesome. Thanks, Chris!

#

The 'Not sensor.office_tv_plug == "unavailable"' solved the problem. Thanks, all!

deft night
#

I have a sensor with an attribute called data queries as {{ state_attr('sensor.recording_schedule', 'data') }} return for example

- name: Some Show She Likes
  duration: 60
  _id: 6001e88ccb5cd777ffe4b3de
  channel: tv3
  startAt: '2021-01-23T20:00:00.000Z'
  addedOn: '2021-01-15T19:10:04.410Z'
  __v: 0
- name: Some Show She Likes
  duration: 15
  _id: 6001f16fab49e4bac92acda2
  channel: tv3
  startAt: '2021-01-23T20:00:00.000Z'
  addedOn: '2021-01-15T19:47:59.707Z'
  __v: 0
#

how do I loop only the names from this

dreamy sinew
#

{{ state_attr('sensor.recording_schedule', 'data')|map(attribute=name)|list }}

#

sorry

deft night
#

lots of undefineds now, I guess its not really a map?

dreamy sinew
#

attribute='name'

#

surprised that didn't crash out

deft night
#

even more undefineds returned in an array

dreamy sinew
#

what is the return type of just the state_attr() statement?

silent barnBOT
dreamy sinew
#

check out the template tester and lets see what comes out

deft night
#

removed all the other templates first, its a string

#

now I got a list, added a json to string flow infront of it

dreamy sinew
#

an that helps

deft night
#

so how do I get it back to a string so it renders πŸ™‚

#

from {{ state_attr('sensor.recording_schedule', 'data')|map(attribute='name')|list }}

dreamy sinew
#

depends. what do you want it to look like?

deft night
#

seems to be fine with the last example in the demo template looping over the list

dreamy sinew
#

there are a few ways to do that but it depends on what you're trying to accomplish

deft night
#

The "Some Show She Likes" and the "Some Show She Likes.

#

its perfectly fine for this, just want a confirmation list after clicking a button in the GUI

#

its a small PoC to port over some old jquery TV recorder I made for my wife 10 years ago to pure HA

#

(and some Node Red to handle the logic)

dreamy sinew
#

noice

glossy viper
#

hi..to avoid asking simple questions please point me where i can find how to compose a syntax like {{ states | selectattr('attributes.room', 'equalto', 'study') | list }} πŸ™‚

dreamy sinew
#

eq

silent barnBOT
dreamy sinew
#

it'll be under "built in tests"

glossy viper
#

ty

gloomy horizon
#

As an update on my question, I've figured out that strptime() requires the time to be in the format, e.g. "5:00 PM". So, now that part is working. Of course, as a timestamp just feeding 5:00 PM in goes back to 1900. Is there a way to change the date returned to today's date with the time as formatted?

#

{{ strptime(state_attr('sensor.leafs_game','next_game_time'), '%I:%M %p') }}