#templates-archived

1 messages · Page 125 of 1

glad moth
#

Would I need to change anything else in the value template or would the following work? - platform: template sensors: windows: friendly_name: "Windows Status" device_class: window value_template: >- {% set windows = ['binary_sensor.office_window_south_status', 'binary_sensor.office_window_north_status', 'binary_sensor.porch_door_status'] %} {{ states.binary_sensor |selectattr('entity_id', 'in', windows)|selectattr('state', 'eq', 'on')|list > 0 }}

dreamy sinew
#

should be fine, just verify in the template tester to see if its returning what you're expecting

rare panther
#

ah okay. Let me figure out whether the source can provide the full raw data - which I presume is roper JSON. Some stupid parsing is done before handing over to me

glad moth
#

Unfortunately, I'm getting this error when I put it in the template tester " TypeError: '>' not supported between instances of 'list' and 'int' "

inner mesa
#

|length

glad moth
#

This doesn't work either - platform: template sensors: windows: friendly_name: "Windows Status" device_class: window value_template: >- {% set windows = ['binary_sensor.office_window_south_status', 'binary_sensor.office_window_north_status', 'binary_sensor.porch_door_status'] %} {{ states.binary_sensor |selectattr('entity_id', 'in', windows)|selectattr('state', 'eq', 'on')|length > 0 }}

inner mesa
#

Sigh

#

|list|length

glad moth
#

That fixes the sensor but it does not respond when a window opens. Does the template need to be : > instead of : >-

dreamy sinew
#

oh woops

silent barnBOT
glad moth
#

Unfortunately, the window sensor is staying "closed" even when I open the window

mighty ledge
#

only every minute

#

if you want it on the fly:

#
          {% set windows = expand('binary_sensor.office_window_south_status', 'binary_sensor.office_window_north_status', 'binary_sensor.porch_door_status') %}
          {{ windows | selectattr('state', 'eq', 'on') | list | length > 0 }}
dreamy sinew
#

ah i always forget about expand

glad moth
#

Do I keep value_template: >- It's still not updating on the fly

mighty ledge
#

Yes. It’ll update when the first window opens only

#

After that, it’s always open until they all close

mighty ledge
zinc fable
#

"{{ state_attr('weather.home', 'forecast') }} gives me lots of information, but I just want the condition cloudy, for instance. How would I go about doing that?

dreamy sinew
#

state_attr(...).whatever

glad moth
#

I still am not getting a response when I open a window with - platform: template sensors: windows: friendly_name: "Windows Status" device_class: window value_template: >- {% set windows = expand('binary_sensor.office_window_south_status', 'binary_sensor.office_window_north_status', 'binary_sensor.porch_door_status') %} {{ windows | selectattr('state', 'eq', 'on') | list | length > 0 }}

dreamy sinew
#

are any of the entities actually changing?

glad moth
#

Yes, I double checked that they are

dreamy sinew
#

put that template in the template tester and check the result

glad moth
#

the result is false even when I change the state of one of the windows

#

Wait I got it, just a misspelling in one of the sensors. Thanks for the template help! All works now!

pastel moon
#

I am trying to make a template sensor to round to one decimal, but it won't. What do I do wrong please?

      hallway_motion_temperature:
        friendly_name: 'Hallway - Motion Temperature'
        value_template: '{{ sensor.hallway_motion_temperature | round(1) }}'
inner mesa
#

Your template is wrong

#

Best to review that whole page

pastel moon
#

Thanks, will do 🙂

pastel moon
#

This did the trick, but "friendly_name" still don't?

      kitchen_motion_2_temperature:
        friendly_name: 'Kitchen - Motion 2 Temperature'
        value_template: '{{ states("sensor.kitchen_motion_2_temperature") | round(1) }}'
        icon_template: 'mdi:thermometer'
        unit_of_measurement: '°C'
inner mesa
#

doesn't what?

pastel moon
#

It does not use the friendly name I set in the template

inner mesa
#

it might not like the "-"

#

does it show up in the attribute list?

#

what doesn't use it?

pastel moon
#

I think I have some leftover config I need get rid of... found some strange entrys so probably it

loud otter
#

Hi, I'm trying to convert automation from yaml to gui but everytime it is save it "produces" an error in formatting

volume_level: '{{states(''sensor.period_of_day_volume'')|float}}'

I change ' with " but at every save it is restored.

ivory delta
#

'an error'. What's the error?

sour acorn
#

trying to trigger at an input_datetime, whats the best way to write that

inner mesa
#

I’m not sure what you’re trying to do there. You can trigger directly on an input_datetime

sour acorn
#

oops

#

let me try

#

my mistake, sorry

grim flicker
#

@glad moth Why dont you make a group with those 3 sensors. something like:

group:
  doorsensor_group:
    name: three doorsensors
    all: false
    entities:
      - binary_sensor.office_window_south_status
      - binary_sensor.office_window_north_status
      - binary_sensor.porch_door_status
#

If im correct when one of them reports open the sensor goes to open. only when all are closed the group will turn close

#

I know this works with lights and booleans. never actually tested it on sensors though

frail dagger
frigid marsh
#

How can I validate a template based on last_changed?

