#templates-archived

1 messages · Page 52 of 1

marble jackal
#

We won't know without seeing your configuration. But it seems off-topic here. Unless you have jinja templates in that configuration.

graceful widget
marble jackal
#

you claim there the template doesn't work. What do you mean with that? The template works fine for me (using another integration, because I don't use ZHA)

haughty breach
#

"i need entity_idand friendly_name ...."

entity_id: {{b}} 
friendly_name: {{state_attr(b, 'friendly_name')}} 
lyric comet
#

Do you want the name of the Device or the friendly name of the Entity?

arctic jolt
#

i've been staring at this for days. i'm trying to get my alarm on my phone to trigger... anything honestly. I've got the sensor entity for next alarm and I'm trying to use this template:

platform: template
value_template: >-
{{now().strftime('%a %h %d %H:%M %Z %Y') ==
(((state_attr('sensor.pixel_5a_next_alarm', 'Time in Milliseconds') | int /
1000) ) | timestamp_custom('%a %h %d %H:%M %Z %Y'))}}

#

I think it's because it's only updating by the minute (that's what the template editor suggests)

#

but adding :%S to the end of those values doesn't seem to fix it

lyric comet
#

I think you are trying to do this the wrong way. Do you have a sensor which contains the time of the next alarm? If so you should be able to trigger something based on the time of the sensor in an Automation.

#
platform: time
at: input_datetime.alarm_time

Is what i use to turn on the radio in the morning. Which is based on my calendar events.

#

every second is fine if you are using the date time unless you reguarly set your alarm less than one second before you want it to go off.

marble jackal
#

just use sensor.pixel_5a_next_alarm in a time trigger

autumn flower
#

I ended up calculating a "seconds until alarm" value in a template sensor, because it seemed the easy way to be able to start things (like "sunrise simulation" lighting) a fixed duration prior to the alarm

  unit_of_measurement: "seconds"
  state: "{{ (as_local(as_datetime(states('sensor.xq_at52_next_alarm'))) - now()).total_seconds() }}"```
Means I can do "numeric state below 1800" as the trigger.  Hasn't failed me yet.
marble jackal
#

In that case I would suggest to just create a template sensor with device_class: timestamp which has a datetime 30 minutes prior to your alarm sensor

autumn flower
#

I have a couple of automations with different offsets; heating/cooling gets adjusted at -1h, bedroom lighting at -30m, other house lights at 0m

marble jackal
#

okay, mkaes sense then

autumn flower
#

Yeah it's definitely ugly, but it's a nice one-size-fits-all solution

marble jackal
#

I would add an availability template for when no alarm is set (you will get errors otherwise) and exclude it from you recorder

plain magnetBOT
#

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

terse palm
#

hi, i have a template sensor that is returning a float value, but when i view the device history in home assistant , it shows up as a bar chart of the numeric values (as if it was a string value), not a histogram / statistics graph like i want to see, is there something extra i have to do to this sensor to get it treated as a numeric value?

crimson lichen
#

command_line today was error:
homeassistant.components.command_line.utils
['Command failed (with return code 1): cat /sys/class/thermal/thermal_zone2/temp']
|--> 08:32:24 Mon, 28-Aug

command_line.yaml:
#Nhiệt độ CPU máy chủ Hass

  • sensor:
    name: "cpu_temperature"
    command: "cat /sys/class/thermal/thermal_zone2/temp"
    unit_of_measurement: "°C"
    value_template: '{{ value | multiply(0.001) | round(2) }}'
    I use Intel NUC.
    Thanks
cerulean karma
#

Hi, I have got a energy sensor (reading values from a tasmota power smartmeter) that sometimes (ever 10+ days, so very rare) writes "unknown" instead of a value into the DB. The Sensor is total_increasing and so the next valid value leads to a jump from 0 (unknown) to ~6600 (which is the actual value). How could I take care that there only get valid values into the DB?

#

`- sensor:

  • name: Strom Zählerstand
    unique_id: strom_zahlerstand
    unit_of_measurement: kWh
    state_class: total_increasing
    device_class: energy
    state: >
    {% if is_number(states('sensor.tasmota_mt681_total_in')) %}
    {{ float(states('sensor.tasmota_mt681_total_in')) }}
    {% else %}
    {{ float(states('sensor.strom_zahlerstand')) }}
    {% endif %}`
marble jackal
#

I would use a trigger based template sensor:

- trigger:
    - platform: state
      entity_id: sensor.tasmota_mt681_total_in
      to: ~
  sensor:
  - name: Strom Zählerstand
    unique_id: strom_zahlerstand
    unit_of_measurement: kWh
    state_class: total_increasing
    device_class: energy
    state: >
      {% set to = trigger.to_state.state %}
      {{ to if to | is_number else this.state }}
cerulean karma
#

thanks 🙂

marble jackal
#

It needs an initial state change from the source sensor to get a first value after you changed it

cerulean karma
#

It seems so work fine

#

And what is the important point of this template that there will be no bad values any more?

#

...as said this occurs only every 10+ days. So I need to wait a few weeks to be sure it works as I am hoping

graceful widget
marble jackal
#

That part checks if the new value is a number (which unknown is not) and if that is not the case, it will return the current state of the template sensor (this.state)

cerulean karma
#

ok fine, thanks

golden plaza
#

Don't know why I didn't try this earlier. Thank you

cerulean karma
#

@marble jackal the use of this.state is new to me, is the use of it right in this template? I just used {{ 0 }} in the else statement...

#

`- sensor:

  • name: "Absolute Luftfeuchtigkeit oben"
    unique_id: "AbsoluteHumidityOben"
    unit_of_measurement: "g/m^3"
    state_class: "measurement"
    state: >
    {% if is_number(states('sensor.temperature_humidity_sensor_2f20_temperature')) and is_number(states('sensor.temperature_humidity_sensor_2f20_humidity')) %}
    {{ ( 1000*e**(19.016-(4064.95/(float(states('sensor.temperature_humidity_sensor_2f20_temperature'))+236.25)))100/(461.66(float(states('sensor.temperature_humidity_sensor_2f20_temperature'))+273.15)) * float(states('sensor.temperature_humidity_sensor_2f20_humidity'))/100 | float) | round (1) }}
    {% else %}
    {{ this.state }}
    {% endif %}`
marble jackal
#

this.state refers to the state at the moment the template is rendered (for trigger based template sensors the moment of the trigger)

#

looks fine this way

cerulean karma
#

ok thanks 🙂

molten frost
#

Hey could someone pleas help me figure out what i am missing? I have the following sensor:
last_soil_humidity: value_template: > {% if has_value('sensor.diymoresoildht11_analog_range1') %} states('sensor.diymoresoildht11_analog_range1') {% else %} states('sensor.last_soil_humidity') {% endif %}

#

and my frontend shows it as a string :/

#

So my history is saying my value is states('sensor.diymoresoildht11_analog_range1')

mighty ledge
#

these lines need to honor pin 2

#

states('sensor.last_soil_humidity')

#

states('sensor.diymoresoildht11_analog_range1')

molten frost
#

Sorry but what does "honor pin 2" mean?

#

Oh wow sorry I am new to discord - now I see that I'm missing {{ }}. THX!

mighty ledge
granite goblet
#

Derive Three-Phase Motor State

silent vector
#

Can I generate attributes in a template sensor dynamically using a loop? I have a rest sensor with attributes that could change on the fly. I would use a template sensor to summarize the data.

It's a flight price API

crimson lichen
plain magnetBOT
#

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

marble jackal
floral shuttle
#

needing to set an input_datetime programmatically, I noticed that {{as_timestamp(state_attr('script.slapen_select','last_triggered'),0) |timestamp_custom('%H:%M',default = none)}} does not set the correct year 😉 what would be the best format to do that? Testing {{as_timestamp(state_attr('script.slapen_select','last_triggered'),0) |timestamp_custom('%Y-%m-%d %X',default = none)}} gives the right format, but not sure if this is only in template editor. Seems so terribly verbose/hacked/complex...

#

to get the idea:```
trigger:
platform: state
entity_id: script.slapen_select
action:
service: input_datetime.set_datetime
target:
entity_id: input_datetime.sleeptime_today
data:
time: >
{{as_timestamp(state_attr('script.slapen_select','last_triggered'),0)
|timestamp_custom('%H:%M',default = none)}}

#

aargh, now seeing this copied automation only uses the time: option. I guess the timstamp option woukld be more complete.... {{as_timestamp(state_attr('script.slapen_select','last_triggered')|as_local)}}

#

yep, this seems to work alright, (without the as_local):

#
    action:
      service: input_datetime.set_datetime
      target:
        entity_id: input_datetime.sleeptime_today
      data:
        timestamp: >
          {{as_timestamp(state_attr('script.slapen_select','last_triggered'))}}```
marble jackal
#

why not use the datetime option:

    action:
      service: input_datetime.set_datetime
      target:
        entity_id: input_datetime.sleeptime_today
      data:
        datetime: >
          {{ state_attr('script.slapen_select','last_triggered') }}
#

that attriubute contains a full datetime object

floral shuttle
#

indeed, why not!. I had missed that too... 😊 much better.

silent vector
marble jackal
#
template:
  - sensor:
      - [ ... ]
        attributes:
          flight_summary: >
            {{ create dict here based on data rest sensor }}
silent vector
chilly furnace
#

I have a very annoying tuya light that claims to only support hs color mode.
In reality, what it really supports is rgb and white with a color interlock.
The result is that HA and everything that relies on it cannot turn the light to its white LEDs through the GUI or voice interfaces (at least through Alexa or homekit).
This means I can request the light turns white, but it will just engage the RGB LEDs in a 255,255,255 state.
Today I realised that I can call a service, light.turn_on with an RGBW value of 0, 0, 0, 255 and to my delight the LEDs in question interpret this well enough to turn off the RGBs and turn on the white LEDs. It's curious that it accepts an RGBW value at all with an interlock though. Setting any of the other three values to anything but 0 will result in the RGB lights coming on and the white turning off. I attempted and confirmed that specifying white: true does not work.

Anyway, to my question. After discovering a way to trigger the white mode with the RGBW value, I wondered if I can wrap the bulb in a Light Template. I specifically want to recreate it with relevant services and specify the specific supported_color_modes: ['rgb', 'white']. I've been looking at the docs here: https://www.home-assistant.io/integrations/light.template but I don't see any mention of specifying supported color modes, so figured I'd ask if this is a use case that makes sense for template lights 🙂

mighty ledge
#

you can't add supported modes without changing actual code

#

Your best option is to create a template light and try to provide all the information you'd like, with templates

chilly furnace
#

...so, the thing I'm asking then. That'll be a yes?

mighty ledge
#

Yes, but you don't define what it supports

#

you define what's available for the light by filling out the yaml

#

that will in essence change "what color modes are supported"

#

i.e. you're trying to change something that's automatically created by the configuration

chilly furnace
#

Goodo, I'd wondered if that would be the case. It says that the other default values are "optimistic" which made me worry it was just going to tell the lovelace card to show all possible elements whether appropriate or not 😅

mighty ledge
#

you do not want optimistic

#

looking at the docs, it's not supported for light templaets anyways

chilly furnace
#

ah well, never mind then. For now I've just stuck an extra button under the cards in question that activates white mode. Normally it's never a problem but every now and then a 3 year old charges into my garden office and screams "'lexa, make lights purple!" and I'm stuck on RGB until I figure it out.

mighty ledge
#

personally, I avoid TUYA products because of these types of reasons

#

They don't have a API that devices adhere to

chilly furnace
#

Me too, this is one of my earliest devices that I just haven't managed to sort yet. I've managed to flash or hack most of them but I can't seem to get that libra ESPHome solution to flash on this stupid chip. That may be my poor soldering skills to be honest though, it just doesn't seem to want to connect.

#

I also find it really weird that there's all this fear over 5G and huawei spying on us, but never a peep about the endless tuya devices folk are plugging into their homes. I swear if things ever did go to shit with China, they could just overload our power grids by turning all our smart plugs and lights on at once 😅

mighty ledge
#

never even heard of this huawei thing

#

I'll have to look it up

#

luckily I don't have any of those devices, however I do have like 304298349823 cheap chinese chip DIY projects

chilly furnace
#

Oh yes, pretty much all the world's 5G infrastructure (masts, dongles, routers) for a long time could only be set up using Huawei equipment. I believe when Trump was in power and was rilling them up he sought a ban on Huawei 5G equipment, I'm not sure if it happened in the end but it seems it was taken seriously enough that even here in the UK the parliament discussed banning it too and several other countries were concerned about it. Seemingly there's a fear china can listen in to 5G network traffic. Something they deny of course and I don't know if any evidence was ever shown, but being proprietry equipment it seems it was enough to get NSA and GCHQ worried about it.
It just always seemed odd to me that they considered that a threat without any real evidence to prove it, but not the fact that these cheapy tuya smart devices we're all installing require server side control by a Chinese company and those most certainly aren't hiding anything about it.

heavy crown
#

Yep, the logic is not there...and then to know that those that spy on the 'western' world are esp. the USA and UK 🙂

chilly furnace
heavy crown
#

All to protect local interests

#

I spy better than you spy

#

anyhow...not for this thread

chilly furnace
#

The new modem my 5G provider sent out recently got rid of my old Huawei one and is a Zyxel one. The bottom says they're based in Denmark. Most odd. But yes, not really the forum for this 😅

silent vector
mighty ledge
#

no

silent vector
#

Is there a workaround to achieve this? Backstory is I'm tracking flight prices and I would like to know when the price is the lowest in the last x days and then I would send a notification for example.

chilly furnace
chilly furnace
#

This one, for instance, tells me my off-peak electric rate by giving me the minimum value in the last 24 hours:

  unique_id: off_peak_electric_rate
  name: "Off-peak electric rate"
  entity_id: sensor.octopus_energy_electricity_current_rate
  precision: 3
  state_characteristic: value_min
  max_age:
    hours: 24```
silent vector
#

I have never used nodered. I might go down the statistics sensor or history sensor route. I was trying to avoid creating a bunch of sensors but it's better than nothing so I can know I am getting the best price. The beauty of ha is I can do this myself with a free API rather than paying some company to tell me the best price lol.

chilly furnace
#

Sounds like you're just trying to recreate SkyScanner and they don't exactly charge a subscription 😅

silent vector
#

I'm using kiwi API.

lofty mason
#

I've been using it less and less lately as automations improve, but when I want to do some complex coding operation or operating on arbitrary sets of history data i think it's still my favorite option.

mighty ledge
#

if the api gives you a list of past flights, then you can just use a normal template

chilly furnace
#

There's an SQL sensor? How have I not known about this?! Oh this opens up so many doors 😄

mighty ledge
#

there is

silent vector
#

For some reason I thought Skyscanner wasn't free.

chilly furnace
#

Ooo i found the doc page. Exciting!

mighty ledge
#

I only use it for database size

silent vector
silent vector
mighty ledge
#

you'd have to come up with the query

spark vortex
#

I have some input_boolean sensors(lets say A, B and C), and I want to set a template sensor based on these rules: if A and B set sensor S = 'partial', if A and C set S = 'partial', if A B and C set S = 'total', how can I do it? But I have around 10 input_boolean sensor, so basically S will be 'total' only when all of them are set

mighty ledge
#

what about if just a or b or c are on, what's the state?

#

just partial?

#

if yes,

spark vortex
#

it is 'total' only when all are on, when one or more are off it is partial, when all are off it is 'off'

#

well. it would bbe nice when it is partial to show the entity frieldy name that is on, but I am not sure if there is a fancy way to show them in a card

#

'on' I assume it is 'total'

mighty ledge
#
{% set booleans = ['input_booean.1', 'input_booean.2', 'input_booean.3', 'input_booean.4'] %}
{% set cnt = booleans | map('states') | map('bool', False) | reject('false') | list | length %}
{% if cnt == 0 %}off
{% elif cnt == booleans | length %}on
{% else %}partial
{% endif %}
marble jackal
#

why not just use select('eq', 'on') after mapping it to state?

mighty ledge
#

sure

spark vortex
#

what does the reject('false') do exactly?

marble jackal
#

it rejects the items which have value False from a list

spark vortex
#

ah get it, thaks

#

ok, I tested it and it works, but I notice a small issue, since not all input_boolean sensors are updated in sync, it will pass from off to partial and then total or from total to partial and then off, is there a way to add a sort of delay to make sure that all input sensors are updated? they are in max 1 second

bleak thicket
#

Hey! I'm trying to add a graph of electricity prices to a notification triggered by an automation:

{% set prices = (states.sensor.nordpool_ee.attributes.raw_today +
states.sensor.nordpool_ee.attributes.raw_tomorrow) 
| selectattr('start', 'gt', now()) | list %}

{% set labels = prices | map(attribute='start') | list %}
{% set data = prices | map(attribute='value') | list %}
https://quickchart.io/chart?c={type:'bar',data:{labels:{{labels}},datasets:[{label:'Price',data:{{data}}}]}}

I'm struggling to figure out how to format the date, so that I can have nice labels for my chart. Is there a filter to run an arbitrary python command, such as strftime on each element in a list, or a built-in filter formatting date somehow? Ideally, I'd like to do something like this
{% set labels = prices | map(attribute='start') | map('strftime', '%a %H:%M') | list %}
to get labels like Tue 23:00, Wed 00:00, Wed 01:00 etc..

#

Rubber duck debugging ftw. As I was typing "does not allow appending elements to a LIST", I figured that I can append to a string 😄

#

This works:

states.sensor.nordpool_ee.attributes.raw_tomorrow) 
| selectattr('start', 'gt', now()) | list %}

