#templates-archived

1 messages · Page 68 of 1

acoustic arch
#

step one works... find all Amersfoort

#

$.[?(@.town == 'Amersfoort')]

#

now its either go to bed or make it late lol

acoustic arch
#

ye im done.. cant seem to find a valid syntax for the minimum value for all Amersfoort gasstations

#

been reading about min() max() sum() etc, but all go into error mode

#

this is the site/json/syntax so far...

acoustic arch
#

I read here that it's not gonna happen

#

I'll be making a couple of sensors from rest I guess and ditch the attributes idea

marble jackal
#

Put all of Amersfoort in the attribute, then create a template sensor like my example above which uses the data from the rest sensor attribute

tardy saddle
#

I found a sensor that somebody listed it in a forum, and I would like to add that into my system. It basically says if it's nighttime. I've added the script to a sensor.yaml and change the configuration.yaml to include the sensor.yaml. BUT how do I access this in an automation?

#

"sensor:

  • platform: template
    sensors:

Period of the day

  period_of_day:
    friendly_name: 'period of the day'
    value_template: >-"
#

Sorry I was trying to add the script

#

so in automation condition if the period_of day = night then turn on light.

#

how do I access period_of _day

marble jackal
#

it will create an entity sensor.period_of_day which you can use in a state trigger or state condition

#

and to format it properly

plain magnetBOT
#

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

tardy saddle
#

I looked all over for a way to edit the post and I don't see it anywhere. I must be blind. i found out there must be something wrong with this text of this script as I found the errors in the log.

marble jackal
#

you are actually not sharing the template part

plain magnetBOT
#

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

marble jackal
#

and when you hover over your post, you will see a menu with a pencil icon

#

use that to edit it

tardy saddle
#

Invalid config for 'sensor' at configuration.yaml, line 13: required key 'platform' not provided,

#

I have only been doing HA for about six days now and still struggling to figure out all of this stuff I'm sorry for the delay questions

marble jackal
#

the first line with sensor: should not be copied to sensor.yaml

#

you already have that line in your configuration.yaml

tardy saddle
#

ooooooh THANK YOU

marble jackal
#

you should also use state_attr() in your template, and if this is your first template sensor, I would suggest to start with using the modern format

#

and not the legacy format

tardy saddle
#

I just copied this from the forum

marble jackal
#

yes, but probably from a rather old post

tardy saddle
#

when I what to check if its Night time using this sensor what is the trigger type?

marble jackal
#
# in configuration.yaml
template: !include template.yaml

# in template.yaml
- sensor:
    - unique_id: bbcc8586-8f93-4fb5-8360-8f132d9d7ac5
      name: Period of the day
      state: >
        {% if as_timestamp(state_attr('sun.sun', 'next_dusk')) - as_timestamp(state_attr('sun.sun', 'next_setting')) < 0 %}
          dusk
        {% elif as_timestamp(state_attr('sun.sun', 'next_rising')) - as_timestamp(state_attr('sun.sun', 'next_dawn')) < 0 %}
            dawn
        {% elif state_attr('sun.sun', 'elevation') < 0 %}
          night
        {% else %}
          day
        {% endif %}
      icon: >
        {% if is_state('sun.sun', 'above_horizon') %}
          mdi:weather-sunny
        {% else %}
          mdi:weather-night
        {% endif %}
      availability: "{{ 'sun.sun' | has_value }}"
#

that's the modern format

#

trigger type will be entity > state (assuming you use the GUI)

tardy saddle
#

is it ok to copy your code?

marble jackal
#

yes

tardy saddle
#

thank you so much for your help. I really do appreciate it. Honestly this is too complicated for me. At this point I used to program all the time but I'm now 70 years old and haven't quite been doing programming for a while so I'm not familiar with the syntax, but I can definitely follow it, I will learn. If this hadn't worked, I had made a boolean helper call nighttime and have a automation to turn it off and on based on sunrise and Sunset. I think that would work but I would like to make this idea work also..

#

what does it return? Like I have sensor.period of the day state but does it not return like night, dusk, dawn, day

marble jackal
#

check in developer tools > states

#

it will return dusk, dawn, night or day

acoustic arch
marble jackal
#

Did you already manage to put all the data in an attriubte of a rest sensor?

mighty ledge
acoustic arch
mighty ledge
#

the online sites don't appear to allow functions

acoustic arch
#

ok ill test it in the rest sensor and see what i get

mighty ledge
#

You may need to alter it

#

using $..price.min() instead of filtering to the town

#

I'm no json path expert, so your mileage may vary

acoustic arch
#

keep running out of gas anyway, so any milage is progress 😉

#
  resource: "xxx"
  scan_interval: 600
  sensor:
    - name: "Benzine Amersfoort #1 prijs"
      unit_of_measurement: '€'
      value_template: "{{ value_json | selectattr('town', 'equalto', 'Amersfoort') | sort(attribute='price') | map(attribute='price') | first }}"
      json_attributes_path: $.[?(@.town=='Amersfoort')]
      json_attributes:
        - town
        - address
        - gps
        - price```
For starters using the wrong path, this works. Im getting the first hit in the list as attributes
edgy umbra
#

Thanks to Thefes for sharing the example i have a min temp sensor. Now if sensor.temp_woonkamer drops to 0 (after a restart or server connection lost...) the min temp show 0. Is there anything i can do to ignore 0 value.

#
  - platform: statistics
    name: Min temp woonkamer
    unique_id: min_temp_woonkamer
    entity_id: sensor.temp_woonkamer
    state_characteristic: value_min
    max_age:
      hours: 12```
bitter atlas
#

isn't relative_time() suppose to convert a date to like "1 day ago" etc?

mighty ledge
#

it does

mighty ledge
#

to ensure it doesn't output 0 on restart

bitter atlas
#

i'm sitting on 2024.2.1 and even the default example in the template under dev tools is showing relative time as The sun will rise at 2024-02-19T07:02:48.967075-06:00.

mighty ledge
#

that's a string not a datetime

bitter atlas
#

{% if is_state("sun.sun", "above_horizon") -%} The sun rose {{ relative_time(states.sun.sun.last_changed) }} ago. {%- else -%} The sun will rise at {{ as_timestamp(state_attr("sun.sun", "next_rising")) | timestamp_local }}. {%- endif %}

#

thats the default entry for the template thing

#

the ago part confuses me if it's not broke lol

mighty ledge
#

relative time doesn't add the ago

#

just the time difference

bitter atlas
#

right but look at it's output above

edgy umbra
#

Petro, any change you can show me how to fix this. 🙂

#
        unique_id: "temp_woonkamer"
        icon: "mdi:sofa-outline"
        state: "{{ state_attr('climate.vicare_heating', 'room_temperature') | float(default=0) }}"
        unit_of_measurement: "°C"```
mighty ledge
#

which is using timestamp_local

mighty ledge
bitter atlas
#

ok then I don't get why 2024-02-19T12:14:44+00:00 dosen't work.. shouldn't it?

mighty ledge
#

Also, relative time only works on times in the past

bitter atlas
#

nm

#

i think i see what you just said

edgy umbra
#

Like this?

#
        unique_id: "temp_woonkamer"
        icon: "mdi:sofa-outline"
        availability: "{{ is_number(states('climate.vicare_heating')) }}"
        state: "{{ state_attr('climate.vicare_heating', 'room_temperature') | float(0) }}"
        unit_of_measurement: "°C"```
marble jackal
#

Yes

#

you can change float(0) to float

#

as you already ensured it is numeric now

edgy umbra
#

Thanks TheFes!

marble jackal
#

you could even remove the whole float filter

#

it is of no use

edgy umbra
#

So it will not warning that there is no default because of the availability?

marble jackal
#

no, because it will not render that template if the availability template renders false

#

the float filter is useless there because of two reasons

  • the state will be a string anyway
  • the value will already be a float
edgy umbra
#

Thanks again for clearing that out.

marble jackal
#
      - name: "temp_woonkamer"
        unique_id: "temp_woonkamer"
        icon: "mdi:sofa-outline"
        availability: "{{ is_number(state_attr('climate.vicare_heating', 'room_temperature')) }}"
        state: "{{ state_attr('climate.vicare_heating', 'room_temperature') }}"
        unit_of_measurement: "°C"
edgy umbra
#

Yep that's what i have now, thanks!

marble jackal
#

wiat

#

wait

#

you should check on the attribute in the availability filter

#

the state of the entity will be a string like heating so this will always be false

edgy umbra
#

This?

#
      - name: "temp_woonkamer"
        unique_id: "temp_woonkamer"
        icon: "mdi:sofa-outline"
        availability: "{{ is_number(states('climate.vicare_heating','room_temperature')) }}"
        state: "{{ state_attr('climate.vicare_heating', 'room_temperature') }}"
        unit_of_measurement: "°C"```
mighty ledge
#

ya

marble jackal
#

state_attr instead of states

edgy umbra
#

Oeps! 🙂

marble jackal
#

like you have for your state template

edgy umbra
#

Just to be sure.

#
        unique_id: "temp_woonkamer"
        icon: "mdi:sofa-outline"
        availability: "{{ is_number(state_attr('climate.vicare_heating')) }}"
        state: "{{ state_attr('climate.vicare_heating', 'room_temperature') }}"
        unit_of_measurement: "°C"```
#

Think this will be it?

marble jackal
#

yes, which is exactly what I posted above 😛

edgy umbra
#

Oh no it's not correct

#

i forgot the attr again 😄

mighty ledge
edgy umbra
#

Yep i know my bad 🙂

mighty ledge
#

just copy/paste thefes

edgy umbra
#
        unique_id: "temp_woonkamer"
        icon: "mdi:sofa-outline"
        availability: "{{ is_number(state_attr('climate.vicare_heating', 'room_temperature')) }}"
        state: "{{ state_attr('climate.vicare_heating', 'room_temperature') }}"
        unit_of_measurement: "°C"```
marble jackal
#

oh yes, I missed that you removed the attribute now

edgy umbra
#

Ow you changed the one you shared 🙂

#

Didn't noticed that

marble jackal
#

this one is exactly what I posted above

edgy umbra
#

Yeah sorry didn't see the change

#

Thanks again both!

marble jackal
#

BTW

#

you can use Temp Woonkamer for the name

#

no need to use a slugified name

mighty ledge
edgy umbra
#

If that is what you mean by "slugified name"?

mighty ledge
bitter atlas
#

it's early am for me.. this is always when I get brain farts trying to mess with my dashboard

#

btw relative_time was spitting out the exact same string in the editor. shouldn't that have error?

mighty ledge
#

nope, relative time doesn't have a default

#

and it only works on times in the past

bitter atlas
#

oh. that was part of why I was running in loops lol

marble jackal
#

so name: This is a nice name for a template sensor will result in sensor.this_is_a_nice_name

marble jackal
bitter atlas
#

I just had to use as_datetime then use relative_time on that in a sensor

keen vale
#
  - platform: template
    kwh_per_km:
    friendly_name: 'kWh per 100 Kilometers'
    value_template: >-
      {% if states('sensor.zoe_mileage')|float > 0 and states('sensor.zoe_plug_s_energy')|float > 0 %}
      {{ 100 / (states('sensor.zoe_plug_s_energy')|float / states('sensor.zoe_mileage')|float)|round(2) }}
      {% else %}
      N/A
      {% endif %}
    unit_of_measurement: 'kWh/100km'
#

I want to create a template to measure kWh/100km usage of my renault zoe. I use a shelly plug s to on the 230V charger

#

Till now it displays 0kWh/100km

plain magnetBOT
#

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

marble jackal
#

you forgot the closing tag

acoustic arch
#
        {{ value_json | selectattr('town', 'equalto', 'Amersfoort') | sort(attribute='price') | map(attribute='price') | first }}
      json_attributes_path: $.[?(@.town=='Amersfoort')]
      json_attributes:
        - WHATGOESHERE?```
