#templates-archived

1 messages · Page 35 of 1

quiet kite
#

Hi, I have a problem with the code posted above. Problem is that the code sends to MQTT: BSB-LAN=S1000= but i need to send BSB-LAN=S1000=0 or 1 2 3, so my code dont send value.

mighty ledge
#

you have {0:'....', it needs to be {'....':0

quiet kite
#

thanks, it works 😉

cold crag
#

Hello !

plain magnetBOT
#

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

cold crag
#

I would like to integrate this chart in this map

#

thanks 😄

stuck remnant
stuck remnant
#

yes but I don't know where to plug it

mighty ledge
#

Where ever you want to use it

#

Only you know what you want to do with that info, so…

stuck remnant
#

I want to have one entity automated so as to reflect the inverse of the other

#

how would I go about using that template to do that

mighty ledge
#

Then you put that in a service call that turns on the other light

stuck remnant
#

yes that's what I'm saying I don't know how to write it

mighty ledge
#

It’s an automation, create the automation first. Then paste that template in the rgb field

stuck remnant
#

with which of the entities pasted instead of some_light

#

is the entity in the template the one that will receive the inverted values?

mighty ledge
#

No

stuck remnant
#

or is it the one from which the normal values will be extracted

#

oh okay

mighty ledge
#

It’s getting the values. {{ }} is outputting the value

stuck remnant
#

I don't know the indentation, this is what I got:
action:

  • service: light.turn_on
    data:
    rgb_color: {% set r, g, b = state_attr('light.main', 'rgb_color') %}
    {{ (255 - r, 255 - g, 255 - b) }}
#

doesn't seem to work like this though

lofty mason
stuck remnant
marble jackal
#

Is your main light on, and did you use the right entity id

cyan musk
#

I'm trying to do an automation involving conditions and triggers for automations (to send in a notification)

    states(trigger.entity_id) == 'on' else state_attr('trigger.entity_id',
    'friendly_name') + ' has finished!'}}```
This doesn't end up working though, what am I doing wrong 😄
rose scroll
cyan musk
#

Thanks!

floral shuttle
#

ive been using this entity like for ages, and in ways like:``` {% set timestamp = states('sensor.next_alarm_timestamp')|int(default=0) %}
{% if timestamp %}
{% set time = now().replace(second=0).replace(microsecond=0) %}
{% set midnight = now().replace(hour=0).replace(minute=0).timestamp() + 86400 %}
{% if timestamp > midnight %}
{{((timestamp - time.timestamp()) // 86000)|int + 1}}
{% else %} 0
{% endif %}
{% else %}
-1
{% endif %}

marble jackal
#

Use as_datetime on the result

#

Oh wait, you are calculating the number of days

#

Just make sure the result is the datetime of the date and time you want to show

#

So something like 2023-04-01 01:16:42.230853+02:00

#

If that's the state of your sensor, it will be shown as relative time on your dashboard

floral shuttle
#

the main sensor currently outputs 1680495600, which is the timestamp int of my next alarm. I (currently) need it to be in tht format, for all other template sensors on that output

#

like the one I posted above, or {% set timestamp = states('sensor.next_alarm_timestamp')|int(default=0) %} {% if timestamp %} {{timestamp|timestamp_custom('%H:%M')}} {% else %} Geen wekker {% endif %}

#

I've always lived with the idea it Was outputting a timestamp, so was surprised actually adding the device_class to it errors out

marble jackal
#

Well, the timestamp device class is a bit strange, as it doesn't expect a timestamp as input

floral shuttle
#

right! i keep forgetting that....

#

i can do this: {{as_datetime(states('sensor.next_alarm_timestamp'))|as_local}} and make it an extra template sensor 😉

#

yes, that works, this is format relative (or no format at all)

#

and this is more-info (or format: datetime in an entities card). That is what @half pendant) was after? :

#

too bad it flukes to Unknown when there is no alarm set... {% set timestamp = states('sensor.next_alarm_timestamp')|int(default=0) %} {% if timestamp %} {{as_datetime(timestamp)|as_local}} {% else %} Not set {% endif %} device_class: timestamp

marble jackal
#

You can use an availability template and make it unavailable

floral shuttle
#

Ok. Solved it for now by using a type: conditional row in the dashboard

sonic ember
#

What am I doing wrong here to be able to compare a datetime to the current time?

{% if states('input_datetime.washing_machine_start_time')|as_datetime() < now() %}
  No time has been set
{% else %}
  Wash will run at {{ states('input_datetime.washing_machine_start_time') }}
{% endif %}

It says: TypeError: can't compare offset-naive and offset-aware datetimes

marble jackal
#

Add | as_local to add the timezone information to the datetime created from the input_datetime

floral shuttle
#

this might be a bit too complex, but given we should be able to do system wide jinja templates in 2023.4 +, Id would like to try and set a first in my config. Translating dates seems a very useful one. {% set volgende = state_attr('sensor.daylight_savings_times','next') %} {%- set next = as_timestamp(volgende.event,0) %} {% set months = ['Januari','Februari','Maart','April','Mei','Juni','Juli', 'Augustus','September','Oktober','November','December'] %} {%- set wdays = ['Zondag','Maandag','Dinsdag','Woensdag','Donderdag', 'Vrijdag','Zaterdag'] %} {%- set wday = next|timestamp_custom('%w',default=none)|int(default=0) %} {%- set month = next|timestamp_custom('%m',default=none)|int(default=0) %} {% set datum = next|timestamp_custom(wdays[wday] ~ ' %-d ' ~ months[month-1] ~ ' %Y' )%} {{datum}} is what I have , but tbh, I am a bit lost how to translate that to a custom_templates, and, next, use it in my regular template sensors.

#

I made a global_macros.yaml file in the custom_templates folder, and have this as first try: {% macro translate_date_datum(entity_id) %} {%- set date = as_timestamp(states(entity_id)) %} {% set months = ['Januari','Februari','Maart','April','Mei','Juni','Juli', 'Augustus','September','Oktober','November','December'] %} {%- set wdays = ['Zondag','Maandag','Dinsdag','Woensdag','Donderdag', 'Vrijdag','Zaterdag'] %} {%- set wday = date|timestamp_custom('%w',default=none)|int(default=0) %} {%- set month = date|timestamp_custom('%m',default=none)|int(default=0) %} {% set datum = date|timestamp_custom(wdays[wday] ~ ' %-d ' ~ months[month-1] ~ ' %Y' )%} {{datum}} {% endmacro %}

marble jackal
#

This looks fine at first glance

floral shuttle
#

on the file name and contents: in the release notes /config/custom_templates/tools.jinja is used. the .jinja is somewhat peculiar for a folder name, but maybe it is a fixed name? I named it /global_macros.yaml without checking that tbh, and it does not error... second, I presume we can create more than 1 macro in that file? Or do we need a single macro file.

#

btw, how do we load those? I tried the example, and reload templates, but it still returns UndefinedError: 'is_on' is undefined

#

heck, I am in the wrong # sorry, I'll hop over to #beta

marble jackal
#

No, you need a .jinja file, not a .yaml file

final sun
#

Hi, I am trying to display the "Finishes at" Attribute of a sensor (timer.test2).
This is listed in the attributes: Finishes at
April 2, 2023 at 21:25:48

{{state_attr("timer.test2","Finishes at")}}

This returns None though. Am I missing something?

marble jackal
#

Yes, check in devtools > states how the attribute actually named

final sun
#

Ah got it ty 👍

marble jackal
#

Don't trust the translated names on your dashboard

velvet glen
#

Hi folks, simple ask hopefully. I've got a wled set up that I'm wanting to show a percentage battery charge for each LED (eg if 12% charged, then just light 12 LEDs and so on). All set up fine and final step is to connect the sensor I have in home assistant with the LEDs. This works with a fixed value for the 'percentage' value, I'm just not sure how to add a template value in yaml, can anyone help?

https://pastebin.com/byZnJS0A

#

You can see my code which works perfectly if I manually change the value - eg 50 in example, I just need this to set the WLED value to that of sensor.battery_percent_2 dynamically

mighty ledge
#

You have to use a service call

velvet glen
#

Ah ok - although I can't see a service call for my WLED? Am I being stupid?

mighty ledge
#

Service calls don’t care about the integration

#

They care about the entity

#

So look up services that you can perform on number entities

velvet glen
#

Yeah, think I've got that - ie it's number.wled_dragon_intensity that I want to change, just struggling with the jumble of home assistant current, forked and legacy approaches to this

#

I can't see how to call this in the automation setting, some tutorials say to give up on HA's automation approach and go back to manually code it all in YAML, some point to other methods

#

I'm trying to use the tautologous select.select_option approach that some tutorials suggested, but doesn't seem to work, ie even hardcoding the value at the moment: service: select.select_option
data:
option: "20"
target:
entity_id: number.wled_dragon_intensity

mighty ledge
#

Match the domains

#

number.xyz will have number.abc services

#

FYI use the documentation

#

Tutorials don’t cover crap, documentation for number will tell you all the services that are available

jolly crest
#

Hey! Should there be any options to change unit when I open the settings for my standard MET weather sensor? There are no options there. Do I have to make a template for the options to show?

marble jackal
#

But I just looked at mine, and I can change the unit of measurement for most

jolly crest
#

So strange. Cant understand it

#

But thanks!

ripe bronze
#

Hey can somebody help me with this template: https://dpaste.org/b3BUr I get this Error: Message malformed: not a valid value for dictionary value @ data['action'][0]['entity_id']

marble jackal
#

you can't use templates there

#

either place entity_id under target: or data:

#

and this doesn't look right either:

  - condition: template
    value_template: "\"{{ trigger.to_state != trigger.from_state }}\""
#

you don't need that, you can add an empty to: or for: to the trigger to make it only trigger on state changes, and not on attribute changes

ripe bronze
marble jackal
#

I see a big difference between what's there, and what you have

- condition: template
  value_template: "{{ trigger.to_state != trigger.from_state }}"

vs:

- condition: template
  value_template: "\"{{ trigger.to_state != trigger.from_state }}\""
#

and it's a post from October 2020, so it's a bit outdated, the functionality with the empty for: or to: didn't exist then

#

also, this:

service: scene.turn_on
data_template:
  entity_id: >
    {{ states('input_select.living_room_scene_select') }}

differs from:

service: scene.turn_on
entity_id: >
  {{ states('input_select.living_room_scene_select') }}
#

I do think data_template was already depreciated in October 2020.

#

So, what will work is:

alias: "s14"
trigger:
  - platform: state
    entity_id:
      - input_select.s14
    to: 
action:
  - service: scene.turn_on
    target:
      entity_id: >
        {{ states('input_select.living_room_scene_select') }}
mode: single
peak juniper
#

Not sure where to put this but I have a question about a restful sensor that only seems to update its value on a HA restart

mighty ledge
#

It should update on the scan interval

peak juniper
#

hmmm, I don't have a scan interval set

#

it used to work fine, used to update every evening

#

presumably it would use the default setting and try to pull info every 30 seconds?

#
  - platform: rest
    name: "Vanguard: Global All Cap"
    resource: https://api.vanguard.com/rs/gre/gra/1.7.0/datasets/urd-product-details?path=[id=vanguard-ftse-global-all-cap-index-fund-gbp-acc][0].navPrice.value
    value_template: >-
        {{ value.split('"')[1] }}
#

this is the rest sensor. It usually stays on the same value for a few days

mighty ledge
peak juniper
#

because it takes the data from a specific element on that webpage

mighty ledge
#

yeah but you can avoid that

#

and do it in your value_template

#

and write code to find the actual value you want

#

instead of defaulting to the first element

peak juniper
#

would that have an impact on the scan interval and why it's not updating?

mighty ledge
#

🤷‍♂️

peak juniper
#

😄

mighty ledge
#

keep in mind that those things will not update unless the source updates

peak juniper
#

the source updates every night, usually at midnight but sometimes an hour or two afterwards

#

a restart of HA forces the sensor to reflect the new value

mighty ledge
#

You could try this: {{ value_json | selectattr('id','eq', 'vanguard-ftse-global-all-cap-index-fund-gbp-acc') | map(attribute='navPrice.value') | first }}

#

with https://api.vanguard.com/rs/gre/gra/1.7.0/datasets/urd-product-details

#

either way, it should update every 30 seconds

peak juniper
#
  - platform: rest
    name: "Vanguard: Global All Cap"
    resource: https://api.vanguard.com/rs/gre/gra/1.7.0/datasets/urd-product-details
    value_template: >-
        {{ value_json | selectattr('id','eq', 'vanguard-ftse-global-all-cap-index-fund-gbp-acc') | map(attribute='navPrice.value') | first }}
#

like this?

mighty ledge
#

yep

peak juniper
#

ok, thanks, will try that and see if that updates properly

compact robin
#

Hello, I'm trying to create a template that changes the icon color of that card if it has less than 15 seconds remaining on the timer, but so far, failing really hard with it:
{% if states('timer.bedroom_ceiling')|int >= 15 %} red {% elif states('timer.bedroom_ceiling')|int < 20 %} yellow {% endif %}

#

I just wanted the icon to show as red if it = or lower than 15 seconds (before ending).
Other than that, could keep the regular color.

inner mesa
#

you can use the finishes_at attribute

compact robin
#

Like this? {% if state_attr('timer.kitchen_ceiling', 'finishes_at') >= '00:00:15' %} red {% else %} disabled {% endif %}

#

I was trying with duration, sometimes it did work, but there's something I'm still not getting and I think it's the time format.

#

How would the finishes_at work considering it's format looks like this: 2023-04-03T16:29:47+00:00

inner mesa
#

you need to review the state and attributes in devtools -> States

#

"finishes_at" is a string representing when the timer will finish

#

something like:

{% set sec_remain = (state_attr('timer.test', 'finishes_at')|default(now(), True)).astimezone().second %}
{{ iif(sec_remain < 15, 'red', 'green') }}
#

but it won't update every second

compact robin
#

@inner mesa It works for the green, but when the timer is counting and should be showing red, it's showing white (like the code's broken).

#

But yes, we seem to be in the right direction cus now it moves. I've tried using different formats like 00:00:15 and '00:00:15' to no success.

inner mesa
#

if you're referring to your original code, yes, because the attribute isn't the remaining time

compact robin
#

Okay, doing some testing, it's misbehaving.
I've used this exact code right now: {% set sec_remain = (state_attr('timer.kitchen_ceiling', 'finishes_at')|default(now(), True)).astimezone().second %} {{ iif(sec_remain < 30, 'red', 'disabled') }}

What's happening is: If the timer is idle, it's showing red (right after finishing). If it's counting - when it should be showing, it's showing white - like there's some broken code, and when the timer is idle after 30 seconds... it's showing the disabled color.

compact robin
#

Did some tests with this, but also seem to remain active for a long time after it goes back to idle:

{{ iif(sec_remain < 30, 'red', 'disabled') }}```
inner mesa
#

My code was also missing the subtraction of now() to get the difference. In any case, there's a way to do it, but I'm tied up in mtgs right now

compact robin
#

No big deal, I'd still appreciate some help cus this surpasses my understanding on template sentences. No rush at all, when you can you can 😄 feel free to @ if you have the time. Thank you!

marble jackal
#

@compact robin what you want won't work, as the template will only update once per minute

#
{% set sec_remain = (state_attr('remaining', 'timer.kitchen_ceiling') | as_datetime | as_local - now()).total_seconds() %}
{{ iif(sec_remain < 30, 'red', 'disabled') }}```
inner mesa
#

would have to make a template sensor with a time_pattern trigger, I think

#

the problem with what you have there is that the attribute disappears when the timer isn't running

#

it gets complicated

#

that's backward :()

marble jackal
#

Yes, that's true, I was saving that for the next step 😅

inner mesa
#

dealing with datetime objects in attributes that are represented as timezone-naive strings drives me crazy

#

also, that disappear

compact robin
#

Okay I was completely unaware this would be this hard to make / pull off but kinda explains the why I barely seen anyone trying to do the same anywhere else.

#

Not wanting to create a nightmare out of this, what if, instead of 30 seconds, it would use 60 seconds. Would that work since it's the refresh time it has natively ?

#

Or would that still missbehave cus the "per minute" update would still be really inconsistent?

#

The time pattern trigger would be like a forced update each X seconds ?

#

Or, if there's a way to trigger an automation with a exact number, creating a new timer per area with 60 seconds, that would start once the other timers reached 60 seconds and I could use the new timer with a conditional card and the icon always red. It's a workaround. Would that be easier ?

glad tendon
#

Battery Sensor Template

marble jackal
compact robin
#

I wanted to make a conditional card with a template card with just the icon, that would show red instead of the regular "white" when it was about to finish. It's for my room cards, on the home page.

#

I already have them showing when they're active. But this is waaaay more complex lol.

tacit sun
#

I have a list of key:value pairs. I want to store these in an array of some sort so that based on a sensor reading (will match the key), I will output the matching value.

Can this be done via template?

compact robin
tacit sun
#

ok... so... I have this: (which works if I pass the key directly)

{% set weatherCode = { '500':'light rain', '501':'moderate rain', '502':'heavy intensity rain' } %}
{{ weatherCode['500'] }} 

How can I use the sensor reading as the key?
Something like:

{{ weatherCode[states('sensor.openweathermap_weather_code')] }} 
mighty ledge
#

but that's not an array, it's a dictionary

tacit sun
#

right, I saw your comments. 🙂

#

I think I just got it...

#

{{ weatherCode[states('sensor.openweathermap_weather_code') | string] }}

mighty ledge
#

my comments?

#

oh, in the link 🤣

#

apparently I'm consistent

tacit sun
#

yeah... you were the main commenter in that article

#

😄

#

on the plus side... that thread solved my issue... so... thanks!

mighty ledge
#

np

#

wow, thats 5 years old

#

too

tacit sun
#

lol - best advice has no expiration?

mighty ledge
#

🤷‍♂️

tacit sun
#

in a template if statement... is there such a thing as:
if number is between x and y then?

inner mesa
#

{{ 3 in range(2, 4) }}

#

-> true

tacit sun
#

Thanks!

inner mesa
#

To be clear, that checks for exact integer matches in that range and not whether a decimal value is between those two numbers. x < y < z, maybe with <= if needed, may be more what you want. @tacit sun

#

in other words, the first one checks if 3 is exactly equal to 2, 3, or 4, rather than 3 being between 2 and 4

tacit sun
#

this should work... because I cast it to int?

%- elif states('sensor.openweathermap_feels_like_temperature') | int in range(41,55) -%}
inner mesa
#

