#templates-archived

1 messages ยท Page 36 of 1

hot harbor
#

Where?
In the configuration.yaml it gives me only error

mighty ledge
#

post what you've tried

#

I use it currently in one of my macros. Makes it easy to avoid code reuse

hot harbor
#

Ok, i've tride to add the line:

{% from 'easy_time.jinja' import easy_time %}
to the configuration.yaml, but it gives me error:

Error loading /config/configuration.yaml: while scanning for the next token found character '%' that cannot start any token in "/config/configuration.yaml", line 156, column 6

In the Dashboard it says:


 1 | {% from 'easy_time.jinja' import  ...
------^
 2 | type: entities
 3 | entities:```
mighty ledge
#
  1. That's not configuration.yaml
#
  1. It has to be in your template
#

wherever you put that template

#
  1. Templates cannot go in lovelace/dashboards
#
  1. That code you posted is dashboard code
hot harbor
#

My Sensor is in the configuration.yaml

mighty ledge
#

type: entities says otherwise

#

that's lovelace

#

or "dashboards"

#

so your import needs to go inside configurtion.yaml in your template. If you say it's in sneosrs, then it goes inside your template sensor

#
{% from 'easy_time.jinja' import easy_time %}
{{ easy_time(states('sensor.valetudo_mistymemorablejay_main_filter') | float(0) * 60) }}
#

all in 1 spot

hot harbor
# mighty ledge all in 1 spot

Ok in the developer tools under template it gives me "5 Tage". But where i have to add this code to take it in my lovelace?

mighty ledge
#

You have to make a template sensor

#

is 5 Tage, 5 days?

#

๐Ÿคฃ

hot harbor
mighty ledge
#

๐Ÿ‘

#

So, have you made template sensors before?

hot harbor
#

I have a Template sensor for my electricity meter (tasmota)

mighty ledge
#

Also, another question... your sensor.valetudo_mistymemorablejay_main_filter, does it have device_class duration, and unit_of_measurement: minutes?

mighty ledge
plain magnetBOT
odd flare
#

does this sensor seem correct? I want to set the rolling daily attribute value

mighty ledge
#

@hot harbor Just add a sensor at the bottom of that file then

  - sensor:
      - name: RENAME THIS
        state: >
          {% from 'easy_time.jinja' import easy_time %}
          {{ easy_time(states('sensor.valetudo_mistymemorablejay_main_filter') | float(0) * 60) }}
hot harbor
mighty ledge
#

Did you rename it?

hot harbor
#

Yes, as Test123 ๐Ÿ˜‚

mighty ledge
#

Hehe, good, you aren't stupid, just don't know the system yet

#

now if you didn't rename it... then I might think you're a little slow ๐Ÿคฃ

#

FYI, the importing crap is very new

#

Like, 6 days new

#

so you won't really see many posts about it on the forums... or anywhere for that matter

mighty ledge
#

if you want it in a self contained template, it's going to be difficult

hot harbor
mighty ledge
#

I'm pretty sure Fes's relative time may show it better. Easy_time is meant to be easy, but not highly configurable

hot harbor
mighty ledge
#

yep

plain magnetBOT
mighty ledge
#

@sand ivy templates resolve types. I.e. if it looks like a number, it will resolve to a number when passed to the config

#

Your only option is to template the entire params field

inner mesa
#

seems like the integration should handle this if it actually needs to be a specific type

mighty ledge
#
params: "{{ [ my_string, '0', '1' ] }}"
mighty ledge
#

I run into this like 4 times a year

inner mesa
#

"broken forever" == sad

mighty ledge
#

for hte past... however long I remember

#

I'm not sure the dev's actually know

#

I'm not about to write it up ๐Ÿคฃ

#

I don't own one

inner mesa
#

Don't have one, don't care

mighty ledge
#

na, it's more like "I don't own one, I can't test it out, not sure if this is a user thing or the integration but I know how to step around the issue"

inner mesa
#

The open source motto

#

along with its corollary - I have one and I shall make it work because I do care

rocky hemlock
#

Hi all. I'm a HASS newbie. I'm trying to create a template sensor that calculates the days remaining before an HVAC filter needs to be changed. I have this in my configuration.yaml, but am not seeing an entity created after restarting my HASS.

Pastebin link: https://pastebin.com/PU5RNKan

Any recommendations would be much appreciated!

sand ivy
inner mesa
rocky hemlock
inner mesa
#

review the HA logs when you reload template entities

#

also, if you have another template: block in configuration.yaml, you need to include the new one under it and not duplicate it

rocky hemlock
#

@inner mesa - I checked to make sure I didn't have more than one template: block in configuration.yaml and i do not (thanks for flagging, though)

I checked the logs and pasted the relevant portion here: https://pastebin.com/19NwyczH

I'm not sure from the logs what I need to do - any suggestions?

spring summit
#

I'm moving some duplicate stuff to the new jinja marcro's, great feature!. Is it possible not to return a new line on the end of the marco, so it it won't break some text lines i'm printing?

mighty ledge
#

If you donโ€™t know what I mean, read the first pin

hexed laurel
#

Hello All, I have a history stats sensor I've set up in config to count the time a fan is on. It works but it doesn't update but every few minutes on the front end UI, Any ideas?

spring summit
mighty ledge
#

You canโ€™t execute 2 functions in 1 output

spring summit
#

{{ print("sensor.kia_e_niro_ev_charge_level") }} {{ print("sensor.kia_e_niro_ev_charge_level") }}```
mighty ledge
#

That will work but it will only break lines in markdown card

spring summit
#

Yes I found out, adding a - to the macro

#
{{ states(entity_id) }}
{%- endmacro -%}```
wanton girder
#

Im trying to make a button on the dashboard that can toggle two services
action:

  • service: water_heater.set_operation_mode
    target:
    entity_id: water_heater.egevej_8_tank
    data:
    operation_mode: "off"
    and
    action:
  • service: water_heater.set_operation_mode
    target:
    entity_id: water_heater.egevej_8_tank
    data:
    operation_mode: "heating"
#

how do I go about this

marble jackal
#

put them in a script and run the script from your dashboard button, but this is something for #automations-archived

#

oh, seems you were sent here from there

runic heron
#

Hi Guys, may I get some help here please. I have created an MQTT binary sensor, the topic either sends 0 or 1 , but I want it display "Empty" and "Not Empty" , however I get OFF/ON only ๐Ÿ˜ฆ
binary_sensor: - name: "Washer" state_topic: "/washer/Out/state" value_template: "{{ 'Not Empty' if value == '1' else 'Empty' }}" payload_on: "0" payload_off: "1"

Any help is appreciated

lofty mason
#

binary_sensor are only on/off. If you want the state to be a custom string, you need a sensor

runic heron
lofty mason
lean yacht
#

Hi all,
I'm trying to build statistics on the amount of time a button is pressed and display that in a graph...
Idea is to provide the sum of the button presses for the last 5 (or perhaps 10) minutes.
(underlying context: my girlfriend is expecting and I'm trying to build a counter for the contractions... every time she feels one, she would click a button. Stats would help to keep track)

#

alternativily, having stats on the interval between the presses would also work

orchid oxide
#

is it possible to use templates to see if an entity is in a zha group

marble jackal
#

I don't expect your girlfriend will be very happy she has to press a button while having contractions, she will probably have something else on her mind

#

But you can look into this

plain magnetBOT
marble jackal
orchid oxide
#

the entity of the zha group, lights.kitchen_lights makes no mention of lights.kitchen_lights_1 or lights.kitchen_lights_2, at least, not in developer-tools/state

wanton girder
#

How do I combine these two

#

switch:

  • platform: template
    switches:
    blind:
    friendly_name: "Blind"
    value_template: "{{ is_state_attr('switch.blind_toggle', 'sensor_state', 'on') }}"
    turn_on:
    service: switch.toggle
    target:
    entity_id: switch.blind_toggle
    turn_off:
    service: switch.toggle
    target:
    entity_id: switch.blind_toggle
#

With

#

switch:

  • platform: template
    switches:
    blind: ??
    turn_on:
    action:
  • service: water_heater.set_operation_mode
    target:
    entity_id: water_heater.egevej_8_tank
    data:
    operation_mode: "off"
    turn_off:
    action:
  • service: water_heater.set_operation_mode
    target:
    entity_id: water_heater.egevej_8_tank
    data:
    operation_mode: "off"
inner mesa
#

please, please, please format your code

#

and if it's that long, use a code share site

plain magnetBOT
#

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

Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.

inner mesa
#

You've shown both the template switch and the service calls. You put the part that you want to run when the switch turns "on" in the "turn_on" part and the other part in the "turn_off" part

#

it's not a matter of "combining", but understanding what you're doing

wanton girder
#

I'm new and just hoping to get some help and learn

hexed laurel
lofty mason
#

now()-based triggers only update every minute intentionally, so it doesn't overload the system with events

hexed laurel
#

Is there a solution for a more real time run timer?

compact rune
mental violet
#
Logger: homeassistant.helpers.script
Source: helpers/script.py:1068
First occurred: 10. April 2023 um 00:00:00 (978 occurrences)
Last logged: 01:00:29

Error in 'choose[2]' evaluation: In 'template' condition: UndefinedError: 'None' has no attribute 'state'
``` Where can I find or how can I find the error ?
mighty ledge
mighty ledge
#

your second choose in a script has the error.

mental violet
#

is there a way, where I can narrow the error down? I went through all of my scripts and searched for choose... but I didnt find any element which doesnt exist anymore or where the state can be wrong.

hexed laurel
mighty ledge
#

you don't want it searching the database anymore than it is

#

all you're going to get is slightly more resolution

fickle kettle
#

@mental violet the error says exactly what the error is. You're trying to use somevariable.state when somevariable is None (ie: no-value)

#

in a template

#

paste your template code that includes "choose[2]"

mental violet
fickle kettle
#

It's probably not in scripts.yaml - it's probably a tempate

#

just grep 'choose' in *.yaml in /config

#

or configured from the ui

#

how many do you have? just look through them in UI if you need to

#

PS: I never made/used a script; but error looks like common template-style issue

mental violet
#

I have many scripts for a LoveLace Button when it has to do more than 1 thing after being pressed.
But I will look into templates as well.

lofty mason
#

I think if you up your debug log level you might get more info about what is running right before that error is thrown

#

it could be something in an integration too I think

fickle kettle
#

Is it something that has happened nearly 1000 times in ~24 hours? There can't be too many of those?

mental violet
#

How can I up my log level? I am seeing HA Core

mighty ledge
#

The error is a template error. The pointer is inside a script or automation

#

it's the second condition in a choose

#

the template will have states.xxx.xxx.state as the method you used to get the state

#

or possibly trigger.to_state.state / trigger.from_state.state

#

you can problably search your files for .state

mighty ledge
#

anyways if it's a xxx.xxx.state, you most likely have a missing entity, or renamed something

mental violet
#

Yes thank you, I found it I searched for states.*.state. Thank you!

fickle kettle
#

So, where was it, what's the yaml? Maybe we can tell you what sensor or value it's missing?

mental violet
#

It was in templates.yaml where a template condition compared 2 variables with old names. In addition I fixed every state.xxx.state to the better variant states('xxx'). Thank you for your help

fickle kettle
#

Ya, that's what the template help pages say. So all fixed?

mental violet
#

Yes thank you for your fast help

fickle kettle
#

np

plain magnetBOT
marble jackal
#

Just create a daily utility meter sensor out of your hourly sensor. That will give you the daily total

#

If you really want to use a template sensor, that will be quite complicated, and will probably go wrong at some point
But you can try the following:
0) remove the availability template, you don't want it to become unavailable, as you need to store the old value

  1. check if both the to_state and from_state of your sensor are numeric
  2. if so, check if the to_state is higher than the from_state (otherwise there was an hourly reset)
  3. calculate the difference if the from_state is higher, ortherwise take the from_state
  4. add that difference to the current state of the template sensor
  5. in any other case, return the current state of the template sensor again