{% set data = prices | map(attribute='value') | list %}

{% set labels = namespace(value='') %}
{% for state in prices -%}
  {% set labels.value = labels.value + "'" + state.start.strftime('%a %H:%M') + "'," %} 
{%- endfor %}

https://quickchart.io/chart?c={type:'bar',data:{labels:[{{labels.value}}],datasets:[{label:'Price',data:{{data}}}]}}
#

Here's how it looks: https://quickchart.io/chart?c={type:'bar',data:{labels:['Tue 23:00','Wed 00:00','Wed 01:00','Wed 02:00','Wed 03:00','Wed 04:00','Wed 05:00','Wed 06:00','Wed 07:00','Wed 08:00','Wed 09:00','Wed 10:00','Wed 11:00','Wed 12:00','Wed 13:00','Wed 14:00','Wed 15:00','Wed 16:00','Wed 17:00','Wed 18:00','Wed 19:00','Wed 20:00','Wed 21:00','Wed 22:00','Wed 23:00',],datasets:[{label:'Price',data:[0.0541, 0.054, 0.0948, 0.0805, 0.0805, 0.0805, 0.0948, 0.1169, 0.1526, 0.173, 0.204, 0.1941, 0.192, 0.1669, 0.1765, 0.1765, 0.1913, 0.1764, 0.1981, 0.1718, 0.1729, 0.2187, 0.2094, 0.1613, 0.1399]}]}}

jolly wigeon
#

Is there a way to change a light. Entity to either a fan or switch? I know there’s a helper to change a switch to those but I’m not sure how to go the other way around.

plain magnetBOT
#

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

inner mesa
#

the problem is that states are always strings and you're doing ascii math

#

this:
states('sensor.jordan_phone_battery_level') < "85" needs to be states('sensor.jordan_phone_battery_level')|float < 85

#

and by putting that first, you'll never hit the second case

#

you need to flip the order of the first two

#

you can also not repeat yourself so much..

#

nest the "if" statement for charging or not, set a variable for the battery_level

vagrant zephyr
#

Thank you I'll try that, wasn't sure what float meant wheb seeing it being used

mighty ledge
#

anyways, if you ever come over to this channel, the proper way to get /<minutes> via a template trigger that works with all intervals is...