that doesn't matter

#

actually, I guess that would work

tacit sun
#
{%- if states('sensor.openweathermap_feels_like_temperature') | int <= 40 -%}
    /Icons/cold.png
  {%- elif states('sensor.openweathermap_feels_like_temperature') | int in range(41,55) -%}
    /Icons/chilly.png
  {%- elif states('sensor.openweathermap_feels_like_temperature') | int in range(56,65) -%}
    /Icons/mild.png
  {%- elif states('sensor.openweathermap_feels_like_temperature') | int in range(66,80) -%}
    /Icons/warm.png
  {%- elif states('sensor.openweathermap_feels_like_temperature') | int > 80 -%}
    /Icons/hot.png
  {%- endif %}
#

I get what you mean

#

it's not a "between", but an "in" rather

inner mesa
#

Yeah, I think that would work. It's just unconventional when comparing numeric values, and is probably slower

tacit sun
#

well, I think it should work for my use. not the most demanding script out there. 🙂
Thanks for the followup though.

exotic grail
#

you probably want something like set temp = states('sensor.openweathermap_feels_like_temperature') | int at the start to save yourself repeated code/calls maybe

inner mesa
#

you can also set a variable and make it much more concise:

{% set temp = states('sensor.openweathermap_feels_like_temperature') | float %}
{%- if temp <= 40 -%}
    /Icons/cold.png
  {%- elif 40 < temp <= 55 -%}
    /Icons/chilly.png
  {%- elif 55 < temp <= 65 -%}
    /Icons/mild.png
  {%- elif 65 < temp <= 80 -%}
    /Icons/warm.png
  {%- elif temp > 80 -%}
    /Icons/hot.png
  {%- endif %}
#

yeah

tacit sun
#

Good suggestion! I will give it a shot tomorrow. 🙂

inner mesa
#

I fixed it so that you won't miss all the cases that are right on the boundary

eternal hazel
#

Hi All. Good morning/afternoon/night

#

I have a sensor i built like this:

#
  • sensor:
    #Range Status based on Shelly EM
    • name: "Range Status"
      icon: mdi:stove
      state: >
      {% if states('sensor.range_power')|float < -10 %} On
      {% else %} Off
      {% endif %}
#

But my range turns itself on and off every few seconds… so the consequence is this:

plain magnetBOT
#

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

eternal hazel
#

Range Status changed to Off triggered by state of Range power changed to -1.9
8:29:27 PM - 1 hour ago

Range Status changed to On triggered by state of Range power changed to -1380.31
8:29:06 PM - 1 hour ago

Range Status changed to Off triggered by state of Range power changed to -2.29
8:28:27 PM - 1 hour ago

Range Status changed to On triggered by state of Range power changed to -1383.53
8:28:06 PM - 1 hour ago

Range Status changed to Off triggered by state of Range power changed to -2.01
8:27:27 PM - 1 hour ago

#