marble jackal
#

I don't think you can, because it requires a key, which you don't have

acoustic arch
#

after that i can write ninja2 stuff to sort this i guess

marble jackal
#

You can't use any jinja for the attributes

#

I wasn't aware you could write json paths as petro suggested, I do think that is the route you need to take

#

but I don't have any experience with that

acoustic arch
#

nor me.

#

im mean... the question isnt hard, the answer seems unrationally hard lol

#

i cant even use platform: file to fetch it into attributes since its not supported

#

i give up

mighty ledge
#

use commandline

#

hold on

acoustic arch
#

using jq?

mighty ledge
#

this post highlights the way to get all the data into attributes when your main object is a list

marble jackal
#

ah, it takes the data, puts it in a named dict, and then you can use that for the attributes.

mighty ledge
#

yep

#

I don't ever remember the syntax, so I bookmarked that post

acoustic arch
#

thx. yet another language to sift through. This is hobby and agony at the same time

agile patrol
#

Any suggestions how to improve it?
1.) I don't like datetime comparisions with timestamps, maybe there is a better, more semantic way?
2.) I'd love to get rid of the loop and maybe filter with something like select.

{% set open_outer_doors_and_windows = state_attr('binary_sensor.outer_doors_and_windows', 'entity_id') | select('is_state', 'on') | list %}
open_outer_doors_and_windows: {{ open_outer_doors_and_windows }}
{% set ns = namespace(open_for_too_long_outer_doors_and_windows=[]) %}
{%- for open_outer_door_or_window in open_outer_doors_and_windows -%}
  {%- if now().timestamp() - states[open_outer_door_or_window].last_changed.timestamp() > 30 -%}
    {%- set ns.open_for_too_long_outer_doors_and_windows = ns.open_for_too_long_outer_doors_and_windows + [open_outer_door_or_window] -%}
  {%- endif -%}
{%- endfor %}
open_for_too_long_outer_doors_and_windows: {{ ns.open_for_too_long_outer_doors_and_windows }}
mighty ledge
#

well, you can use shorter variable names for starters

marble jackal
#

{{ expand('binary_sensor.outer_doors_and_windows') | selectattr('state', 'eq', 'on') | selectattr('last_changed', '<', now() - timedelta(seconds=30)) | map(attribute='entity_id') | list }}

mighty ledge
#

that also works

#

diffferent apporach

#

fyi fes, that should be seconds

#

not minutes

#

timestamp is seconds

marble jackal
#

oh

#

I knew that of course, but I just noticed the 30 and assumed a door which is open for 30 seconds wouldn't be considere open for too long

mighty ledge
#

yeah, it won't cause the template to update fast enough

agile patrol
# marble jackal `{{ expand('binary_sensor.outer_doors_and_windows') | selectattr('state', 'eq', ...

awesome, exactly what I was looking for, thx!

BTW, I've stumbled upon expand, but I didn't really explore it, as I could find any documentation for it…

It's not a Jinja function, as it is not listed here: https://jinja.palletsprojects.com/en/3.1.x/templates/
So it must be a HA addition – the only mention I've found was https://www.home-assistant.io/docs/configuration/templating/#working-with-groups

The expand function and filter can be used to sort entities and expand groups. It outputs a sorted array of entities with no duplicates.
Kinda circular definition 😄 Expand can expand groups 😄 Whatever that means 😛

So I'll just ask… what does it do exactly?

mighty ledge
#

it takes a list of entity_id's and turns them into an expanded list of state objects

marble jackal
#

when used on a group it expands the group members

#

it also works on nested groups, so it goes down to the actual entity ids

agile patrol
mighty ledge
#

TemplateState is the state object

agile patrol
mighty ledge
#

if that binary_sensor is a helper group of binary_sensors, it will expand the group into individual state objects

#

state objects are the backbone of HA

#

there's entity_id's and state objects, nothing else

#

an entity_id is a string

#

an identifier for the entity itself, which is a state object

agile patrol
#

ok, so it is just a function that takes a list of entity_ids and returns a list of state objects with the entity_ids from the objects storage? it's a service object locator, one would say, right? 😄

mighty ledge
#

it's main use is to expand grouped entities

#

i.e. if you have a grouped entity named binary_sensor.abc that is made up from 2 binary sensors binary_sensor.1 and binary_sensor.2

#

when you expand binary_sensor.abc you will get state objects for binary_sensor.1 and binary_sensor.2

#

if it's not grouped, you'll just get the state object for the input entity_id

agile patrol
mighty ledge
#

they are helper entities that you create in the UI or if you create the old school entitys that start with group.xxx

#

if you didn't create it manually in the UI, it's not a grouped entity

agile patrol
mighty ledge
#

it handles everything

marble jackal
#

yes, but it would also work on a comma seperated string
{{ expand('sensor.a, sensor.b') }}

mighty ledge
#

lists, arrays, tuples, extra arguments

agile patrol
#

And that's what's missing: a solid documentation… list of every function/filter - with described arguments, return values, error handling, etc… just my little rant. i hope i can help to improve it, although my knowledge is cleary lacking here 🙂

mighty ledge
#

it's been mentioned many times, but no one wants to put in the work to do that

#

in an agreeable format

agile patrol
# mighty ledge in an agreeable format

yeah, i guess… i can see simple tables, DL/DT/DDs, linkable headers, etc. no standard format. there is also a {% configuration %} tag, which looks promising to be used on a larger scale. anyway, still exploring. when too many standards, i may invent yet another standard to rule them all… <fameous xkcd comic here> 😄

mighty ledge
#

tables don't look good on mobile

#

so thats out

#

the standard isn't the hard part, it's actually documenting each filter, function, and test

#

it would be a massive amount of work to do this. Once the format is decided, the work will most likely be done by a few of us volunteers.

agile patrol
inner mesa
#

I think one of things that will come out of that is inconsistency and limitations in existing functions. Some take single entity_id but not a list, for instance

#

Is hard to tell now unless you try it and you get some unfriendly error

mighty ledge
#

it'll be treated like python's docs tho

inner mesa
#

I 'fixed' a few of those in a branch, but didn't follow through

mighty ledge
#

frencks spook documentation has examples

acoustic arch
acoustic arch
#

now the next step is to select the first/second/third option etc and try to make something out of it

agile patrol
# mighty ledge e.g. <https://spook.boo/flatten>

yeah, this is what i wish we had, instead of the Templating docs page mess, awesome 🙂 well, i'll do what i can until that, but that's an offtopic; thx again for the expand explanation, and @marble jackal for a much improvement to my little template 😗

mighty ledge
#

well, that's most likely what is coming, we are waiting on frenck to decide on the format, lay the ground work, so we can all start adding the separate pages

acoustic arch
#

even more good news. selecting the first sorted item:
[ sort_by(.price) | .[] | select(.town == "Amersfoort") ] | .[0]

#

or first remove crap, then sort.
[ .[] | select(.town == "Amersfoort") ] | sort_by(.price) | .[0]

#

and the cli
curl "httpaddress" | jq '[ .[] | select(.town == "Amersfoort") ] | sort_by(.price) | .[0]'

mighty ledge
#

why aren't you just putting it all in data like the post?

#

otherwise, if you have 3 of these separate calls, you'll be hitting the endpoint x3 instead of x1

acoustic arch
#

im just posting my steps

mighty ledge
#

not to mention, you can then just do the sorting in jinja whenever the data updates instead of every time you poll

acoustic arch
#

the last one is the one i need

#

then hopefully i can attribute this single json entry

#

finally!

      name: "Benzine Amersfoort prijs #1"
      command: curl "https://xxx/" | jq '[ .[] | select(.town == "Amersfoort") ] | sort_by(.price) | .[0]'
      command_timeout: 30
      scan_interval: 300
      value_template: "{{ value_json.price }}"
      json_attributes:
        - organization
        - town
        - gps
        - address```
tardy saddle
#

I am trying to learn and understand a sensor. The sensor returns a state and an icon. On the automation GUI it has fields for another Entity and Attribute, From, To. Where do I check the state? Does that make any sense? I want to say that if the sensor state = night then turn on the lights.

acoustic arch
#

boooo json path, yeah baby jq

marsh cairn
tardy saddle
marsh cairn
#

For example with state triggers or state conditions.

tardy saddle
#

for example: ``` alias: test day time
description: ""
trigger:

  • platform: state
    entity_id:
    • sensor.period_of_the_day
      attribute: night
      condition: []
      action:
  • service: light.turn_on
    metadata: {}
    data: {}
    target:
    device_id: 7b09c5dd81a3e1df6ac5f2811e7ce16b
    mode: single
#

is putting attribute night, the place where I checked to see if that's the right state? Maybe the GUI doesnt have the right field?

marsh cairn
#

In this case, the automation will fire on any change of the attribute "night"

plain magnetBOT
#

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

marsh cairn
#

You don't have an attribute "night". I assume you try to trigger on the state "night"

tardy saddle
#

yes

#

I guess I have the edit the YAML manually and not use he GUI

marsh cairn
#

Then you cannot use any attribute. Leave that field empty and put "night" into the "to" field.

tardy saddle
#

ohhh

#

using developer tools if I enter the state and then click set state, is that supposed to simulate the state and should trigger the automation?

marsh cairn
#

Yes

tardy saddle
#

hummm didnt triger. The automation does turn on the light if I click run, so I know that part is correct.

#
description: ""
trigger:
  - platform: state
    entity_id:
      - sensor.period_of_the_day
    to: night
condition: []
action:
  - service: light.turn_on
    metadata: {}
    data: {}
    target:
      device_id: 7b09c5dd81a3e1df6ac5f2811e7ce16b