obtuse sky
#

device_entities(devid) returns a list with entities, the list has a find() function, but how i regex match specific element from the list?

#

find() don't permit regex, only simple string

marble jackal
#

search allows regex

#

devcice_entities('banana') | select('search', '^light.') | list

obtuse sky
#
{%- set dev.name = device_attr(devid, "name") %}
  {%- for ent in device_entities(devid) %}
    {{ent.find("(?:_version)(?<!_newest_version)$")}}
    {%- if ent.find("(?:_version)(?<!_newest_version)$") |int>=0 %}
      {{ ent }}
    {%- endif %}
  {%- endfor %}
{%- endfor %}
#

i have try {{ ent | select('search', ".*(?:_version)(?<!_newest_version)$") | list }}

#

but is not working

marble jackal
#

what are you trying to achieve here

#

so far you are working with entity_id's, but it looks like you want something from the attributes of those entities

obtuse sky
#

i want to check if _version exists on device entities

#

because device_entities return version and _newest_version

#

and on a simple find, returns both

#

and i need to regex one of them

marble jackal
#

your ent variable will be an entity id, for example update.mariadb_update

obtuse sky
#

exact, but is a list

marble jackal
#

there will never be _version or _newest_version in that entity_id

obtuse sky
#
    update.tasmoadmin_update
    sensor.tasmoadmin_version
    sensor.tasmoadmin_newest_version
    sensor.tasmoadmin_cpu_percent
    sensor.tasmoadmin_memory_percent
    binary_sensor.mosquitto_broker_running
    update.mosquitto_broker_update
    sensor.mosquitto_broker_version
    sensor.mosquitto_broker_newest_version
    sensor.mosquitto_broker_cpu_percent
    sensor.mosquitto_broker_memory_percent
    binary_sensor.samba_share_running
    update.samba_share_update```
marble jackal
#

hmm, okay

#

I only have update entities in that list

#

ah wait, I didn't enable those

#

you could also get the installed version out of your update entities

obtuse sky
#

yes, but the new version avalibile no

marble jackal
#

anyway, this works for me, there is no need for a for loop (let alone a nested for loop)

{% set devid = integration_entities('Supervisor') | map('device_id') | unique | list %}
{% set ent = devid | map('device_entities') | sum(start=[]) %}
{{ ent | select('search', ".*(?:_version)(?<!_newest_version)$") | list }}
#

the newest version is also in the update entity

obtuse sky
#

ok, i will test now, you code is working, i will try to make us of it

wanton girder
#

If I want to use templates, do I past the code - via the /developer-tools/template or ??

marble jackal
#

you put the template in a field which accepts them. devtoops > templates is used to create/check them

obtuse sky
#
  {%- for ent in device_entities(devid) %}
    {{ ent is match(".*(?:_version)(?<!_newest_version)$") }}
  {%- endfor %}
{%- endfor %}```
#

i manage like this

marble jackal
#

why the for loop? It is not needed

obtuse sky
#

because the secound loop i create specific chips based on the find

marble jackal
#

yes, but you are still using a for loop now

#

and I showed you above that you don't need a loop at all

obtuse sky
#

something like

marble jackal
marble jackal
plain magnetBOT
#

To format your text as code, enter three backticks on the first line, press Shift+Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks.
```yaml
example: here
```
Don't forget you can edit your post rather than repeatedly posting the same thing.

wanton girder
#

I want to toggle these to services here on my dashboard

#
service: automation.turn_off
action:
  - service: water_heater.set_operation_mode
    target:
      entity_id: water_heater.egevej_8_tank
    data:
      operation_mode: "heating"

service: automation.turn_on
action:
  - service: water_heater.set_operation_mode
    target:
      entity_id: water_heater.egevej_8_tank
    data:
      operation_mode: "off"
#

via a button if possible

marble jackal
#

still doesn't answer where you want to have a template

#

there you can ask how to assign a service call to a button on your dashboard

wanton girder
marble jackal
#

Then you should explain more clearly what you want to achieve. Because so far I don't see the need for templates

#

And please leave your questions on the public channels, I'm not a personal HA support

wanton girder
#

I would like a button on my dashboard - if is heating and pressed it turns off (one service) and if its off and pressed it turns on heating (another service) - Its a water heater

marble jackal
#

still no need for templates, you can use a script with a choose or if action, and select the right action based on that

#

and then call that script by pressing the button

obtuse sky
radiant vault
#

Not sure if templates is the right place, but I need assistance with setting up entities that will differ based upon a selection.

I have thermometers for the bbq that I want to set up so when I choose an option (e.g. chicken or lamb) it will change what the gauge range is and change the timer etc

If anyone can point me in the right direction fir where to get started that would be appreciated

plain magnetBOT
hearty verge
#

When using value_json with a binary_sensor what valid values will automatically be converted to the on/off true/false?

mighty ledge
#

so set payload_on: true and payload_off: false and you should be good with your value.isError template

#

or don't set those fields and match the output of your template to those fields

hearty verge
#

I actually just read this in the docs! But thanks!!!!!

#

Does that mean my True/False in my value_json needs to also be a string an not a true / false but rather a "true" "false"?

#

The answer does appear to be "yes"

#

which means I'll have to modify the JSON which shouldn't be too bad

#

payload_on string (optional, default: ON)

Says it needs to be a string...

mighty ledge
#
{{ "ON" if value_json.isError else "OFF" }}
hearty verge
#

Whats the flow to get a string into relative time?

{{value_json.metaData.lastUpdatedDate | as_datetime | relative_time()}} looks exactly the same on the ui as: {{value_json.metaData.lastUpdatedDate | as_datetime}}

#

My lastUpdatedDate is 2023-04-11T16:53:25Z

#

appears to work fine in tempalte editor

#
{% set lastUpdate = '2023-04-11T16:53:25Z' %}
AsIs: {{ lastUpdate }}
as_datetime: {{ lastUpdate | as_datetime }}
as_relative {{ lastUpdate | as_datetime | relative_time }}
#

returns:

AsIs: 2023-04-11T16:53:25Z
as_datetime: 2023-04-11 16:53:25+00:00
as_relative 2 hours
#

This is in a value template for a sensor... maybe i need to change the class perhaps

mighty ledge
hearty verge
#

When i put that into the value template for MQTT -> Sensor it doesnt show taht way

#

I'm using a value_template in an MQTT discovery sensor and it shows as this: 2023-04-11T16:53:25Z if I'm using value_template="{{ value_json.metaData.lastUpdatedDate | as_datetime | relative_time()}}",

#

In the template editor it shows differently.

#

If i use device_class timestamp it still shows that way

mighty ledge
hearty verge
#

So if i want an elapsed time since last update

#

do i use a device class? or skip out on that

mighty ledge
#

Both do the same thing

#

Using the timestamp with ad_datetime letโ€™s the ui handle relative time

hearty verge
#

I'd like my sensor to show something like:

Time of last update: 2 hrs 15 mins

mighty ledge
#

Neither will output that

hearty verge
#

Oh thats perfect

#

thank you!

#

it says 3 hours ago

#

thats all i needed

#

and now i offer thanks

mighty ledge
#

Yes, thatโ€™s all relative time will do

#

It wonโ€™t do more sig figs

hearty verge
#
device_class="timestamp",
value_template="{{ value_json.metaData.lastUpdatedDate | as_datetime }}",

FTW

mighty ledge
#

I.e. you always get the most significant number

hearty verge
#

Thanks guys

#

super helfpul

inner raft
#

Hey there.
If I have a variable called "speakers" with targets selector in a script.

What stop me to write this:

alias: Wait until speakers stop
wait_template: >-
  {{ expand(speakers.entity_id) | selectattr('state','eq','playing') | list |
  count == 0  }}

Does not work but I am sure I am not too far.

marble jackal
#

If the variable speakers contains a list of entity_ids, the code you posted will work if you remove .entity_id

inner raft
#

I believe target selector is represented as

target:
  entity_id:
    - media_player.a
    - media_player.b

But I am not 100% sure

marble jackal
#

Then this should work

wait_template: >-
  {{ expand(speakers) | selectattr('state','eq','playing') | list |
  count == 0  }}
#

Or:

wait_template: >-
  {{ speakers | select('is_state', 'playing') | list |
  count == 0  }}
inner raft
#

I will try now

copper blade
#

Hi all, how would I setup a sensor to aggregate another sensor which reports a energy production for the full last hour? I want to calculate an overall total. I tried this but SolarthermieGesamtleistung always reports the same value as solar_energylasthour.

- trigger:
    # Aggregate hourly production of solar collectors to daily
      - platform: state
        entity_id:
          - 'sensor.solar_energylasthour'
    sensor:
      - name: "Solarthermie Gesamtleistung"
        unique_id: "SolarthermieGesamtleistung"
        device_class: "energy"
        state_class: "total_increasing"
        unit_of_measurement: 'kWh'
        state: >-
          {{  (states('sensor.solar_energylasthour') | float) }}
plain magnetBOT
marble jackal
#

Use an hourly utility meter on the sensor

#

Oh wait, the other way around

copper blade
#

๐Ÿ™‚ Yeah i have the hourly value and want to sum it up

marble jackal
copper blade
#

So sensor.solar_energylasthour reports like 0.3 kWh for 10-11 am and 0.5 for 11-12 and so an

#

Oh I missed that sorry for double post

#

Thanks for the reply earlier - you mention it will be hard using template, so I will try to use the utility meter.

marble jackal
#

Is the hourly sensor a utility meter sensor?

inner raft
copper blade
marble jackal
#

Then I would suggest creating a yearly utility meter from that sensor

#

Then, after that, create a template sensor which has an attribute in which you sum the previous_period attribute of the utility meter on yearly basis, and you add the value of the utility meter to the value of that attribute

#

Or you use an input_number and an automation instead of that attribute

inner raft
#

I am now quite proud of my sonos notification script ๐Ÿ™‚ . I can pass a media, or message to use with cloud tts. It plays and then restore the snapshot when finished

storm prawn
#

is it possible to get a persons / users profile picture via template ?

#

tried some possibilities like user.image / user.profile etc

eternal hazel
#

Hi Everyone!

I was using sensor.uptime as a condition in some of my automations that send notifications. Now, with the new option to reload the YAML without restarting HA, this sensor doesn't get reset and new notifications are sent every time i re-read the YAML. What would be your suggestion to detect that HA config was recently reloaded?