Is there a way to add a delay to my “state” code in the sensor definition so that it has to be less than 10 for two consecutive readings (or for 45 seconds)?

lofty mason
#

If I needed those exact requirements, I would probably personally go to an automation involving triggering on state change, awaiting a second state change trigger with a timeout, and driving an input_boolean from that. but that's not as elegant as just a template sensor.

eternal hazel
#

I’ll try that. I know binary sensors have the “delay_off” which would allow me to add the time.

#

Yes, i can add the delay to the trigger on the automation - but i decided i wanted this to be a learning exercise as well 🙂

lofty mason
#

actually I don't get that input data at all. why does it jump so wildly from 2 to 1300?

#

I don't know if a lowpass would do much good with that messy data

eternal hazel
#

Because an electric range turns itself on, goes red hot, then turns itself off. Then turns itself on again, and keeps alternating

#

And i’m capturing the data with a Shelly EM, that measures Watts

#

So it’s either full blast, or it’s idle.

#

The difference between cooking in power 1 and power 9 is the interval between the ONs and the OFFs

#

It’s negative because it’s 220v and i put the sensor on one of the phases - the other phase would be positive

lofty mason
#

k

#

so you can write triggers for template sensors

eternal hazel
#

Or i could flip the sensor but i don’t want to open the fuse box again 🙂

#

All i want to do is a simple automation: If person-group_Adults = Away, then alert if range = on or if oven = on

#

Notify*

lofty mason
#

sure

eternal hazel
#

But first step is a reliable sensor - is the range on

lofty mason
#

for range_status sensor, I would maybe write two triggers:

numeric_state: 
  below: -50  

numeric_state: 
  above: -10
for: 
  minutes: 1
#

then it will instantly turn to on anytime it gets a single high power reading, but it wont go back to off until it sees above -10 for 1 minute

eternal hazel
#

This is exactly what i’m looking for. But where do I add this?

lofty mason
#