mode: single ```
mighty ledge
#

automations only trigger when state changes occur

#

if the state was already night, it's not going to trigger

tardy saddle
#

now I need to examine that sensor that I found online and see if it really makes sense or should I just use sunrise and Sunset and had a helper boolean turned on

dapper aurora
#

does anyone have an example of a template sensor that uses attribute_templates? i want to have a template sensor that has a few different attributes based on conditions

dark mauve
#

Hi all - I’ve successfully connected my Litter Robot to Discord so I can get notifications when there’s a change in state or status. However when I read the status code all I can get is the 3 letter abbreviation versus the expanded meaning that shows up in the Home Assistant interface. How can I use templates to get the expanded text? I saw a post in forums where someone had to recreate the mapping even though it already exists in the code, and thought there has to be an easier way than this, right?

inner mesa
#

how did you connect it to Discord?

dark mauve
#

Discord integration - I’m using notifications to send messages to a Discord channel

inner mesa
#

then you can send whatever you want

dark mauve
#

Plus that’s not really maintainable if the manufacturer decides to add a bunch of statuses later

inner mesa
#

can't you just use the existing attribute?

#

that's what I use to display the status in the frontend

#

{{ state_attr('vacuum.litter_robot_4_litter_box', 'status') }}

#

seems like you're using the state from sensor.litter_robot_4_status_code

#

all the workarounds in that thread seem unnecessary, and it was from 2022

#

if you need it to be the state of an entity for some reason, just create a template sensor with something like what I put above

dark mauve
#

Let me try that

#

I’m surprised that didn’t get suggested in that thread

inner mesa
#

it's a weird thread

#

the integration has been updated quite a lot since 2022

wary yew
#

I'm trying to make a template in a mushroom card result in an invisible character because I cannot leave it empty (if I do the title gets vertically centered and collides with secondary info, see https://file.coffee/u/cFPmt-Y2zczEvYwdJUt2u.png). But I have tried a few ASCI invisible characters and they seem to get ignored by the template and gets detected as empty. Can anyone tip me in the right direction?

type: custom:mushroom-template-card
    primary: Kitchen
    secondary: |-
      {% if is_state('timer.kitchen_lights_timer', 'active') %}
        ----- here I need an invisible character, so it isn't empty ---------
      {% else %}
        {{ states('sensor.wiser_lts_temperature_kitchen', with_unit=True) }} | {{ states.binary_sensor.kitchen_presence_sensor_presence.last_changed | relative_time }} ago det
      {% endif %}
marble jackal
marble jackal
#

This works best with trigger based template sensors

wary yew
fringe remnant
#

Hey everyone! I'm building a sensor to get the electricity price of the previous hour. I have a sensor with all prices per hour, but I am having trouble getting the previous one

#

```{{ (state_attr('sensor.nordpool_kwh_fi_eur_3_10_024', 'raw_today')).22.value }}''`

#

Basically, I would need to change the '22' here to always show one less than the current hour - I was able to make a template sensor, but I'm not sure how to replace the '22' with a reference to the sensor?

inner mesa
#

{{ (state_attr('sensor.nordpool_kwh_fi_eur_3_10_024', 'raw_today'))[now().hour - 1].value }}

#

like that?

#

no need for a separate template sensor if you just want the current hour

fringe remnant
#

Well, that certainly simplifies it! I didn't know the correct syntax to use :)

#

Thank you, I will confirm it works in a moment

inner mesa
#

you'll probably have an issue at midnight

fringe remnant
#

Yeah, that's why I had the template sensor to fix that

inner mesa
#

if you have a sensor that does what you want, you can just replace the portion above with [states('sensor.whatever')|float]

marble jackal
#

The state of that sensor is the current price right? You could trigger on a state change in a trigger based template sensor and store the previous value as the template sensor state

fringe remnant
#

That also sounds like a good solution

#

If I can figure out how to store the pre-change value, that is!

marble jackal
#
- trigger:
    - platform: state
      entity_id: sensor.nordpool_kwh_fi_eur_3_10_024
      not_to: ['unavailable', 'unknown']
      not_from: ['unavailable', 'unknown']
  sensor:
    - unique_id: nordpool_previous price_sensor
      name: Nordpool previous price
      state: "{{ trigger.from_state.state }}"
fringe remnant
#

Ah, thank you @marble jackal You're entirely too kind!

#

And thanks to you too, Rob, for the assistnace

marble jackal
#

Don't restart HA 30 seconds prior to the hour change though 😉

lost locust
#

I have an automation trigger on an event. can I get the event data in a notification message or condition?

I'm looking to get event.data.device_id. when I look at {{ trigger }} it looks like the event property is empty.

#
platform: event
event_type: tag_scanned
variables:
  source: "{{ trigger.event.data.device_id }}"

this seems to work

#

then I use {{ source }}

lost locust
#

is there an easier/shorter way to write this?

{% set front_door = is_state("input_text.tagreader_front_door", source) %}
{% set side_door = is_state("input_text.tagreader_side_door", source) %}
{% set back_door = is_state("input_text.tagreader_back_door", source) %}

{% if front_door %} lock.front_door_deadbolt
{% elif side_door %} lock.side_door_deadbolt
{% elif side_door %} lock.back_door_deadbolt
{% else %} none
{% endif %}
#

ideally I'd just get front/side/back and chain it with the string?

#
{% set location = 
   is_state("input_text.tagreader_front_door", source) and "front" 
   or is_state("input_text.tagreader_side_door", source) and "side"
   or is_state("input_text.tagreader_back_door", source) and "back" or "none"
%}

{{ "lock." + location + "_door_deadbolt" }}

not sure if this is better or worse 😂

inner mesa
#

It doesn't make sense

#

The last attempt

#

The 'and "front"' part and such

#

There's nothing wrong with the first one. There are fancier ways, but 🤷

summer salmon
#

Anyway to get the previous state of an input_text in a template? or do i have to do SQL

marble jackal
#

a trigger based template sensor which triggers on the state change of that input_text, and then stores trigger.from_state.state

summer salmon
#

wow it was one cm above my post facepalm. thanks man

fringe remnant
#

Speaking of trigger templates, how would I sum the previous and new state? Surely it's not {{ trigger.from_state.state }} + {{ trigger.to_state.state }}
Both should be treated as floats

marble jackal
#

{{ trigger.from_state.state | float + trigger.to_state.state | float }}

fringe remnant
#

Thanks again!

lost locust
placid kindle
#

is there a way to provide a default for a trigger state in a template? I have an automation that automatically turns on the radio when the light turns on. Same with off. i currently use this action template, but on every startup HA complains that the automation could not be validated and might be broken, because the state is not known during it's check.

data:
  entity_id: media_player.soundtouch_bathroom_stefan
service_template: media_player.turn_{{ trigger.to_state.state }}
plain magnetBOT
#

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

mighty ledge
#

add unavailable as a not state condition

placid kindle
#

thanks, will give it a try

marble jackal
placid kindle
#

not a fan of having to track yet another helper entity (and exclude it from history etc etc)

marsh cairn
mighty ledge
placid kindle
#

where else would you put the suggested code if not into a yaml defining sensor entities etc?

mighty ledge
#

he's telling you to modify your trigger

#

which has nothingt o do with a helper entity, that's why we are all confused by your response

#

your automation would look like this instead:

alias: "Auto: Bad-Radio an/aus"
description: Radio an/aus wenn Licht in Bad an/ausgeschaltet wird
trigger:
  - entity_id: light.home_secondary_bathroom
    platform: state
    to:
    - 'on'
    - 'off'
action:
  - data:
      entity_id: media_player.soundtouch_bathroom_stefan
    service_template: media_player.turn_{{ trigger.to_state.state }}
mode: single
placid kindle
#

well, just a code snippet alone did not tell me where to put it. And it looked like a sensor definition to me

mighty ledge
#

well, its a trigger

#

not a sensor def

#

- platform: xxxx is only used for old style yaml configurations.

#

otherwise it's a trigger

placid kindle
#

if you know this syntax, then yes. I create my automations via UI 😉

mighty ledge
#

then just remove the condtion and add on and off in the too field via the UI

#

you can always swap to yaml mode to view the output as well

#

no need to get testy with us 😉

inner mesa
#

you may actually prefer it 🙂

#

and just stop using the UI for automations

placid kindle
#

well, I wrote my own blueprint about a year ago, but that's about it. Forgot whatever I had learned back then since I don't have that many automations, and all the others could be easily done via UI

#

and even though I do code for a living, I prefer to not have to do so for private things.

torn current
#

Hey! Came for some help, as I am having some difficulties when trying to comprehend the error messages. I have set up this light template (http://pastie.org/p/0hFLPjYKIxyHYTOVpL1jYe), and I'm getting some errors.

TemplateError('TypeError: %x format: an integer is required, not float') while processing template 'Template<template=({{ '%0x' % (int(0) * 255 / 100)}}) renders=4>' for attribute '_state' in entity 'light.inspire_light'
TemplateError('ValueError: Template error: int got invalid input 'unknown' when rendering template '{{states('input_number.temperature_input') | int}}' but no default was specified') while processing template 'Template<template=({{states('input_number.temperature_input') | int}}) renders=4>' for attribute '_temperature' in entity 'light.inspire_light'
TemplateError('ValueError: Template error: int got invalid input 'unknown' when rendering template '({{states('input_number.h_input') | int}}, {{states('input_number.s_input') | int}})' but no default was specified') while processing template 'Template<template=(({{states('input_number.h_input') | int}}, {{states('input_number.s_input') | int}})) renders=4>' for attribute '_hs_color' in entity 'light.inspire_light'||.

It is probably a very dumb error, as it's my first time trying this srry

plain magnetBOT
#

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

north locust
#

Trying to convert my download speed 202546408 to (202.55 Mbps)
divide by 1024 ?

inner mesa
#

a few things

#

this part doesn't make sense:
"{{ '%0x' % (int(0) * 255 / 100)}}"

#

what's the int(0) doing there?

mighty ledge
#

that will always return {{ '%0x'%0 }}

torn current
mighty ledge
#

0 in hex is 0 decimal

inner mesa
#

I suggest not using code from whoever posted that

mighty ledge
#

you're taking 0, multiplying it by 255/100, which is still 0, then converting it to hex

#

that's a ton of extra steps when you can just output 0

#

hex is interpreted as an integer by the resolver too. So it's alot of extra steps.

inner mesa
#

I suspect that that int(0) there was supposed to truncate some other value?

inner mesa
#

the danger with copying stuff

torn current
#

I think it will be better to remake that part

mighty ledge
#

why don't you just explain what you are trying to do

#

based on what I see, you copied most of it because the other templates shouldn't fail unless you use the wrong enitty_id

#

so, you basically never updated any of the code it seems

#

to use your entities

torn current
#

I'm trying to pass that value into hex because the script that will use that needs to send a ble write in hex

north locust
#

If i add device_class to this , can i do a convert in gui ? on data_rate ?

    sensor:
      - name: "Download"
        value_template: "{{ value_json.data.download | round(0) /1024 }}"
        unit_of_measurement: "Mbps"
        icon: mdi:download
torn current
mighty ledge
#

and device_class

north locust
#

can i just create a unique id ?

mighty ledge
#

yep

north locust
#

ah thnks

mighty ledge
#

if you are trying to write hex to a service call, post the service call and how you want to use it and we can help

north locust
#
      - name: "Download"
        unique_id: downloadzorssss
        value_template: "{{ value_json.data.download | round(0) }}"
        device_class: data_rate
        unit_of_measurement: "Mbps"
        icon: mdi:download

      - name: "Upload"
        value_template: "{{ value_json.data.upload | round(0) }}"
        unique_id: uploadzorssss
        device_class: data_rate
        unit_of_measurement: "Mbps"        
        icon: mdi:upload

this about right ?

#

hmm it can do decimal conversion, but no conversion of mb/s kb gb etc ...

mighty ledge
#

yeah, as long as data_rate is valid

#

your unit of measurement needs to match with the device_class

north locust
#

api has a strange output

"download":202869048,"upload":186606752
#

200 mbit

mighty ledge
#

always consult the docs 😉

north locust
#

ah bits/s

#

i guess

mighty ledge
#

not sure which what you're intending it to be with Mbps, I would assume MB/s

#

B would be byte

#

Bit is bit

#

very different

north locust
#
Latest download
202.87 Mbps
0.28% faster

but api outputs in

"download":202869048,"upload":186606752
inner mesa
#

is there an issue?

north locust
#

guess its bit/s ?

inner mesa
#

what did you expect it to be?

north locust
#

confused , was bit/s , mb and mib brrrrr

#

ty working

#

conversion now , pretty sensor ! 😛

mighty ledge
#

that looks like bits

north locust
#

how do i clear historical data from these sensors ?

#
      - name: "Download"
        unique_id: downloadzorssss
        value_template: "{{ value_json.data.download }}"
        device_class: data_rate
        unit_of_measurement: "bit/s"
        icon: mdi:download
#

found it , purge service

distant sky
#

does anyone have a drop in template for making a new sensor which mirrors another temperature sensor with an offset?

EG I have temp sensor 1 at 20 degrees,
I want to have temp sensor 2 which is 20 degrees minus 5.5 degrees.

wanton sapphire
distant sky
final trellis
#

hello,
is this correct please ?

{{ states('binary_sensor.rain_sensor_switch1') == 'on' and states('sensor.gw1100a_v2_2_1_rain_rate') | float(0) >= 7  }}
marble jackal
#

The version you posted here will prevent that error

final trellis
#

it didn't - it still gave error

marble jackal
#

This is the version which caused the error {{ states('binary_sensor.rain_sensor_switch1') == 'on' and states('sensor.gw1100a_v2_2_1_rain_rate') | float >= 7 }}

#

It doesn't have the default for the float filter

final trellis
#

ok

#

i understant - so the default was missing
you are right - thank you fes

gentle sundial
#

Hi! Is it possible to use a state as an attribute like: {{state_attribute('sensor.mySensor','sensor.mySensor.state')}} or: How to quote a Doublebracket inside a Doublebracket? Thanks!

fickle sand
marble jackal
#

You are missing a closing parenthesis

noble fern
#

G'day All! I'm losing the plot here on something simple that I've done a thousand times with strings but never with datetime stuff. I'm trying to combine a date field with a time field to get a datetime that I can compare. I'm buggered if I can concat them properly to convert. For example, I have: {% set last_detected_timestamp = states('sensor.birdnet_last_detected_date') ~ states('sensor.birdnet_last_detected_time') %} I know I haven't done the as_datetime yet but it makes one long string without the space and therefore will not convert. I know it's something basic but I've been looking at it for too long. Could someone steer me in the right direction please?

gentle sundial
gentle sundial
marble jackal
noble fern
#

That seems to work. I thought that as_datetime might be able to take two sep. inputs to combine but I see I need to feed it the concatenated string including the space. Ahh well. Thanks for confirming. I did it the second way with the join as it appeals to me more. 🙂 Thanks @marble jackal

dusk gate
#

Hi! I have a device that writes this to me from mqtt explorer but I can't control it. Can anyone help me?
connect = true
stat = LED1_R:OFF;LED1_G:OFF;LED1_B:128;RELAY1:0N;SW1_AC:PULL;SW1_DC:PULL;=>0
I should create a switch

mighty ledge
#

You'll have to provide more information that that @dusk gate

#

that's not enough info for anyone to help you create a switch, on top of that, you will need to know the commands that turn the switch on and off.

#

you'll also need to tell us what information in the topics mean that the switch on or off.

dusk gate
#

I have this 4box brand device. it is a switch with 2 relays. I managed to connect it via mqtt to my server and from mqtt explorer I can see the status changes.
I created a switch on home assistant that changes state when the relay changes state. my problem is that I don't know the commands to send for relay toggle. the manufacturer doesn't provide them to me and I wanted to know if there is a way to find them myself

dusk gate
mighty ledge
#

I already told you what information we need

#

we need to know what topics to use to turn the switch on and off

#

we need to know the comand that is required for the device that does the turning on/off

#

we need to know what value in the inforamation you provided, represents the state of the switch being on or off

#

we need to know the topic that this information is stored

dusk gate
#

M053B-90380C349464
stat = LED1_R:OFF;LED1_G:OFF;LED1_B:ON;LED2_R:OFF;LED2_G:OFF;LED2_B:OFF;RELAY1:OFF;RELAY2:OFF;SW1_AC:PULL;SW2_AC:PULL;SW1_DC:PULL;SW2_DC:PULL;=>-1.00=>0=>0=>MOTOR_STOP
led
2
r = off
1
r = off
relay
2 = off
1 = off
sw
2
dc = pull
1
dc = pull

#

this is what I get on mqtt explorer. I apologize in advance but I'm not an expert in this

mighty ledge
#

That's still only the status and that doesn't tell us how to use it

#

which is what you need to figure out

#

there will be a manual with your device that describes the things I'm asking for

dusk gate
#

nope. unfortunately Italians are jealous of their jobs and want to have control 😅 so they don't provide this information. in fact, even when I asked, they didn't provide me with anything, which is why I was asking you if you knew a way to find them independently

mighty ledge
#

then there's nothing you can do if you don't know how to reverse engineer it

#

without knowing what command to send to the device to turn it on, you won't be able to do that

dusk gate
#

I can tell you that I managed to enter the http page by finding the user and password (they don't provide it) and from there there are the http commands to control the device.

mighty ledge
#

same for off

#

if there are http commands you can attempt to use rest commands with the device to turn it on or off.

#

which means you'd need to make mqtt binary sensors for each relay, 2 rest commands per relay, then combine them with template switches

dusk gate
mighty ledge
#

that can be included in the rest command

dusk gate
#

Can you give me an example of how to do it?

plain magnetBOT
dusk gate
#

to combine mqtt and REST I can't create a switch but can I only use it with automations? correct?

plain magnetBOT
#

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

dusk gate
#

this is my configuration and now the "test" switch works correctly and follows the status of the relay even if an error pop-up appears below: an error occurred while requesting the resource.
Does anyone know how to do better than this? advice?

mighty ledge
#

are you getting an error with the rest command?

#

or with the MQTT switch?

#

or with the test switch?

dusk gate
#

but it still works

mighty ledge
#

look in your logs for errors

#

post them here

dusk gate
#

ok I'll do it later I'm not on the PC anymore. thank you very much for now

gentle sundial
#

Hi best Community again : Now I'm struggeling about another Problem and don't know, where to start. The Topic is: Combining If-Clauses. So I have 2 Sensors A = [x,y,z] & B = [1,2,3] (just for Example!) … When A is something do something if B is something … does have anyone an examplecode to orientate in that … cannot put it together within the Dev-Tools by myself. Cheers - M.

warm steeple
inner mesa
#

it's not any different than just one of them

#

it's the exact same syntax

pliant condor
#

Quick Q, can I set the state of an entity in a template? I have a Zigbee light that is connected to a power strip that is sometimes switched off. If that happens when the light was on, the state of the light remains on, and I cannot switch the light off because it cannot be reached. I would like to change the state representation like you can do in Dev Tools, but in an automation. Is that possible and how?

lofty mason
#

no you can't change the state of some other entity

pliant condor
#

Too bad. I hoped that would be possible since you can do it in the UI

lucid thicket
#

You can create a template light, and you can have the logic for the off state be affected by whether or not the Zigbee light is available

lofty mason
#

that's more of a hack for testing, you wouldn't want to do that even if you could. it gets reset the next time the device updates.

pliant condor
# lofty mason that's more of a hack for testing, you wouldn't want to do that even if you coul...

What exactly does 'it gets reset the next time the device updates' mean? Would it update even if it is unavailable? Because I am fine with the device updating once it has power again. I can determine whether or not it has power through the state of another entity. The only logic I want to have is: 'if power to device is off, consider device off' . In all other cases the state of the device is whatever it tells you it is.

lofty mason
#

well, it doesn't matter because you can't do it anyway.

#

you can make a template as suggested

pliant condor
#

I'll give that a try, thanks @lofty mason and @lucid thicket for the suggestions and clarifications.

sudden bison
#

I feel like this one is more difficult than it should be, but I'm also very fresh to using Templates. Maybe someone can get me started in the right direction?

My goal: count how many applications in TrueNAS have a pending update.

Data available: Using the TrueNAS integration, a device was created that has multiple sensor entities, each representing an installed application. The main state information is simply if the application is on or off. Each application has additional attributes, including "Update Available" (value of 1 or 0).

As I expect the applications to change relatively frequently and I'd like to not manually redefine this over and over, I'd love to: produce a list of all sensors/entities belonging to this device. Test each entity for the "Update Available" attribute. Count how many entities has "Update Available" equal 1.

#

Alternatively, an equally as useful item would just be a complex filter for a UI card. Filter to display entities belonging to that device. Filter again to display entities with that attribute state equal to 1.

sudden bison
dusk gate
ruby vault
#

it must be, with the platform

mighty ledge
#

So “neither”

marble jackal
#

but it needs to be set up under sensor

mighty ledge
#

Yep, becaues it's a platform

marble jackal
#

unless somebody moves it to a history_stats integration (and adds a config flow)

#

Pff, I had to correct at least 3 typo's there.. might indicate I need a coffee

mighty ledge
#

are you on mobile or keyboard?

marble jackal
#

on keyboard

mighty ledge
#

ah yes, then you need a coffee

#

I've noticed that autocorrect on IOS has become shit

#

it has started auto completing words as I type and completing the words while keeping both the incorrect word and correct word

thorny snow
#

Hi! I tried to get the Humidity for my Aqara Temperature / Humidity Sensor via Template. This command just returns "null", i don't know what to do

#

{{ state_attr('sensor.aqara_umweltsensor_wohnzimmer_luftfeuchtigkeit', 'humidity') }}

inner mesa
#

does that entity have that attribute?

#

straightforward debugging. devtools -> States

thorny snow
#

now i tried {{ states('sensor.aqara_umweltsensor_wohnzimmer_luftfeuchtigkeit') }} and it works ... im new in home assistant 😄

inner mesa
#

so it was just the state, then

#

I don't know what most of those words mean 🙂

#

anyway, devtools -> States in the future

thorny snow
#

it kind of means "sensor.aqara_environmentsensor_livingroom_humidity" 😄

inner mesa
#

then yes, it was just the state

mighty ledge
#

just curious, what made you think you had to get humidity from the entity when the name has humidity in it?

inner mesa
#

random copy/paste

thorny snow
#

just trying to build a helper for an alert...so the idea was to check if the humidity is above 60% ...but i guess my approach to get the humidity from the entity was wrong

inner mesa
#

it's important to understand the difference between states and attributes to be successful in HA

thorny snow
#

yeah i think i have to do a little research 😄

mighty ledge
#

you shouldn't need templates for this btw

#

seems you've googled yourself into a weird area

#

a simple automation using a numerical trigger would alert you. All done via the UI, no templates.

thorny snow
#

yes thats what i did in the first place. but then i wanted to implement an alert that sends notifications while the humidity is above 60% and only stops when it falls below 60% again

mighty ledge
#

that would be a time pattern trigger every x minutes that checks a condition if the numerical value is above 60%

thorny snow
#

okay yeah maybe there is a more easy way to do this...as you already mentioned I did a lot of google research in the last hours 😄

inner mesa
#

The Wisdom of Google is sometimes overrated

mighty ledge
#

well, also if you input 💩 to google, you get 💩 out

#

might be best to hit up the HA glossary before going google happy

haughty breach
#

If I have a list of dictionaries, is there a good way to get the index of one of the dicts based on either a unique key or k-v pair existing in the dict?

#

NVM

mighty ledge
elder moon
sudden bison
#

Oh, actually...it's not updating. Attributes have changed, but the filtering isn't.

plain magnetBOT
#

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

sudden bison
#

That message has a question about proper syntax... My attribute name has a space in it. The auto entities card strips out any quotations I put around it. If I use a different attribute without a space, the test works and I get expected results. I can use the dev tools for state testing and get expected values from the attribute with a space in it, but it lets me use quotes.

I guess...what's the correct way to escape out a space in this context?

agile patrol
sudden bison
plain magnetBOT
#

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

gentle belfry
#

Ok, I'm so sorry to noob you all with this. My google foo is poor (spent days on this already) I am really hoping you all will take mercy upon me and forgive me my noobness.

#

I have popped this webhook triggered sensor into my templates.yaml file (which I'm calling via the include in my config.yaml file). And I am not getting the expected outcomes.

#

First problem is the binary sensor showing the valve state seems to be inverted with it's icon display. When the state value is "on" it is showing that correctly but is instead displaying the "closed" icon, and when it is "off" it is showing the "open" icon. I can't for the life of me work out why.

#

Second problem is that it seems my level sensor is not correctly evaluating the value and displaying the appropriate icon. So I'm pretty sure I am totally misunderstanding how that is supposed to work.

Your help would be much appreciated. 🙂

plain magnetBOT
#

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

gentle belfry
#

I've flipped the icons around in that binary sensor so that it displays correctly, as you can see, but if I put them back the right way (so the open is shown when the state is on) then it actually displays them wrong.

lucid thicket
#

For your level sensor, you have parenthesis in the wrong spot

#

Should be like this:

{% if states("sensor.tank_level") | float < 1 %}
haughty breach
#

Whenever using a trigger-based template sensor you should recalculate values for attributes and icons instead of using this because this will be the previous state, not the current state.

lucid thicket
#

Ah, good point, thank you. I’ll remove that reply

#

I can’t see anything wrong with the icon template on the binary_sensor then.

lucid thicket
#

But for state based template sensors, the this object is updated after the state and after each attribute. Probably because the template sensor is being re-triggered upon each of those updates and therefore this gets updated each time?

lucid thicket
#

Thank you. Looks like I need to make some tests on my system to ensure I know exactly what it is doing

gentle belfry
inner mesa
#

this.is_state isn't a thing

gentle belfry
#

so digi is referring to some other this?

#
      icon: >
        {% if this.is_state("binary_sensor.tank_valve", "on") %}
          mdi:valve-open
        {% elif this.is_state("binary_sensor.tank_valve", "off") %}
          mdi:valve-closed
        {% else %}
          mdi:valve
        {% endif %}
inner mesa
#

No

gentle belfry
#

not like that?

inner mesa
#

No

gentle belfry
#

my noobness is showing i bet. 😉

inner mesa
#

without knowing what you're doing

haughty breach
#

You've misunderstood, you should use trigger.json.open not this

gentle belfry
#

but the value is setting correctly

#

it is just the icon is not

#

oh, evaluate the trigger value

#

not the state object

#

that's what you are saying?

#
      icon: >
        {% if ("this.trigger.json.open", "on") %}
          mdi:valve-open
        {% elif ("this.trigger.json.open", "off") %}
          mdi:valve-closed
        {% else %}
          mdi:valve
        {% endif %}
#

like that?

#

wait, without the is_state

inner mesa
#

the first argument of is_state is an entity_id

gentle belfry
#

would that work?

#

(tries)

inner mesa
#

no

#

I'm going to take a stab at whatever it is you're doing

#
      icon: >
        {% if trigger.json.open == "on" %}
          mdi:valve-open
        {% elif trigger.json.open == "off" %}
          mdi:valve-closed
        {% else %}
          mdi:valve
        {% endif %}
haughty breach
#

Rob you've got hanging )

inner mesa
#

fixed

#

is that what you're talking about?

haughty breach
#

Yep

gentle belfry
#

so i'm passing boolean true or false in that json payload

#

should i use that, or use the "on" and "off" in the conditional eval?

inner mesa
#

you should use whatever you're sending

gentle belfry
#

roger that

#

reloading now

#

🙂

#

working perfectly!!!

#

so that was a race condition on my eval right? because the state object was not updated yet

haughty breach
#

Since you're passing a bool and the output are static strings you could also use immediate if:

      icon: >
        {{iif(trigger.json.open,"mdi:valve-open","mdi:valve-closed","mdi:valve")}}
gentle belfry
#

so evaluating my trigger input is the safest way to do it

#

legend!!!

#

let me take a shot at fixing the level sensor below. 🙂

#

brb

#

Do i need to cast the json value to a float when i am setting the state, or will it do that for me?

#
{"open": true, "level": 0.0}
#

that's my input

haughty breach
#

You shouldn't need to cast to float based on your input, but it won't hurt to do so

inner mesa
#

I hope that second comma is really a colon

gentle belfry
#

nope, did not need to cast it.

#

yeah, sorry, is colon

#

😛

#

works perfectly!!!!

#
      icon: >
        {% if trigger.json.level < 1 %}
          mdi:gauge-full
        {% elif trigger.json.level < 2 %}
          mdi:gauge
        {% elif trigger.json.level < 3 %}
          mdi:gauge-low
        {% elif trigger.json.level < 4 %}
          mdi:gauge-empty
        {% else %}
          mdi:alert-circle
        {% endif %}
#

should have occured to me that evaluating the state object may have been a race condition

#

should have been evaulating my input, as i knew that was current

#

lol

#

this is why i got a B- average for my CS bachelors. 😉

#

thanks guys, you are legends!!! so sorry for my noobness. 🙂

inner mesa
#

no worries

dusk gate
#

Logger: homeassistant.components.websocket_api.http.connection
Source: components/websocket_api/commands.py:240
Integration: Home Assistant WebSocket API (documentation, issues)
First occurred: 22 febbraio 2024 alle ore 22:07:02 (22 occurrences)
Last logged: 22 febbraio 2024 alle ore 22:25:18

[547634908736] Client error occurred when calling resource 'http://192.168.1.194/cmnd?action=OFF2'
[547967039552] Client error occurred when calling resource 'http://192.168.1.74/cmnd?action=ON2'
[547967039552] Client error occurred when calling resource 'http://192.168.1.74/cmnd?action=OFF2'
[547967039552] Client error occurred when calling resource 'http://192.168.1.194/cmnd?action=ON2'
[547967039552] Client error occurred when calling resource 'http://192.168.1.194/cmnd?action=OFF2'

#

Traceback (most recent call last):
File "/usr/local/lib/python3.12/site-packages/aiohttp/client_reqrep.py", line 966, in start
message, payload = await protocol.read() # type: ignore[union-attr]
^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.12/site-packages/aiohttp/streams.py", line 622, in read
await self._waiter
File "/usr/local/lib/python3.12/site-packages/aiohttp/client_proto.py", line 224, in data_received
messages, upgraded, tail = self._parser.feed_data(data)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "aiohttp/_http_parser.pyx", line 557, in aiohttp._http_parser.HttpParser.feed_data
aiohttp.http_exceptions.BadHttpMessage: 400, message:
Data after Connection: close:

b'<ON2>HTTP/1.1 200 OK'
#

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "/usr/src/homeassistant/homeassistant/components/rest_command/init.py", line 143, in async_service_handler
async with getattr(websession, method)(
File "/usr/local/lib/python3.12/site-packages/aiohttp/client.py", line 1194, in aenter
self._resp = await self._coro
^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.12/site-packages/aiohttp/client.py", line 605, in _request
await resp.start(conn)
File "/usr/local/lib/python3.12/site-packages/aiohttp/client_reqrep.py", line 968, in start
raise ClientResponseError(
aiohttp.client_exceptions.ClientResponseError: 400, message="Data after Connection: close:\n\n b'<ON2>HTTP/1.1 200 OK'\n ^", url=URL('http://192.168.1.194/cmnd?action=ON2')

The above exception was the direct cause of the following exception:

#

Traceback (most recent call last):
File "/usr/src/homeassistant/homeassistant/components/websocket_api/commands.py", line 240, in handle_call_service
response = await hass.services.async_call(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/src/homeassistant/homeassistant/core.py", line 2279, in async_call
response_data = await coro
^^^^^^^^^^
File "/usr/src/homeassistant/homeassistant/core.py", line 2316, in _execute_service
return await target(service_call)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/src/homeassistant/homeassistant/helpers/service.py", line 892, in entity_service_call
single_response = await _handle_entity_call(
^^^^^^^^^^^^^^^^^^^^^^^^^^

plain magnetBOT
#

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

mighty ledge
#
   include:
   - template: "{{ states | map(attribute='entity_id') | select('is_state_attr', 'Update available', 1) | list }}"
#

@sudden bison

#

you can filter that down to truenas if you know the integration name for truenas

sudden bison
#

I ask because it has multiple devices.

mighty ledge
#

devices don't matter

#

if you have an entity that you know is created by truenas, post the result of this template from the template editor

{{ device_attr('yourentityhere', 'identifiers') }}
#

make sure you put your entity in the yourentityhere

sudden bison
#

I think in this case, it might actually, but I may wrong. In this integration, each "device" has a wildly different set of entities. They're all representing different aspects of a server appliance. There actually probably wouldn't be a conflict in this instance, as that's likely not the same attribute in the other "devices," but if there was, it would be information I actually don't want showing in the card.

mighty ledge
#

you are wrong, devices don't matter HA works off entities

#

please post the information I asked for

#

or if you know the device_id for the Truenas Apps device, that works too

#

either way, need that info

#

one of the 2

sudden bison
#

Yeah, I wasn't getting expected values out of that in the States editor. I'm just getting an empty set:
[]

mighty ledge
#

are you putting in the correct entity_id?

#

post what you pasted please

sudden bison
#

Sorry, was originally on a phone and that was way too burdonsome for this task. Just repeated on my computer. Pasting this:
{{ device_attr('binary_sensor.ha', 'identifiers') }}
still yielded
[]

#

That's one of the sensor entities associated with TrueNAS Apps

mighty ledge
#

not according to the template

#

it should have identifiers

#

can you post a screenshot of binary_sensor.ha in developer tools -> states page?

#

I guess it's possible it doesn't have identifiers

#

is this a custom integration?

#

how about this instead {{ device_id('binary_sensor.ha') }}

sudden bison
sudden bison
sudden bison
mighty ledge
#

Well it seems that the truenas dev is not doing anything by the books

#

which is the root cause of your problems

sudden bison
#

I'll raise some issues in the repository.

mighty ledge
#
   include:
   - template: "{{ device_entities('12dae07592ad7d75cc4f9993f7170fb9') | select('is_state_attr', 'Update available', 1) | list }}"
#

that template will filter down to what you want

#

no other filters needed.

#

you can verify that in the template editor

sudden bison
#

Yep, the template editor looks like it gave me an accurate list. Shows a good list of everything it checked, and then the actual filtered result string.

#

Only small adjustment I had to make for it work in the card was to raise "template" up a level.

  template: "{{ device_entities('12dae07592ad7d75cc4f9993f7170fb9') | select('is_state_attr', 'Update available', 1) | list }}"
  include: []
  exclude: []```