#

This is what i was using:

{{ ((as_timestamp(utcnow()) - as_timestamp(states('sensor.uptime'))) | round(0)) > 120 }}
eternal hazel
pine musk
#

hello beautiful people

#

question about de-json-ifying data from a REST API

#

the data comes back like this:

{"inputs":{"lat":"36.09","lon":"-86.64","limit":"1"},
 "errors":[],
 "warnings":[],
 "version":"3.1.0",
 "metadata":{"sources":["Ventyx Research (2012)"]},
 "outputs":{"company_id":"13216",
            "utility_name":"Nashville Electric Service",
            "utility_info":[{"company_id":"13216",
                             "utility_name":"Nashville Electric Service"}],
            "commercial":0.1032,
            "industrial":0.0661,
            "residential":0.1026}}
#

and I am trying to pick off the utility_name, with commercial, industrial, and residential as json_attributes

#

but I've lost my mind, trying to deal with nested json

exotic grail
#

what's wrong with the nesting?

pine musk
#

i don't know how to handle it..

#

My rest experience was XKCD;s json

#

which is nice and flat

pine musk
#

yeah, thats the page I was aattempting to grok

exotic grail
#

I haven't used it before but blindly: $.outputs as the json_attributes_path and then what you have as json_attributes?

pine musk
#

but it seems to be bouncing off my understanding

exotic grail
#

oh sorry I slightly misread what you had said, you wanted utility_name as the value_template

#

you wanted value_template: "{{ value_json.outputs.utility_name }}"

pine musk
#

still not working, but that looks right

exotic grail
#

what did it do?

pine musk
#

gave me unknown

exotic grail
#

unknown for/

pine musk
#

for the value of the sensor

exotic grail
#

are you sure it's able to pull the json in that case

pine musk
#

the json results I posted came from curl'ing the url

exotic grail
#

right but I mean from HA

pine musk
#

passign the same url I passed to curl

exotic grail
#

you could try pasting in the example json_attributes code into your list and seeing if that works. dunno seems like it's straight forward enough that it might be some problem in retrieving it

grand quarry
#

If you share the yaml someone might be willing to test it out and fix it

fallow sand
#

Hey everyone - is there a way to pass a sensor value to select.select_option?
I'm trying to set my ecobee homekit controller preset based on a sensor value that is defined by a schedule, but while this is accepted as a valid call, it doesn't seem to work:

service: select.select_option
data:
  option: "{{ states('sensor.downstairs_hvac_preset') }}"
target:
  entity_id: select.downstairs_current_mode

thanks!

acoustic arch
#

why do i get these slashes when going from GUI to Yaml?
- wait_template: "{{ is_state(\"switch.v2_hal_mvbox_stand_3\", 'off') }}"

#

and if i paste this in develop tools-->templates, its invalid๐Ÿ˜ตโ€๐Ÿ’ซ

marble jackal
#

because the GUI uses double quotes inside and outside the template, and therefor has to escape the quotes inside the template

#

it will be rendered correctly, but indeed doesn't work in the devtools

acoustic arch
#

ok thanks!.

#

its nog a bug, its a feature! ๐Ÿฅณ

plain magnetBOT
lofty mason
mighty ledge
#

it looks like he's using the service caller on dev tools -> services tab

#

which doesn't accept templates

lofty mason
#

what yes it does

mighty ledge
#

it's a pretty common mistake

lofty mason
#

I just tested this ?

mighty ledge
#

Unless something changed, it's never accepted templates

lofty mason
#

"The UI does not support templates, you can still use the YAML editor."

mighty ledge
#

๐Ÿคทโ€โ™‚๏ธ must be a new addition

#

historically, it has never accepted templates

lofty mason
#

glad it does now ๐Ÿ˜

mighty ledge
#

Ya, I was just looking for it

#

myself

#

It was a PITA for years

#

I must have forgotten about it and the PSTD from dealing with no-templates in that area trumped my memory

rich fjord
#

Hey there! Which color names can I use in Home Assistant in templates? I tried HTML color names but not all seem to work. Can I also use hex color codes? How? ๐Ÿ™‚

analog mulch
#

Trying to reuse template macros. I have a file "/config/custom_templates/weather.jinja" which contains the macro eaqi_list. I call (in the template editor) {% from 'weather.jinja' import eaqi_list %} and I get an error TemplateNotFound: weather.jinja. What am I doing wrong?

mighty ledge
#

did you restart after adding it?

analog mulch
#

ah, you mean reloading the templates is not enough?

mighty ledge
#

the first time you add them, you need to restart

#

and reloading templates does not reload custom templates, it reloads template entities

analog mulch
#

ok, I did not restart after editing weather.jinja from empty to containing something. Let's see if this solves it

#

but do I now need to restart every time I tweak any macro in custom_templates?

#

or just the first time it is created?

mighty ledge
#

no, you just need to call the homeassistant.reload_custom_templates service call

#

it's not a button in the UI

#

you have to manually call it from developer tools -> services or make a button that calls that service

analog mulch
#

ok restarting has fixed it. thanks a lot @mighty ledge Petro

mighty ledge
#

๐Ÿ‘

fallow sand
south stirrup
#

If i want to change the change the blue background of my google cast cards on the dashboard, can i use poster: url ? Or is it an different code, can't get it to work

#

source: Galaxy S8
type: media-control
entity: media_player.spotify_mvdl

plain magnetBOT
mighty ledge
#

You can't do that

#

secrets can't be used in templates

#

Sometimes you can work around the issue with template sensors using the new template style instead of the old template style

#

in your case...

#
template:
- trigger:
  - platform: state
    entity_id: sensor.my_iphone_bssid
    not_to:
    - unknown
    - unavailable
    variables:
      bssids: !secret home_bssids
  binary_sensor:
  - name: My iPhone
    device_class: presence
    state: >
      {{ trigger.to_state.state in bssids }}
echo shard
#

Thanks, let me try that

spark flame
#

petro should teach a templates class haha

echo shard
#

So I added that to my configuration and reloaded, but I can't see the new binary_sensor

mighty ledge
#

when you add the new template integration you have to restart

echo shard
#

Ah not just a Quick Reload then

mighty ledge
#

reload only works if it's loaded in

#

after you add it once, reload will work on any new template you add

#

but the first one, you have to restart

echo shard
#

OK, it's there now, but is set to 'unknown' even though the BSSID is in the secrets list..

#

Does it only update when the value changes...

mighty ledge
#

yep

#

if you want it to check on restart, you need to add that trigger

#

and also add variables to that trigger too

echo shard
#

oh

#

no idea how to do that tbh

#

Should I be using Node Red or something instead?

mighty ledge
#

You don't know how to add a trigger to that?

echo shard
#

I've been coding for 40 years, but been using home assistant for 1 day ๐Ÿคฃ I'll get there

#

The problem is there seems to be a lot of different syntaxes so googling is taking time

#

I think the template system has undergone changes

mighty ledge
#
template:
- trigger:
  - platform: state
    entity_id: sensor.my_iphone_bssid
    not_to:
    - unknown
    - unavailable
    variables:
      bssids: !secret home_bssids
  - platform: homeassistant
    event: start
    variables:
      bssids: !secret home_bssids
  binary_sensor:
  - name: My iPhone
    device_class: presence
    state: >
      {{ trigger.to_state.state in bssids }}
echo shard
#

Declarative languages in DSLs tend to take a little longer to get your head around ๐Ÿคท๐Ÿผโ€โ™‚๏ธ

#

That makes sense, so the triggers are OR'd and the variable has to be defined on both triggers to ensure it's available when the template is evaluated for the binary_sensor state

#

I can pick stuff up pretty quickly usually

#

This is literally the first template I'm writing

#

So apologies for being a bit n00b

mighty ledge
#

it's all good

echo shard
#

So do I have to duplicate this template trigger for each sensor, or is there a more elegant way (blueprints?)

#

I don't like copy pasta

mighty ledge
#

if you have multiple phones you're checking with the same list of bssids, then just copy/paste the binary_sensor with a different name

#

otherwise you'll have to come upwith a different way to represent the data

#

like a map

#