{{ ((now() - '2023-08-30T00:00:00' | as_datetime).total_seconds() // 60) % states('input_number.aquaponics_cycle_interval') | int == 0 }}
#

but keep in mind that it will not work with an 1/minute. No template sensor will do that because of how templates are designed

marble jackal
#

I thought it was using the minutes of the hour.. guess I was wrong 🙂

mighty ledge
#

you an also use any date in place of '2023-08-30T00:00:00' to get your desired minutely repeating

marble jackal
#

But it does make it more reliable than I thought it was

mighty ledge
#

you'll have a hiccup

marble jackal
#

Yes, I don't use them that much, but now I understand how they actually work

#

TIL

mighty ledge
#

modulos?

marble jackal
#

I also learned how to work work dictionaries in Python, which is a breeze compared to jinja

mighty ledge
#

yes, jinja sucks for dicts

#

it's all because jinja is designed to not create new memory, it just want's to traverse existing memory

marble jackal
#

No I thought /7 would just trigger at X:07, X:14 etc, same every hour

mighty ledge
#

It will

#

but then between 56 and 7 will be more than /7

#

that's an 11 minute gap

#

if you truly want /7, then you have to use an always increasing number

marble jackal
#

0 is also devisable by 7

mighty ledge
#

yeah, still same principle, you'll have a 4 minute gap, point is, it's not actually /7 when you use now().minute

marble jackal
#

No, okay, I understand that

mighty ledge
#

if you want to be really lazy you can use timestamp, but you can't alter the seed date

#

{{ (now().timestamp() // 60) % ... }}

marble jackal
#

But with the paint pattern trigger, will it use the minutes since 1970/1/1 00:00 UTC?

mighty ledge
#

no, it uses startup as the seed

#

HA startup

marble jackal
#

Ah okay, check

#

Does it also run at startup?

mighty ledge
#

not sure

#

I would assume it does run at startup?

marble jackal
#

With an uptime sensor you could really replicate the time_pattern trigger behavior then

mighty ledge
#

Yep, well within reason

#

can't go below 2 minutes 😕

#

you could with a template entity that uses a time_pattern trigger.

#

a 1 minute increment would always be true with a template

crude crest
#

You can do a trigger on a 1 second time pattern and use the input_number as a condition if you need more than a 1-minute resolution

mighty ledge
#

right, essentially the same as a template entity w/ trigger, but it wouldn't have extra traces in the automation editor for each 'failed' condition

crude crest
#

But that gets a little excessive to have an automation triggering every second imo

mighty ledge
#

that shouldn't matter tho if your lowest increment is 5

#

also, tinkerer's idea of an automation that schedules the next time might be another way to go

#

the downside is that it might get wonky after a restart

crude crest
#

Right. I scaled back the input_number to only go up to 30 so that I wouldn't have to worry about wonky intervals that go over an hour.

mighty ledge
#

as long as 60 is divisible by the increment, you should be good. Truncating it at 30 makes 25 the only wonky one. It'll trigger at 0, 25, 50, and then 0 again

#

all the other increments start and end at 60

crude crest
shy badge
#

Hello beautiful people, I think this is a Template question. I have created a ESPHome IR Remote Climate device but would now like to use a Xiaomi temperature sensor in conjunction with it. I have seen 1 way and that is to link the Xiaomi sensor to the ESP device with BLE but that's not an option here. So, Is there a way to create a thermostat using both these items together?

mighty ledge
#

You can however use generic thermostat integration which might get you what you want without templates

summer salmon
#

anyone know how to use wildcard?

was going to do an automation on the first of every month
{{ now().date() == "x-x-01" }}

plain magnetBOT
summer salmon
#

that was easy, thanks

shy badge
mighty ledge
#

I'm not sure what youmean?

shy badge
mighty ledge
#

if you already have a climate entity, why do you want a second climate entity?

#

sounds like you just want an automation?

shy badge
#

Beacause I need a temperature reading tied to it for setpoints

mighty ledge
#

ah ok, yes that would be generic thermostat, but it proabaly isn't what you want

#

and I don't think what you want exists

shy badge
#

😦

mighty ledge
#

anyways, read the documentation I linked, it covers how to set up generic thermostat, but make sure you read what it's meant to do

shy badge
#

Yeah I have used it before and it works fine for things like broadlink ir using smartir etc but as you said it doesn't look it supports ESPHome IR Remote Climate

#

could be worth me making a feature request

mighty ledge
#

if the behavior does what you want, you can make scripts

shy badge
#

Way above my pay grade LOL

mighty ledge
#

if you can use generic theromostat, you can make a script

#

it's all through the UI

#

and any templating issues can be solved here

shy badge
#

ohhh ok, I'll have a look.

#

cool cool, thank you

mighty ledge
#

make a script, use that in generic thermostat

summer salmon
lofty mason
summer salmon
#

so to trigger an automation on the first its as simple as this?
`trigger:

  • platform: time
    at: "00:00:01"
    condition:
  • condition: template
    value_template: "{{ now().day == 1 }}"`
haughty breach
#

Or just use a template trigger:

trigger:
  - platform: template
    value_template: "{{ now().day == 1 }}"
#

There's no need to trigger every day just to check if it's the first.

lofty mason
#

Isn't that going to run the template once per minute forever? I feel like maybe time trigger might be more efficient?

haughty breach
#

No his was a time not time_pattern trigger

lofty mason
#

I know but you're proposing a template trigger, with now(), which I think will be executed once per minute.

haughty breach
#

Yep, you're right 🤦‍♂️

#

I moved all those kind of things to calendar event triggers

mighty ledge
#

It’s negligible tho

#

The template listener is going to run regardless how many times it runs the template

#

If it was doing heavy math I’d avoid the template trigger

short parrot
#

After I understood that the threshold helper cannot do this, I have been directed here towards creating a template for a binary sensor that works like a threshold sensor, where the upper limit can be set via a slider or a +/- field in the dashboard (like a numeric input helper) - the problem is....I have zero clue how to even approach this, and code is very hard for me, so I am grateful for any hints or code snippets that can help me

Secondly, I wanted to ask if this template sensor is universal, just like a helper that I can add to any automation, or if I need to code it separately in all my automations

haughty breach
short parrot
# haughty breach Threshold is a binary sensor, so you will want a Template binary sensor (https:/...

Thank you!

Well essentially I want it to turn on when a certain temperature is exceeded on a sensor (sensor.temp_bedroom_temperature), and turn off when the temp of the sensor drops under the 'threshold' (Fan Set Temp). Now the actual threshold value I want to be able to set it from the dashboard, either as a scale (22-29 degrees C for example) or as a number with +/- signs. I noticed that a very simple implementation is having a numeric input helper (input_number.fan_set_temp_bedroom) to do that

Does this level of detail help more?

haughty breach
#

We need to know how you want the output to be mapped. Is the goal to have it turn "on" as it crosses the upper limit then "off" only after it crosses the lower? Or should it only be "on" between the two set points?

short parrot
haughty breach
#

The most basic configuration for that is:

template:
  - binary_sensor:
      - name: Bedroom Fan Threshold
        state: |
          {{states('input_number.fan_set_temp_bedroom')|float < 
          states('sensor.temp_bedroom_temperature')|float}}

Edit: Fixed typo. Thanks Rob

short parrot
#

whoa!! thank you! @haughty breach - just so I understand better...even if input_number is a number it has a "state"?

inner mesa
#

All entities have a state

short parrot
inner mesa
#

BTW, that code is wrong. value_template: should be state:

#

Otherwise, yes

short parrot
#

thank you kindly @haughty breach and @inner mesa

summer salmon
#

hi again. so i wanted to create a template to display the state of a sensor a month ago. and thanks to your help i got it to work, this is what i got so far:
{% if now().day == 1 %} {{ states('sensor.day_02') }} {% endif %} ... {% if now().day == 30 %} {{ states('sensor.day_31') }} {% endif %} {% if now().day == 31 %} {{ states('sensor.day_01') }} {% endif %}
but i realized this is not going to work for certain motnhs..?
is it possible to combine now()day and now()month in some way?
thanks!

fickle kettle
#

Oh that's so bad. Use code/variables man

#

why is your data split into 30+ sensors?

haughty breach
#

What about something like:

{% set d_num = (now() - timedelta(days=30)).day %}
{% if  d_num in range(1,10) %}
{{ states('sensor.day_0'~d_num|string)}}
{% else %}
{{ states('sensor.day_'~d_num|string)}}
{% endif %}
lucid thicket
#

{{ states('sensor.day_' ~ ('%02.f' | format(now().day))) }}

fickle kettle
#

timedelta() is the key, along with a format-string, but maybe this is solving the wrong problem. Why is the data in 30 sensors

haughty breach
#

Because SQL is hard... smile

fickle kettle
#

Dude it ain't too hard. Maybe restart your problem. Maybe the hive-mind can suggest better solution.

#

Oh you're not the OP ignore 😉

#

can use a SQL sensor to pull accurate values from states. Magic!

#

But OP @summer salmon hasn't answered why his data is so screwey

summer salmon
#

i agree with you guys, im new at this i have no clue what i am doing

fickle kettle
#

take a step back - explain why your data may be in ~30 separate sensors?
then maybe we can suggest a good solution

#

where did the data come from?

summer salmon
#

now this is just embarrasing lol
i dunno, i have always stored my data in seperate sensors ike this and never had any issues so have not really seen a reason to not do it.
but thanks for your advice i'll read up on sql and get my shit togetger

fickle kettle
#

We're happy to help, no need to be embarassed.

lucid thicket
#

In the meantime here is code that incorporates both timedelta and the format string and should work for you
{{ ('sensor.day_' ~ ('%02.f' | format((now() - timedelta(days=30)).day))) }}

There’s probably a more elegant way tho

fickle kettle
#
{{ 'sensor.day_%02d' % (now() - timedelta(days=30)).day }}
#

@summer salmon where does your data come from? how do you store it? interested

#

@summer salmon if your data is in sensor.day_01 to 31 (day of month) and you want to retreive the one for 30 days ago, a one-line sensor is:

{{ states('sensor.day_%02d' % (now() - timedelta(days=30)).day) }}
summer salmon
#

thanks guys, its appreciated.
i store ny data in utility meters with calibrate.utility meter service calls with automations. i have always known this is not the correct way to do it, but its beginner friendly and as i said... i never had any problems actually.
you guys rock by the way

fickle kettle
#

Not sure I understand. Screenshots? I never used the service on utility_meter fwiw

summer salmon
#

since you are curious it all started with me making a sensor to calculate the cost per day of diffrent devices, my electricity price changes every hour (no peak price, its actually 24 different prices per day)
so i did
{ (states('sensor.kwh_last_period')|float(0) * states('sensor.elec_price_last_period')|float(0)) | round(3)}}
and stored that data in 24 diffrent sensors. and added them together with a helper. maybe it sounds weird but it was really easy, even for me lol

fickle kettle
#

Do you want help "fixing" that? Or want to solve with the data you have?

summer salmon
#

im only doing this cause i think its fun, i want to learn as much as possible. your more than welcome to send me a DM with your thoughts, i sadly have to run to work now. and as you might presume i dont work with anything computer related lol

fickle kettle
#

(with current data) I would probably try and implement it using a SQL sensor, or maybe via REST API to access history...

fickle kettle
#

If you know that only one record per day is added to the sensors data, you can fetch the 30th-to-last value with something like

SELECT * FROM states
WHERE metadata_id = (SELECT metadata_id FROM states_meta where entity_id = 'sun.sun')
ORDER BY state_id DESC
LIMIT 30, 1
copper dirge
#

Hi Guys, I have a quick tile setup on my android phone that opens and closes my garage door. But it's only a momentary switch so guess back to off after half a sec. It's there a way to have the quick tile state be based off a door sensor I have on the garage door?

dusky ore
#

Dumb templating question- trying to pull calendar events from multiple calendars into a single sensor. Following the logic in this thread but since I have multiple calendar.list_events services, I wind up with duplicate nested attibutes:
https://community.home-assistant.io/t/how-to-list-multiple-calendar-event-in-a-template/349139/39?u=skelso

My event data winds up looking like:
`data:
scheduled events:

  • events:
    • start:
      summary
  • events:
    • start:
      summary
  • events:
    • start:
      summary
      I want:data:
      scheduled events:
  • events:
    • start:
      summary
    • start:
      summary
    • start:
      summary`
fickle kettle
#

@summer salmon (phew!) I've got a solution for you. It involves using a SQL sensor to query the state table in the DB.
It finds the right sensor to use by using DATE_SUB functions in SQL plus DATE_FORMAT('sensor.day_%d')
Then selects the first value that's at least the right age...
TLDR: add the following to the bottom of your configuration.yaml and restart HA

sql:
  - name: Old Data
    query: >
        SELECT states.* FROM states
        INNER JOIN states_meta ON states.metadata_id = states_meta.metadata_id
        WHERE states_meta.entity_id = DATE_FORMAT(DATE_SUB(NOW(), INTERVAL 1 MONTH), 'sensor.day_%d')
        AND last_updated_ts < UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 1 MONTH))
        ORDER BY state_id DESC
        LIMIT 1
    column: "state"
#

tested on mariadb, but I assume sqllite will be the same...

#

hmm, maybe it isn't. let me know which DB you have.

#

The sensor-select part will be something like
strftime('sensor.day_%d', date('now', '-1 month'))
and the date filter will be something like
AND last_updated_ts <= strftime('%s', 'now', '-1 month')

undone jungle
#

Hi all, is there an easy way to print out the list of enabled entities for a given integration?

#

I was thinking of putting it in the template editor to print out all my Shelly entities that are enabled. I am switching away from the community integration and back into native, but wouldn't want to break all my dashboards and automations, so would like to keep track of the names.

#

I came across the general template, though struggle with adjusting it to print out just specific integration entities:

{% for state in states -%}
{{ state.entity_id }}
{% endfor %}
undone jungle
#

???

#

Nevermind!! Found this {{ integration_entities('smartthings') }}

#

It could only use an enabled entity filtration

#

Currently it spits out all.

summer salmon
half pendant
#

Trying to figure out whats wrong with this automation. I'm fairly certain it's something in the current_volume section. https://dpaste.org/61yZB
Error while executing automation automation.office_dial_rotate: TypeError: can only concatenate str (not "float") to str

marble jackal
#

@half pendant My guess is this: new_volume: "{{ max(0, min(current_volume + (volume_change | float), 1)) }}"

#

BTW there is nothing secret about device id's they are just randomly generated by HA when you integrate them

#

same with the numbers for entity id in the device stuff as of last month

#

The error caused by you placing quotes around the templates in the current_volume variable

#

you are outputting a string with the template, not the result of the template

plain magnetBOT
#

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

marble jackal
#

yes, I just explained why

half pendant
#

So it should be current_volume: |- {% if state_attr('media_player.homepod_mini', 'volume_level') == 0 %} {{states('input_number.office_tv_last_volume_level') | float}} {% else %} {{ state_attr('media_player.homepod_mini', 'volume_level') | float }} {% endif %}

marble jackal
#

correct

half pendant
#

i see!

#

yes! That works

marble jackal
#

are you sure the volume_level is still reported when the device is off?

#

Google devices don't

half pendant
#

the homepods are never off. They are always on. I had an issue with the apple tv not reporting volume level sometimes so i switched to the hompods (they are all connected). The issue i had there was that sometimes the homepods would report volume_level = 0 even though it wasn't, so the volume level would get superlow when i tried to lower it. To offset that i'm now saving away the latest volume level and using that if the homepods are reporting 0

distant plover
#

I have a bunch of entities starting with sensor.tgtg_ and I want to create a 'template sensor with the count of the sensors above 0 as the state, and in an attribute a list of all the sensors above 0'. Help? 🙂 I've tried with {{ states.sensor | selectattr('entity_id', 'search', 'sensor.tgtg_') | map(attribute='state') | map('float', 0) | sum }}
and that seems to do the first part, but I'm not sure how to get the sensors above 0 in an attribute.

marble jackal
#

that's not a count of the entities, that's the sum of their state

distant plover
#

I thought that's what you meant yesterday. 🙂

#

End goal is to trigger if one of those entities has state above 0

#

But I see that you wrote 'count'... 😛

marble jackal
#

Yest, I understand the goal, but I said you need a template with the count as it's state

#

you are also writing that in your text above

#

{{ states.sensor | selectattr('entityid', 'search', '^sensor.tgtg') | map(attribute='state') | select('is_number') | map('float') | select('>', 0) | list | count }}

distant plover
#

It was almost copy paste of your answer yesterday 😄

marble jackal
#

this will give a count of the sensors which are reporting a number, and not equal to 0

#

can they be negative?

distant plover
#

No, can't be negative

#

0 or maximum 30 I'd say

marble jackal
#

okay, in that case the code above will give you the count

#

for the entities:
{{ states.sensor | selectattr('entityid', 'search', '^sensor.tgtg') | selectattr('state', 'is_number') | selectattr('state', '!=', '0') | map(attribute='entity_id') | list }}

#

to be sure you are using the same data, you could use the same for the count, and just add | count

#

what are you trying to do anyway?

#

maybe this will help

#

first part is the template sensor, second part is an automation which sends out notifications when there is a box available, and you can click to go directly to to app on the selected box (assuming you also use Android)

#

oh it also uses my variables template sensor

distant plover
#

I want to be notified with details about each entity the moment that entity has state > 0. Getting notifications about TooGoodTooGo 🙂

#

(Sorry for the late response)

#

Funny. Thanks. I'll check it out. My previous automation also took me straight to the box. 🙂

dusty dust
#

hello. I have a sensor that displays power in real time(watts), that goes negative when discharging batteries, and positive when charging. I want to make 2 new template sensors, one that only counts negative values, and one that only counts positive values, Both sensors need to output positive numbers of Kwh with riemann integral. How would i go about to make that sensor in configuration ?

dusty dust
#

i came up with this one to read only negative values on my sensor. But it does not work.

#
  • sensor:
    - name: "Testningnegativ"
    unit_of_measurement: "W"
    state_class: measurement
    device_class: power
    state: >
    {% if states('sensor.not_connected_battery_power') | float(0) =< 0 %}
    {% set gridout = (states('sensor.not_connected_battery_power') *-1) %}
    {% else %}
    {% set gridout = 0 %}
    {% endif %}
    {{ gridout }}
    attributes:
    last_reset: '1970-01-01T00:00:00+00:00'
#

stolen from some random place since i have no idea how to code

#

the one called positive is working as intended, looking like this,

  • sensor:
    • name: "Testningpositiv"
      unit_of_measurement: "W"
      state_class: measurement
      device_class: power
      state: >
      {% if states('sensor.not_connected_battery_power') | float(0) >= 0 %}
      {% set gridin = states('sensor.not_connected_battery_power') | float(0) %}
      {% else %}
      {% set gridin = 0 %}
      {% endif %}
      {{ gridin }}
      attributes:
      last_reset: '1970-01-01T00:00:00+00:00'
mighty ledge
#
- sensor:
  - name: Positive
    device_class: power
    unit_of_measurement: W
    state_class: measurement
    state: >
      {% set value = states('sensor.not_connected_battery_power') | float %}
      {{ value if value >= 0 else 0 }}
    availability: "{{ states('sensor.not_connected_battery_power') | is_number }}"
  - name: Negative
    device_class: power
    unit_of_measurement: W
    state_class: measurement
    state: >
      {% set value = states('sensor.not_connected_battery_power') | float %}
      {{ value | abs if value < 0 else 0 }}
    availability: "{{ states('sensor.not_connected_battery_power') | is_number }}"
dusty dust
#

did you write this just now? i would like to understand what i am even doing. but i guess that is up to my betters.

mighty ledge
#

yes

#

it's missing state class tho, i'll edit that

dusty dust
#

ah i got an error

#

name is an invalid option for template it says

mighty ledge
#

you forgot the - sensor line

dusty dust
#

i pressed copy on the box. but i'll look if i misplaced it

mighty ledge
#

make sure that -sensor line lines up with all your other templates as well

dusty dust
#

i cannot get it to work for some reason

mighty ledge
#

post all your yaml, not just what I created

dusty dust
#

okey

#

just gonna overlook for sensitiv info

#

your entry is close to the top

mighty ledge
#

take a look at your correct template sensor

dusty dust
#

tried moving forward name from the same line at sensor aswell

mighty ledge
#

indentation matters in yaml

dusty dust
#

so i have found out. this isnt the first time i had issues

#

it works now

#

thank you very much.

#

now im just going to put these template sensors in a riemann and get kwh out of them

distant plover
mighty ledge
#

make a notification group and use that instead

distant plover
#

Oooh.. that's neat. Thanks.

sullen osprey
#

How i can do a LIKE instead ewual in automation: {{ trigger.calendar_event.summary == "M9" }}

marble jackal
#

You can test if the summery contains M9

#

but what do you mean with LIKE? Is N9 like M9? or M10?

sullen osprey
marble jackal
#

what doe you mean with like?

sullen osprey
#

Ok, on my calendar, i have different appointement for hockey my younger kids mentionned M9 into the appointement and my oldest one M11. I would like to trigger 20 min before appointement contain M9

marble jackal
#

{{ "M9" in trigger.calendar_event.summary }}

#

{{ trigger.calendar_event.summary is search("M9|M11") }} or this to check on both in one go

hexed galleon
#

Anyone able to point me in the direction of capturing the last zha_event from a device? Wanting to build a template sensor for the last fired event from an IKEA 5-button remote.

hexed galleon
tepid onyx
#

iudhskjfd9

#

ah damn cat

marsh cairn
#

{{ state_attr('input_device.keyboard','cat') }} JamCat 😆

heavy crown
#

Hey all, I have 5 sensors, sensor.test_mon, sensor.test_tue, etc. I need to use these in a card and would like to know if I can template the day in the sensor, e.g.

#

{{ states('sensor.test_{{now().strftime("a")' }}

#

this obviously does not work

lofty mason
marble jackal
#

There are actually 7 days in the week, so this will still error two days per week (with 5 sensors)

gusty bloom
#

Hello! I've a JSON list that's being returned froma restful call similar to this (only it's >255 characters:

[
  "Dog",
  "Cat",
  "Fish",
  "Rabbit",
  "Lizzard",
  "Iquana",
  "Mouse"
]

I'm trying to pull the data from this into a sensor (so that I can then feed it into the selection choices on an input_select helper.
because of the result length, I need to put this data into an attribute instead of the state, but I can't seem to find any examples that start with a list without keys and such.

inner mesa
#

Just make it the value of a key

gusty bloom
# inner mesa Just make it the value of a key

Thanks, I've been trying to do that most of the day, lol

rest:
- resource: http://192.168.255.10/api/
  sensor:
    name: Shop
    value_template: "OK"
    json_attributes: 
      -pets: {{value}}
  scan_interval: 120
#

am I close?

inner mesa
#

You need a space before pets and quotes around the template

#

You probably also need {{ value_json|from_json }}

gusty bloom
#

Parses, but no attribute.

marble jackal
#

I don't think you can do this in a rest sensor

#

you can only provide a dict key as attribute, which you don't have

gusty bloom
#

I have something in a commandline sensor, but it feels dirty. 🙂

marble jackal
#

json_attributes string | list (optional)
A list of keys to extract values from a JSON dictionary result and then set as sensor attributes. If the endpoint returns XML with the text/xml, application/xml or application/xhtml+xml content type, it will automatically be converted to JSON according to this specification

inner mesa
#

Oh, you're right

#

My mistake

#

I dislike that

marble jackal
#

It is a bit annoying if there are no dictionaries in the json

gusty bloom
#

I was hoping there was a way to injet a dict

inner mesa
#

Too restrictive

gusty bloom
#

oh well, I appreciate you guys taking a look at it!

inner mesa
#

I suggest making a feature request to make REST attributes more like a template sensor

lucid thicket
#

You can try the multiscrape addon which allows for templates in the attributes

acoustic arch
#

im trying to run a test script to let lights change colors as a sort of party lights. I have them in sync now with a shared variable as delay. but i would like to run the loop with each light his own random delay. This still runs in sync.....

https://hastebin.com/share/ehisepafiq.yaml

#

i expect light 1 to blink with 1sec interval, the second with 5

#

but they both change color at 5sec

#

or do i need a loop per light in a main loop?

tawny sedge
#

I'm trying to get the value of a numeric helper in the trigger of an automation. I want to set the "minutes" value to the value of the numeric helper.

plain magnetBOT
#

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

tawny sedge
#

This YAML is invalid. What am I doing wrong with the syntax in the "minutes"?

#

This is the error "Message malformed: expected float for dictionary value @ data['for']['minutes']"

buoyant pine
#

I'm guessing it's not possible to use templates with device triggers/conditions/actions. You'll want to use a state trigger

marble jackal
#

That's indeed the case

summer salmon
# fickle kettle How’d it go?

thanks for pushing me, noticed i really needed to learn this.
i kinda wondered why my history was only 10 days, had recorder setup all wrong. and apparently was not even using mariadb. i learned alot, thank you

fossil venture
summer salmon
fossil venture
#

Simplicity. Why run up a seperate container if it is not needed? I use it because I also host my Kodi databases in MariaDB.

#

If it wasn't for that and that I have a lot of LTS data stored there (hard to move back) I'd use the default DB.

summer salmon
#

i dont know about you, but i kind of enjoy spinning those containers up lol.
i get your point though

tawny sedge
bitter atlas
#

How do you renable a template sensor you had set a unique id and disabled via ui? It just vanished from the states list

marsh cairn
#

Settings - Devices & Services - Entities: There is a triangular symbol below the dotsvertical . You can select to show hidden/disabled entities there.

#

You can find it now and enable its visible or enabled setting.

royal vortex
#

I have a lot of temperature sensors feeding into automations through templating, and using the min, max of said sensors. Is there a way to only use the data if it has updated in the past X minutes? I have a very klugey setup currently, and I feel like it could be a lot better.

{% set my_min = 400 %}{%- if states('input_boolean.use_probe_1') == "on" -%}{% set my_min = ([states('sensor.igrill_probe_1') | int(400), my_min |     int(400)] | min) %}{%- endif -%}{%- if states('input_boolean.use_probe_2') == "on" -%}{% set my_min = ([states('sensor.igrill_probe_2') | int(400), my_min | int(400)] | min) %}{%- endif -%}{%- if states('input_boolean.use_probe_3') == "on" -%}{% set my_min =([states('sensor.igrill_probe_3') | int(400), my_min | int(400)] | min) %}{%- endif -%}```
#

the 400 is in there because they "should never be that high" (aka something is on fire so nothing really matters anymore)

#

currently I'm using a seperate input boolean per input to "toggle it" off and on

haughty breach
#

What is the goal of this template?

#

What is the purpose of the booleans?

haughty breach
royal vortex
#

The purpose of the booleans is effectively to disable the other sensors from being used in the measurements (ala, I don't care about probe 2 right now so don't include it in the math). If I could use the last updated attributes it'd work without the boolean

haughty breach
royal vortex
#

ohhh, I'll have to give that a try. That'd help a ton! Thank you!

slate fossil
#

Earlier I wrote some JavaScript that uses a single LET variable instead of a bunch of IF statements to return an icon for use in a custom:button-card. It even has a part to catch a undefined variable.
So then I set out to make the same thing in Python/Jinja for use in a Mushroom Template Card. It took a while to get it to return the matching variable but I must have spent the last two hours trying to catch the undefined variable. Tried all kinds of different stuff to try to make it work...

#

The whole time: I was trying to call the WRONG MDI ICON! Was trying to return mdi:question when it is really mdi:help (which returns a question mark.)

#
...code snippet...
{% set icon = conditions[weather_condition] %}  
{% if icon is not undefined %}
  {{ icon }}
{% else %}
  mdi:help
{% endif %}```
final sun
#

Is there something special I need to do for this work?

          {% if state_attr('climate.badezimmer_eg', 'preset_mode') ==
          'week_program_1' %}
              green
          {% else %}
            red
          {% endif %}```
slate fossil
#

Assuming you're trying to use that in a frontend card. It depends on the card you're trying to use it on. If it is a stock card, chances are it won't work as they're generally not able to be templated.

final sun
#

I am trying to use button-card.
The documention shows a different syntax though:

            if (entity.state < 60) return 'lime';
            if (entity.state >= 60 && entity.state < 80) return 'orange';
            else return 'red';
          ]]]```
inner mesa
#

Yes, you should follow the docs

final sun
#

Alright ty. I was hoping I didn't have to learn a new syntax 😅

slate fossil
#

The custom:button-card uses JavaScript while most templating is in Jinja. Head over to #frontend-archivedas your question is more frontend-based.

dusky ore
#

Will try this, thank you!

jagged knoll
#

I want to track a 240v breaker by using a CT in one leg (to track one phase), to get estimated consumtion I would need to multiply total active energy output by two

This should work to create the template sensor

- name: "Bomba de Casa Total"
  state: "{{ states('sensor.shellypro3em400_e05a1b339cec_phase_c_total_active_energy') | float(0) * 2}}"
  unit_of_measurement: 'kWh'
  device_class: energy

My question is, how can I list it as individual device in energy dashboard I dont see it there

dusky ore
jagged knoll
haughty breach
marble jackal
plain magnetBOT
#

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

marble jackal
#

@normal notch this is not a valid template
value_template: "{{ camera_type }} == 'Driveway'"

#

Move the ending curly brackets to just between the single and double quote

fossil venture
#

When do template images update? Mine only seem to update when home assistant is restarted.

marble jackal
#

Depends on the template used to get the image. If it is not using anything which causes it to reload on state change like states() you might want to add something like a trigger

fossil venture
#

Yeah I'm not. Just a web url that does not change. Thanks for the tip. I'll change them to triggered template images.

marsh cairn
fossil venture
#

These are cloud cover images, they only update every hour so I'll use a time pattern trigger for that.

marsh cairn
#

But with that time pattern trigger alone you will get that image 1h after HA start or a template reload. Before that the image will not be available. That's why I added the templates reload and HA start triggers too

#

That way it is immediately available and gets actualised in a timely pattern

fossil venture
#

No, will get it every hour. Every time the hour is divisible by 1 (and the seconds == 0). Also I've just been reading the site information and it actually only updates every 3 hours. So 1 hour should be plenty.

marsh cairn
#

Yes, but you will see it the first time after an hour (edit: at the next load time)

fossil venture
#

So you are saying they are not restored?

normal notch
marsh cairn
fossil venture
#

Ah. Ok then. Thanks for the tip.

marsh cairn
#

Every reload of templates in the dev tools or HA restart kills those

fossil venture
#

The untriggered ones reloaded on restart so I assumed the triggered ones would too.

marsh cairn
#
  - triggger:
      - platform: homeassistant
        event: start
      - platform: event
        event_type: event_template_reloaded
      - platform: time_pattern
        minutes: "/15"
    image: ......```
was my approach
fossil venture
#

Pretty much what I have now. Thanks.

marble jackal
fossil venture
#

Doing some tests...

#

Can confirm. They are not restored.

#

Will open an issue.

normal notch
fossil venture
#

Actually the docs only say that triggered template binary sensors and sensors are restored. So it would have to be a feature request.

#

It specifically says "The state of other trigger-based template entities is not restored."

fossil venture
normal notch
#

Gave that a go but it didn't seem to work, but will try again incase I mis-typed. Thanks! 🙂

fossil venture
#

Use the developer tools template editor to check

#

Just set the value of camera_type first, ```
{% set camera_type = "Driveway" %}
"camera.{{camera_type | lower }}_camera_sub"

normal notch
#

Will give it a quick shot, thanks! Dev tools did seem to work though... two tics

#

Ah it works! Perhaps I had mis-typed it before, as it did not generate an image before. Thanks!!! 🙂

wicked smelt
#

I need some help! I am trying to merge/append two dicts together. Any ideas?

marble jackal
#

Does dict(dictionary_1, **dictionary_2) do the trick?

rare linden
#

Can anyone see anything wrong with this?

- name: "[Motion] Sensors"
  state: |-
    {% set sensors = states.binary_sensor|default([], true) | selectattr('entity_id', 'defined') | selectattr('state', 'defined') | selectattr('attributes', 'defined') | selectattr('attributes.device_class', 'defined') | rejectattr('state', 'eq', 'unavailable') | selectattr('attributes.device_class', 'eq', 'motion') | sort(attribute='last_updated', reverse = True) | sort(attribute='state', reverse = True) | list  %}
    {{ sensors }}

it works in the template under development tools

It should get a list of all valid motion sensors and sort them in order of latest update and on state before offstate

#

but when i create it under sensors.yaml which i include in my configuration.yaml it just comes up as unavailable

plain magnetBOT
#

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

rare linden
#

Found the issue "State max length is 255 characters."

floral shuttle
#

guess this {{state_attr('sensor.daylight_savings_times','dst_changed_today') == true or state_attr('sensor.daylight_savings_times','dst_change_tomorrow') == true}} could be written as {{state_attr('sensor.daylight_savings_times','dst_changed_today') or state_attr('sensor.daylight_savings_times','dst_change_tomorrow')}} too

#

or would that cause some edge case issue at change (not sure what could go wrong, but just to be sure..)

rare linden
#

only potential issue i can see is if the result is undefined but then it should resolve to false so therefor it would be the same as == true

#

so it should be functionally the same

#

but if you're worried about potential issues i'd do state_attr('blah')|bool

#

that way it will always resolve to an actual boolean

marsh cairn
floral shuttle
#

yeah, thx. been using this binary since forever, and never had an issue with it being unavailable, so guess that wont be required. trimming down on yaml characters....

floral shuttle
#

fwiw, I am testing these:```
dst_change_tomorrow: >
{% set dt = now() + timedelta(days=1) %}
{{now().astimezone().tzinfo != dt.astimezone().tzinfo}}
dst_changed_today: >
{% set dt = now() + timedelta(days=-1) %}
{{now().astimezone().tzinfo != dt.astimezone().tzinfo}}

summer salmon
#

im guessing there is no easy way to make
timestamp_custom('%A, %-d %B')
display in swedish?
and yeah, if i change general language settings in HA, it might change, but i for sure dont want to do that.

marble jackal
#

Uhm, that will display 2023-09-02 There is nothing to translate in that

summer salmon
#

sorry pasted wrong thing 😉
edited post

#

kinda weird that even if i do TTS google translate with swedish, it will still say friday instead of fredag.

marsh cairn
#

A quick and dirty workaround might be something like this (for today's name of day in Swedish - at least I hope it is correct 😆 ):

{% set weekday = weekdays[now().weekday()] %}
{{ weekday }}```
summer salmon
#

hahahah yeah that worked!
but only for {{ weekday }}
guess i have to rewrite the whole thing to make it work around that

marsh cairn
#

You just need to replace the now().weekday() by something that counts the weekday from 0 to 6.

marble jackal
#

You can use petro's, macros, there is a Swedish translation provided

summer salmon
#

that is indeed very cool and interesting. thanks!
but thing is, i did this looong template based around dates (from calendar)
so everything is built upon |timestamp_custom('%A, %-d %B')
that gives me Friday 22 September
which does not seem to want to be translated.
its not really a big deal, i can probably live with it
im gonna assume this is because i did it wrong from the beginning.

cursive totem
#

Hi, whats going on here then? i have written a template that works fine in the template tool but shows as unavailable once loaded?

#

trying to think how i can show the issue

inner mesa
#

by sharing the template

cursive totem
#

there must be some kind of of limit to how many lines can be output it works with 5 but not 6.. ill share the code 2 sec

inner mesa
#

states can't be more than 255 characters

lyric comet
#

Your are probably exceeding the 255 limit for a state. Use Attributes or multiple sensors.

slate fossil
#

was waiting to see the response from a Mod and a Padawan writing at the same time. 😆

cursive totem
#

right that makes sense

#

thank you

inner mesa
#

we all share a hive mind

cursive totem
#

think ill split it into 3 sensors

marble jackal
#

Or... Put it in an attribute

cursive totem
#

That could work.. i want to show it on a markdown card but you can show attributes there cant you?

inner mesa
#

yes

lyric comet
#

If you are using a Markdown card, why not simply use a Template Macro and include that when you need it.

#

You already have the code to build it.

cursive totem
#

cos i dont know what im doing lol

inner mesa
#

I was going to ask if you wrote that 🙂

marble jackal
#

Or if it's only for the card, just use the template in the card

cursive totem
#

well blow me .. pasted it into a markdown card and its perfect

#

thank you xoxox

lyric comet
torpid crag
#

Hi All, i have a KG measurement. Is there any way to round to the nearest half KG? e.g. 10.0, 10.5, 11.0

autumn flower
#

A nice way, or a horrible way? Because the time-honoured method is output=round(input*2)/2

#

Should be able to throw that into a template sensor

torpid crag
#

Thanks!

coarse apex
#

Hey everyone, I'd like to create a template that gets the last 5 minutes of a sensor's data from recorder integration and uses that to generate an average. I'm having trouble figuring out how to do that.

marble jackal
#

a SQL sensor makes more sense for that

fossil venture
#

Use the statistics integration

marble jackal
#

oh or that 🙂

#

even more sense

fossil venture
plain magnetBOT
coarse apex
#

thanks guys, I'm stuck in the old influxdb style way of doing things

#

need to get used to thinking in this new way

#

works perfect thanks everyone

cerulean karma
#

''' - condition: state
entity_id: switch.shelly_test
state: "off"
for:
hours: 0
minutes: 5
seconds: 0'''

#

is there a change to check this automation condition as a template?

#

chance

haughty breach
#

An equivalent template would be:

{{ is_state('switch.shelly_test', 'off') and
states.switch.shelly_test.last_changed <= now() - timedelta(minutes=5)}}
cerulean karma
#

great, thanks @haughty breach

mossy compass
#

can I read user profile settings inside a template? I want to get the language the user has set

marble jackal
#

nope, templates don't know anything about the frontend

mossy compass
#

rip, my family is gonna have to cope with English titles then (or I could add a separate "setting" for that)

marble jackal
#

Well

#

with some cards which accept templates, there is a user variable, which contains the username

#

you can use that in the card directly

#

@mossy compass eg

type: markdown
contents: >
  {{ 'Bananas' if user in [ 'Dad', 'Mom', 'Little brother'] else 'Oranges' }}
mossy compass
#

oh yeah I could do that too

#

thanks for the suggestion

tepid citrus
#

Is there a way to say how long the previous state was for location? I am using a location notification blueprint, and I want the notification text to say how long the person was at the location they are leaving.

marble jackal
#

If you use a state trigger on the person entity, you can compare the last_changed of the from_state and the to_state to see how long it was in that state

silent vector
#

I'm trying to get the current item + next item in this list.
example output
84 00
But I am getting
UndefinedError: there is no next item
https://dpaste.org/CXWVj

marble jackal
#

that's because in your last iteration there is no next item

#

{{ loop.nextitem | default("") }} will resolve that

silent vector
silent vector
#

Would this be the place to ask for scrape sensor help? As in getting the right data from the html

mighty ledge
#

parsing w/ templstes -> here

floral shuttle
mossy compass
#

that's (maybe) what I meant with a separate setting

#

still a newbie

rare linden
#

Is there any good way of implementing an area filter onto the occupied_sensors? i know you can put the entity_id into area_id() but don't think that would work well for the below scenario

    {% set area = 'bedroom' %}
    {% set occupied_sensors = states.binary_sensor|default([], true) | selectattr('entity_id', 'defined') | selectattr('state', 'defined') | selectattr('attributes', 'defined') | selectattr('attributes.device_class', 'defined') | selectattr('attributes.device_class', 'eq', 'motion') | selectattr('state', 'eq', 'on') | list  %}
inner mesa
#

I would start with area_entities('kitchen')

rare linden
#

looks like i can do | selectattr('entity_id', 'in', area_entities(area))

inner mesa
#

that's one way, yes. or you just start with that instead of states.binary_sensor

#

in other words, start with the list of entities that you care about (are in that area) and filter from there

#

area_entities(area)|expand|xxxx

rare linden
#

ah yeah, that would certainly be a nice optimization, only just ran across area_entities before your answer didn't realise it returned a list of entity states for the area

#

Will do it that way, thanks

waxen lance
#

hi everyone i have a door lock sensor that shows locked/unlocked but it doesnt expose a door lock entity, it just logs this in the device logbook. [VeriLock Translator fired Notification CC 'notification' event 'Access Control': 'Manual lock operation']

#

how can i create a template sensor for these devices to show locked/unlocked status?

lucid thicket
waxen lance
#

its zwave correct. it doesnt actuate the lock, its only a locked/unlocked sensor. I have the events isolated but my question is about creating the template

#

is there a way to create a "lock" template sensor that will show locked/unlocked based on an automation I create triggered by the events?

lucid thicket
#

Here is something that could get you started; you don’t need an automation; this sensor will update when it sees the event:

template:
  - trigger:
      - platform: event
        event_type: zwave_js_notification
        event_data:
          device_id: your_device_id
          label: Access Control
    sensor:
      - name: "Front Door Lock Event"
        state: "{{ trigger.event.data.event_label }}"
        unique_id: front_door_lock_event
#

You could modify that with a template lock that doesn’t do anything, or you could use a template binary sensor

waxen lance
#

awesome thanks i will take a look

#

much appreciated

lucid thicket
#

Sorry, I was wrong, it looks like a trigger-based lock doesn’t exist. You’d have to make it a trigger-based binary sensor

waxen lance
#

so i got this...

#

template:

  • trigger:
    • platform: event
      event_type: zwave_js_notification
      event_data:
      domain: zwave_js
      node_id: 219
      command_class: 113
      command_class_name: Notification
      event_label: Door Unlock
      type: 6
      event: 1
      event_label: Manual unlock operation
      sensor:
    • name: "Sunroom Door Unlocked"
      state: "{{ trigger.event.data.event_label }}"
      unique_id: sunroom_door_lock_event
#

but how do i do the lock vs unlock?

#

there are 2 separate events and i

#

Maybe this?

#

template:

  • trigger:
    • platform: event
      event_type: zwave_js_notification
      event_data:
      domain: zwave_js
      node_id: 219
      command_class: 113
      command_class_name: Notification
      event_label: Unlocked
      type: 6
      event: 1
      event_label: Manual unlock operation
      sensor:
    • name: "Sunroom Door Unlocked"
      state: "{{ trigger.event.data.event_label }}"
      unique_id: sunroom_door_lock
lucid thicket
#

Can you provide the detail on what the lock event is? For your template (the code after the state key) you’ll want something that evaluates to on or true when the lock event is received, and then evaluates to off or false in all other cases

#

And you want this sensor updated (you want the template code re-evaluated) on both Locked and Unlocked events, so you need to remove the things in the trigger that would only match one of those events

plain magnetBOT
#

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

waxen lance
#

yep here are the events

plain magnetBOT
#

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

#

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

waxen lance
lucid thicket
#

here's two different ways to do it, hopefully this helps you understand what is possible with a trigger-based template sensor: https://paste.debian.net/1291092/

Also, for future reference, help with template sensors should be under #integrations-archived and if you're having issues with the code for the state, then this is the right place

waxen lance
#

ok thanks again! ill do some reading

#

appreciate the help

lucid thicket
#

by the way, in that debian paste, you'll have to either delete one of the two options (both the trigger and the binary_sensor sections) or else make the name and unique_id actually unique between them

#

And I used device_id in the trigger because that ID is unique to that lock. The nodes could get reused if the lock is removed and a different device is added. But the device_id will be new & unique each time a device joins the zwave network.

median mason
#
{% set monitored_entities = ['sensor.hue_toilet_motion_sensor_battery', 
                            'light.diningroom', 
                            'light.office1'] %}
{% set no_entities = 0 %}

{%- for monitored_entity in monitored_entities -%}
  {%- if states(monitored_entity) in ['unavailable', 'unknown'] -%}
    {% set no_entities =  no_entities + 1 %}
  {%- endif -%}
{%- endfor -%}

{{ no_entities }}

there are two entities which are unavailable and unknow. why do i get out 0, not 2?

marble jackal
#

Because of the scope of the for loop

#

Your changes in the for loop exist only there, you need to define a namespace

#
{% set monitored_entities = ['sensor.hue_toilet_motion_sensor_battery', 
                            'light.diningroom', 
                            'light.office1'] %}
{% set ns = namespace(no_entities = 0) %}

{%- for monitored_entity in monitored_entities -%}
  {%- if states(monitored_entity) in ['unavailable', 'unknown'] -%}
    {% set ns.no_entities =  ns.no_entities + 1 %}
  {%- endif -%}
{%- endfor -%}

{{ ns.no_entities }}
#

But you can easily do this without a for loop

#

{{ monitored_entities | map('states') | select('in', ['unavailable', 'unknown']) | list | count }}

coarse apex
#

Hi again! I'm trying to get the energy consumption of a device today. How could I do that with a template? It should be possible given that the Energy tab has no issue getting that data.

plain magnetBOT
marble jackal
#

Use that, no templates involved

coarse apex
#

But I'm not looking for an utility meter?

#

This is for a single device

#

track consumptions of various utilities (e.g., energy, gas, water, heating).

#

oh I see, thanks

marble jackal
#

Create a utility meter based on the energy sensor of that single device

coarse apex
#

How does the energy tab get that data anyway?

#

is it something I can't take advantage of as it needs to be an internal integration?

marble jackal
#

It uses the long term statistics in which the hourly deltas of each sensor are stored

#

It basically sums up all those hourly deltas for the selected period

#

It doesn't create entities or sensor values for those totals

coarse apex
#

Is there a way I could take advantage of the long term stats for my templates or is this only for integrations?

#

Anyway using utility meter worked fine, thanks!

fossil venture
coarse apex
#

It seems to be working just fine, but I'll resort to SQL sensor if I need to

peak spire
#

Hi! I just noticed something weird with regex_replace and service input_text.set_value.. If I look at the template result in the template dev tools, I get the correct result:

Template: {{ states('input_text.ios_reminders_handlelisten') | regex_replace(find='((Klesvaskemiddel)(\\n)?)', replace='', ignorecase=True) }}
Result: Something\nThis\nThat

When I try to use this with input_text.set_value, it ignores the match of \n
Result: Something\n\nThis\nThat

Any ideas? 🙂

silent vector
#

How might I achieve this output list from these 2 separate lists?

I am essentially saying every 4 items in main_list reset cycle list back to 0. Which is why bob is foo. I assume I might need a nested loop but I wasn't sure if there's a cleaner way.

https://dpaste.org/Q6baQ

marble jackal
#

Why is adam skipped

marsh cairn
#

Because eve is missing

silent vector
#

Oh Adam is skipped because I fudged up

silent vector
inner mesa
#

what about bob?

silent vector
#

I removed it as I wanted to keep the example clear

#

Essentially every number of items in cycle_list in this example 4 items reset back to the first item in cycle_list when we get the output.

That's why Chris at position 5 is foo and if I added Bob back at position 6 then Bob would be santa

inner mesa
#

We should just continue discussing your name choices and ignore your question 🙂

silent vector
#

It was pretty funny the Adam and eve one lol

#

This is just something complex that I am not sure of the right way to approach in jinja

#

Nevermind I figured out something for this lol.

marble jackal
#

Does it look something like:

{% set ns = namespace(zipped=[]) %}
{% for item in main_list %}
  {% set ns.zipped = ns.zipped + [ item ~ ': ' ~ cycle_list[loop.index0] |  default('foo') ] %}
{% endfor %}
{{ ns.zipped }}
silent vector
#

Looks like this and disregard names lol

{% set main_list = ['goo','fuy','udur','dhdh','shhd','eueh'] %}
{% set cycle_list = ['pr1','pr2','pr3','pr4'] %}
{% set ns = namespace(zipped=[]) %}
{% for item in main_list %}
  {% set ns.zipped = ns.zipped + [ item ~ ': ' ~ loop.cycle(*cycle_list) ] %}
{% endfor %}
{{ ns.zipped }}

This slight difference achieves the reset I was looking for

floral shuttle
#

now we have the actions in trigger templates I finally started out using the response_variable and tried to template that into a useful entity... followed the weather forecast example successfully. but, how can we test this response_variable in eg dev tools?

#

also asked in the Petition thread in the community so forgive my double ask.

floral shuttle
cerulean karma
#

what is the correct way to print the state of a input_boolean in a template?

marble jackal
#

{{ states('input_boolean.your_input_boolean') }}

cerulean karma
#

hm thats what I tried

#

{{ states('input_boolean.luftentfeuchter_status') }} -> TypeError: float() argument must be a string or a real number, not 'NoneType'

marble jackal
#

that template can not generate that error

#

what's the full error

cerulean karma
#

oh damn you are right

#

I thought it should at least print it since I put it in first line

#

thank...again 🙂

plain magnetBOT
#

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

cerulean karma
#

is there a chance to create a endlessloop when missing the condition?

#

I change the input_boolean which is the trigger on change at the same time

#

Would HA prevent me from creating such a loop?

fickle sand
#

I don't think you need an infinite loop. You are just trying to sync the input_boolean with the switch right?

cerulean karma
#

yes

fickle sand
#

Then the above automation is sufficient, the chance that you toggle the input boolean and the switch changes at the exact same ms is almost zero

cerulean karma
#

yes the automation seems to work fine, I just came to my question when thinking about it....What would HA do if I create a automation with trigger: on change and action: toggle

fickle sand
#

Yeah you could use input_boolean.toggle instead of the if/then/elseaction, but that is more something for #automations-archived

cerulean karma
#

yes sure....

marble jackal
# cerulean karma yes sure....

you could simplify your automtion (with the use of a small template)

alias: Luftentfeuchter_Status_setzen
trigger:
  - platform: state
    entity_id:
      - switch.shelly_luftentfeuchter
      - input_boolean.luftentfeuchter_status
    not_to: "unavailable"
condition:
  - condition: template
    value_template: >-
      {{ states('input_boolean.luftentfeuchter_status') != states('switch.shelly_luftentfeuchter') }}
action:
  - service: homeassistant.turn_{{ trigger.to_state.state }}"
    target:
      entity_id: >
        {{ [ 'input_boolean.luftentfeuchter_status', 'input_boolean.luftentfeuchter_status' ] | reject('eq', trigger.entity_id) | list }}
mode: single
cerulean karma
#

that looks much better 🙂

#

hm but it works not as expected...If I change the input_boolean it should change back automatically

#

simple said: it should be a excact copy of the switch

#

and when I change it manually it should change back

marble jackal
#

oh wait

#

I misunderstood your intention

cerulean karma
#

background is that I have a "readonly" switch

marble jackal
#
alias: Luftentfeuchter_Status_setzen
trigger:
  - platform: state
    entity_id:
      - switch.shelly_luftentfeuchter
      - input_boolean.luftentfeuchter_status
    not_to: "unavailable"
condition:
  - condition: template
    value_template: >-
      {{ states('input_boolean.luftentfeuchter_status') != states('switch.shelly_luftentfeuchter') }}
action:
  - service: input_boolean.turn_{{ states('switch.shelly_luftentfeuchter') }}
    target:
      entity_id: input_boolean.luftentfeuchter_status
mode: single
#

that should do what you want

cerulean karma
#

no..sorry 🙂

#

I can toggle the boolean in the UI as I want.

marble jackal
#

this does the same as your automation

#

it copies the state of your switch to that of the input_boolean

cerulean karma
#

but what if I manually change the input_boolean to the wrong state?

#

It seems not to correct it again

marble jackal
#

it triggers the automation, and sets it to the state of the switch again

cerulean karma
#

I completly copied the code but it does seems not to do the same as my automation

marble jackal
#

situaton: swith is on, boolean is on

you then toggle the boolean, this will trigger the automation. Your condition will pass, as the states differ.
The action will perform input_boolean.turn_on as the state of the switch is on

#

wait

#

there were some double quotes which shouldn't be there

#

removed it

#

at the end of the service call

cerulean karma
#

Executed: 7. September 2023 um 12:09:03
Error: Template rendered invalid service: input_boolean.turn_off"

#

service: input_boolean.turn_{{ states('switch.shelly_luftentfeuchter') }}"
target:
entity_id: input_boolean.luftentfeuchter_status

marble jackal
#

yes, remove those double quotes after }}

cerulean karma
#

great now it works 🙂

#

interesting to use variables for calling a method

marble jackal
#

not sure why you'd want to do this though

cerulean karma
#

I want to show the state in a entity card without giving the posibility to change it with a "quick" click

#

so I add the input_boolean into the list of the entity_card to visualize the state but have it "readonly"

marble jackal
#

So you have a toggle which doesn't toggle? Why not just create a template binary sensor out of it

cerulean karma
#

Yes I have a not working toggle 🙂

#

don't really understand what you mean with the binary sens

#

I think I got it now....will try that

#

@marble jackal You are right again, I really like that... 🙂

plain magnetBOT
#

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

marble jackal
#

What did you already try?

supple ginkgo
#

Tried using: intent_uri: "google.navigation:q={{ states('input_text.navigate_to') }}"
And a series of other similar strings... I know the variable/helper is working as I can reference that if I send it stright to a notification, Ithink the issue is when I'm trying to use it as part of the intent_uri line...

marble jackal
#

I see no reason why that would not resolve the template to the actual state

#

what does it show if you test it in devtools > template

supple ginkgo
#

The command works in the sense that it starts google maps on my phone and starts the navigation even, but instread of passing the address from the variable the query box on navigation shows the variable name/string...

marble jackal
#

not sure what you mean there, can you upload a picture to imgur and share the link

supple ginkgo
supple ginkgo
tight thicket
#

How can I check if a state of a select option is chosen?

{% if is_state('input_select.trockner_status', 'trocknet') %}
blue
{% else if is_state('input_select.trockner_status', 'fertig') %}
green
{% endif }```
#

does not work

lofty mason
#

I think jinja needs elif not else if. else if is showing me syntax errors in template devtool, have you tried using that?

#

Also you need a %} at the end

tight thicket
#

could have seen that by myself

#

thank you!

glacial relic
#

So there's now a new integration with the "google assistant" where you can send google assistant commands like: "turn on kitchen light" or "turn off office light" and that does work for me preaty well (it has some latency, but overall it works).

However, i'm trying to also send some shopping items to my shopping list that is listed in google keep.
When i say the following command to one of my google nests / displays, it works well:

Add something to the shopping list

So i tried to send the same command using the new google assistant service but that doesn't work.
I don't know why.

service: google_assistant_sdk.send_text_command
data:
  command: add something to the Shopping List
hearty verge
#

Is there a way to mimic a device selector in the template editor to say see all devices wiht a manufactor that equals something?

I'm trying to debug.

It looks like i can take a device id and get an attr from it but nto sure if i can see all the attributes on specific device and/or itterate through every single device

marble jackal
remote perch
#

I saw this message on the forums and it intrigued me about how you can create a sensor of all automations that are currently in progress and Tinkerer mentioned coming here to see how. I've created dozens of template entities, but am curious what this might look like. I never was interested in this before, but as it always goes in home automation - you see something new and you just have to have it even if you don't really need it 🙂

pliant gale
#

Anyone know how I can determine the count and names of automations in progress at any one point in time - using the "current" - with a template sensor or the like (trying to make sure my RPI is not overwhwlemed and concerned when I see CPU spikes that I am not expecting...)?

#

@remote perch I didn't see your message above and I guess I followed you from the forum lol

marble jackal
winter pilot
#

Would this be the best place to post about custom:button-card templating ?

inner mesa
winter pilot
#

ok, thanks!

jovial pilot
#

Working on trying to create a template for a light based pomodoro timer I'm trying to set up. The goal is to have the card either display "Off" or the current duration of the timer, but using the following code:

Off
{% else %}
{{ state_attr('timer.30_minutes','remaining') }}
{%endif%}```
It displays the duration of the timer, not the remaining time. Any suggestions for me?
lofty mason
#

the true remaining time for a timer is not in the state machine, it can't be retrieved with a template. At best you can subtract the finishes_at time from now(), but that only updates once per minute.

#

remaining only updates when it is paused.

#

The entities card will however display the live remaining time for a timer, if you want to use that.

jovial pilot
#

I think that's probably the better way to do it.

#

Thanks for that karwosts

fiery mauve
#

hey, since 2023.9.0 all my templates are gone. also: vscode doesn't work anymore

marble jackal
#

both are unrelated to this channel.
If the whole template integration is broken, that's something for #integrations-archived, VSCode is something for #add-ons-archived (assuming you are referring to the add-on)
This channel is for help with the actual jinja code

fiery mauve
#

oh ok never mind

acoustic arch
#

goodmorning. When ever i turn off ALL lights in the house in one go, sometimes something stays on. Is it because the zigbeenetwork get flooded with commands? Im thinking of looping through all lights that are on, and turn them off with a little interval.

So from some automation i have i found this:

    ['light.voortuin_wand']) | selectattr('state', 'eq', 'on')  |
    map(attribute='entity_id') | list }}```

How can i loop this like a `for each`
marble jackal
#

just use that as the input for the for_each

acoustic arch
#

ill have a go at it. ill search for for_each

marble jackal
#

it's on of the options of the repeat action

acoustic arch
#

found it thx. step 1 is to exclude some rooms.

marble jackal
#

are all your lights zigbee?

acoustic arch
#

no, some are wifi

#
  | selectattr ( 'domain' , 'eq' , 'light' )
  | selectattr('state', 'eq', 'on')
  | map ( attribute = 'entity_id' )
  | list }}```
