#templates-archived

1 messages · Page 80 of 1

mighty ledge
#

e.g. my NWS entity...

graceful whale
#

That’s it!

mighty ledge
#

however in developer tools -> states...

#

no forecast attribute.

#

i.e. you have to use the service

graceful whale
#

Is this internally stored/polled periodically, or is the service just being called when I browse to the entity?

mighty ledge
#

does it matter? You don't have access to that without the service

graceful whale
#

And service = retrieve the data from NWS (request data, wait for reply over Internet) each time?

mighty ledge
#

You're assuming it does htat

#

each weather integration is different

#

it may be cached data, it may request new data. Each integration is different.

#

That integration polls for data every 60 minutes, regardless how many times you call the service. I.e. it's cached data.

graceful whale
#

So, services may cache data and don’t do asynchronous retrievals each time? That’s what I was trying to ask. I see that many of the weather integrations limit how many calls per hour/day you can do.

mighty ledge
#

integrations do the caching

#

integrations manage the services they create

#

the service can do anything the integration code-owner can dream up

graceful whale
#

OpemWeatherMap, for example wants a credit card in case you go over so many per day.

mighty ledge
#

If you're not willing to read the code, you'll have to do practical tests to find this information out.

graceful whale
#

Gotcha. Was thinking that maybe the data wanted is stored in an “entity” object and I could somehow access it directly from Jinga with some function and do everything in Jinga.

mighty ledge
#

no, entities are designed to have the least amount of data as possible because their states go directly into the database

graceful whale
#

So, state=sensor=local and service=get from integration (possibly cached)? All integration interaction with templates falls under these two categories?

mighty ledge
#

I'd say, it's a safe bet to assume every weather integrations get_forecast is cached hourly.

#

otherwise, look at each integrations coordinator file to see the polling frequency

#

I don't really understand your template comment

#

templates access the state machine and they are synchronous, not async. So templates are limited to a "snapshot in time"

#

which is what the state machine provides

opaque sentinel
#

If I move my template sensors from config.yaml to a split file (templates.yaml), will this keep the history (or create a new sensor)?

mighty ledge
#

everything will remain the same if you don't alter the entities. Restart, don't reload.

opaque sentinel
#

Great

#

Is this also true for changing the syntax of the template? I've got both today and would like to harmonize it. As in:

  sensors:```
and
```template:
  - trigger:
mighty ledge
#

Only if you have unique_id's

#

if you don't have unique_id's, add them. Restart. Then convert them to the new style. Then restart again.

#

Do not reload under any circumstances

opaque sentinel
#

Hmm ok, even if they are not created from the ui?

mighty ledge
#

Not sure what the UI has to do with this

#

unique_id creates a config entry for the entity. Then when you convert to the new style, nothing will alter because you have a config entry that it will use.

opaque sentinel
#

I heard somewhere, on the podcast I think, that templates from the UI was dependant on unique ids. Or something. But whatever - thanks, will try!

mighty ledge
#

I think you're miss hearing things. They were most likely mentioning that you don't need to add a unique_id because the UI is creating it

opaque sentinel
#

Yeah probably

spring knot
#

Is there a way to pull time information off of a history graph? For example, I have a sensor that shows how long a playstation is on and I would like to have it show Playstation - 30 Mins or something like that.

plain magnetBOT
#

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

inner mesa
#

make a template sensor with it

brisk storm
#

ohh, that makes a bit more sense

inner mesa
#

a more compact way to express that would be:

{% set mode = states("sensor.toplotna_mode")|int %}
{% set map = {0: 'Hot water', 1: 'Heating', 2: 'Cooling', 3: 'Hot water + heating', 4: 'Hot water + cooling'} %}
{{ iif(mode <= 4, map[mode], 'Unknown mode: ' ~ mode) }}
brisk storm
#

i was looking for something like this!

#

thanks

#

there's a ) missing somewhere on the 3rd line and i'm not entirely sure where it's supposed to go

#

got it

#

oh yeah, it's all coming together :)

inner mesa
#

Oops, yeah

distant plover
#

How can I find out how many times a temperature sensor has changed in the last 24 hours? And maybe even how many times just the number in front of the decimals?

marble jackal
#

A trigger based template sensor which triggers on every state change of the temperature sensor and then increments it's own state with one

ebon copper
#

Copying from #automations-archived because I went the wrong place (again):

Okay, I feel like this should be easy. I want to keep this simple for my sister and have a card that lets them set time and temp for day mode and night mode for a heater in a plant nursery. Have that all working but I just learned about the generic termostat helper, so I'm migrating to that. There should be a way to run an automation to set the temp at a helper number when the correct time comes around, but I'm failing because it's looking for a float value

https://dpaste.com/DQTY9V4KL

tame axle
#

Hi! I have a card for my 3d printer, based on the octoprint state sensor: https://dpaste.com/6BQ2YBQ63
The states for it can be: Printing, Operational, and Unavailable.
Is there any way to just show the card as 'off' when Unavailable? I don't like seeing it as a faulty device on my dashboard

plain magnetBOT
#

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

mighty ledge
hoary nest
ebon copper
#

Thank you!

#

I knew it had to be something dumb

mighty ledge
hoary nest
#

will try. Thanks !

#

WHOAH

#

I bow myself to thee mister wizard.

ebon copper
#

We bow to our green gods

marsh cairn
frail dagger
#

What about the purple ones?

marsh cairn
#

We are daemons

frail dagger
#

WOOT! YES! Programs unite!!!

hoary nest
#

one more thing. Is it because it's nested JSON ?

spring basin
#

Hi folks - i need a little help with hardening a template sensor that occasionally becomes unavailable. I think it is related to using this.state as an attribute but I can't find a better way.

#

`# Sensor to compare the latest GPS speed data when it changes

Holds latest acceleration calculation as state

  • trigger:
    • platform: state
      entity_id: sensor.jago_iphone_speed
      sensor:
      • name: "Jago iPhone Acceleration"
        unique_id: jago_iphone_acceleration
        icon: "mdi:speedometer"
        state_class: measurement
        state: "{{ ((trigger.to_state.state | float(0) - trigger.from_state.state | float(0)) / states('sensor.jago_gps_age') | float (0)) | round(4) }}"
        attributes:
        speed_last: "{{ trigger.from_state.state | float(0) }}"
        speed_now: "{{ trigger.to_state.state | float(0) }}"
        state_last: "{{ this.state | float(0) }}"
        state_delta: "{{ (states('sensor.jago_iphone_acceleration') | float(0) - state_attr('sensor.jago_iphone_acceleration', 'state_last') | float(0)) | round(4) }}"`
marsh cairn
#

Dividing by 0 if the GPS age is unavailable might break it

spring basin
#

when it works it works. I need state_last attribute to hold the last state to allow me to work out state_detla

#

I have tried to use {{ has_value(states('sensor.jago_gps_age'))}} but this always returns false

#

even when it has a value

marsh cairn
#

Whenever that sensor is not numerical, it will default to 0 in your template. And that is a problem

frail dagger
spring basin
#

thanks - what is wrong with the syntax?

inner mesa
#

you were providing the state of the entity and not the entity

#

you can see the difference between yours and his?

spring basin
#

yes - now I can. sorry. didn't look properly

#

the docs say you can use has_value as a filter. would this be a good approach for hardening this template?

marsh cairn
#

You can use that for an availability template. But that wouls also mean being unavailable, when that sensor has no value.

spring basin
#

Thank you. I want the sensor to be available at all times and always trigger - happy with it returning 0 when gps_age is unavailable. how can I harden so this is the case?

marsh cairn
#

At least you need to change the default value of GPS age to something else than 0. Some sane value.

spring basin
#

OK. i will change the default to 1 for gps_age.

marsh cairn
#

If you want the state of the complete template to be 0 when GPS age is unavailable, I guess you would have to work with if-else or iif

spring basin
#

I have a feeling the issue is with using this.state as an attribute so I will use has_value to harden this and also look to usee iif for the state

spring basin
#

is using iif a better way than using a filter with default or no difference? For example...

#

{{ iif( has_value('sensor.jago_gps_age'), states('sensor.jago_gps_age'), 0 ) }} {{ states('sensor.jago_gps_age') | float(0) }}

#

to be clearer do the above examples do exactly the same thing? Return 0 if unavailable or unknown

marsh cairn
#