(dictionary - if you know software

echo shard
#

Yeah, I understand dict/maps

mighty ledge
#

ok, so...

#
home_bssids:
  '****fd': sensor.my_iphone_bssid
   '****13': sensor.sons_iphone_bssid
  ...
#

then

marble jackal
#

You could also put that list in a file in your custom templates folder, and import it

mighty ledge
#
template:
- trigger:
  - platform: state
    entity_id:
    - sensor.my_iphone_bssid
    - sensor.sons_iphone_bssid
    not_to:
    - unknown
    - unavailable
    variables:
      bssids: !secret home_bssids
  - platform: homeassistant
    event: start
    variables:
      bssids: !secret home_bssids
  binary_sensor:
  - name: My iPhone
    device_class: presence
    state: >
      {{ bssids.get(trigger.to_state.state, None) == 'sensor.my_iphone_bssid' }}
#

you have to reverse the bssid lookup probably

echo shard
#

The BSSIDs are the wireless access points in the house, so the idea is to have a simple presence sensor when a phone is connected to any of the BSSIDs in the list. So it's not unique to each phone, but there should be a unique binary_sensor per phone.

mighty ledge
#

there, that would work

echo shard
#

Also, my state is still 'unavailable' despite adding the start up check ponder

mighty ledge
#

it's possible secrets are just strings

echo shard
#

Yeah, I think they infamously are

mighty ledge
#

then...

echo shard
#

I tried an input_select, but I couldn't get that array in a template either

mighty ledge
#
home_bssids: >
  { "****fd": "sensor.my_iphone_bssid", "****13": "sensor.sons_iphone_bssid" }
#

and...

#
template:
- trigger:
  - platform: state
    entity_id:
    - sensor.my_iphone_bssid
    - sensor.sons_iphone_bssid
    not_to:
    - unknown
    - unavailable
    variables:
      inp: !secret home_bssids
      bssids: "{{ inp | from_json }}"
  - platform: homeassistant
    event: start
    variables:
      inp: !secret home_bssids
      bssids: "{{ inp | from_json }}"
  binary_sensor:
  - name: My iPhone
    device_class: presence
    state: >
      {{ bssids.get(trigger.to_state.state, None) == 'sensor.my_iphone_bssid' }}
#

but you gotta make sure home_bssids is valid json

echo shard
#

Ooo 'from_json', ...

#

lemme try

mighty ledge
#

and if you're interested... read up on yaml anchors. It will shorten the code to...

template:
- trigger:
  - platform: state
    entity_id:
    - sensor.my_iphone_bssid
    - sensor.sons_iphone_bssid
    not_to:
    - unknown
    - unavailable
    variables: &bssid_variables
      inp: !secret home_bssids
      bssids: "{{ inp | from_json }}"
  - platform: homeassistant
    event: start
    variables: *bssid_variables
  binary_sensor:
  - name: My iPhone
    device_class: presence
    state: >
      {{ bssids.get(trigger.to_state.state, None) == 'sensor.my_iphone_bssid' }}
echo shard
#

Oooo nice

eternal hazel
#

does your wifi/router not have a native integration?

echo shard
#

I prefer BSSIDs are more secure/unique than SSID

floral steeple
#

hi all, what wrong with my formatting, here: it does not like something but I cannot figure it out: thanks

    - name: recycle_collection
      unique_id: c9ec687d-be8d-44cb-9943-980e539d3506
      state: >-
        {{ min(((state_attr('calendar.recycling_refuse','start_time') | as_timestamp - today_at('00:00') | as_timestamp) / 86400) | int,2) }}
      attributes: >-
        days: 
          {{ ((state_attr('calendar.recycling_refuse','start_time') | as_timestamp - today_at('00:00') | as_timestamp) / 86400) | int }}
eternal hazel
floral steeple
#

error message:

Source: config.py:982
First occurred: 12:45:09 PM (2 occurrences)
Last logged: 12:45:44 PM

Invalid config for [template]: expected a dictionary for dictionary value @ data['sensor'][28]['attributes']. Got "days: \n {{ ((state_attr('calendar.recycling_refuse','start_time') | as_timestamp - today_at('00:00') | as_timestamp) / 86400) | int }}". (See /config/templates.yaml, line 1).
echo shard
eternal hazel
mighty ledge
eternal hazel
#

mine takes 3-5 minutes (i forget what the wifi timeout is) until it treats the endpoint as offline

echo shard
#

OK, feel like I'm getting close:

eternal hazel
#

too late ๐Ÿ˜„

echo shard
#

Secrets.yaml (obfuscated)

  [ '...:fd',
  '...:13',
  '...:7b',
  '...:29',
  '...:6d',
  '...:71',
  '...:8' ]```
#

That should create a JSON array

plain magnetBOT
echo shard
#

No errors, but still shows 'unknown' even when phone's BSSID is in array, and after restart...

mighty ledge
#

well, you didn't relaly do it right

echo shard
#

oh

mighty ledge
#

JSON requires "

echo shard
#

That's a JSON array...

mighty ledge
#

it's a json array with bad values inside

echo shard
#

JSON strings can be quoted either way

mighty ledge
#

JSON does not accept '

#

they cannot

floral steeple
echo shard
mighty ledge
#

by all means, you can also go the route you're going

#

but your code and configuration will be 10x

#

if you use a dictionary instead of a list, your total config will be

#
template:
- trigger:
  - platform: state
    entity_id:
    - sensor.iphone_1_bssid
    - sensor.iphone_2_bssid
    not_to:
    - unknown
    - unavailable
    variables: &bssid_variables
      inp: !secret home_bssids
      bssids: "{{ inp | from_json }}"
  - platform: homeassistant
    event: start
    variables: *bssid_variables
  binary_sensor:
  - name: My iPhone
    device_class: presence
    state: >
      {{ bssids.get(trigger.to_state.state, None) == 'sensor.iphone_1_bssid' }}
  - name: My 2 iPhone
    device_class: presence
    state: >
      {{ bssids.get(trigger.to_state.state, None) == 'sensor.iphone_2_bssid' }}
#

ah, but there is an issue

#

since we added the second trigger

#

the template in state won't work

#

I'll have to come back another time as I have a work call

echo shard
#

No problem, still isn't working for me sadly

#

But some good learning thank you

#

Need to figure out how to debug

floral steeple
marble jackal
#

The text provided there is slugified to the entity_id

#

And if you provide a unique_id you can change the name, entity_id, icon and area in the UI

floral steeple
#

you're right, I just changed it in the UI. thanks!

floral steeple
#

I'm trying to figure out how to create an even using the local calendar integration that runs every week (all day), from April 1 to Aug 31, every year? When I try to set this up, it works but only for 1 year. Would some sort of templating fix or automate this as I don't think its a function the calendar support (yet).

terse walrus
#

Hey there, what is the best way to determine the max precipitation probability in the next X hours from an hourly weather entity?

#

Essentially, how do I turn something like this (returns a list of dicts)

{{ state_attr('weather.my_weather','forecast')[0:3] }}

into this

[4, 15, 15]

Where each element in the list is the value for 'precipitation_probability' from each forecast dict?

inner mesa
#

{{ state_attr('weather.wf_udp', 'forecast')[0:3]|map(attribute='precipitation_probability')|list }}

#

->

[
  40,
  30,
  20
]
terse walrus
#

Ah, map(). Perfect, thank you!

plain magnetBOT
haughty breach
floral steeple
opal pulsar
#

Hi friends ) Maybe its a stupid question but i wasted half day and cant finish this )
i need and entity that will tell my thermostats in what mode they must run ( winter/summer mode ) , i wrote in my conf.yaml this code:
input_select:
thermostat_mode:
name: Thermostat Mode
options:
- Winter
- Summer
initial: Winter
now my problem is icon )) i cant do diferent icons for diferent states (( i found this one , them must change by himself as i understand but it does not work (
mdi:SunSnowflakeVariant

marble jackal
#

input_select entities have a fixed icon

merry marsh
#

Yes. card-mod related but error is at least displayed as template-error/problem. Any clue, how to dig deeper to see which template leads to this error message exactly?

marble jackal
#

what's the template? ๐Ÿ™‚

merry marsh
#

That is the question.

#

๐Ÿ˜‰

#

It is a genaral error from my UI. So a lot of templates are in this page. And one is leading to this and I don't know which.

hexed laurel
#

I suck at HA,

{%- if states('sensor.time') | as_timestamp >= '5:00' %} Good Morning! {% else %} Hey! {%- endif %}

Is throwing me and error that there's an invalid input, can someone point out my moronity?

marble jackal
#
{%- if  now() >= today_at('5:00') %} 
Good Morning!
{% else %}
Hey!
{%- endif %} 
#

you were comaring an inteteger (timestamp) with a string

#

something like 18000 > "05:00"

mighty ledge
lapis flax
#

anyone around, good at extracting data from a JSON in a template? i need a bit of help

mighty ledge
hexed laurel
#

Appreciate it @marble jackal !

lapis flax
#

can anyone point me in the right direction, if i want to extract the value from 17:00:00 each day, and from 21:00:00 each day.. and the days that the 21:00:00 value does not exist, i want to extract the lates value instead.. i cant figure out where to start from this JSON ?? https://pastebin.com/kfPVXGsD

merry marsh
# mighty ledge If it's a template that's passed to the backend, i.e. it's jinja, it will output...

It was a template in a card-mod section. No further details in the logs. Because of this I thought, if there is another way to get nearer to the problem. At the end of the day I have duplicated the view and removed one card after another and then put the templates of the last card in the dev-tools and foud the problem. But ofc it would be faster, if I would be able to see the input with the error seomewhere.

floral shuttle
#

figured I had enough guards here: {% set nu = now().replace(minute=0, second=0 , microsecond=0).isoformat() %} {% set watts = state_attr('sensor.solar_forecast_estimate_watts','watts')%} {% set data = watts.items() %} {{watts[nu] if nu in watts else 'No production estimated'}} and yet every now and then I see Template variable error: 'None' has no attribute 'items' when rendering '{% set nu = now().replace(minute=0, second=0 , microsecond=0).isoformat() %} {% set watts = state_attr('sensor.solar_forecast_estimate_watts','watts')%} {% set data = watts.items() %} {{watts[nu] if nu in watts else 'No production estimated'}}'

#

do I really need to add a guard on the attribute itself?

#
          {% set nu = now().replace(minute=0, second=0 , microsecond=0).isoformat() %}
          {% set watts = state_attr('sensor.solar_forecast_estimate_watts','watts')%}
          {% if watts %}
          {% set data = watts.items() %}
          {{watts[nu] if watts and nu in watts else 'No production estimated'}}
          {% else %} Offline
          {% endif %}```
marble jackal
#

You can default watts to an empty dict

#

{% set watts = state_attr('sensor.solar_forecast_estimate_watts','watts') | default({}, true) %}

copper blade
#

I'm using a utility_meter to sum up the values of a sensor. This works, but I have one issue wich I don't see from the docs how I can solve it. The utility_meter shall provide the sum of the day. The sensor reports, how much energy has been consumed the last hour, so e. g. 9-10: 55 Wh, 10-11: 88 Wh, 11-12 110 Wh, ... 14-15 66 Wh. My issue is the utility_meter will not add the values from the sensor once the values start dropping. In the e. g. It will stay at 110 Wh (which was the maximum value on that day). Any ideas how to solve this?

utility_meter:
  solarthermie_tagesleistung:
    name: "Solarthermie Tagesleistung"
    unique_id: "SolarthermieTagesleistung"
    source: sensor.solar_energylasthour
    cycle: daily
copper blade
errant hinge
#

Is there 'best practice' for where to create/save templates, etc. please?
Watched https://www.youtube.com/watch?v=FfjSA2o_0KA recently and I realised there are probably plenty of ways to achieve something in Home Assistant but potentially some may be poor for performance.

I have a couple of integrations that provide 'measurement' (state_class) entities with a 'unit_of_measurement' in Watts. For my dashboard, I would like some of them displayed in kW to one decimal place.

While it seems possible to use the dashboard code editor to tweak a card label, is there a better/correct way? Helper?

      {{ states('sensor.myenergi_zappi_XXX_internal_load_ct1') | float /1000 | round(1) }} kW```
inner mesa
#

you're just rounding 1000, BTW

#

nothing wrong with creating a template sensor for that

#

or do it in the frontend if the card supports it

mighty ledge
#

click the entity, click settings, change your units and precision

errant hinge
#

deleted out of context reply

mighty ledge
#

pretty sure it's global

#

just refresh your page

errant hinge
#

Ah, in this instance I don't think this specific integration is using the units in that way so changing them in configuration is not possible. I think many of the numeric values are being returned as strings, hence the need for the | float

mighty ledge
#

no, that's a miss understanding on your part

#

all states are strings in templates

#

any entity (that's a sensor) added by the UI will have the ability to change the UOM or precision

#

if it's added via yaml, there's ways to get it to allow you to change those settings

errant hinge
#

Thank you. When I change the unit to kW and click 'Update' it seems to revert to W.

mighty ledge
#

refresh your page and make the change

#

ctrl+F5 to hard reset the page

errant hinge
#

I tried via the dialog that's shown from the entity on both /developer-tools/state and /config/entities. Will try again tomorrow, maybe from the phone app.

mighty ledge
#

it's the same dialog

#

they are not different

#

just do it in 1 spot

#

change it, click update and it'll be done

#

otherwise check your log for errors

errant hinge
#

Just tried on the phone app. It works fine for an entity in the Solaredge integration but not for the myenergi integration entity. I will submit an issue on the myenergi integration GitHub. I couldn't spot anything obviously related in the logs. Thanks for your help.

winter path
#

Hi all, wondering if someone can help me out with a cover template. I installed a zen16 relay for my garage with a zse43 tilt/shock sensor. The basic cover I was able to make and will paste below. What I would like to do is make it so if it was in the closed position, and then the shock is detected, it will show a status of opening, and vice versa. Not sure if that is possible.

#

`cover:

  • platform: template
    covers:
    small_garage_door:
    device_class: garage
    friendly_name: "Small Garage Door"
    value_template: "{{ is_state('binary_sensor.small_garage_door_window_door_is_open', 'on') }}"
    open_cover:
    service: switch.turn_on
    entity_id: switch.small_garage_door
    close_cover:
    service: switch.turn_on
    entity_id: switch.small_garage_door
    stop_cover:
    service: switch.turn_on
    entity_id: switch.small_garage_door`
dusk sorrel
#

hi all does not work break

#
{% if character == ' ' or character == '|'  %} {% break %} {% endif %}
marble jackal
#

I assume this is part of a for loop

#

please post the whole template, nog just a snippet

dusk sorrel
#

Just i need break "for loop" in certain case. How to it?

dusk sorrel
#
{# {% set vol=states('sensor.serial_sensor').split(' ')[5] %} #}
{% set data = states('sensor.serial_sensor') %}
{% set index = data.find('V') %}
{% set voltage = 0 %}
{% set multiple = 1 %}
{% set index = index-1 %}
{% for i in range(index) %}
  {% set character = data[index-i] %}
  {% if character != ' ' or character != '|'  %} {%break%} {% endif %}
  char={{ character }}
  voltage = {{voltage}}
{%endfor%}
{{data}}
index={{index}}
#

error

#
TemplateSyntaxError: Encountered unknown tag 'break'. Jinja was looking for the following tags: 'elif' or 'else' or 'endif'. The innermost block that needs to be closed is 'if'.
marble jackal
#

@dusk sorrel are your running 2023.4?

#

Because the {% break %} function has been introduced in that version

dusk sorrel
#

ok thank you

lean yacht
#

Hi,
I've created a template sensor, however the sensor cannot be selected in the logbook (it does show up in history).
The sensor is not excluded from the recorder.
Any clue why ?

lofty mason
pale star
#

hi, does anyone know what I do wrong here? this works in the development tools templates but does fail when it's present in configuration.yaml
value_template: "{{ ((states('sensor.total_photovoltaics_energy') |float - states('sensor.smart_meter_ts_65a_3_energy_real_produced') | float /1000) + states('sensor.smart_meter_ts_65a_3_energy_real_consumed') | float /1000) | round(3) }}"

inner mesa
#

'Fail'?

pale star
#

2023-04-14 13:24:25.841 ERROR (MainThread) [homeassistant.bootstrap] Failed to parse configuration.yaml: while parsing a block mapping in "/config/configuration.yaml", line 1, column 1 expected <block end>, but found '<block mapping start>' in "/config/configuration.yaml", line 418, column 7. Activating safe mode

#

it's this code that gives me trouble ๐Ÿ˜ฆ

energy_self_usage: unique_id: 'energy_self_usage' friendly_name: "Energy_Self_Usage" unit_of_measurement: 'kWh' ย ย ย ย ย ย ย value_template: "{{ ((states('sensor.total_photovoltaics_energy') |float - states('sensor.smart_meter_ts_65a_3_energy_real_produced') | float /1000) + states('sensor.smart_meter_ts_65a_3_energy_real_consumed') | float /1000) | round(3) }}"

inner mesa
#

I don't see anything obviously wrong in that snippet. It's probably in the context around it

pale star
#

if I use this all works

energy_self_usage: unique_id: 'energy_self_usage' friendly_name: "Energy_Self_Usage" unit_of_measurement: 'kWh' value_template: "{{ (states('sensor.total_photovoltaics_energy') |float - states('sensor.smart_meter_ts_65a_3_energy_real_produced') | float /1000) | round(3) }}"

#

only difference is that I added one more set of brackets and another calculation for a parameter

plain magnetBOT
floral steeple
#

Hi All, would this be a way to trigger an automation on a specific day, i.e. April 1st, every year

trigger:
  - platform: template
    value_template: "{{ now().month == 4 and now().day == 1 }}"
lofty mason
floral steeple
haughty breach
#

Use a calendar event trigger

floral steeple
#

Thanks again!

#

thinking about this, I would have to make an event in the calendar

#

but, when I try to use it as a trigger, it only gives me the option to select a calendar. not an event (at least in the UI)?

lofty mason
loud mountain
#

i want to output the remaining time in minutes, but the output is not round ( 21.52974258263906 ), any fix?
thanks

{% if state_attr(timer,'finishes_at') %}
  {{(as_timestamp(state_attr(timer,'finishes_at'))-as_timestamp(now())) /60| round(default=0)  }}
{% else %}```
inner mesa
#

You're rounding 60

loud mountain
#

it's in second to minutes so /60?

inner mesa
#

You're rounding 60

#

You need to add parentheses

loud mountain
#

in the (/60)?

inner mesa
#

No

loud mountain
#

sorry i'm noob, please let me know thanks

inner mesa
#

{{((as_timestamp(state_attr(timer,'finishes_at'))-as_timestamp(now())) /60)| round(default=0) }}

#

you're applying round(default=0) to 60

#

you need to apply it to the entire expression

loud mountain
#

ah i see it

#

so /60 before round

inner mesa
#

you need parentheses, as I showed above

loud mountain
#

cool

clear mist
#

hey guys, i'm trying to make a script to play specific media when a button on the dashboard is pressed - the script is the same except the title of the media, which will be from the button

i've got this code, which works, but i can only hardcode the value for INSERT_MEDIA_TITLE_HERE - i don't know how to make it based on a value from a button or something else

data:
  media_content_type: EPISODE
  media_content_id: >-
    plex://{ "library_name": "TV Shows", "show_name": INSERT_MEDIA_TITLE_HERE,
    "episode.unwatched": true, "episode.inProgress": [true, false], "resume": 1,
    "sort": "originallyAvailableAt:asc", "maxresults": 1 }```

if anyone has any ideas on how to make this work, that'd be appreciated!
marble jackal
#

You can't use templates in a tap action, you need to use a script or automation

clear mist
#

yeah, i figured it out - i've used a script with service_data values that i'm passing in from the buttons

#

hey guys, another question:

i'm trying to make 5-6 buttons that all call the same script with different service_data, and depending on the value of the service_data, i want it to do something

i'm stuck on how to get a script that can do 5-6 different things based on the service_data value? how would i make a script that does this? would i want to make an action for "wait for template", run the code and just end the whole thing in {{ true }}, or is there a better way?

thorny snow
tidal heart
#

I have this template sensor that gives me open windows/doors as a text like "Open in bedroom", "Open in bedroom and bathroom window open" etc etc. Its a long one, can this be made in a better way? I just tried and tried until I got a good resault but sometimes I get Error while processing template: from it. https://pastebin.com/9VuMkx1m

rose scroll
clear mist
#

it's annoying when things fail, but when it starts working finally then it feels good

rose scroll
# tidal heart I have this template sensor that gives me open windows/doors as a text like "Ope...

To compile the list of open doors:

{% set open_doors = states.binary_sensor | selectattr('attributes.device_class', 'defined') | selectattr('attributes.device_class', 'eq', 'door') | selectattr('state', 'eq', 'on') | map(attribute = 'attributes.friendly_name') | list %}
{% set ns = namespace(output = '') %}
{% for door in open_doors %}
  {% if door != open_doors[-1] %}
    {% set ns.output = ns.output + door + ', ' %}
  {% else %}
    {% set ns.output = ns.output[:-2] + ' and ' + door %}
  {% endif %}
{% endfor %}
#

Then to pretty_print it:

{% if open_doors | length == 0 %}
  {% set ns.output = 'No doors are open.' %}
{% elif open_doors | length == 1 %}
  {% set ns.output = ns.output + ' is open.' %}
{% else %}
  {% set ns.output = ns.output + ' are open.' %}
{% endif %}
{{ ns.output }}
tidal heart
#

Thanks!

fallow gulch
#

I'd like to set up a template binary sensor that turns on when an existing binary sensor does, and only turns off when that same sensor and another sensor do (ideally for more than 10 minutes)

#

i can't seem to find any examples of how to do this though

mighty ledge
#
template:
- trigger:
  - id: 'on'
    platform: state
    entity_id: binary_sensor.1
    to: 'on'
  - id: 'off'
    platform: template
    value_template: "{{ is_state('binary_sensor.1', 'off') and is_state('binary_sensor.2', 'off') }}"
    for:
      minutes: 10
  binary_sensor:
  - name: Whatever
    state: "{{ trigger.id }}"
#

keep in mind that it will be unknown after you first create it

#

then whenever binary_sensor.1 turns on for the first time, it will be on until the off trigger occurs. After that, the state will persist over restarts.

fallow gulch
#

until the state of the target sensor changes, i gather

#

yep

#

I use a separate template.yaml, so I guess I put that trigger section outside of the sensor and binary_sensor sections?

mighty ledge
#

no

#

that whole chunk needs to go together

#

post the contents of your current file that's separate. Also post the include you're using

fallow gulch
#

config.yaml has
template: !include template.yaml

plain magnetBOT
fallow gulch
#

which i'm guessing is not right

mighty ledge
#

No, remove the - template:

fallow gulch
#

it didn't like that

#

template integration failed to load

marble jackal
marble jackal
fallow gulch
#

ah!

#

that makes sense

#

that's working now!

silent vector
exotic grail
#

it says km if you scroll up a few lines

river elk
#

Looking for some help with a template. this is just one part of my "morning brief" that is played each morning. I want it to print out (tell me) if a leak sensor was set off in the last 12 hours and which one it was. the "state" is either on or off and the reported attributes are: battery: 72.5, battery_low: false, linkquality: 123, tamper: false, temperature: 27.03, voltage: 2800, water_leak: false, device_class: moisture, friendly_name: G-Bathroom Leak Sensor water leak. This what I have and it does not error out but it also does not report if any of the sensors are set off. I have purposely set them off but I always get none have reported wet. ```
{% set leak_sensors = [
'binary_sensor.ac_leak_sensor_water_leak','binary_sensor.fridge_leak_sensor_water_leak','binary_sensor.g_bathroom_leak_sensor_water_leak','binary_sensor.lr_sink_water_leak_sensor_water_leak','binary_sensor.washer_water_leak_sensor_water_leak','binary_sensor.mb_birgit_leak_sensor_water_leak','binary_sensor.mb_joe_leak_sensor_water_leak',
] %} {% set twelve_hours_ago = now().timestamp() - 12 * 60 * 60 %} {% set
wet_sensors = [] %} {% for sensor_id in leak_sensors %} {% if
states(sensor_id) == 'wet' and as_timestamp(states(sensor_id).last_changed)
>= twelve_hours_ago %} {% set _ =
wet_sensors.append(sensor_id.split('.')[1]) %} {% endif %} {% endfor %} {%
if wet_sensors %} The following leak sensors reported a state of "wet" in
the last 12 hours: {{ wet_sensors | join(', ') }}. {% else %} None of the
leak sensors reported a state of "wet" in the last 12 hours. {% endif %}