#

i cant add keuken to the area_entities

#

because of my lack of knowlegde in synta 😉

marble jackal
#

I would put all the lights you want to turn off in a zigbee group, and turn that group off

acoustic arch
#

the zigbee relays through 2 sets of ikea gui10... and i hate them

#

they need resetting sometimes

marble jackal
#

you can't add multiple areas to area_entities

acoustic arch
#

anyway.... i prefer to turn them off one by one... with 1sec intervals. Is kinda fancy as well

marble jackal
#

you can do expand(area_entities('woonkamer') + area_entities('keuken'))

acoustic arch
#

that looks good!

marble jackal
#

but you don't need to expand them anyway

acoustic arch
marble jackal
#

(area_entities('woonkamer') + area_entities('keuken')) | select('search', '^light.') | select('is_state', 'on') | list

acoustic arch
#

devtools template tools says YES 😆

#

step 2. for each. ill be back 😉

marble jackal
acoustic arch
#

thx for the help

#

its all working.

cerulean karma
#
{% set x = "AAA" %}
{%- for i in range(1, 10) -%}
  {% set x = "BBB" %}
{% endfor %}
{{ x }}
#

why is x still "AAA"?

#

does the for loop change the context?

marble jackal
#

because of scope

#

the changes done inside the for loop are done there, the variable outside the scope is unaffected. The x in your loop is basically a diffent x then the one outside it.