(my code is just pseudocode, you'll need to fix the syntax)

eternal hazel
#

Ok. This is a great idea. Let me see what i can cook up.

#

Thank you.

lofty mason
#

I actually do think a lowpass or averaging filter could work too as another idea. sorry I didn't quite get what the data represented originally, so I was a little confused. In that case it would just smooth our your data to be ~600 instead of -1300/-10/-1300/-10.

plain magnetBOT
#

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

eternal hazel
#

The problem i’m having is that it’s creating a sensor.range_status and a sensor.range_status_2

#

I don’t know how to attach two triggers to the same sensor

marble jackal
#

just add the two triggers in one trigger section, and only add one sensor section

#
- trigger:
  - platform: numeric_state
    entity_id: sensor.range_power
    below: -50
    id: "On"
  - platform: numeric_state
    entity_id: sensor.range_power
    above: -10
    for:
      minutes: 1
    id: "Off"
  sensor:
    # Range Off if consuming less than 10w for 1Minute or more
    - name: "Range Status"
      state: "{{ trigger.id }}"
#

But with those states I would suggest to use a binary_sensor 🙂

floral shuttle
#

having some mqtt sensors for returning to the grid, but the are positive, and I need them to be negative. I had set unit_of_measurement: kW value_template: > - {{value}} device_class: power state_class: measurement to them, and all seemed fine. However, lowering my loglevel I now see HA is complaining.... and says they are a string (which does not comply with the state_class. Dev tools show that when I take out the space and do -{{value}} it changes to the type number, but I wonder if we have a better template method to negate that value? Or maybe simply {{0 - value|float}} ?

marble jackal
#

why do you have the dash?

#
value_template: >
  {{ value }}
#

I would expect that

#

that's also what makes it a string

#

to make them negative, you can do this:

value_template: >
  {{ value | float * -1 }}
#

don't know if the float filter is needed, depends what is provided as value

#

{{ 0 - value | float }} will have the same effect

floral shuttle
#

guess I was expecting looking for the opponent of {{ -123|abs}} like {{123|neg}}

silent vector
#

If I set an input text value in an automation service call to {{ now() | as_timestamp }} how would I in an automation check if the time now is > 6 hours from that input text state?

marble jackal
floral shuttle
#

ha yes, I didnt think of that. though in this case, where only positive numbers (or none) are received that wouldnt hurt. btw, all of the mentioned options do that: Negate, as in toggle the polarity/sign. That's why I mentioned looking for the opposite of |abs, as that always returns positive.

#

good to keep the current actual behavior though, thx for reminding me (#makesnoteinyaml)

marble jackal
#
{% set v = value | float(0) %}
{{ v * -1 if v > 0 else v }}
marble jackal
silent vector
#

Much better than this as I was not even sure what to do with this

{% set time = '1680605418.057968' %}
{{ now() - time | as_datetime }}
marble jackal
#

that could also work

#
{% set time = '1680605418.057968' %}
{{ now() - time | as_datetime > timedelta(hours=6) }}
silent vector
#

Oh wow I was so close 😲.

#

How would I get the time from 13 hours ago in as_timestamp format.

#

{{ now() | as_timestamp - 60 * 60 * 13 }}

#

Is that it? Seems to work

marble jackal
#

{{ (now() - timedelta(hours=13)) | as_timestamp }} or {{ now() | as_timestamp - 60 * 60 * 13 }}

silent vector
#

Perfect thank you.

plain magnetBOT
#

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

marble jackal
eternal hazel
# marble jackal ```yaml - trigger: - platform: numeric_state entity_id: sensor.range_power...

This worked perfectly! Thank you! THe only thing I noticed is it won't change unless the trigger is triggered... so when i restarted HA it kept the Range as ON even though it was off - it required me to turn the range on and off to trigger the changes. I'll read up on startup behavior but it felt weird since the updates are coming from Shelly (sensor.range_power fluctuate between 0.0 and -1.8ish, so i know updates are being processed by HA).

marble jackal
#

that's the deal with trigger based template sensors

#

they only change when triggered

#

you can add the startup event as trigger, but that will require a more advanced template

eternal hazel
#

Thank you!

eternal hazel
grand quarry
#

```
codehere
```

```yaml
syntaxhighlighted: code
```
Instead of yaml you can also use other code tags like cpp, js, python and so on. Depending on what you share

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.

eternal hazel
#

I'm trying to show a dashboard that show's me on a call, and if not on a call, my location. How do i call my current location in the else statement?

{% if states('binary_sensor.work_mbp_audio_input_in_use')=='on'%} On a Call 
{% elif states('person.adult1')=='home'%} Home 
{% else %} Away 
{% endif %}
marble jackal
#

you are missing the closing backticks

#

and this is not yaml, it's jinja 🙂

eternal hazel
#

I have multiple locations mapped, like Gym, School, etc

#

so i'd like for it to show the name of the resolved location

#

instead of me hardcoding this thing

mighty ledge
#

{{ states('person.adult1') }}

#

instead of away

marble jackal
#
{% if is_state('binary_sensor.work_mbp_audio_input_in_use', 'on') %}
  On a Call 
{% elif is_state('person.adult1', 'home') %}
  Home 
{% elif is_state('person.adult1', 'not_home') %}
  Away
{% else %}
  {{ states('person.adult1') }}
{% endif %}
mighty ledge
#

That would work too

eternal hazel
#
{% if states('binary_sensor.work_mbp_audio_input_in_use')=='on'%} On a Call 
{% else %} {{states('person.adult1') }}
{% endif %}
marble jackal
#

yeah

eternal hazel
#

I can rip out the Home one since it'll resolve just as well.

#

cool

mighty ledge
#

well, it will return home and not_home

marble jackal
#

but maybe {{ states('person.adult1') | replace('not_home', 'away') | title }}

mighty ledge
#

You should use what thefes wrote

#

or that too

eternal hazel
#

what's title?

mighty ledge
#

This Is A Title

eternal hazel
#

ahhhh

mighty ledge
#

this is not a title

eternal hazel
#

that's needed for usre

#

sure 😄

#

was one of my pain points 😄

marble jackal
#

and it replaces the state not_home with away

eternal hazel
#

but - what if i have multiple locations?

marble jackal
#

then it will use the state

#

which is the zone the person entity is in

mighty ledge
#

the state of your person will be the zone you're in

#

if that's not happening you need to return the state of your device_tracker

#

or attach your device_tracker to your person

eternal hazel
#

but i had to change it to a template card to make this work - and that's where this didn't work as intended.

#

so basically it resolves as the name of the zone if it's a known zone, and not_home if somewhere else

#

and what we're doing is saying put the name of the zone, and if it resolves as not_home, then replace with Away

#

is my undersatnding correct?

marble jackal
#

so, you can use a single line template if you want:
{{ 'On a Call' if is_state('binary_sensor.work_mbp_audio_input_in_use', 'on') else states('person.adult1') | replace('not_home', 'away') | title }}

#

the state of a person entity is either home, not_home or the name of the zone he/she is in

eternal hazel
#

This was great! Thanks for this!

plain magnetBOT
#

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

shell widget
#

Good morning everyone! I'm trying to split/parse a weather alerts entity. I've got a template working in the dev tools editor that parses it how I would like, but I'm not sure how to translate it into separate template sensors.
template is in the txt file above 😂

mighty ledge
#

put it in a markdown card, otherwise you probably wont' get them as separate sensors that only appear when you have an alert

#

you'd have to make static sensors and if there are more alerts than sensors, you won't get the remaining alerts

shell widget
#

Blerg.

shell widget
mighty ledge
#

yep

shell widget
#

How would I go about splitting them?

mighty ledge
#

you have to figure out what you want as a state for the sensor

shell widget
#

I don't know how to create/assign the data to different entities based on the for loop

mighty ledge
#

then you have to extract that information into the template

#

you can't have a for loop

shell widget
#

Oh so I can't use my nifty loop 😭

mighty ledge
#

no

shell widget
#

I was so proud of that 😂

mighty ledge
#

basically you're going to remove the references to i|string

#

and replace them with the actual value

#

and just make separate template sensors pulling that info

shell widget
#

What about the description for loop? I only care about the impacts item

#

Can I still use that to create an impacts attribute?

mighty ledge
#

I don't know what you want as the state, so... that's up for you to decide

shell widget
#

State: title
Attributes: issues, begins, ends, s, e, severity, impacts

mighty ledge
#

Yep you can do that

shell widget
#

Ok lemme give it a shot, will return if I have issues.

mighty ledge
#

👍

shell widget
# mighty ledge Yep you can do that

Alright impacts is giving me issues. This is what I tried just now:

impacts: >
  {% set description = state_attr('sensor.pirateweather_alerts', 'description_0').split('*') %}
  {% for item in description %}
    {% if (item|trim).split('...')[0] = 'IMPACTS' %}
      {{ (item|trim).split('...')[1] }}
    {% endif %}
  {% endfor %}
inner mesa
#

==

shell widget
#

Swear I had that...

inner mesa
#

maybe, just pointing out something obvious

shell widget
#

Sigh no error now.

#

Yay it works! Now to copy and paste a bunch of times.

#

There's no way to declare a variable that can be used throughout the entire sensor definition right? Everything is limited in scope to just the specific line?

inner mesa
#

There isn't a "variables" block to define them in, but I think a previous exchange confirmed that you can set an attribute and self-reference that attribute

shell widget
#

Oh that's neat... I assume using state_attr or is there a better/easier way?

inner mesa
#

this.attributes.whatevefr

shell widget
#

I was hoping to be able to define a 'global' variable i that would replace my for loop index

inner mesa
#

attributes are free

silent vector
#

How would I make test for an empty list/tuple?

#

Meaning it could be [] or ([],[]) and so forth

#

So simply x != [] doesn't work

#

It could be more than 2 empty lists it could be a 20 so I'm trying to make this test dynamic ([],[],[],)

marble jackal
#

Something like this?

{% set x = ([],[],[]) %}
{{  iif(x | sum(start=[])) }}

Or

{% set x = ([],[],[]) %}
{{  x | sum(start=[]) | count > 0 }}
silent vector
#

Would | flatten != [] work?

#

Seemed to work

#

Not sure if it's as good as your examples though?

#

Oops the flatten filter might be Ansible only lol

exotic grail
#

flatten would be best if you have nested empty stuff

#

unless sum does do that too?

silent vector
#

Nope wouldn't be nested just a bunch of comam separated empty lists ([],[]) or empty comma separated empty strings but it seems flatten works for both

gray plover
#

I have a for loop figured out to give me the temperature from a specific hour in the forecast. Is there a way that I can use this to get a list of temperatures from a range of hours?

{% set pd = state_attr('weather.xxxx_hourly','forecast') %}
{% for i in range(0,x) %}
{% if as_local(as_datetime(pd[i].datetime)) == now().replace(hour=21, minute=00, second=0, microsecond=0) + timedelta(days=0) %}
{{ pd[i].temperature }}
{% endif %}
{% endfor %}```
#

The state attribute forecast is a list as you'd expect.

- detailed_description: ''
  datetime: '2023-04-04T17:00:00-04:00'
  condition: cloudy
  precipitation_probability: 5
  wind_bearing: 90
  temperature: 64
  wind_speed: 15```
plain magnetBOT
#

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

daring swift
#

It works until I add the sensors part that has openweather in it.

marble jackal
#

{{ state_attr('weather.xxxx_hourly','forecast') | selectattr('datetime', 'eq', today_at('21:00')) | map(attribute='temperature') | list }}

#

To select on a time range you can use
{{ state_attr('weather.xxxx_hourly','forecast') | selectattr('datetime', '>=', today_at('21:00')) | selectattr('datetime', '<=', today_at('23:00')) | map(attribute='temperature') | list }}

marble jackal
#

So you need - binary_sensor: instead of binary_sensor:

#

If there is only one item, it converts it to a list item if you don't add the hyphen, but as soon as you add a second one it will break

gray plover
crimson lichen
#

@marble jackal please help me
I have : 15/02/2023 nhuận (Quý Mão)
Now, i want get "Quý Mão"
I has use {{ states('sensor.lunar_exlab')[18:25] }} is ok.
But i want asking other way can get "Quý Mão" in "(....)"

#

I found other way : {{ states('sensor.lunar_exlab').split("(")[1] |replace( ")", "" ) }}

marble jackal
#

Do you want the part between the parenthesis

#

Or do you always want Quý Mão

crimson lichen
marble jackal
#

I don't understand, if you always want that string, just provide the string

crimson lichen
#

I have state of sensor.lunar_exlab is : 15/02/2023 nhuận (Quý Mão)

marble jackal
#

Okay, no problem.
But if you want the text between the ( and ) you can do what you did using split and replace

crimson lichen
#

yep
But i want other way can get it

marble jackal
#

Why? It's a fine way to get the part you want

crimson lichen
#

to learn more

marble jackal
#

You can do two splits

#

{{ states('sensor.lunar_exlab').split("(")[1].split(")")[0] }}

crimson lichen
#

Many thanks

jolly crest
#

Hi! I got ChatGPT to make me a template sensor. The attribute template works fine in developer tools, but in config it gives me multiple errors: https://codeshare.io/wngyzD

mighty ledge
#

Because what it’s doing is impossible to do

#

There’s a reason chatgpt is banned

#

This would be it

jolly crest
#

But why did it work in developer tools?

mighty ledge
#

Because developer tools does not validate yaml. That code produces invalid yaml and it uses templates in a field that does not accept templates

#

Not to mention, it misused quotes in the attributes as well.

jolly crest
#

Ah okey i see. Ill try another way

final lark
#

Hello, starting to modify all the legacy template to new format but I could not have this one working.
state: '{{ states (input_number.electricity_price) }}' don't give yaml syntax issue but give HA error Template variable error: 'input_number' is undefined when rendering '{{ states (input_number.electricity_price) }}'
state: {{ states ('input_number.electricity_price') }} give yaml issue
state: '{{ states ('input_number.electricity_price') }}' give yaml issue
state: >
{{ states ('input_number.electricity_price') }} give yaml issue
I'm a bit lost

#

I'm trying with state: "{{ states ('input_number.electricity_price') }}" now ...

marble jackal
#

and bingo, that one should work

marble jackal
# final lark Hello, starting to modify all the legacy template to new format but I could not ...

the first one is missing quotes around the entity id (you could have used double quotes " because you wrapped the template in single quotes)
the 2nd one was missing the quotes around the template (you could have used double quotes, as you placed single quotes around the entity_id)
the 3rd one had single quotes inside, and single quotes outside the template, you should have replaced one of those with double quotes

final lark
#

Yes , after restarting, it's doing the job 🙂 . The first also give issue in dev tools. That was more clear after what to do. Thanks for the notice

plain magnetBOT
#

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

manic onyx
#

I have this if I wanted to do random room names, but I dont know how to do similar with the room IDs:
{{ state_attr('vacuum.deebot', 'rooms').keys()|list|random }}

tacit sun
silent vector
#

If I have [% string %] [% and %] surrounding the string how can I remove that in a comma separated list. So that it would be string instead of [% string %]

inner mesa
#

It would be easier if you gave an actual example

silent vector
#

[% foo %], [% bar %], [% foo %]

#

How would I get foo, bar, foo

#

Essentially removing [% and %]

inner mesa
#

Like this?

{% set data = ['[% foo %]', '[% bar %]', '[% foo %]'] %}
{{ data|map('replace', '[% ', '')|map('replace', ' %]', '')|list }}
silent vector
#

Yeah that would work I was not sure if there was a cleaner way

inner mesa
#

['foo', 'bar', 'foo']

#

You could split on the space and take the second item from each

#

I'm not sure that's actually better

final lark
#

I count motion via a template with
{{ states.binary_sensor
| selectattr('state', 'eq', 'on')
| selectattr('attributes.device_class', 'defined')
| selectattr('attributes.device_class', 'eq', 'motion')
| map(attribute='name') | list | count }}

but I see one sensor that should not be part of it
If I add | rejectattr('attributes.browserID') before the last line , I get in devtool
'homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'browserID'
if I remove the rejectattr line , there is a binary sensor with this attribute.
why it's nok ? any idea ?

inner mesa
#

You didn't add 'defined'

#

Look at the selectattr in your existing code

final lark
#

but if I add defined , I can't remove it ?

inner mesa
#

What?

#

Compare your selectattr and rejectattr

final lark
#

| rejectattr('attributes.browserID', 'defined')

#

ok yes, I forgot that

#

thank you RobC 🙂

mighty ledge
#

regex can find strings in any way shape or form, then return only the things you care about, by making your capture groups correctly

#

all with a generator

inner mesa
#

indeed, I forgot about that

#

it always takes me several tries to figure out the capture syntax we need

floral steeple
#

see how healthy your templates are by checking how many times it renders (on 2023.4)

data:
  type: RenderInfo
silent vector
#

Map replace worked thought I sent that earlier. Yes regex I am learning more and more

#

About

plain magnetBOT
#

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

inner mesa
#

18 tries later:

{% set data = ['[% foo %]', '[% bar %]', '[% foo %]'] %}
{{ data|map('regex_replace', '\[% (.*) %\]', '\\1')|list }}
vestal narwhal
#

I think it is the rejectattr('attributes.friendly_name','in',NODEV) that fails

inner mesa
#

you need to add selectattr('attributes.friendly_name', 'defined') before that

mighty ledge
#

{{ data | map('regex_findall', '\[% (.*) %\]') | map('first') | list }}

#

findall does everything

#

you can even get multiple groups

#

{{ data | map('regex_findall', '(\[% )(.*)( %\])') | map('first') | list }}

#

gotta map first, that's kinda dumb. Seems like a bug

vestal narwhal
#

tx

inner mesa
#

but yeah, I never think of regex_findall

tacit sun
#

I am looking to read the value from the volume level of an alexa device and store it into an input number, however... I'm stuck trying to get the value of volume out of the media_player.myAlexa
It has an attribute: volume_level but... I'm stuck at trying to figure out how to access that value...

#

This shows me "standby": {{ states('media_player.myAlexa') }}

#

I tried: {{ states('media_player.myAlexa_volume_level') }} and got "unknown"

marble jackal
#

You need state_attr()

tacit sun
#

nailed it! Thanks!!

inner mesa
#

also, entity_id is all lowercase. states() may fix that for you, but best to use the proper case

tacit sun
#

yeah... I changed the name for pasting into discord 😉 Thanks for the heads up.

#

How can I set the value of an input number to the value of the volume from this attribute? doesn't seem to play nice (I don't know how to do it)...

service: input_number.set_value
data: {}
target:
  entity_id: input_number.alexa_volume
data:
  value: {{ state_attr('media_player.myalexa','volume_level') | float }}
#

I keep getting this error: "required key not provided @ data['value']. Got None"

inner mesa
#

you need to surround the template in quotes

#

and you have two "data:" parts

tacit sun
inner mesa
#

you just have some basic issues

tacit sun
#

that link represents what I want to do though...

  • record current device volume
  • change volume to announcement level
  • make announcement
  • change device volume back to original volume
#

I think I did get the input number working though based on your feedback. Thanks!

floral steeple
#

hey all, im having some isues following the basic macro example on the 2023.4 release notes

#

I made a folder
/config/custom_templates/

#

then create a file called
tools.jinja

#

then I placed this in the file

{% macro answer_question(entity_id) %}

Is the {{ state_attr(entity_id, 'friendly_name') }} on?
{{ (states(entity_id) == 'on') | iif('Yes', 'No') }}!

{% endmacro %}
#

then I go to developer tools, template and place this in the text box

{% from 'tools.jinja' import answer_question %}
{{ answer_question('light.kitchen') }}
#

my error message is this:
TemplateNotFound: tools.jinja

#

any ides what is wrong here?

#

maybe I have to restart HA?

floral shuttle
#

shouldn this time_pattern used in a trigger template update each minute: - platform: time_pattern seconds: 00?

#

entities and their secondary_info: last-updated keep counting the minutes..

#

full disclosure:```
template:

  • trigger:

    • platform: state
      entity_id: input_number.battery_alert_level
    • platform: time_pattern
      seconds: 00``` and a change in the input_number updates correctly
#

even - platform: time_pattern minutes: '/1' doesnt update.?

barren jungle
floral steeple
floral shuttle
#

the state, and cnsequently, secondary info line showing last_updated

mighty ledge
#

the trigger will force a recalc

#

that doesn't mean the calc will resolve a different value

#

if it's the same value, nothing is updated

#

i.e. neither is last_updated

floral shuttle
#

wait, really, Ive always believed the last_updated was always updated, no matter if the value of the state changed...

mighty ledge
#

nope, read the docs again

#

for state objects

floral shuttle
#

sure. but. is there no way then we can check?

mighty ledge
#

check what?

#

that last time it recalced?

floral shuttle
#

whether it was triggered/updated

mighty ledge
#

not really

#

you can see the last time the main state changed, or the last time the whole state object changed

#

last_updated is main state

#

last_changed is whole state object

floral shuttle
#

yes, but as you stated, if that state doesnt change, as in this case will be for many hours, that last_updated wont either... Im just trying to bring down the constant rerendering of my templates a bit, but like to know I am having some success 😉

mighty ledge
#

well, you shouldn't really have to worry about that

#

any template using states object is throttled to 1 minute as it is

#

states.xyz is throttled to 1 second

#

everything else is instant

floral shuttle
#

in my case it is about using energy values of lets say 50 entities, all changing state, so those will render constantly

mighty ledge
#

yes, that will

floral shuttle
#

where once a minute suffices

mighty ledge
#

unless it's coming from states.sensor

#

then it'll only update at most once per second

#

regardless, 50 triggers isn't really going to break the bank

floral shuttle
#

any preference for - platform: time_pattern minutes: '/1' or - platform: time_pattern seconds: 0?

mighty ledge
#

what breaks things is iterating all states

#

first one

floral shuttle
tacit sun
#

if I make a group of media players, can I do some sort of for loop to grab the volume_level of each player, store it, change it, do something, and change it back to the initial value?

mighty ledge
#

with a script, yes

tacit sun
#

hrmm... off to testing

#

it works! Woo!

fossil venture
finite iron
#

hi. In the forum I found this expression: .{{trigger.to_state.object_id[:-6]}} What does [:-6] do and is it explained somewhere?

finite iron
#

ok..this function returns an element of a list and apparently comes from Python. now I just need to understand :-6.

marble jackal
#

[:-6] is the same as [0:-6]

#

it defines the range of items you want from the list

#

[x:y] xis the start of the range, y the end

#

and negative numbers start at the end and count backwards

#
{% set l = [ 0, 1, 3, 4, 'a', 'b', 'c', 3, 2, 1] %}
{{ l[4:-3] }}

This returns [ 'a', 'b', 'c' ]

finite iron
#

ah ok. so that's how it works. ..and if i write [-3:0], then these are the last 3 elements of the list.

marble jackal
#

no, the last 3 elements is [-3:]

finite iron
#

without the 0, understood.

#

so the template above returns the first 6 parts of the Object_id.

#

wrong 🙂

marble jackal
#

[:-6] will show all the parts besides the last 6 parts

#

it will start at the first (0, which is the default if you don't enter a start item) and ends at -6

finite iron
#

learned something again. Thank you. 🙂

velvet glen
#

Quick one hopefully - I've got a percentage bar showing the amount of energy being used by my house. I want it to convert the kW to a percentage, but I want to create a max limit so that more than 3000kw always equals 100%

#

{{ ( 100 * states('sensor.consumption_power_2')|float(0) / 3000)|round(0)|int(0) }}

#

This seems to convert the kW successfully to a percentage, however it assumes I'll never use more than 3kw

#

so if I use 4kw, it'll break the percentage (ie with more than 100%)

#

Any ideas?

marble jackal
#

{{ [100, (100 * states('sensor.consumption_power_2') | float(0) / 3000) | round(0) | int(0)] | min }}

#

@velvet glen this creates a list with 100 and the result of your original template, and takes the lowest value out of those two

finite iron
#

@marble jackal Just to learn. would {{ ( 100 * [states('sensor.consumption_power_2') , 30000] min) | float(0) / 3000) | round(0) |int(0) }} also work?

marble jackal
#

no

#

but this would
{{ ( 100 * [states('sensor.consumption_power_2') | float(0) , 3000] | min / 3000) | round(0) |int(0) }}

rigid chasm
#

HI guys i am trying to find out about this template sensor. This is the error message :Template error: strptime unknown' when rendering template '- type: template
content: >-
{{ (strptime(states('sensor.date_time'),
'%d-%m') - timedelta(days=2)).strftime('%a
%d') }}

#

i am using this date format by my country 6.4.2023

marble jackal
#

you can't use strptime as a function

#

you need to do {{ (states('sensor.date_time').strptime('%d-%m') - timedelta(days=2)).strftime('%a%d') }}

rigid chasm
velvet glen
floral shuttle
#

ah this is a nice challenge: - unique_id: next_alarm_timestamp_true name: Next alarm timestamp true state: > {% set timestamp = states('sensor.next_alarm_timestamp')|int(default=0) %} {% if timestamp %} {{as_datetime(timestamp)|as_local}} {% else %} Not set {% endif %} device_class: timestamp renders perfectly, except when no alarm is set, and it takes the 'else'... in which case Ha errors with rendered invalid timestamp: Not set which ofc is correct..

#

how to set a usefull 'else' here?

#

using -1 just to give it a numerical value, but it has a strange effect, in that the state doesn't change when moving from a set alarm, to a non alarm. iow, it keeps its last value. Error in the log is gone though, so thats good.

marble jackal
#

as already mentioned, I would use a availability template on the sensor, to make it unavailable when no time is set

orchid oxide
#

is there any way to find the default icon for a given device class (or some other way to assign an icon to an entity with a default icon)

#

for onewith a non-default icon i can do {{states.domain.entity_id.attributes.icon}}, but idk how to find an icon for one with a default icon

#

(for context im trying to use a mushroom template card within an auto entities card)

    card_param: cards
    filter:
      include:
        - area: vardagsrum
          domain: sensor
          options:
            type: custom:mushroom-template-card
            entity: this.entity_id
            primary: "null"
            icon: ```
marble jackal
#

I don't think you can

shell widget
#

Do I need to do something special to get a service call to render a template from a dashboard button? Identical service call works from the dev tools, but does not work from the dashboard.

plain magnetBOT
#

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

shell widget
#

Exact same service call works from dev tools just fine

service: script.phone_launch_app
data:
  person: Nick
  app: clock
  activity: set_alarm
  extras:
    HOUR: >-
      {{(state_attr("input_datetime.nick_wakeup_time","timestamp")|as_datetime).hour}}
    MINUTES: >-
      {{(state_attr("input_datetime.nick_wakeup_time","timestamp")|as_datetime).minute}}
#

Output from dashboard call:

Launch=:=clock=:=set_alarm=:=android.intent.extra.alarm.HOUR:{{(state_attr("input_datetime.nick_wakeup_time","timestamp")|as_datetime).hour}}=:=android.intent.extra.alarm.MINUTES:{{(state_attr("input_datetime.nick_wakeup_time","timestamp")|as_datetime).minute}}=:=
#

Output from dev tools call:

Launch=:=clock=:=set_alarm=:=android.intent.extra.alarm.HOUR:9=:=android.intent.extra.alarm.MINUTES:30=:=
marble jackal
#

You can't use templates in dashboard actions

#

as you can see it just takes the literal text of the template, it doesn't render it

#

use a script instead, and do the template logic in the script

shell widget
#

Blergh

#

That's frustrating

mighty ledge
#

Just make a script, takes 2 seconds

shell widget
#

Yeah it's not hard

mighty ledge
#

or adjust phone_launch_app to use entity_id's instead of the number

#

usually I write a script using the other script

shell widget
#

The phone_launch_app script is kept purposely generic, it basically just formats the command to send a command to join>tasker

mighty ledge
#

i.e. script.phone_lauch_app_auto

shell widget
#

What do you mean by that?

mighty ledge
#
phone_lauch_app_auto:
  sequence:
  - service: script.phone_launch_app
    data:
      person: Nick
      app: clock
      activity: set_alarm
      extras:
        HOUR: >-
          {{(state_attr("input_datetime.nick_wakeup_time","timestamp")|as_datetime).hour}}
        MINUTES: >-
          {{(state_attr("input_datetime.nick_wakeup_time","timestamp")|as_datetime).minute}}
shell widget
#

Oh I gotcha

#

Not enough caffeine yet apparently

#

Been trying to keep my scripts tidy and flexible where I can. So much for that!

shell widget
mighty ledge
#

just have it pass the input_datetimes

rose scroll
#

Sure. Just define a script variable.

mighty ledge
#
phone_lauch_app_auto:
  sequence:
  - service: script.phone_launch_app
    data:
      person: Nick
      app: clock
      activity: set_alarm
      extras:
        HOUR: >-
          {{(state_attr(wakeup_datetime,"timestamp")|as_datetime).hour}}
        MINUTES: >-
          {{(state_attr(wakeup_datetime,"timestamp")|as_datetime).minute}}
#

then

#
service: script.phone_lauch_app_auto
data:
  wakeup_datetime: input_datetime.nick_wakeup_time
#

I.e. no template in the frontend

#

@shell widget ^

shell widget
#

Yeah no template on the front-end makes sense

mighty ledge
#

apparently I can't spell launch

rose scroll
#

Or rather, declare a field

fields:
  username:
    name: Username
    selector: 
      ...some selector
...
mighty ledge
#

that too

#

but it requires more templating

rose scroll
#

Then you can reference it by person: {{ username }}

shell widget
#

In the passthrough script, can I do:

variables:
  pass_person: {{ person }}
sequence:
  - service: script.phone_launch_app
    data:
      person: {{ pass_person }}
      *blah blah*
mighty ledge
#

and it requires a specific format for your datetime

shell widget
#

Sorry I'm slow on mobile

mighty ledge
#

are all your datetimes: input_datetime.<name>_wakeup_time?

#

if yes, you can easily just provide the person

shell widget
#

For this, yes

#

I just am trying to minimize making specific scripts for each device if I can, that will quickly balloon out of control 😂

#

Does !include_dir_named allow for subfolders? don't see a #configuration channel that would be a better place to ask.

mighty ledge
#
phone_lauch_app_auto:
  sequence:
  - service: script.phone_launch_app
    data:
      person: "{{ person | title }}"
      app: clock
      activity: set_alarm
      extras:
        HOUR: >-
          {{(state_attr('input_datetime.' ~ person | lower ~ '_wakeup_time',"timestamp")|as_datetime).hour}}
        MINUTES: >-
          {{(state_attr('input_datetime.' ~ person | lower ~ '_wakeup_time',"timestamp")|as_datetime).minute}}
#
service: script.phone_lauch_app_auto
data:
  person: Nick
shell widget
#

Ok I like that!

mighty ledge
#

you can also add the descriptor & selector that @rose scroll is talking about

#

then you can use the script in the UI (with nice UI selections)

#

if you don't care about that, don't bother

shell widget
#

That's how I constructed phone_launch_app

#

Nice and neat with all the options laid out.

mighty ledge
#

Yeah, then just do that

#

I add them to all my scripts incase I ever want to switch to the UI

#

or if someone copies my crap to use it

rose scroll
#

Haha I can't imagine when you would find the UI the superior option Petro...

mighty ledge
#

I like it for dev tools -> services

#

that's about it

#

mainly because I can't remember what the hell I added for the script

shell widget
#

I wish I could do both for the same dashboard 😔 writing from yaml is so nice when I have an actual keyboard, but it really really sucks mobile.

#

I haven't found a good editor for android

#

If y'all have any suggestions...

mighty ledge
#

all mobile devices suck for text.

shell widget
#

Indeed, but I got a 4 yo and 14 yo, about half my dev time is mobile.

rose scroll
#

I once saw a guy coding on a mobile phone w a Bluetooth keyboard in a bar in Da Nang. Hilarious.

mighty ledge
#

I had a coworker at my last job who would develop on long car rides using his phone.

#

mind you, he was developing code for a hardware device that he did not have while sitting in the passenger seat

#

🤷‍♂️

#

This was in 2012 BTW

#

when it was 10x worse than now

shell widget
#

My ZFold3 at least has a nice big screen, but most hosted editors (vscode addon and node-red) act really wonky with intellisense and the virtual keyboard

shell widget
mighty ledge
#

He wrote open source software for NASA in his free time that analyzed infrared photos... he was out there already

silver flare
#

Hello, if I want to use the new feature to reuse templates, where should I put the import statement in the yaml file? Can I put it in the beggining of the file and then I canreuse the macros all over the file?

mighty ledge
inner mesa
#

it would be nice if you could have a template_import: section or similar that does it globally

#

sticks them in the global environment

#

like lovelace resources

mighty ledge
#

Time will tell

#

I see this feature expanding

silver flare
inner mesa
#

or import: under template:

silver flare
#

so for now, the improvement is that I can replace the macro code all over the place with the import statement

#

The import statement will be duplicated

#

final question: If a macro in my .jinja file uses another macro inside the same file I don't need an import right?
For example: macro A uses macro B inside. In my YAML I only need to import macro A right?

#

I'm having an error with this approach

mighty ledge
#

so i'm assuming no

#

I'm in the process of making some over the next couple of days. I'll let you know when I find out

#

I'm currently designing mine with the idea that it executes the file.

#

i.e. you can nest macros and only import the ones you want

#

Just try it, if i was at home I would

silver flare
#

so I should define the "private" macro inside the "public" one right?

mighty ledge
#

try it both ways

#

I was making my private ones _blah(...)

#

because jinja/python doesn't have private/public classes/functions

#

everything is public but _ in front of it is like saying "don't use this"

silver flare
#

I tried both ways and it didn't work

mighty ledge
#

post what you tried?

silver flare
#

{% macro dew_point(t, rh) -%}
{% macro theta() -%}
{{ log(rh/100) + (at)/(b+t) }}
{%- endmacro %}
{{ ((b
float(theta())) / (a-float(theta()))) | round(1) }}
{%- endmacro %}

#

tried this

#

I'm using dew_point in my templates

mighty ledge
#

not sure if that would work

silver flare
#

ah wait

#

I found an issue

mighty ledge
#

but i would expect this to work

#
{% macro theta() -%}
{{ log(rh/100) + (at)/(b+t) }}
{%- endmacro %}

{% macro dew_point(t, rh) -%}
{{ ((bfloat(theta())) / (a-float(theta()))) | round(1) }}
{%- endmacro %}
silver flare
#

nevermind, let me fix some stuff

#

I need to pass some arguments that were previously not needed

mighty ledge
#

oh yeah, you're missing args for theta

silver flare
#

yep

mighty ledge
#

TBH, I've never tried nested macros

#

also, you got an error on your bfloat

#

and from what I can tell, the macros will return typed values

#

but they might be typed after the fact

#

i.e. they are strings before they are imported

#

All things I can't answer yet. Sorry

silver flare
#

it's working in my current process at least

mighty ledge
#

with nested?

silver flare
#

no no

#

when I define the macro in the template sensor directly

mighty ledge
#

ah ok, good

#

nice

#

1 less thing for me to verify

silver flare
#

🙂

#

Ill fixx the arguments later and post the results

mighty ledge
#

👍

marble jackal
#

I can confirm that you don't need to include templates in the same file

shell widget
#

@mighty ledge just wanted to say thanks again for the help earlier. Can now dynamically set my phone alarm from my bedside display dashboard 😀

mighty ledge
#

Nice!

shell widget
#

Took me an embarrassingly long time to realize I was missing quotes around a template 🤦‍♀️

marble jackal
#

If that's that you mean

mighty ledge
silver flare
#

@mighty ledge got it working without nesting, the problem was the missing arguments

#

{% set a = 17.625 | float(0) %}
{% set b = 243.04 | float(0) %}
{% macro theta(t, rh) -%}
{{ log(rh/100) + (a*t)/(b+t) }}
{%- endmacro %}

{% macro dew_point(t, rh) -%}
{{ ((b*float(theta(t, rh))) / (a-float(theta(t, rh)))) | round(1) }}
{%- endmacro %}

marble jackal
silver flare
#

then I just import dew_point in the template

silver flare
marble jackal
#

With the code above you only need to import the dew_point macro

#

You don't need to import the theta macro and variables

silver flare
#

ah yes

#

I had already tried that

mighty ledge
#

how in the f do we not have abs()

#

huh, it's only a filter. Odd.

river elk
#

Just wanted to post my "morning briefing" the reason is, I know ZERO about Jinja and barley can use the UI! Everywhere I looked people seemed to only be using Amazon stuff and I am in to the Google speakers..Point being If I can figure it out You can to. Might take twice as long and you might need a little help from CHAT GPT ( I really did use it for a couple things) or the fine folks here but it can be done. I am looking for some advice though. This is all inside a automation which I assume might not be the best way to do it and I would like to be able to make changes easier so if you have suggestions PLEASE let me know. Thanks. File is to big to post so here is a link. https://drive.google.com/drive/folders/1FwcwxwMycLFgM4lbgis_lRs_vta1mxq9?usp=share_link

barren violet
#
{{ area_entities('kitchen') 
  | reject('is_hidden_entity') 
  | expand
  | selectattr('device_class', '==', 'temperature')
  | map(attribute='state')
  | map('float') 
  | average 
  | round(1, 0)
  | string 
  | replace('.', ',') }} °C

I've been experimenting with the new area_entities and I tried this to get the average of all the temperature sensors in a given area, but the selectattr can't find the device_class attribute. How am I supposed to filter the entities with the temperature device class?

marble jackal
#

@barren violet It's attributes.device_class

#

And I don't think that 0 in the round filter is doing what you think it's doing

#

You can also do this without the need to expand

#
{{ area_entities('kitchen') 
  | reject('is_hidden_entity') 
  | select('is_state_attr', 'device_class', 'temperature')
  | map('states')
  | select('is_number')
  | map('float') 
  | average 
  | round(1, default=0)
  | string 
  | replace('.', ',') }} °C
plain magnetBOT
#

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

marble jackal
#

I see a lot of numbers, which numbers are you interested in? Or all of them?

manic onyx
#

all of them. I just want 1 random number as output, which is selected from all of the ones in the sensor. Vacuum has a habit of resetting its map, so room numbers change. I just gave up on changing it all the time and now just do random room cleaning when HA detects that I left the house

marble jackal
#

Also the list from default?

#

And corridor is also a list, do you want the list returned, or one of the numbers from that list

manic onyx
#

I just wanted all numbers combined and a random one closen

manic onyx
#

if I do this:
state_attr('vacuum.deebot', 'rooms').values()
it gives me
dict_values([0, 13, [8, 5, 11], [9, 1], [10, 2], 12, 3, 6])

but how do make it to give me just 1 random number? 🙂

#

if I use .keys() in place of .values() - it works fine and I can just | random it. But how do work with these values()?

marble jackal
#

You can use | random as well, but it will give you either a single number, or a list with several numbers, depending on which one is selected

manic onyx
#

it gives me another list. Is ther a way to merge them all into one?

#

it give me like either 13 or [9, 1]

#

and more importantly - how do I use it in a script?

manic onyx
#

all sorted 🙂

shell widget
#

Is there an easy way to check the state of each entity in a list or just a for loop?

#

I've got a script that allows multiple entities to be selected for a field. I want to loop, playing the selected media on all of the selected entities, then wait_template for them all to go state: idle before repeating

copper blade
#

What is a good strategy to sum up a total from an energy sensor which report the consumption of the last hour (value changes once each hour)?

odd flare
#

what's the correct syntax for now() (time) to be formatted as hh:mm:ss?

#
              {% set arrival_time = strptime(states.input_datetime.nanny_first_arrived_today.state, '%H:%M:%S') %}
              {% set departure_time = now().strftime('%H:%M:%S') %}
              {% set hours = (departure_time - arrival_time).total_seconds() / 3600 | round(2) %}
              {{ hours | round(2) }}
            {% else %}
              0
            {% endif %}```
#

I've tried now().strftime('%H:%M:%S') above but I think this is failing as it's a string

#

TypeError: unsupported operand type(s) for -: 'str' and 'datetime.datetime'

inner mesa
#

You're trying to do datetime math on a formatted string

#

Why are you turning it into a string?

odd flare
#

i dont know how to make a datetime object in hh:mm:ss format

inner mesa
#

datetime objects don't have a format

#

Just use now()

odd flare
#

so i'm trying to do the delta between departure and arrival

#

right now the arrival evaluates to 1900-01-01 08:36:03

#

so if i use now() it wont work

mighty ledge
#

This new macro functionality is awsome

#

Makes the entire variables custom integration useless

#

You can import things that you {% set %} and those maintain the native types unlike the output from the macros which is always strings.

#

You can make a macro file that other macro files read from. And you can import from it

mighty ledge
mighty ledge
#

I posted it in share your projects

marble jackal
#

👍

mighty ledge
#

@marble jackal ^

marble jackal
#

Found it on the forum already

mighty ledge
#

You can put translations in a separate file and import them but it won’t work with hacs

marble jackal
#

Yes, I had the same thought with my relative time plus macro

mighty ledge
#

It’s 100% doable. I had it working last night

marble jackal
#

Which is now a bit obsolete I guess, as yours does that too

mighty ledge
#

You can import more than just macros too

marble jackal
#

Well mine does months

mighty ledge
#

Isn’t yours different?

marble jackal
#

Yes, you can also use it for global variables

mighty ledge
#

I’m not trying to step on your toes

#

Just tabulating all my time macros into a lib

marble jackal
#

No, I didn't take it that way 🙂

#

I'll add Dutch to yours 🙂

mighty ledge
#

Thanks 🙏🏻

#

The library should just be named “inspired by Marius questions”

#

I’m wondering if there is a way to have a separate file dictate the default language

marble jackal
#

PR created

#

If there would be some error handling possible when importing a non existing file, you could ask people to create a settings file

marble jackal
#

I noticed somebody forked my repo, but when I clicked on it, it showed it was not forked by anybody. Looking at your repo's I did find who it was 🙂

mighty ledge
#

Who was it?

#

I’ll merge your pr when I get home

#

Hah, apparently it was me?

marble jackal
#

yeah

mighty ledge
#

Must happened when I clicked on the link yesterday

marble jackal
#

strange thing is that when I clicked on the 1 it showed it wasn't forked

mighty ledge
#

So odd

#

I looked at yours to see the format of the new template for hacs

#

And I stole your buttons. They are nicer than the ones in my other repo 🤣

#

(Hacs icons). Badges whatever you call em

marble jackal
#

I stole them from some other hacs repo

mighty ledge
#

I think we should make a joint lib for basic functions

#

Not sure how to do that

marble jackal
#

btw, the url for the downloads is quite funny lauwbier.nl

mighty ledge
#

.nl?

marble jackal
#

it translates to lukewarm beer

mighty ledge
#

Hah

inner mesa
#

we can't build new filters this way, can we?

mighty ledge
#

Nope

inner mesa
#

boo

#

that's what a search told me

mighty ledge
#

But I was thinking of adding a filter that accepts macros as the first arg

inner mesa
#

I don't really get it - should just be a function with the first parameter as the input

mighty ledge
#

Ya

inner mesa
#

there was a github issue

mighty ledge
#

Problem is, macros can’t handle *args

#

Which will cause errors

#

They naturally handle **kwargs but not args and that kinda breaks when you use them as a filter from what I can tell

mighty ledge
#

That’s a lot of words that just mean: disappointment

#

I bet we could make a function that registers a macro on the fly

#

As a filter

orchid oxide
#

little confused, i m testing for a template and i have the template {{expand(area_entities('Living Room'))|count}} which gives me 57, yet under

this template listens for the following state changed events:
theres 59 entities. the two missing entities are light.fan_lights and light.fan_lights_group
and one of those two missing entities is the ony im trying to evaluate for

#

so uh, whats going on here, is there way to fix it? does it have something to do with it being a group

fresh egret
#

is there a way to get the average value of a sensor for today? starting from midnight to 'now'

I want a utility meter that shows me how much of my used energy is solar energy, from today

orchid oxide
#

also i dont have an entity light.fan_lights anywhere in my home assistant, just tht latter group

odd flare
odd flare
mighty ledge
#

It's an experimental feature ATM

#

I don't think it has been added fully yet

#

The repo is passing HACS tests

orchid oxide
vital bluff
#

Could someone try this in their dev tools/template and tell me if you're seeing a double space between the day name and number

Timestamp is: {{ (as_timestamp(now()))|timestamp_custom("%A %e %B %Y") }}```
lofty mason
#

I believe day number is commonly padded as 2 digits

vital bluff
#

thanks, my solution was to use a replace " "," "

chilly hemlock
#

Hey, is there a template that can check every single light entity and see if any have changed state in the last X minutes? I'm looking to use it as a condition.

inner mesa
#

this will tell you if any lights changed state in the last 5 minutes:
{{ states.light|selectattr('last_changed', 'gt', now() - timedelta(minutes=5))|list|length > 0 }}

lean yacht
#

Hi,
I have a filter defined to ensure values are within boundaries... However during startup my snesor is not setup yet. Hence I get errors for hte filter that it detect a string "unknown" rather than a numeric value.
Any idea how I can fix this ?

radiant dock
#

Hi, it's possible on template to export de result on attribute poster ? :

  - title_default: $title
    line1_default: $episode
    line2_default: $release
    line3_default: $number - $rating - $runtime
    line4_default: $genres
    icon: mdi:eye-off
  - airdate: '2023-04-07T19:54:52Z'
    aired: ''
    release: $day, $date $time
    flag: true
    title: Control Z
    episode: Maria ?
    number: S03E02
    runtime: 35
    rating: ''
    poster: /local/upcoming-media-card-images/plex/plexguide2_Added_série/p27941.jpg
    fanart: /local/upcoming-media-card-images/plex/plexguide2_Added_série/f27941.jpg
friendly_name: plexguide2 Added série```
#

i test this:
{{ state_attr("sensor.plexguide2_added_serie", "data") }}.

but the result is all is test replace data to poster I have a result : none

#

thank's for your help 🙂

marble jackal
#

Can you share the current config?

lean yacht
marble jackal
#

How did you define the filter then

lean yacht
#
  name: Bedroom Humidity Filter
  unique_id: bedroom_humidity_filter
  entity_id: sensor.bedroom_humidity
  filters:
   - filter: outlier
     window_size: 4
     radius: 5.0
   - filter: range
     upper_bound: 100
     lower_bound: 0```

My filter is defined in `sensor.yml`
#

This is the log entry:
2023-04-08 12:01:27.257 WARNING (MainThread) [homeassistant.components.sensor] Sensor sensor.bedroom_humidity_filter has device class humidity, state class measurement and unit % thus indicating it has a numeric value; however, it has the non-numeric value: unknown (<class 'str'>); Please update your configuration if your entity is manually configured, otherwise create a bug report at https://github.com/home-assistant/core/issues?q=is%3Aopen+is%3Aissue+label%3A%22integration%3A+filter%22

marble jackal
radiant dock
#

but I don't understand the [1].poster

#

😦

marble jackal
#

The data attribute consists of a list with dictionaries

#

[1] takes the 2nd item from the list .poster returns the value for that key

orchid oxide
#

whtas wrong with my template sensor here

      platform: event
      event_type: zha_event
      event_data:
        device_id: 405aa8670b602b8480633896e93eac3a
        command: current_orientation
  - sensor:
      - name: Vibration Tilt
        state: 'on'
        attributes:
          X: >
              {{trigger.event.data.args.X}}
          Y: >
               {{trigger.event.data.args.Y}}
          Z: >
               {{trigger.event.data.args.Z}}```
#

i've got this automation and it works fine ```alias: zha test
description: ""
trigger:

  • platform: event
    event_type: zha_event
    event_data:
    device_id: 405aa8670b602b8480633896e93eac3a
    command: current_orientation
    condition: []
    action:

  • service: notify.persistent_notification
    data:
    message: >-

    'X': "{{trigger.event.data.args.X}}" 'Y':
    "{{trigger.event.data.args.Y}}" 'Z': "{{trigger.event.data.args.Z}}"
    

mode: single

#

but the template sensor x y and z are showing as null

#

just kidding it should be sensor and not - sensor

orchid oxide
#

is it possible to have multiple trigger sensors for a template sensor

inner mesa
#

Multiple triggers?

orchid oxide
#

yeah like

inner mesa
#

Yes

orchid oxide
#

sry lmao getting an example

#
      platform: event
      event_type: zha_event
      event_data:
        device_id: 405aa8670b602b8480633896e93eac3a
        command: current_orientation
  - trigger:
      platform: event
      event_type: zha_event
      event_data:
        device_id: 405aa8670b602b8480633896e93eac3a
        command: Tilt
    sensor:
      - name: Vibration Tilt
        unique_id: vibration_tilt
        state: '{{trigger.event.data.args.degrees}}' 
        attributes:
          X: >
              {{trigger.event.data.args.X}}
          Y: >
               {{trigger.event.data.args.Y}}
          Z: >
               {{trigger.event.data.args.Z}}```
#

something like this ideally

inner mesa
#

Please use a code share site

#

You keeping flooding the channel

#

It's just like an automation. The syntax you gave above isn't correct

orchid oxide
#

kk and sry

#

ty

radiant dock
#

Another question it's possible to send notification on companion with picture url generated with template directly :

service: notify.mobile_app_ludo_ha_app
data:
  message: "Série: {{state_attr('sensor.plexguide2_added_serie','data')[1]['title']}}"
  data:
    image: "https://ha.xxxxxxx.com{{state_attr('sensor.plexguide2_added_serie','data')[1]['poster']}}"```

The name is ok but no image attached i received the url not valide but  If i test to add on message test  the url is ok :
```https://ha.xxxxxxxx.com/local/upcoming-media-card-images/plex/plexguide2_Added_série/p27941.jpg```
#

any idea ?

fierce turret
#

Does anyone have a template sensor to show the last triggered motion sensor?

crimson lichen
#

serie vs série

rustic raft
#

I have a complex template var used in a blueprint, and it evaluates to a specific number. For example one of the numbers it may evaluate to is 40 ergo {{ 40 }}

**What I'm trying to do: **If the template var evaluates to <100, I want the template var to multiply the evaluated number until the final evaluated number is >= 100.
So it'd evaluate to {{40 * 3}} in this example.

Any idea if that's possible? I'm digging through Jinja docs right now. Reduce-like filter would be perfect

inner mesa
#

Seems like you just want to divide 100 by the number, round up, and multiply the number by the result

rustic raft
#

Yup good call, will do that. Thanks for the different perspective 👍

velvet glen
#

I've got a simple template that's returning values from a solar panel.

#

{{ ( 100 * [states('sensor.consumption_power_2') | float(0) , 3000] | min / 3000) | round(0) |int(0) }}

#

One small issue is occasionally it loses connection to the solar inverter and returns a null value

#

Is there a way to say 'if null, then don't update'?

#

It only happens for a very intermittent period (inverter checks every 5 secs)

#

I basically want the value to persist if a null value is returned

marble jackal
#

You church for the state and if it's not what you want, use this.state to refer to the current state of your template sensor

tepid onyx
#

Hello, I have an automation using a template as a trigger from HA android companion app. It works once but next time it's updated the attribute i'm using stays the same and the automation does not fire. Please see http://pastie.org/p/02A8reF949rZldWQ6K39Mm for details

lofty mason
tepid onyx
#

ah yes sir, that did it. thanks

sinful bison
#

Hello ! happy Easter all

I had a question about the doc here : https://www.home-assistant.io/docs/automation/trigger#numeric-state-trigger
There is this example:

automation:
  trigger:
    - platform: numeric_state
      entity_id: climate.kitchen
      value_template: "{{ state.attributes.current_temperature - state.attributes.temperature_set_point }}"
      above: 3

But i don't understand where is the state value in value_template coming from, and testing it with just state | int return an error.

Any doc I should read ?

inner mesa
#

the state of the entity_id that you provided

#

entity_id: climate.kitchen

sinful bison
#

that was my guess to, but it doesn't work :(

inner mesa
#

well, it's true

#

"state" is a state object

#

it's not the state

#

state.state is the state

sinful bison
#

ok, that would make sense with the state.attributes in the example, in what doc this is explained ?

#

value_template: "{{ state.state | int + 17 }}" does work, but such shorthand is very practical and i would like to read about them :)

inner mesa
#

looks like it isn't explained there

#

are you asking about where is the state object documented?

#

templating in general?

sinful bison
#

i mostly know the state object, same for templating, but i never knew that this shorthand what available in t hat case and was it was build with.
I've read about the trigger value you can use for example, but if there is more like it i would like to know where to read about it

inner mesa
#

that's a very specific use case

#

"state" representing the state object isn't a general thing

sinful bison
#

i know :D that's why i was looking for some doc

I would have added it but ... i'm kind of in a cold state when it come to making PR on Hass ... I really hopped it was just written somewhere i didn't look for it like the Trigger data you can read about in https://www.home-assistant.io/docs/automation/templating/

inner mesa
#

it's a special case for the numeric_state trigger to support the value_template

#

but I don't see it explicitly called out or explained beyond the examples

sinful bison
#

You gave me the clue to move forward, so i'm good.
It would need to be added, i usually do thing like that on project i used, but i don't feel ok doing it for Hass.

inner mesa
#

why?

sinful bison
#

i'll just make an issue, it could be a simple addition for someone

sinful bison
# inner mesa why?

honestly it's not a subject for a public chat, and i will sound like a whiny dumb dumb ...

inner mesa
#

you can just hit "edit" at the bottom

sinful bison
proud cradle
#

Can someone explain why the first returns a value and the 2nd None?

{{ states.sensor.duet_status.attributes.job.filePosition }}
{{ state_attr('sensor.duet_status','job.filePosition') }}

#

I know for sure the property is there and that it has a value (2480699), why can't I access it from the the state_attr() function?

radiant dock
#

@marble jackal Hi, it's possible with template delete un word on path ?

#

example : ```{{ state_attr("sensor.plexguide2_added_serie", "data")[1].poster }} -> /local/upcoming-media-card-images/plex/plexguide2_Added_série/p27941.jpg

#

it possible de result is just : /upcoming-media-card-images/plex/plexguide2_Added_série/p27941.jpg

#

delete /local ?

inner mesa
#

job.filePosition is not an attribute

#

if you want to use state_attr(), you would need to do {{ state_attr('sensor.duet_status','job').filePosition }} or {{ state_attr('sensor.duet_status','job')['filePosition'] }}

inner mesa
radiant dock
#

Ho thank @inner mesa it's work 🙂

marble jackal
#

Oh, RobC already answered that 🙂

novel lantern
#

Hello , How can I create a Home Assistant template to calculate the time left to the next trigger of my automation.garden ? I want the output to be in the format of "Next run after X days, X hours, and X minutes". or time left x day x h x m Thanks in advance!

inner mesa
#

How would it know?

novel lantern
#

i have an automation with fix time like every sunday monday at 3 AM

#

in general , getting current day and time , then find how many hours until automation.time , im new to HA so not sure

marble jackal
#

So basically you want the time left until next Monday 3 AM

novel lantern
#

yah dynamically getting the info from my automation and do some calculation im not even sure if this possible in HA

plain magnetBOT
#

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

novel lantern
#

this is dummy only

#

i want to show a card to display time left to run garden automation

marble jackal
#

Okay, it's not only on Sunday.
You can't get this info from your automation directly.

novel lantern
#

yah , i need to know what day today , then find the closed day to my day then count the hours between

marble jackal
#

There is no data stored when a automation will trigger in the future

novel lantern
#

oh okay

#

is my config correct if i want to run that automation every sun tue thu sat at 2:29:00 or there is a better way to do it?

marble jackal
#

Your current automation is fine. But the fact that you want to know the next run is a bit more complicating

novel lantern
#

yah , if i know how to access the information such conditions or trigger from template maybe i can solve it by simple if with loop through the week days

#

and compare ,

#

i tried {{ state_attr('automation.garden', 'condition') }} seems not correct

marble jackal
#

There is no condition attribute in an automation

#

The automation config isn't stored in it's attributes

novel lantern
#

oh okay , seems this is not possible , Thanks for help

marble jackal
#

This will give you the datetime of the next run

{% set days = [ 1, 3, 5, 6] %}
{% set time = '02:29' %}
{% set after_time = now() > today_at(time) %}
{% set next_day = days | select('>=', (now().weekday() + (1 if after_time else 0)) %7) | list | first %}
{{ today_at(time) + timedelta(days=(next_day - now().weekday() + 7)%7) }}
inner mesa
#

I was screwing around with something very like that and was starting to get bored trying to figure it out 🙂

#

your "next_day" is better that what I came up with

novel lantern
#

not the actual next run of my automation.garden entity

inner mesa
#

How is that different?

novel lantern
#

idk if i understand it correctly , the point is lookt at this config ``` alias: garden
description: "smart irrigation system 5 Zones every 2 days at mid night "
trigger:

  • platform: time
    at: "23:00:00"
    condition:
  • condition: time
    weekday:
    • sun
    • sat
    • wed
      action:
  • service: script.smart_irrigation_demo_2
    data: {}
    mode: single
#

the template which @marble jackal shared , will return sat date.

#

i hope you got what i mean

#

😦 sorry for my english

inner mesa
#

Ok. Your statement above is just two ways to say the same thing

novel lantern
#

Oh now i got it

#

he used static time

#

starting from sunday ?

inner mesa
#

You can use the 'relative time plus' macro from TheFes to display how long until the next run

novel lantern
#

on this array , days = [ 1, 3, 5, 6] 0 is sunday ?

inner mesa
#

6 is Sunday

novel lantern
#

Okay 0 should be sat

inner mesa
#

0 is Monday

novel lantern
#

Got it , Thanks ,

heavy crown
#

Hi all, I'd like to know if groupby can be used to count the entities/attributes per group and (!) show them

#

trying to formulate this a bit better...

#

if I have a sensors with an attribute that are high, medium, low can I group by attribute and then show which atribtues has which count?

#

From {% set list_json = { 'att1':'h', 'att2':'h', 'att3':'l' } %}

#

I'd like to get something alike : h = 2 and l = 1

rose scroll
marble jackal
rose scroll
#

So...anyone plucked the low-hanging fruit yet, of a Jinja macro that counts the number of entities of domain X (or any arbitrary list of id's) that have state Y?

marble jackal
#

Nope, but good idea, might be good to add a couple of such relative small templates in a set, like petro did with Easy Time

loud mountain
#

for this

entity_id:
  - fan.cosmos
from: "off"
to: "on"
icy tree
#

RESTful sensor issue

rigid chasm
#

Hi guys. i have this hvac statistic sensor wich shows me the current week '' - platform: history_stats
name: stofa weekly
entity_id: sensor.stofa_climate_activity
state: "heating"
type: time
start: "{{ as_timestamp( now().replace(hour=0, minute=0, second=0, microsecond=0) ) - now().weekday() * 86400 }}"
end: "{{ now() }}" ''

#

How do i edit it to show me last week of this sensor and stops on monday at 00:00

mighty ledge
floral locust
#

is this a reasonable way to have a sensor to show the current price of electricity? is it inefficient or crappy in any way?

{% if is_state("binary_sensor.off_peak_power", "off") -%}
  on peak rate here
{%- else -%}
  off peak rate here
{%- endif %}
mighty ledge
#

yes... why wouldn't that be a reasonable way?

floral locust
#

I falsely thought all templates polled once a minute like the ones in the development tools tab, I see now it has a listener and will only change when the binary_sensor changes value

lean yacht
#

Can a macro call another macro ?

mighty ledge
#

yes

#

a macro can even call itself

hot harbor
#

Hi guys

I would like to have the remaining time of consumables displayed by my vacuum robot in the format D:H:M:S.

The input comes from MQTT as minutes.

The only thing I have managed so far is to convert it to hours.

Can someone help me?

mqtt:
  sensor:
    - name: "Filter"
      state_topic: "valetudo/MistyMemorableJay/ConsumableMonitoringCapability/filter-main"
      unit_of_measurement: "Stunden"
      value_template: "{{ (states('sensor.valetudo_mistymemorablejay_main_filter') | float / 60) | round(0) }}"```
mighty ledge
#
{{ timedelta(minutes=states('sensor.valetudo_mistymemorablejay_main_filter') | float(0)) }}
hot harbor
mighty ledge
#

you'd have to replace the string with german

#

I'm building a macro library for time that can probably do this in the future

hot harbor
mighty ledge
#

it currently does not do that

hot harbor
mighty ledge
#

You can pass it to the easy_time function but it will only output the largest significant value

#

and you'd have to multiply the value by 60, seeing that your current units are minutes

#

{{ easy_time(states('sensor.valetudo_mistymemorablejay_main_filter') | float(0) * 60) }}

#

it will output X days in german

rose scroll
# mighty ledge a macro can even call itself

Woah macro-ception mindblown

Well there's another low-hanging fruit...a macro for a bisection search algorithm, bonus points if it's recursive. Though I can't imagine why anyone would ever need something like that in HA haha.

marble jackal
#

@hot harbor my Relative Time Plus macro can show as many time fractions as you want, but also doesn't support German yet

#

But if you can provide me the right translations in an issue in GitHub (or in a PR) I can add it

hot harbor
# mighty ledge it will output X days in german

I give up. Tried to enter the code, but then nothing appears.

When I try to enter the code in the template, it tells me that easy_time is not defined.

I think I'll just leave it in English for now, it won't kill me. 😅

mighty ledge
#

You’ll have to import thefes s relative time too

#

Gonna have the same problem if you don’t know how to import macros

marble jackal
#

In both readme's it's explained how to import it 🙂

hot harbor
marble jackal
#

The fact that you can import them is new, after that you can use them similar as you would use a jinja function

hot harbor