I have sensor for which I have set scan_intervals at specific times in the day using automations, and it makes sense to only show those sensors during these times. Unfortunately using condition: 'time' does not validate (see https://paste.ubuntu.com/p/6ZH5tY5X5R/), so I need to use another way. So since last_changed is relative to the scan interval automation, this should work...if I knew how to write it correctly.

Logic: Validate True/False if {{ relative_time(states.sensor.drive_to_work.last_changed) }} is less than 5 minutes. It don't know if using 'relative_time' is the right way to go about this, I just think it makes sense in this case - feel free to correct me.

mighty ledge
#

Relative time returns a string

#

You have to calc it out yourself if you want a number without units

edgy umbra
#

Hi,

Anyone know how to get the min value from this template? {{ state_attr('climate.vicare_heating', 'room_temperature')}}

dreamy sinew
#

what is the output of that template?

inner mesa
#

I suspect that the easiest way to get a historical min/max for an attribute is to create a template sensor to surface that attribute and then use the min/max integration on it

ivory delta
#

cough statistics sensor cough

inner mesa
#

still have to get at the attribute somehow

ivory delta
#

Yes. I was disputing the min/max sensor part 😄

#

Min/max exposes the min/max/mean of the current values, right? Not a rolling average based on history.

inner mesa
#

yeah, fair enough

edgy umbra
silent barnBOT
dreamy sinew
#

Probably that then

ivory delta
#

What he said (but I said first 😄 )

edgy umbra
#

Thanks, that seems what i was looking for. 🙂

dreamy sinew
#

lol i forgot about that integration, only posting because if you mono

glad moth
fresh ibex
#

Hi, Im new to home assistant and ran into a this problem. When I use the round(2) syntax, it rounds the number to 2 decimal places but shows trailing zeros with 1 at end. (e.g. 72.24000000001) How can I fix this and why is this happening? thanks

#

aircon_bill:
friendly_name: "Aircon Bill"
unit_of_measurement: 'PHP'
value_template: >

      {% set W = 0.56 | float %}
      
      {% set P = 10 | float %}

      {% set H = states('sensor.aircon_monthly') | float %}

      {{ W * P * H | round(2) }}
marble jackal
#

You are only rounding H

#

use {{ (W * P * H) | round(2) }}

fresh ibex
marble jackal
#

Great!

oak tiger
#

Little help with proper way to handle this. I have 6 media players around the house. One one or more I usually play radio station. For each media player I need to check what radio station is playing (media_player media_title attibute). If it is specific radio station I need to call a rest sensor or url that will fetch artist and title for that radio station. And I would like to display this in lovelace. So I am brainstorming for whole day how to handle this. Maybe check for each media player if state is playing and then read the media_title from it. But what next. How to tell HA to go and fetch json data with artist and title for that specific radio station?

#

This is my rest sensor that holds the data of the artist and title for specific radio station. But I do not want to refresh this sensor if nothing is playing on any of the media players.
https://paste.ubuntu.com/p/ZZFrvCZrp8/

#

Maybe best way is to create automation for each media player that checks if it is playing. If state is playing, I would do a lot of if/else if to see what is playing. If specific radio station is playing then call service to update this rest sensor for that station every 5 seconds. Going in right direction?

thorny snow
#

I'm trying to setup a sensor in HA to display the current power of my solar panels. Huawei has this unofficial API where the data is available through a public kiosk mode XHR, but the JSON kinda sucks. Everything within "data:" is just a long string. Please see here:
https://eu5.fusionsolar.huawei.com/rest/pvms/web/kiosk/v1/station-kiosk-file?kk=oscxz8K15J

So. I tried to do a template like this:
{% set data = {"data":"the really long string here","success":true,"failCode":0} %}
{% set dict = data.data|replace('"', '"')%}
{{ dict }}

But, even though HA says that dict is actually of type dict i can't access {{ dict.realKpi.realTimePower }}

Any ideas why?

dreamy sinew
#

because top level might be a dict but values inside might not be

thorny snow
#

hm okay. Any ideas on how to get the realTimePower value then?

dreamy sinew
#

.share that instead

silent barnBOT
#

Please use https://paste.ubuntu.com/ to share code or logs. Please don't use Pastebin, since it can randomly add spaces to the main view.

thorny snow
dreamy sinew
#

so the output becomes a dict, but it isn't at the point you're looking at it

#

a simple replace won't turn it in to a dict

#

this works

#
{{ d.realKpi.realTimePower }}```
thorny snow
#

wow it did, THANK YOU! Ive been struggling with this for three days 😄

timid wolf
#

Hello everyone. I am having a problem with the output of the json table. There is a bus traffic site that can send data to a json table. I want in HA to display the arrival of the bus at the bus stop.

#

this returns the first bus in the list

#

how to return the result with another bus?

thorny snow
#

on what criteria do you want to select the bus?

timid wolf
#

for example this

#

{"imei":"353173064454000","gov_number":"197","route_id":"14B16FB795F5E70B99852BB3E0E05CFE","route_short_name":"7","route_long_name":"Тр. № 07 м-н "Каскад" - Європейська площа","route_type":8,"time":"2021-04-29 11:08:34","longitude":24.753315,"latitude":48.937415,"satellites":8,"speed":0,"spec":[true,true,false,false]}

thorny snow
#

it's an array of buses, so i guess you can access the bus by index.

#

what happens if you do this for example: {{ value_json[3] }}

timid wolf
#

the same first bus from the list

#

I did this option

mighty ledge
#

you aren't downloading the file

timid wolf
#

homeassistant.exceptions.InvalidStateError: Invalid state encountered for entity ID: sensor.bus_number. State max length is 255 characters.

mighty ledge
#

if you want it based on bus number:

  - platform: rest
    resource: https://city.dozor.tech/iv-frankivsk/devices
    name: bus_number
    value_template: >
      {%- set bus_number = 2 %}
      {%- set found = value_json | selectattr('route_short_name', 'eq', bus_number | string) | list %}
      {%- if found | length > 0 %}
        {{ found }}
      {%- endif %}
    json_attributes:
      - longitude
      - latitude
      - route_long_name
#

yes thats more than 256 characters

#

you'll need to figure out what you want as the state

#

and the JSON attributes are based on json_path, so you'll need to figure that out

true otter
#

Is this the right place for a script that uses templates?

#

I am trying to both a script and templates to set the volume on selected media players.

dreamy sinew
#

worth a try

timid wolf
silk smelt
#

Hi all! I am trying to put some templates inside a package with a utility meter but I'm having problems with the formatting. Can someone help me out? I would appreciate it 🙂 https://pastebin.com/qDNXYvPG

past raft
#

Good Morning, I am newbie at HA. Are there basic config template I can use? I got HA install but curious if there were any sample templates to referene?

ivory delta
spiral imp
#

I have a pretty involved template that sets "when" equal to a date - a date. If it calculated to -1 I want it to return "Yesterday". Will this work?

{% elif when == -1 %}
     Yesterday
dreamy sinew
#

have you tried testing it?

spiral imp
#

just tested by tweaking a value, thanks

lucid oasis
lucid oasis
#

I'm trying to find how to pass variables in a package and include one package file multiple times.

#

For example - packages:
sm7822b_01: "{% with index='01', var_2='value 2', var_3=500 %} !include packages/home/sm7822b.yaml {% endwith %}"

#

Gives configuration validation error - expected a dictionary for dictionary value @ data['packages']['sm7822b_01']

gray loom
#

im making a template for a fridge magnet, which device_class should i use? is it motion

#

is there a list of device classes

ivory delta
#

A fridge magnet? 😐

#

Not sure I'd consider that a device. More a souvenir.

gray loom
#

is there a way to change the state of an entity, i have a door magnet and would like my entity to show "open/closed" instead of "detected/clear"

ivory delta
#

There we go. That's the information you should have given in your initial post... what it is you're actually trying to show.

#

The device class opening is about... opening things, so open/closed.

fresh ibex
#

Hi. I'm planning to monitor our device usage for the entire month but I want the sensor to start and end at the 28th day of the month. I though I already got it since i got it to work for 3 days, but now its showing me unknown reading from the sensor. This is the code that i used

  • platform: history_stats
    name: Aircon Monthly
    entity_id: switch.aircon
    state: "on"
    type: time
    end: "{{ (now().replace(hour=23, minute=59, second=59)).replace(month=(now().month + 1), day=28) }}"
    duration:
    days: 30
fossil venture
#

Not all months are 30 days long. Also what happens in December? Month = 12 + 1 ?

mighty ledge
oak summit
#

I'm in need of help if anyone cares to lend a hand, I'm trying to figure out how to take a two variables (inputs from a blueprint), one with a time in it (ie 06:00:00) and one with a number of minutes in it (ie 60) and I want to be able to use the time variable minus the number of minutes.

In my searching I found this, https://brianhanifin.com/posts/home-assistant-date-time-template-macros/#subtract_time, but I can't quite figure out how to use it.

I tried to do it this way, https://paste.ubuntu.com/p/tTkrTVMSDy/

But throwing it in devtools / Template gives me TypeError: '>=' not supported between instances of 'int' and 'str'. I'm clearly doing something wrong, but I can't tell what.

dreamy sinew
#

Need to convert that date string into a datetime object and use timedelta() to apply the difference

inner mesa
#

perhaps something like this:

#

{{ (as_timestamp(strptime(time, "%H:%M:%S")) - minutes*60)|timestamp_custom("%H:%M:%S") }}

#

I don't know what types you'll get from the blueprint

dreamy sinew
#

But if you want to compare 2 dates it's better to leave them as dates

oak summit
#

No dates, just a time. So I think what Rob said there should work, I'll play with that a bit and that looks was easier to deal with than that macro thing I saw on brian's site

inner mesa
#

ok, so {{ strptime(time, "%H:%M:%S") - timedelta(minutes=minutes) }}

oak summit
#

Yeah, I have that up, I just wasn't sure how to do subtraction part across two different formats, with one being hh:mm:ss and one just being mm

sacred sparrow
#

sensor:

  • platform: template
    sensors:
    timer_ric3:
    friendly_name: "Timer"
    value_template: "{{ state_attr('timer.cook_rice', 'remaining') }}"

How come the timer doesn't count down?

inner mesa
#

because the remaining attribute is only set when the timer is paused or reset

sacred sparrow
#

ahh I see. How can I get the count down?

inner mesa
#

you can't, really

sacred sparrow
#

when I do "state" instead it just says "active" or "idle"

inner mesa
#

as the docs indicate

#

is your goal to display it in the frontend?

sacred sparrow
#

it displays in the front end but I use "tileboard" to display on a different style of front end and it doesnt work there

inner mesa
#

displaying a countdown is usually done within the frontend itself

#

a more universal timer is one that you maintain manually with an input_number and an automation that decrements the value each second

#

there's probably no way to user a timer to do it

oak summit
#

The template you gave me rob seems to have mostly worked, but (at least while I'm testing it in the devtools / Templates page) it's outputting it with a date, even thought my inputs don't have a date.

inner mesa
#

the first one?

#

this doesn't: {{ (as_timestamp(strptime(time, "%H:%M:%S")) - minutes*60)|timestamp_custom("%H:%M:%S") }}

#

the format at the end just includes the time

#

if you use the second one, I think you need to convert it to a timestamp and then format it like this:

#

{{ as_timestamp(strptime(time, "%H:%M:%S") - timedelta(minutes=minutes))|timestamp_custom("%H:%M:%S") }}

#

but maybe there's a more direct way. There's no strftime

dreamy sinew
#

Timestamp custom is basically strftime

inner mesa
#

You just have to turn it into a timestamp first

oak summit
#

yeah I figured out what I was doing wrong there shortly after I sent that 😅 Now I'm getting errors when trying to import it as a blueprint, but I think I'm just going to go to bed first.

deep citrus
#

any suggestions on how to format a number as currency using markdown / templating ?

#

ie, include commas and prepend $

#

ahh, found it 🙂 {% set total_x = "${:,.2f}".format(total_x) %} {{ total_x }}

ivory delta
silent barnBOT
silent barnBOT
thorny snow
#

the brightness and white values are never sent unless they are what was changed

#

ahh thanks hassbot 🙂

#

according to the device state in developer tools the brightness and white values are kept in the state correctly

#

so I would expect them to always be sent along with the payload regardless of whether they've changed

mighty ledge
#

@gray quailThat's probably the best way to handle it but you need to worry about crossing the year line and that should be added into your configuration. You'll also want to hardcode in your timezone.

mighty ledge
gray quail
#

Yeah, was thinking about how. And solved it with an if block. It does the job, but there's probably a cleaner way.

      {%- if strptime(" ".join([pickup_day, pickup_month, now().year|string, '+0000']), '%d %m %Y %z') < now() %}
        {%- set pickup_year = now().year + 1 %}
      {%- else %}
        {%- set pickup_year = now().year %}
      {%- endif %}
      {{ strptime(" ".join([pickup_day, pickup_month, pickup_year|string, '+0000']), '%d %m %Y %z') | timestamp_local }}
#

Still iterating over the code

thorny snow
#

sent as in: when I click a colour on the wheel, neither the brightness or white_value keys are filled. When I change the brightness, that key is filled, along with whatever the colour is at the time, but white_value is not; when I change the white_value, the colour and new white_value show up but brightness is empty

gray quail
#

Not all colors are sent, only the ones that change

thorny snow
#
{"state": "on", "rgb": [190,0,255], "brightness": , "white_value": 175
} <-- when I changed the white value specifically
{"state": "on", "rgb": [190,0,255], "brightness": 255, "white_value": 
} <-- when I changed brightness specifically
{"state": "on", "rgb": [127,0,255], "brightness": , "white_value": 
} <-- when I change colour specifically
mighty ledge
#

You always have to play the conversion game with time when it's a string

mighty ledge
thorny snow
#

that's what I started with. however the doesn't solve the problem that I cannot send something that is in the state

mighty ledge
#

you've got if red is defined... etc. You'll also need a if brightness is defined

#

and you can pull from itself

thorny snow
#

it should just always send what it knows about those values

mighty ledge
#

it doesn't know anything about those values

#

you have to tell it where to pull the values

thorny snow
#

according to the device state, it does

mighty ledge
#

yes but you have to tell it to the template

#

by using state_attr('sensor.xyz', 'brightness')

thorny snow
#

that's not anywhere in that example?

mighty ledge
#

or light in your case

#

that's part of templating in general

#

to get the current brightness of any entity, you have to grab it from the state machine

#

to access the state machine, you have to use the methods that exist

thorny snow
#

it's also not mentioned anywhere in hte linked template documentation

mighty ledge
#

Yes it is

thorny snow
#

I'm looking at it

thorny snow
#

that is very unclear then

mighty ledge
#

it's coding, you need to read it like an api

#

there are so many possiblities that the docs can't cover it. It would be impossible

#

so you have to 'read the api' and figure out the fringe cases

thorny snow
#

I'm messing with that now yes

mighty ledge
#

attribute's are literally limitless. You can name an attribute anything. Covering all examples would be impossible, that's where you have to read the method to get an attribute then figure out how to use it in the scenario you are trying to provide

thorny snow
#

but why don't I have to do that with the colour values then

#

they always seem to work fine

mighty ledge
#

because you have them in an ifstatement

thorny snow
#

..w.hy does that matter

mighty ledge
#

you're always providing brightness and whitevalue

gray quail
#

"rgb": [190,0,255]

You've hardcoded this line

mighty ledge
#

ah yes, that too

thorny snow
#

yes, I would also always provide colour

#

so ideally I'd rip out all the if statements

gray quail
#

So when no color is provided "rgb": [190,0,255] is sent. That's why you always see rgb

thorny snow
#

and just get a bare json template

#

okay yeah that is a good point

#

you're right

mighty ledge
#

I'd do it this way... (give me a sec to write it out)

thorny snow
#
  command_on_template: |
    {
      "state": "on",
      "rgb": [
        {{ state_attr('avea_proxy', 'rgbw.[0]') }},
        {{ state_attr('avea_proxy', 'rgbw.[1]') }},
        {{ state_attr('avea_proxy', 'rgbw.[2]') }} 
      ],
      "brightness": {{ state_attr('avea_proxy', 'brightness') }},
      "white_value": {{ state_attr('avea_proxy', 'white_value') }}
    }
#

so in theory something like this should work

#

provided I got the key structure right

#

which I can check in the developer part

gray quail
#

You could test it on the template page

mighty ledge
#
  command_on_template:
    state: "on"
    rgb: >
      {%- if red is defined and green is defined and blue is defined -%}
        {{ [ red, green, blue ] }}
      {%- else %}
        {{ state_attr('light.avea', 'rgb') }}
      {%- endif %}
    brightness: >
      {%- if brightness is defined -%}
        {{ brightness }}
      {%- else %}
        {{ state_attr('light.avea', 'brightness') }}
      {%- endif %}
    white_value: >
      {%- if white_value is defined -%}
        {{ white_value }}
      {%- else %}
        {{ state_attr('light.avea', 'white_value') }}
      {%- endif %}
#

super simple, then you don't need to deal with json

thorny snow
#

would be nice, however the other end kinda expects it

#

but yeah I got they key names all wrong so I'll fix that first

mighty ledge
#

FYI this json:

{'a': {'b': 1 }}

is the same as:

a:
  b: 1

in yaml

#

What I wrote will work based on your first template

gray quail
#

😱 I didn't know you could do it that way XD

mighty ledge
#

if your first template worked as json, which it seems like it does

#

json and yaml are interchangable inside yaml

#

you just need to know how to change json to yaml

gray quail
#

Oh my,, got some work to do XD

mighty ledge
#

listed items foo: [ 'a', 'b', 'c' ] are this in yaml:

foo:
- a
- b
- c
gray quail
#

Yeah I worked with JSON and Yaml for years... But didn't know it would convert the command_on_template, etc to JSON when sent

mighty ledge
#

it should

gray quail
#

Let's test

thorny snow
#

okay that is very good to know actually

#

because yes, that would make typing it out a lot less annoying

gray quail
#

It has to be a string according to the docs

mighty ledge
#

I use this an an MQTT payload in my own automations:

    payload:
      args:
      - nodeId: "{{ node_id }}"
        commandClass: 112
        property: "{{ parameter }}"
      - set
      - "{{ [ parameter, value, bytes ] }}"
#

so it definitely has to work

thorny snow
#

well, in theory YAML is basically a string

#

so it should work the same as sending straight JSON

mighty ledge
#

try it, if it doesn't work I can help you with the JSON version

gray quail
#

What schema are you using?

mighty ledge
#

it does make it seem like it will fail validation

thorny snow
#

I'm having some trouble extracting the rgbw_color entries but I'll post what I came up with

mighty ledge
thorny snow
#

yes

#

ah there we go

#
command_on_template: >
  state: on
  rgb:
    {{ state_attr('light.avea', 'rgbw_color') }}
  brightness: {{ state_attr('light.avea', 'brightness') }}
  white_value: {{ state_attr('light.avea', 'white_value') }}
mighty ledge
#

does that work?

#

you're missing a >

#

and quotes

thorny snow
#

I'm plugging it into the config file now so I guess we'll see

mighty ledge
#
command_on_template: >
  state: on
  rgb: >
    {{ state_attr('light.avea', 'rgbw_color') }}
  brightness: "{{ state_attr('light.avea', 'brightness') }}"
  white_value: "{{ state_attr('light.avea', 'white_value') }}"
thorny snow
#

yeah exactly, I caught that newline as well and it's really not necessary

mighty ledge
#

FYI that won't work if you provide rgb, brightness, or whitevalue

#

the version I posted should work with that

#

worse case is you have to convert the template I gave you above into json

thorny snow
#

ah okay, commas are still necessary and apparntly it did not convert to JSON

#

state: on rgb: "(255, 72, 118, 100)" brightness: "99" white_value: "100"

#

values are there though 🙂

mighty ledge
#

aright, then:

  command_on_template: >
    {
      'state': 'on',
      'rgb':
         {%- if red is defined and green is defined and blue is defined -%}
           {{- [ red, green, blue ] -}}
         {%- else %}
           {{- state_attr('light.avea', 'rgb') -}}
         {%- endif %},
       'brightness':
         {%- if brightness is defined -%}
           {{- brightness -}}
         {%- else %}
           {{- state_attr('light.avea', 'brightness') -}}
         {%- endif -%},
       'white_value':
         {%- if white_value is defined -%}
           {{- white_value -}}
         {%- else -%}
           {{- state_attr('light.avea', 'white_value') -}}
         {%- endif -%}
    }
thorny snow
#

why all the ifs, btw

mighty ledge
#

because if they aren't provided in your service call, then you add them yourself

#

for example, if you just change the color... they aren't provided in the service call

#

and vice versa

#

so on the surface you just change the brightness but under the hood it sends the color brightness and whitevalue

thorny snow
#

ah small change

mighty ledge
#

now you rpobably need to change the logic for the rgb and the whitevalue

#

and use one or the other

thorny snow
#

the key containing the colour information is rgbw_color

mighty ledge
#

ah

#

ok

gray quail
#
command_on_template: >
  { "state": "on"
  , "red": {{ red|default(state_attr('light.mqtt_dmx_right', 'rgb_color')[0])) }}
  , "green": {{ green|default(state_attr('light.mqtt_dmx_right', 'rgb_color')[1])) }}
  , "blue": {{ blue|default(state_attr('light.mqtt_dmx_right', 'rgb_color')[2])) }}
  , "dimmer": {{ brightness|default(state_attr('light.mqtt_dmx_right', 'brightness')) }}
  }
mighty ledge
#

ah yes, that would also work

#

using default over the if statement

#

probably a more condensed route

thorny snow
#

heck if that is the case I can just rip out white_value altogether since it's in the array already

#

ohh that's a nice trick 🙂

silent barnBOT
thorny snow
#

wait for the link

#

there we go

#

that's the result for now I think

gray quail
#

You don't need the - in {{...}} blocks

thorny snow
#

yeah, probably. it came from the examples

gray quail
#

I think this still does not work as you wanted

thorny snow
#

I need to read up on jinja wrt the minuses everywhere

mighty ledge
#

depends on what characters are between the {{ }}

#

{{ }} , {% would require the -'s

thorny snow
#

ah yes that was to strip whitespace

#

there we go

gray quail
#

@thorny snow RGB will never be sent. Because white_value and ( red, green, blue) are never sent in one message

thorny snow
#

a missing |list was all that was needed

#

well, funny thing is, it will, because the light works in rgbw mode

#

so the white value is automatically in that same list of rgbw_color

gray quail
#

Ah offcourse

thorny snow
#

therefore I can move the check into that section

#

of course now I have to rewrite the parser, but I had to do that anyway

#
{
  'state': 'on',
  'rgb':[255, 0, 191, 110],
   'brightness':199
}
#

but that looks very neat

#

and parseable, which is nice 😄

#

okay now you're just showing off 😛

gray quail
#

Nah made an error 😉

#

And I'm bored 😉

#

Wouldn't it be easier to parse when sending all the values as a separate key/value pair?

thorny snow
#

doesn't really matter

#

I need all four values together anyway

#
        let bulb_color_w = that.settings.color[3] && that.settings.state;
        let bulb_color_r = that.settings.color[0] && that.settings.state;
        let bulb_color_g = that.settings.color[1] && that.settings.state;
        let bulb_color_b = that.settings.color[2] && that.settings.state;

I suppose this makes for some more consistent reading

#

that.settings.state here is a bitmask btw

#

just in case you were wondering what the hell was going on there

gray quail
#

let r, g, b, w = that.settings.color

JS is not my thing, but would this be possible?

thorny snow
#

in python I think so, but not in plain JS

#

although EMCAscript 6 might have added something like that

gray quail
#
const [red, yellow, green] = foo;
console.log(red); // "one"
console.log(yellow); // "two"
console.log(green); // "three"
thorny snow
#

but my programming days are a bit behind me 😛

ivory delta
#

Depends if you're working with an array or an object but both can be 'destructured'. The syntax is just a little different for each.

#

And yes, I believe those were introduced with ES6, so there's support for them on pretty much every platform/browser.

thorny snow
#

okay so yes, I guess I can do that 😄

dusty sluice
#

im finely get my rely to work, but dont like the card in HA. just have a button. I wolde like to have 2 arrow one for upp and one for down, but dont know how to creat it. i just have 1 entiy of it

thorny snow
#

you can create a vertical stack with two buttons in it

#

and give each an icon and an action

silent barnBOT
thorny snow
#

something like that.

weary drift
#

Don't know if this is the correct place. But if i have blinds (cover) that wont work with open/close but position works. Could i modify the entity card so that up sets position x and down sets position z?

astral pebble
#

Maybe #frontend-archived would be better for the card stuff, but if you want to create a new entity here is the right place

weary drift
#

Oh there's "Template cover". Didn't know that existed. I'll look into it first and see if it works.

weary drift
#

Works pretty good. Still the problem with if i open the cover the Up button is greyed out when i press stop. I guess i want it to say opening and closing until the position is reached. Now i set position 100 and if i press stop in the middle it's still at 100.

ivory delta
#

It can't know whether it successfully opened all the way or not if you don't give it a value_template 😉

#

It has to guess. You told it to go up, so it must have gone all the way up.

weary drift
#

Yeah that's true.

#

I was thinking about making an ugly solution and set the values at 99 and 1 instead of 100 and 0.

#

But since i'm giving it the "go to 100" how would a value_template check the position if it still thinks the position is 100?

ivory delta
#

Forget the template sensor for a moment. How does HA know the position of the cover?

weary drift
#

I guess it gets it from the device from the Local Tuya integration. If i set a position with the entity created by the integration it'll go there and i have it as an attribute at the entity.

#

The original problem is that it's stuck at opening/closing and wont change the position status if i use the open/close commands instead of position.

ivory delta
#

Ok. Go check that. See if HA can read the position value.

weary drift
#

Aah right. I don't think HA can i'm afraid.

ivory delta
#

Then that's your problem. Computers are amazing but they need information to work.

weary drift
#

I checked the integration where the "current position" is supposed to be. But just "0" when i've set a value.

#

I might get different result by flashing it with Tasmota.

#

But the TuyaSmart app have the information. So it's the integration that does not get it.

ivory delta
#

The integration can only get what it's allowed to get. Lots of these cloud-based apps don't expose all the same information and functionality for other things to see.

#

Tasmota/ESPHome is usually a better idea where possible, then you have full control.

weary drift
#

Yeah i need to read up on that. And if it works on the devices I've got.

#

Thanks a lot anyway! At least i know in what direction to look.

hybrid spoke
#

Hello everyone!
I am trying to configure a Modbus device into HA and I am receiving messages in "ASCII"} for example, which need to be converter to decimal to show the real value 112510 could someone help me?

#

I was trying to convert it first to hex because then i knew how to convert it to decimal and the best I came up with was {{ value_json.encode('ascii') }} but is not entirely converting the payload b'\x01}'

astral pebble
#

does from_bytes work?

hybrid spoke
#

as {{ value_json.from_bytes }} ? no

astral pebble
#

Do some research on the function to find how to use it and then see if it works

paper root
#

why am I getting a million template variable warnings

#
    name: "APDS-Right"
    state_topic: "tele/OpticalUnit_F041D4/SENSOR"
    value_template: "{{ value_json['APDS9960'].Right}}"
    payload_on: "1"
    off_delay: 3
    device_class: moving```
#

if its some helper feature like I saw how can I disable that

#

Since its really annoying

#

No I cant change it to be multiple topics so dont recommend me that, im using tasmota

paper root
#

The problem I have is that tasmota has 2 modes for the APDS-9960

#

Gesture mode and rgbc+lx mode

#

so if I change modes the gesture message basically dissapears in the next message

viscid vigil
#

Hey, afternoon. I'm using a command_line switch to control a wifi switch via an API. I can get the Command on and command off to work fine as it uses a PUT request and passes "data" -d. however, the state command requires data from a GET request. Short version is, can I use home assistant attribute values in a GET request (within the URL) ? The put is working but the GET isn't (the put doesn't require the attribute value in the URL, the GET does)

pastel moon
#

Is there a better way to define this? I basically want "sensors" for 'Day, Soft & Night'

Day: condition: "{{ states('sensor.daylight'), 'golden_hour_1' | 'solar_noon' | 'golden_hour_2' }}"
Soft: condition: "{{ states('sensor.daylight'), 'sunrise_start' | 'sunrise_end' | 'sunset_start' | 'sunset_end' }}"
Night: condition: "{{ states('sensor.daylight'), 'dusk' | 'nautical_dusk' | 'night_start' | 'nadir' | 'nautical_dawn' | 'dawn' }}"
paper root
#

im giving up this is impossible

dreamy sinew
#

@pastel moon what are you trying to accomplish? What is the expected output of this?

#

@paper root is that key flipping in and out of that payload? If so, seems like a poor implementation on the other side and you're just kinda stuck with it

#

might be able to hack around it but its still a hack

paper root
#

yeah its flipping in and out of payload

#

APDS_9960 has 2 modes in tasmota

#

Gesture and sensor

dreamy sinew
#

you'll have a bad time integrating directly then

paper root
#

any other way I could do that?

dreamy sinew
#

create a sensor from the full payload, an automation that posts to new mqtt topics for both keys, sensors that watch those new topics

paper root
#

yeah nevermind

#

seems like a shoddy implementation to me so ill figure something out

dreamy sinew
#

the shoddy side is on the end device

pastel moon
paper root
edgy umbra
#

Anyone see whats wrong with this template? 🙂

#
    if (states['light.designlamp'].state == "unavailable") return 'Niet Beschikbaar';
    else return 'Helderheid: ' + [Math.round](states['light.tvlamp'].attributes.brightness / 2.55) +  '%';
  ]]]```
dreamy sinew
#

its not a template as it sits

#

also you're mixing things all over the place

inner mesa
#

I'm not a JS guy, but this looks weird: [Math.round](states['light.tvlamp'].attributes.brightness / 2.55)

edgy umbra
#

Yep there is a problem but can't seem to figure it out

#

This is the original which works fine but i want to add a else state...

#
  [[[
    var bri = states['light.tvlamp'].attributes.brightness;
    return 'Helderheid: ' + (bri ? Math.round(bri / 2.55) : '0') + '%';
  ]]]```