That won't help at all.
Your logic would have to be
if GPS age has value: use the template (I'd still set the default for the GPS age to 1)
if not: state is 0

spring basin
#

sure - i will change gps age default to 1. That's easy.

#

when you say 'use the template' do you mean the state inside the triggered template sensor? (sorry i'm quite new to this stuff)

marsh cairn
#

I meant that template from the state section earlier

#
      state: >
        {% if has_value('sensor.jago_gps_age') %}
          {{ ((trigger.to_state.state | float(0) - trigger.from_state.state | float(0) / states('sensor.jago_gps_age') | float (1)) | round(4) }}
        {% else %}
          0
        {% endif %}
spring basin
#

Thank you @marsh cairn - understood. That is what I thought too so I did understand after all

haughty kiln
#

#frontend-archived message looks like i greatly overcomplicated this. the answer is simplyThere are {{ states['light'] | selectattr('state','eq', 'on') | list | count }} lights on and {{ states['opening'] | selectattr('state','eq', 'on') | list | count }} doors open.

inner mesa
#

I don't think that states['opening'] is a thing unless you've installed a custom_component that supports it

marble jackal
#

If not, you need states.binary_sensor and you need to check on the device_class attribute

storm cloud
#

Can I get the timestamp from an event in a template? I'd like to get the exact time of the event which has triggered an automation. I've tried sensor.date_time_iso but that is only giving me the time the automation executed to the minute. I'd like to at least get to 1 second resolution.. Thanks.

marble jackal
#

The last_triggered attribute gives you the date and time it last triggered accurate to the microsecond

#

If you want the exact time the event was sent, create a trigger based template sensor which triggers on that event and writes the time (either of the trigger, or just now()) to it's state

#

Just use now().strftime('%H:%M:%S') in a template to get the current time including seconds

plain magnetBOT
#

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

willow wing
#

ah looks beeter now, but the spacees beetween etch word is away too now

frail dagger
willow wing
#

makes no change (no space beet etch word)

marble jackal
#

why do you have new if statements every time?

willow wing
#

dont know how i can do it in a other way

plain magnetBOT
#

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

marble jackal
#

@willow wing how about this?

{% set sensor = 'sensor.iphone_chrissi_companion_app_geocoded_location' %}
{% set attr = states[sensor].attributes if sensor | has_value else {} %}
{{
  [
    attr.get('Thoroughfare', 'N/A'),
    attr.get('Sub Thoroughfare', 'N/A'),
    attr.get('Locality', 'N/A')
  ] | reject('eq', 'N/A') | join(' ')
}}
willow wing
#

ahhh, thats cool and works perfect, would never have thought of it, would it be possible to check the value "null" to? can i add this via a comma?

marble jackal
#

reject('in', ['N/A', none])

#

If I understand you correctly

#

which value would be null?

willow wing
#

all three can have this vlaue "Thoroughfare, sub Thoroughfare and Locality"

#

so its enought to add it in the reject line like your example?

marble jackal
#

yeah, in that case you can do this:

{% set sensor = 'sensor.iphone_chrissi_companion_app_geocoded_location' %}
{% set attr = states[sensor].attributes if sensor | has_value else {} %}
{{
  [
    attr.get('Thoroughfare'),
    attr.get('Sub Thoroughfare'),
    attr.get('Locality')
  ] | reject('in', ['N/A', none]) | join(' ')
}}
willow wing
#

perfect thank you 👍🏻 👍🏻 (but the comma does not be setted in you example)

can i ask you one more too?

marble jackal
#

which comma?

willow wing
#

my format was "street number, location"

#

so it is missing a comma after the Sub Thoroughfare

#

i got it, thanks 🙂

marble jackal
#

how did you add it?

willow wing
#

attr.get('Sub Thoroughfare') +",",

marble jackal
#

that will not work in case its none and will break the reject filter

willow wing
#

ah okay, than its bad 🙂

frail dagger
#

Wouldn't join(', ') work?

marble jackal
#

then you will have a comma between each

willow wing
#

but its no worry only nice to have, the UI is never perfect ^^

frail dagger
#

Right, but if attr.get('Thoroughfare') is N/A or none, then it would just be attr.get('Sub Thoroughfare'), attr.get('Locality').

marble jackal
#
{% set sensor = 'sensor.iphone_chrissi_companion_app_geocoded_location' %}
{% set attr = states[sensor].attributes if sensor | has_value else {} %}
{% set t, s, l = attr.get('Thoroughfare'), attr.get('Sub Thoroughfare'), attr.get('Locality') %}
{% set ts = [t, s] | reject('in', ['N/A', none]) | join(' ') %}
{{[ts, l] | reject('in', ['N/A', none, '']) | join(', ') }}
frail dagger
#

lol that's awesome.

willow wing
#

it works you'r crazy, thank you very much

marble jackal
#

you're welcome 🙂

distant plover
marble jackal
#

a template only has access to the current states, no history

#

you can create an sql sensor to recteive data from the database

distant plover
#

Aha. Then thanks. 🙂

marble jackal
#

and you could store changes in an attribute of a template sensor, so you can build up your history

distant plover
#

It was more of a one time thing to figure out if I should update an eink on every change. But I guess I can use SQL manually to do a count.

spring knot
#

I need help, been searching the web and trying a few things and can't wrap my head around this. I need something to be able to pull states from a device/entity history and output the time of that state. For example, on a game councel, the history will show "Playing" and "Idle". So between 07:00 and 08:45 the states is playing then 08:45 to 14:00 is idle then 14:00 to 18:00 is "playing" Trying to create a card that will show the total amount of time it was in the "playing" state and it updates through out the day.

Hope that makes sense.

mighty ledge
#

history statistics integration

plain magnetBOT
spring knot
#

OMG. I can't beleive I have missed that. I'll check it out and see if that works. Thanks 🙂

spring knot
#

Yup. looks like this is doing what I wanted. 🙂 Thanks again for the help!!

tough depot
#

Hi all, I am trying to set an automation for when I trigger an alarm. I want to send a notification to my phone where I get to know the name of the entity that triggered the alarm. How do I do that? I know to get a sensor state I need to use {{ states('sensor.id') }}, but what about the name?

marble jackal
#

trigger.to_state.name should work

#

but it's a bit depending on the trigger you use in the automation

tough depot
#

Let me take the template I currently have

plain magnetBOT
#

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

tough depot
#

Reason why I want to do it this way is in case in future I change in HA the name of the sensor to something else, so that I can avoid having to go change the name in the notification message every time as well

tough depot
#

For some reason couldn't find exactly what I needed online

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
#

follow the trigger variables link for some more information and options

spring knot
#

O.k. at a loss again. I have a history sensor up and running and working. When I go into devolopment and states to find the sensor, I see it and change the unit of messurements from h to min. I go into the entities to look at it and it updates there. But then when I go to add the card, it shows as xx:xx ie 20:12. Am I missing something somewhere?

spring knot
marble jackal
#

how it is shown on the frontend depends on the device class of the sensor

spring knot
#

Hoping this is the place for this questions. So I got my sensors up and running the history_stats is working. What it does is gives me a running total but I would like it to reset and start at 0 every day. Is that possible?

lofty mason
#

that's what history_stats does? what did you give for the time parameters?

spring knot
#

Orrr, will it reset everyday. I guess when I add the end time to go back 1 month, it added all of that time on today. So it basicly went from 65 minutes up to 760 minutes within a matter of seconds lol.

#
  name: DarkPlaystation Play Time
  unique_id: 5432154
  entity_id: sensor.darkplaystation_activity
  state: "playing"
  type: time
  start: "{{ today_at().replace(day=1) }}"
  end: "{{ now() }}"```
lofty mason
#

I think you want this:

start: "{{ today_at() }}"
#

that means today at midnight

spring knot
#

O.k. and then it keeps that history of each day still, but restarts at midnight?

lofty mason
#

this is a sensor. it updates its value throughout the day. whatever history was recorded in the past will never change

#

the parameters you give it tell it how to compute its current value

spring knot
#

o.k. That makes sense.

#

So is there away to have this sensor pull the history going back as well? or am I SOL with that and have to let it just gather new data going forward?

lofty mason
#

you can only ever change its current value. what was recorded in the past, is fixed

mighty ledge
spring knot
#

When I placed the start to go back 1 week. it took the time of the playing state and added it to the current day. The history graph didn't show the previous 7 days, just today with the added time.

mighty ledge
#

oh, I see what you're asking. Nothing you add in home assistant will ever add history

#

it's always from this point forward

#

if you want to see just last weeks count, you'd have to adjust your start and end to show last weeks start and last weeks end

spring knot
#

O.k. but to track it with the history_stats sensor, it's only going to record going forward.

mighty ledge
#

I dont think you understand what start and end are doing

spring knot
#

It's o.k. not a big deal 🙂

mighty ledge
#

If you set the range to be start 7 days ago and end 6 days ago, you get the value from 7 days ago.

#

But the result is added to your system at this moment

#

It won’t have a history

#

Because you just added it

#

The result of the sensor will always be 7 days ago.

brisk storm
#

hello again!
i have a modbus sensor which gives me a 16bit number and each bit means something (basically i wanna break a single sensor down into 16 binary sensors). how do i do something like this? i'm pretty sure a template sensor is only 1 and can't multiply and i also don't feel like creating all of those maually

mighty ledge
#

About to mow the lawn, post an example output from the source sensor and I can help in about an hour or so

brisk storm
#

here's a copypaste from the datasheet:
bit0: O01 System 1 compressor output (0-OFF/1-ON)
bit1:Reserved
bit2: O03 Fan high speed output (0-OFF/1-ON)
bit3: O04 Fan low speed output (0-OFF/1-ON)
bit4: O05 Main circulating water pump output (0-OFF/1-ON)
bit5: O06 Domestic hot water pump output (0-OFF/1-ON)
bit6: O07 Four-way valve 1(0-OFF/1-ON)
bit7: O08 Electric heating energy level one (0-OFF/1-ON)
bit8: O09 Electric heating energy level two (0-OFF/1-ON)
bit9: O10 Hot water 3-way valve (0-OFF/1-ON)
bit10: O11 Alarm output (0-OFF/1-ON)
bit11: O12 crankshaft heating tape (0-OFF/1-ON)
bit12: O13 chassis heating tape (0-OFF/1-ON)
bit13: O21 heating pump (0-OFF/1-ON)
bit14: O22 hydraulic module water circuit electric heating (0-OFF/1-open)
bit15: O23 hydraulic module water tank electric heating (0-OFF/1-ON)

#

as i said, it's a 16bit number as always but this time it uses the bits as flags for different things

#

right now the value is 85 aka 0b0000000001010101

brisk storm
#

honestly, i'm not sure if i care enough to implement the bitfields

#

there's 11 registers like this and it's usually just pointless information i don't care about or error flags

#

i'll do it if there's an easy way but if not, that's fine

mighty ledge
#

Back, it's super easy

#
{% set bytes = "{0:016b}".format(value) | map('int') | reverse | list %}
#

just put the sensor output in value

#

@brisk storm ^

#

bytes[0] is byte 1

#

etc all the way up to byte 16 bytes[15]

#

as a template sensor...

#
template:
- trigger:
  - platform: state
    entity_id:  <FILL THIS OUT>
  variables:
    bytes: >
      {{ "{0:016b}".format(trigger.to_state.state | int(0)) | map('int') | reverse | list }}
  binary_sensor:

  - name: Byte 1
    state: {{ bytes[0] }}
  - name: Byte 2
    state: {{ bytes[1] }}
  - name: Byte 3
    state: {{ bytes[2] }}
  - name: Byte 4
    state: {{ bytes[3] }}
  - name: Byte 5
    state: {{ bytes[4] }}
  - name: Byte 6
    state: {{ bytes[5] }}
  - name: Byte 7
    state: {{ bytes[6] }}
  - name: Byte 8
    state: {{ bytes[7] }}
  - name: Byte 9
    state: {{ bytes[8] }}
  - name: Byte 10
    state: {{ bytes[9] }}
  - name: Byte 11
    state: {{ bytes[10] }}
  - name: Byte 12
    state: {{ bytes[11] }}
  - name: Byte 13
    state: {{ bytes[12] }}
  - name: Byte 14
    state: {{ bytes[13] }}
  - name: Byte 15
    state: {{ bytes[14] }}
  - name: Byte 16
    state: {{ bytes[15] }}
#

fill in the rest

#

and or perform math

#

or do whatever

frail dagger
#

Does anyone have a quick one liner to get a list of all the notify.* services?

frail dagger
#

I figured as much, but thought I'd ask. Thanks.

north helm
#

Hi there. I'm having an issue with a RESTful sensor. It's pulling the data ok, but when I try to update through Lovelace, it's coming up appended with a _3 and getting the following error. "This entity ('sensor.wet_bulb_globe_thermometer_3') does not have a unique ID, therefore its settings cannot be managed from the UI. documentation for more detail."

#

I've been looking around and can't quite figure out how to give it a Unique ID. I need this because that value is coming over as Celcius and I want to convert it to Fahrenheit without doing a seconday template with a formula.

frail dagger
plain magnetBOT
#

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

north helm
#

But what do I specify after unique_id?

frail dagger
#

Whatever you want.

#

It can be a string of anything, as long as it's unique. You could use "981273098127390812739018273" or whatever strikes your fancy. 🙂

north helm
#

Huh.... Let me try that. That's FAR too easy if true. 🙂

frail dagger
north helm
#

Well son of a.... Don't I feel silly now?

frail dagger
#

lol no need to feel silly... I still get it wrong from time to time.

north helm
#

Now I just need to get the unit conversion working. Guessing it's something like unit_of_measurement: C

frail dagger
#

unit_of_measurement: F should automatically do the conversion (I think).

north helm
#

I'll let you know in a moment.

#

Nope. Now instead of reading as "21" it's "21 F"

frail dagger
#

What does the JSON look like?

north helm
#

"wet_bulb_globe_temperature": 21.4,

#

Added native_unit_of_measurement: °C. and now getting This entity is no longer being provided by the rest integration. If the entity is no longer in use, delete it in settings.

frail dagger
#

That's because native_unit_of_measurement isn't a valid attribute.

north helm
#

I thought the docs didn't lie....

#

🙂

frail dagger
#

That's for a sensor entity. The rest sensor entity doesn't have that attribute. What you linked is the base sensor class, but not everything derives from that.

north helm
#

Ohhhh

frail dagger
#

So, it looks like you need to do the conversion in your value_template from C to F.

north helm
#

OK. I can do that. It's ugly but I can do it.

frail dagger
#

'{{ ((value_json["obs"][0].wet_bulb_globe_temperature | int(0)) * 1.8) + 32 }} should do it.

#

Actually... my parens might be off there. I didn't test it. Doh.

#

There we go. Fixed it.

north helm
#

{{ ((value_json["obs"][0].wet_bulb_globe_temperature | int(0) * 1.8) + 32) }} Ahhh, yours should be right.

#

LOL... Yeah, mine came back as 57.7 degrees.... HA!

frail dagger
#

I do temp calcs WAY too often. lol

inner mesa
#

Stupid metric system, amirite?

frail dagger
#

lol you said it... not me!

north helm
#

Still unavailable.... Hmmmm. And look, I grew up on metric, but Americans will do anything to avoid it so here we are.

frail dagger
#

The sensor is unavailable?

north helm
#

Yeah....

frail dagger
#

Ok. 1 sec. Let me test it.

north helm
#

Thanks. I'm probably doing something really dumb.

#
    unique_id: MercuryWetGlobe
    resource: https://swd.weatherflow.com/swd/rest/observations/station/26820
    method: GET
    name: "Wet Bulb Globe Thermometer"
    device_class: temperature
    native_unit_of_measurement: °F
    headers:
      Authorization: !secret tempest_api
    value_template: '{{ ((value_json["obs"][0].wet_bulb_globe_temperature | int(0)) * 1.8) + 32 }}'
    scan_interval: 5
frail dagger
#

Change native_unit_of_measurement to unit_of_measurement.

north helm
#

Damnit.

frail dagger
#

🤣

north helm
#

Now I has teh shame.

frail dagger
#

hahaha again, no worries!

#

I take it that it's working better now?

north helm
#

I took it out entirely and now I'm re-adding °F

#

And there it is.

frail dagger
#

Woot!

north helm
#

Thanks for being so patient with me.

frail dagger
#

Oh, not a problem at all!

north helm
#

I really appreciate your help.

frail dagger
#

If you want to test it in dev tools > templates:

{% set value_json = { 'obs': [{ 'wet_bulb_globe_temperature': 20 }]} %}
{{ ((value_json["obs"][0].wet_bulb_globe_temperature | int(0) * 1.8) + 32) }} 
north helm
#

I don't use that tool enough.

frail dagger
#

Oh yeah, that needs to change.

north helm
#

It certainly will!!

#

I wish I didn't have to run, but movie night is starting and I need to pay attention. Hope you have a good weekend and stay cool. Thanks again!!!

frail dagger
#

Right on. Sounds good. Have a good weekend yourself and happy to help. 🙂

north helm
#

I'm sure I'll be back later this weekend now that I've gotten into the guts of my system. 🙂

hallow sparrow
#

Is there a way to determine if a sensor's value is increasing or decreasing in a template? My use case is that I am trying to write an automation to send a notification when the house reaches "temperature crossover." So, I want to have one trigger for when the outside temperature is rising and equals the inside temperature (would naturally occur sometime in the morning). Then, I want another trigger for when the outside temperature is dropping and equals the inside temperature. This way I can send notifications to either open or close windows depending.

inner mesa
#

Those are just two numeric_state triggers in an automation

#

One above and one below

hallow sparrow
#

What I was thinking was a template trigger similar to: {{ float(states(sensor.inside_temp)) == float(states(sensor.outside_temp)) }}

#

but I suppose a template sensor and then numeric state trigger is cleaner

#

wait, are you saying to use the value template in numeric state trigger, @inner mesa ?

inner mesa
#

No

#

I'm suggesting using a trigger with one entity and comparing with the other

hallow sparrow
#

So, something like...

platform: numeric_state
entity_id:
  - sensor.outside_temp
id: crossover_morning
above: sensor.inside_temp
inner mesa
#

Yes. That will trigger when the outside temp becomes higher than the inside temp

hallow sparrow
#

Thank you!

lucid thicket
#

is there an elegant way to convert an arbitrary timezone-aware datetime into UTC?

#

I'm using this at the moment:

{% set dt = '2022-12-18T15:10:00-05:00' | as_datetime %}
{{ dt.astimezone(as_datetime(0).tzinfo) }}
marble jackal
#

Not that elegant though

shrewd wraith
#

can somebody explain me what data home assistant expects as daily and hourly forecast data? i'm trying to populate a template weather entity. From looking around i understood that the forecast values are no longer stored within the weather entity itself (although populating the "forecast" attribute does show the forecast...) The documentation isn't really helpful either concerning this detail...

frail dagger
shrewd wraith
#

well..that's the thing: I'm not using any integrations for this. What I want to achieve is setting up a weather entity without having to go through the process of writing my own integration...

frail dagger
shrewd wraith
#

ah dammit... well then time to spin up the environment then 🙂

nocturne chasm
#

if {{ events | map(attribute='summary') | join(', ') }} results in Test1's Birthday, Test2's Birthday, Test3's Birthday how would I get the result Test1, Test2 and Test3's Birthday? I have been playing with loops but can't even get close to figuring it out

mighty ledge
#

if you want the and, it's a longer template

nocturne chasm
#

yea, was trying to get the and

inner mesa
#

you just have to separate out the [0:-2] and the [-1] or |last element

nocturne chasm
#

I was also playing with | replace with a count but you cant work that backwards

nocturne chasm
inner mesa
#

concatenate everything but the last one + ' and ' + the last one

#

yes

#

but then if you sometimes don't want the 'and'...

nocturne chasm
#

I always want the and for the last one

inner mesa
#

using code to generate consistent grammatical language sucks

nocturne chasm
#

yes

#

so you are saying use split?

inner mesa
#

no

#

I'm saying divide the problem into the items up to the last one and the last one

#

it's a list

#

kind of a stupid example, but:

{% set events = ['a foo', 'b foo', 'c foo'] %}
{% set replaced = events|map('replace', ' foo', '')|list %}
{{ replaced[0:-1]|join(', ') ~ ' and ' ~ replaced[-1] ~ "'s birthday" }}
#

-> a, b and c's birthday

#

to be consistent with your birthday theme:

{% set events = ["a's birthday", "b's birthday", "c's birthday"] %}
{% set replaced = events|map('replace', "'s birthday", '')|list %}
{{ replaced[0:-1]|join(', ') ~ ' and ' ~ replaced[-1] ~ "'s birthday" }}
nocturne chasm
#

ok, I am trying 🙂

inner mesa
#

you can add a second comma there if you're a fan of the Oxford Comma

nocturne chasm
#

I havent even figured out how to replace ["a's birthday", "b's birthday", "c's birthday"] with my actual sensor info

inner mesa
#

events | map(attribute='summary')|list

nocturne chasm
#

auh so:

{% set events = [events | map(attribute='summary')|list] %}
{% set replaced = events|map('replace', "'s birthday", '')|list %}
{{ replaced[0:-1]|join(', ') ~ ' and ' ~ replaced[-1] ~ "'s birthday" }}
inner mesa
#

you added some extra []

#

try it out in devtools -> Templates

nocturne chasm
#

the huge problem I am having is event is an actual variable in the sensor and I dont really understand variables and variables wont work in the template editor will it?

inner mesa
#

I'm creating two variables right there

#

I don't know what "variable in the sensor" means, unless you really mean "attribute"

nocturne chasm
#

auh hold on. i think the template editor still gave me a clue

inner mesa
#

you're describing the most annoying thing in the world 🙂

mighty ledge
#

in template editor

inner mesa
#

How can we make this as complicated and time consuming as humanly possible? Now, let's add more steps

mighty ledge
#

paste

{% set <RESPONSEVARIABLE> = {"calendar.lambosino_s_random_events":{"events":[{"start":"2024-07-13","end":"2024-07-15","summary":"Palmerton Super & Sprint"}]}} %}

but change the <RESPONSEVARAIBLE> to whatever you want to set in your actions

#

then test away

#

SHUT IT TIM BEFORE YOU SAY ANYTHING ABOUT MY PR

lofty mason
#

I did propose a new copy template button there... just waiting for merge 😬

#

Oh I gave up on you a long time ago 😉

mighty ledge
lofty mason
#

{% set service_response = ... %}

mighty ledge
#

Yeah

inner mesa
#

what I really want is to be able to write a temporary script that can populate the Jinja environment

mighty ledge
#

see now I wanted to have response_variable as a field in the service caller and when you copied it, it would use the variable

#

I couldn't get the UI layout correct for the response_variable field so I dropped the PR

lofty mason
#

yeah I just left it hardcoded

mighty ledge
#

better than nothing, but I don't like to deliver things that annoy me still 🤣

#

problem with being a perfectionist with PRs even though I never do anything perfectly

nocturne chasm
mighty ledge
#

just curious how you did it

nocturne chasm
#

so I have gotten to this:

      - variables:          
          events: "{{ birthdays['calendar.family_birthdays'].events }}"
          count: "{{ events | count }}"
          descriptions: >- #"{{ events | map(attribute='summary') | join(', ') }}"
            {% set events = events | map(attribute='summary') |list %}
            {% set replaced = events|map('replace', "'s Birthday", '') |list %}
            {% if count == 1 %}
              {{ events }}
            {% else %}              
              {{ replaced[0:-1]|join(', ') ~ ' and ' ~ replaced[-1] ~ "'s Birthday" }}
            {% endif %}
#

which works perfect for more than one event

#

but if there is only one event, the state has [ ] around it

inner mesa
#

Replace events with events|first

#

The [ ] mean it's a list

nocturne chasm
#

awesome!!! Thanks

bold vale
#

I've setup a custom piper assist voice (glados) and am able to make it say stuff based on templates in the test voice option in the voice settings, it then tells the values of the templates.

But when I try to make an automation for the voice it reads the template out loud, instead of telling the value of the template. From what I googled I understand this is because I need to use data template, instead of data, but Im struggling on how to convert the automation i made so it works. I created the Automation using the gui, not 100% sure if thats the best way to do it, as the yaml code looks so different compared to other tts automations I have

#

service: media_player.play_media target: entity_id: media_player.woonkamer_speaker_lamp data: media_content_id: >- media-source://tts/tts.piper?message=+Hello+human%2C%0AThe+outside+temperature+is+%7B%7B+states%28%27sensor.buienradar_temperature%27%29+%7D%7D%C2%B0.++It+is+%7B%7B+states%28%27sensor.buienradar_condition%27%29+%7D%7D+%0Awith+a+windspeed+of+about++%7B%7B%0A++++states%28%27sensor.buienradar_wind_speed%27%29+%7D%7D+km%2Fh.+Tomorrow+will+be+%7B%7B%0A++++states%28%27sensor.buienradar_condition_1d%27%29+%7D%7D.+It+will+be+about+%7B%7B%0A++++states%28%27sensor.buienradar_temperature_1d%27%29+%7D%7D%C2%B0.%0A%0A++++And+incase+you%27d+like+to+know%2C+there+are++%7B%7B+states.light+%7C+rejectattr%28%27entity_id%27%2C+%27in%27%2C%0A++++label_entities%28%27Lightgroup%27%29%29+++++%0A+++++++++++++%7C+selectattr%28%27state%27%2C+%27eq%27%2C%27on%27%29+%0A+++++++++++++%7C+list%0A+++++++++++++%7C+count+%7D%7D+lights+turned+on.%0A&language=en-us&voice=glados media_content_type: provider metadata: title: >2 Hello human, The outside temperature is {{ states('sensor.buienradar_temperature') }}°. It is {{ states('sensor.buienradar_condition') }}

plain magnetBOT
#

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

haughty breach
#

data_template was deprecated in core services nearly 4 years ago, so it is very unlikely that using data is the issue. You may want to ask over in #voice-assistants-archived .

prisma marsh
#

Anybody know why I can't use lists in 'include_entities'? I've tried everything

      selector:
        entity:
          multiple: true
          include_entities: |-
            ['switch.3cf8c52f004b1200_1_water_switch']
#

I can't use sameline because I'm trying to do a template and it throws a syntax error over the {%

inner mesa
#

in any case, it looks like it just takes a list

prisma marsh
#

well, it won't take this

{%set ns = namespace(entities=['switch.3cf8c52f004b1200_1_water_switch'])%}
            {%for area in areas()%}
              {%for entity in area_entities(area) if 'water_switch' in entity%}
                {%set ns.entities = ns.entities + [ entity ]%}
              {%endfor%}
            {%endfor%}
            {{ ns.entities | list }
#

it says 'found None'

inner mesa
#
          include_entities:
            - switch.3cf8c52f004b1200_1_water_switch
            - switch.someotherthing
#

that's because it's a multiline template

prisma marsh
#

template viewer shows the list properly

inner mesa
#

you need to use include_entities: > and then indent that whole thing on the next lines

prisma marsh
#

tried this

          include_entities: >
            {%set ns = namespace(entities=['switch.3cf8c52f004b1200_1_water_switch'])%}
            {%for area in areas()%}
              {%for entity in area_entities(area) if 'water_switch' in entity%}
                {%set ns.entities = ns.entities + [ entity ]%}
              {%endfor%}
            {%endfor%}
            {{ ns.entities | list }
inner mesa
#

now you're missing a }

prisma marsh
#

missed copy, not from source

#

I'll move to blueprints because this may be something blueprint specific

ocean hedge
#

Hi,
I have a template sensor that gives Callander message for my rubbish collection calendar of either Black or Pink (colours of the sacks) is there a way to change the state colour automatically. For example when the calendar message is Black the state colour is black, when the calendar message is Pink the state colour is pink. Hope that makes sense and someone is able to help. Thanks - Jake

Template sensor:
“ {{ state_attr('calendar.rubbish', 'message') }} “

silent seal
#

But otherwise it really depends on the card you're using as to what you can do

lean yacht
#

Hi all,
I used to have a tempate that displayed the logged in user with {{name}}.
I noticed that this does not seem to work anymore... did I miss a notification on the developer portal ?

mighty ledge
plain magnetBOT
#

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

lean yacht
mighty ledge
#

It's working here

lean yacht
#

I deleted browser cache and cookies and logged in again, but still not working

mighty ledge
#

is it 12 where you are?

#

cause your template doesn't cover exactly 12.

lean yacht
#

what version of Mushroom are you using ? I'm on 3.6.4

mighty ledge
#

the version has nothing to do with it

#

it's a tepmlate, registered the same way as all other templates

lean yacht
#

thanks

plain magnetBOT
#

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

deft ice
#

a less wrong version, but still not working

plain magnetBOT
#

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

marble jackal
deft ice
#

the problem I'm having is with the syntax of whats inside the [[[ ]]]

#

thought you'd me more used to the syntax

marble jackal
deft ice
#

ah, thanks, I'll go there

marble jackal
#

It could be your Jinja template though

#

It needs quotes

deft ice
#

where?

marble jackal
#

@deft ice
"tab_number": "{{ variable.var_tab_number }}"

deft ice
#

gonna try

#

Failed to call service script.turn_on/[object Object]. expected str for dictionary value @ data['service']. Got {'entity_id': 'script.set_monitoring_tab_number', 'data': {'variables': {'tab_number': '{{ variable.var_tab_number }}'}}}

#

do you know what it is or is more to frontend?

marble jackal
#

Why not just simply use the call_service tap action?

deft ice
#

because I want to use 2 actions, I trying to make the first one work

#

besides this one I have to

#

call a dom event with this:
local_condicional_card:
action: set
ids:
- tabs1: hide
- tabs2: show
- tabs3: hide

marble jackal
deft ice
#

thanks anyway 🙂

#

I've posted there

fringe sail
#

Hey guys. I need help with templates of a certain time. I'm trying to make a sensor that will show the next sunset in plain time, not this example...```

2024-07-15T01:26:57+00:00```
I know how to make template sensors, but I'm out of my depth with changing timestamps to regular time.

haughty breach
#

Assuming that is a datetime string and "regular time" means "HH:MM" format...

{{ ('2024-07-15T01:26:57+00:00'|as_datetime|as_local).strftime('%H:%M')}}
fringe sail
slow basin
#

Hello, been trying to get my power consumption to be logged by HAOS, but struggling with the integral (Riemann sum) sensor

#

Even after waiting for several hours for the sensor to update stat history it remains at 0.0 kWH

#

Current setup is:
I have a template sensor exposing the current consumption (W) of my switch and then I use said sensor as the source for the integral sensor

#
    platform: template
    sensors: 
        mainpc_power:
            friendly_name: "Main PC Power"
            unit_of_measurement: W
            value_template: "{{ state_attr('switch.gaming_pc','current_consumption') }}" 
#

Integral sensor confiuration:

Metric prefix: k (kilo)
Time unit: Hours
Input sensor: sensor.mainpc_power
Integration method: Trapezoidal rule
marble jackal
#

does the template sensor show data? And that second block is not the sensor configuration, those are the attributes of the sensor

slow basin
lofty mason
#

So it doesn't work great with constant value templates.

slow basin
#

So if it was outputting a constant 89.9W it won't perceive that change and assume it's sitting at 0?

lofty mason
#

Well it doesn't assume anything, it's just waiting for the next update of the source sensor to update itself. as soon as your PC shut off it would then instantly jump to the correct value

#

Is the source sensor changing?

#

actually I'm sorry I misread and thought your sensor was a constant template. you can ignore what I said.

slow basin
#

Wait, so I don't have a constant template?

marble jackal
#

karwosts meant like a fixed value. Your value is based on actual consumption provided by the smart plug

slow basin
#

Ohhh, yeah, based on the state of my switch's reported current consumption

slow basin
#

All other values were left untouched (save for the name of course)

lucid thicket
lofty mason
slow basin
#

Does anything seem to be amiss with the way I have the sensor set up?

#

I tried making an integral sensor for a different device that just has their current consumption exposed as a sensor and it reports just fine

slow basin
#

I think I've figured it out(?)

#

The kWh measurement was so low that it was a whole decimal place lower than what I expected

#

So the value reported just (0.00) needed to be expanded (0.004)

#

But also switched to left riemann sum

steady spindle
#

Hi. I have a rest sensor to retreive a numeric value. From time to time it fails (no service, no internet ...) . Is there a way to return "No value" or "None" or "Null".
For me it's a normal case, and i don't want to have errors in the log. The workaround |float(0) will produce wrong statistics. Thx.

steady spindle
#

Thx @silent seal . I copy/pasted one example and missed that option. I'll give a try! Thx for your quick answer! 😉

cursive ice
#

is there a way to have a icon via a label template? example in a complication?

modern torrent
#

hey, i am trying to get the percipitation probability at a specific time, i am almost there, but the timezone stuff is messing with me and i don't know how i can get the correct values

    selectattr('datetime', 'ge', now().replace(hour=11, minute=59, second=59, microsecond=0).isoformat()) |
    selectattr('datetime', 'lt', now().replace(hour=13, minute=0, second=0, microsecond=1).isoformat())) |
    map(attribute='precipitation_probability') | list
    }}```
This is my current template, the issue is that the values stored in the weather sensor are at utc 0, but my timezone is utc +2 in the summer and i think it changes to utc+1 in the winter so just subtracting 2hours only works during the summertime. how can i get the correct value independent of the timezone? i want to get the percipitation value from 11 am to 12 am (2 values)
marble jackal
#

today_at('11:59:59').astimezone(utcnow().tzinfo).isoformat()

#

That will return 2024-07-16T09:59:59+00:00

#

BTW, you are only getting 12:00 now

modern torrent
#

awesome, that works thank you very much

sacred rune
#

Hi all, can somebody help me with the following:
I have put data from my pyscript into 2 sensors(min_price and max_price) which are updated each minute.
it's a min and max energy price.
With the statistic integration I can allow home assistant to have 2 additional sensors which are a minimum value of the past 15 minutes of min_price and the maximum value of the past 15 minutes of max_price.

How can I trigger this on the exact hour, 15minutes past, 30 minutes past and 45 minutes past the hour?
I know it must be a simple thing but i cant get my head around it.

frail dagger
marble jackal
#

"/15" will trigger on the whole hour, and 15, 30 and 45 minutes

#

no need for 4 triggers

frail dagger
#

Ah... right.

sacred rune
#

Thanks, right now I have the sensors created under my 'sensors.yaml' file.
I must move them to my 'templates.yaml' file and use a trigger with time pattern

Does this change the functionality of the statistics max_age 15 minutes?

sacred rune
#

Because when I use the statistics it just holds a min or max value 15 minutes, lets say from 14:20 untill 14:35 but i want it to hold it from 14:15 untill 14:30

feral trellis
#

Is there some mechanism to add an attribute to an entity (via customize.yaml) that has either a template value, or the value of another entity? Or are only static string/number values allowed?

I have a dehumidifier via a custom integration that have a action property, and I was hoping I could use the power draw from another sensor to set it to "DRYING" or "IDLE" according to the docs.

haughty breach
haughty breach
sacred rune
#

OK, done!

hallow sparrow
#

Is there a better way to have a template sensor trigger on specific hours beyond having a trigger for each hour? e.g.

template:
  - trigger:
      - platform: time_pattern
        hours: "6"
      - platform: time_pattern
        hours: "7"
      - platform: time_pattern
        hours: "8"
    action: ...
#

I want to trigger that template sensor to update every hour between 06:00 and 17:00 only.

lucid thicket
#

{{ 6 <= now().hour <= 17 }}

inner mesa
lucid thicket
#

Ya that’s probably better.

#

But we’re in the templates channel, dammit!

hallow sparrow
#

🤔 I tried adding a condition, but it caused an error. Can you point me to docs or examples of what you mean by template condition?

#

I had tried a time condition, to be clear.

lucid thicket
#

It’s on the same page RobC linked, just scroll up slightly

#

But there’s no reason the time condition wouldn’t work. We can help with errors. But should be in #automations-archived

hallow sparrow
#

This is for a template sensor in configuration.yaml, which is why I posted here. I'm happy to move it elsewhere if this isn't the appropriate channel.

lucid thicket
#

Well that is the problem

#

Trigger-based template sensors don’t accept conditions. At least, a conditions section is not supported.

hallow sparrow
#

Okay, yeah... that's what I figured from the error... which is what brought me here.

lucid thicket
#

You can either do a template trigger with all the logic, or you can do the hourly time pattern trigger and put some logic in the template where you are setting the state (and attributes, if you have them).

hallow sparrow
#

Let me un-XY this and present my use case to see if there's a better solution. I need to parse the result of the service call weather.get_forecasts with type twice_daily to extract the daily high temperature for a specific time window (my weather entity doesn't support hourly or daily for $reasons). and that time window is only available from 06 to 17:00, so i want to get it each hour (it may change during the day as forecasts update). I want that queryable in automation conditions.

#

if i query the service outside that time window, it would be unavailable... so either handle the unavailable case and don't update the value or limit the sensor update to those hours were the two paths i could think of.

#

a template trigger with all the logic
this is probably the sanest approach

lucid thicket
#

Yeah I’m still pondering but that is my gut reaction. Was also hoping someone else would jump in with a brilliant idea.

hallow sparrow
#

story of my life right there

#

thanks for the ideas/pointers/troubleshooting! much appreciated!

lucid thicket
#

No problem

marble jackal
mighty ledge
#

assuming that's local TZ

#

forecast times are UTC

warped blade
#

can anyone please help me figure out why this script I was using to make a noise machine isnt working anymore? it starts the playback on the device just fine. But it no longer stops after the amount of time i select from a drop down I created.

#
      == '2 hour' %}\n  02:00:00\n{% elif duration == '4 hours' %}\n  04:00:00\n{%
      elif duration == '6 hours' %}\n  06:00:00\n{% else %}\n  04:00:00\n{% endif
      %}\n"```
mighty ledge
#

we can't answer that without knowing all the available states for the input_select and where you're using the template.

warped blade
#

oh sorry

#

one sec

#

I have it set for 2 hours, 4 hours and 6 hours.

#

and I am using the template in a script that turns the media player on, starts a playlist then has that template as a delay template.

tight adder
#

Hi, I've created a statistics for wind speed as follow :
platform: statistics entity_id: sensor.solarws_windspeed_meter name: "Wind Speed Statistics" sampling_size: 10 max_age: minutes: 10
and I want to get wind gust with the follow sensor :
`- sensor:

  • name: "wind_gust"
    unit_of_measurement: "km/h"
    state: >
    {{ state_attr('sensor.solarws_windspeed_meter', 'max_value') }}`
    Problem, sensor always return null, but I can see in statistics that there is value recorded
mighty ledge
warped blade
#

oh, duh

#

im an idiot

mighty ledge
warped blade
#

I am going to put the actual script I have in here is that ok?

plain magnetBOT
#

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

warped blade
#

sorry if i seem slow. brain issues

mighty ledge
#

I don't see how that wait template ever worked

warped blade
#

that sounds about right. I have zero idea what im dong with templates

mighty ledge
#

You're using multi-line and single line notation for your template.

#

use one or the other

tight adder
# mighty ledge where are you putting each configuration?

I have a splitted configuration like this :
sensor: !include_dir_list ../entities/sensors template: !include_dir_merge_list ../entities/template
1st code is in the template folder and is working, 2nd is in sensor but return null

mighty ledge
warped blade
#

all i did was create it from the ui and enter the wait template chatgpt made for me. so if theres a better way for me to do it I will do that

mighty ledge
#

and you're probably using the wrong entity_id in your template

mighty ledge
warped blade
#

i see that now

mighty ledge
#

if you use a template, you need to stick with a single line template or multiline template

#

not both in 1

warped blade
#

ok, sorry i am still new to this and dont understand

mighty ledge
#
multiline: >-
  {{ ... }}
#
singleline: "{{ ... }}"
#

you're doing

blah: >-
  "{{ ... }}"
tight adder
tight adder
#

I've triple check this it's ok. I've pasted the value from the wheel in the graph

mighty ledge
#

The only reason it would be unavailable is if you have it in the wrong file, you have the wrong entity_id, or the attribute doesn't exist, or the attribute is none. You've confirmed it's in the correct file. So now you have to confirm the entity_id, attribute, and it's value.

warped blade
#

i am double checking everything

tight adder
#

From the states dev tools :
state_class: measurement
unit_of_measurement: km/h
icon: mdi:weather-windy
friendly_name: solarws Windspeed Meter

mighty ledge
#

notice the lack of max_value attribute?

tight adder
#

in fact i just see that the statistics template is not created :(....

mighty ledge
#

what do you mean 'statistics template'?

#

you mean the statistics entity?

#

that's not the correct lingo

#

it's not a template. A template is only the syntax between {{ }} {% %} and {# #}

#

everything else is a configuration and it's yaml.

#

so when you say 'statistics template', that doesn't make sense

tight adder
#

plateform sorry !

mighty ledge
#

that's your statistics entity, look in your logs for errors.

tight adder
#

no in fact the sensor is from my weather station. I need to check to understand why the statistics plateform was not created. Thx for the road !

mighty ledge
#

make it in the UI

tight adder
#

exactly !

mighty ledge
#

but you're making it in yaml...

#

statistics can be made from the UI. So if you are struggling or don't understand yaml, then make it in the UI.

#

Then, once the stats entity exists, you use THAT entity_id for your template, not the source of your statistic sensor.

tight adder
#

generaly I do all in yaml, but time to time, I made more bug than I resolve 😄

warped blade
#

@mighty ledge it was exactly like you said. i changed to using only 1 type of template in there. and wouldnt you know it the friggin thing turns off again.

obtuse lava
#

Good morning- I have a json response from Mealie that is captured at https://pastebin.com/raw/tXH1gjLi . I'm trying to figure out how to get each recipe name listed under the 'items' array to show up in a card. I looked at the restful integration to maybe create multiple sensors, but since it is an indeterminate number of values I can't hard code anything. The desired endgoal is phase 1) get all available recipes to be listed in a card; phase 2) be able to click on them and view the recipe.

So far I have created the following code that prints each available name:
{% for item in my_test_json['items'] %} {{ item.name }} {% endfor %}

but I don't know what to do with it or how to get that into a card. Any help is appreciated

stuck sedge
#

Is there a way to specify the icon color for a template sensor (defined in the UI) ?

marsh cairn
#

More a #frontend-archived question, but if you are using a tile card, you can define the color there.
If you want to be more crazy and change colors depending on status, you would need custom cards/integrations.

stuck sedge
#

Was thinking of having it red when the sensor reported an error, green when in the normal state and a few other colors for other states

lime olive
#

I don't know if I've missed a breaking change, but this used to work and now it doesn't
Can anyone notice anything wrong with it?

  entity_id: >-
    {% set ignore = [ 'switch.bedroom_main_2', 'switch.porch_blinds', 'switch.porch_left', 'switch.hs110_4', 'switch.cinema_tv_internet', 'switch.lounge_tv_internet', 'switch.iot',
    'switch.not', 'switch.virus2', ] %} {{ dict((states.switch|list)|groupby('state'))['on'] |
    map(attribute='entity_id') | list | reject('in', ignore)| join(', ') }}
service: switch.turn_off
#

I'm getting the following when I execute the script.

Error running action
not a valid value for dictionary value @ data['entity_id']. Got None

But when I try the template in dev tools not errors are showing. Weird

mighty ledge
#

that doesn't return a list

#

that returns comma separated strings

inner mesa
#

it's got some weird stuff in it, too

mighty ledge
#

yep

#

lots of unnecessary casting

inner mesa
#

{{ states.switch|map(attribute='entity_id')|select('is_state', 'on')|reject('in', ignore)|list }}

mighty ledge
#
{{ states.switch | map(attribute='entity_id') | reject('in', ignore) | select('is_state', 'on') | list }}
inner mesa
#

pfft

mighty ledge
#

reject before you select

inner mesa
#

yeah, thought about that after I hit enter, but I had to beat you

mighty ledge
#

lol

frail dagger
#

The ignore list would be a lot easier with labels, I would think. label_entities('ignored switches') | ...

mighty ledge
#

I'd only have labels for what I want to target

frail dagger
#

Same.

mighty ledge
#

then you wouldn't be throttled or traversing the whole domain

frail dagger
#

I've tried to avoid that a lot in my templates lately.

lime olive
#

Thank you both, was just testing what gpt gave as a solution and it seems to be working.

service: switch.turn_off
data_template:
  entity_id: >
    {% set ignore = ['switch.bedroom_main_2', 'switch.porch_blinds', 'switch.porch_left', 
                     'switch.porch_right', 'switch.hs110_1'] %}
    {% set switches_on = states.switch | selectattr('state', 'eq', 'on') | map(attribute='entity_id') | list %}
    {% set switches_to_turn_off = switches_on | reject('in', ignore) | list %}
    {% if switches_to_turn_off | length == 0 %}
      {{ 'none' }}
    {% else %}
      {{ switches_to_turn_off | join(', ') }}
    {% endif %}
frail dagger
lime olive
lime olive
inner mesa
#

you can tell it's ChatGPT because it's using data_template, which has been deprecated for many many years

#

and that it was crap

frail dagger
lime olive
frail dagger
lime olive
inner mesa
lime olive
inner mesa
#

is just a super verbose way of doing what petro and I gave you

#

please don't post ChatGPT stuff here

#

especially not in the context of "this is what chatgpt gave me, please help debug it"

lime olive
#

Anyhow, all good

#

besides, I didn't ask to debug that one. Just that this is what gpt spat out and it worked

plain magnetBOT
#

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

nocturne chasm
#

I keep getting Trigger Update Coordinator: Error executing script. Error rendering template for variables at pos 3: TypeError: '>' not supported between instances of 'int' and 'str'

#

and I am pretty sure it has to do with lines like this (states('sensor.other_birthdays_days') == '0')

#

but I cant get rid of the error

inner mesa
#

you're doing some string math in there

#

for instance:

 {% elif count_other == '0' and count_next > '1' %}
#

that seems like a fragment of a larger template as I can't see where you're setting count_other and count_next

#

in any case, everywhere you're using > and == you should be comparing against numbers

#

and you're currently comparing strings all over the place

nocturne chasm
#

let me get you the whole thing because honestly I have tried and cant figure it out. I get exactly what you are saying though

#

my assumption is that the error is from the first > so I tried to fix that hoping it would move to another operator and I never get past >

#

all the count variables are intergers so no parens around the numbers?

#

but states are strings so they should be |int > 0?

inner mesa
#

Just remove the quotes around all the numbers

#

You're turning the integers into strings and then comparing them with integers

nocturne chasm
#

yup. I figured it out

night citrus
#

Hello! I made a simple template that changes an icon based on a location sensor. Is it possible to extract the icon attribute in an entities card's icon field?

alpine sierra
frail dagger
alpine sierra
frail dagger
sturdy tendon
#

I recently got a oral-b io toothbrush and am trying to make a toggle of "have teeth been brushed". How as a helper preferably would i say if this value has been seen true and stay true until x timeofday then false. So far i have got it to go True if teeth brushed for 2 min but the second any other change occurs the duration changes to 0 and thus false. any help apricated my regular hass guy is on holiday atm

plain magnetBOT
#

@sturdy tendon Sadly we're not mind readers (any more anyway, not after the last time we tried). Please share the YAML and any errors so we can see what you've done.

sturdy tendon
# plain magnet

all i got so far:
{% set t = states('sensor.io_series_6_7_ff7e_duration') | int%}
{% if t >= 5 %} {{true}}
{% else %} {{false}}
{% endif %}

inner mesa
#

From the Oral-B integration docs, it says it offers this sensor:

Toothbrush state - whether the toothbrush is running, idle.

#

if you use that sensor and check for whatever the "running" state is (look at devtools -> States), then if that sensor is greater than zero, the toothbrush has run today

urban rune
winter forge
#

Hi guys!
I am a noob coder trying to make his "What is Maxi doing" template code better.
(This is my current messy code for this sensor:https://pastebin.com/dPSm0k89)

I've started by doing a decision tree diagram of how it should work.
Diagram --> https://i.imgur.com/nn2rfvl.png

I am now blocking on how to merge different branches within the Jinja2 template. Specifically all the "No" branches going to "Is there music playing somewhere".
My goal is to reduce the amount of duplicated code and checks.
Is there a way to send the code directly to "anchors" just like we do in windows scripting? (With goto)

runic pagoda
#

Hey friends. I have a list (or an array, whatever jinja calls it) and I want to find the first element based on some criteria. Is there a good way to do that?

inner mesa
#

the details depend on what criteria and what the list items are

runic pagoda
#

The list items are objects, the criteria is a key on that object

inner mesa
#

so, dicts

#

or what kind of objects?

#

I mean, some form of this is probably what you want:
{{ somelist|selectattr('somekey', 'eq', 'somevalue')|list|first }}

runic pagoda
#

yep, that did it thanks

#

well, is there a way to do the key where somekey is equal to a list of possible values? In JS it's like ['a', 'b', 'c'].includes('a')

#

perhaps in instead of eq?

#

yep, that worked

undone jungle
#

Hi all, is there a UI helper that can track state of 10 switches and report as binary.sensor when all are OFF/ON, or would this be purely a template territory.

undone jungle
#

But won't a group create a 'group' switch and not a binary sensor?

silent seal
#

You just need to use the "all entities" option

undone jungle
#

I know it's semantics though still, wouldn't want it actuated by mistake.

silent seal
#

No, a group is a kind of binary sensor in this case

#

When you add the group it asks you what kind of group, and that is the domain of the group it creates

undone jungle
#

Will give it a go now!

#

Thank you!

frail dagger
#

You could also do a template binary sensor that tracks your switches state if you really need a binary sensor. Just an additional option for you.

undone jungle
#

@silent seal maybe I am thick, but going for a group, when I select binary sensor, since switches are technically not binaries, they are not selectable.
When I select switch though, I can add them, which is creating a functional switch then.

silent seal
#

I must have misread before, I thought they were sensors already

undone jungle
silent seal
#

You'll probably be best off with a template binary template sensor

undone jungle
#

On to 'typing' from clicking.

plain magnetBOT
#

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

undone jungle
#

Would this be a sensible way of going about it?

#

I'd probably add an availability as well

frail dagger
#

Personally, I would label the switches in the UI and then use label_entities() instead.

undone jungle
#

Hmm.. may I ask why? What's the benefit - wouldn't labels change more often than entities?

silent seal
#

Not if you don't change them

#

But it also means you can easily get all of those devices elsewhere too

undone jungle
#

I've not 'subscribed' to the label 'craze' yet 🙂 Haven't had the time to play around with it.

#

May be my chance now... 😉

frail dagger
#

So, the way I would do it is:

{{ (label_entities('your label') | select('state', 'eq', 'on') | list | count) > 0 }}
#

Bascially, if any switch with that label is on, then the binary sensor will be true. Otherwise, it'll be false.

undone jungle
#

And availability-wise?

#

So that any physically ON switch in a unavailable state doesn't make me heat and cool at the same time

frail dagger
undone jungle
#

In other words : {{ (label_entities('Floor heating') | select('state', 'eq', 'on') | list | count) > 0 }}

frail dagger
frail dagger
undone jungle
#

Needs both correct case and an underscore for spaces

#

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

frail dagger
#

Where did you set the label? On thhe device or the switch entity itself?

undone jungle
frail dagger
#

You can't put YAML into the editor.

#

It only accepts templates.

#

Only put: {{ (label_entities('Switch') | select('is_state', 'on') | list | count) > 0 }} in.

#

Plus... you can also just use a template binary sensor helper in the UI if you want to 😉

frail dagger
#

Ok. Test JUST the template in the editor.

undone jungle
#

This may be a bug or something I don't understand, but it works differently with and without the underscore in the name.

frail dagger
silent seal
#

label_entities can take the ID or the name as a parameter

undone jungle
#

Then without the underscore it works just fine, like it does for you

undone jungle
frail dagger
#

Eh, then go with the name. Or you could add a label_id() call in there, but that's just fluff.

undone jungle
frail dagger
#

Yay?

#

It works?

#

lol

#

I'm guessing that the valve.* entities are correct, yes?

undone jungle
#

Yes, they are!

frail dagger
#

Woot! Throw that into your YAML (or helper in the UI if you want) and let that puppy go!

undone jungle
#

just one is a little strange, which must be some issue in my entity naming or labeling

undone jungle
frail dagger
#

Possibly. Like, you have a label at the device level and then use the same label at the entity level, it seems to get a bit weird.

frail dagger
undone jungle
#

Didn't realize the wealth of possibilities!

frail dagger
undone jungle
#

The only thing that still eludes me is how I should handle availability issues

#

These Tuya based floor heating switches are at times finicky leading to switch being unavailable while on for an hour or so, and I'll be airing the house while heating.

silent seal
#

So do you want to assume unavailable is on or off?

frail dagger
#

You don’t have to. The select takes care of that already.

#

If the state of the valve is unavailable, it won’t be selected.

#

If they are all unavailable, the count will return 0.

undone jungle
#

Well that is the problem right there.
It needs to be the opposite!
The unavailable being assumed OFF is incorrect for this use case, because unavailable can be ON, which is when I don't want to pump cold air into the house.

silent seal
#
{{ (label_entities('Switch') | expand | selectattr('state', 'in', ['off', 'unavilable']) | list | count) > 0 }}
undone jungle
#

Thank you both so much! My automation is coming along nicely.

marble jackal
silent seal
#

I was sure you could do that but it wasn't working for me yesterday. I guess my original entity list didn't have any of those

slow basin
lucid thicket
#

Since 2024.7, you also have the parameter max_sub_interval which can improve accuracy in certain scenarios also

robust star
#

So i have a bunch of zone triggers and these trigger notifications tailored to the zone that was triggered in one automation, this works but when my GPS flutters i will get multiple notifications within a minute for entering that zone. Can i use a template to delay the time between repetitions of the same zone?

frail dagger
robust star
#

But once the gps leaves the zone it would reset the minute right? Meaning if it’s bad it would never trigger

frail dagger
mighty ledge
#

just understand that you can't leave a zone then reenter it, legitimately

inner mesa
#

Sorry, you left home and cannot return

#

Need to buy a new house

bronze prawn
#

https://dpaste.org/3U7ZD#L15

Can someone take a look at my automation and tell me what I am doing wrong? Pretty sure I am not formatting the dictionary call in the highlighted line correctly but can't figure it out.

#

I see in traces that the value is not being populated

marble jackal
#

Is the variable defined correctly? Because you used the multi line indicator I think it's a string now, and not a dict. You could just use a YAML mapping.

bronze prawn
#

First time messing around with dictionary (I think) so very well could be incorrect. Can you guide on how to define?

inner mesa
#

I think you're right. Just define the dict in YAML

bronze prawn
#

Hmm. I may have done that before.

marble jackal
#
soundmachine_dict:
  thunder: http://...
  ocean: http://...
#

Like this

bronze prawn
#

ah.. thanks

#

Yep. Working now. Thanks guys!

marble jackal
#

Other solution would have been to wrap it between {{ and }} as that would make it a template and then it would be parsed to a dict.

empty bone
#

Hello and happy

#

Well I didn't mean to post that. I was going to say Hello and happy Sunday to you all. Is there anyone on here that might be willing to share or tell me where I might find a weather template write up using tomorrow.io. So that I can see how t owrite and configure the weather template.

bronze prawn
#
service: conversation.process
metadata: {}
data:
  agent_id: conversation.chatgpt
  text: >-
    keep your answer to two or three sentences.  provide your answer as python
    dictionary.  return only the dictionary and no other data.  Do not include
    back ticks or the word python.  The dictionary should include my original
    question with key of question and your answer with the key answer.  My
    question is:  {{ trigger.slots.question }} 
response_variable: ai_answer

So I'm using this automation and it appears to be sending me back a python dictionary:

#
{
"question": "what is the date",
"answer": "Today's date is 2024-07-21."
}

But I can't parse it. I'm guessing it is a string and not an actual dictionary. Any tips on converting it?

inner mesa
#

what does "But I can't parse it" mean?

bronze prawn
#

Apologies:

set_conversation_response: "{{ai_answer.response.speech.plain.speech}}"

This will give back the dictionary I posted above, but when I try to do:

set_conversation_response: "{{ai_answer.response.speech.plain.speech.answer}}"

I get nothing back. Perhaps I'm not structuring that correctly

bronze prawn
#

tried asking it for a YAML formatted dictionary and still can't pull just the answer value

haughty breach
#

{{ ai_answer.response.speech.plain.speech.answer | from_json }}

bronze prawn
#

traces shows this as the changed variable:

ai_answer:
  response:
    speech:
      plain:
        speech: |-
          question: what time is it
          answer: 19:24:09
        extra_data: null
haughty breach
#

Sorry, I forgot to move answer:
{{ (ai_answer.response.speech.plain.speech | from_json)['answer'] }}

bronze prawn
#

ohhhhh

bronze prawn
bronze prawn
empty bone
#

Where can I go to get some help or guidance on my template? Everytime I post in this Discord "templates" under Home assistant no one responds to my request. Please can someone tell me a better place to locate a person who can assist me. I would very much appreciate it.

inner mesa
#

Try the forum. We're all volunteers who answer what we can when we can

#

looking back through your post history here, I see plenty of people resonding to your posts 🤷

#

so maybe adjust expectations

lucid thicket
hollow brook
#

Hi, i want to turn on a fan is the dew point difference between outside and inside is > 5. Can anyone help? I installed thermal comfort, it calculates the dew points. I tryed to make a helper that calculates basement dew point - 5, but this does not give me any values

#

This is my template: {{ sensor.keller_taupunkt - 5 }}

steady spindle
hollow brook
#

@steady spindle thanks... is moves the comparsion in the helper, right? How do i create such a helper?

#

Sorry... but io am new to HA... i need to find the starting points first 🙂

steady spindle
#

Helper using a template
yeah ...it's never easy the first time 🙂 -)

hollow brook
#

But... do you have any idea, why my helper did not work? Do i need the states function and return a result?

steady spindle
#

let me try. I just gave you a quick and dirty solution. not fully tested. just the idea 😉

hollow brook
#

forget it... i got it 🙂

#

{{ states( 'sensor.keller_taupunkt' ) | float() - 5 }}

#

Now i know 2 ways to solve that problem... thanks 😉

marble jackal
#

In case you're lazy (like me)... There is no need to add parenthesis to filters if you don't add parameters

#

So | float is fine

empty bone
hushed bison
#

I've created a custom template sensor which is calculating the fraction between two other sensors and return a float value. However, in history view it is presented as a bar of numbers and not as a graph. I've searched the docs for a suitable device class, but none really fits and there is no unitless "fraction" or "ratio"-class. Any ideas what I can do to get it displayed as a graph?

inner mesa
#

don't you just need to assign a unit_of_measurement?

lofty mason
hushed bison
hushed bison
inner mesa
#

Right, makes sense to use state_class. I didn't know that had the same effect

river mortar
#

Good day,

I am trying to display the value of an attribute from my entity. I realize now that I am having such a time because its then nested under a property within that attribute. Is there a way to isolate that property?
[2:59 PM]
This is specifically with a Eufy Lock.

frail dagger
#

{{ state_attr('your_lock_entity', 'attribute_name') }} should work.

river mortar
#

{{ state_attr ('binary_sensor.front_door_debug_device' , 'locked') }}

#

So thats what I have but it reports null

#

However I can watch it change under properties when I lock or unlock the door from true to false

#

Its like I need it to drill down one more level into the properties to report the state change but I cant find anything that mentions this online

frail dagger
#

Why are you doing it that way? Isn't the Eufy lock exposed as a lock entity?

river mortar
#

negative. I followed all the walk thrus I could and it reports as a debug device

#

I was just happy I got it to show up at all

frail dagger
#

Which integration is it? That seems... weird

river mortar
#

The only one I could get to report was Eufy Security but I needed to add a add on to get that to work

#

But with that the door lock somehow showed up but not as a lock

#

For clairification. I am a super noob to HA and knowing what I know now I would have bought a few different things haha

frail dagger
river mortar
#

Yes

#

I didnt install the go2rtc as I am not using it for cameras

frail dagger
#

That's weird that there is no lock entity created.

#

You might want to remove the integration, restart HA and then readd it again. Because something is not right there.

river mortar
#

Ok sounds good. Will do

river mortar
#

Well from everything I can find it should be reporting as a lock. Its supported. Everything checks out. But it still shows up as the wrong device

#

Cancel last

#

I am a moron

frail dagger
#

lol yes?

river mortar
#

It helps if you show the entites you want to control

#

I knew this.......

frail dagger
#

lmfao yeah, that does help.

river mortar
#

I need to start smoking again.......Good god. Well thats an entire day I will never get back

frail dagger
#

Eh, it happens. At least you got it figured out.

river mortar
#

I think I am basically a Hacker now

elder quarry
#

I've been searching, but can't find anything specific in the release notes, forums, etc. Has something recently broken old templates? I didn't realize I was using old templates, but on the Latest container, I am getting 3 or 4 of these errors

I knee-jerked my version back to 2024.5.5, and it seems to be working. I believe I was on 2024.4 previously.

silent seal
#

My speculation is that there's something in your template that's not valid, and the definitions tightened when the new feature was added, hence the failure.

elder quarry
#

Cheers, thanks. I think I'll probably have to figure out the right way to convert these

#

Was hoping there was a quick and obvious issue.

inner mesa
#

if there's more to the log than that, maybe there is

#

that usually indicates something that would be caught by checking the config

empty bone
#

I have a section of a weather template I am working on. The YAML checker website is saying I have duplicate mapping keys in a particular section. I looked up what is meant by "duplicate mapping keys" and the stackoverflow web site mentions merging parameters into a single list. Except I need someone to look at this section of code and tell me how I am supposed to "merge the parameters" and still get out seperate information for each unique_id. Can I post a section of the code? and how should I go about doing that so someone can take a look?

plain magnetBOT
#

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

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

inner mesa
#

it just means that you have two identical keys at the same level in the YAML

#
foo:
foo:
empty bone
#

Would you RobC if you are avalible please take a look at my section of code. At the bottom is the error I'm getting from the YAML checker website. What I am gathering is it wants me to eliminate the duplicate mapping key of the unique_id I have for "tree-pollen" if I do that how will the code calculation know the "tree-pollen" is separate from the "grass-pollen" or the "weed-pollen" I'm a bit baffled. http://pastie.org/p/1G97Esp8kXdHJTRJ9VycuU

inner mesa
#

several issues there

#

first, you're missing the fact that you need to format the sensor blocks as list items

#

see this from the example in the docs:

    sensor:
      # Keep track how many days have past since a date
      - name: "Not smoking"
        state: '{{ ( ( as_timestamp(now()) - as_timestamp(strptime("06.07.2018", "%d.%m.%Y")) ) / 86400 ) | round(default=0) }}'
        unit_of_measurement: "Days"
#

specifically, the leading "-"

#

each sensor block needs to be another list item, and you're getting that error message because you just have one big block with the keys duplicated over and over

#

second, you haven't provided a name for the sensors beyond the first one

#

third, you just have some bad formatting in there

#
        {% else %}
        Unknown
        {% endif %}known
        {% endif %}
#

fourth, you can set up a variable mapping in the action to greatly simplify all that

empty bone
#

Thankyou for your input and feedback. Do you have a link to some doc where I can look up how to break up the sensor block. And how to setup the variable mapping so that I can simplfy it?

inner mesa
#

just the docs, really

#

I'm fixing it for you

empty bone
#

Hey RobC I really appreaciate your help. And I aprreciate your time in fixing it. That will give something to look at a see what exactly you are talking about.

#

That is awesome and very simplified indeed! Thank you again!

inner mesa
#

there's still a bunch wrong with it

#

I'm going to stop here

#

mainly because I don't really know what you're doing

#

you seem to want to get the forecast, but then use other entities as the state for the template sensors

#

you do one or the other, but not both

empty bone
#

I think I got the weather template all figured out. I got the green check at the YAML checker website. So I went and posted it into my configuration.yaml file. And I got the green check mark. I saved it and then I went to Developer Tools and hit "check configuration before I went to restart. And it gave me the following error message.

#

Configuration errors
Error loading /config/configuration.yaml: while scanning for the next token
found character '\t' that cannot start any token
in "/config/configuration.yaml", line 294, column 1

#

Ok, never mind. I got it fixed and it all checked out.

inner mesa
#

that was a tab. only spaces, no tabs

elder quarry
plain magnetBOT
#

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

robust star
#

is it possible to convert brightness_pct to brightness in a template? its for the mqtt.publish service

#

The first goes from 0 to 100 while the other goes from 1 to 255.

frail dagger
marble jackal
#

multiply with 2.55 and then round to 0 decimals?

inner mesa
#

To be fair, multiplication is hard 🙂

robust star
#

yeah templating is rather new to me but i could have done a little more research, thanks!

frail dagger
robust star
robust star
# frail dagger No worries. Just keeping it simple. 😊

template ended up looking like this:

{
  "color_temp": "{{state_attr('switch.adaptive_lighting_upstairs', 'color_temp_mired')}}",
  "transition": "0",
  "brightness": "{{(state_attr('switch.adaptive_lighting_upstairs', 'brightness_pct') | multiply(2.55) | round)}}",
  "state": "OFF"
}
inner mesa
#

I still feel like you're following some documentation that tells you to use MQTT (like Z2M) when you can just use native HA service calls (callback to #templates-archived message)

robust star
#

If i were to use the light.turn_on service and set the color temperature while keeping the light off the color temperature doesn't actually change.

#

with mqtt.publish it is possible to do so, hence why i use that service for this specific usecase

robust star
#

@inner mesa or did i misunderstand what you said? Still pretty new at this.

inner mesa
#

no, I think you're right

#

you cannot change the brightness of a light without also turning it on

#

perhaps you can via Z2M directly through MQTT

#

or the color temp, I guess. I don't have any such lights, so can't say for sure

robust star
#

Yeah the color option execute_if_off helps and doing it like above keeps the light off

marble jackal
#

You might need to cast it to an integer if you use it like this

robust star
inner mesa
#

Follow |round with |int

#

But if it works, it works

robust star
#

ah thank you :)

rustic hull
#

does the statistics platform only work for the last 10 days in the recorder? I'm trying to use it on a template sensor that is included in long term statistics, I'm only getting very recent data (based on count and coverage ratio). Any way of getting averages from long term statistics?

#
  • platform: statistics
    name: Switch Usage Stats Last Year
    entity_id: sensor.switch_usage
    unique_id: sensor.switch_usage_stats_last_year
    state_characteristic: average_step
    max_age:
    days: 365
lofty mason
#

Any way of getting averages from long term statistics?
Aside from a frontend statistics card, no you cannot.

Unfortunately statistics integration just uses your recorder history and is completely separate from LTS.

rustic hull
#

thats unfortunate

#

I guess my next best option is to run some python script directly on the SQL DB?

lofty mason
#

There is SQL sensor integration, maybe you can do something with that

unique turret
#

How do add multiple state entities here:
{% set state= expand(states.light.kitchen) | selectattr( 'state', 'eq', 'on') | list | count %} {% if state > 0 %} | {{ state }} light {% else %} {% endif %}

inner mesa
#

that's a weird one

#

what are you trying to do there?

#

I mean, I guess this is what you're looking for:
{% set count = ['light.one', 'light.two']|select('is_state', 'on')|list|count %}

unique turret
#

Just display, how many lights are in a light group tbh

#

so basically, it will show multiple groups of lights, not indivual ones

green yacht
#

I have an apollo MTR presence sensor, it has 3 definable zones, each zone will show a count of "Zone X All Target Count" which is really helpful for writing conditional automations.

For my dashboard I really want to represent presence as "Detected" or "Clear" to match the rest of my presence sensors. Basically if the "target count" is > 0 the result should be "Detected" if the target count is 0 the result should be "Clear". Do I accomplish this with a "Template sensor?"

lofty mason
green yacht
#

thank you! digging into that now. Thanks for pointing me in the right direction.

slender adder
#

Question, im trying to make a response notification, and where i dont respond (aka timout)
It will the device turn off\

#
{{ wait.trigger.event.data.action == continue_on_timeout }}
#

does that work?

green yacht
elder quarry
green yacht
lime pasture
#

Hi all. Just got an aqara G4 can't figure out how to get the button press automations working in HA. It is not a binary sensor / sensor, but instead an event. It shows up on the device, with an updated timestamp when pressed. The event type is single_press. But it doesn't show in developer tools > events when I listen for single_press events. As the event itself is just a timestamp I don't know how to work with it.

I found a blueprint that that I could use to get a notificaton with snapshot from camera and some buttons to be able to open the aqara app, open our front gate etc. But don't know how to trigger from the event.

wet lynx
#

it has the brackets and separate lines which arent allowing my code to work

wet lynx
#

ive been fighting this issue for 3 days holy crap ive exhausted google

marble jackal
plain magnetBOT
#

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

fossil venture
#

Usually contact binary sensors are 'on' when doors are open, so if that is the case for your sensors you would need to look for {{ 'on' in doors }}

#

Why did you call it "all doors closed" if you want it on if any are open?

tawny coral
#

true, too many double negatives 😄

#

so on = open and off = closed

#

right

#

{% set doors = [
states('binary_sensor.vardagsrum_altandorr'),
states('binary_sensor.kok_altandorr_mot_baksida'),
states('binary_sensor.entre')
] %}
{{ 'on' not in doors }}

#

then this would make more sense?

#

still a double negative, shit

#
        friendly_name: "All Doors Closed"
        value_template: >-
          {% set doors = [
            states('binary_sensor.vardagsrum_altandorr'),
            states('binary_sensor.kok_altandorr_mot_baksida'),
            states('binary_sensor.entre')
          ] %}
          {{ 'off' in doors }}
#

This makes sense then

tawny coral
mighty ledge
#

that will report if 1 in the 3 is off

#
{% set doors = [ 'binary_sensor.vardagsrum_altandorr', 'binary_sensor.kok_altandorr_mot_baksida', 'binary_sensor.entre'] %}
{{ doors | select('is_state', 'on') | list | length == 0 }}
#

that will tell you if all doors are off

#

You could also make a binary sensor group and just look for it being off.

fossil venture
#

Ignore their sensor name they actually wanted "binary sensor to on if any of the doors are open"

#

Which now I think about it could be done a lot simpler with a group.

mighty ledge
#

ok, then just a binary sensor group

fossil venture
#

snap

#

@tawny coral look 👆

plain magnetBOT
#

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

arctic sorrel
#

Do share the error 😉

neat crag
#

Right here 😄 sorry
2024-07-25 09:41:30.993 ERROR (MainThread) [homeassistant.config] Invalid config for 'template' at configuration.yaml, line 29: invalid template (TemplateSyntaxError: unexpected ')') for dictionary value 'sensor->0->state', got "{% if is_state('binary_sensor.garage_sensor', 'on') and is_state('switch.garage_door', 'on') %}\n opening\n{% elif is_state('binary_sensor.garage_sensor', 'off') and as_timestamp('states.switch.garage_door.last_updated') < 5) %}\n closing\n{% elif is_state('binary_sensor.garage_sensor', 'off') %}\n open\n{% else %}\n closed\n{% endif %}\n"

#

I dont know if "states.switch.garage_door.last_updated" is correct syntax? I searched in the docs, etc. but it seems to be the correct structure.

#

or maybe i take the wrong approach? all i want to achieve is to check when the switch was pressed the last time and compare it to the current time

arctic sorrel
#

Looks lke the problem is a stray ), but I'll let the template gurus help when they're around

neat crag
#

thank you anyways 😉
the final goal is to have the garage door in opening or closing state when the button was pressed max 18 seconds ago (door needs about 18 seconds to open and close)

marble jackal
#
< 5)
   ^ there