#

you need to define a namespace to have access to them outside the loop

#
{% set x = namespace(value="AAA") %}
{%- for i in range(1, 10) -%}
  {% set x.value = "BBB" %}
{% endfor %}
{{ x.value }}
cerulean karma
#

oh thought I create a global var whem putting it on top

marble jackal
#

no, jinja works different here compared to python

cerulean karma
#

uff 😦

#

ok thanks for that 🙂

stuck sedge
#

Is there a way to get locale-specific formatting of dates in templates? Like day-names in norwegian?

mighty ledge
#

No

#

You have to fully template it

#

I mean "Yes", but it's not simple like using strftime

plain magnetBOT
#

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

mighty ledge
#

or, don't use a target selector as they are the hardest to work with when trying to get an entity list

vagrant monolith
#

How can I use that to just contain the ones in my "entities" field?

>
  {%- set ns = namespace(ret=[]) %}
  {%- for key in ['device_id', 'area_id', 'entity_id'] %}
    {%- set items = lights.get(key, [])  %}
    {%- if items %}
      {%- set items = [ items ] if items is string else items %}
      {%- set filt = key.split('_') | first %}
      {%- set items = items if filt == 'entity' else items | map(filt ~ '_entities') | sum(start=[]) %}
      {%- set ns.ret = ns.ret + [ items ] %}
    {%- endif %}
  {%- endfor %}
  {{ ns.ret | sum(start=[]) }}