mighty ledge
#

ok, might have read the docs wrong, so that's probably correct

#

yep, I did

sudden bison
#

Really appreciate your help here, Petro. It's a nice frontend card that my learning experience got marred with by what seemed to be a non-compliant custom integration. That template you wrote makes good sense to me, and since I know what it was trying to do beforehand, that's a good basis to help me understanding the syntax in templating a little bit better. The filter character was...not clear to me in how it was working. It's still not 100%, but I'm going to keep looking into it further and play around a bit until it makes more sense to me. I want to actually learn this instead of just use it, after all.

sudden bison
#

It all comes out OK in the end here though.

mighty ledge
#

well you don't need include or exclude when using a template

#

because it can do it all

sudden bison
#

As I see now!

mighty ledge
#

you can even have the template output dictionaries that represent your cards and all the information that's placed in the cards

#

instead of it outputting a list of entities

#

card_param makes the output of filter and places the values as cards instead of entity_id's

#

which builds this for me

#

non entities, but calendar events

#

when I say you can do anything with auto-entities, i truely mean it. There are very few limitations.

sudden bison
#

I see, yeah, I can definitely see it being a powerhouse.

plain magnetBOT
#

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

clear python
#

sensor:

  • platform: template
    sensors:
    home_energy_usage:
    friendly_name: "Home Energy Usage"
    unit_of_measurement: 'lx'='
    device_class: 'illuminance'
    value_template: "{{ states('sensor.myenergi_my_home_power_generation') }}"