ivory delta
#

The problem is that it's not valid JS 🤷‍♂️

#

Math.round(number) is a function. That backasswards syntax you've written isn't even JS.

edgy umbra
#

I want to have the brightness but if the state of that light is unavailable i want to have "Not Available" instead of the brightness

ivory delta
#

We know.

edgy umbra
#

🙂

ivory delta
#

Your intent is clear. Your JS is... terrible.

#
return (states['light.designlamp'].state == "unavailable") ? 'Niet Beschikbaar' : `Helderheid: ${Math.round(states['light.tvlamp'].attributes.brightness / 2.55)}%`;```
#

That's a one-liner, btw. Don't go adding line breaks.

#

I don't know how the cards handle random line breaks.

edgy umbra
#

I have added this but now it says brightness: NaN%

#
  [[[
    return (states['light.designlamp'].state == "unavailable") ? 'Niet Beschikbaar' : `Helderheid: ${Math.round(states['light.tvlamp'].attributes.brightness / 2.55)}%`;
  ]]]```
#

It's for the custom:button-card

ivory delta
#

Then you need to break it down and see why Math.round(states['light.tvlamp'].attributes.brightness / 2.55) isn't a number.

#

I'd guess if the light is off, it has no brightness...

edgy umbra
#

Normally it says brightness: 0% if it's off, just tested with the light on but still give NaN%