neat crag
#

i changed it to

now() - as_timestamp('states.switch.garage_door.last_updated') < 5

at least the error is gone, now i get the state "unknown"

marble jackal
# neat crag thats the counterpart of this first one -> (now() , do i need to remove the lead...
{% if is_state('binary_sensor.garage_sensor', 'on') and is_state('switch.garage_door', 'on') %}
  opening
{% elif is_state('binary_sensor.garage_sensor', 'off') and as_timestamp('states.switch.garage_door.last_updated') < 5) %}
  closing
{% elif is_state('binary_sensor.garage_sensor', 'off') %}
  open
{% else %}
  closed
{% endif %}

This is the template from your error message, there is no (now() in there

marble jackal
#

Or do
now() - states.switch.garage_door.last_updated < timedelta(seconds=5)

neat crag
neat crag
#

Thank you sir for your help!

neat crag
restive swift
#

Hi folks, I'm trying to include the numeric state that triggered an automation in the message (I have an automation that includes 3 sensors with an upper or lower threshold in each, so 6* 'or' when triggers. it's close - I can see the values in the trace but not prettily in the message
message: Voltage out of spec ({{ trigger.entity_id }} to {{ trigger.to_state }})

snow ember
#

Hi, i have an agenda trigger that tell's me of an upcoming appointment. Now it says just that there is a appointment coming. Is there a way to know for which appointment the trigger is fired? And @arctic sorrel suggested that a ⁠template can do that, probably. Could someone suggest on how to do this properly?

frail dagger
red badge
#

i've got a template i want to use in a template binary sensor to combine three different binary sensors with some simple rules https://dpaste.org/oT46v#L7
the template editor says this template will only be listening too the first two of the tree sensors. any idea why? if i put the third sensor on its own line, its listed

frail dagger
red badge
#

ah right. so i can safely ignore it

frail dagger
#

Yup.

scenic verge
#

i currently have templates in configuration.yaml. how do i move them to templates.yaml?

#

if i add "template: !include templates.yaml" studio code server says it already exists...which is true.

#

so i suppose im not allowed to include templates of a file, AND have templates in configuration.yaml at the same time....So i need to move.

frail dagger
#

Just move them to templates.yaml and save the file.

scenic verge
#

does anyone have a weather forecast template example for precipitation for next 2 hours?

#

or 1h...i can try to mess with it and see if i can get it working for myself.

snow ember
scenic verge
#

always a bit scared stuff breaks by messing with so much code.

marsh cairn
scenic verge
marsh cairn
#

https://dpaste.org/hnLUQ
That creates one sensor with all available hourly and daily forecasts as JSON in attributes.
That JSON can be processed in other templates.

scenic verge
marsh cairn
#

I created a weather entity to show the forecast for tomorrow.

scenic verge
#

i also tried to modify the weather forecast example to make it work for me...but no luck. this is what i have now:

      - platform: time_pattern
        hours: /1
    action:
      - service: weather.get_forecasts
        data:
          type: hourly
        target:
          entity_id: weather.openweathermap
        response_variable: hourly
    sensor:
      - name: Precipitation Chance 1h
        unique_id: precipitation_chance_1h
        state: "{{ hourly['weather.openweathermap'].forecast[0].precipitation_probability }}"```
But it does not create a entity.
marsh cairn
marsh cairn
scenic verge
marsh cairn
#

If the data structure is correct, it should.
That's why I added the triggers for HA start and template reload. To have the data available immediately

#

Did you reload the templates?

scenic verge
#

does this use a API call as well to reload these?

#

or does it grab data from whats currently available from the openweathermap integration, and depends on polling time of that integration?

scenic verge
#

reloading templates in developer settings did not help.

frail dagger
#

If this is your first template sensor, you need to restart HA.

scenic verge
#

my configuration.yaml shows: template: !include templates.yaml

#

my templates.yaml has:

  - trigger:
      - platform: time_pattern
        hours: /1
    action:
      - service: weather.get_forecasts
        data:
          type: hourly
        target:
          entity_id: weather.openweathermap
        response_variable: hourly
    sensor:
      - name: Precipitation Chance 1h
        unique_id: precipitation_chance_1h
        state: "{{ hourly['weather.openweathermap'].forecast[1].precipitation_probability }}"
frail dagger
#

Remove the template:. It's not valid in included files.

scenic verge
#

now to figure out how to copy this sensor to include 2h results. is that the number in .forecast[1].precipitation_probability?

frail dagger
#

Maybe forecast[2]?

scenic verge
#

i guess forecast 0 is the hour ahead, and 1 stands for 60-120 mins? 🤔

#

and still wondering if this template thing will use a api call on openweathermap or not?

frail dagger
#

Perhaps. IIRC, OWM has their API response published somewhere. You'd just need to scan that JSON and see what it returns. And yes, it will use api calls.

haughty breach
frail dagger
#

Really? Huh... Wasn't that one of the things that was mentioned with forecasts were removed from the state machine?

scenic verge
frail dagger
# haughty breach I could be mistaken...

Honestly, I don't remember off the top of my head. I remember the megathread that came out with the change and I could have sworn there was something there about consuming api calls on OWM (and maybe others?). I'm not sure.

haughty breach
frail dagger
scenic verge
#

Does anyone know?

scenic verge
#

(the forecast[0]) number

lucid thicket
# scenic verge (the forecast[0]) number

That is the number of the item in the list that it is picking out, and is zero-indexed. So whatever list is returned, [0] is the first item, and [1] is the second item, and so on

scenic verge
#

i currently have copies of the following, with different entity name and id, and then just the forecast[1] number changed....but both entity's that were created, return the same precip chance... 😦

#
    - platform: state
      entity_id: weather.openweathermap
  action:
    - service: weather.get_forecasts
      data:
        type: hourly
      target:
        entity_id: weather.openweathermap
      response_variable: hourly
  sensor:
    - name: Precipitation Chance 1h
      unique_id: precipitation_chance_1h
      state: "{{ hourly['weather.openweathermap'].forecast[0].precipitation_probability }}"```
lucid thicket
#

You can return the entire forecast by removing after the word forecast starting with the bracket, so it ends like …forecast }}"

scenic verge
#

but where do i read that list then

#

ah with a new entity it creates.

lucid thicket
#

However you may run into the 255 character limit on the state, so I’d recommend you put that into an attribute instead of the state

lucid thicket
scenic verge
lucid thicket
#

No, keep the trigger unchanged. Keep the state template unchanged. After the state: line, add an entry for attribute: then another line my_attribute: "{{ stuff }}"

marble jackal
#

Just run that service call in devtools > services, and you'll see the entire list

#

Well, actually it's a mapping, containing a list

lucid thicket
#

Well that is definitely the easier way to do it