this throws a fit of a error and again dont understand any of it if its even close

#

'Sensor None has device class 'illuminance', state class 'measurement' unit 'lx' and suggested precision 'None' thus indicating it has a numeric value; however, it has the non-numeric value: 'sensor: - platform: template sensors: home_energy_usage: friendly_name: "Home Energy Usage" unit_of_measurement: 'lx'=' device_class: 'illuminance' value_template: "804"' (<class 'str'>)
'

inner mesa
#

That unit of measurement doesn't make sense

#

Probably should just be lx, but you have three quotes and an =

#

Further:

plain magnetBOT
#

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

clear python
#

changed that still get this at bottom

#

Sensor None has device class 'illuminance', state class 'measurement' unit 'lx' and suggested precision 'None' thus indicating it has a numeric value; however, it has the non-numeric value: 'platform: template sensors: home_energy_usage: friendly_name: "Home Energy Usage" unit_of_measurement: lx device_class: 'illuminance' value_template: "583"' (<class 'str'>)

#

sorry im genuinley lost with this stuff i just want a simple

this entity -sensor.myenergi_my_home_power_generation

which is displaying in watts

into a 'fake' Luxs sensor so i can expose it to homekit

inner mesa
#

Please use formatting

clear python
#
  sensors:
     home_energy_usage:
       friendly_name: "Home Energy Usage"
       unit_of_measurement: lx
       device_class: 'illuminance'
       value_template: "{{ states('sensor.myenergi_my_home_power_generation') }}"
