#templates-archived

1 messages · Page 30 of 1

fossil venture
#

Also you don't need to iterate to do that. {% set checklights = expand(state_attr('group.alllights', 'entity_id')) | rejectattr('entity_id', 'in', ['light.tilewall01', 'light.li11_hallway', 'light.li08_bedside_lamp_01', 'light.li09_bedside_lamp_02']) | selectattr('state', 'eq', 'on') | map(attribute='entity_id') | list %}

tepid onyx
marble jackal
#

@tepid onyx Easiest would be to give the scripts the same object_id as the lights and add | map('replace', 'light.', 'script.')

#

But you could also create a dict to map the light to the right script

thorny snow
#

Hello you all

thorny snow
#

Maybe someone can help me with a small task. I want to create a sensor, that - depending on a condition - shows the values of one sensor or another. How can I do that?

#

to be concrete - I have two electric cars with two "State of charge" values. In my "custom:power-distribution-card" I can add a sensor for my car, so I see the State of Charge of my car, when the car is charging. Here I have to decide which sensor of which car I use. So I want to create a new sensor that always shows the state of charge of the car, that is currently charging. Like:
If car1 is currently charging, show SoC of car1, if car2 is currently charging, show SoC of car2. If no car is charing, show SoC of car that was charging last.

thorny snow
#

I think I can do that with a template, however i have no idea how to actually do it 😦

marble jackal
#

@thorny snow {{ [ 'sensor.car1', 'sensor.car2'] | map('states') | map('float', default=0) | max }}

acoustic arch
#

trying to pass a variable to a script. Number works. But string not yet.

data:
  set_brightness: "dim"```

fighting with the quotes. any suggestions?
#
value_template: "{{set_brightness == \"dim\"}}"```
??
obtuse zephyr
#

Just do

condition: template
value_template: "{{ set_brightness == 'dim' }}"
acoustic arch
#

ill try it out

#

got it!

#

also forgot to disable another condition in the script🤦🏼‍♂️

#

thank you

livid island
#

hi all, maybe someone knows if it's possible to make a condition from the current dashboard url or from switch dashboard your in.

#

Something similar to this

{% set dash = dashboard().current %}
{% if dash = bedroom %}
Your viewing the bedroom
{% else %}
Your viewing something else
{% endif %}
tepid onyx
lone birch
#

hey! I have created a sensor that contains the (estimated) number of seconds until my heatpump's reservoir will be heated again. However showing a countdown in seconds for something that is often many hours in the future is not practical (although it is practical so have it as a number to perform calculations in automations). Is there a way of displaying that sensor as a sensibly formatted countdown while still have it be a time and not a string?

lofty mason
#

Do you want it to display "hh:mm:ss" updated per second? Or just something fuzzy like "in 4 hours"?

#

I don't know that having a sensor with "seconds remaining" is a great idea, I don't think you really need or want to have a state change every second, that sounds like a lot of slamming on your database. Better to just set the state to the time it will be done, and then you can calculate what you need based off that, or use the frontend to display the seconds remaining without forcing tons of state updates.

#

I am aware that working with datetimes in automations can occasionally be a bit confusing and daunting, but once you learn how it works and can get past that I think you'll find you don't really need a state with seconds remaining.

lone birch
#

I was playing with the idea of a timedelta

#

which does seem to work

#
        {% set secondsSinceLastChanged = as_timestamp(now()) - as_timestamp(states.sensor.temperatura_actual_acs.last_changed) %}
        {{timedelta(seconds = ((states('sensor.temperatura_actual_acs') | int - (states('number.temperatura_objetivo_acs') | int - 5.5)) / 0.3333 * 3600 - secondsSinceLastChanged) | int)}}
#

however I see your point. In reality instead of the remaining time, I could have an "estimated hour"

#

same thing, much easier on the database because it would update far less often

lofty mason
#

The two options I can think of are if you have a timer entity, you can set the timer with the number of seconds until done when you calculate it, and then the frontend will show the time remaining in hh:mm:ss format.

Alternatively, if you have a sensor with the finishing time as the state, and set it to device_class timestamp, the frontend will display that sensor as a relative time like "In 33 minutes".

lone birch
#

^ that sounds like the best idea

#

@lofty mason but how do I generate a sensor for a time in the future that doesn't recompute all the time?

lofty mason
#

Well I guess that's up to you, how you compute the future time, and how often you want to compute it. What are the inputs to the formula?

lone birch
#

essentially I've estimated that the water cools about 1/3°C each hour. So if the water is at 48°C and i know that it will be heated again the moment it goes below 45°C, my estimation is (48 - 44.5) / 0.333, but for extra accuracy since the temperature sensor has a 0.5°C sensibility, I'm taking into account how many seconds ago the temperature last changed

#

if it last changed 30 minutes ago, I'm subtracting 30 minutes

lofty mason
#

I mean it's ok if the time in the future recomputes when the inputs change. I'm not saying you have to totally stop updates to the database, I was just suggesting that you don't need a "countdown" where you're causing state updates every second that are unneeded.

If it was mine I would probably just recompute a new finishing time every time the temperature sensor changed, that seems reasonable.

lone birch
#

it does

#

I don't think I need to account for the time passed since it last changes. It might help with accuracy when first calculated, perhaps after a reboot, but from that point on since the value will be computed with every temperature change, it will be calculated with very little to no delay

tepid onyx
#

If you have a temperature sensor on the heat pump why not use the temp it starts heating and the temp it stops heating. then notify when it gets there. If you really want to get a time till it stops heating a trend sensor would probably work

lone birch
#

@tepid onyx I'm not sure I follow your reasoning. I want to have an estimation of when it will heat. Like, in 5h 23m

#

@tepid onyx I just learned that trend sensors exist

#

i like that, it could work, specially because my estimation of 0.333°C/hours depends on the current ambient temperature. The room where the reservoir is ~14°C. In summer it will be at 25°C, so the speed at which the reservoir looses heat will be different

lone birch
#

is there a way of getting the current time similar to now() but that doesn't cause the template to update every minute?

marble jackal
marble jackal
lone birch
#

I could update with the same frecuency as the other sensor it relies on, the current time has no effect

marble jackal
#

Create a trigger based template sensor and use the state change of the other sensor as the trigger

tepid onyx
marble jackal
#

Not right now, I'm on mobile

lone birch
#

@marble jackal that sounds promising. I've been using HA for years and I keep learning about features I didn't know existed all the time. Trigger sensors and the trend integration today, and the bayesssian integration a week ago

plain magnetBOT
#

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

marble jackal
#

@lone birch The new template sensor format falls under the template integration, where your old (legacy) template sensors fall under the template integration

#

The docs always assume that the code is directly placed in configuration.yaml, so the first line is the integration

jovial horizon
#

Hi. I am trying to scrape my energy price from a website displaying the price in cents per kWh. For my energy dashboard I want the price to be in EUR/kWh. When I try to convert in EUR via value_template is goes wrong. Anyone seeing what is wrong in this code:

value_template: "{{ (value | replace(',', '.')) / 100 }}"

marble jackal
#

@jovial horizon You will still have a string after replacing the comma with a dot

#

You need to convert it to a float before you can divide it

jovial horizon
marble jackal
# tepid onyx could you elaborate on creating a mapping please

your pastie expired, so I could not see the actual scripts anymore, but I meant something like this:

{% set light_to_script =  {
                            'light.tilewall01': 'script.foo',
                            'light.li11_hallway': 'script.petunia',
                            'light.li08_bedside_lamp_01': 'script.whale',
                            'light.li09_bedside_lamp_02': 'script.bar'
                          }
%}
{% set checklights =  expand('group.alllights')
                        | rejectattr('entity_id', 'in', light_to_script)
                        | selectattr('state', 'eq', 'on')
                        | map(attribute='entity_id')
                        | list 
%}
{{ light_to_script.items() | selectattr('0', 'in', checklights) | map(attribute='1') | list }}
grave solstice
#

Hi, i have been banging my head for a while so ill try asking 🙂

I have a mqtt sensor where i have a value template....

I receive a comma seperatted list all, good i can extract the value i need... However, i want to add the other values i receive as attributes, is this possible.

Question2: In the value template if i receive a specific value i would like to NOT update the current state....

thorny snow
#

Hi, I have a sensor that updates every minute and in that way spams the log. Is there a way to only update this sensor the moment that the sensor that it is based upon updates? This is the template sensor:

    tesla_timechargingfinished:
      friendly_name_template: "Tesla finishes charging at"
      value_template: "{{ (now() + timedelta(hours=states('sensor.tesla_time_to_full_charge')|float)).strftime('%H:%M') }}"
thorny snow
lofty mason
#

But I'm not aware of a way to restrict the update rate of templates, or to prevent now() from triggering minutely updates.

#

Or if the only issue is the logbook, just exclude this sensor from the logbook.

marble jackal
#

you'll have to use the new template sensor format then, the legacy format you are using now doesn't support triggers

#
template:
  - trigger:
      - platform: state
        entity_id: sensor.tesla_time_to_full_charge
        to: ~
    sensor:
      - unique_id: tesla_time_charging_finished_template_sensor
        name: Tesla finishes charging at
        state: "{{ (now() + timedelta(hours=states('sensor.tesla_time_to_full_charge')|float)).strftime('%H:%M') }}"
lofty mason
#

oh neat, I had no idea templates could have customized triggers 👍

lone birch
#

@thorny snow I did it like this:

#
- trigger:
    - platform: state
      entity_id:
        - sensor.temperatura_actual_acs
        - number.temperatura_objetivo_acs
  sensor:
    - name: "Próximo arranque ACS"
      unique_id: forecasted_next_acs_cycle
      state: "{{now() + timedelta(seconds = ((states('sensor.temperatura_actual_acs') | int - (states('number.temperatura_objetivo_acs') | int - 5.5)) / 0.3333 * 3600))}}"
      icon: "mdi:calendar-clock"
marble jackal
lone birch
#

instead of having:

# configuration.yaml
sensor:
  - platform: template
    sensors:
      sensor_name: 
        friendly_name: Fridge temperature
        value_template: "{{stuff}}"

I should have

#configuration.yaml
template:
  - sensor:
    - name: Fridge temperature
      state: "{{stuff}}"
inner mesa
#

That would be the new format, yes

lone birch
#

I have homework then. A lot of stuff to move around

#