mighty ledge
#

You have to use all 3 templates in that post

#

your selector is mapped to a variable named lights

#

e.g.

#
variables:
  lights: !input light_target
  device: ...
  area: ...
  entities: ...
#

then, use "{{ entities }}" for your snapshot entities template.

vagrant monolith
#

Failed to call service script.flash_house. Entity IDs cannot be None for dictionary value @ data['snapshot_entities']. Got None

plain magnetBOT
#

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

mighty ledge
#

you're spacing isn't correct

vagrant monolith
#

Where? :P

#

Oh right

mighty ledge
#

also, you don't have quotes around your entities template

vagrant monolith
#

So it sayd object objcet now

plain magnetBOT
#

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

#

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

mighty ledge
#

You're doing htis in all yaml right? No UI?

#

if you choose to use the UI for this, you cannot switch to UI mode

#

only view it in yaml mode

#

aside from that, it will work.

vagrant monolith
#

Yes I view in in yaml only yes

mighty ledge
#

Then just run it and it should work

#

if it doesn't, post the full json trace here using a share site

plain magnetBOT
#

@vagrant monolith 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.

vagrant monolith
#
color:
  - 224
  - 27
  - 36
repeat: 1
entities:
  entity_id:
    - light.axel_bedroom_window
    - light.axel_bedroom_bed
    - light.axel_bedroom_wardrobe