#

apologies didnt even know that was a thing

marble jackal
#

you missed the last sentence of that bot message 😉

clear python
#

god damn it

inner mesa
#

Seems like there's an extra quote in the state of that entity making it not look like a number?

clear python
#

Yep as you can probably imagine

that went clean over my head

#

i can see in the error its changing with the sensor live so i assume this is close

sudden bison
#

Funny enough, I was spending some time creeping through the integration code to try and understand what they were doing/why it went wrong.

They clearly had the intent for the attribute names to not have spaces. In the code defining the attributes, I'm seeing "human_version", "update_available", and "container_images_update_available" all listed as attribute name strings for this entity type. It's pretty consistent throughout all the code.

I did find a helper function that looks like it intends to just give a human-readable version of various attributes. Lots of calls for
res = res.replace("some-data-that-exists", "a-more-readable-version-of-some-data")

But the first call looks problematic.
res = attr.replace("_", " ")

If I'm not mistaken, that function just replaced the value of attr, then defined res as that value. Instead, it should have defined res as attr (no modifier), and in a separate line, redefine res as a modified version of itself.

#

Dang it, that formatting stripped out my underscores.

#

Regardless, my assumptions seem to be wrong. The method seems to be a fine way that doesn't modify attr.

#

I am 100% in over my head, but it's a fascinating learning experience.

elder moon
#

Is there a function which would replace national accents with latin letters in a string in jinja2?

#

I think it’s called normalization in Python

silent seal
#

I don't believe so, but you can use the replace function with a series of characters you want replacing

elder moon
#

Would slugify do that?

#

I mean I could just do a replace on polish characters but I would rather do something universal and share with community

inner mesa
#

That will change it to lowercase and replace spaces with _ I think

#

And probably also do what you want, but more that you don't

elder moon
#

That’s should be ok because I’m trying to prep a string for display on Awtrix, which uses a font without accents but also without lowercase/uppercase 😉

mighty ledge
#

it will remove all odd characters tho

fossil venture
#

What's the best way to get this condition to pass if the automation has never triggered? condition: condition: template value_template: "{{ now() - state_attr('automation.workshop_camera_motion', 'last_triggered') > timedelta(minutes=1) }}

fossil venture
#

What I came up with: {{ now() - state_attr(this.entity_id, 'last_triggered') > timedelta(minutes=1) if state_attr(this.entity_id, 'last_triggered') is not none else true }}

inner mesa
#

I think you could just do:
{{ state_attr(this.entity_id, 'last_triggered') is none or now() - state_attr(this.entity_id, 'last_triggered') > timedelta(minutes=1) }}

#

just a shorter version of what you have

#

whenever you return "true" or "false", there's usually a better way

haughty breach
#

I usually use:

{{ now() - this.attributes.last_triggered|default(as_datetime(0),1) > timedelta(minutes=1) }}
fossil venture
#

This is why I asked. Thanks.

devout dragon
#

https://pastebin.com/nQML0t5a is it possible to do something like this ? its the color_threshold value i want to have dynamicly set to the value of my input_number

devout dragon
#

solved it with config-template-card

odd condor
#

Hi guys, I need a bit of help with templates, please. I'm trying to filter entities that are of device_class:battery and then from them ones that have value below 20%. Apparently it would seem that state is not an integer so my function does not work correctly. Does anyone know how to correct it? Thanks! {{ states.sensor|selectattr('attributes.device_class','eq','battery')|selectattr('state','le','20')|list }}

#

The second selectattr is problematic, if I use " equal to 100" then it works properly. So either state is not an int or le function does not compute?

mighty ledge
#

You ahve to use namespace and convert the state to a float or integer

odd condor
#

I was actually trying to convert it from namespace into this to "simplify" 😄 So it doesn't work this way. Thanks!

rocky crypt
#

Hey there. I have a quick question. I wanted to create a dummy lock... I am able to create one, but I had to create a dummy switch with it to get it to work for value_template. Is there a way to do this without a dummy switch? Just have the dummy lock with lock/unlock services?

#

I tried omiting value_template, but it didn't like that. Then I tried pointing value_template to itself:

value_template: "{{ is_state('lock.dummy_lock', 'unlocked') }}"

and that made the lock stuck in unlocked mode... I couldn't click lock... It did nothing.

stray gazelle
#

In a template is it possible to serialize json?

lucid thicket
#

Use the filter to_json

stray gazelle
lucid thicket
#

There is a string filter also

lucid thicket
rocky crypt
#

@lucid thicket Perfect. Thank you! I will give this a shot later today!

rose bone
#

Hey everyone,

I'm looking for an easy way to monitor all battery levels for my zigbee devices.

I'd like HA to send me a notification every time I come home and a device is below 10%. (And which one)

Is there a template for that?

Alternatively I could make an automation but I would have to put every device entity as a condition and whenever I get notified I would have to check manually which device triggered it.

#

Or is there an easier way to monitor zigbee battery levels?

winter cape
#

Hi, I need help with actionable notifications. Is possible to show actions only is relevant? I mean action iron_plug, only if is iron on?
service: notify.mobile_app_jiri_ipx data: title: Upozornění! message: "{{message}}" data: actions: - action: HOME_TURN_OFF title: Vypnout vše - action: IRON_PLUG_TURN_OFF title: Vypnout žehličku - action: LIGHTS_TURN_OFF title: Zhasnout - action: MEDIA_TURN_OFF title: Vypnout média - action: FANS_TURN_OFF title: Vypnout větráky

marble jackal
#

You can, but you need to template the whole action section

winter cape
#

What do you mean?

eager yarrow
#