the old format does not allow (or I didn't see a way) of having a trigger on a sensor

inner mesa
#

That's true

lone birch
#

all clarified. Since I missed the memo of formats changing, did anyone produce any migration guide? @inner mesa Seems simple enough tho

inner mesa
#

Maybe? It's pretty straightforward

lone birch
#

yeah, don't worry

winter forge
#

That link will take you to the template sensors line on my github

#

The goal of the sensor is to determine what I am up to

inner mesa
#

I don't know what you want folks to do with that monstrosity

winter forge
#

Tell me if they see any blatant error that a non-coder like me might miss 😛

tepid onyx
thorny snow
#

I have from 2 ESPHome devices power values (P1 and P2) and I want to divide the 2 values to create a new variable (P1 / P2 = Factor). Can this be done in a template?

upper basalt
#

I’m trying to create a humidifier ‘device’ based on different entities, not a generic hygrostat but an actual humidifier-device, I have ‘everything’ I need but as different entities (from localtuya) so anyone know how to do that, to create a ‘generic humidifier’?

lofty mason
#

I don't believe devices are creatable as an end user.

obtuse zephyr
#

and why doesn't generic hygrostat suit that need?

neon bolt
#

Hi, I try to compare 2 values this way

#

condition: template
value_template: >-
{{ state_attr('climate.nest', 'target_temp_low')| float(0) }} = {{
states('input_number.temperature_confort')| float(0) -2 }}

#

😦 unable to make it friendly to read ...

#

but it seems it doesn't work ...

inner mesa
#

that's not a valid template

#

you have to write one template with the logic inside

plain magnetBOT
#

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

inner mesa
#
{{ state_attr('climate.nest', 'target_temp_low')| float(0) == states('input_number.temperature_confort')| float(0) - 2 }}
neon bolt
#

wow, ur so right

cyan elm
#

Hi guys, I'm stuck on something that is seemingly so simple, I'm trying to get my config file to add all the template files in the the folder templates. It's loading one, but one of them keeps giving me errors, here it is below

#
Invalid config for [template]: [masterbed_temperature] is an invalid option for [template]. Check: template->sensor->0->masterbed_temperature. (See /config/templates/temperatures.yaml, line 0).
#

That's the error

plain magnetBOT
#

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

cyan elm
#

That's what the temperatures.yaml that its adding looks like

#

I've checked indentations a million times, if someone could help it would be greatly appreciated

lofty mason
#

What about this?

- sensor:
  - name: masterbed_temperature
    value_template: "{{ state_attr('climate.l1_100', 'current_temperature') }}"
    unit_of_measurement: '°C'
    friendly_name: 'Master Bedroom Temperature'
    device_class: temperature

I'm looking at template examples but I don't see one where there's just a raw string instead of a name key. could be wrong though, not sure

#

is this being included under a template: key? Looks like you might be mixing up a bit of new format and legacy format.

cyan elm
cyan elm
#

how is valid template invalid?

#

lol

#

value*

inner mesa
#

it sounds like you're mixing up the old and new formats

#

you want state:

cyan elm
#

oh state instead of value template?

cyan elm
#

I see

#
- sensor:
  - name: masterbed_temperature
    state: "{{ state_attr('climate.l1_100', 'current_temperature') }}"
    unit_of_measurement: '°C'
    friendly_name: 'Master Bedroom Temperature'
    device_class: temperature
#

Trying this

inner mesa
#

I don't think it accepts "friendly_name"

cyan elm
#

The interesting this is when I Had this in my config.yaml before I exported it to separate files

#

it was working a charm

inner mesa
#

that seems doubtful

cyan elm
#
- sensor:
  - name: masterbed_temperature
    state: "{{ state_attr('climate.l1_100', 'current_temperature') }}"
    unit_of_measurement: '°C'
    device_class: temperature
#

This worked, thanks!

#
Invalid config for [template]: expected dictionary for dictionary value @ data['sensors']. Got [OrderedDict([('name', 'masterbed_temperature'), ('state', "{{ state_attr('climate.l1_100', 'current_temperature') }}"), ('unit_of_measurement', '°C'), ('device_class', 'temperature')]), OrderedDict([('name', 'kitchenliving_temperature'), ('state', "{{ state_attr('climate.l1_102', 'current_temperature') }}"), ('unit_of_measurement', '°C'), ('device_class', 'temperature')]), OrderedDict([('name', 'toplounge_temperature'), ('state', "{{ state_attr('climate.l1_101', 'current_temperature') }}"), .... (See /config/templates/temperatures.yaml, line 0).
#

Sorry another question, when I put them all back, this is the error I get now

plain magnetBOT
#

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

lofty mason
#

it's sensor: not sensors:

cyan elm
#

bruhhhhh

#

Thanks Tim!

lofty mason
#

sensors is the legacy format, which you're mixing up

cyan elm
#

Hopefully it's all sweet now

#

It's all sweet! Thanks!!!

brittle shore
#

hello, im trying to template a nested variable, i believe thats what youd call it. im basically brand new to HA.

Ive got a helper, with some value in it that id like to access using a variable instead of referencing the helper directly.

the idea is that i would to perform an action using the value stored in one of 5 helpers. thus the variable reference.

the helpers are named color1 - color5 etc. its the color[n] bit that i cant seem to crack. i can explicitly call any of them and it works fine. the value of n (1-5) is stored in a local var called "result"

value: "{{ states('input_text.color[result]') }}" #returns an unknown value

value: "{{ states('input_text.color1') }}" # correctly returns the value stored in helper 1

#

i know its something simple, but given my limited exposure i cant spot the syntax hang up etc

inner mesa
#

{{ states('input_text.color' ~ result) }}

brittle shore
#

thx much i was just coming back to say that i arrived at value: "{{ states('input_text.color' ~ result) }} as well

tribal cedar
#

Is there a way to avoid template loops (seeing them reported in the logs) in a template where in a binary sensor, I need to find many other binary sensors matching a certain substring. eg

        {%- for sensor in states.binary_sensor -%}
        {%- if 'motion_triggered_now_in' in sensor.entity_id and 'utility' not in sensor.entity_id -%}

I guess because this template 'listens' to all states.binary_sensor its classed as having a template loop. Is there some way to narrow that sensor watch to avoid loops, yet still having one binary sensor search for others.

marble jackal
#

@tribal cedar you don't need a for loop for that

#
{% set sensors = states.binary_sensor | selectattr('entity_id', 'search', 'motion_triggered_now') | rejectattr('entity_id', 'search', 'utility') | map(attribute='entity_id') | list %}
#

That will list all entity_id's which match the if statement

harsh lintel
#

how to convert hex string 'fffb' to 16-bit signed integer -5

fffb -----> -5

marble jackal
#

{{ 'fffb' | int(base=16) }} returns something, but not -5

silent vector
#

I'm trying to see if test has more than 1 light. but I get str object has no attribute 'light'

{% set test = 'light.front_door_outdoor_light','light.foo_light' %}
{{ test | selectattr('light') | list | length }}
marble jackal
#
{% set test = 'light.front_door_outdoor_light','light.foo_light' %}
{{ test | select('match', '^light') | list | length }}
silent vector
#

How are you doing the highlighting?

marble jackal
#

python instead of jinja

silent vector
#

Nevermind yeah I saw that when I copied it lol

#

Awesome

#

Thank you

silent vector
#

How would I ignore white space in a string? When using startswith let's say foo.startswith('bar') but a user puts in bar it wouldn't match

marble jackal
#

apply trim first?

#

{{ (' bar' | trim).startswith('bar') }} returns True

thorny snow
silent vector
#

Awesome thank you

tepid onyx
#

| map('trim') | list
t o trim whitespaces in list elements

#

or
| regex_replace('^(\\S+\\s+\\S+)\\s+.*$', '\\1')
to trim all whitespaces.
lots of ways

naive knoll
#

Using the commonly used light counter script which works fine.

{{ states.light
| rejectattr('attributes.entity_id', 'defined')
| selectattr('state', 'eq', 'on')
| list | count }}

However I have lights which are toggled on by switches. Given there are lots of 'switch.' based entities in home assistant is there a way of isolating the lights powered by switches and counting them?

rose scroll
naive knoll
plain magnetBOT
#

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

marble jackal
#

the state template is rendered before the attributes are created, so the state_attr() will result in none

#

the state template will then fail on the as_datetime(none)

#

and because of that your template will be unavailable

#

some other remarks, I don't know if self referencing using this works in the legacy format (which you ar using)

#

and you can simply use {{ days_since >= 3 }} . That will already return True or False. No need to build an if statement to achieve the same result

deft pebble
#

Would it be posibble to change the result of the following:

{{ state_attr(''media_player.hdmi_sync_box'', ''volume_level'') }}

This shows as an value of 0.00 (0.00 - 1), but i would like to show the result in percentage.

#

Such as 0.56 shows as 56%

lofty mason
#
"{{ (state_attr('media_player.hdmi_sync_box', 'volume_level')|float * 100) | int }}%"
deft pebble
#

Awesome, thank you!

halcyon fulcrum
plain magnetBOT
marble jackal
#

the legacy template is mentioned at the bottom of that page

tribal cedar
# marble jackal <@623023579692400641> you don't need a for loop for that

Thanks for that. It seems even with the much improved approach to find these sensors, HA is still reporting it as a template loop. I assume the fact that I mention states.binary_sensor at all, means it is still looping internally with the pipes | and is looping over itself, reporting it then as a template loop? I wonder is there a way around it.

halcyon fulcrum
#

Thanks!

hard venture
#

I'm working on a Template condition in an automation.
I've got it triggering off of an event and I'm specifying the device_id: of the event I captured. For the condition, I want to look at Data: -> parms -> move_mode. I presume that my trigger condition would look at {{ tringger.event.data}}, but how do I specify all the way down to get to look at move_mode?
would {{trigger.event.event_data.parms.move_mode}} do the trick or just error out on me? I'm not sure I can test this in devtools | Template, can I?

#

answers the question: No

lofty mason
#

Can you post the full contents of the event you captured from the devtools?
if there's a further dictionary inside the event data, then yeah you'd just keep adding to the path to the final variable you're after

inner mesa
#

You probably at least have one too many 'event' items in there, but yes, seeing the actual event would help.

plain magnetBOT
#

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

hard venture
#

hah, yeah, I see where I typed event.event - that was a typo on my part, not a copy/pasta

lofty mason
#

yeah in that case trigger.event.data.params.move_mode should be a usable variable in a condition or action

hard venture
#

Thanks, @lofty mason . I presume I need to enclose it in {{ }}, correct?

lofty mason
#

Yes if you're writing a template.

hard venture
#

OK. thought so, just wanted to confirm. That'll eliminate one error...

dense swan
#

Question based on documentation found at https://www.home-assistant.io/integrations/cover.template/ . I have a Garage template sensor I created that takes an upper and lower tilt sensor into play on their status and creates the Garage Sensor based on their combined status. Based on the documentation and the value_template option it says open, closed, etc. but my Template sensor reports Open, Closed, etc. Do I need to lower case to comply or will HA convert it automatically?

lofty mason
#

I believe the states to use are "open" and "closed". If you see capitalization, that's probably just displaying the "human friendly" version. Do you just see those in the frontend display, or where are you seeing "Open" exactly?

dense swan
#

I wrote this

plain magnetBOT
#

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

dense swan
#

I wrote out Open, Opening, and Closed which HA would use for the cover.template's value_template to determine status

#

Not sure if should/need to change them to lowercaase to comply

#

Like when I look at states for sensor.garage, which the cover would use says the Open version not open like other states do

#

So not sure this would mess with the value_template's processing ability

#

didn't know if cover templates do a lc(value) to make it comply or do I have to

#

Its just tomato tomatoe but just asking

#

Guess this answers it:

#

2023-02-23 18:46:21.539 ERROR (MainThread) [homeassistant.components.template.cover] Received invalid cover is_on state: unknown for entity cover.garage_door. Expected: open, opening, closed, closing, true, false

tight parrot
#

Am I able to change the min/max/units settings on an input_number based on another value?

I tried this, but it'd seem I can't use templates in those fields directly:

# Input number for setting a custom height
input_number:
  standing_desk_height:
    name: Standing Desk Height
    icon: mdi:human-male-height-variant
    min: {{ states("number.upsy_desky_min_target_height") }}
    max: {{ states("number.upsy_desky_max_target_height") }}
    unit_of_measurement: {{ states("select.upsy_desky_height_units") }}
inner mesa
#

No, you cannot

haughty breach
#

If you use a template number you can template everything but the unit... because unit_of_measurement isn't a valid key for template number entities.

template:
  number:
    - name: Standing Desk Height
      state: "{{this.state | default(0,1)}}"
      optimistic: true
      set_value:
        - service: number.set_value
          target:  
            entity_id: number.standing_desk_height
          data:
            value: "{{ value }}"
      icon: mdi:human-male-height-variant
      min: '{{ states("number.upsy_desky_min_target_height") }}'
      max: '{{ states("number.upsy_desky_max_target_height") }}'

However, it is only restart tolerant if you use a standard input number or text to save the state value...

ivory lotus
#

hi all, I have an issue with a template sensor where I changed the unit from Wh to kWh (by dividing the state by 1000). After Restarting HA the Value stays in Wh. Why?

#

- name: "Solar Forecast Watt Hours" unit_of_measurement: "kWh" device_class: energy state_class: measurement unique_id: solar_forecast_watt_hours #availability: "{{state_attr('sensor.solar_forecast_watt_hours_raw', 'watts')[state_attr('sensor.solar_forecast_watt_hours_raw', 'watts')|sort|select('le', now().strftime('%Y-%m-%d %H:%M:%S'))|list|last] |float |is_number }}" state: > {% set time_now = now().strftime('%Y-%m-%d %H:%M:%S') %} {% set tkey = state_attr('sensor.solar_forecast_watt_hours_raw', 'watt_hours') |sort|select('le', time_now)|list|last %} {{ state_attr('sensor.solar_forecast_watt_hours_raw', 'watt_hours')[tkey] /1000 | float }}

#

if I check the state in the dev tools it changes accordingly and everything seems to work

#

i mean in the dev tools - template editor tool...

#

is there a way to force the template sensor to take the updated state? (nevertheless, the sensor is updating the value, but does not divide it by 1000....)

marble jackal
#

are you sure there isn't a sensor.solar_forecast_watt_hours_2 now? Could be if you also added/changed the unique_id while making the changes

half pendant
#

Trying to create a universal media player that uses source as a combination between a TV and an Apple TV. Basically i want to use the HDMI 1 and 4 (PC AND XBOX) from the TV but everything else from the Apple TV (HDMI 2). Is there a way to do this? So source list should be "Apple tv source + HDMI 1 and 4 from TV" and when i select the appropriate one it should switch to the corresponding input on the tv as well

median mason
#

I want to set the name of this custom button based on the value of the entity. when its empty, it should be "select room" and when it has some values (eg: kitchen, living_room etc) it should be "clean". but i dont get that. it shows the code itself.

- type: custom:button-card
  entity: variable.deebot_kajer_beti_ronbot_queue
  icon: mdi:play-pause
  name: >-
    {%- if is_state('variable.deebot_kajer_beti_ronbot_queue', "") -%}
      Select rooms
    {%- else -%}
      Clean
    {%- endif -%}
half pendant
#

I tried giving the universal remote a custom source list like this source_list: input_select.lg_inputs but it does not seem to work...

floral shuttle
#

is direct way to create a RFC 3339 format (ie. yyyy-mm-ddThh:mm:ss+offset) time sensor other than via strptime/format? I had this{{as_timestamp(now())|timestamp_local}} but it still contains the milliseconds.

marble jackal
#

if you have a timestamp, you can simply use | int

#

{{ (as_timestamp(now()) | int) | timestamp_local }}

#

2023-02-24T14:21:38+01:00

floral shuttle
#

right! {{as_timestamp(now())|int|timestamp_local}}

#

o wait, you do something else

#

its correct though, never thought of |int ' ing that. thx!

#

would be a nice filter though 😉 {{now()|rfc_3339}}

marble jackal
#

I actually do the same, I've added some unneeded brackets

floral shuttle
marble jackal
#

so you created a template sensor which outputs that format, and then used that in the card config?

acoustic arch
#

i pretty much always do INT/FLOAT(default=0), but now i have a sensor with verrry high numbers. Like 300k. When i graph this and an 0 is added i get an almost flat line due to the 0.

#

Should i remove the default and let it just make an error to remove the zero values?

marble jackal
#

You should probably add an availability template to make the template sensor unavailable when the source sensor(s) are not providing the right state

halcyon fulcrum
#

How could I select sensors which states are 'on' and use the list to pick their attribute values? I've tried some rejectattr and selectattr trickery but I don't fully understand how they work.

inner mesa
#

states.sensor|selectattr('state', 'eq', 'on')|map(attribute='attributes.whatever')

#

Otherwise, need more details on what 'pick' means and what you've tried

#

Plus, you probably mean binary_sensor

mossy flax
#

HI! surely I'm missing something in restoring a template sensor on reboot. I have a sensor that updates a few times a week and would like the status not to go unknown after reboot

#
- trigger:
    - platform: state
      entity_id:
        - sensor.impedenza_francesco_raw
    sensor:
      - name: Impedenza Francesco
        unique_id: impedenza_francesco
        unit_of_measurement: 'ohm'
        state_class: measurement
        icon: mdi:omega
        state: |
          {% if states('sensor.impedenza_francesco_raw')|is_number %}
            {{ states('sensor.impedenza_francesco_raw') }}
          {% else %}
            {{ this.state }}
          {% endif %}
plain magnetBOT
#

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

marble jackal
#

Change your trigger to this, and just refer to {{ trigger.to_state.state }} in the state template

- trigger:
    - platform: state
      entity_id: sensor.impedenza_francesco_raw
      not_to:
        - unavailable
        - unknown
mossy flax
marble jackal
#

Your are missing the quotes at the end

#

But besides that, yes

mossy flax
#

what does to_state mean? Where can I find documentation on this?

inner mesa
#

Third link in the topic

mossy flax
#

why is the previous value not loaded?

marble jackal
#

You can do that from developer tools > YAML

#

Anyway, I guess it needs to be triggered again because the configuration changed

mossy flax
#

I'm doing some tests, now it seems to work. I think the problem was that I set the value through "set state" to try, but it seems that through this function the value is not saved in the db and when I restarted it gave me this problem. anyway, it looks ok

floral shuttle
halcyon fulcrum
# inner mesa Otherwise, need more details on what 'pick' means and what you've tried

I've created these kind of template binary sensors and I would like to gather all the rooms together which needs cleaning. In other words the binary sensors which are true. I also would need to extract the room_id's from the attributes of the binary sensors to get my vacuum robot to understand which rooms are to be cleaned during that day.

  - binary_sensor:
    - name: "Living Room Cleaning"
      state: "{{this.attributes.cleaning_need}}"
      attributes:
        room_id: "15"
        timestamp: "{{1677059173.283542}}"
        days_since: >
          {% set today = now().date() %}
          {% set last_cleaned = this.attributes.timestamp %}
          {% set days_since = (today - as_datetime(last_cleaned).date()).days %}
          {{ days_since }}
        cleaning_need: >
          {{this.attributes.days_since >= 3}}```
inner mesa
#

alright, so what I gave you should help

halcyon fulcrum
# inner mesa alright, so what I gave you should help

I'm getting an error with that at the moment

{{states('binary_sensor.living_room_cleaning') | selectattr('state', 'eq', 'on') | map(attribute='attributes.room_id') }}
<generator object sync_do_map at 0x7f3ee7e23bc0>
#

well, I guess it is not an error but something else

inner mesa
#

you started with a state, which is a string

#

I thought you might be further along that that

#

{{states.binary_sensor | selectattr('state', 'eq', 'on') | selectattr('attributes.room_id', 'defined')|map(attribute='attributes.room_id')|list }}

halcyon fulcrum
#

ah now I got it, thanks! Any tips how to get this filtering working only with specified sensors? Now it seems to collect every binary sensor it finds.

inner mesa
#

only ones with a 'room_id' attribute

#

but yes: {{expand(['binary_sensor.xxx', 'binary_sensor.yyy']) | selectattr('state', 'eq', 'on') | selectattr('attributes.room_id', 'defined')|map(attribute='attributes.room_id')|list }}

halcyon fulcrum
halcyon fulcrum
languid onyx
#

I'm having trouble with a template.
This works:
{{ states.sensor.wabash_river_level_data.attributes["site"]["observed"]["datum"][0]["primary"]["#text"]}}
but documentation suggests NOT using states (and it doesn't seem to work in a sensor template in my configuration.yaml)
This doesn't:
{{state_attr('sensor.wabash_river_level_data','site').observed.datum.0.primary.#text}}
Not sure how to deal with the special character #.
Anyone have ideas on what I'm doing wrong?

inner mesa
#

you still need to use the ["#text"] format for that part

#

{{ state_attr('sensor.wabash_river_level_data','site').observed.datum.0.primary["#text"] }}

#

or you can just use [xxx] for all of them after the state_attr() call

tribal cedar
#

TheFes was helping me yesterday to avoid a template loop but I can't seem to find a way to stop it. I have one binary sensor that needs to find binary sensors that match certain attributes. The fact that it loops or filters on states.binary_sensor seems to result in HA reporting it as a template loop. Is there some magic way out of this?

This is not my full template but it gives the jist of the fact that if I mention states.binary_sensor at all, its a loop. Can literally the word states.binary_sensor not be mentioned?

{{ states.binary_sensor | selectattr('entity_id', 'search', 'motion_triggered_now_in') | list | count }}

languid onyx
crystal idol
#

I'm on the beta, so maybe shouldn't ask here, but the openAI integration has a custom template now, and I tried it in the template section of dev tools, but it is giving me an error that 'areas' isn't defined.. anyone have a quick fix?

languid onyx
# inner mesa you still need to use the ["#text"] format for that part

Well I may have spoken too soon. Works in the Developer Tools yaml window, but when I plug it into a sensor, I get an error.

  • sensor:
    • name: "WBRL"
      state: "{{state_attr('sensor.wabash_river_level_data','site')["observed"]["datum"][0]["primary"]["#text"] | float }}"
      state_class: measurement
      unit_of_measurement: ft
      I get the error :
      bad indentation of a mapping entry (175:72)
      174 | ...
      175 | ... sh_river_level_data','site')["observed"]["datum"][0]["primary ...
      ------------------------------------------^
      So I'm still missing something!
crystal idol
#

Looks like maybe it just wants you to tab your long line in the same as the one above it? 🤷 Not sure though!

buoyant pine
#

Really need to see the YAML formatted as code

plain magnetBOT
#

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

languid onyx
#

And wabash_river_level_data is from above the template

# Wabash River Level      
  - platform: rest
    name: Wabash River Level Data
    resource: https://water.weather.gov/ahps2/hydrograph_to_xml.php?gage=lafi3&output=xml
    value_template: "{{ now() }}"
    json_attributes:
      - site
      - observed
      - forecast
obtuse zephyr
#

Use ' instead of " in your indexing within the state template

languid onyx
plain magnetBOT
#

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

formal ember
#

Whats the go to method do group all entities of a particular type now? I know it got changed a while back. I am using the below in an automation, however just want to have a simple on off switch on a dashboard and not sure how to go about it.

service: light.turn_off
target:
  entity_id: >-
    {{ states.light | map(attribute='entity_id') | reject('eq',
    'light.wled_christmas_tree_master') | list }}
plain magnetBOT
#

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

tulip kindle
#

sorry for bad post above.
how can I use hs_color in template for icon_color?

#
      {% if states('sensor.plug03_current') > '0.2' %} hs_color(161,98) {% else %}
      disabled {% endif %}```
dry cobalt
#

How would i make a template that checks if a state atribute contains anything at all?

I want a template that returns true if the attribute "manual_controll" contains anything at all

at first i thought i could use a lenght filter or something but that is not a valid filter.

I feel like im missing something super obvious

{{ state_attr('switch.adaptive_lighting_bad', 'manual_control') | contains (*) }}

i thought maybe a "wild card" would work but no 😦

inner mesa
#

Is it defined, but just blank? Or doesn't exist at all?

plain magnetBOT
#

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

dry cobalt
#

i am unsure what "defined" means in this context but im guessing this is "defined" ?

inner mesa
#

Why does |length > 0 not work?

#

Or is not none

dry cobalt
#

oh my god🤦‍♂️
i tried again, i must have made a typo or something when i tried it the first and second time..

Third times the charm

#

lenght worked

#

i appriciate the help ❤️

dry cobalt
#

~~Still working on the above template; it now prints out which entity that is in manual controll, like this

    {{ state_attr('switch.adaptive_lighting_bad', 'manual_control')[0] }}
{% else %}
    none
{% endif %}```

in this case the output is " light.bad "

can i make the " light.bad " clickable in some way?~~
#

actually i have a better idea, a conditional button to turn off manual controll that shows up if the template outputs anything 😄

edgy mural
#

Hey all, has anyone ever seen a template render properly in the template editor, but incorrectly in an automation?

#

I have this template

{% set requested = states("sensor.zone1_requested") == 'True' %}
{{ 'switch.turn_on' if requested else 'switch.turn_off' }}

But it's rendering switch.turn_on in the editor and switch.turn_off when part of an automation

marble jackal
#

You could probably simplify that to switch.turn_{{ 'on' if states('sensor.zone_1_requeated') | bool(False) else 'off' }}

inner mesa
#

My guess is that 'True' is being evaluated differently in each case for some reason.

floral steeple
#

hi all, is there a way to create a stateless toggle button (on-off) to a switch with on off states?

obtuse zephyr
#

You just want an input_button that will call the switch.toggle service?

floral steeple
obtuse zephyr
#

One possible way (probably not the best) is to check trigger.to_state.context.parent_id in a condition and if that's set, the state change was made by an automation.

floral steeple
#

oh, that is brilliant! that could work. what would the condition be equal to, not none or none?

   value_template: '{{ trigger.to_state.context.parent_id == none }}'
obtuse zephyr
#

You want it to be True when it's none

#

so, as you have it

#

(except w/ value_template not indented that far)

floral steeple
#

ah ha, ok let me try this, ok, I'll fix that indentation

grave solstice
obtuse zephyr
floral steeple
#

thank you very much @obtuse zephyr it worked perfectly with the condition you mentioned. I placed it as a global condition and although it does double fire at the same it time, it fails on the second time because the condition was not met.

grave solstice
#

Well i have configured a card it looks good... however i want to use the auto entities with that card so all my units will show up... i have come so far to understand i need to template that

pine musk
#

hey gang... Just finished my streaming audio media_player build, and want to build a templated media_player around it, that can keep state, and resume playing after TTS

#

is this the right place to ask?

marble jackal
#

You can probably achieve what you want with auto-entities, but that is a #frontend-archived thing

grave solstice
#

I have another issue....

I got a Template Sensor with an attribute. I want to update that attribute from a script.... but in script i hace target and there asfaik i can only choose a entity_id....

marble jackal
#

There are no service calls to update sensors
Your only option is to create a trigger based template sensor and trigger on an event sent in the script

bronze stag
#

Hey can someone help me with the current Template? The rounding is not working 😭

#
template:
  - sensor:
      - name: "Füllstand (Volumen)"
        unique_id: "ZisterneVolume"
        unit_of_measurement: "L"
        state: >
          {% set volume = states('input_number.zisterne_volumen') | float %}
          {% set height = states('input_number.zisterne_hohe') | float %}
          {% set level = states('sensor.zisterne_ultraschallsensor') | float %}

          {{ ((volume / height) * level | round(2)) }}```
#

I getting Values like 4.681,81818181818

grave solstice
marble jackal
#

Use parenthesis

bronze stag
#

Oh i understand

#

{{ (((volume / height) * level) | round(2)) }}

#

Thanks mate

marble jackal
marble jackal
grave solstice
#

So what your take ... I have a input _text value which a user can set an rttl tone.... I have a sensor.door with attribute ringtone...

#

Any smart ideas for me to proceed?

marble jackal
#

I have no clue what you want to achieve here. That sensor.door is a template sensor? What is the YAML code for the sensor

strange fjord
#

can i take week day in templates ?

inner mesa
#

See the links in the channel topic

#

Second one

plain magnetBOT
#

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

grave solstice
#

Thanks a lot!!!

marble jackal
#

Wait, do you want that attribute to match the input text?

strange fjord
#

i'm done 😄

spice oar
#

I've been looking around but am having trouble finding any good leads. I have a IR fan that receiving commands from a broadlink RM4, that part it working around 95%, and it's just missing a few commands here and there. My thinking was that I also have a energy meter on the fan, which gives me info on wattage i.e. fan level. Is there a way to combine the output from the power meter and the fan entity itself?

spice oar
spice oar
#

Is it as simple as adding the template sensor into the percentage template instead?

willow belfry
#

Is it possible to transform the output of a Template Sensor in such a way that a unique numeric value can be passed based on the state of the attribute? For example, the Template below will return heating, idle, and cooling. I'd like to transform those attributes to something like 2, 1, and 0.

      - name: "HVAC Status"
        state: "{{ state_attr('climate.home_thermostat','hvac_action') }}"```
marble jackal
#
  - sensor:
      - name: "HVAC Status"
        state: >
          {% set mapping = { 'heating': 2, 'idle': 1, 'cooling': 0 } %}
          {{ mapping[state_attr('climate.home_thermostat','hvac_action')] }}
willow belfry
#

Wow

#

That's amazing, thank you!

spice oar
#

So far I ve been able to create a

floral shuttle
#

archhh... dont see it. I have 8 sensors with a state indicating the days left to an event. I want to template the next upcoming event (count days is lowest) , and then show the name. started with: {{states.sensor|selectattr('entity_id','search','verjaardag')|map(attribute='state')|list}} which gives me this list ['57', '114', '359', '182', '49', '80'] so doesnt even sort on the number, but still on the names. even with sort: {{states.sensor|selectattr('entity_id','search','verjaardag')|map(attribute='state')|list|sort}} returning ['114', '182', '359', '49', '57', '80']

#

now, that is not the most important thing here, I first need a template to find the lowest number, and then show the name

#
``` returns 114....
obtuse zephyr
#

You'll need to add a | map('int') prior to | min otherwise you're sorting strings

floral shuttle
#

a yes, that helps..{{states.sensor|selectattr('entity_id','search','verjaardag')|map(attribute='state')| map('int')|min}} results in 49, and ```{{states.sensor|selectattr('entity_id','search','verjaardag')|map(attribute='state')| map('int')|sort}}

thorny snow
#

How can I extract the total amount of minutes from a timestamp? The following template gives me the minutes in the hour (so the full time would be 5 hours and 24 minutes, and this template gives me just "24" as result instead of (5*60)+24 minutes=324. How can I get 324 as a result from this?

{{ (as_timestamp(state_attr('sun.sun', 'next_dawn')) - as_timestamp(now())) | timestamp_custom('%M') }}

devout cedar
#

Hi all, I would like to create a sensor template to sum all my MQTT sensor.*_energy entities. Note I also have sensor.solaredge_*_energy from the SolarEdge integration which I don't want in there. I only want the sensors from my MQTT integration. Is there a way to accomplish this?

thorny snow
marble jackal
#
{% set lowest = states.sensor|selectattr('entity_id','search','verjaardag')|map(attribute='state')| map('int')|sort|first %}
{{states.sensor|selectattr('entity_id','search','verjaardag')|selectattr('state', 'eq', lowest|string)| map(attribute='entity_id')|join}}
floral shuttle
#

ofc, that must be it. Shows empty though (and I cant find a typo....):

devout cedar
#

Holy shit! I didn't know there was an editor like that 🙂

floral shuttle
#
 |selectattr('state', 'eq', '49')| map(attribute='entity_id')|join}}
``` works though
#

so its not wanting a number but a string...

marble jackal
#

I've added the filter

floral shuttle
#

Entity_id: {{states.sensor|selectattr('entity_id','search','verjaardag') |selectattr('state', 'eq', lowest|string)| map(attribute='entity_id')|join}}

#

check!

devout cedar
#

or maybe it is possible to have the value actually saved to be an integer? Seems logical

#

And then you don't need to mess around with it everywhere you want to use it

marble jackal
#

States are always strings

#

Attribute values can be integers

floral shuttle
#

I was planning on adding it to a small markdown card:``` - type: markdown
content: >
## Volgende event:
{% set lowest = states.sensor|selectattr('entity_id','search','verjaardag')
|map(attribute='state')| map('int')|sort|first %}
{{states.sensor|selectattr('entity_id','search','verjaardag')
|selectattr('state', 'eq', lowest|string)| map(attribute='name')|join}}
{{states.sensor|selectattr('entity_id','search','verjaardag')
|selectattr('state', 'eq', lowest|string)| map(attribute='state')|join}} dagen

#

figured to set states.sensor|selectattr('entity_id','search','verjaardag') apart in a var, but it wont be merged correctly in he other templates

marble jackal
#
{% set events = states.sensor|selectattr('entity_id','search','verjaardag')|list %}
{% set lowest = events|map(attribute='state')| map('int')|sort|first %}
{{events|selectattr('state', 'eq', lowest|string)| map(attribute='entity_id')|join}}
#

That should work

obtuse zephyr
#

and lowest will have your number of days, you don't have to refetch that

devout cedar
#

quick fix

floral shuttle
#

having this now:```
{% set lowest = states.sensor|selectattr('entity_id','search','verjaardag')
|map(attribute='state')| map('int')|sort|first %}
{% set events = states.sensor|selectattr('entity_id','search','verjaardag')|selectattr('state', 'eq', lowest|string)|list %}

Volgende event:
{{events| map(attribute='name')|join}}
{{events| map(attribute='state')|join}} dagen

#

I think this does it:```
{% set verjaardag = states.sensor|selectattr('entity_id','search','verjaardag')|list %}

{% set lowest = verjaardag
|map(attribute='state')| map('int')|sort|first %}

{% set events = verjaardag
|selectattr('state', 'eq', lowest|string)|list %}

Volgende event:
{{events| map(attribute='name')|join}}
{{events| map(attribute='state')|join}} dagen

marble jackal
#

I think this does it:```
{% set verjaardag = states.sensor|selectattr('entity_id','search','verjaardag')|list %}

{% set lowest = verjaardag
|map(attribute='state')| map('int')|sort|first %}

{% set event = verjaardag
|selectattr('state', 'eq', lowest|string)|list|first %}

Volgende event:
{{event.name}}
{{event.state}} dagen

floral shuttle
#

better vars:```
{% set events = states.sensor|selectattr('entity_id','search','verjaardag')|list %}

{% set first = events
|map(attribute='state')| map('int')|sort|first %}

{% set event = events
|selectattr('state', 'eq', first|string)|list %}

Next event:
{{event| map(attribute='name')|join}}
{{event| map(attribute='state')|join}} days```

lone birch
#

this might be a silly question. I defined a template sensor that performed some calculation based on other sensors, but when I first defined it I made a mistake and instead of a number I was generating a string containing a number. I've since then fixed it but the history graphs shows as a multicolored bar instead of as a chart, probably because it contained strings at some point. How can I fix it? Maybe by erasing the history?

floral shuttle
#

nice!! this does it indeed:```
{% set events = states.sensor|selectattr('entity_id','search','verjaardag')|list %}

{% set first = events
|map(attribute='state')| map('int')|sort|first %}

{% set event = events
|selectattr('state', 'eq', first|string)|list|first %}

Next event:
{{event.name}} {{event.state}} days
``` didnt have the |first on the set event variable, so it errored at first... very nice indeed!

winter haven
#

How can I get the start time from a calendar entry? I want to check if the start time is a specific hour of a day. It seems the best way is to use templates?

lofty mason
winter haven
tulip kindle
#

I want a color shifting icon for my template card. Is it possible to set icon-color in a template, to HS color value i.e.(hhh.hhh, sss.sss)?

#

(my device is a cheapo zigbee light strip for my tv backlight that returns HS color format via state_attr('light.lightstrip_tv_level_light_color_on_off','hs_color')

maiden magnet
#

Hey, how can I create a template sensor that filters out everything except "01:00" from this issue "2023-02-27T07:08:02.506396+01:00"

edgy mural
#

Hey all, I'm having trouble figuring out what's going on with this template.

{% set sleeping = states('sensor.sleeping') %}
{{ sleeping }} # false, type boolean
{% set sleeping = states('sensor.sleeping') %}
{{ sleeping }} # False
{{ "yes" if sleeping else "no" }} # yes
#

It's like the type of sleeping is changing from boolean to string and the first letter is being capitalized depending on what the next line is

inner mesa
#

states are always strings

edgy mural
#

why does it report as a boolean in the first example?

inner mesa
#

it doesn't

#

it's just a string

#

always

#

if you want it to be evaluated as a boolean, you can do {{ bool(sleeping) }}

edgy mural
#

I can't paste a screenshot here but Home Assistant template editor is clearly stating that it's Result type: boolean which I just took as being correct

inner mesa
#

that doesn't matter - it reevaluates it for you there

#

ignore that

edgy mural
#

do we know what values evaluate to true or false for the bool() function?

inner mesa
#

yes, it's described in the docs

#

a large paragraph

edgy mural
#

speaking of which, what's the best way to search the docs?

inner mesa
#

I use Google

#

home asssistant whatever

compact charm
#

how do i format a datetime string attribute (e.g. "2023-02-01 00:00:00-05:00") in a lovelace template? Looking to say something like "Feb 01, 2023" ideally

edgy mural
#

When I use bool in my template, it says bool is undefined

{% set sleeping = bool(states('sensor.sleeping')) %}
inner mesa
#

{{ ("2023-02-01 00:00:00-05:00"|as_datetime).strftime("%b") }} gives "Feb". Format as desired based on the link

compact charm
#

thanks!

inner mesa
#

{% set sleeping = bool('true') %} works fine for me

edgy mural
#

That's probably true, I pin the version and upgrade rarely

#

I appreciate the help!

inner mesa
#

you'll need to break that habit if you plan to use the documentation

edgy mural
#

yeah, it looks like the documentation isn't versioned

inner mesa
#

it always represents the latest version

compact charm
inner mesa
#

remove "|as_datetime"

compact charm
#

ok, now i'm getting UndefinedError: 'None' has no attribute 'strftime'

inner mesa
#

that doesn't make sense

#

what are you using now?

compact charm
#
{% for item in integration_entities('anniversaries') %}
  {{ state_attr(item, "next_date").strftime("%b") }}
{%- endfor %}
#

if i remove .strftime("%b"), i get the correct strings

inner mesa
#

remove the .strftime() call and see what it prints

#

ok

compact charm
#

oh, wait. i think there is a None entity in the results

inner mesa
#

seems like you're getting a "None" in there

compact charm
#

i need an if check

#

the integration includes a calendar entity, not all sensors

#

so, i need to filter that out

#

that was it. thank you again!

marble jackal
#

That's new in 5.0. messed up my template as well

inner mesa
#

if you want to change brightness_pct, start with brightness_pct

rose scroll
#

"{{ state_attr('light.bedroom_dimmer', 'brightness_pct') + 10 }}"

#

Pop that in Dev Tools > Templates to test. That page will also indicate what type of data is outputted by the template.

inner mesa
#

That can't be the result of putting that in the template dev tool

rose scroll
#

Is your light currently on?

inner mesa
#

how can I examine the attributes to understand what they even are?
devtools -> States

rose scroll
#

So...your light doesn't have a brightness_pct attribute? Check in Dev Tools > States.

#

Is this a Switch as X entity?

#

I doubt that will work if brightness_pct isn't provided by the entity.

#

Try it. But then again, if it provides brightness, why not just use that?

#

So...does your light provide the brightness attribute?

#

I'm gonna guess that if brightness_pct doesn't exist, then neither does brightness.

blazing cradle
#

Hey I’m trying to get a sun rise entity to return “10:00” instead of “1 hour ago”. What am I doing wrong? https://dpaste.org/95wmo

inner mesa
#

You can't use templates in a device action

#

use "call service" instead, and just stop using device actions

inner mesa
#

light.turn_on

plain magnetBOT
floral steeple
#

Hi, so is it

      - "unknown" 
      - "unavailable"

Or

not_from:
      - unknown
      - unavailable

Does it matter? Thanks

maiden magnet
marble jackal
maiden magnet
#

oh ok, thats nice

maiden magnet
floral steeple
#
  - platform: state
    entity_id:
      - button.esphome_web_a85214_dyson_humidifier_power_on_off
    id: Dyson Humidifier Changed
    not_from:
      - unknown
      - unavailable
#

When it goes unavailable and comes back, it triggers.

#

Should the not_from take care of this?

#

Wonder if I should use a global condition in the automation, just after the triggers :

  - condition: template
    value_template: "{{ trigger.from_state.state not in ['unknown', 'unavailable'] }}"
inner mesa
#

Both should do the same

floral steeple
#

Interesting I just realized that if a button is stateless, this is checking the state. I'll have to try the global condition cause it's triggering from unavailable using not_from 😀

thorny snow
plucky depot
#

I want to create two helper toggles that should show a random value from a static list but never the same value. Can anyone explain how to do this ?

marble jackal
open hound
#

😐 󠀀󠀀

marble jackal
#

But the state of a button is de last time it was pressed

marble jackal
open hound
#

Can a state sent from a trigger automation (using events), be given a template value?

#
state:"{{state_attr('calendar.school','message')}}"
#

Is that valid?

marble jackal
#

Sorry, it's not clear to me what you are trying to do

open hound
#

I am trying to set a trigger template by using an automation.

#

Essentially, I want the state of a sensor to be the name of the calendar event.

marble jackal
#

then use a template trigger

#
platform: template
value_template: "{{ states('sensor.your_sensor') == state_attr('calendar.school','message') }}"
#

or

platform: template
value_template: "{{ is_state('sensor.your_sensor', state_attr('calendar.school','message')) }}"
open hound
#

My issue is an issue that kind of affects both automations, and templates. I created a template trigger. (within templates.yaml) and am planning on update the sensor values by using an automation (so that I have more control over the frequency at which it updates).

#

So, within an automation, I am firing a custom event that will update the value of the template sensor with event data.

marble jackal
#

You mean you created a trigger based template sensor right?

open hound
#

Yes.

marble jackal
#

okay, you can use templates when firing an event

open hound
#

I wanted to pass the value of another sensor to the state of this sensor.

plain magnetBOT
#

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

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

open hound
#

I wanted the state of this sensor to equal the value of the message attribute from calendar.

marble jackal
#

It's probably helpful if you post the template sensor and the event you ar using

marble jackal
#

Well seems you overcomplicated it a bit, but this will work with the following even fired from your automation/script

event: set_schooleventsched
event_data:
  state: "{{state_attr('calendar.school','message')}}"
  attributes:
    state: "{{ 'something' }}"

That will set the sensor state to the message and all the attributes of the sensor to something

#

you also need to provide all data with every update now, as you didn't build in any failsafe for missing data

open hound
#

The main issue is... I have very specific criteria for when I want this to be updated. 😐

#

I do have a separate template sensor that correctly gets the correct times, etc...

#

However, it triggers every single minute.

#

And being that I have automations that activate whenever the state changes.... those automations fire way too frequently.

marble jackal
#

I would change the template sensor to this:

- trigger:
    - platform: event
      event_type: set_schooleventsched
  sensor:
    - name: SchoolTimes
      state: "{{ trigger.event.data.message if trigger.event.data.message is defined else this.get('state', 'unknown') }}"
      attributes:
        school_date: "{{ trigger.event.data.school_date if trigger.event.school_date is defined else this.attributes.get('school_date', 'unknown') }}"
        school_start: "{{ trigger.event.data.school_start if trigger.event.school_start is defined else this.attributes.get('school_start', 'unknown') }}"
        school_end: "{{ trigger.event.data.school_end if trigger.event.school_end is defined else this.attributes.get('school_end', 'unknown') }}"
        wait_for_bus_before: "{{ trigger.event.data.wait_for_bus_before if trigger.event.wait_for_bus_before is defined else this.attributes.get('wait_for_bus_before', 'unknown') }}"
        wait_for_bus_after: "{{ trigger.event.data.wait_for_bus_after if trigger.event.wait_for_bus_after is defined else this.attributes.get('wait_for_bus_after', 'unknown') }}"
#

Then you can use the following event:

event: set_schooleventsched
event_data:
  message: "{{ state_attr('calendar.school','message') }}"
  school_date: '01-01-2023'
  school_start: '10:30'
  school_end: '12:30'
  wait_for_bus_before: '10:00'
  wait_for_bus_after: '10:45'
open hound
#

Hmmm 🤔

marble jackal
#

if you leave out one of the parts of the event, it will retain the current value (unless there is no current value, in that case it will use unknown)

open hound
#

Retaining is good... 🤔

#

My main issue(s) are...

#
  1. As soon as the calendar event starts... all of my times change. (As it goes on to the next event in the calendar, instead of seeing the current event through (and beyond) its completion.
#

And with my son, school times aren't static. 😐

#

He's in a special ed program.

#

So, having them remain dynamic is important.

#

And...

#
  1. I don't want the automations that use the sensor to be triggered, every single minute when the sensor updates (as a sensor updates counts as a sensor change. 😐
marble jackal
#

You can send the event any time you want

open hound
#

My old method was just using a template sensor.

#

(Which was less complicated)

#

But wreaked havoc on my automations. 😐

#

Because every single minute, they'd rapidly switch to unknown, and then switch to the correct value, which would cause my automations that used a state changed event to count that as a state change, and refire the automations (which involve sending messages to my speakers).

#

Hmmm 🤔

#

Is there a way to do this type of thing without having to resort to trigger based template sensor?

#

So that if the template already has a value, do nothing and leave it alone?

#

I wouldn't mind it running the check every single minute, as long as the state changed events do not register a state change because the value did not change.

marble jackal
#

What if the value needs to be updated?

open hound
#

Well, I'd want the template sensor to use conditions to retain the current value (if no change is needed) and to change the value if the value needs to be updated. 😐

#

So, essentially... it'd have to compare to the current value of the sensor (recursively), and if the new value equals the old value, do nothing... otherwise, update it to the new value.

#

🤔 󠀀󠀀

#

Is it possible to do a recursive comparison like that?

#

Using a 'this'?

marble jackal
#

I don't think there is a lot of difference in resource usage to check in the conditions if the new values are different compared to the old ones, or to just send the event and update the sensor

open hound
#

Well... as it was stated... I "over-complicated" it. So, I was wondering if there was a less complicated way of doing it. 🤔

#

Ideally, I would like this sensor to set its times, once a day...

#

(Usually, at midnight... BUT be able to set its times in the event there are no times set (due to power outage, etc).

#

Hence the automation to check every hour, and then only update the value in the sensor if there isn't a valid value within the sensor.

marble jackal
#

you could do that with the sensor above

open hound
#

Excellent.

marble jackal
#

do one update at midnight, and check hourly on false values and update it if needed

open hound
#

And your suggested modifications make what change?

#

The automation will include all of the attributes, which will all change at the same time.

#

My automation wasn't quite finished yet.

#

I just wanted to make sure I had the syntax correct. 🙂

marble jackal
#

you were overcomplicating things with the attributes in the event

#

and also the usage of state instead of what the actual event data was

#

If you always send all the data, you don't really need the check if it's defined

open hound
#

Ah, I see what you are saying.

#

I just figured, since the state of that sensor was going to be the title of the calendar entry....

#

That I would just call it "state"

marble jackal
#

okay, but you were also using attributes.state

#

there is no need to use another attributes level in the event data

open hound
#
action:
  - event: set_schooleventsched
    event_data:
      state: "{{state_attr('calendar.school','message')}}"
#

I haven't gotten that far yet. 😐

#

But

#

It is good to know that I don't need to include the attribute in there.

#

Cause I really wasn't sure how the syntax of that was going to go. 😐

#

So, you actually answered my next question. 🙂

#

So, thank you for that.

marble jackal
#

the point is that the trigger based template sensor will fail on the attributes if you don't provide all data

plucky depot
#

I want to create two helper toggles that should show a random value from a static list but never the same value. Can anyone explain how to do this ?

marble jackal
#

A toggle is on or off, it doesn't show a value

plucky depot
#

Sorry I meant the name of the toggle. Like "Clean <roomname_from _list> 0|1"

marble jackal
#

you can't template the name of a input_boolean/toggle helper

#
switch:
  - platform: template
    switches:
      test_switch_1:
        unique_id: 0086e6b1-265a-4cb4-b345-f2fc490cf90b
        friendly_name: "{{ [ 'option 1', 'option 2', 'option 3', 'option 4'] | reject('eq', states.switch.test_switch_2.name | default) | list | random }}"
        value_template: "{{ states('input_boolean.test_1') }}"
        turn_on: &toggle1
          - service: input_boolean.toggle
            target:
              entity_id: input_boolean.test_1
        turn_off: *toggle1
      test_switch_2:
        unique_id: 52789344-d995-4294-8c03-4c472f7151df
        friendly_name: "{{ [ 'option 1', 'option 2', 'option 3', 'option 4'] | reject('eq', states.switch.test_switch_2.name | default) | list | random }}"
        value_template: "{{ states('input_boolean.test_2') }}"
        turn_on: &toggle2
          - service: input_boolean.toggle
            target:
              entity_id: input_boolean.test_2
        turn_off: *toggle1
#

@plucky depot you could do something like this, which creates two swich entities with the templates used for the name. They are connected to two input_booleans

plucky depot
#

@marble jackal Thanks!, I will try that.

open hound
#

😐 󠀀󠀀

#

My changes keep reverting to a non-working version now.

#

On the automation side of it.

#

It keeps tacking in an "attributes: null" into my event data.

#

It refuses to save.

#

Not sure what is going on now. 😐

marble jackal
open hound
#

Change them to single?

marble jackal
#

one of those yes

#

I guess you normally use double quotes inside, and single outside

#

I do the opposite

open hound
#

So, in the automation when I am passing the data, use single quotes there?

#

Or within the actual template.yaml file?

marble jackal
#

"{{'double quotes outside, single quotes inside' }}" or '{{ "single quotes outside, double quotes inside" }}'

#

NOT "{{ "double quotes outside, double quotes inside" }}" like you are doing now

open hound
#

Oh... in regards to the timestamps ....

#

Ok.

marble jackal
#

you are actually mixing it

#

If you use the multi line notation you can do that (although I would still advice against it)

#
some_key: >
  {{ 'this' + "that" }}
open hound
#

My confusion there was that in the documentation, I have always only seen double quotes used within those timestamps for the filters. 😐

#

So, I just figured it was the way it always had to be.

marble jackal
#

both can be used

#

"{{ "double quotes outside, double quotes inside" }}" this breaks it into 3 part
Part 1: "{{ "
Part 2: double quotes outside, double quotes inside
Part 3: " }}"

open hound
#

Makes sense...

plucky depot
#

@marble jackal sorry for all the questions but how do I make the template-switch names update once a week ? Do I need to create some automation or can I add a trigger somehow in the template ?

marble jackal
#

Do you need them to be static the rest of the week? Because the templates will be rendered again on each reboot

plucky depot
#

yes that's correct. I was planning to have template for my kids chores so that they get assigned a room to clean each week 🙂

marble jackal
#

Create 2 trigger based template sensors which update each Monday (or another day of choice) and select the new chore

#

refer to those for the switch name

#
template:
  - trigger:
      - platform: template
        value_template: "{{ now().weekday() == 0 }}"
      - platform: event
        event_type: new_random_chores
    sensor:
      - unique_id: e891d4d0-ad9f-4c5f-9ed6-873622c58756
        name: Chore Kid 1
        state: "{{ [ 'option 1', 'option 2', 'option 3', 'option 4'] | reject('in', [states('sensor.chore_kid_2'), this.get('state')] | list | random }}"
      - unique_id: 316d2eba-fcc2-4def-b6e5-86eaa847c0b7
        name: Chore Kid 2
        state: "{{ [ 'option 1', 'option 2', 'option 3', 'option 4'] | reject('in', [states('sensor.chore_kid_1'), this.get('state')] | list | random }}"
#

so set an initial state (or select new chores if you need) go to developer tools > event and send an event with type new_random_chores

plain magnetBOT
marble jackal
#

and then the change the templates for the switches to friendly_name: "{{ states('sensor.chore_kid_1') }}"

plucky depot
#

Thanks for all the help @marble jackal 🙂

marble jackal
#

you could even reject the chore from last week if you want

#

so they don't get the same chore twice in a row

plucky depot
#

Ok, great

marble jackal
#

I've added it in the code above

#

You could also put the chores in a select helper

#

so you can easily add chores from the GUI

#

replace [ 'option 1', 'option 2', 'option 3', 'option 4'] with state_attr('input_select.chore_list', 'options') then

open hound
#

Got it working now. Thanks @marble jackal

thorny snow
#

I have succesfully extracted the hours from an attribute and converted to string for as_timestamp. However, it's giving me an error. This is working:

{% set tijdstipopkomst = (as_timestamp(t) |timestamp_custom('%H:%M')) %}
{% set time = "07:00" %}
{{ (((as_timestamp(strptime(time, "%H:%M"))) - as_timestamp( strptime( now().strftime("%H:%M"), "%H:%M") )) /3600) | float}}```
#

However, I would like to use {{ tijdstipopkomst }} as value for time. This results in ValueError: Template error: strptime got invalid input '{{ tijdstipopkomst }}'

#

Goal: To get the amount of hours in decimal since sunrise to use in a dynamically updating graph.

marble jackal
#

what are you trying to calculate here

#

and why are you coverting now() which is a datetime, to a string representation of the time, then back to a timestamp?

thorny snow
#

The hours since sunrise, in a decimal form (so 7 and a half hours shows up as 7.5 instead of 07:30). I can then use this in Apexcharts to dynamically set the start of my graph each day.

marble jackal
#

do you want the number of hours until the next rising?

thorny snow
#

No, I'm using the next rising as a substitute for last rising (as they differ only a couple of minutes and there is no last rising)

marble jackal
#

ah okay

#

you are really overcomplicating this

thorny snow
thorny snow
marble jackal
#
{% set t = state_attr('sun.sun', 'next_rising') | as_datetime - timedelta(days=1) %}
{{ (now() - t).total_seconds() / 3600 }}
thorny snow
#

Oh wow that is indeed a lot easier. Thanks a lot for this!

foggy valve
#

Hi all, I have a siren in HomeAssistant that only reports a binary_sensor.siren_alarm. It seems impossible to trigger the actual siren, even tho I manually changes the alarm to true and the 'sensor' to on.. Do I need to template it to a switch? Thx in advance

keen hawk
#

Hey, I have a template that works in the dev-tools template testing but shows unknown when I look it up under entities

#

Its a sensor but it shows unknown

plain magnetBOT
#

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

inner mesa
#

You're not outputting anything in your 'if' path

marble jackal
#

this looks overly complicated

floral shuttle
#

wondering is it would considered a bug, when using toggle_lights_area: alias: Toggle lights area mode: restart icon: mdi:autorenew sequence: service: light.toggle data: entity_id: > {{area_entities('library')}} and the unavailable lights throw an error

#

would have hoped the area_entities() to take care of that

marble jackal
#

I can imagine this will throw errors because there are other entities besides light entities in your library

floral shuttle
#

sure, but the service selects only the lights to act upon

#

it only throws an error on 1 single unavailable light

marble jackal
#

does it? If I use light.toggle on a switch, I will get an error?

#

But why not just target the area?

floral shuttle
#

didnt think of that...

marble jackal
#
service: light.toggle
target:
  area_id: kitchen
floral shuttle
#

even shorter

marble jackal
#

well library

floral shuttle
#

somehow that wont go at all...hmm

#

via the UI that works. states the identical error though

#

the ambilights of my tv are unavailable, because the tv is off. the light is registered as entity though, but cant be toggled. same question: should that not be auto-ignored/rejected

marble jackal
#

@keen hawk can you try this?

      {% set input = state_attr('sensor.daily_energy_price', 'ee') | selectattr('timestamp',  '>', now().timestamp()) | list %}
      {%- set ns = namespace(cheapest_time=0, cheapest_price=999.00) -%}
      {%- for i in range(input | count - 2) -%}
        {% set price = input[i:i + 1] | map(attribute='price') | average %}
        {% if  price < ns.cheapest_price %}
          {% set ns.cheapest_price = price %}
          {% set ns.cheapest_time = evening_night[i].timestamp %}
        {% endif %}
      {%- endfor -%}
      {{ ns.cheapest_time | timestamp_custom('%Y-%m-%dT%H:00:00') }}
marble jackal
#

you can filter them out using a template

floral shuttle
#

yeah... I had that, but this would be so much more elegant

floral steeple
#

hmm, i just relized....I have have to put a not_to

#

its triggering from being available to not available

#

but not triggering from not_from

#

lol this is confusing

#

but I think that is the problem....not_to available, unknown

#

would this work?

    entity_id:
      - button.esphome_web_a85214_dyson_humidifier_power_on_off
    id: Dyson Humidifier Changed
    not_from:
      - unavailable
      - unknown
    not_to:
      - unavailable
      - unknown
marble jackal
#

yes, that should work

floral shuttle
cursive knoll
#

I have 10 pictures to Level how to make template for water?

plain magnetBOT
#

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

raw jay
#

anyone can help me?

grand quarry
#

That's not really related to templating. More of a networking issue

raw jay
#

why network?

#

other sensors from this host are working

#

only the switch is not

inner mesa
#

because of this:

No route to resource/endpoint
If the resource that it shows is correct, then it's not the template at fault

zealous flame
#

Is there a “friendly name” of a state you can call? So for a window sensor the state is on or off, but can you get it to display open or closed by calling on a specific attribute or something?

inner mesa
#

Nope

grave solstice
#
      - platform: event
        event_type: state_changed
        event_data:
          new_state:
            state: grafitti_road
    binary_sensor:
      - name: grafitti_road
        state: "on" ```
#

Is not trigegred by:

plain magnetBOT
#

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

grave solstice
#

What have i missed

marble jackal
grave solstice
#

my bad

#

since it was a template trigger i thought it could go here...

worn fox
#

Hello every1. im struggling with the template tile on wear os. can some1 help? i just want to show a sensor value and im getting template error. im typing this: <b>{{sensor.shelly_em_geral_channel_1_power}}</b>

#

looks like "sensor" is undefined

marble jackal
marble jackal
#

that's not the way to get the state of an entity

#

try <b>{{states('sensor.shelly_em_geral_channel_1_power')}}</b>

worn fox
#

i read the docs but it doesnt explain much. i was reading jinja2 docs now...

worn fox
marble jackal
worn fox
#

oh i was looking at the companion apps docs bcause when we click on the '?' icons thats what it opens. thanks. ill take a look

half pendant
#

Trying to setup a universal media player. But when overriding select_source with select_source: service: media_player.select_source target: > {% if state_attr('media_player.lg_c2', 'source') == 'Apple OTT' %} media_player.kontor {% else %} media_player.lg_c2 {% endif %} data: source: "{{ source }}"
I get the error dictionary update sequence element #0 has length 1; 2 is required

marble jackal
#

the template is fine, that's not causing this message

half pendant
#

Ok. Guess i have to troubleshoot some other way then.

marble jackal
#

does that field accept templates?

inner mesa
#

Everything under data: and target: do

marble jackal
#

yeah, I realized that a few seconds after I typed it

#

then something else grabbed my attention

cursive knoll
#

@marble jackal
I have 10 pictures to Level how to make template for water?

#

tank level

#

i need template only

marble jackal
#

cursive knoll
#

hello mr

zealous flame
mighty ledge
# marble jackal

I’m still on vaca but I have a few forum posts that calculate the volume of a cylinder on its side

thorny snow
#

hey there... i'm new here in discord and in HA-community... i have a problem with template-sensor i want to create... what is the best way to get supported?

lofty mason
#

Hi, welcome. You can just start by asking the question you need help with, and likely someone will be able to answer.

thorny snow
#

ok, can i also post code-snippets here ?

#

i want to have a entity, that will display one of 3 states (string) in my dashboard... it should display the state of an smart-plus-sensor, where i plug-in two chargers for e-scooter. the 3 states should be "charging", "standby" and "off".

lofty mason
#

In the channel description is recommended to use paste sites for sharing code blocks, though a short few lines here doesn't hurt.

thorny snow
#

ok...

#

whats a part out of my config.yaml... but this doesn't work fine... i dont understand it... first: is this way the best? should i use config.yaml or sensor.yaml ?

#

@gist: my state is always goes "boom" 😄

lofty mason
#

Before putting it into yaml, go to developer tools -> template and try there, it's much faster for iterating.

thorny snow
#

in dev-tool it works fine... i don't understand that

lofty mason
#

ok, well that's a good start

thorny snow
#

ahhh ok: state '0' != '0.0'

#

zero is NOT "zero.zero"

lofty mason
#

you should cast those states to float and compare

#

you probably don't want string compare for the greater/less than comparisons either

#

left a comment there

manic niche
#

Hello everyone. Would there be a reason why a service call works perfectly fine in the dev tools but the same code doesn't in a button in the lovelace UI? This is template related because the data sent is coming from input_select entities, with plain text both calls work fine.

thorny snow
#

@lofty mason you're right... it should be a compare of values

lofty mason
#

@manic niche are you sure the frontend card you're using supports template? most of the main cards do not support templates.

thorny snow
#

ohhh... i dont know

manic niche
#

calling a script instead works like a charm. Thank @lofty mason

thorny snow
#

is it possible to define the color for timeline-view in HA for each state?

#

now it's likly very "random" colors...

lofty mason
#

I think you need a state_class to be a valid statistic?

lusty echo
#

Ok i will try

#

ok now it seems to be working, thanks

floral shuttle
#

should we repeat the main - trigger key for each trigger? tried to add the sensors below it, but cant get it right, please have a look?

#

first figured we can move the sensor: block under the same tab as platform: state, as those are the defining trigger id's but that wont work

marble jackal
#

you should be able to define multiple sensor under one trigger

#
template:

  - trigger:

      - platform: state
        entity_id:
          - binary_sensor.porch_buiten_sensor_motion
          - binary_sensor.terrace_buiten_sensor_motion
          - binary_sensor.parking_trash_buiten_sensor_motion
        to: 'on'
    sensor:

      - unique_id: last_motion_outside_triggered
        name: Last motion outside triggered
        icon: mdi:motion-sensor
        state: >
          {{area_name(trigger.entity_id)}}
        attributes: &attributes
          history: >
            {{(this.attributes.history|default(['Not yet set']))[-8:] + [ this.state ]}}
          entity_id: >
            {{trigger.entity_id}}
          last_triggered: >
            {{trigger.to_state.last_changed.isoformat()}}

      - unique_id: last_motion_inside_triggered
        name: Last motion inside triggered
        icon: mdi:motion-sensor
        state: >
          {{area_name(trigger.entity_id)}}
        attributes: *attributes
floral shuttle
#

yes but this is not the case here, I need different sets of triggering entity_id's (have 4 of these )

#

its not consistent with any of the other integrations, requiring to repeat the top key for each individual set if triggers

marble jackal
#
template:
  - trigger: []
    sensor: []
  - sensor: []
  - number: []
#

this is how the list looks

#

you are now indenting the sensor part

#

which breaks it

#

the sensor is now defined in your trigger

#

which makes in impossible to define multiple triggers for one sensor

#
template:
  - trigger:
      - platform: state
      - platforme: event
    sensor: []
#

this sensor will update on both triggers

visual olive
#

Good morning everyone! Is there anyone around that is experienced with splitting the configuration.yaml file into other files?

marble jackal
#

Yes, but I don't see how that's related to the topic of this channel

visual olive
#

I need some help while setting Template sensors within multiple files 🙂

plain magnetBOT
#
The topic of this channel is:

Become a real Jinja2 Ninja! Don't worry my Genin, we are here to help! You can find general Jinja docs at https://jinja.palletsprojects.com/en/3.1.x/templates/, Home Assistant extensions at https://www.home-assistant.io/docs/configuration/templating/, and trigger variables at https://www.home-assistant.io/docs/automation/templating/

This channel is for support with Jinja templates. Some custom Lovelace cards support other types of templates, such as those written in JavaScript, and #frontend-archived is the right channel for that.

Please use http://pastie.org/, https://dpaste.org/, or https://paste.debian.net/ to share code or logs

marble jackal
visual olive
#

Fair enough! Thanks @marble jackal !

hallow pebble
#

Can I template an entity_id like this?
´´´

  • service: scene.turn_on
    entity_id: scene.kids_room_{{(states(''input_select.kids_scene_selector''}}
    ´´´
marble jackal
#

no

#

only if you put it under target or data

#
- service: scene.turn_on
  target:
    entity_id: scene.kidsroom{{ states('input_select.kids_scene_selector') }}
hallow pebble
#

Thanks 🙂

ember cloud
#

Hi there. Could someone please help with this. My Energy tarif is as follows: From 0 - 200 kWh price is 0.08, from 200 - 300 price is 0.09 and from 300 onwards price is 0.13. Need to write up a template for cost calculation. I've written the following template:

template:
  - sensor:
      - name: Energy Price
        unit_of_measurement: "AZN/kWh"
        state: | 
          {% if states('sensor.home_energy_meter')|float(0) <= 200 %}
            0.8
          {% elif states('sensor.home_energy_meter')|float(0) > 200 and states('sensor.home_energy_meter')|float(0) <=300  %}
            0.9
          {%- else -%}
            0.13
          {%- endif %}

Will this work correctly? For example say I used 500 kWh this month. How would this be calculated? Will it apply price 0.13 AZN for those extra 200 kWh used on top of 300 only?

#

I've run it through the templates and it seems to work alright. Just not 100% sure about the math part of energy calculation.

floral shuttle
# marble jackal this sensor will update on both triggers

right, I had not considered that indeed. by bad. sorry for that. So that does mean we have to create a - trigger key per set of triggers. ok. next challenge was a bit more complex. It turns out we can not use the this variable on a template trigger sensor last_changed? Ive been going back and forth to have the state of this sensor Not show a timestamp, but get the triggering entity And its timestamp in a set of historic attributes. The only reliable way seems to verbosely use the entity_id of the sensor itself:

#

before, I did this with the CC variable, but that was heavily reprimanded 😉 I also have an AD app doing this, but that is having some trouble if its own, so I figured why not build the trigger template to doing this

#

easiest would have been to set the time in the state (as the commented bit shows), but then the history graphs in more info run into space issues. Would be really nice if we could use this.attributes.last_triggered (it is a trigger template sensor after all) or at least this.last_changed (any entity has a last_changed, which is really what I am looking for here). no such thing, so I faked a last_triggered attribute, but even that I can not call using this.attributes.last_triggered

marble jackal
#

a sensor doesn't have a last_triggered attribute, so that only works for automations

#

I thought there is a trigger date in the trigger, but that doesn't seem to be the case

#

but I guess you could use trigger.to_state.last_changed

#

which you are already doing 🙂

#

BTW, why are the defaults for you history list items? While the standard history is a string

floral shuttle
#

yes, but that changes the time in the history panel to read the to_state, and not the sensor, so it gets all confused

floral shuttle
marble jackal
#

You could build the whole history dynamically as a list though

floral shuttle
#

o? that would be much better, can you give me a nudge please?

#

btw this is what I had before```
- unique_id: last_motion_sensor_triggered
name: Last motion sensor triggered
icon: mdi:motion-sensor
state: >
{{area_name(trigger.entity_id)}}

{{trigger.to_state.name.split(' sensor Motion')[0]}}

    attributes: &attributes
      history: >
        {{ (this.attributes.history | default(['Not yet set']))[-8:] + [ this.state ] }}
      entity_id: >
        {{trigger.entity_id}}
      last_triggered: >
        {{trigger.to_state.last_changed.isoformat()}}```
#

hence the list in the default

marble jackal
#
last_arrival:
  person: person.martijn
  at: '2023-02-28T22:02:22.734480+01:00'
last_departure:
  person: person.martijn
  at: '2023-02-28T22:02:07.693854+01:00'
arrival_history:
  - person: person.martijn
    at: '2023-02-28T22:02:02.738222+01:00'
  - person: person.marleen
    at: '2023-02-28T18:57:36.099214+01:00'
  - [ .. 8 more items here ]
departure_history:
  - person: person.martijn
    at: '2023-02-28T19:38:03.101676+01:00'
  - person: person.marleen
    at: '2023-02-28T18:34:10.960711+01:00'
  - [ .. 8 more items here ]
icon: mdi:home
friendly_name: Home person history
#

I'm not completely sure now why do not only have the history

#

trying to rebuild it now

#

updated version (also on GitHub)

friendly_name: Home person history
arrival_history:
  - who: Marleen
    at: '2023-03-01T13:23:22.764623+01:00'
  - who: Martijn
    at: '2023-03-01T13:22:32.859332+01:00'
  - [ .. 8 more items here ]
departure_history:
  - who: Marleen
    at: '2023-03-01T13:23:19.138472+01:00'
  - who: Martijn
    at: '2023-03-01T13:22:29.464805+01:00'
  - [ .. 8 more items here ]
icon: mdi:home
marble jackal
floral shuttle
#

no it does not work unfortunately. thing what is making this complex, is that the history_1 should log the correct time for that entity, and thus gets propagated through the other history items. but it really is the last_changed of the actual sensor, all other formats change the timing in the history_item 1 to something being the last changed of that item, and not the sensor

marble jackal
#

let me quickly try something

floral shuttle
#

so I am left with the only 100% correct template, the spelled out sensor entity_id

marble jackal
# floral shuttle so I am left with the only 100% correct template, the spelled out sensor entity_...
- trigger:
    - platform: state
      entity_id:
        - input_boolean.test
        - input_boolean.hide_header
      to: "on"
  sensor:
    - name: Last input boolean triggered
      unique_id: 563caa69-50be-4449-8aad-b56879913c4d
      state: "{{ states[trigger.entity_id].last_changed.strftime('%X') }}"
      icon: mdi:toggle-switch-variant
      attributes:
        history: >
          {%- set what = states[trigger.entity_id].name %}
          {%- set at = states[trigger.entity_id].last_changed.strftime('%X') %}
          {%- set previous = this.attributes.history | default([]) %}
          {%- set new = [dict(what = what, at = at)] %}
          {{ new + previous[:4] }}
icon: mdi:toggle-switch-variant
friendly_name: Last input boolean triggered
history:
  - what: hide_header
    at: '12:48:40'
  - what: test
    at: '12:48:25'
#

you can also use where = area_name(trigger.entity_id) if you rather have the area

floral shuttle
#

yes, I can see that working now, is cool. trying to format the layout to read Frontdoor: 14:01:20 and ditch the 'what' and 'at'

marble jackal
#

@floral shuttle just format the new like you want, i created a dict there, if you just want a string you can do that

#
{%- set where = area_name(trigger.entity_id) %}
{%- set at = as_local(states[trigger.entity_id].last_changed).strftime('%X') %}
{%- set previous = this.attributes.history | default([]) %}
{%- set new = [where ~ ': ' ~ at] %}
{{ new + previous[:4] }}
floral shuttle
#

you beat me to it, I was testing {%- set what = states[trigger.entity_id].name %} {%- set at = states[trigger.entity_id].last_changed.strftime('%X') %} {%- set previous = this.attributes.history | default([]) %} {%- set new = [what + ': ' + at] %} {{ new + previous[:4] }} and had to walk around the house.. 😉

marble jackal
#

looks similar 🙂

floral shuttle
#

it does show the ugly quotes though.

#

note there is also an hour issue.... bottom last_triggered is correct

marble jackal
#

ah, you need to use as_local

#

adjusted in my last version

#

don't think you can do anything about the quotes, it's a string

#

if you don't want those, you need to go back to your old version with the separate attributes.

floral shuttle
#

yeah that would maybe be easiest. there always a compromise. you version has the state as top history item, which I had before in my configs too, I then though, hey, the state is not history, so lets change that. which then lead me into the timing trouble on those triggers..

#

also, Since we are not allowed to 'safe' too much history in the state machine, I wonder what would be best: 1 bigger attribute like yours, or 5 smalles ones with a single item..

marble jackal
#

we are allowed to do anything with the attributes of our own template sensors

#

if you want to create entities in a core integration you are limited in what you can put in the attributes

#

but you can also sort them the other way round if you do {{ previous[-4:] + new }}

#

oh wait, you wanted to omit the state from the history

#

the issue there is that you don't know what triggered that last state change

#

the time is in this.state

#

so if you don't want to include it in the history, and you already have a separate attribute to store the last area or name or whatever, you can also do that

plain magnetBOT
#

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

marble jackal
#
template:
  - trigger:
      - platform: state
        entity_id:
          - binary_sensor.hallway_door
          - binary_sensor.garage_door
          - binary_sensor.garage_corridor_door
          - binary_sensor.front_door
          - binary_sensor.back_door
          - binary_sensor.corridor_door
          - binary_sensor.stookhok_door
        to: 'on'
    sensor:
      - unique_id: last_door_triggered
        name: Last Door triggered
        icon: mdi:motion-sensor
        state: "{{ states[trigger.entity_id].last_changed.strftime('%X') }}"
        attributes:
          history: >
            {%- set previous = this.attributes.history | default([]) %}
            {%- set new = [this.attributes.last_area | default('nowhere') + ': ' + this.state] %}
            {{ previous[-4:] + new }}
           last_area: >
            {{ area_name(trigger.entity_id) }}
floral shuttle
#

oops. sorry.

#

the advantage of that is that I can &anchor the attributes in other sensors below that (and not have to spell out the entity per sensor)

#

that last template is nice too, it turns it all around a bit. using the state for the timestamp. will consider that in an additional sensor probably. thanks!

marble jackal
#

as said, on the moment of the trigger, this.state will be the current state (so before the new state is rendered, so basically the previous state)

#

so you can use it to generate the history, if you don't want the last update in the state, and in the history as well

floral shuttle
#

have to carefully study this some more, because I was just editing the attributes last (previously history_1) to ```
last: >
{% set stamp = as_local(states[trigger.entity_id].last_changed).strftime('%X') %}
{% set id = state_attr(trigger.entity_id,'friendly_name').split(' door')[0] %}
{{ id + ': ' + stamp }}

heavy crown
#

Hi, is it possible to template a mqtt sensor?

#
mqtt:
  sensor:
    - name: myelectricaldata_year_2023
      icon: mdi:flash
      unit_of_measurement: 'kWh'
      state_topic: "myelectricaldata/consumption/annual/2023/month/3"
#

I'd like to template 2023 and 3

rich quarry
#

any way to get the amount of entities in a device? like i have an intergration with a device and that device has 20 entities and sometimes more, how do i get that number?

floral shuttle
#
{{device_id('light.living')}}

{{device_entities(device_id('light.living'))|count}}```
rare furnace
#

Hello.

I am struggling with templates... Not sure what I'm doing to be fair atm. I have a temp.sensor showing lots of decimals to the value "5.08123841192373257681239" and I want to round it to show only 2 decimal places.
I have found a way how to round the number using this: {{ states('sensor.flexit_outdoor_air_temperature') | round(2)}}

But where do put this? I think I am supposed to enter it in a template in... configuration.yaml(?) not sure. And then how do I actually use it in the card on the dashboard?
I have tried alot of things but I cannot make sense of it. Thanks

rich quarry
#

iirc you can now use the UI to set the decimal places

#

go to the settings of the entity

rare furnace
#

Yeah ok. I cannot see a setting to set the decimal places

heavy crown
#

later today...2023.3

marble jackal
#

The problem with your template is that all states are strings

#

so you are trying to round a string, which doesn't work

#

oh wait, I think round already does the conversion

rare furnace
#

No I mean, in template editor in developer tools it shows correct rounded value

marble jackal
#

but if it is just for display purposes on your dashboard, I would suggest to wait for the 2023.3 release later today

rare furnace
#

Sorry, I am completely new to HA, I dont even know how to add a template and where to put it. But I have some coding experience so rounding the number was not that hard

rich quarry
#

add this to your configuration.yaml ```yaml

template:

  • sensor:
    • name: "Decimal Temperature"
      unit_of_measurement: "°C"
      state: >
      {{ states('sensor.tempsensor') | round(2)}}```
rare furnace
#

Oh really, theres a new release today? 😄

marble jackal
rich quarry
#

oh yea my bad

rare furnace
#

float I guess

marble jackal
#

but like mentioned above, round already does the conversion to number

#

it's not needed

#

I would add either a default in the round filter, or an availability template

rare furnace
#

yeah I think I have it covered in what I mentioned earlier

#

{{ states('sensor.flexit_outdoor_air_temperature') | round(2)}}

#

this works

marble jackal
#

and you need to indent the template under state

#
template:
  - sensor:
      - name: "Decimal Temperature"
        unit_of_measurement: "°C"
        state: >
          {{ states('sensor.tempsensor') | round(2) }}
        availability: "{{  states('sensor.tempsensor') | is_number }}"
rare furnace
#

Btw, does it matter where i put it in config file? Like can I put it all the way down or like at the beginning?

rich quarry
#

btw

rare furnace
#

Yeah I allready did

#

It worked in template editor

marble jackal
#

it doesn't matter where, but if you already have a template: key somewhere, you need to place it under that key

#

and only define template: once

rare furnace
#

Okay, I dont have a template key anywhere. Just started out trying to figure it out today

marble jackal
#

you can also put them in a seperate file like already exists for automations

#

but.. tomorrow this will not be needed, as you can round the current value in the GUI

#

or now already, if you install the beta

rare furnace
#

Nice. That sounds awesome.

#

But I also want to learn templates so why not

floral shuttle
#

on the rounding in yaml: I deleted many many of those in my config yaml files, and only required a few precision settings in the new Frontend... that is a very fine and new feature in HA 2023.3!

rare furnace
#

Cool

#

But to my next question, how do I actually use this in the dashboard?

floral shuttle
#

it saves a lot of yaml, and hence the risk if typo's... 😉 no more trouble with default values etc etc

rare furnace
#

Btw, any need to restart Rpi or refresh something to make the template active?

marble jackal
#

and the code above will create a new sensor, which you can use in your dashboard

#

so you will have one rounded sensor, and one with all the decimals

rare furnace
#

Oh, okay. I see

marble jackal
#

which is another advantage of changing the precision on the actual sensor as of 2023.3

rare furnace
#

Yeah I guess. Do you know when the new version will be released?

marble jackal
#

somewhere today, when it's ready

#

always on the first Wednesday of the month

#

for a major release. and minor releases during the month

rare furnace
#

Okay, awesome. I am totally new to HA and Rpi, installed HA this weekend for the first time

visual matrix
#

Any easy way of converting this to a 'voice assistant' readable value? Current it says ex: 1 dollar dot 55. What can I do to make it show 1 dollar and 55 cents ?
{{ states('sensor.gasbuddy_average_gas_price') | int /100 }}

marble jackal
#
{% set value = states('sensor.gasbuddy_average_gas_price') | int / 100 %}
{% set d = value | int %}
{% set c = ((value - d) * 100) | int %}
{{ d ~ ' dollar' ~ ((' and ' ~ c ~ ' cent'~('s' if c > 1)) if c) }}
visual matrix
#

Thank you! Works perfectly

plain magnetBOT
#

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

cursive knoll
#

hello how to add a picture to this template

#
  • platform: template
    sensors:
    watertank_card:
    value_template: >-
    {% if states.sensor.watertank.state | float <10 %}
    empty
    {% elif states.sensor.watertank.state | float <20 %}
    20
    {% elif states.sensor.watertank.state | float <30 %}
    30
    {% elif states.sensor.watertank.state | float <40 %}
    40
    {% elif states.sensor.watertank.state | float <50 %}
    50
cursive knoll
#

this is my template is wrong

  • platform: template
    sensors:
    binary_sensor.20:
    value_template: >-
    {% if states.binary_sensor.20.state | float <20 %}
    20
    state_image:
    81: local/water/1.png
    entities: []
    type: picture-glance
    entity: binary_sensor.20
rare furnace
#

Ok I have a new issue. I have a multi state value I want to convert to text with a template.
So the states can 1, 2, 3, 4, 5, 6 and 7 where they each represent a string value. How can this be done?
So far this is what I have:

  • sensor:
    • name: "OpMdSts"
      state: >
      {{ states('sensor.flexit_current_operating_mode')}}
inner mesa
#

I would do that with a dictionary lookup

rare furnace
#

Yeah, can I make a dictionary in the config file?

inner mesa
#
  - sensor:
      - name: "OpMdSts"
        state: >
          {% set map = {"1": "thing1", "2": "thing2"} %}
          {{ map[states('sensor.flexit_current_operating_mode')] }}
rare furnace
#

Ahh, okay cool

#

So much to learn, never done yaml before. I have some xml experience but not much. And also almost never used javascript before, but I know some Python and Lua. Steep learning curve I guess. Thank you for helping me!

inner mesa
#

Check out the links in the channel topic for Jinja syntax. There's a lot of similarity to Python

rare furnace
#

Allright. Does the Jinja syntax to f.x. button-card addon? Would love to try out the more customizable cards. But so far I haven't tried them out much since I really didn't know what I was doing

inner mesa
#

are you talking about the custom button card?

#

"addons" are completely different things

#

if so, it uses Javascript, and has lots of examples in the documentation

rare furnace
#

yeah button card

#

hacs "addon" sorry

inner mesa
#

HACS has no addons

#

that's a custom card for the HA frontend

plain magnetBOT
#

An add-on is a Docker container with tweaks to allow it to be configured in the Supervisor UI. It is only available in the Supervised installs (#330990055533576204 and #330944238910963714) since if you've used any other install method you're able to install software already.

rare furnace
#

Yeah a bit confused about all the terminology I guess

heavy crown
inner mesa
#

you mean specifically in the state_topic?

#

Looks like "no"

hard venture
#

This should be the easiest, most obvious thing ever, and I thought I had it working at one point, but it seems to be throwing an error now: {{ max[10,2] }} yields UndefinedError: function object has no element (10, 2). What does that mean and how do I fix the error?

mighty ledge
#

because the syntax is wrong

#

max([10,2])

#

or [10,2]|max

hard venture
#

🤦‍♂️ And, that's why it worked elsewhere, but not here.

#

Forest, meet trees...

#

I knew it was simple and obvious, I just wasn't seeing it.

mighty ledge
#

Always check the punctuation

ember cloud
#

thanks 🙂

ember coyote
#

If a sensor has an attribute that returns this kind of array, how do I parse it to only return the value of "id"?

{'Value1': {'added_date': 1677245317, 'id': 60}, 'Value2': {'added_date': 1676604867, 'id': 89}, 'Value3': {'added_date': 1676407928, 'id': 14}}

ember coyote
#

I need that value to use in a service call

lofty mason
#

I think maybe state_attr('sensor.xxx', 'attribname').Value1.id

floral steeple
#

hi all, i'm mathematically challenged here. I'm trying to make a sensor that is based on the value of another sensor. The real sensor outputs a voltage from 0.00to 10.00 V, the new sensor should output a velocity based on this value, where 0.00 V = 0.00 m/s and 10 V = 30.00 m/s, a simple linear relationship

lofty mason
#

{{ (value / 10) * 30 }} ?

#

or {{ value * 3 }} 🙂

floral steeple
#

lol that is it!

#

thank you!

#

now time to make the template....

floral steeple
#

ok, I think I messed this up but here goes

    - name: hvac_velocity
      unique_id: 2c2ca0b1-9916-467f-99fa-6dbf395a43c7
      state_class: measurement
      unit_of_measurement: m/s
      device_class: speed
      state: >
        {% set voltage= states("sensor.smart_implant_voltage_3") %}
        {% set velocity= {{ (voltage / 10) * 30 }} %}
inner mesa
#

you didn't convert the state to a float, and you're nesting your template

#

and you didn't output anything

#

As TimO pointed out, this will do it:
{{ states("sensor.smart_implant_voltage_3")|float * 3 }}

floral steeple
#

thank you, all! this works

#

if I wanted 2 decimal places, is it this?
{{ states("sensor.smart_implant_voltage_3")|float * 3 | round(2) }}

inner mesa
#

that rounds "3"

#

{{ (states("sensor.smart_implant_voltage_3")|float(0) * 3) | round(2) }}

floral steeple
#

You saved me again, thank you

plain magnetBOT
#

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

inner mesa
#

how is that related to a template?

humble void
#

maybe it's not...sorry not sure where to ask for help. All of my coding for this integration is in the configuration file. I'll figure it out...

inner mesa
heavy crown
inner mesa
heavy crown
half pendant
#

I have a universal media player where i've said that the state (as an attribute) should be taken from my TV but it seems to take it from the apple tv anyhow. Anyone know why this could be?

marble jackal
#

not without you sharing the code

plain magnetBOT
#

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

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

cerulean karma
#

Hi, I have got a power sensor that seems to be a string instead of a float. Is there a way to define it as float a the source?

#

{{ 'sensor.tasmota_mt681_power_cur' + 1 }} -> TypeError: can only concatenate str (not "int") to str

marble jackal
#

ALL states are strings

#

but you are not even getting the state, you are only providing a string with the entity_id

cerulean karma
#

arg

marble jackal
#
{{ states('sensor.tasmota_mt681_power_cur') | float + 1 }} 
      ^ to actually get the state               ^ to convert it to a number
cerulean karma
#

got itn thanks 🙂

#

so states('sensor.tasmota_mt681_power_cur') is even always a str?

marble jackal
#

yes

cerulean karma
#

ok thanks

half pendant
feral turtle
#

Howdy

#

i have a working template sensor, but i got hass errors, Error while processing template:

marble jackal
marble jackal
#

and I think you have your comparisons mixed up

half pendant
mental violet
#

Hello, I have a list with strings in it, but I want to change them all to floats (so I can sum them). Is there a filter for that or do I have to do this via a for loop?

marble jackal
#

@half pendant yes

marble jackal
mental violet
#
{%- set ns = namespace(data=[]) %}
{%for temp in sensor_temp_list%}
  {% set ns.data = ns.data + [temp|float] %}
{%endfor%}
{{ns.data|average|round(2)}} ```
I have now this, but I have the feeling it should be simpler than that
#

ah, perfect thank you

feral turtle
#

maybe a conversion error between float and int ?

marble jackal
#

proably a typo in the entity_id, so the returned state is now unknown
and you didn't add defaults to your float filters, so it now fails on trying to convert unknown to a float

proud kite
#

hi all, maybe a trivial topic: I have a template sensor where I want to read the water temperature only while a filtering pump started running (because before then the measurement does not accurately reflect the temperature of the water in the swimming pool, as the probe is attached to a pipe next to the pump). I currently have the following:

template: sensor: - name: pool_water_temperature state: >- {% if states('switch.ovalesublime_pool_relay_01_01') == 'on' %} {% set res = (states('sensor.ovalesublime_irrigation_ds18b20_2_temperature') | float) %} {% elif states('switch.pool_water_temperature') != 'unavailable' or states('switch.pool_water_temperature') != 'unknown' %} {% set res = states('switch.pool_water_temperature') %} {% else %} {% set res = 'unavaliable' %} {% endif %} {{ res }} state_class: measurement unit_of_measurement: "°C"

this works ok but there is a 5 min period while the temperature is still converging, as the water starts to circulate across the pipe. I would like to ignore those first 5 minutes as well. How can I tell from the template how long an entity is in a given state?

#

I know there is the ".last_changed" attribute but that doesn't seem to reflect the time in the "on" state

mighty ledge
marble jackal
#

ah yes, probably that's it 🙂

mighty ledge
#

the error says different tho

#

🤷‍♂️

marble jackal
#

maybe he fixed that already

half pendant
#

When i run the following code in the template tester in HA UI it works as expected but when i put it in the state_template for universal remote i get unknown. Anyone know why?

  {{ states('media_player.kontor') }}
{% else %}
  {{ states('media_player.lg_c2') }}
{% endif %}```
#

I've just run the quick reload yaml from the ui and not restarted HA totally

narrow surge
obtuse zephyr
narrow surge
#

I would like to start heating when I'm in the room for 5 minutes. Still have to figure out what numbers to use as threshold.

#

Instead of a simple: if motion detected start heating now. Which also triggers when I'm no longer than 2 minutes in the room.

obtuse zephyr
#

One thing with motion detection.... will it be sensing motion for the entire 5 minutes you're in the room? You might only get a portion of that time as motion, even if you're still occupying it

narrow surge
#

No, its flips a lot between on/off, even when I'm in range. It clears after 30 seconds, then it waits for new motion, which occurs within 10 seconds or so. Which is why counting the amount is my best bet.

unique briar
#

wondering if anyone can help me out with value templates and a JSON sensor? I've spent hour combing through docs and old forum posts, but can't figure this out. I have a JSON sensor which works well trying to get the temperature from a fireboard (wireless grill thermometer) in JSON format, but when I try to use a value_template to return just a single number, I got nothing.

half pendant
unique briar
#

ok trying to post code but can't figure out discord formatting either

plain magnetBOT
#

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

obtuse zephyr
unique briar
#

for the code I posted, I get the error: Template variable warning: 'list object' has no attribute 'temp' when rendering '{{value_json.temp}}'
but I get all the attributed correctly as expected: [{"temp":73.2,"degreetype":2,"channel":1,"created":"2023-03-01T21:55:35Z"}]

half pendant
#

@unique briar I've really got no idea but you are fetching a file called temps.json in the resource field and then trying to send in a file called value_json.temp in your value_template field

unique briar
#

Template variable error: 'temps' is undefined when rendering '{{temps.temp}}' when changing that. My assumption is that value_json.temp should get the value of the FIELD temp in the JSON that is returned, but i'm wondering if that's wrong.

mighty ledge
#

your template should be {{ value_json.temp }} if "temp" is a key in the value_json dictionary, assuming it is a dictionary.

#

and, going to that resource, it is not a dict, it is a list

unique briar
#

ah okay, so i'd need to grab the value based on index position in the list then?

#

that makes sense, since i'm seeing Template variable warning: 'list object' has no attribute 'temp' when rendering '{{ value_json['temp']}}' when i try it a different way

mighty ledge
#
sensor:
  - platform: rest
    unique_id: fireboard
    name: fireboard
    resource: https://fireboard.io/api/v1/devices/a5b139fa-0d19-44b2-b6f1-d31fd8afeab4/temps.json
    method: GET
    headers:
        Authorization: Token cc0da08db376820b638e1f10c6bee466019f45bc
    scan_interval: 30
    json_attributes_path: '$.0'
    json_attributes:
          - "degreetype"
          - "temp"
          - "channel"
          - "created"
    device_class: temperature
    value_template: '{{value_json[0].temp}}'
unique briar
#

what's fun there is that the list is seemingly returned in a different order every time

#

is it possible to sort the list before processing? do standard python methods for lists work here?

mighty ledge
#

nope

#

you'd have to use a different method aside from rest

#

if you want attributes

unique briar
#

[{"channel":1,"created":"2023-03-02T14:05:53Z","temp":68.2,"degreetype":2}]
[{"temp":68.2,"created":"2023-03-02T14:06:03Z","degreetype":2,"channel":1}]

two logs seconds apart

mighty ledge
#

if you just want the temperature, sure, you could make a template that grabs the correct temp

unique briar
#

temperature is really all that I care about to be honest

#

timestamps should come in automatically, degreetype is just F so I can set that using unit_of_measurement and i'm only using the one channel

mighty ledge
#

oh, that's what you meant by order

#

yeah, that doesn't matter

#

that's a dictionary

#

well a list with a dictionary inside it

#

this means list []

#

this means dictionary {}

#

a populated list is [4, 3, 5, 2, 1 ]

#

if that order changes, then you're SOL

#

you currently only have [{...}]

#

the first item is {...}

unique briar
#

okay, what about something like "{{ value_json[0].temp}}"