This doesnt work

mighty ledge
#

see my post above

#

I can't help without traces

vagrant monolith
#

How do I find traces?

mighty ledge
#

Go to the scripts page, and view the trace

stuck sedge
stuck sedge
mighty ledge
warped marsh
#

Hi, i am trying to make a switch to mount my synology crypto folder by ssh, but i always get the log command failed.
The keyless ssh login works from the homeassist terminal and the command also works after logging in.
But when i try to test the command from HA terminal, i get ash: synoshare: command not found.
The command is: ssh -i /config/.ssh/diskstation_rsa -o 'StrictHostKeyChecking=no' -q root@192.168.178.69 'synoshare --enc_mount \"crypto\" _PASSWORD_'
(I also tried simple commands like MyHostName with the same result)

little forge
#

anyone spots why below doesn't work? {% set state = states('sensor.pir_living_illuminance_lux') %} {% set low = states('input_number.light_threshold_dark') %} {% set high = states('input_number.light_threshold_daylight') %} {% if is_number(state) and state > high %} daylight {% elif state < low %} dark {% else %} in between {% endif %}

#

it alternates between daylight & dark, also when the value is clearly between

inner mesa
#

All states are strings

#

You're checking if it's a number, but not actually converting it into one before the comparison

#

Add |float(0) (or whatever default you want) to each of the first three lines, and you can get rid of the is_number check

little forge
#

doh. thanks Rob

visual matrix
#

Is there any way of using the chosen entity_id in a script for the data value? Ex: using the input_number.set_value service

#

service: input_number.set_value data: entity_id: input_number.{{ states('sensor.pick_the_good_input_number_to_play_with') }} value: >- {% set number = entity_id.state |int + states('number.dynamicincrement') |int %} {{ number }}

#

Would appreciate if someone can point me in the right direction

mighty ledge
#

you have to build the entity_id again and then use the states() function in your value template

final lark
#

Hello, since the update 2023.9. One of my template is triggered twice where previously it was triggered only one time

#

the trigger is very simple

- trigger:
    - platform: state
      entity_id: binary_sensor.grid_calculation
      to: "on"
mighty ledge
#

that's not a template

final lark
#

and this binary_sensor.grid_calculation is having an auto-off after 120 sec.
till now I never had issue with the calculation

plain magnetBOT
#

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

final lark
mighty ledge
#

regardless, if it's triggering twice, it's not a template issue

#

keep in mind, this channel is about templates, not the template integration or triggers

final lark
#

but they added action block in the release, not link to that ?

mighty ledge
#

it could be but that's the template integration 😉

final lark
#

oh ok , I got it

mighty ledge
#

anyways, nothing with the new action section changed triggers

#

so your issue is with binary_sensor.grid_calculation

final lark
#

ok. but something change 🙂

mighty ledge
#

I doubt it

final lark
#

thank you petro for the notice

mighty ledge
#

I bet you that your binary_sensor is going on -> unavailable -> on

#

so, verify that your binary sensor is working properly

final lark
#

nope it's on or off (only the first time after loading it's unavailable)

mighty ledge
#

well thatw ould cause an extra trigger

final lark
#

condition is to: "on"

mighty ledge
#

yes, but if it goes from unavailabe to on, it will trigger

final lark
#

yes indeed.

mighty ledge
#

if it goes any state to on it will trigger

#

and there are 4 possible states: off, unknown, unavailable, and on

#

on -> on will not trigger

#

all the rest will

plain magnetBOT
#

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