Heya, pls apologize for another n00b question: Is there a more elegant way to define the months in here?
Aim is to display annual tasks from a dedicated 'per year' calendar - its working in HA already, but feeling like writing self-repeating poems.
Reference pic from my 'old' system see [here](#frontend-archived message).

inner mesa
#

You could just write a macro and call it

eager yarrow
#

Thanks Rob, appreciate the instant answer, on first glance it exactly sounds what I am looking for. 🙂

lethal bison
#

there has to be an easier way to select a sensor with the most recent datetime

plain magnetBOT
#

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

lucid thicket
marble jackal
zealous ibex
#

The syntax of the templates to me is quite complex.

#

Is there a plan to get rid of it with something more user friendly such as js or python?

marble jackal
#

I don't think so, that would be a major breaking change. And I think it quite fits the purpose

zealous ibex
#

I don’t like the multi line part where each line you have to do the parenthesis

#

Or would it be an idea to implement auto completion in the editor for things like this?

mighty ledge
#

Just use vacode and it handles that for you.

#

Jinja will never go away

plain magnetBOT
#

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

coral garden
#

hello

#

I have a template light. It has turn_on, turn_off, set_level and set_temperature

#

each one of those calls a service: light.turn_on(off) command

#

when I have an automation that turns on the light I get the error 2024-02-25 07:55:38.149 WARNING (MainThread) [homeassistant.helpers.script.upstairs_led_template] Upstairs LED Template: Already running

#

I think that the way the automation calls the light.turn_on for the template light, which includes brightness and color temperature, calls the set_level and set_temperature commands of the template light in rapid succession, such that the template light is completing the set_temperature command when the set_level command is called

plain magnetBOT
#

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

coral garden
#

How can I avoid this problem because my template light isn't executing the brightness command

#

i forgot a ?

coral garden
#

Template variable warning: 'brightness' is undefined when rendering '{% if brightness is defined %}

#

?

#

how to I check if a variable is defined?

marble jackal
#

It's probably from somewhere else

coral garden
#

so template light calls set_temperature if the light.turn_on call has color_temp:

#

I am not formatting this correctly.

#

the only way to set brightness if the light.turn_on call has color_temp is to include {{ brightness }} in the set_temperature section of the template light

#

but, if I call light.turn_on with only color_temp, the call fails because there is no {{ brightness }} and I don't know how to check for {{ brightness }} if {% if brightness is defined %} throws an error

inner mesa
#

What error?

coral garden
#

I think the template light integration, should check if there is {{ brightness }} in a light.turn_on call that has color_temp and handle it gracefully

#

Template variable warning: 'brightness' is undefined when rendering '{% if brightness is defined %}

#

I chuckled at it

inner mesa
#

You'd have to make separate service calls if you want to include or exclude keys unless you make it even more complicated

coral garden
#

you mean do a light.turn_on with just color temp and then one that sets the brightness?

#

I'm already too deep

inner mesa
#

I think it's something else

coral garden
#

maybe this is an template light integration issue. I think it would be helpful if the template light could handle a light.turn_on call with only color_temp

inner mesa
#

Yes

coral garden
#

yes, it works in the template editor but not in the template light

inner mesa
#

You can template the entire data section if you want

plain magnetBOT
#

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

coral garden
#

my yaml has correct formatting in my file

#

wait there's a '"`

inner mesa
#

You need to remove the quotes

#

Don't use quotes in a multiline template

coral garden
#

okay now it works

#

once again the issue is with what I've done and not HA

lethal bison
#

@marble jackal I'm awake now!
I'm testing the code you pasted, it appears the time is determined and set to next_alarm.time correctly, but the entity_id is not copied to the next_alarm variable. Odd because if I change the line

{% set next_alarm.time = alarm_dt %}

to

{% set next_alarm.time = alarm_dt %}
{{alarm_dt}} {{alarm.entity_id}} {{next_alarm.entity}}

alarm.entity_id is correctly shown, but next_alarm.entity is still 'None'

haughty breach
#

spelling

#

next_alarm.enitity vs next_alarm.entity

lethal bison
#

ahh duh

#

thank you!

lethal bison
#

For anyone interested, I've made a group for each person in my household, with all of the sensors exposed for their phones by the companion app. The intended purpose is to trigger adaptive lighting for their bedroom, say 30 mins before their alarm goes off, the lights in their room will slowly increase brightness and color temp

lethal bison
#

Trigger warning - I havent done any reasearch yet -
What's the datetime format that would be easiest to interact with natively in HA? I have access to the alarm timestamp, but the datetime reported by the _next_alarm sensor appears to use ISO format

sacred sparrow
#

how do I ignore the state change if attributes.last_called_summary is ","

        Summary: >
          {{ expand('media_player.alexa_sonos_beam', 'media_player.alexa_echo_show', 'media_player.alexa_echo_spot', 'media_player.alexa_echo_dot')
            | selectattr('attributes.last_called_timestamp', 'is_number')
            | sort(attribute='attributes.last_called_timestamp', reverse=true)
            | map(attribute='attributes.last_called_summary') | first }}```
lethal bison
#

use a reject filter:
| reject('equalto', ',', attribute='attributes.last_called_summary')

sacred sparrow
#

when I do that : {{ expand('media_player.alexa_sonos_beam', 'media_player.alexa_echo_show', 'media_player.alexa_echo_spot', 'media_player.alexa_echo_dot') | selectattr('attributes.last_called_timestamp', 'is_number') | sort(attribute='attributes.last_called_timestamp', reverse=true) | map(attribute='attributes.last_called_summary') | first | reject('equalto',',', attribute='attributes.last_called_summary') }}

#

it says "<generator object select_or_reject at 0x7f886ef120e0>"

#

if I move the rject after the expand I get: "TypeError: _operator.eq() takes no keyword arguments"

marble jackal
#

Use reject('eq', ',') before the list filter

#

after the map filter

vital crown
#

Why is this not working?
{{ is_state('input_boolean.laddbox_schema', 'On') ? 'green' : 'red' }}

#

I got
TemplateSyntaxError: unexpected char '?' at 50

#

How should I write?

marble jackal
#

{{ 'green' if is_state('input_boolean.laddbox_schema', 'on') else 'red' }}

#

Also note the state will be on, not `On'

vital crown
#

Thanks , seems to work fine 🙂

marble jackal
#

Alternative
{{ is_state('input_boolean.laddbox_schema', 'on') | iif('green', 'red') }}

#

Which is more in line with what you had

devout dragon
#

what would be the difference of states("sensor.nordpool_kwh_se3_sek_3_10_025", "current_price") vs state_attr("sensor.nordpool_kwh_se3_sek_3_10_025", "current_price") ? 🙂 the documentation i find isnt so complete imho 🙂

vital crown
marble jackal
#

That's a different thing

#

But related though

#

states() is used to return the current state of the entity

#

state_attr() is used to return the value of one of the attributes of an entity

devout dragon
#

yes, but seems states() with entity name and then the attribute does the same thing? 🙂

marble jackal
#

No, it doesn't

#

That's just for that particular example, as the attribute value is the same as the state

devout dragon
#

hmm ok 🙂 so i might just have gotten luycky with that nordpool entity then 🙂 updated the templates to use state_attr insted 🙂

marble jackal
#

the 2nd parameter for states() indicates if you want to use the full state value as stored in the database, or if you want to use the precision set in the entity settings

#

so basically you were using:
states("sensor.nordpool_kwh_se3_sek_3_10_025", rounded="current_price")

devout dragon
#

oh, thats what i find missing in the documentation realy 🙂 the syntax of the actual function .. all i find is a bunch of examples of how to use it in the documentation but nothing that realy tells what the arguments are 🙂

haughty breach
#

I was just about to post the exact same thing

marble jackal
#

But, the templating docs are not the best, there are ideas to improve them

devout dragon
#

@marble jackal ah must have missed that then, would be nice with an ordenary documentation where you get the function name, click on it and get the arguments etc not baked into some text somewhere 🙂

marble jackal
#

Yeah, that's the current idea

devout dragon
#

yes!

sacred sparrow
#
            | selectattr('attributes.last_called_timestamp', 'is_number')
            | sort(attribute='attributes.last_called_timestamp', reverse=true)
            | reject('eq', ',')
            | map(attribute='attributes.last_called_summary') | first
             }}``` ?
marble jackal
#

After the map filter, otherwise you are still working with the full state objects

#

and before the first filter

#

you can also do it before map, but then you need to use | rejectattr('attributes.last_called_summary', 'eq', ',')

sacred sparrow
#

I'll give it a go 🙂 thanks!

subtle anvil
mighty ledge
#

specifically for the service calls data field?

subtle anvil
#

A service call, for the image field within data

#

Basically want one of these, based on the condition of a template:

data:
  image: "{{ snapshot }}"
# or
data:
  video: "{{ snapshot }}"
mighty ledge
#

ok, are you planning on sending other things?

#

ok

#

how do you plan on knowing which one?

subtle anvil
#

From a template conditon. Can use a trigger id or the payload of the mqtt request

mighty ledge
#

ok, what's the trigger ID?

subtle anvil
#

If it's triggerid is new I want image otherwise I want video`

#

Just to clarify, I specifically want one service call. I'm trying to avoid using a choose action if possible

mighty ledge
#

ok

#

so

#
data: >
  {% if trigger.id == 'new' %}
    {{ {'image': snapshot} }}
  {% else %}
    {{ {'video': snapshot} }}
  {% endif %}
subtle anvil
#

Oooh, then I conditionally return the dict itself? Does it have to formatted as json?

mighty ledge
#

typos

#

sorry

#

you can conditionally return the dict or you can do some fancy add/removing of the key

#

but conditionally with the dict is eaiser if you just have 1 options

#

multiple options, you want to go the other route

subtle anvil
#

Ok sweeeeeet, this makes sense, I will tinker around with that later.

I can test later, but do you know if I format it as yaml in the template?

data: |
  {% if trigger.id == 'new' %}
    image: {{ snapshot }}
  {% else %}
    video: {{ clip }}
  {% endif %}
  tag: {{ tag }}
  url: {{ url }}
mighty ledge
#

you have more keys there

subtle anvil
#

Gotcha, so we're relying on jinja to convert the json to dict

#

I do have other keys I want included

mighty ledge
#

{'x': 'y'} is a dict

#

if you want to include other keys...

subtle anvil
#

Right haha I know, just trying to understand limitations of jinja

#

I do need the other keys. The main reeason I want to do this is because the two notifications share all the other keys except for choosing either image or video

mighty ledge
#
data: >
  {% set ns = namespace(items=[('tag', tag), ('url', url)]) %}
  {% if trigger.id == 'new' %}
    {% set ns.items = ns.items + [('image', snapshot)] %}
  {% else %}
    {% set ns.items = ns.items + [('video', clip)] %}
  {% endif %}
  {{ dict.from_keys(ns.items) }} 
subtle anvil
#

Looks straightforward enough, haven't heard of namespace but will look into it! TY

#

I'm not seeing any docs on the dict.from_keys() fn though, do you have link for docs?

mighty ledge
#

there wont be any docs about it

#

it's a built in for python dictionaries

#

it's not even documented there

subtle anvil
#

I didn't realize you had access to python builtins from jinja?

#

Is jinja literally just exec'ing python code in the expressions?

mighty ledge
#