obtuse zephyr
#

You had initially said they report on/off (which is true), but then in the template you look for wet

#

Keep in mind, that template will only report sensors that are actively wet

river elk
obtuse zephyr
#

And, you need a namespace var if you'll be appending like that

marble jackal
#

as_timestamp(states(sensor_id).last_changed) you need square brackets around the sensor_id here

river elk
marble jackal
#

If you search on namespace in this channel you'll probably have enough examples

river elk
marble jackal
#

You can do all that by just using filters, there is no need for a loop and namespace

#

Wait, maybe the storms append part

#

What are you trying to achieve

#

You only want the object_id right?

#

That can also be easily achieved

river elk
# marble jackal What are you trying to achieve

So I have a "morning brief' that HA speaks to me. I just want it to tell me if any leak sensors went off in the last 12 hours and which ones. Mind you I have automations that go off, scream over my speakers and blink lights etc. They work. I am just pisse dthat I can't get this to work so I am bull-dogging it!

livid rain
#

I have automation that turns on lights in the evening by activating a scene, but I don't want it to touch lights that are already on. A script that iterates through the lights set in the scene and only takes action on those that are off perhaps. It gotta be based on the scene, I change it often, I can't hardcode lights and settings.

marble jackal
#

{{ expand(leak_sensors) | selectattr('state', 'eq', 'on') | selectattr('last_changed', '>=', now() - timedelta(hours=12)) | map(attribute='object_id') | join(', ') }}