final lark
#

I know that petro.

mighty ledge
#

that's not the full template integration

final lark
#

that's part of it

mighty ledge
#

right but how can we debug it without the trigger

plain magnetBOT
#

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

mighty ledge
#

it also has no safety built into it

final lark
#

Everything was running since 2 months

#

I just update to 2023.9 from 2023.8.4

#

then value received now is twice the value.
example: delta is 0.2 and at the moment is binary is on , I see 0.2 +0.2

#

where before it was 0.2

mighty ledge
#

and are there errors in your logs? None of your to_states/from_states have proper defaults applied to the float conversions

final lark
#

nothing change

#

no errors ...

mighty ledge
#

Yes, I get nothing changed, but nothing changed with HA in regards to triggers

#

I'm trying to lead you to the real problem instead of focusing on what you think is the problem

final lark
#

my assumption was, mhh they introduce action block then may be it goes twice due to that

#

the binary is very simple case here with auto_off

#

so it's on by the template and auto off ... nothing more than that

mighty ledge
#

it's not that simple, you have no safety built into that

#

and your trigger is a state change trigger

#

which could be unavailable to a value

final lark
#

when it raised to on ; calculation is passing twice ... I have put a count-in on it , I'm waiting some sun 🙂

mighty ledge
#

it depends on how sensor.filtered_electricity_meter behaves at startup, or in general

#

you have 0 unavaiable safty built into all your templates. Meaning it all those can go unavailable.

final lark
#

the value is fine there

mighty ledge
#

Well, the create an issue and provide proof that it’s triggering twice

final lark
#

yes, I will do some template to simulate the case

#

from now... I'm suspect something wrong but I cannot point where exactly.

mighty ledge
#

I’m 100% sure nothing is wrong.

#

But I’ll let you do you

#

It’s all the same trigger code everywhere. Literally.

#

You’d see this issue in automations. And the pr to add actions was small, and does not touch triggers.

final lark
#

ok . I need to leave , my wife is waiting me ... 😉 thank you already for the small chat petro for helping me

visual matrix
floral steeple
#

today I learned something new about using the ChatGPT prompts, turns out if I simply use this prompt, the quote is the always the same (this is part of a morning greet automation that runs when I enter the office):

  - service: conversation.process
    data:
      agent_id: [redacted]
      text: tell me a random quote
    response_variable: quote

so, I have to add something variable to it like date, time, temperature. If I use date or time, would it be something like this?
text: tell me a random quote {{ now }}

inner mesa
#

Yes

#

Maybe it's caching the results to throttle requests? Aren't they limited?

floral steeple
#

im not sure, its a paid plan so I hope they are not doing that

#

she was very polite, but this was the responce to that above:

        speech: >-
          Apologies for the confusion, but it seems there's been an error in
          your request. If you're looking for a random quote, here's one for
          you:


          "Life is what happens when you're busy making other plans." - John
          Lennon
#

I've heard the John Lennon quote like 20 times already 🙂

#

using {{ now }} in the template editor, gives an output of <function now at 0x7f120eeac0>

#

maybe I have to convert it actual date

inner mesa
#

now()

floral steeple
#

ahh ok, that didn't work either, but the responce was a bit better

speech: >-
          I'm sorry, but as an AI, I don't have the ability to predict or
          generate specific quotes for future dates. I can provide a general
          motivational quote if you'd like. Here's one:


          "Believe you can and you're halfway there." - Theodore Roosevelt

if I change the prompt to "provide me a general motivational quote" this so far is working
Also, someone mentioned upping the temperature.

#

ok, this robot needs a bit of training

#

ok, its back to repeating Roosevelt

inner mesa
#

He didn't say how to finish the other half

floral steeple
#

ok this seems to work, I did it 6 times and it gave me 6 different quotes every time, not a template solution though
generate a beautiful quote...

#

ill post the quote last trace for you RobC

      Here is your AI generated quote of the day Life is like a camera. Just
      focus on what's important, capture the good times, develop from the
      negatives, and if things don't work out, just take another shot.
#

😀

floral steeple
#

Maybe I can template the word beautiful to randomly pick other adjectives

#

beautiful, calming, mathematical, scientific, political,

#

Etc.

#

And the word is picked at random

#

generate a {{ [ "motivational", "scientific", "calming", "mathematical", "political", "religious","beautiful"] | random }} quote...

#

How's my syntax here?

inner mesa
#

Try it in devtools -> Templates

floral steeple
#

thanks, Rob. This works

  - service: conversation.process
    data:
      agent_id: [redacted]
      text: >-
        generate a {{ [ "motivational", "scientific", "calming", "mathematical",
        "political", "religious", "beautiful" ] | random }} quote...
    response_variable: quote
tight thicket
#

Hey, I have a template sensor with round(1) but it shows me the value with a . instead of a ,
what can I do about this?

{{ states('sensor.balkonkraftwerk_efficiency') | float | round(1) }} %
#

All other values are shown with ,

marble jackal
#

If you put it on your dashboard, it will show a comma

#

You might need to have a unit of measurement for that though

silver pewter
#

Hi all! I want to set a input datetime with date NOW + 30 days. But i dont know how, The example below works with a entity + 30 days. but i want to use like "now()" somehow 🙂 anyone knows how? 😄

{{ (state_attr('input_datetime.dishwasher_last_clean_date', 'timestamp') + 2592000) | timestamp_custom('%Y-%m-%d')}}

and

{{ (states('input_datetime.dishwasher_last_clean_date') | as_datetime + timedelta(days=30)).isoformat() }}
marble jackal
#

{{ now() + timedelta(days=30) }}

#

You don't need to convert it to a string

silent vector
#

I'm having quite the struggle formatting to add a thousands separator comma. I know I can use state measurement number and the UI would add it but this is a template with a lot of attributes I would rather not make a sensor per attribute.

"{:,.2f}"
"{0:,.2f}"
'{0:,}'
'{:,}'

{{ '{:,.2f}' | format('225344') }}
All get me TypeError: not all arguments converted during string formatting

tight thicket
marble jackal
tight thicket
#

unit_of_measurement is %

silver pewter
final lark
# mighty ledge Well, the create an issue and provide proof that it’s triggering twice

Hello @mighty ledge
from the issue of yesterday, it's triggered one time but the template is processing twice the data.
I created an automation with the same trigger as in the template integration and as action write in system logs.
So it's sure that is not triggered twice but the issue of calculation and the template itself is for sure doing twice the work.
Each time the trigger is it, the counting attribute is having +2

drifting kraken
marble jackal
#

What's your code?

drifting kraken
marble jackal
#

Note that it expects a number, not a string

#

And format is a Python method, not a filter

silent vector
inner mesa
#

only in dev->templates, I would guess

#

it sees the comma and thinks it's a list

marble jackal
#

Not sure why it does that, it will output fine if you add more text

silent vector
#

Oh ok then I actually had it right earlier 🤦‍♂️ I was thrown off by the list

#

Thank you both

lapis gust
#

In some configurations of others i see a state trigger -> to: ~ I cannot find anything in the documantation about trigger to "tilde". Can someone explain or give directions where i can find info in the documentation?

lofty mason
# lapis gust In some configurations of others i see a state trigger -> to: ~ I cannot find a...

It was published here, though it does seem to be missing from the trigger documentation 🤔
https://www.home-assistant.io/blog/2021/12/11/release-202112/#triggering-on-any-but-only-state-changes

Basically it's the same thing as to: , which is documented. I believe it's just a feature of YAML syntax, that an empty value, ~, null, Null, and NULL are all accepted as the same thing.
(also I see this is not a templates question)

rough blaze
#

Trying to create my first template by reading the temperature of a weather entity. I have the following, and I have loaded all yamls, but when look up dev tools states, I do not see the template.

#
  • platform: template
    sensors:
    weather_temp:
    friendly_name: "Weather Temperature"
    unit_of_measurement: 'degrees'
    value_template: "{{ state_attr('weather.local_weather', 'temperature') }}"
lofty mason
#

IIRC if it's your very first template, you need to do a reboot, and not just a yaml hot reload

rough blaze
#

Can do.

#

That did it! TY @lofty mason

lofty mason
#

In the future you can do yaml reload for changes or additions of new templates. It's just that when you have none, the platform is not even loaded, so it doesn't know how to do reload.

red pebble
#

Hope this is the correct channel to post this apologise if not. I have a Zigbee double socket that I control with the following Yaml using the Value_template but I guess I need a condition as when I operate one switch it affects the other as they both have the same value of 'Power' but there is another value of 'Endpoint' which is either 1 or 2.

plain magnetBOT
#

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

fickle kettle
#

any way to convert existing template sensors (edited in yaml) into the new UI-driven ones?

#

I can see the new sensor created in /config/.storage/core.entity_registry and core.config_entries....

#

Also, is there any way to get a multi-line template editor in the UI (for those new templates)?

#

Also, is there any way to export/import these?

mighty ledge
mighty ledge
fickle kettle
uneven pendant
#

Sensor goes to 'Unknown' because the host is offline

#

Command failed (with return code 255): ssh -i /config/.ssh/brendyn -o 'StrictHostKeyChecking=no' pizza@192.168.51.25 "type interactive.txt"

#

When the whole point is to show the host is offline

#

I use a avlue template if yes, true, else false

#

Why is it ignoring my template?

cerulean karma
#

Good Morning

#

is this the right way (especially the last line) to make sure, that the sensory will have a valid value? No matter if there is a unknown/unavailable sensor before?

plain magnetBOT
#

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

cerulean karma
#

Or is there something like a try...catch that you should use?

merry marsh
#

What is best practice or best working way to manual manipulate/correct data of a trigger template? If I do it via developer tools or via python hack services or custom integrations, which can set values to sensors, it is returning back to the old value after HA restart. As far as I tried until now.

The way I'm currently using is another trigger (template reload) and then a value temporarily assignment in changing the template. Then reload. And then reverting back to the wanted template and reloading again. Then it ofc stays.

But I wonder if there is an easier/better way.

marble jackal
#

You want to manipulate the state of a trigger based template sensor?

merry marsh
#

Yes

marble jackal
#

I would use an event trigger, and send a custom event in your automation

#

What's the use case here?

merry marsh
#

Correct wrong data because of HA bug. 😂

marble jackal
#

Okay, but you want to use the state of a sensor unless it's faulty?

merry marsh
#

After I correct it it is not faulty anymore at the moment.

merry marsh
# marble jackal What's the use case here?

I have no automation here. Then perhaps my current way is faster. I only thought there is a value box or way, where I can directly set it to a new value and where it stays after reboot.

marble jackal
#

You can also send the event in devtools, or just use an input_number

marsh cairn
#

Is the correction consistent (like dividing by 10,100,... or addition/substraction)?

merry marsh
acoustic arch
#
data:
  message: >-
   {{ states('sensor.mobiel_xxx_last_notification','android.text') }}```

When i template the state with dev tools, its the full long text. But when i use it in this write-to-file-service, its get cut to a certain amount of chars. Didnt count but maybe 255 chars?
#

so im using an attribute which can contain more then 255 chars. So its something the service-call chops up to 255

cerulean karma
#

What is the best way to change the values from a devicetracker from athome+away to on+off?

#

do I really have to create binarysensors for each?

jagged obsidian
#

probably but why do you need them to be on/off?

cerulean karma
#

I use them to represent the state of Laptop/PC,... in a custom:mushroom-entity-card.

#

and if the Laptop is powered on the card says "At home"

jagged obsidian
#

does the card support templating?

cerulean karma
#

I do not think so, but let me look that up

#

there is nothing to fix it I think

cerulean karma
#

ah that could be working, thanks 🙂

#

this works great!

acoustic arch
#
  {{ states.sensor  | selectattr('entity_id', 'search', 'tgtg') | map(attribute='state') | map('int', 0) | list | sum  }} beschikbaar
{%else%}
geen TGTG
{%endif%}```
NOW: This does a count(adds) all states of all selected entities, whenever they are non zero. for example 21 is the output from 4 entities.
WISH: Output the amount of entities which has it state non zero. So i don want 21. but 4.
mighty ledge
#

you joking?

#

you literally have the code in that template that gets what you want

acoustic arch
#

do i? lol

mighty ledge
#

yes you do