ivory delta
#

🤷‍♂️

#

states['light.tvlamp'].attributes.brightness can't be a number or that would work fine.

#

Forget the UI. Check the Dev Tools.

edgy umbra
#

Thanks going to check it there. 🙂

ivory delta
#

Makes me wonder why you didn't just write the rest with ternary too 🤷‍♂️

#

Or this for simplicity:

return (states['light.designlamp'].state == "unavailable") 
  ? 'Niet Beschikbaar' 
  : `Helderheid: ${Math.round((states['light.tvlamp'].attributes.brightness || 0) / 2.55)}%`;```
edgy umbra
#

To be honest, i have zero js knowledge and just trying to build on excisting code, that's also the reason why i strugle so hard with this. 🙂

ivory delta
#

Default the brightness to 0 so it doesn't explode Math.round()

hybrid spoke
#

Hello everyone!
I am trying to configure a Modbus device into HA and I am receiving messages in "ASCII"} for example, which need to be converter to decimal to show the real value 112510 could someone help me?
I was trying to convert it first to hex because then i knew how to convert it to decimal and the best I came up with was {{ value_json.encode('ascii') }} but is not entirely converting the payload b'\x01}'

edgy umbra
ivory delta
#

I told you already. It's because states['light.tvlamp'].attributes.brightness isn't a number. You need to figure out why.

edgy umbra
#

Ok i'm going to try find out how i can solve that. Thanks for your help.

#

Got it working with this, now i only need to figure out how to round the brightness. Because now it's at 55% and it shows like 140. 🙂

#
    if (states['light.designlamp'].state == "unavailable") return 'Niet beschikbaar';
    else return 'brightness: ' + states['light.designlamp'].attributes.brightness;
  ]]]```
ivory delta
#

Well... that's just maths again...

#

But if it's not a number, it's likely to blow up 🤯

#

Humour me... use this as your template instead:
return typeof states['light.designlamp'].attributes.brightness;

coarse blaze
#

@hybrid spoke i would be interest to know how you gonna figuer out to decode ascii to decimal, im assuming thatyou will need to convert to hex and then dec {{ value_json.encode('ascii') }}
wondering why you get those b'\x01}'

#

dont think that would be easy to do it

edgy umbra
ivory delta
#

Would you like to share how?

dreamy sinew
#

nah, gotta go full stackoverflow in here

frank gale
#

@edgy umbra in which programming language is that?

dreamy sinew
#

this is JS

#

not anything to do with "templates" as used by automations etc

edgy umbra
#

Sorry about that, i thought this was also a template.

dreamy sinew
edgy umbra
#

Thanks i will post anything related to this in frontend next time.

frank gale
#

So I have a MQTT topic /this/that/there
The: /this/that is always the same, only /there changes. Can I use a template that listens to /this/that and add a list o attributes to a sensor like:
`- there1 : attributes

  • there2: attributes `
    etc ?
ivory delta
#

Templates don't listen to topics. Integrations do.

frank gale
#

then i got to integrations 😄

#

*go

#

or where I ask about a sensor template question?

ivory delta
frank gale
#

Then I'm in the right place, I need a template for my sensor, I already wrote that 😄

ivory delta
#

🤦‍♂️

#

Templates don't do what you're asking for.

#

Templates don't fetch information from MQTT...

#

Sensors do that 😉

inner mesa
ivory delta
#

You mean they should use a sensor? 🤯

frank gale
#

thanks!

marble trench
#

I could use some assistance. I am trying to add the workday sensor, and I am getting this error when I validate my config "Platform error sensor.workday - No module named 'homeassistant.components.workday.sensor'"

#

I added the following to my binary_sensors.yaml

  • platform: workday
    country: US
ivory delta
#

It sounds like you added it to your sensors, not binary sensors.

inner mesa
#

It looks like you put it under sensor:

marble trench
#

Wow, thanks so much. I had originally put it in sensors and then moved it to Binary after realizing that it needed to be there. Apparently never saved the sensors.yaml to commit the changes. Guess that was an hour of googling wasted.

ivory delta
#

It happens

#

I don't want to admit how many hours I've spent troubleshooting typos.

true otter
#

hey guys is the such a thing as an input_select template?

#

I am trying to create a single Input_select template entity for all my sonos players. I have come up with this template: media_player: - platform: template media_players: current_source_template: "{{ states('input_select.media_player') }}" data_template: > {% if is_state("input_select.media_player", "Office Sonos") %} media_player.sonos_connect {% elif is_state("input_select.media_player", "Kitchen/Dining Sonos") %} media_player.kitchen_dining {% elif is_state("input_select.media_player", "Patio Sonos") %} media_player.patio {% elif is_state("input_select.media_player", "Denon AVR-X4500H") %} media_player.denon_avr_x4500h {% elif is_state("input_select.media_player", "Jeffery") %} media_player.googlehome1790 {% endif %}, but I don't know how to test it an make sure it works and it is not showing up in Dev-Tools.

thorny snow
#

Good evening all. Looking for assistance on a template This pulls the condition from NWS. I'd like to evaluate this to see if "rainy" = true. Not quite sure how to achive that. {{ state_attr('weather.korh_daynight', 'forecast')[0].condition }}

ivory delta
warm isle
#