just know that it takes a list of tuples [('key', 'value), ('key', 'value')]

mighty ledge
subtle anvil
#

I think what I'll probably do is define the dict of shared values in a variables block, then conditionally add the image or video block in the template

mighty ledge
#

pretty much any 'complex object' in jinja is going to be a python object with a few exceptions

#

one being namespace

subtle anvil
#

ahh gotcha

mighty ledge
#

jinja is limited to scope

#

meaning that you can't adjust a variable inside an if statement and expect it to change when outside the if statement

#

you have to use namespace to get that

subtle anvil
#
variables:
  json: "{{ trigger.payload_json.after }}"
  type: "{{ json.type }}"
  event_id: "{{ json.id }}"
  label: "{{ json.label }}"
  camera_id: "{{ 'camera.' ~ json.camera }}"
  camera_name: "{{ state_attr(camera_id, 'friendly_name') }}"
  base_url: https://redacted/api/events/{{ event_id }}
  clip: "{{ base_url }}/clip.mp4"
  snapshot: "{{ base_url }}/snapshot.jpg?crop=1"

  shared_data:
    tag: "{{ event_id }}"

So I couldn't use the shared_data here?

mighty ledge
#

i.e.
{% if x == 4 %}
{% set y = 2 %}
{% endif %}
{{ y }} # ERROR

subtle anvil
#

Cause shared_data should be available globally to all actions

mighty ledge
#

shared data will be a dict, but you won't be able to alter it

subtle anvil
#

Could I convert it to a namespace and add a key to it?

mighty ledge
#

if you want to pass shared data as the dict, you have to do even more crap

mighty ledge
#

in regards to what you want to do...

#

this would also work...

subtle anvil
#

namespace behaves as a dict though right?

#

Just in a limited scope?

#

eww i see something nasty i could do....

loop over items in shared_data then add them to namespace, then convert namespace to dict

mighty ledge
#
data: >
  {% set output = dict(url=url, **shared_data) %}
  {% if trigger.id == 'new' %}
    {{ dict(image=snapshot, **output) }}
  {% else %}
    {{ dict(video=clip, **output) }}
  {% endif %}
subtle anvil
#

ah that's much cleaner

mighty ledge
#

** is python

subtle anvil
#

right

mighty ledge
#

for kwargs

subtle anvil
#

yup yup, cool

mighty ledge
#

doesn't work if your keys have spaces in the name

subtle anvil
#

so ambiguous which python features are avail to jinja lol

mighty ledge
#

which means you have to use the KVP method above

subtle anvil
#

yup yup, makes sense

mighty ledge
#

i.e. you can't change a value in the dictionary and you can't add to a dictionary, and you can't use the update function on a dictionary

#

so you're stuck making new dictionaries in stupid ways

subtle anvil
#

yeah, that's an ok limitation with me, still makes the template lib powerful as hell lol

mighty ledge
#

yes it does

#

take a look at my automations

#

I abuse the shit out of this everywhere

subtle anvil
#

well i appreciate you taking the time to explain all of that, this should make my shit wayyyyy more DRY

mighty ledge
#

look in scripts & automations folders

#

have fun 👍

#

you already understand complex concepts more than most people (99.99999%), so you should be GTG

subtle anvil
#

ye, im a software dev, it's been a fun side project. Just redid my whole homelab setup and am working on configuring my NVR

mighty ledge
thorny snow
#

Hi. I am new user of Discord and HA. Where can I ask a question about creating helper and using it in automation? I have created temperature helper and I understand that states are always strings. Now I am trying to compare it with number but getting 'undefined' error. Sorry if this is not the right place to ask...

inner mesa
#

please share the code that you're using

plain magnetBOT
#

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

thorny snow
#

state template
{{ state_attr('weather.forecast_home', 'temperature')}}
I have created it via frontend - it shows graph with data, so far so good
In the automation:

    - service: light.turn_on
      entity_id: light.rgbcontroller
      data_template:
        rgb_color:
          - "{% if sensor.tempoutside | int <= -35 %} 255 {% elif
            sensor.tempoutside | int == -34 %} 240 {% elif sensor.tempoutside
            | int == -33 %} 225 {% elif sensor.tempoutside | int ==
            -32 %} 210 {% elif sensor.tempoutside | int == -31 %} ``` and so one - found this one online
inner mesa
#

sensor.tempoutside should be states('sensor.tempoutside')

#

you used state_attr() in the first one, so presumably you're aware of the templating docs?

#

if you found that online, I wouldn't vist there again for a correct answer

#

it's also missing a trailing "

thorny snow
#

Ok. This worked:

          - "{% if states('sensor.tempoutside') | int <= -35 %} 255 {% elif
            states('sensor.tempoutside') | int == -34 %} 240 {% elif states('sensor.tempoutside')
            | int == -33 %} 225 {% elif states('sensor.tempoutside') | int == ```...
#

thank you!

eager yarrow
#

Having the following triggers in a new template that is working well at startup / yaml reload:

  - trigger:

      - platform: homeassistant
        event: start
      - platform: event
        event_type: event_template_reloaded
      - platform: state
        entity_id: calendar.jahreskalender

Expectation was that it is also triggering when the calendar is changing (local HA calendar, last entry). However, it doesnt fire when adding / changing / deleting entries in that calendar. Of course its all layer 8 fault - but what did I do wrong?

summer grove
#

Can someone help me with a template for a change in numeric state. I need the condition to be previous state is greater than new state.

inner mesa
#

pretty straightforward

#

{{ trigger.from_state.state|float > trigger.to_state.state|float }}

silent vector
#

Is it not possible to use jinja for template sensors with a yaml dictionary?
I keep getting
template value should be a string for dictionary value for the last 2 keys in webhook_ids

https://dpaste.org/mCKVH

I tried this both with the states('input.text.xyz') inline with each value (frigate,zwave_js) and broken out the way I have it now with separate keys under image_names

marble jackal
#

you can only use a template in an attribute, so you can't use a yaml dict

#

use something like

#
      image_names: >
        {{
          {
            'frigate': states('input_text.frigate_image_name'),
            'zwave_js': states('input_text.zwavejs_image_name')
          }
        }}
silent vector
#

Ah ok that's what I was going to try next thank you.

acoustic arch
#

i have these spikes going to zero(0), because well... my default is 0. How can i ignore zero values so my graph wont look all wonky?

  sensors:
    stroom_import_export_balans:
      value_template: "{{ 1000 * (states('sensor.power_production') | float(0) - states('sensor.power_consumption') | float(0) ) }}"
      unit_of_measurement: 'W'
      friendly_name: "netto import of export"```
marble jackal
#

add an availability_template so the sensor will be unavailable when your source sensors are not providing numeric data

acoustic arch
#

ive heared of that one before! ill look into it. thx!

wary yew
#

Is it possible to create a template sensor that gets info from the event after the next event of my calendar? The calendar entity returns the directly next one. I need the one after as well for some specific reminder. The event exists in the calendar.

marble jackal
wary yew
#

I was reading just that

mighty ledge
wary yew
#

the link to docs points to the same plance, but both calls exist

mighty ledge
#

list_events is old, avoid it

marble jackal
#

list_events is de old one, which is depreciated, get_events is the newer one, which allows multiple calendars as target

wary yew
#

yeah, sorry for the double post

#

xD

#

seriously wasn't thinking on a service call to achieve it, and skipped the services part in the docs, mb

plain magnetBOT
#

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

wary yew
#

This is the call response if it helps:

calendar.meals:
  events:
    - start: "2024-02-27T23:00:00+00:00"
      end: "2024-02-27T23:30:00+00:00"
      summary: Sopa y 3 burgers de pollito
      description: >-
        El caldo es el que ha sobrado al mediodía. Sacar burgers pollo a
        descongelar.
    - start: "2024-02-28T15:00:00+00:00"
      end: "2024-02-28T15:30:00+00:00"
      summary: Pechugas de pollo al horno con especias y patatas al horno
      description: Sacar 2 pechugas de pollo a descongelar.
inner mesa
#

great, now I'm hungry

#

you need to surround your templates in quotes

wary yew
#

why does this work {{ state_attr('calendar.meals', 'message') }} but this {{ message | state_attr('calendar.meals', 'message') }} returns an error Error rendering data template: TypeError: state_attr() takes 3 positional arguments but 4 were given ?? I don't get what it has to do with state_attr

#

just looking to use the variable message if it exists, and the state_attr if not. That's what the ternary operator does, right?

inner mesa
#

what is your goal with the second one?

#

it's not valid

#

are you trying to set an attribute?

wary yew
#

no

#

it's a message for my speaker

inner mesa
#

I'm saying that this is nonsense: {{ message | state_attr('calendar.meals', 'message') }}

wary yew
#

I want it to use the variable "message" from earlier if it was passed on, and it it doesn't, for it to use the value of the sensor

#

I get it, I just don't get whyx D

#

prob it's my bad understanding of |

inner mesa
#

I think you're trying to use | for "or", which it isn't

#

it introduces a filter

wary yew
#

hmmm, not familiar either. Chatgpt misled me too then. What would it be the right way then?

inner mesa
#

what does "if it ws passed on" mean? not defined?

wary yew
#

it also suggested {{ message if message else state_attr('calendar.meals', 'message') }}

inner mesa
#

if you're using ChatGPT, you're just getting yourself in trouble. please don't

#

nobody here wants to debug the crap that ChatGPT produces

wary yew
#

just wanted to don't be too much of a bother here...

inner mesa
#

question remains:

what does "if it ws passed on" mean? not defined?

wary yew
#

but other automations call the same script without generating that variable

#

so I want to use the variable if it was passed to the script by the automation, or else use the default sensor value

inner mesa
#

so what value does it have when you don't want it to be used?

wary yew
#

state_attr('calendar.meals', 'message')

inner mesa
#

"none"?

wary yew
#

that's the "default"

inner mesa
#

no, the message variable

#

again:

what does "if it ws passed on" mean? not defined?

#

you're assigning something to the "message" variable, and then wanting to decide something based on its value later

wary yew
#

yep

inner mesa
#

so.....

wary yew
#
    data:
      variables:
        message: {{ state_attr('calendar.meals', 'agenda')[1].summary }}
        description: {{ state_attr('calendar.meals', 'agenda')[1].description }}
inner mesa
#

you need to know what value it has when you want to use its value and when you want to use the attribute

#

I think we're just going in circles now

wary yew
#

hmm sorry

#

I just want to use it if it exists

inner mesa
#

it will always exist

#

you're declaring it

wary yew
#

not within the script

inner mesa
#

so, what value does it have when you want to use it, and when you want to ignore it?

wary yew
#

I declare it in an automation

#

when I want to ignore, it doesn't exist AFAIK

inner mesa
#

you are passing it to the script....

#

no

#

you aren't conditionally passing it to the script, you are always passing it to the script

wary yew
#

not always. The script will be called by other autos that do not have the variable

inner mesa
#

ok

#

you've only provided that one example

haughty breach
#

What is the purpose of using get_events if your script isn't passing anything from the response?

inner mesa
#

if you're not passing it at all, then you can use {{ message if message is defined else state_attr('calendar.meals', 'message') }}

wary yew
inner mesa
#

maybe you can use iif() there, but I don't know for sure

wary yew
#

just for my learning, what does | do then?

#

I def got that wrong

#

I thought it was a type of IF

mighty ledge
#

| applys a filter

wary yew
#

ok, will read on that

mighty ledge
#

jinja has functions, filters, and tests

#

function()

#

x | filter

#

y is test

wary yew
#

got it, thanks

wary yew