marble jackal
livid rain
#

Yeah, a script that reads the scene

#

I'm struggling with a template that can read the status of the lights set in a scene and save all the lights that are off to a new temp scene

marble jackal
#

What do you mean with reads the scene

livid rain
#

Finds the lights set in a scene and then their status

river elk
marble jackal
marble jackal
livid rain
#

Well, if I have two lights in my scene, one off and one on, I want it to check both entity_id's for their status, and save the entity_id that are not on to a variable

#

And read the scene.yaml for what settings the lights that are off should be set to, then add that to a new temp scene, then activate that scene, then wait a bit, then delete the temp scene

#

Unless there's a better way

marble jackal
inner crest
#

im a lost puppy, looked at the docs of configuration/templating and no clue how to set it to none if no update for X minutes

marble jackal
edgy umbra
#

This shows as 11:3, any change to show 11:03?

#
  var d = new Date(entity.last_changed);
  return `${d.getHours()}:${d.getMinutes()}`
]]]```
marble jackal
#

This will be the time in UTC BTW

edgy umbra
#

Oh OK.

inner crest
#

i want to set it to "none" or whatever if no update

marble jackal
#

This will be true if sensor.device has changed more than 10 minutes ago

inner crest
marble jackal
#

What do you want it changed less than 10 minutes ago?

inner crest
#

cuz my stuff will be uodated via api

marble jackal
#

{{ 'something' if now() > states.sensor.device.last_changed + timedelta(minutes=10) else 'something else' }}

#

'something' can also be none

inner crest
#
template:
  - binary_sensor:
      - name: "Gaming Server "
        state: "{{ none if now() > states.sensor.device.last_changed + timedelta(minutes=10) }}"```

looks good?
inner mesa
#

You have no 'else'

marble jackal
#

Which will mean it will always be none

inner crest
#

else pass?

marble jackal
#

But if it's for a binary sensor you need true or false

inner crest
#

by pass i mean do nothing

#

like py

marble jackal
#

So there is some device. You want to check if it has changed more than 10 minutes ago.
You want to use that in a binary sensor, which expects true or false for it's state template.

inner crest
#

yes it's a server, either it's on or off, or the status is unknown

marble jackal
#

Also know that last_changed is reset after a HA restart, so it will always be true for the first 10 minutes after a restart

inner crest
#

guess will set it to a minute then lol

inner crest
marble jackal
#

No that will always return none

inner crest
#

what should i put as else then?

#

whatever the last sensor value was?

marble jackal
#

You can refer to this.state to get the current state

inner crest
#

guess that should work

marble jackal
#

But that still doesn't make sense

inner crest
#

how so?

marble jackal
#

Because the binary sensor state template expects true or false

inner crest
#

can't it be undefined?

marble jackal
#

And you are feeding it none or the current state

#

So that will result in it being off (none) or off (current state)

inner crest
#

so ill just go with int

marble jackal
#

It's like you're having a green fence and you are saying you want to paint it green, or the current color

marble jackal
inner crest
#

integer

#

cuz integer can be null definetly

#

but how does HA know someth9ing is " Unavailable"?

#

this is what i want to set the sensor to

marble jackal
#

You can define an availability template

#

Which is explained on the same page as I linked above

inner crest
#

so then i would need 2?

inner mesa
#

It seems like you e list track of the actual goal

#

You're just in the weeds now

inner crest
#

yes, because i dont see how there isn't a simple setting to set it to "unvaiable" if no update
pretty sure someone did this before me

#

no clue, compleatly lost

marble jackal
#

Maybe it will help to explain what your goal is here, but I'm off to bed now

inner crest
#

alrady did

inner crest
#

and another server will just send api requests to ha letting it know if the server is on or off

#

but it should fail back to unavailable or null or whatever if there is no updates

silent flicker
#

I tried to do

{{ states.calendar.home_assistant.attributes.summary }}

to get the event title, but I got an error:

UndefinedError: 'homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'summary'

should i actually be using:

{{ states.calendar.home_assistant.attributes.message }}

instead?

#

.message actually works and gives me the event title, but i thought the summary was for that

#

maybe i'm remembering wrong

haughty breach
#

summary returns the title of the calendar event when you are referencing the trigger variable like trigger.calendar_event.summary.

message returns the the title of the current or next calendar event when referencing the state object of the calendar entity like states.calendar.example.attributes.message. or state_attr('calendar.example', 'message') The correct one to use depends on what you are trying to do.

silent flicker
#

so im using an automation that works based off when the home_assistant calendar triggers. so that makes sense

#

but if i want to debug, how do i see the summary in the templates? do i just use "message" to see it instead?

#

since it looks like i can only use summary when an automation is being triggered?

#

basically i want to see what the summary value is in the templates but i dont see a way to call it. only way i see to call it, is by using the "message" which appears to be the same value

haughty breach
#

The trigger variable only exist when the automation is triggered. The easiest way reliably test an automation that uses a calendar event trigger you need to use a test calendar event.

silent flicker
#

trying to test my event trigger but its not working for some reason, ugh

lofty mason
#

the trigger event data is all stored in the automation trace; click on "Changed Variables"

silent flicker
#

yeah i see the automation trigger but traces dont show anything, as if it never ran lol

#

ergh now i have to figure that out before i can figure out my summary / message issue

lofty mason
#

screengrab one of the traces; maybe you're not reading it correctly?

silent flicker
#

the timestamp on them never updates

#

im trying a cal event further out, just to see if maybe its not enough time to generate

lofty mason
#

there's some 15 minute rule on calendar triggers, like you can't create an event in the next 15 minutes I think

silent flicker
#

i think thats my issue

#

testing it now

lofty mason
#

Note that calendars are read once every 15 minutes. When testing, make sure you do not plan events less than 15 minutes away from the current time, or your trigger might not fire.

silent flicker
#

well when i did it less than 15 min, i was reloading the integration

#

and it showed up, but i wonder if that still isnt working

#

so im just doing one really far out

#

quite a pain to wait that long in between tests

#

unsure if theres more that needs to get stored, etc

silent flicker
#

yeah it still didnt trigger after 30min something else going on i gotta figure out now lol ugh

#
platform: calendar
event: start
offset: "0:0:0"
entity_id: calendar.home_assistant

using this but now its not triggering with an event lol it did for months

silent flicker
#

why doesnt this trigger?

#
alias: calendar test fix
description: ""
trigger:
  - platform: calendar
    event: start
    offset: "0:0:0"
    entity_id: calendar.home_assistant
condition: []
action:
  - service: notify.persistent_notification
    data:
      message: calendar has been triggered
mode: single
inner mesa
#

There's no template there

#

Your offset looks both malformed and unnecessary

silent flicker
#

sorry i am asking in the wrong channel on top of that

orchid oxide
#

is it possible in some way to, within a template, get the integration which an entitiy comes from

#

specifically i have a template that rejects devices with a source_type of router, but when the integration that the devices comes from (netgear) is reloading or off for any reason, that attribute disappears, which means the device(s) i dont want to be part of the resulting template show up anyways

#

and i figure if i can just specify devices that belong to that specific integration, it would just be simpler

marble jackal
#

You can use integration_entities() to list all entities of an integration

orchid oxide
#

Ooh unaware that existed ty, that's perfect

inner crest
heady mirage
# inner crest Could someone help out?

Not sure what others think. But maybe changing how you check the server maybe more helpful. Instead of pushing updates to HA, why not have HA 'ping' whatever system your wanting to check on a timer with a short timeout to prevent hanging threads when the system is offline

inner crest
daring swan
#

can I somehow combine if statements with template expressions?

plain magnetBOT
daring swan
#

I want to calculate the approx cost of filament for a print and for that I need to apply a factor based on the filament used (which I get from the filename of the print)

marble jackal
#

Not like this, you can either put the whole calculation in every part of the if statement, or set a variable

daring swan
#

yeah I went the variable way

plain magnetBOT
daring swan
#

Can I somehow access historic values of input_text?

plain magnetBOT
thorny canyon
#

Hey, I could really need some help with the "Message" content of an automation notification. I setup the "Waste Collection Schedule", sensors for the different waste types, as well as a sensor for the upcoming disposal day.
The automation checks for the next disposal event and if itโ€™s <2 days, it will send out a notification. I now want to include the waste type with the message, but canโ€™t find the right variables to fetch it from the โ€župcoming disposal dateโ€œ sensor.
Any help is much appreciated.
Find yaml configs above

#

This is the sensor Iยดm using for the notification (translated from German to English). I guess I canยดt use the garbage type in the message content, since itยดs not included in the "value_template"?

- platform: waste_collection_schedule
ย  ย  name: Next Disposal
ย  ย  details_format: "upcoming"
ย  ย  value_template: '{% if value.daysTo == 0 %}today{% elif value.daysTo == 1 %}tomorrow{% else %}in {{value.daysTo}} Days{% endif %}'
ย  ย  date_template: '{{value.date.strftime("%d.%m.%Y")}}'
ย  ย  add_days_to: 1

daring swan
#

Why is it not possible to access old values of an input_text field? ๐Ÿ˜ฆ

marble jackal
#

You can probably use an SQL sensor for that. And when using a state trigger you can get the old and new value from the trigger variables

#

But this is the same for all entities in Home Assistant, not just an input_text

daring swan
#

hm so I would like to look at the last 10 values for a table

#

ah I cannot post a picture but imagine a picture that only shows a table with one line instead of the desired 10 ๐Ÿคฃ

exotic grail
#

why do you even want that

daring swan
#

I want a table showing a log of the last 10 prints including cost

exotic grail
#

10 prints?

daring swan
exotic grail
#

oh 3d printer

#

...why not log your prints to a database

daring swan
#

ahk, yeah. Sorry should've said that

exotic grail
#

just add the table to a DB and read data off that. or put it in google sheets / excel etc

marble jackal
#

Looks like something for a Google sheet

daring swan
#

don't know why. HomeAssistant has so many things you can do that it overwhelms me ๐Ÿ˜„

exotic grail
#

it's not really a legit use case for input_text

#

that's a kludge

marble jackal
#

It's built to automate your home, not to create spreadsheets

daring swan
#

well I have all the data in Homeassistant and just search a structure where I can save it

exotic grail
#

you could have HA trigger writing into a DB / sheet maybe

daring swan
#