I always forget how to handle timestamps.
I try to get a sensor up wich is showing me in how many hours I got until the lights turn on (in the hope that I see the number and go into the bed out of fear of the short night. but I currently fail to get a timestamp (where I can substract ``now()` from) out of my sensor.
currently so far

{{( ((now()+timedelta(days=1)).strftime("%Y-%m-%d ") ) + strptime( states('sensor.alarm_time1'), '%Y-%m-%d %H:%M:%S.%f') ) }}```
== 2021-05-05 06:36 
  (i know, adding a day to it is'nt even a good idea, but currently the only one I got)

adding `.timestamp()` after does not work as expected
fast mason
#

The filter option for logger: uses regex right?

copper seal
#

Hello guys, quick question: regex_search("<enabled>true</enabled>\n<normalizedScreenSize>") is it the break line correct?

dreamy sinew
#

make it work there and then use what you work out

main vortex
#

Is there a generic way to get the parent device of an entity? e.g. the parent camera entity for a binary_sensor. Use case is to setup a motion trigger for a camera's binary sensor motion entity and resolve the related camera to send a push notification.

ivory delta
#

Not directly. The information you're after can be retrieved via the API but that's a faff. Are the names of your entities similar enough that you can just match them by patterns?

main vortex
#

Probably, but I was hoping for something more robust.

ivory delta
#

If they follow a systematic naming convention, that's going to be simpler.

#

I'd say this is the robust way. Fewer pieces to get wrong.

main vortex
#

I'll give that a shot 🙂

oak summit
#

How do I combine these two seperate true false checks into a single one that only outputs true if they're both true?

{{ state_attr('media_player.living_room_tv', 'app_name') == "Netflix" }}
{{ is_state('media_player.living_room_tv', "playing") }}
gray quail
#

I've got a webscraper that gets the day and month the trash is collected. I've extracted the value and constructed a DateTime. Would I save this as the state, or am I missing something?

ivory delta
#

{{ state_attr('media_player.living_room_tv', 'app_name') == "Netflix" and is_state('media_player.living_room_tv', "playing") }}

trail ginkgo
#

I'm trying to create a reusable "battery level" icon_template, but when defining this as part of a sensor configuration ... how do i refer to the value of the sensor itself inside the icon_template ?

night warren
#

Quick question....I want to use the current time in a notification

data: message: 'Test at {{now().hour}}:{{now().minute}}' data: timeout: 20

But the minute doesn't show as 02, 03 etc. When it is single digit minutes of the hour.

trail ginkgo
#

I believe you should look at strftime

night warren
#

Ta!

pastel moon
#

I need a condition for a template sensor and have tried this

condition: "{{ is_state('sensor.period_of_day', 'dawn' | 'night') }}"

which did not work. I have tried to search for a hint... Please help

charred dagger
#

Try is_state(..., 'dawn') || is_state(..., 'night')

pastel moon
#

Ah, thanks! Will do

dreamy sinew
#

or states(...) in ['dawn', 'night']

pastel moon
#

That is niice! Like it! Thanks! 🙂

bleak trail
#

How to format date object to dd-mm-yyyy, currently in HA it is showing in ISO format yyyy-mm-dd?

#

I'm using config-template-card to create the graph

mighty ledge
#

Depends where you see that date

bleak trail
#

type: 'custom:config-template-card' variables: DATE: 'states[''sensor.eloverblik_energy_total''].attributes.metering_date' card: type: 'custom:mini-graph-card' name: '${"Strømforbrug d. " + DATE}'

#

I would like to do date formatting on DATE variable

mighty ledge
#

You have 2 options, format the date using js or make a template sensor that pulls the date from the attribute and formats it using python/jinja

#

In both cases you’ll need to make a datetime object or timestamp then convert that to a date string

bleak trail
#

Do you have a link on how to add JS in template ?

ivory delta
#

You already know how:
name: '${"Strømforbrug d. " + DATE}'

#

This is template literal: ${}. Anything you do inside those curly braces can use JavaScript.

patent flame
#

How to avoid 0 value when unavailable entity?

#

It should not have dot instead of 0 value...

jagged obsidian
#

0 value in lovelace or ?

#

what's the use case?

dreamy sinew
#

"unavailable"|float -> 0

patent flame
patent flame
ivory delta
#

You want to skip that datapoint instead of treating it as zero?

stiff fjord
#

hey, is there any possibility to iterate in a template only over the entities of a specific integration?

dreamy sinew
#

integration is not typically known by the state object

bleak trail
#

Thx @ivory delta , I have changed my lovelace mode to YAML and added following code to name:
name: > {% set date = as_timestamp(strptime(state_attr('sensor.eloverblik_energy_total', 'metering_date'), "")) %} {{date | timestamp_custom('%a, %d %b %Y')}}
But the result is just code and when I try it in Developer Tools it shows correct out -> "Tue, 04 May 2021"

ivory delta
#

Well that's Jinja... you can't use Jinja in the frontend.

bleak trail
#

doesn't Jinja run in templates?

ivory delta
#

In the backend, sure.

#

In Lovelace... nope.

#

Your browser doesn't understand Jinja. Browsers basically only know HTML, CSS and JavaScript.

bleak trail
#

I thought it would convert Jinja before sending to the browser.

ivory delta
#

How would it do that? The states change.

#

Anyway... this is a discussion for #frontend-archived. Either way, go figure out the JavaScript you need for what you want.

bleak trail
ivory delta
#

I don't think you can do that with the built-in history graph card. You probably need to look at custom graph cards or use something like Grafana.

inner mesa
#

the best you can do is remember the last value and repeat it if you don’t want a discontinuity

ivory delta
#

Which is still a guess and therefore bad data... arguably the better option is to find better graphs.

patent flame
#

0 ruins the graph scale...

#

If you have a value arround 50.000 and then you get a 0...

inner mesa
#

That’s why I recommended repetition. You can’t pretend that a state change didn’t happen

patent flame
#

I have other graphs that simply dont have a value to that point.

#

If you repeat the value and the entity id always unavailable then you wont know...

inner mesa
#

I have no solution, then

ivory delta
#

If your current tool doesn't work for what you need, use a different tool.

patent flame
#

Ok then...

thorny snow
#

if entity > 0

#

value_template: >-
  {% if value_json.entity|int > 0 %}
     {{ value_json.entity }}

inner mesa
#

is that an answer to something?

#

it's not a good one 🙂

ivory delta
#

My favourite part is that when it doesn't satisfy the if, it'll return None instead and still be treated as zero.

thorny snow
#

NaN

inner mesa
#

what are you trying to do? you just posted a broken template with no context

plain zinc
inner mesa
#

that's great!

#

it'll be a breaking change, though

dreamy sinew
#

yeah, that might cause a lot of pain

inner mesa
#

the good kind of pain?

dreamy sinew
#

no, the bitching kind

inner mesa
#

should have been that way from the start

dreamy sinew
#

its a good change but this would break a lot of people

plain zinc
#

I've flagged it as such

dreamy sinew
#

right, but that could be a barrier to acceptance

inner mesa
#

could add "typed_xxx" like I was suggesting for the input_xxx, but that gets messy when there are a bunch of existing attributes

dreamy sinew
#

i was thinking of just adding them under a sub_dict

plain zinc
#

I'd be happy with a separate set of attributes, it's a non-issue from my perspective

dreamy sinew
#

state_attr('thing', 'time_objects').next_dawn

inner mesa
#

yeah, could do that

dreamy sinew
#

that way you could have both for a while

#

and start a deprecation process

plain zinc
#

I'll start that conversation on the PR.

bright quarry
#

In the previous release, we introduced a trigger-based template sensor. This release extends on that features by adding support for trigger-based binary sensors using templates.
can someone simplify this for my pigeon brain

plain zinc
inner mesa
#

it's a little different in that it's duplicating the state in a typed attribute, but it might be nice to have a common way to represent typed attributes

#

it's kind of a mishmash now

#

plus, I guess all attributes are "typed", just not always to what you want or expect 🙂

plain zinc
#

String is a type 😛

silent barnBOT
wide widget
#

Can anyone tell me why this template returns "Unknown" instead of "None", yet every other status works fine?

      value_template: >
        {% if is_state('sensor.brodie_occupancy', 'Home') and is_state('sensor.sarah_occupancy', 'Home') %}
          Both
        {% elif is_state('sensor.brodie_occupancy', 'Away') and is_state('sensor.sarah_occupancy', 'Home') %}
          Sarah
        {% elif is_state('sensor.brodie_occupancy', 'Home') and is_state('sensor.sarah_occupancy', 'Away') %}
          Brodie
        {% elif is_state('sensor.brodie_occupancy', 'Away') and is_state('sensor.sarah_occupancy', 'Away') %}
          None
        {% else %}
          Failed
        {% endif %}
inner mesa
#

‘None’ is a special term now that templates return typed values

#

It ends up as ‘unknown’, and I think your only easy option is to choose a different word

#

Change it to ‘Nothing’ and see if that works

wide widget
#

yep. that did it. thanks

marsh lynx
#

Good morning -

In my lovelace UI I have added a simple on/off switch for my switchbot, however i need to improve it by incorporating some logic whereby the binary_sensor.heating_power_state value is read first, before toggling the switch respectively.

If the binary_sensor.heating_power_state is already on, the switch in the UI should be in the **ON **position, and clicking the switch will turn it **OFF **(which will subsequently set binary_sensor.heating_power_state to off too.

My thinking is that if I can get this logic working, I'll prevent turning off the heater when it is already off (and inadvertently turn it on by accident).

If this makes sense to anyone, is anyone willing to help me put together an automation or script?

marsh lynx
silent barnBOT
wide flame
#

Hi all...

I'm having problems templating roller blind position inside an automation. If temperature goes above 21 degrees the position should be 100, else 0.
{{% if states("sensor.aeon_trisensor_balcony_temperature" | float > 21) %}}

Complete automation is here:
https://paste.ubuntu.com/p/4BxrJGHzQZ/

In developer tools i get TemplateSyntaxError: unexpected '%'.
Any ideas are welcome. 🙂

jagged obsidian
#

its {%

wide flame
#

Oh man... thanks! 🙂

wide flame
#

HA is still not happy.
After removing the excess { I get

AttributeError: 'bool' object has no attribute 'lower'

fossil venture
#

That error is not from the automation you posted. It has no |lower filter.

wide flame
#

But why do I get that error from Template under Developer Tools when I paste the automation?

wide flame
#

Solved it! 🙂
{% if states.sensor.aeon_trisensor_balcony_temperature | float > 21 %}

jagged obsidian
#

{% if states("sensor.aeon_trisensor_balcony_temperature") | float > 21 %}

silent barnBOT
plain zinc
wide flame
mighty ledge
#

@marsh lynx your value template should get the state of the sensor, not the switch

#

You should be using states method, not state_attr

#

On the binary sensor

marsh lynx
mighty ledge
#

And?

#

None of that matters

#

Use the states method in the value_template. Don’t use state_attr. Only provide it the binary_sensor entity_id

#

Also, you’ll have to change your toggle service to switch.turn_on and off inside the respective areas in the switch template

silent barnBOT
mighty ledge
#

Please stop posting code walls, use a code sharing site

silent barnBOT
#

Please use https://paste.ubuntu.com/ to share code or logs. Please don't use Pastebin, since it can randomly add spaces to the main view.

mighty ledge
#

And yes, that config looks like it should work

inner mesa
fading bear
#

So i've got a scrape sensor which pulls a verbal date from a website (it's bin collection time again) for example "WASTE + FOOD WASTE Saturday 8 May". I'm struggling to work out how to translate this into a date and type which i can interact with via automations etc. I'm guessing it'll turn into a sensor with the bin type, and the date as an attribute. Anyone willing to help me with this? I just can't seem to work it out

marsh lynx
pastel moon
#

I really would appriciate some help. Been at this value sensor for hours and havn't got it working... The if's are now just place holders of what I'd like to achieve

        value_template: >-
          {% set cTime = now().hour %}
          {%- if cTime cTime is between 6 & 8 -%}
            state1
          {%- elif cTime is between 9 & 10 -%}
            state2
          {%- elif cTime is between 11 & 15 -%}
            state3
          {%- else -%}
            state4
          {% endif %}
#

Any pointers/help much appriciated

dreamy sinew
#

6 < cTime < 8

#

<= if you want inclusive

#

cTime in [9, 10] with just the 2 values

pastel moon
#

Yes, I forgot that, I have tried to read on this... Thank you! Will try this 🙂

pastel moon
#

Hm. Using this

      value_template: >-
        {% set cTime = now().hour %}
        {%- if 6 <= cTime <= 8 -%}
          stage1
        {% endif %}

I get the error

Error: Testing configuration at /config
Fatal error while loading config: argument of type 'NoneType' is not iterable
Failed config
  General Errors: 
    - argument of type 'NoneType' is not iterable
#

if commenting it out "ha core check" completes successfully...

dreamy sinew
#

likely unrelated

pastel moon
#

Agreed it seems unlikely to be related, but as it works without this part... Well, which channel should I post a Q about this?

#

Yep. found it. An indentation issue. Thanks for the help!

acoustic arch
#

hello all. Count anyone point me in the right direction for the following?

I would like a notification IF a window is still open when i leave home. I would also like to know which one.

#

I think i need a template for that, but im unfalimiair with the syntax of it

#

i got a group going which gives me ON/OFF if any sensor is open

pastel moon
#

How can I test if any light is on using templates?

dreamy sinew
#

states.light|selectattr('state', 'eq', 'on')|list|length > 0

pastel moon
#

Wow 🙂 Interesting! Will try. Thanks!

silent barnBOT
unique gyro
#

Woops a bit longer than I taught.

#

I’m trying to debounce a noisy ZigBee sensor using the new binary sensor template in HA but i’m not sure how it should be formated, i’ve come up with this but is does not seem to work : https://paste.ubuntu.com/p/nXKmwPHMp7/

ivory delta
#

That's... not a template 🤔

unique gyro
unique gyro
#

There doesn’t seem to have any documentation either about it outside the 2021.05 release. 😕

wet pulsar
#

Is it possible to use a template reading an input slider to adjust an entry in the config? Specifically the confidence level for an image processor.

fossil venture
#

The options documentation for the integration will list if they take templates or not.

jagged obsidian
#

is there a way to know which unit for temperature homeassistant is using that can be used in an automation or template for a true/false result?

mighty ledge
jagged obsidian
#

can an automation know in any way whether the instance of homeassistant the automation is ran on uses Fahrenheit or Celsius because if for example the automation sends a number value somewhere where only one unit is accepted

mighty ledge
#

it's not accessible through templates

jagged obsidian
#

oke

mighty ledge
#

but just hardcode it

#

it's not like it's going to change

jagged obsidian
#

blueprint

mighty ledge
#

check the sensor / device it's coming from

jagged obsidian
#

its a number entity with no unit

#

making 2 blueprint seems to be the way

mighty ledge
#

or a blueprint and a sensor template

jagged obsidian
#

you cannot simply import or add a template sensor using UI

mighty ledge
#

is that a requirement?

jagged obsidian
#

i'm not making it for myself, i'm trying to make accessible blueprints so beginner users can just import it and it runs

fluid thorn
jagged obsidian
#

That looks simple enough

acoustic arch
#

hello!

    'eq', 'on')|map(attribute='name')|list|join(', ') }}```

How can i put these group items on seperate lines each? Some kind of linebreak thing?
#

also. is it possible to exclude one by name of do i need to make a seperate group for it?

#

@fluid thorn thats exactly what im doing with this template lol

#

im trying to get a notification with open doors/windows.

#

i can remove |join(', ') but that will print ugly brackets

nocturne chasm
#

Make a group without the entity you want and go to dev tool / templates to play with your template.

#

here is a hint:

{{ expand('group.deurenraamsensor') | selectattr('state', 'eq', 'on')|map(attribute='name')|list|join('\n') }}
acoustic arch
#

Oooooo /n is the line break?

#

I'll check when home

inner mesa
#

{{ expand('group.downstairs_lights') | selectattr('state', 'eq', 'on')|map(attribute='name')|list|join('\n') }}

#

other slash

burnt zephyr
#

how would i do a wait template for a variable called input_boolean.pause_tour for the off state?
i tried a few things based off of examples and I cant seem to get it to work.

solar lodge
#

Any idea why this automation to change brightness doesnt work?:trigger:

  • platform: state
    entity_id:
    • light.recibidor
      to: 'on'
      for: '00:00:5'
      condition: []
      action:
  • service: light.turn_on
    data:
    entity_id: '{{ trigger.entity_id }}'
    brightness: 69
#

If I do turn_off instead it does work

plain zinc
#

@inner mesa So I'm back to working on getting my template the "hard way" to work via {{ strptime(states.sun.sun.attributes.next_setting, "%Y-%m-%dT%H:%M:%S") - now() }} but am getting TypeError: unsupported operand type(s) for -: 'str' and 'datetime.datetime'

Am I crazy or is strptime busted?

#

I could be using it wrong, but I'm not thinking so...

#

It's gross, and I don't feel it matches what the documentation suggests strptime does, but I've worked around it to the same result shakes fist

https://hatebin.com/hwmaflhvpb

inner mesa
#

I've been playing with strptime and I haven't been able to get it to return a datetime either

plain zinc
#

Maybe I'll focus my efforts there to simplify my template

#

Thanks for the "i'm not crazy" check.

inner mesa
#

I think it's a problem with the format string, but it's not easy to debug in devtools -> Templates. It claims that everything is a string

plain zinc
#

oh possibly jinja2 needing a literal % modifier?

inner mesa
#

this works:

#

{{ strptime(as_timestamp(state_attr('sun.sun', 'next_setting').split('.')[0])|timestamp_custom("%H:%M:%S"), "%H:%M:%S") - strptime(as_timestamp(now())|timestamp_custom("%H:%M:%S"), "%H:%M:%S") }}

#

strptime() returns the string if it can't parse it

ivory delta
#

Or a neater way:

{{ sec//3600 }}h{{ sec%3600//60 }}m```
#

You just need both to be the same type. Make both timestamps.

inner mesa
#

timestamps generally seem easier to use

ivory delta
#

Everything is just timestamps. Dates and string formatted dates are just eye candy.

#

Epoch time ftw.

plain zinc
#

it's just frustrating that the docs don't line up.

#
b{{ strptime(states.sun.sun.attributes.next_setting, "%Y-%m-%dT%H:%M:%S.%f+%Z") }}```

returns:
```A2021-05-10T00:36:07.625034+00:00
b2021-05-10T00:36:07.625034+00:00```

Just both strings.
inner mesa
#

but my example above proves (I think) that if you format the time in a known way and then parse it with that string, it returns a datetime that can be used in math

ivory delta
inner mesa
#

devtools -> Templates says a datetime is a string

ivory delta
#

Both work as expected until HA casts the types.

inner mesa
#

{{ now() }}

plain zinc
#
``` Doesn't work though :/
#

I wouldn't expect a pre-cast to happen in the math operations

#

|as_timestamp works.... it's just annoying

#

ok my kid just woke up, time to give my SO a break.

Thanks for the "i'm not crazy" check

swift summit
#

I'm trying to get the state out of a helper called input_text.announcement and put it in a message: {{ trigger. .what? }} I have tried so many combinations now and always get '[object Object]': null which makes me think it is not getting recognised. I'm assuming from the examples trigger represents the trigger of the automation. If I do it in VisualCode instead it just makes the script unavailable in the editing so is suspect causes it to break.

ivory delta
#

You still haven't done what Rob asked... share what you're doing.

#

There's a whole lot of guessing on your side already and you're expecting us to guess too.

swift summit
#

not really. I'm trying to figure out what the bot means by paste using ubuntu! not intuitive at all!

ivory delta
#

🤔

inner mesa
#
  1. go to the link 2. paste what you're trying and isn't working 3. share the link
swift summit
#

got it

ivory delta
#

Your code is not the same as the examples.

inner mesa
#

you need to surround the template in quotes

ivory delta
#

message: {{ trigger.to_state.state }}
is not the same as
message: '{{ trigger.to_state.state }}'

#

Hence HA telling you it's an object (curly braces mean an object).

swift summit
#

Makes sense. I had tried "" but not go. You are 100% right though. Now working. Ta for the help. Quick question in the example it uses message: > then has the message on the next line without speech marks. Does the > tell yaml this is a string.

ivory delta
#

No, it tells it that it's a multi-line entry (and therefore will always be treated as a string and needs no quotes).

#

YAML cares about whitespace and linebreaks.

swift summit
#

Awesome, that could come in handy. When it is multiline does it then treat the line ends as \n or just ignore as one big string no matter how many lines?

silent barnBOT
#

YAML is the mark up language used by Home Assistant, consistent indenting (two spaces per level) is key. Here is a primer, and this explains multi-line templates. For validating YAML see YAML Lint.

ivory delta
#

More info there. It's not specific to HA, so there's plenty of into on the internet.

swift summit
#

Ta mono. Today was the first time I've got around to playing with Yaml for anthing other than config so lot to learn. My missus wanted something to allow her to message me hence the automation attempt 😉

acoustic arch
#

i well its working. Ill separate it with a slash i think

carmine stag
#

Hey there! I have a lovelace card that shows a historical graph of a utility meter, but I'd like to change the actual value that's shown with a value template. Is it possible to do this? The graph history seems to be lost when I create a new value template sensor

inner mesa
#

You need to add a ‘unit_of_measurement’

carmine stag
#

The utility meter already has a unit and doesn't seem to like me adding a unit_of_measurement

inner mesa
#

I’m commenting on your last sentence

carmine stag
#

Gotcha, yeah the new template sensor has a unit of measurement already, but acts as if the first point on the graph is a few minutes ago, which honestly makes sense. If I lose the past few days of data on my utility sensor for the front-end, that's fine, I was just curious if there was a cleaner way to do things in one place

inner mesa
#

No, you’re now graphing the historical state of your new sensor

carmine stag
#

👍 Sounds good, thanks!

oak summit
#

I want an automation to output some things about tomorrow's weather forecast, I'm wanting a template for these three values out of the weather.kgus_daynight I have.
https://paste.ubuntu.com/p/y6rCBg8ZkK/

I do know how to get normal attributes, but I'm not sure how to output things inside the forecast object, at the time this automation will be firing it should be the second item in the forecast object, I've added #this 1 #this 2 and #this 3 to the three places I need to know how to template for, but if someone can help me with one of them I'm sure I can figure out the other 2 fairly easily.

#

oh, I think I just figured it out!

#

but I'll wait to see what rob is typing lol

inner mesa
#

{{ state_attr('weather.xxx', 'forecast')[0]["temperature"] }}

oak summit
#

I got {{ state_attr('weather.kgus_daynight', 'forecast').2.precipitation_probability }}

inner mesa
#

and [1] and [2] etc.

oak summit
#

is there any particular need for the brackets?

inner mesa
#

that's how one indexes into a list

#

the ".2." might work, but it's ambiguous

oak summit
#

well, the one I put there actually worked, so I was just wondering if there was an edge case where i shouldn't do it that way.

inner mesa
#

whatever works

oak summit
#

oh wait, adding the brackets breaks it in the devtools /templates... I guess I'll go without then 😅 it didn't break anything, I did it wrong. kept the period, did .[2] instead of just [2].

inner mesa
#

I'm used to more Pythonic syntax

oak summit
#

Sorry for the dumb questions if they are dumb 😅 I'm just excited I'm finally starting to understand templates more

inner mesa
#

np. play around in the dev tools and see what works

silent barnBOT
thorny snow
#

Hi to all,

i'm trying to make a button to show his entity state on when clicked navigate to another window, and when holding the button toggle another entity switch

the state is ok, the navigation is ok, but when i make the toggle to the switch it gives me an error failing to toggle the switch to turn on. Can anyone give me an hint to what i'm doing wrong

https://paste.ubuntu.com/p/6hbS88KtP3/

nocturne chasm
nimble copper
#

With the new template trigger binary sensors, is it possible to create a binary sensor that checks if a numerical state is true for X number of minutes? And then turns off the binary sensor when it's no longer true?

nocturne chasm
#

The template trigger just updates the state of the binary sensor when the trigger value is satisfied.

nimble copper
#

It looks like the new delay_on keys in the template sensors might do the trick.

waxen dawn
#

Hi,

I'd like to upgrade my game from:

    google search, cut and paste, 
    fiddle with the code, 
    and see if it works```
to a little actual programming in Home Assistant and ESPHome.

Is there some sort of outline or tutorial that can start me off?
Or is my request kind of like asking a doctor to give you in 15 minutes what took him 10 years to learn?

Thanks in advance.
jagged obsidian
#

first: its not programming

#

learn yaml structure, learn jinja templating

waxen dawn
#

I've got yaml structure (at least at a novice level) so I'll look into jinja templating. Thanks

jagged obsidian
#

and don't try to understand HA docs, understand them first

waxen dawn
#

I get the don't "try" just "do" concept. Maybe the jinja templating will get me closer to that goal.

jagged obsidian
#

it will let you understand what all those {% if and | int things do

waxen dawn
#

👍

acoustic arch
#

how can i get the weather the TODAY date?

#

since it changes every day?

jagged obsidian
#

i'm not sure what's pasted in the pastebin

acoustic arch
#

its a forecast sensor accuweahter

jagged obsidian
#

not a weather entity?

acoustic arch
#

is an entity yes, sorry

#

this is spit out in developers tools

#

i need datetime today

jagged obsidian
#

well you get the current weather with states(weather.name)

acoustic arch
#

mmm. I would like an early morning of the weather that day

#

not current...

jagged obsidian
#

why do you need early morning of today if its noon?

acoustic arch
#

sorry... i need the weather of the day, given to me in the morning

#

so current doesnt cut it

jagged obsidian
#

date comparisons get very complicated

acoustic arch
#

thats why i was thinking parsing that datetime:

#

thats why im here lol 😉

jagged obsidian
#

perhaps {{ state_attr('weather.name', 'datetime' ) | timestamp_custom('%Y-%m-%d') == now().strftime('%Y-%m-%d') }}

acoustic arch
#

holy!

#

hahaha. damn son!

jagged obsidian
#

the timestamp formatting might need adjustments

acoustic arch
#

ill go paste this in develop

#

{{ state_attr('weather.huis_2', 'datetime' ) | timestamp_custom('%Y-%m-%d') == now().strftime('%Y-%m-%d') }}

#

is giving me False

#

gotta go. Youve given me a good direction. Found some on the site with this sting

#

thx

formal ember
#

I have an average temp sensor, it reports in 2 decimal places, is there a way to force it to report as only 1 decimal place? (OCD kicking in...) have read the template docs and cannot figure out an example to use

formal ember
#

solved.... for future reference...

    home_temperature_average:
      friendly_name: "Home Temperature Average"
      unit_of_measurement: '°C'
      value_template: "{{ (states('sensor.home_temperature_average') | float ) | round(1) }}"
warm beacon
#

Where is the mistake?
Just one line in the Template editor results in 5 {{ "%.2f" | format(5 | float) }}
Several lines or a comment add up to 5.00 Ahhh: {{ "%.2f" | format(5 | float) }} How do I have to format a number so that 2 decimal places are always displayed?

inner mesa
#

The |float isn’t doing anything there

#

{{ "%.2f"|format(5) }}

warm beacon
inner mesa
#

Not for me

#

5.00

warm beacon
# inner mesa 5.00

Only with this single line in the editor?? {{ "%.2f"|format(5) }} nothing else.

inner mesa
#

it did on my phone, but trying it again on my desktop machine it's returning a number and "5"

#

weird

flint crown
#

Is there a possiblity for a template SQL Sensor ? A SQL Sensor which is evaluate at state change.

fair verge
#

seems you have to have - trigger: even if empty

inner mesa
#

@warm beacon It looks like you need to have something in addition to the format string to get it to evaluate to a string, like {{ "$%0.2f"|format(5) }}. Other characters also work, but a space does not

#

this is "true": {{ "%0.2f"|format(5) is string }}, but this returns a number: {{ "%0.2f"|format(5) }}

pastel moon
inner mesa
#

I think that will only work in a data: block

#

but you can use the scene.turn_on service and do it that way

#

states('sensor.period_of_day'), BTW

pastel moon
#

True, and thanks! More digging to do... 🙂

#

but how will what's in the data: block affect entity_id?

inner mesa
#

because you put the entity_id in the data: block

pastel moon
#

getting close?

sequence:
  - service: scene.turn_on
    data:
      target: scene.hallway_{{ states('sensor.period_of_day') }}
inner mesa
#

I don't know how target: works. I would use entity_id: there

pastel moon
#

lol. ha core check didn't protest, but agree... Were too hasty

pastel moon
#

Well, this works nicely, but could the value of the sensor be captured in a variable somehow? As is it could theoretically change while running the script (will add more entities_id's)?

  sequence:         
    - service: scene.turn_on
      data:                 
        entity_id: scene.hallway_{{ states('sensor.period_of_day') }}
distant plover
inner mesa
#

@pastel moon Yes, you can store it in an input_text

#

But it seems like you would want to use whatever is current

pastel moon
#

I will add the list to a few more and would like to make sure all are set to the same value...

inner mesa
#

@distant plover yes

#

Ok

distant plover
#

Basically just replace it with {{ states.light.bad_led_over_speilet.attributes.brightness | int}} ?

#

Or... I have to do something clever to convert range 0-255 to 0-99

ivory delta
#

number / 2.55

inner mesa
#

state_attr('light.bad_led_over_speilet', 'brightness')

distant plover
#

Thanks. I guess I used the old method.

#

But / 2.55 will become 100, not 99

#

And if I do {{ (state_attr('light.bad_led_over_speilet', 'brightness') / 2.55 -1)|int }} I will get 0 when brightness is 1 😛

ivory delta
#

So subtract 1... 🤔

#

If something expects a percentage, it will accept 100.

distant plover
#

Hmmm... I can try.... it's a zwave parameter

ivory delta
#

The reason you'll often see 0-255 is that those numbers can all be represented by an 8 bit number. 256 would take it into a second byte. 0-100 has no such problems.

distant plover
#

Didn't work. It wouldn't change the parameter if I chose 100

#

Just reset it to its current state

ivory delta
#

If you need an integer value, divide by 256 instead and then floor the resulting number.

#

You might get some values that are off by one but it'll fix 0 and 99 for you and still be a linear scale.

distant plover
#

Thanks, I can live with 256 🙂

pastel moon
#

this is so fun! Can't believe I didn't got involved earlier! 😄

distant plover
#

What's a good way of getting a template trigger for changes to brightness? I need on to off, off to on, brightness up and brightness down.

inner mesa
#

just trigger on brightness changes and sort it out in the action: with a choose:

distant plover
#

I actually don't care what trigger it is. I need to do an action on any change to the device 😛

#

But what's the best way of doing a trigger on brightness changes?

inner mesa
#

it's just a state trigger

#

best, read the whole page

#

the trick is that I believe that the brightness attribute only exists if the light is on, so you'd also need to trigger on a state change to off

distant plover
#

Brilliant! Thanks.

elder quarry
#

hey folks, i'm trying to get a state template for my thermostats, but i am always getting "heat" rather than "off"

#

surely i am missing something here

#

2nd_floor_hvac_state:
friendly_name: "2nd Floor HVAC State"
value_template: "{{ states('climate.2nd_floor_thermostat_mode') }}"

inner mesa
#

that's a weird template sensor. why not just use climate.2nd_floor_thermostat_mode?

#

what's the point of replicating that state?

elder quarry
#

i just realized what i think i actually want is the attribute hvac_modes

#

i want to display the current status and setpoint without using the full climate card

inner mesa
#

I figured 🙂

#

hvac_modes is a list of all the modes. also probably not what you want

#

hvac_action is what it's doing now

elder quarry
#

right, that returns an array, though it does indicate 'off' in the state tab

inner mesa
#

the state of climate.xxx is what it's currently set to

#

then it's off

jagged obsidian
#

If it's always in heating mode you might need idle as off

elder quarry
#

ahhh, thank you

#

action is indeed what i want

#

i wonder why it "highlights" off when it is on heat

#

in the modes, that is

jagged obsidian
#

If it's off in states then it's off, otherwise it's on but in different climate mode

elder quarry
#

heat just turned on a minute ago

inner mesa
#

you're asking why off is quoted?

elder quarry
#

right

inner mesa
#

so it's recognized as a string, rather than a boolean

#

it's just an artifact of YAML

elder quarry
#

thanks, that makes sense

#

man, everything is so easy once you figure it out

pastel moon
inner mesa
#

You can’t just use the input_text directly. It has to be a template

rocky vapor
#

Supposedly supplying a trigger is optional however I can't seem to declare a template without it..
Invalid config for [template]: required key not provided @ data['trigger']

inner mesa
#

Put the entity_id in data: and use a template as you did with the scene

inner mesa
rocky vapor
#

declare a template without a trigger

inner mesa
#

What are you want the state of the template to be?

rocky vapor
#

not important at this stage

inner mesa
#

🤷

#
- platform: template
  sensors:
    roomba_status:
      friendly_name: Status
      value_template: "{{ states('vacuum.taileater_2_0') }}"
      icon_template: mdi:robot-vacuum
rocky vapor
#

anything declared under the "template:" key in config requires a trigger?

rocky vapor
#

right, declared under "sensors:"

inner mesa
#

but the first example from the docs does not have a trigger

rocky vapor
#

or "template:"

#

the example you've shown me appears to be a sensor declaration if im not mistaken?

inner mesa
#

as is yours

#

just different ways to write it

rocky vapor
#

no, i'm specifically declaring these under "template:"

inner mesa
#

are you saying that the example in the docs is wrong or doesn't work?

rocky vapor
#

the docs say a trigger is optional.

#

if i declare a template without a trigger, i get an error: Invalid config for [template]: required key not provided @ data['trigger'].

#

so either the docs are wrong, or i'm missing something painfully obvious

inner mesa
#

yours doesn't look like the docs

rocky vapor
#

OK..

inner mesa
#

first, you've commented out the first line. second, you have a second sensor: block

#

from the docs:

rocky vapor
#

i've commented out the first line because its a linked file.

inner mesa
#
template:
  - sensor:
      - name: "Average temperature"
        unit_of_measurement: "°C"
        state: >
          {% set bedroom = states('sensor.bedroom_temperature') | float %}
          {% set kitchen = states('sensor.kitchen_temperature') | float %}

          {{ ((bedroom + kitchen) / 2) | round(1) }}
#

yours:

rocky vapor
#

thats beside the point

inner mesa
#
#template:
  - sensor:
    name: "Test"
    state: "Test"
  - trigger:
      platform: time_pattern
      minutes: "/1"
    sensor:
      icon: mdi:update
      name: "Docker cloud backup"
      state: "{{ relative_time(strptime(states.sensor.rclone_timestamp.state|int|timestamp_custom('%Y-%m-%dT%H:%M:%S.%f%z'), '%Y-%m-%dT%H:%M:%S.%f%z')) }} ago"
#

note the second "sensor:"

rocky vapor
#

yes im declaring two seperate templates

#

the second of which, is using the trigger

pastel moon
inner mesa
#
- sensor:
    - name: "Test"
      state: "Test"

- trigger:
    - platform: time_pattern
      minutes: "/1"
  sensor:
    - icon: mdi:update
      name: "Docker cloud backup"
      state: "{{ relative_time(strptime(states.sensor.rclone_timestamp.state|int|timestamp_custom('%Y-%m-%dT%H:%M:%S.%f%z'), '%Y-%m-%dT%H:%M:%S.%f%z')) }} ago"
rocky vapor
#

yeah.. unfortunately same error. I've tried declaring

  - sensor:
      - name: Sun Angle
        unit_of_measurement: "°"
        state: "{{ '%+.1f'|format(state_attr('sun.sun', 'elevation')) }}"
#

by itself, same error

inner mesa
#

that one works for me

rocky vapor
#

the hell is going on here..

inner mesa
#

sensor: presumably wants a list

#

anyway, I just followed the docs closely

rocky vapor
#

you were able to declare a template without a trigger?

inner mesa
#

@pastel moon Yes, your indentation is all over the place

pastel moon
#

its is... forgot to mention that before pasting... It is correct in the actual script tho

inner mesa
#

I can't help debug something that's only in your file

pastel moon
inner mesa
#

this is not an entity_id: "{{ states('sensor.period_of_day') }}"

#

and you didn't tell it what to set it to

#
test:
  alias: New Script
  sequence:
    - service: input_text.set_value
      data:
        entity_id: input_text.scene
        value: scene.hallway_{{ states('sensor.period_of_day') }}
    - service: scene.turn_on
      data:
        entity_id: "{{ states('input_text.scene') }}"
  mode: single
pastel moon
#

Thanks! I had corrected the entity_id and was reading... perfect 👍

rocky vapor
#

if anyone can confirm outright they can declare a template without a trigger, please tag me in the post. cheers

inner mesa
#

I did

rocky vapor
#

what version of home assistant are you running @inner mesa ?

#

I'm running Home Assistant 2021.4.6

inner mesa
#

2021.5.2

#

From your definition

rocky vapor
#

alrightttt

#

im not going insane

#

thank you!

inner mesa
#

There was a change in 2021.5, but I don’t recall the details

rocky vapor
#

pulling the latest images now

#

working fine now, thank you @inner mesa

#

that was driving me up the walls

inner mesa
#

I haven’t used that feature, so the 2021.5 changes didn’t register with me, or that it would affect you

#

This doesn’t seem template related

#

Please stop posting everywhere. It won’t help

#

Stop tagging me

#

Chill out and Google ‘home assistant locked out’

#

Blocked

bitter atlas
#

never had to do it, can't help you with that. that page pretty much covers every scenario so you must be missing something or doing something off. also this issues belong ONLY in #330990055533576204 and NO other channel so please stop posting in this one and after you have THOROUGHLY tried everything then post for help in #330990055533576204

inland hazel
#

@worthy tangle That was completely uncalled for.

#

Ghost spamming the mods is not allowed, and therefore you are no longer allowed here.

#

1 simple “atMOD” message is fine when someone is breaking the rules and we need to be directed toward it. However, sending 4 messages, each consisting of multiple mod tags, that’s completely uncalled for.

winter belfry
#

yes, none of this deserves the mania you are applying to it.

plucky oyster
pastel moon
#

This script acts on a sensor than can return 'day', 'night', 'morning' & 'evening'. When the latter two happens I would like it to return 'soft' instead. Am I on the right track with this value template? https://paste.ubuntu.com/p/3BdrHYFrCj/

inner mesa
#

Close, but not quite

#

There no value_template: key for input_text.set_value and you can’t return a key: value pair from a template

#

Use value: instead of value_template: and just return the value you want in the template

pastel moon
#

Template checks out in Dev Tools, but when enabled in the script, I get a warning when trying to run it (flashes past) something about template generating an unknown entity_id...

#

Don't understand that, tried googling a lot

inner mesa
#

You probably need data: instead of target:

#

Like in my example from last night

pastel moon
#

Oh!! I knew I was missing something... You did say data was needed for templates... 😊

#

this flashes past real quick when manually running the script (no idea which log it ends up in if any): "failed to call service script/hallway_lights_on. not a valid value for dictionary value @plucky token['entity_id']". This is after changing target -> data. Any idea? What is returned by the template looks identical to what I typed on the line above...

inner mesa
#

What is the state of the input_text?

pastel moon
#

You know what... You're a genius... !! I had forgot to define it in the Helpers... I thought of it as a kind of variable, not an entity... Thanks!! This unlocks much I have planned... 😄

ruby crane
#

I have a sunset sensor with the state 2021-05-11T21:12:55.988118+02:00, how do I extract the hour and minute from it?

#

{{ as_timestamp(states('sensor.sunset')) | timestamp_custom('%H:%M') }}

jagged obsidian
#

in short don't use the old states definition

restive flume
#

does anyone know if it is possible to prevent a template from triggering this sort of warning in the logs?

#

2021-05-12 18:20:49 WARNING (MainThread) [homeassistant.helpers.template] Template variable warning: 'None' has no attribute 'state' when rendering '{% if states.media_player.yamaha_receiver.state %}{{ states.media_player.yamaha_receiver.attributes.source }}{% endif %}'

restive flume
#

ah! well that solves it.. no longer need the if either hopefully

#

nice.. {{ state_attr('media_player.yamaha_receiver', 'source') }}

#

easier to read

dark dome
#

Ok so I think I'm getting close to my goal finishing my light api project

#

I used an api to monitor crypto prices and change the lights accordingly

#

But now I need to get the hour to hour change from them

drowsy field
#

May I ask why I tried to access to my MQTT device sensors and get "Instance is not a number"?

#

This is my snippet for MQTT part:

sensor 1:
  platform: mqtt
  name: "analog"
  state_topic: "M1"
  qos: 0
  unit_of_measurement: ""
  value_template: "{{ value_json.a }}"
#

I just want to show it in a gauge in lovelace.

type: gauge
name: Usage
unit: '%'
entity: sensor.analog
min:0
max:100
fossil venture
#

You need a unit of measurement for it to be regarded as a number. Use a space instead of null, unit_of_measurement: " "

#

It will still look like there is no unit.

grim flicker
#

Is there a way to make a template trigger which triggers when a entity_id is above a sensor value? On the Home assistant docs i only read examples about when it reaches a specific value

#

I made a condition that should work: ``` condition:

  • "{{ state_attr('climate.tstat_3a71c8', 'current_temperature') |float < states('sensor.tstat_temperatuur_plus_1')| float }}"```
    now i would like to make a trigger which actually almost does the same thing
inner mesa
#

The exact same thing

grim flicker
#

can i use that line also in a trigger

inner mesa
#

It’s a template that you can use in a template trigger

grim flicker
#

maybe a stupid question but would something like this work:

trigger:
- "{{ state_attr('climate.tstat_3a71c8', 'current_temperature') |float < states('sensor.tstat_temperatuur_plus_1')| float }}"

or does this way of coding only works with conditions

inner mesa
#

Shorthand only works in conditions.

grim flicker
#

Just to be sure... and then im out of your hair... this should work:

  - platform: template
    value_template: "{{ state_attr('climate.tstat_3a71c8', 'current_temperature') |float > states('sensor.tstat_temperatuur_plus_1')| float }}"

i cant test the automation until the room temp is 1.5 degrees higher then the set temp.

inner mesa
#

You can. Set the state manually in devtools -> States

grim flicker
#

ok thanks

#

ok it works! never knew that the defining state button overrides the values to test automations. When do they reset back? when the state is updated?

ivory delta
#

When the integration next sets it.

grim flicker
#

ok thanks. i learn something every day 🙂

ivory delta
#

Just wait until you hear about the API

grim flicker
#

i some apis to calculate the amount of rain and let google tell me if its going to rain. and show messages of home assistant on my lametric clock using local api's. I LOVE api's 😅

dusty hawk
#

Do areas have states like groups? I'm getting errors using groups as entities for light.turn_off. I have the following script I could use to use, but the wait_template needs a state to wait for. Do areas have states? ``` - condition: template
value_template: "{{ is_state(entity, 'on') }}"
- service: homeassistant.turn_off
data_template:
entity_id: "{{ entity }}"
- wait_template: "{{ is_state(entity, 'off') }}"
timeout: '00:02:00'

ivory delta
#

No

#

Areas and groups aren't the same thing though. Use the group.

#

What errors are you getting?