the issue I'm having with going external is that I have all the data required to show already in HA and am just fighting to be able to access it in a way that allows me to list the prints on my printing dashboard

marble jackal
#

You could create 10 input texts and write the data to them on every state change (so it the first one the latest state, and then in the second one the previous state of the first one, etc)

exotic grail
#

add in a counter so know which one to write to next ๐Ÿ˜„

marble jackal
#

Or do something similar in the attribute of a trigger based template sensor

daring swan
#

mh yeah that's DEFINITELY a kludge xD

lofty mason
#

If you ever play with nodered it's really easy to get historical data that way, with the history node.

#

give you all the states and attributes of a given time window

daring swan
#

I was hoping that I could somehow access the old values that are obviously there as you can access them with the history view of the entity

lofty mason
#

Yeah I've always been a bit surprised there was not an easier way to retrieve the historical stuff. One of the few things I still go to NR for.

#

I guess maybe SQL sensor is the equivalent

daring swan
#

but nodered is also on my bucket list. However I already had to learn python to get the duet3d integration to a state that allows me to get the necessary data into HA so I had to cut my complexity for the moment to get anywhere. But anyways, this has nothing to do with template-related stuff anymore

languid pendant
inner mesa
#

What did you try?

languid pendant
#

I added system_log: fire_event: true to configuration.yaml In automations, I used evvent type: system_log_event for a trigger, under event data I've tried multiple values but nothing works. I simulate a log entry I use dev tools/services/System Log: Write Message: bevis

inner mesa
#

do you see events? I just added this to configuration.yaml and I see events that I could trigger on:

system_log:
  fire_event: true
#
event_type: system_log_event
data:
  name: custom_components.hacs
  message:
    - Could not update theme - Timeout of 60s reached
  level: ERROR
  source:
    - custom_components/hacs/base.py
    - 850
  timestamp: 1681668750.1706276
  exception: ""
  count: 1
  first_occurred: 1681668750.1706276
origin: LOCAL
time_fired: "2023-04-16T18:12:30.171734+00:00"
context:
  id: 01GY5M9ETVGR2NK7W7MK94ZG6T
  parent_id: null
  user_id: null
#

it looks like it only fires events for "warning" and "error" (or higher, I guess)

#
    handler = LogErrorHandler(
        hass, conf[CONF_MAX_ENTRIES], conf[CONF_FIRE_EVENT], paths_re
    )
    handler.setLevel(logging.WARN)
plain magnetBOT
#

@languid pendant I converted your message into a file since it's above 15 lines :+1:

inner mesa
#

great, that should work

languid pendant
#

So the problem I"m having is how to incorporate it into a trigger?

inner mesa
#

what did you try?

languid pendant
#

in automations / triggers / event type: system_log_event event data: data:
name: homeassistant.components.system_log.external
message:
- bevis

inner mesa
#

just share the trigger

plain magnetBOT
#

To format your text as code, enter three backticks on the first line, press Shift+Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks.
```yaml
example: here
```
Don't forget you can edit your post rather than repeatedly posting the same thing.

inner mesa
#

you're describing it

languid pendant
#

platform: event
event_type: system_log_event
event_data:
data:
name: homeassistant.components.system_log.external
message:
- bevis

inner mesa
#

please format it properly

#

you have an extra data: there

languid pendant
#

Wow

#

now it works thank you very much!!

#

one last quick question, lets say hypothetically the log entry contained a variable (i.e. "bevis 12") how would you create a trigger based on the word bevis alone, ignoring the number after it?

inner mesa
languid pendant
#

okay, I'll look into it! thanks again!

frozen kite
#

Due to recent changes to HA Calendars, so that 0 duration events are no longer allowed, an existing automation no longer runs. I'm trying to format a template to give me a correctly formatted end_date_time equivalent to "now() plus one minute". I've Googled about and found that end_date_time: "{{ (now().strftime("%s") | int + (60)) | timestamp_custom("%Y-%m-%d %H:%M",false)}}" appears to give me what I want in Developer Tools Template Tester, but doesn't work in the Automation. Can anyone point me to documentation that properly explains the change that has been made, as I presume it will include an explanation of how to format this correctly?

obtuse zephyr
frozen kite
#

Thanks, I'll try that. - Yeah, that worked beautifully, many thanks! ๐Ÿ‘

austere relic
#

I have trouble figuring this one out: I want to check a template condition against multiple values:
{{ trigger.to_state.state == "button_1_double"}}
something like that, but template condition compatible:
{% if states('trigger.to_state.state') in ("button_1_single", "brightness_move_up") %}

haughty breach
#

The trigger variable is already the state object, so you don't use states()

#

{% if trigger.to_state.state in ["button_1_single", "brightness_move_up"] %}

inner mesa
#

probably just need the test:
{{ trigger.to_state.state in ['button_1_single', 'brightness_move_up'] }}

chilly locust
#

I'm trying to convert a string to an int so I can use it in an if statement, but I think I'm converting it wrong because it isn't working. Is this correct?
{% set t = states('sensor.waqi_air_quality_data_waukesha') | int %}

marble jackal
#

Don't see anything wrong with this, it will give you a variable t which is the state of that sensor converted to an integer.
However, you didn't add a default for the filter, so you will get an error when the state is not numeric (eg unavailable just after a restart)

chilly locust
#

Strange. Because it's not working. I even tried attaching it to an input number to force it to update, and still nothing.

fallow sand
#

I'm trying to create an availability template for a couple of binary sensors, but can't quite get the syntax for determining if either of these are not available ...something like this:
"{{ not ['unknown', 'unavailable', 'none'] in [states('binary_sensor.nursery_occupancy'), states('binary_sensor.nursery_north_ptz_motion')] }}"
any help is appreciated!

chilly locust
#

Here's what I have for the state:

        state: >-
          {% set t = states('input_number.air_quality_force') | int %}
          {% if 0 > t > 51 %} Good
          {% elif 50 > t > 101 %} Moderate
          {% elif 100 > t > 151 %} Unhealthy for Sensitive Groups
          {% elif 150 > t > 201 %} Unhealthy for Everyone
          {% elif 200 > t > 251 %} Very Unhealthy
          {% elif 250 > t > 301 %} Hazardous
          {% endif %}
marble jackal
#

That's because all of these statements can never be true

#

You are saying that 0 should be higher than t AND t should be higher than 51

#

All your >'s should be <

#

And you should probably have an else in case t >= 301

exotic grail
#

can you even have0 > t > 51 syntactically?

marble jackal
#

Yes, if you do 51 > t > 0

exotic grail
#

though that's confusing since, 0 > t, so t is negative? and then t > 51

#

ah okay, didn't know it let you chain up the >s

marble jackal
#

That was my point

exotic grail
#

ah, I was more commenting on just the syntax since I hadn't seen it before

#

am used to languages where you just have to add ands

marble jackal
#

Ah, it is allowed in jinja. ๐Ÿ™‚

mighty ledge
#

and python too

#

0 < x < 50

#

makes more sense like that

valid kite
timid echo
#

I am trying to understand value_template in the context of this automation I am trying to create via the UI. The objective is to have an Action if my Deep Freezer temperature has been above 20 degrees for 10 minutes or longer. here is my current automation. I was told I need to put in a value template. My question is if I just want to have the trigger compare the actual to the current. Do I need the above value that was placed by the UI?

#
  alias: Deep Freezer Notification
  description: Happens if the Deep Freezer is above 20 degrees for 10 minutes.
  trigger:
  - platform: numeric_state
    entity_id: sensor.h5100_1171_temperature
    for:
      hours: 0
      minutes: 10
      seconds: 0
    above: 20
    value_template: '  '
#

so could that be something as simple as {sensor.h5100_1171_temperature.current_temperature}

chilly locust
marble jackal
#

And add attribute: current_temperature

timid echo
#

so remove value_template? and add attribute?

marble jackal
#

Yes, if you want to trigger if that attribute value is above 20

timid echo
#
- id: '1681672048461'
  alias: Deep Freezer Notification
  description: Happens if the Deep Freezer is above 20 degrees for 10 minutes.
  trigger:
  - platform: numeric_state
    entity_id: sensor.h5100_1171_temperature
    for:
      hours: 0
      minutes: 10
      seconds: 0
    above: 20
    value_template: '  '
    attribute: current_temperature
#

yes

#

How can I validate what the attribute names are on my entity?

fallow sand
#

This long method seems to give me an accurate result but I'm curious if there is a more efficient way to write this:
availability_template: "{{ not 'unavailable' in [states('binary_sensor.nursery_occupancy'), states('binary_sensor.nursery_motion')] and not 'unknown' in [states('binary_sensor.nursery_occupancy'), states('binary_sensor.nursery_motion')] and not 'none' in [states('binary_sensor.nursery_occupancy'), states('binary_sensor.nursery_motion')] }}"

marble jackal
timid echo
#

ok

#

TY ๐Ÿ˜„

marble jackal
timid echo
#

will device_class: temperature have an attribute current_temperature?

orchid oxide
orchid oxide
#

usually the state is the temperature

fringe sail
#

Does anybody have an idea of how to write a condition that only allows an action if a door has been opened and closed more than a certain number of times?
I tried this example, but I don't think that it's correct.

  • condition: template
    value_template: "{{ states('binary_sensor.master_bed_door_sensor')|count > 2 }}"
    enabled: true
orchid oxide
#

Probably the easiest way would be to create a template sensor that increases in value every time the door State changes and have it reset when it stays in one state for however long you want the time out to be

#

I suppose alternatively you could do that with an Automation and a number helper

fringe sail
orchid oxide
#

Look up input_number helpers in the integration docs. Setting it up with an automation should be pretty straightforward, you can use the UI for that

fringe sail
#

I ended up with this...

if:

  • condition: template
    value_template: "{{ states('input_number.master_bed_door_open_and_close_count') > '4' }}"
    enabled: true
    then:
  • service: cover.open_cover
    data: {}
    target:
    entity_id: cover.master_bed_shades
  • service: light.turn_off
    data: {}
    target:
    entity_id: light.master_bed_lights
tepid onyx
fringe sail
orchid oxide
#

the reset to demo template button in developer-tools/template is going to drive me crazy

orchid oxide
#

at any rate im happy to give pointers where i can

orchid oxide
#

so i am still very much still new to more advanced templates...is there a less complicated way to do the following than what i have?

{% set ns.list={}%}
  {%for group in json["listItems"]|selectattr("label","defined")|groupby("label.name")|list%}
    {% set ns.group=[]%}
      {%for item in group.list%}
        {%set ns.group = ns.group + [item["display"]]%}
      {%endfor%}
  {%set ns.list = dict(ns.list,**({group.grouper:ns.group}))%}
{%endfor%} 
 {{ns.list}}```
dusk sorrel
#

hi all. I am using "serial sensor platform". But when not coming serial data, sensor.serial_sensor not be empty. How to decide it?

#
- platform: serial
  serial_port: /dev/ttyUSB0
  baudrate: 115200
analog mulch
#

With the new behaviour of today_at in 2023.4, can I still use it in template triggers? E.g. if I want something to fire at 9:01 once per 24 hours, what do I now need? Is the below, correct/wrong/overcomplicated?

{{today_at("9:01") < now () < today_at("9:02")
marble jackal
#

If you want something to trigger at 9:01 once every24 hours, my suggestion would be a time trigger

#
platform: time
at: "09:01"
#

but your trigger would also work, nothing really changed for your use case, template triggers without references to an entity_id were already rendered once per minute

analog mulch
#

Hmm, so leads me to worry: I also have a numeric conditions of some sort there, so in reality it's something like

{{ (today_at("9:01") < now () < today_at("9:02") ) or (states('sensor.bla')|float > 10) }}

How does this evaluate? Still once per minute, every time sensor.bla changes? Would it fire multiple times between 9:01 and 9:02 even if the second test if false?

#

Ah, but it will just be true at all times during 9:01, so it will actually fire once on the first change. Doh

marble jackal
#

Is that a trigger or a condition?

willow wing
#

Hey, someone knows why these template in my template.yaml are not working?

  • switch:
    #Klimaanlage Bรผro
    klimaanlage_buero_econo:
    friendly_name: "Econo"
    value_template: "{{ is_state_attr('climate.klimaanlage_buero', 'econo', 'on') }}"
    turn_on:
    service: tasmota_irhvac.set_econo
    data:
    entity_id: climate.klimaanlage_buero
    econo: 'on'
    turn_off:
    service: tasmota_irhvac.set_econo
    data:
    entity_id: climate.klimaanlage_buero
    econo: 'off'
marble jackal
#

that is a template switch, which belongs the switch integration and not to the template integration

#

so it should be in your configuration.yaml under switch:

#

or in an included file which is included in after that key

novel crystal
#

hey. I'm trying to sum specific values stored in an array and return the average of said values as the template state. however I'm failing miserable...

plain magnetBOT
novel crystal
#

state is being returned as

state: >
        ,
        ,
        ,
        ,
        ,
        ,
        ,
        -0.0745
willow wing
mighty ledge
novel crystal
#

oh that's awesome, thanks @mighty ledge

#

I still get a weird state though, at least "visually"

#
state: >
        
        
        0.0071
#

oh wait, my fault! sorted

willow wing
#

@marble jackal When i wanna move these code vom template to binary_sensor what i need to change?

#

Present Check

  - name: "Present Check"
    state: >
        {{ is_state('device_tracker.martin', 'home')
         or is_state('device_tracker.iphone_von_arabella', 'home') }}
mighty ledge
#

you change sensor: to binary_sensor:

willow wing
#

when it is in the binary_sensor.yaml i dont need this step?

#

i think i need platform: template and so things?

marble jackal
#
template:
  - binary_sensor:
      - name: "Present Check"
        state: >
            {{ is_state('device_tracker.martin', 'home')
             or is_state('device_tracker.iphone_von_arabella', 'home') }}
#

that should be the completed code after includes

willow wing
#

thanks for correcting my script

marble jackal
#

you can probably

short parrot
#

Hi everyone! how can I correctly pull out the datetime from an attribute to calculate a time delta? I tried this in a value template but it does not work: {{ now() - states('script.youtube_on_shield.last_triggered') | as_datetime > timedelta(minutes=1) }} (the error is: In 'template' condition: TypeError: unsupported operand type(s) for -: 'datetime.datetime' and 'NoneType'

plain magnetBOT
#

To format your text as code, enter three backticks on the first line, press Shift+Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks.
```yaml
example: here
```
Don't forget you can edit your post rather than repeatedly posting the same thing.

short parrot
#

Or some other way to confirm that the script did not run in the last minute...

obtuse zephyr
#

states('script.youtube_on_shield.last_triggered') should be state_attr('script.youtube_on_shield', 'last_triggered')

short parrot
inner mesa
#

It looks like you used a period instead of a comma

#

But you're not providing enough to properly debug

short parrot
short parrot
inner mesa
#

remove |as_datetime

short parrot
inner mesa
#

It was already a datetime object, so you don't need to convert it. It's a terrible error message

short parrot
#

Ahh, right! Thank you @inner mesa ๐Ÿ™‚

inner mesa
#

it's expecting to convert a string or timestamp integer to a datetime object, but it found a datetime object

short parrot
#

Can I somehow check with a template if a specific state of a device happened in the last xx minutes?

#

(not the state in which it is now)

inner mesa
#

you would either need to use an SQL sensor to mine the history or a template binary_sensor that triggers on a state change of the entity to the state you want

#

for the latter, you're creating a sensor that captures the last time the entity was in that state, and then you can use the last_changed property for that

short parrot
#

the second one sounds a lot simpler...

austere relic
#

what am I'm missing here? works in dev tab. shorthand notation example looks pretty similar.
- condition: and conditions: - {{ (states("input_number.counter")| int) < ((states("input_number.target")|int) - 1) }}

austere relic
late trench
#

Hey all, I hope I am posting on the correct channel. I need some assistance getting a value that has been returned from a ssh shell_command and manipulating the data. Anyone who can help it would be greatly appreciated.

#

I am trying to get the status of an outlet and when I ssh in and issue the command the result is "outlet is currently on: true" ... However if I assign that shell command as the status for a switch it doesn't understand the result so I need to manipulate it to show "1' any ideas?

obtuse zephyr
#

๐Ÿค” What are you actually trying to do? Is HA unable to integrate w/ the outlet where you could just grab its state from HA itself?

floral steeple
#

hi all, I would like to use this a trigger for a choose option, and then for an if-then-else

  - platform: numeric_state
    entity_id: sensor.co2
    id: HVAC
    above: 1000
    below: 1000

but, how do I create the condition if above 1000 then or else (below 1000)

obtuse zephyr
#

Do you actually want 2 separate triggers? One above 1000 and one below 1000? That single trigger I don't think will do anything for you, since the above/below defines a threshold for triggering

floral steeple
#

i want both because I wanted a trigger for when CO2 is above 1000 ppm (i.e. CO2 levels are high), and then tell me that its below 1000 ppm (i.e. CO2 levels are safe)

obtuse zephyr
#

yeah, I believe you want two triggers, your CO2 won't simultaneously be above 1000 and below 1000

floral steeple
#

oh, I would have to create 2 sepearate triggers then...

obtuse zephyr
#

Yup, w/ separate IDs and use those IDs in your choose

floral steeple
#

got it, thanks

late trench
obtuse zephyr
#

and are you using a template switch?

late trench
#

Yes as well as shell commands

obtuse zephyr
#

Could you share what you've got on a code sharing site and paste the link here?

icy ravine
#

Hi all - looking for some help creating a template that will track my water bill, based on usage per month. I've tried a few things on my own and can't seem to get it to work quite how I want, so thinking that starting over with input from the community may be best. Here's what I'm working with:

  1. Billing cycle starts on the 18th of the month, goes to the 17th of the next month
  2. Bill is calculated based on gallons used per month:
    1,000-5,000 gallons in a month = $4.81 per 1,000 gallons
    5,001-10,0000 gallons in a month = $6.61 per 1,000 gallons
    10,001+ gallons in a month = $9.62 per 1,000 gallons
  3. A base fee of $12.03 is also added onto the bill at the end of the month
  4. I have a sensor that tracks the gallons used per day (sensor.main_water_line_today_s_water_usage) - again this is daily, so the sensor resets to 0.0 (gallons) at midnight every night (maybe I need another one to log each day, then reference that in the bill calculator?)

Thanks in advance for any input!

late trench
#

to be clear the outlets turn on and off just cant get the status

obtuse zephyr
#

And what's the error you're getting

late trench
#

no error just not updating status

#

i don't think im using the value_template correctly

obtuse zephyr
#

Does the command exit w/ a 0 code?

#

That is, does out1status exit w/ 0

#

and then dump Outlet 1 is currently on: true to stdout?

#

Also keep in mind, in your initial question you said "outlet is currently on: true" and casing is significant

late trench
#

im sorry i don't understand

late trench
obtuse zephyr
#

Easiest way.... from a shell

out1status
echo $?

late trench
#

Command failed (with return code 127): shell_command.status_outlet1

obtuse zephyr
#

Well that sounds like a separate problem.... or the command never worked?

#

out1status is correct? It's not like outlet1 status?

late trench
#

it works from shell

late trench
obtuse zephyr
#

From shell... on 192.168.6.170?

late trench
#

from shell on ha

#

teminal

#

terminal

lofty mason
# icy ravine Hi all - looking for some help creating a template that will track my water bill...

I'd probably just have a nightly automation that increases a monthly counter (like an input_number helper) by the value of the daily sensor, right before it resets. Once you have the number of gallons used in that billing period, calculating the price should be pretty straightforward with a template.

Though I'd also check if there was a way to make my data fit into the energy dashboard for water.

obtuse zephyr
late trench
#

ok so how do i do that?

#

sorry for my ignorance

obtuse zephyr
#

Add homeassistant.components.command_line: debug to your logger: in configuration.yaml

#

and restart

late trench
#

ok but before i do that i just realized that i am also getting the same error in logs for the turn on and off

#

so i did some more testing and using the switch DOESN'T work but running the service in developers tools does

#

so i think the issue is in my switch config?

obtuse zephyr
late trench
#

ohhhh

icy ravine
late trench
obtuse zephyr
#

You're welcome

late trench
#

Ok switch is working, status isn't but I'll test a few things first

dusty hawk
#

What is the maximum character length of an Entity Attribute (not for the State which is believe is 255)?

inner mesa
#

I believe that it's quite large, like 32k, but only to avoid causing DB perf issues

late trench
obtuse zephyr
late trench
#

lol

#

at least no errors now

#

ill turn it on

late trench
obtuse zephyr
#

the normal home-assistant.log file

icy ravine
#

I d probably just have a nightly

plain magnetBOT
dusk sorrel
#

i am using serial integration. How to buffer last 10 data with end \n\r or 250 characters?

marble jackal
#

You need device_class: water and state_class: total_increasing

#

the state_class can not be set in the legacy template sensor format which you are using

#

ow wait

#

it's only the price, sorry

#

you need unit_of_measurement: currency/unit

#

so eg $/gal

marble jackal
#

@mighty ledge if I use something like set foo = bar | default() and bar was not provided, what will foo be? I always assumed it was none but that doesn't seem to be the case, since foo is none returns false, so I'm wondering what it will be? It surely is falsely, so something like iif(foo) will return false

#

same with a structure like set foo = bar if bar is defined (so without an else)

mighty ledge
#

I use

#

| default(none)

marble jackal
#

I started using that now as well ๐Ÿ™‚

#

ah yes, foo is string returns true

digital harness
#

Hello everyone, im new to HomeAssistant and i have a Problem. I try to get this template work. It works in the editor, but when i put it in the config.yaml and did a reboot, it shows as unavailable.

plain magnetBOT
#

@digital harness I converted your message into a file since it's above 15 lines :+1:

digital harness
#

maybe u can help me. thanks!

obtuse zephyr
#

Take a look at your log

#

what does it say

#

availability: states.sensor.shellyuni_e868e7f472ec_adc

#

that needs to be a template string

digital harness
#

Thank you!

obtuse zephyr
#

Yep you bet, if you want it to flip to unavailable, you will need to add that back, but actually have it be a template and have it return true when it's available.