#templates-archived

1 messages ยท Page 45 of 1

pseudo plume
#

I have doen

marble jackal
#

Okay, any log messages now

pseudo plume
#

maybe I did not refresh

#

i cleared the log and realoaded all yaml config

marble jackal
#

Okay, open the log again

pseudo plume
#

First occurred: 11:44:49 AM (1 occurrences)
Last logged: 11:44:49 AM

Invalid config for [template]: invalid template (TemplateSyntaxError: unexpected char "'" at 118) for dictionary value @ data['sensor'][0]['state']. Got "{% set inside = states('sensor.studio_temperature') | float %} {% set outside = state_attr('weather.home', temperature') %} {{ min(inside, outside) }}\n" invalid template (TemplateSyntaxError: unexpected char "'" at 93) for dictionary value @ data['sensor'][0]['availability']. Got "{{ states('sensor.temperature_sensor') | is_number and state_attr('weather.home', temperature') | is_number }}". (See /config/configuration.yaml, line 10).

#

same eror I think, new timestamp

#

wait

#

am I issing a ' at the start of temperature ?

marble jackal
#

Yes

#

Also in the availability template

#

Probably my bad ๐Ÿ˜…

humble mortar
mighty ledge
#

you have backticks...

#

use quotes that don't match interior quotes

#

or multiline notation

pseudo plume
#

the sensore has reappered

#

but it is showing state ;unkown'

#

unkown

#

unknown goddamit

marble jackal
#

Check the template in devtools

#

Both

pseudo plume
#

ValueError: Template error: float got invalid input 'unknown' when rendering template 'template:

#

and the the text from config, and then complainign about not having a default set

#

oh my bad this time

#

I had setudio_temperatur instead of temperature_senosr

#

that was the olld name then I changed it

#

Ill correct that ehn I think it should work

#

yay !! working now !

humble mortar
# mighty ledge use quotes that don't match interior quotes

Original sensor:

sensor.ttgo_poe_001_zone01_state
ttgo-poe-001 Zone01 State: OK
icon: mdi:door
friendly_name: ttgo-poe-001 Zone01 State

Binary translation of above sensor

binary_sensor.alarmo_zone_01_state
Alarmo Zone 01 State: unavailable
friendly_name: Alarmo Zone 01 State

Changed code here in the thread ignore the txt. Not sure if I corrected it properly?

https://discordapp.com/channels/330944238910963714/672223497736421388/1123983894367195257

#

Sorry I'm not totally understanding.

#

The sensor.ttgo_poe_001_zone01_state that it is looking at currently says OK yet the binary clone is showing unavailable

plain magnetBOT
lyric comet
#

What value do you want the sensor to get you can not set a sensor state to the whole list. You could set the list into the attributes for the sensor.

humble mortar
#

the binary equivalant of

#

OK and ALARM

lyric comet
# humble mortar the binary equivalant of

attributes:
source_value: "{{states("sensor.alarm_front_door_state")}}"
availability: > {{ states("sensor.alarmo_front_door_state") in ['OK', 'ALARM'] }}

You are using two different sensors here, surely they should be the same and both should be your original sensor

humble mortar
#

Please look at the thread for the updated yaml

mighty ledge
#

NonaSuomy, you haven't fixed any of the changes I said

#

this is a backtick `

#

that's wrong in your template

#

you also have the multiline notation >

#

but you have everything on the same line

#

move it to the next line

#

and by it, i mean the template

#

i.e. everything inside {{ }}

humble mortar
#

I don't see any backticks at the end of that thread

mighty ledge
#

...

humble mortar
#

I feel like you guys are looking at the txt file instead of the thread under it

mighty ledge
#

backticks

humble mortar
#

Yeah the text file not the thread below it.

mighty ledge
#

there is no thread below it

plain magnetBOT
echo shard
#

This is so frustrating, even when I set the state to 'on' it still comes through as off / Away???!

#

No errors in the logs, no help whatsoever to debug it ๐Ÿ˜ฆ Feel like I waste ages trying to decode the YAML syntax rather than actually every achieving anything

#

OK, the following works:

  - binary_sensor:
      - name: "Craig's iPhone connected to Home Wifi"
        device_class: presence
        state: "{{ is_state('sensor.craigs_iphone_bssid', state_attr('input_select.home_bssid', 'options')) }}"
marble jackal
#

Yes, that was what I was about to suggest

echo shard
#

So maybe only the homeassistant start trigger was firing...

marble jackal
#

I was wondering why you were using a trigger based template sensor here

echo shard
#

I think I saw in a tutorial somewhere that you need to force an update on start for some reason...

#

But I wonder why the trigger doesn't fire

marble jackal
#

Not for state based template sensors

sonic sand
#

hey, I got this template which working fine
http://pastie.org/p/4VGBV5oiZumbJnRcYGcRve

now I have got new reolink camera and did added an option to my automation that I will receive the sub image when the automation is triggered, however I cannot put this template into the 'caption' of the Telegram send photo

service: telegram_bot.send_photo
data:
  authentication: digest
  file: /config/www/tmp/snapshot_aquarium_sub.jpg
  caption: test

I tried to change the caption to the "message" that in the link that I sent above, it did created an error.
Is there a way to use this template inside service like telegram_bot.send_photo?

static shuttle
#

Btw, finally tested this and it worked great!
"Hello, {USER}. Welcome to Our Home!
Motion detected in 3 rooms, (2 downstairs and 1 upstairs). The average temperature inside is 70.9ยฐF, (70.6ยฐF downstairs & 71.3ยฐF upstairs). The sun rose 5 hours ago."
I stole that sun rose code from the template in Developer Tools - anyone know how to make one that will also say "The sun will set in {X} hours. / The sun set {X} hours ago" ? ๐Ÿ™‚

lyric comet
#

The Sunrise and Sunset fields are always the next ones, so you will need to create some helpers to contain the previous ones then check if the current value is on the same date or the next day and get the previous one. It was something I was looking to do, but I have not had time to build all the elements.

neat prairie
#

yep. first bit is easy. the second bit less so. however if you only care about the number of hours, you can cheat

static shuttle
#

Hours literally only, or minutes as well?

neat prairie
#
{% if ( s < 46400)  %} {{ (s // 3600) |int }} hours till sunset
{% else %}
{{ (((s-86400)*-1) // 3600) | int }} hours past sunset 
{% endif %} ```
#

Might need to adjust numbers a little. that 46400 for example

#

you can cheat with hours, because sunset doesn't move that much

#

if you want to cheat less, then do what Jane_T says. have an automation which goes off early in the day to save the next_setting into an helper. then refer to that.

analog mulch
#

how can I test if a variable is null -- I am trying to condition on null parent_id's in triggers

#

=='' doesn't seem to behave wel

static shuttle
#
  The sun rose {{ relative_time(states.sun.sun.last_changed) }} ago.
{%- else -%}
  The sun will rise at {{ as_timestamp(state_attr("sun.sun", "next_rising")) | timestamp_local }}.
{%- endif %}```
This is the code for the sunrise one. Could I do something similar with an if/else to make two separate sentances?
"The sun will set in x hours."
"The sun set x hours ago."
Maybe using "below_horizon"?
neat prairie
#

if not variable is defined

neat prairie
analog mulch
# neat prairie in a template, test for not is defined

Hmm - this still doesn't seem to work: in my trigger I have

    context:
      id: 01H44AQ59HYG98SVVK59WSPDQX
      parent_id: null
      user_id: a0b44a5b08a84cbf912658588c58bca7

And yet "{{not trigger.to_state.context.parent_id is defined}}" seems to evaluate to false

neat prairie
#
  alias: "Iphone battery above 50%"
  condition: template
  value_template: "{{ (state_attr('device_tracker.iphone', 'battery_level')|int) > 50 }}"```
#

hmm. actually no, looks like it does also work that way

lyric comet
#
{% from "easy_time.jinja" import easy_time %}
{% set diff_rose = as_timestamp(states('input_datetime.sun_rise_today')) 
< as_timestamp(now()) %}
{% set diff_set = as_timestamp(states('input_datetime.sun_set_today')) 
< as_timestamp(now()) %}
The sun {{'rose' if diff_rose}}{{ 'will rise in' if not diff_rose }} {{easy_time('input_datetime.sun_rise_today')}} {{ 'ago' if diff_rose }}
and {{ 'set' if diff_set }}{{ 'will set in' if not diff_set }} {{easy_time('input_datetime.sun_set_today')}} {{ 'ago' if diff_set }}
lyric comet
#

having set up two date time helpers which are set using

marble jackal
#

Use
"{{ trigger.to_state.context.parent_id is not none }}"

plain magnetBOT
neat prairie
#

sun_set_today_today ?

#

(I'm guessing there's a reason for the second today)

mighty ledge
#

Why are we making a datetime for that?

#

IIRC there's already sun entities with those times

neat prairie
#

but not after sunrise and sunset

#

they reset to the next one

mighty ledge
#

Ah, why would you want it tho after? Just curious

neat prairie
#

"The sun set X ago"

mighty ledge
#

ah

neat prairie
#

and someone else was dealing with automations which switched stuff off a few hours after solar noon, because they were getting solar power.

lyric comet
#

I used helpers, as I thought they would be simpler for the OP to use. it would be more elegant to make trigger template sensors, but they need YAML confidence to use.

neat prairie
#

(elegance is overrated ๐Ÿ˜‰ )

static shuttle
lyric comet
#

That is simply template code for mark downs, but as I said you need to install easy_time the details are in the link I posted along side it

#

You also need to set up the two helper entities and add in the automation.

grizzled grove
#

What's the best way to deal with: 'ZeroDivisionError: float division by zero'? When it's inevitable that one sensor goes "0".
Shouldn't availability deal with it?

#
availability:  "{{ states('sensor.XXX') | float > 0 }}"
#
{{ (4.186*(80000*(58-states('sensor.heater_temperature')|float(0)))/states('sensor.heater_watts')|float(0)) | round(0) }}
#

It's inevitable that the sensor.heater_watts will be at 0, at some point.

#
availability: "{{ states('sensor.heater_watts') not in ['0', 'unavailable', 'unknown', 'none'] }}"
#

This also, doesn't do the trick...

analog mulch
lyric comet
humble lichen
#

hi, I am from Argentina and I need your help
after the HA updates I can red an MQTT string in a mqtt sensor configuration
Json Example:

plain magnetBOT
humble lichen
#

mqtt:

  • name: "Maquina id 1 Mac"
    state_topic: "talleresBanfield/fabrica/produccion/monitoreo"
    value_template: >
    {% if value_json['1'].mac is defined %}
    {{value_json['1'].mac }}
    {% else %}
    {{ states('sensor.maquina_id_1_Mac') }}
    {% endif %}
grizzled grove
#

@lyric comet Is there a way to add a second condition, something like: {% if watt > 0 | temperature > 58 %} , after defining the '58', in the equation, as 'temperature'?
As it is, when the temperature goes beyond '58' the result gets negative...

{% if watts > 0 and temperature > 58 %}

Did it.

humble lichen
#

but not any more, only numbers can be

plain magnetBOT
inner mesa
#

the ['1'] doesn't match the JSON input your provided

#

is there more to the JSON that you didn't post?

lyric comet
# lyric comet ``` {% from "easy_time.jinja" import easy_time %} {% set diff_rose = as_timestam...

Out of interest, I found a slightly tidyier way to format the sentence.

{% from "easy_time.jinja" import easy_time %}
{% set diff_rose = as_timestamp(states('input_datetime.sun_rise_today')) < as_timestamp(now()) %}
{% set diff_set = as_timestamp(states('input_datetime.sun_set_today')) < as_timestamp(now()) %}
{{-('The sun will rise in %s and ' | format(easy_time('input_datetime.sun_rise_today'))) if not diff_rose}}
{{- ('The sun rose %s ago and ' | format(easy_time('input_datetime.sun_rise_today'))) if  diff_rose}}
{{-('will set in %s' | format(easy_time('input_datetime.sun_set_today'))) if  diff_set}}
{{- ('set %s ago' | format(easy_time('input_datetime.sun_set_today'))) if  not diff_set}}
mighty ledge
#

it's best to avoid it if you can because it doesn't always take TZ into account

#

e.g.

#
{% set diff_rose = states('input_datetime.sun_rise_today') | as_datetime < now() %}
lyric comet
#

Happy to learn what is the best way to do maths on timestamp strings?

#

from sensors?

mighty ledge
#

it's best to use datetime objects which are TZ aware

lyric comet
#

How do I get one from a sensor?

mighty ledge
#

states('sensor.xyz') | as_datetime

lyric comet
#

Thanks I will change my template over.

mighty ledge
#

assuming it's the state and it's a timestamp sensor

lyric comet
#

Is now() a datetime object or do I need a different method

mighty ledge
#

those input datetimes will need a | as_datetime | as_local

mighty ledge
#

it makes it easy to offset times too

lyric comet
#

Excellent. I just picked up as_datetime from examples.

mighty ledge
#

e.g. {{ now() + timedelta(hours=45) }}

#

or

#

e.g. {{ now() + timedelta(hours=45, minutes=32, seconds=12) }}

lyric comet
#

Looks good, I try and read the docs as much as possible, but some of the jinja2 stuff is a bit scattered.

#

I will try those out on the template trigger sensor I am building to avoid the input_datetime fields and to give me a sun_plus sensor, with todays dawn and dusk and solar noon as attributes.

#

I think I have seen a time difference as well haven't I?

mighty ledge
#

what do you mean?

lyric comet
#

((sunset - sunrise) / 2 ) + sunrise = solar_noon

mighty ledge
#

Yeah

lyric comet
#

I will go off and play now, thanks for the instructions

mighty ledge
#
{% set sunrise = states('input_datetime.sun_rise_today') | as_datetime | as_local %}
{% set sunset = states('input_datetime.sun_set_today') | as_datetime | as_local %}
{{ sunrise + (sunset-sunrise) / 2 }}
#

FYI, jinja uses pedmas

marble jackal
#

oh, you can just divide a timedelta in half

mighty ledge
#

parenthesis, exponent, division, multiplication, addition, subtraction. Applied in that order

mighty ledge
#

Let me check ๐Ÿคฃ

#

yep

marble jackal
#

ah, nice

neat prairie
#

(Everyone should use UTC. keep things simple)

mighty ledge
#

The whole point of them is to make math easy with time, so I just assumed it worked

#

with datetimes, it doesn't matter what TZ you use

#

it handles it all for you

#

input_datetimes are not TZ aware, so you have to use as_local

#

unless you made it UTC

#

other than that, if it has a TZ attached to the timestring, just use as_datetime and don't care about the TZ

neat prairie
#

I'm meaning in all things. So I can tell an American I'm going to talk to them at 4pm and no conversion is needed ๐Ÿ˜‰ Sure, it might mean that Australians are getting out of bed at 9pm, but still ๐Ÿ˜‰

marble jackal
#

And instead of summertime, we just do everything 1 hour earlier in the months April - October?

#

(assuming northern hemisphere)

willow wing
#

is it possible to work with wildcards in a template?

#

for example "calender.* "

marble jackal
#

probably, what do you want to achieve?

#

If you start with states.calander you already only have the calendar entitties

willow wing
#

ok, thanks

mighty ledge
#

you can't use wildcard format, you have to use regex or jinja's version of wildcards

marble jackal
#

what's jinja's version of wildcards? ๐Ÿ˜…

willow wing
#

i hate regex ๐Ÿ™‚

mighty ledge
#

or endswith

marble jackal
#

ah

mighty ledge
#

"airquotes"

marble jackal
#

or search if it's somewhere in the middle

mighty ledge
#

around jinja's widlcards

mighty ledge
willow wing
#

all fine, i use now mutpile actions :), better to read and unterstand it later

floral shuttle
#

working in the community, but this is an isolated thing: how to set an empty list as default? {% set msgs = state_attr('sensor.persistent_notifications','notifications')|default([]) %} {{msgs|count}} throws errors on reloading:TypeError: object of type 'NoneType' has no len()')

marble jackal
#

none is valid, so it won't apply the default

#

use | default([], true) to apply the default when the input is none

mighty ledge
#

or state_attr('sensor.persistent_notifications','notifications') or []

#

#lazyness

marble jackal
#

or that ๐Ÿ™‚

mighty ledge
#

I consider using that style "voodoo" because I have to look up how it works every time I use it

floral shuttle
#

it does work though ๐Ÿ˜‰ like it

mighty ledge
#

Yes, it will work

#

but it gets complicated if notifications is anything other than a list or None

#

which won't happen

#

But if it did happen.... shit gets weird

marble jackal
#

you wrote some template a long time ago which provided more details about it, when I tried to look for them I could't find them anymore ๐Ÿ˜›

floral shuttle
#

I've copied Fes' answer too for when I run into trouble..

mighty ledge
#

writing it now

#

sec

#

that's the code if you want to run it

#

here's the output

#

the bad or bad is where voodoo happens

#

Oh, I guess I just learned the voodoo

#

by doing that table ๐Ÿคฃ

#

bad or bad chooses the 2nd arg every time

#

TIL

#

no more voodoo

#

the last good or bad is labeled wrong, thats bad or bad

#

and good or good appears to always choose the first item

#

whcih makes sense because it bails when it finds something good

marble jackal
#

indeed, makes sense

#
   0:00:00   |    [0]     -> [0]
   0:00:00   |   {0: 0}   -> {0: 0}
   0:00:00   |     1      -> 1
   0:00:00   |    True    -> True
   0:00:00   |     0      -> 0
   0:00:00   |  0:00:00   -> 0:00:00
``` it takes the 2nd one here
#

but it's still good, as shown in the last one

#

the only thing that is sometimes run into with these kind of things is that I actually need 0 as a valid value

mighty ledge
#

0's might return 'false'

#

so that might not be "good"

#

I was just trying to find that opposite of None, which is a populated object

#

but timedeltas probably have an implemented or override

marble jackal
#

Well, what I sometimes do (which is related) is using | select(), but that filters out 0 as well

mighty ledge
#

nice trick, yes that's related for sure

lyric comet
#

Thanks for the help earlier with the solar noon. I have done a new trigger template which will get tested at 5 past midnight tonight. ๐Ÿซฐ

floral steeple
#

Hi any idea's on how to create a sensor that shows the date and time of when a file was last updated?

neat prairie
#

command line sensor?

floral steeple
#

Hmm let me look into that thanks

neat prairie
#

stat is an appropriate command to use to get the last modification time of a file

#

stat -c "%y" filename

floral steeple
#

Oh that is cool, let me give this a try, thanks!

neat prairie
#

(you might want to use %Y to get it as a timestamp.)

floral steeple
#

This if to create a time-stamp of a camera snapshot jpg file (the camera does not support time-date stamp on the photo). How would the output of this sensor look like as written?

command_line:
  - sensor:
      name: Bird Feeder Snapshot
      command: "stat -c "%Y" /local/bird_feeder/blink_camera_still_image.jpg"
      scan_interval: 1800
#

i'm wondering if I need a value template if its some number in seconds from 1970 ๐Ÿ™‚

#

something like this, maybe

command_line:
  - sensor:
      name: Bird Feeder Snapshot
      command: "stat -c "%Y" /local/bird_feeder/blink_camera_still_image.jpg"
      scan_interval: 1800
      value_template: "{{ value | timestamp_local }}"
neat prairie
#

That looks more reasonable ๐Ÿ™‚

#

that 1800 means 30 minutes between checks.

floral steeple
#

correct, 30 min is what I'm looking for

neat prairie
#

๐Ÿ™‚

#

ahhh. I see an issue.

#

replace the "%Y" with '%Y'

#

using double quotes there will conflict with the double quotes around the whole thing

floral steeple
#

oh good catch, thanks I would not have noticed that

#

do I need a device class?

#

like number or something

neat prairie
#

I think you're good without

#

I think it's just going to store as a string.

#

(I think what I said was out of date, so I'm stripping it out)

#

if you do assign a device class, I think you'll probably want timestamp

floral steeple
#

I was looking for that list, thanks for finding it for me!

#

I'm having some word issue with the syntax of setting this command line sensor. I know this was changed in the last release, I'm using the !include function where I refer to a command_line.yaml file, But if you have 2 sensors and following the example in the documentation, it seems to fail just regular syntax checking.

#

It seems I cannot use the appended file with !include when setting up command line sensors

#
command_line:
  - sensor:
      command: SENSOR_COMMAND
  - sensor:
      command: SENSOR_COMMAND_2
#

If I remove the first 2 lines from this and then make it left most in the command_line.yaml file it fails syntax

neat prairie
#

so you're doing like

    name: my nifty sensor
    command: mycommandhere
- sensor:
    name: my other nifty sensor
    command: myothercommandhere

in a file you included with something like
command_line: !include command_line.yaml

#

?

#

what's the syntax error?

floral steeple
#

Oh never mind, of course. It was the double quotation versus single quotation. I completely mis-read your message, LOL.

floral steeple
#

Actually, when I put that command right into terminal, it says no such file or directory.

#

But that's not true, it actually is there, and it does exist. So might be a permission issue?

#

OK the path should be
config/www/....

#

rather than local.That works!

#

Thanks for your help and patience ๐Ÿ™ mission accomplished.

lyric comet
#

I have been tinkering with the Sun settings to store todays using a trigger template when the midnight value change on sun. Any comments or suggestions for improvements - http://pastie.org/p/2jkX4G7uzp9RPseXjjdixL

marble jackal
#

I don't think the this variable is available in the trigger, and if it is, you should use this.entity_id in that template for the trigger

#

But I would advice to just use the entity_id, and not refer to the this object there

lyric comet
#

Thanks, I will change it back over to the standard format. See how that works tonight.

floral steeple
zealous ibex
#

So I would like to monitor how long has an automation has run. based on
last_triggered
I can get that time string, how can I compare that string with a time duration for exmaple 30 seconds?
{{now() - state_attr('automation.sofa_light_ikea','last_triggered')}}

inner mesa
#

timedelta(seconds=30)

zealous ibex
#

thanks I found if I do it this way it's a string ''0:00:00.000000'' it's a string

#

and i was searching for a way to convert this string to that time type

floral steeple
#

Ok, I thought I solved this issue, but it seems not. Here's the yaml for a sensor that I simply want to know the last time it was modified:

- sensor:
    name: Bird Feeder Snapshot
    command: "stat -c '%Y' /config/www/bird_feeder/blink_camera_still_image.jpg"
    scan_interval: 600
    value_template: "{{ value | timestamp_local }}"
    device_class: timestamp
    unique_id: db187e8e-867e-4fb1-9d5e-c9f7ab9d8d84

but the sensor state is unknown and the error message is here:
http://pastie.org/p/7in6mqG9T2ZCYnyG1JTzrt
am I missing like a | float or something somewhere? thanks

zealous ibex
#

Does HA light entity has something like a previous state
So by refering to it I can set the light to the previous status?

lofty mason
#

no that's not stored

#

make a scene snapshot if you want to save a state for recall later

zealous ibex
#

okay a scen it is. will check on that thanks

inner mesa
zealous ibex
#

i wanted to do that mainly to quit an automation if it hangs

#

I mean it's quite a large automation so there can be many unexpected behaviors but if it runs longer than say 20 seconds it will just quit

zealous ibex
#

The create scene part:```
service: light.turn_on
data:
hs_color:
- "{{ range(360)|random }}"
- "{{ range(40,80)|random }}"
brightness: "{{ range(1,255)|random }}"
transition: 0.2
target:
entity_id: light.0x6c5cb1fffe6882ca

service: scene.create
data:
scene_id: sofa_light_prev_state
entities: light.0x6c5cb1fffe6882ca
snapshot_entities: light.0x6c5cb1fffe6882ca

#

On another branch the turn on scene part:```
service: scene.turn_on
data:
transition: 0.2
target:
entity_id: scene.sofa_light_prev_state

inner mesa
#

I doubt you want both of these:

  entities: light.0x6c5cb1fffe6882ca
  snapshot_entities: light.0x6c5cb1fffe6882ca
zealous ibex
inner mesa
#

what does "the same" mean?

#

you haven't really said what isn't working

zealous ibex
#

So the first part of the code creates a scene and gives the light a random hs_color. And the 2nd part turns on that scene. But after the random color action, executing part 2 (scene turn on part) does not restore the color to the previous one before the random color

lofty mason
#

you're running scene.create before light.turn_on right?

inner mesa
#

so you created the scene after you set it to the new value

zealous ibex
#

yeah sorry I also realized that and corrected that so now it's create scene first and random 2nd

#

but still it's the same. when i turn on that scene no matter what color previously it will restore to a yellowish color

#
service: scene.create
data:
  scene_id: sofa_light_prev_state
  snapshot_entities: light.0x6c5cb1fffe6882ca
service: light.turn_on
data:
  hs_color:
    - "{{ range(360)|random }}"
    - "{{ range(40,80)|random }}"
  brightness: "{{ range(1,255)|random }}"
  transition: 0.2
target:
  entity_id: light.0x6c5cb1fffe6882ca
#
service: scene.turn_on
data:
  transition: 0.2
target:
  entity_id: scene.sofa_light_prev_state
#

Just to be clear this is my now code

tight hinge
#

I am using the Radio Thermostat integration and struggling trying to create sensors to enable graphing of the hourly HVAC runtime, target temp and actual temp over time (would like 2 yr to enable yoy reporting.

I would like to get some feedback on my template configuration.yaml file additions. I an a newb with HA but I have spent a lot of RTFM time. I have et to successfull create anything but I feel like I am getting closer to understanding the plumbing. Need a helping hand to get me over the hill.

inner mesa
#

just share what you have and your questions

plain magnetBOT
floral steeple
neat prairie
fathom slate
#

Do I have to put all the command_line sensors together in config? I would like to intersperse command_line with templates, ... and keep things that are logically connected (e.g., sensor, battery of sensor, derived sensors or sensor, ...) together

haughty breach
floral steeple
fathom slate
zealous ibex
zealous ibex
#

But it can only restore once since I only have 1 scene and 1 snapshot.

#

Is there a way to create multiple snapshots of a scene and scene.turn_on you can choose which snapshot to restore?

shut flint
#

I am trying to create a template sensor based on attributes of 2 sensors to calculate average rainfall. Added the below code to configuration.yaml without issue but I cannot seem to be able to find the sensor.

template:
  - trigger:
    - platform: time_pattern
      minutes: 1

  - sensor:
    - unique_id: current_ave_rainfall
      name: "Current Ave Rainfall"
      unit_of_measurement: "mm"
      state_class: measurement
      device_class: precipitation
      state: >
        {{ ((state_attr('sensor.tp_rainfall', 'Value') + state_attr('sensor.ts_rainfall', 'Value')) / 2)
plain magnetBOT
#

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

marble jackal
#

@shut flint are you sure there is actually an attribute called Value? Check this in:

plain magnetBOT
marble jackal
#

My guess is you actually want the sensor state

#

Which you can get with states('sensor.foo')

#

Do note that states are always strings, so you need to convert it to a number using | float or | int

karmic oar
#

I'm trying to extract some json attributes from my airtags json file. HA can pull the file, but I'm told it's not a dictionary. Jsonpathfinder would leave me to believe I'm calling the right path. Example JSON and and YAML posted here for anyone that might be able to help: https://pastebin.com/LtYC1pxi

marble jackal
#

I don't see timestamp in location
"location" : null

karmic oar
#

I did a lot of sanitizing

marble jackal
#

value_json[1].location.timeStamp

#

You have this

#

While location is null

karmic oar
#

It's sanitized

#

Location is not null

#

Take a look at 1, not 0

marble jackal
#

Oh wait, you're right

karmic oar
#

I have a lot of other json type things set up that work fine, so I'm not sure what I'm missing here

mighty ledge
karmic oar
#

Result type: dict

#
Empty reply found when expecting JSON data
mighty ledge
#

And whatโ€™s causing the error?

#

Is that HA or?

karmic oar
#

HA

mighty ledge
#

Ok, and this is a rest sensor?

karmic oar
#

No, it's a command_line sensor

mighty ledge
#

Ok then your command isnโ€™t working

#

It may be working, but you may be using json attributes which would cause the error

#

Are you using jsonattibutes?

#

Ah yes you are

#

Thatโ€™s the problem

#

Json attributes are expecting a dict

#

Your endpoint returns a list

#

Transform it into a dict and you should be good

karmic oar
#

I guess I don't know how to do that

mighty ledge
#

I donโ€™t have it memorized

karmic oar
#

Because it keeps telling me it is a dictionary

mighty ledge
#

Itโ€™s not though

karmic oar
#

And I've tried using jq to change that

mighty ledge
#

What you output above is a list of dicts

karmic oar
#

A list of dicts...

#

I guess I'll run with that for a bit.

mighty ledge
#

[ means list

#

{ means dict

#

Your output starts [{

karmic oar
#

Oh an array

#

Yes

#

Which I thought was fairly normal

#

And gets referenced in that thread above

mighty ledge
#

Yeah but thatโ€™s the rest integration

karmic oar
#

I didn't realized that rest and command_line would treat the data any differently

mighty ledge
#

All integrations are different

karmic oar
#

True, but I thought the method use to handle the data would be part of some underlying shared library

mighty ledge
#

Nope

karmic oar
#

So I'm left trying to do some sort of data massaging to use the airtag json file I'm retrieving via ssh

#

Because rest can't use ssh

#

I would imagine

mighty ledge
#

Thereโ€™s a way to use command line to transform the data

#

You should look into that

#

I think itโ€™s as simple ass plopping it into another dictionary so you can call out a single attribute that contains all the information

karmic oar
#

Looking for it now

mighty ledge
#

Command central did it on the forums replying to me about a year or so ago

karmic oar
#

I feel like I've already tried this. I end up with the error: homeassistant.exceptions.InvalidStateError: Invalid state encountered for entity ID: sensor.find_my. State max length is 255 characters.

karmic oar
#

Which is why folks want to send their json to state attributes that don't have the length restriction

lyric comet
#

Yep, I put "OK" or the retrieval datetime in the State and then use template sensors to pull out what I need from command results.

plain magnetBOT
sonic sand
#

In other words, I want to somehow implement this template into the telegram_bot.send_photo action, if it's possible as the caption of the photo; instead of having 2 messages which spam my telegram.

fossil totem
#

Is there a means in jinja (filter etc) to turn an integer into written numerals? like, int(73) | something == "seventy three"?

lyric comet
#

There might well be an easier way.

fossil totem
#

that's a starting point!

marble jackal
#

How big can the numbers get?

fossil totem
#

in my situation, reading off temperatures in ยฐF, so from below zero to a hundred and some change.

marble jackal
#

Okay, that keeps it manageable

#

Integers only?

fossil totem
#

correct!

marble jackal
#

You could create a list with the written out numbers 0 to 19

#

And a second list with 20, 30, .., 100

#

No mappings would be better

#
{% set value = -20 %}
{% set v = value | abs %}
{% set m1 = {
              2: "twenty",
              3: "thirty"
            }
%}
{% set m2 = {
              1: "one",
              2: "two",
              18: "eighteen",
              19: "nineteen"
            }
%}
{% set a = v // 10 %}
{% set b = v % 10 %}
{% if v == 0 %}
  zero
{% else %}
  {{ 'minus' if value < 0 }} {{ m1[a] if v >= 20 }} {{ m2[b if v >= 20 else v] | default() }}
{% endif %}
#

Something like this

#

Just add the missing values in the mappings

fossil totem
#
{% set numbers = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"] %}
{% set tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"] %}
{%- macro to_words(n) -%}
  {%- if n < 0 -%}
    negative {{ to_words(-n) }}
  {%- elif n < 20 -%}
    {{- numbers[n] -}}
  {%- elif n < 100 -%}
    {{- tens[n // 10] }} {{ numbers[n % 10] if n % 10 != 0 else "" -}}
  {%- else -%}
    {{- numbers[n // 100] }} hundred {{ to_words(n % 100) if n % 100 != 0 else "" -}}
  {%- endif -%}
{%- endmacro -%}
#

I had GPT-4 walk me through this answer. It works well! I did constrain the input values to -199 to 199, but it seems to work within that range in my limited testing.

#
to_words(73): seventy three
to_words(173): one hundred seventy three
to_words(17): seventeen
to_words(-17): negative seventeen
to_words(0): zero
marble jackal
#

Okay, mine works for -99 to +99, but could be adjusted to work with hundreds as well

fossil totem
#

yeah it turns out this works from -999 to 999 kinda for free

#

the more i look at this the more i dig it, the recursion for negative values is clever. i doubt i would have come up with this on my own, can't take much credit for the machine here.

marble jackal
#

It's kinda funny the macro uses itself

marble jackal
#

Okay, final version of my approach, which works from -1999 to 1999 if the mappings would be complete

{% set value = 111 %}
{% set v = value | abs %}
{% set m1 = {
              2: "twenty",
              3: "thirty"
            }
%}
{% set m2 = {
              1: "one",
              2: "two",
              11: "eleven",
              18: "eighteen",
              19: "nineteen"
            }
%}
{% set a = v // 100 %}
{% set b = (v - a * 100) // 10 %}
{% set c = v % 10 %}
{% set d = v % 100 %}
{% if v == 0 %}
  zero
{% else %}
  {% set p1 = 'negative' if value < 0 %}
  {% set p2 = (m2[a] ~ ' hundred') if a %}
  {% set p3 = m1[b] if v % 100 >= 20 %}
  {% set p4 = m2[c if d >= 20 else d] | default() %}
  {{ [p1, p2, p3, p4] | select() | join(' ') }}
{% endif %}
inner mesa
#

does it cover eleventy-one?

marble jackal
#

Hmm, no ๐Ÿ˜…

inner mesa
#

Then it's no good in Middle Earth

#

but with that caveat, I'm sure it's fine ๐Ÿ™‚

marble jackal
#

Now it does, it will say one hundred eleven though

lyric comet
#

Mine was originally done for Phone numbers as my other half did not like missed calls being read by Alexa as three thousand and forty three two hundred thousand four hundred and forty six!

marble jackal
#

That makes sense

fossil totem
#

on both of ours, "1023" comes back as "ten hundred twenty three" ๐Ÿ˜„

marble jackal
#

Hmm

#

Right

inner mesa
#

it's almost to proper MIddle Earth

marble jackal
#

Even completed the mappings

zealous ibex
#

I have a state based binary sensor which is defined as below```

  • trigger:
    - platform: state
    entity_id:
    - sensor.0x943469fffec8d2eb_action
    - sensor.ikea_bedroom_remote_action
    to: 'brightness_stop'
    binary_sensor:
    - name: "Brightness stop"
    state: "on"
    auto_off: '00:00:01'
Previously it only has 1 entity now I expanded it to 2. It worked but I did not really find how this can be done on the template part of the docs. Can anyone point me to the io site about this info?
inner mesa
#

first example

zealous ibex
#

Yeah but it did not show cases with multiple entities

inner mesa
#

it does

#

right there

#
template:
  - trigger:
      - platform: webhook
        webhook_id: my-super-secret-webhook-id
    sensor:
      - name: "Webhook Temperature"
        state: "{{ trigger.json.temperature }}"
        unit_of_measurement: ยฐC

      - name: "Webhook Humidity"
        state: "{{ trigger.json.humidity }}"
        unit_of_measurement: %
#

two entities

lyric comet
zealous ibex
inner mesa
#

neither

lyric comet
#

After I fixed the index error.

inner mesa
#

the entities don't affect the trigger at all

#

ignore the webhook trigger, I'm just copying the example from the docs. Use whatever trigger you want

torpid mural
#

I've got my template working in template editor. It returns a list of the entity_ids I'd like included on this card. But what's the syntax to get the entities card to accept my generated list?

type: entities
entities: >-
  {{ states.sensor 
    | rejectattr('attributes.device_class', 'undefined') 
    | selectattr('attributes.device_class', 'eq', 'power') 
    | rejectattr('entity_id', 'in', area_entities('energie')) 
    | map(attribute='entity_id') 
    | sort()
    | list() }}

results in "Entities must be specified". Please help me find the correct syntax for this situation?

marble jackal
inner mesa
#

oh, you just added another entity? I'm not even sure what the question is then

marble jackal
floral shuttle
wide monolith
#

is there a way to create fake entities (like sensors) to aid building a template?

The idea of if I have a sensor.light or person.max, can I create a fake version of that to dev against?

zealous ibex
#

I did not find it but I took a guess and it worked

inner mesa
#

use them how? It's exactly the same as with automations, if you mean using the trigger variable

#

anyway, if you figured it out..

zealous ibex
#

yeah and just to check 1 last thing there, if the trigger is based on both entity 1 and 2, then it's either or?

#

So still the old rule about multiple triggers?

inner mesa
#

it is impossible for a single trigger to refer to more than one thing

#

this is not possible:

if the trigger is based on both entity 1 and 2

zealous ibex
#
- trigger:
      - platform: state
        entity_id:
          - sensor.0x943469fffec8d2eb_action
          - sensor.ikea_bedroom_remote_action
        to: 'brightness_stop'
    binary_sensor:
      - name: "Brightness stop"
        state: "on"
        auto_off: '00:00:01'
#

But this code works for both 2 entities

inner mesa
#

not at one time

#

for any trigger, it will only be for one of those entities

zealous ibex
#

yeah I don't know what would happen when both entities are triggered but in my case the likelihood of that is very low. so

inner mesa
#

if both change state to that value, you will get two separate triggers

zealous ibex
#

can't say I fully follow what you said.

#

Let's talk about the edge case here

#

If both entities triggerd at the same time than I have 2 triggers? Than which trigger is the binary sensor I created is based on?

inner mesa
#

yes, two triggers. the entity will be based on the last one

zealous ibex
#

okay so there's a possibility that the first entity's state change won't influence the binary_sensor's value

#

Good to know thanks

shut flint
sonic sand
#

Hey! I want to somehow implement this template into the telegram_bot.send_photo action, if it's possible as the caption of the photo; instead of having 2 messages.

service: telegram_bot.send_photo
data:
  authentication: digest
  file: /config/www/tmp/snapshot_aquarium_sub.jpg
  caption: test

http://pastie.org/p/3UthMHO4d0bqYTv2FDuqYw

marble jackal
normal rapids
#

Greetings.. I would appreciate some advice for setting up some ESPHome based smart plugs (8). They are automatically detected and are working well, but their sensors show up as 'sensor.athom_smart_plug_v2_power', 'sensor.athom_smart_plug_v2_power_2' etc. I would like to map these to 'sensor.kettle_power' and 'sensor.dryer_power' etc. Is there a nice way of doing this? I could make sensors for all of these, but with 'power', 'current', 'voltage' for each one it's going to get lengthy.

marble jackal
#

adjust it in the ESPHome config

#

you are probably using the same config for all, so it will use the same names

lyric comet
#

Another option is to rename the device in Settings, it will rename all the sensors as well, but prefix the name for the sensors with athon. eg sensor.athon_kitchen_power etc

marble jackal
#

or do that ๐Ÿ™‚

normal rapids
#

@marble jackal Yes, but I would rather not mess with the ESPHome ๐Ÿ˜‰ It is putting the MAC address on the end, so the ESPHome device names are unique -abcdef, but the 'nice' names are all the same.

#

@lyric comet I have done that with a couple of the sensors, but the name change hasn't propagated through..

lyric comet
#

Strange I did it yesterday for a plug and on changing the device it asked if I wanted to change the sensors. Perhaps it does not work if you have already edited the entities.

marble jackal
#

you can try to remove the ESPHome integration for one of the plugs, and wait until it's discovered again

#

then after re-adding, you can try the rename option again

normal rapids
#

There are two places to change the 'name/id'.

#

@marble jackal I will try that..

west marsh
#

can anybody help for a templatesensor? Try to get an number sensor from the 7th june this yeahr to the actual day

marble jackal
#

{{ (now().date() - as_datetime('2023-06-07').date()).days }}

floral shuttle
#

ive been looking at this now for the last 20 min.... {{state_attr('sensor.low_level_batteries','low_batteries')}} outputs a list of entity_id's. I want this to be used in a notification to show the names. cant make it happen . Ive tried the map(attribute='friendly_name') and expand on the list, but nothing succeeds.

#

the attribute itself is low_batteries: > {%- set alert_level = states('input_number.battery_alert_level')|int(default=0) %} {% from 'batteries.jinja' import batteries %} {%- set ns = namespace(batt_low=[]) %} {%- for s in expand(batteries().split(',')) if s.state|int(default=0) < alert_level %} {%- set ns.batt_low = ns.batt_low + [' ' + s.entity_id] %} {%- endfor %} {{- ns.batt_low|join(',')}}

floral shuttle
#

aarghh, there was an oddity in the main template creating that attribute. see{%- set ns.batt_low = ns.batt_low + [' ' + s.entity_id] %} addin an extra space in that list. Ive taken that out, and {{expand(state_attr('sensor.low_level_batteries','low_batteries')) |map(attribute='name')|list}} now makes it happen

floral shuttle
#

bringing another challenge: can we map this replace structure?```
{{-expand(state_attr('sensor.low_level_batteries','low_batteries'))
|map(attribute='name')|join(', ')
|replace('sensor Battery','sb')
|replace('draadloze dimmer','dd')
|replace('hygro temp Battery','htb')
|replace('bewegingssensor','bw')
|replace('afstandsbediening','ab')
|replace('door: Battery level','dbl')
|replace('Battery Level','bl')
|replace('flood sensor: Battery level','bl')
|replace('dimmer switch battery level','dsb')
|replace('dimmer switch Battery','dsb')
|replace(' Internal','')
|replace('Battery','')}}

#

in pseudo code something like replace(['a','b','c']['1','2','3']) ?

marble jackal
floral shuttle
#

yes, I tried all of that, but it broke because of that extra [' ' + . Cant even remember why I had put it there, and its really remarkable, as the output of that attribute was used for a long time in my auto-entities filter. That must have been smart enough to dont be bothered by it.

#

btw the main template attribute itself is based on this custm_template: {%- macro batteries() -%} {{- states.sensor |selectattr('attributes.device_class','defined') |selectattr('attributes.device_class','eq','battery') |rejectattr('state','in',['unknown','unavailable']) |map(attribute='entity_id')|join(',') -}} {%- endmacro -%}

marble jackal
#

eg regex_replace(' Internal|Battery', '')

floral shuttle
#

a yes, I was looking for that syntax yes! forgot it was regex.. thx! this only works for the same outcome? can not use it to swap those items on the left, with items on the right?

marble jackal
#

not sure

floral shuttle
#

ok, let me try

marble jackal
#

you could also use a mapping, but then you need to do the replacing in a for loop

floral shuttle
#

this doesnt work: |regex_replace('sensor Battery|draadloze dimmer |afstandsbediening |hygro temp Battery', '1|2|3')}} as it replaces any of the left strings with the complete right string ๐Ÿ˜‰

floral shuttle
#

the regex behavior is a bit more complicated than simply replacing those strings and replacements in my template above. even replacing all with an empty ' ' or even '' has unexpected results. for now I guess Ill keep it at message: > {{-expand(state_attr('sensor.low_level_batteries','low_batteries')) |map(attribute='name')|sort|join(', ') |replace(' sensor Battery','') |replace(' draadloze dimmer','') |replace(' hygro temp Battery','') |replace(' bewegingssensor','') |replace(' afstandsbediening','') |replace(' door: Battery level','') |replace(' Battery Level','') |replace(' flood sensor: Battery level','') |replace(' dimmer switch battery level','') |replace(' dimmer switch Battery','') |replace(' Internal','') |replace(' Battery','')}} and move the opening line to the notification title, to save some extra space in the notification (it gets truncated on those long outputs, reason for all of this finetuning)

sonic sand
#

Hi Is it possible to put this template into the telegram_bot.send_photo service as caption message?

service: telegram_bot.send_photo
data:
  authentication: digest
  file: /config/www/tmp/snapshot_aquarium_sub.jpg
  caption: test
    {% if values.error %}
      ๐ŸŸ โŒ The fishes have not been fed at {{ values.timestamp }} โŒ
    {% else %}
      ๐ŸŸ The fishes have been fed {{ values.value }} portions at {{ values.timestamp }}.
    {% endif %}
lyric comet
#

What error do you get when you try it?

#

Also try it with out the fancy icons.

sonic sand
lyric comet
#

Where is values coming from? Did you define it as a variable?

#

Remember template variables are not passed through scripts.

sonic sand
lyric comet
#

I presume if you remove/disable the telegram action it works ok? If you look at the trace how far through is it getting?

sonic sand
lyric comet
#

If you use a simple template like
caption: "{{ 'This is a test' }}"
for your caption what comes through or do you get an error?

sonic sand
#

let me try, thanks for help

lyric comet
#

Now try changing it to

caption: "{{ values.error }}"
#

If you look in Traces for the changed variables can you see your values table there?

sonic sand
lyric comet
#

It does not as if for some reason values which is defined in your variables section of your script is not available for some reason. Can you see it in the trace?

sonic sand
marble jackal
#

you are using RUN ACTIONS?

lyric comet
#

I might be tempted to create another variable and try using that. You will not be able to run the section on it's own as the variables will not be set.

marble jackal
#

the variables are based on trigger variables, there is no trigger if you use run actions

#

oh wait, they are not

sonic sand
#

is there a way to set those variables to the actions?

#

because it does using them on conditions too

marble jackal
#

No, I was mistaken, they are based on the actual state

#

the condition is based on the trigger, but that's fine

#

the condition is not used when you use run actions

sonic sand
#

the actions i'm using are send message (which i want to get rid off), and camera take snapshot

marble jackal
#

does the template for values work if you put in in developer tools > template right now

sonic sand
#

hold on let me try

lyric comet
#

Could you add a time trigger to run it every few minutes to test it

sonic sand
#

You mean this right?

    {% if values.error %}
      ๐ŸŸ โŒ The fishes have not been fed at {{ values.timestamp }} โŒ
    {% else %}
      ๐ŸŸ The fishes have been fed {{ values.value }} portions at {{ values.timestamp }}.
    {% endif %}
marble jackal
#

no

#

I meant:

    {% if state_attr('switch.hfjh_v2_eadb_fish_tank_2', 'event.4.1') is not none
    %}
      {% set value = (state_attr('switch.hfjh_v2_eadb_fish_tank_2', 'event.4.1') | from_json).value[0].value.split(',') %}
      {% set timestamp = (state_attr('switch.hfjh_v2_eadb_fish_tank_2', 'event.4.1') | from_json).timestamp %}
    {% endif %} {% set timestamp =  timestamp | default() |
    timestamp_custom('%H:%M %A', default='unknown') %} {% set value = (value |
    default())[6] | default('unknown') %} {% set error = (value | default())[5]
    | default() == 0 %} {{ dict(timestamp=timestamp,value=value,error=error) }}
sonic sand
#
Result type: dict
{
  "timestamp": "20:30 Sunday",
  "value": "2",
  "error": false
}
This template listens for the following state changed events:

Entity: switch.hfjh_v2_eadb_fish_tank_2
marble jackal
#

okay

sonic sand
quiet spruce
#

Hello, I'm trying to get an alert firing based on when garbage is due to be collected. Currently, collection is due tomorrow: {{state_attr("sensor.general", "daysTo")}} returns 1, so I'm validating that this is tomorrow by calling {{state_attr("sensor.general", "daysTo") == 1}} which returns true. So far, so good. However, when I try and use this in an alert:

alert:
  garbage_general:
    name: General Bin Collection Due Tomorrow
    entity_id: sensor.general
    state: '{{state_attr("sensor.general", "daysTo") == 1}}'
    repeat: 60
    can_acknowledge: true
    notifiers:
      - mobile_app.iphone

The alert unfortunately remains in an idle state. I appreciate this is probably me doing something stupid with the alert, and the templating is probably fine, but this felt like the best place to ask. Any tips?

sonic sand
# marble jackal okay

so it's impossible to make that template in the caption field? should I just stick to the two messages ?

marble jackal
#

no, it should just work

#

but can you explain step by step what you are doing and when do you see an error?

marble jackal
sonic sand
plain magnetBOT
quiet spruce
#

@marble jackal - the helpful bot above changed my reply to a file. Any further tips?

marble jackal
#

You removed the state line in the alert config, it should have state: "on"

lyric comet
#

As I believe Fes explained the value field is not available if you just run one line of the automation.

sonic sand
mighty ledge
#

You can put the variables as the first action and they won't be skipped

sonic sand
dense patio
#

I feel so stupid today

#

what am I doing wrong here?

#
  - platform: template
    sensors:
      - players_online:
        friendly_name: "Players Online"
        entity_id: sensor.minecraft_server_players_online
        value_template: {{ state_attr('sensor.minecraft_server_players_online', 'players_list')[0:] }}
#

I just want to make an attribute it's own entity

#

and stuff I find online is incomprehensible

inner mesa
#

You didn't surround your template in quotes

#

Also, I don't know why you have [0:]. I don't think it does anything useful

dense patio
#

it technically outputs a list of all players lmao

#

could remove it yeah

inner mesa
#

You also need to remove the - before the name

#

In short, follow the example

dense patio
#

thank you!

inner mesa
#

What is entity_id doing there?

dense patio
#

not sure, I'm just copying random things from the internet as I said

inner mesa
#

It looks like you took a very old example and changed some random things

#

Yeah

dense patio
#

Yeah I'll adjust, one moment

inner mesa
#

See the docs

dense patio
#

yepp

#
  - platform: template
    sensors:
      players_list:
        friendly_name: "Players List"
        value_template: "{{ state_attr('sensor.minecraft_server_players_online', 'players_list') }}"```
#

should be good now, according to HA

#

restart time

#

Lovely, it works

#

thankies~

fair wind
#

How can I use the result below, and turn into automation/script to switch.turn_on switches that have same 'entity_id' as list of results? End goal is to have automation/script that is triggered when Sun=sunset.

{% for state in states.sensor | rejectattr('attributes.RStatus', 'undefined') | selectattr('attributes.RStatus', '==', 'O') %}
{{ state.entity_id }}
{% endfor%}

inner mesa
#

start by just outputting an actual list

#
service: switch.turn_on
data:
  entity_id: "{{ states.sensor|rejectattr('attributes.RStatus', 'undefined')|selectattr('attributes.RStatus', '==', 'O')|map(attribute='entity_id')|map('replace', 'sensor.', 'switch.')|list }}"
plain magnetBOT
terse palm
#

is there any way i can get a graph of how many minutes an entity has been in a state, by day?

#

actually, i guess it's a little more complicated than that - i want to see daily AC usage, my entity "thermostat_cooling" is set to 0 when the AC is off, and some value like 72 when the AC is on, so i wanna know how many minutes it's been non-zero for the day

lofty mason
terse palm
#

perfect, thanks!

silent flicker
#

apologies, i am rewriting mine because it got a little ugly. hope that is okay. i am using the weatheralerts HACS addon. I am trying to figure out what to write in my template to get the output of the "description" field in the weather alert.

for example, i want to get the data that is only inside "description" or "area":

plain magnetBOT
silent flicker
#

right now i can write this to get the full alert:

{{ state_attr('sensor.northumberland', 'alerts') }}
marsh cairn
#

So the output you posted is the attribute 'alerts' of the sensor.northumberland ?

silent flicker
#

yes that is right

#

but i wanted to text to speech the alert

#

but not the whole thing, because thats huge

#

would there be an easy way to search or split by "description:" to extract just that bit?

marble jackal
#

Look in developer tools > states, it will have an actually readable output

#

But probably this will work

{{ state_attr('sensor.northumberland', 'alerts') | map(attribute='description') | list }}
#

Probably still a lot of text

silent flicker
#

thats better. it just looks like this:

['THE NATIONAL WEATHER SERVICE HAS ISSUED SEVERE THUNDERSTORM WATCH\n440 IN EFFECT UNTIL 10 PM EDT THIS EVENING FOR THE FOLLOWING\nAREAS\n\nIN PENNSYLVANIA THIS WATCH INCLUDES 12 COUNTIES\n\nIN CENTRAL PENNSYLVANIA\n\nADAMS                 COLUMBIA              CUMBERLAND\nDAUPHIN               FRANKLIN              LANCASTER\nLEBANON               MONTOUR               NORTHUMBERLAND\nPERRY                 SCHUYLKILL            YORK\n\nTHIS INCLUDES THE CITIES OF BERWICK, BLOOMSBURG, CARLISLE,\nCHAMBERSBURG, DANVILLE, GETTYSBURG, HARRISBURG, HERSHEY,\nLANCASTER, LEBANON, NEWPORT, POTTSVILLE, SHAMOKIN, SUNBURY,\nWAYNESBORO, AND YORK.']
inner mesa
#

Add |first

silent flicker
#

what the heck does that do lol

plain magnetBOT
silent flicker
#

it looks way better

inner mesa
#

Just what sounds like - returns the first item in the list

silent flicker
#

it got rid of all the weird spacing and \n

marble jackal
#

Because it actually converts the \n to a line break

#

But if there are multiple alerts active, you'll only see the first one

inner mesa
#

I guess you could do |join('\n')

marble jackal
#

You could do something like

{{ state_attr('sensor.northumberland', 'alerts') | map(attribute='description') | join('\n') }}
inner mesa
#

Pfft

marble jackal
#

What he said

silent flicker
#

Thanks I will try that in a few. Only reason I need this now is because we had 2 tornadoes yesterday and no alarms.

silent flicker
marble jackal
#

Yes, with the last version I posted

fierce barn
#

Hi, I'm trying to send the username to the script. I have code that used to work, until a few weeks ago.

  action: call-service
  service: script.tooglescript
  data:
    notify_id: |
      {{ user }}```
#

Now it's not sending anything.
Any idea how to fix this?

marble jackal
#

You can't use templates in a tap action

fierce barn
#

Ooo, do you have any suggestions on how to do this?

marble jackal
#

Hmm, maybe I'm wrong though.. But I'm off to bed now.

#

So I can't test it

fierce barn
#

Good night

heavy island
#

I have some windows sensor entities that are all of the form binary_sensor.<room>_<identifier_might_have_underscores>_window_open I want to make sensors per room that indicate that any window is open. What is the yaml for that?

grizzled grove
#

Is there a way to multiply a decimal value (as a percentage), then substract that value from the multiplicand; all in the same expression?
ex:

{{ (10.60 * 0.01) | round(2) }} = 0.11

Then substract the "0.11 " to the "10.60".

inner mesa
#

Parentheses

#

It's just math and order of operations

marsh cairn
#

Instead of calculating 1 % and substracting it, I'd suggest to calculate 99%.
{{ (10.60 * 0.99) | round(2) }}

grizzled grove
grizzled grove
marsh cairn
#

You could also alter it to use changing percentages by using (1 - percentage) instead of 0.99 - "percentage" to be replaced by a proper variable

#

In the 0.01 format

grizzled grove
#

Indeed. Thanks for the ideas!

edgy gorge
#

For a custom button card, I'm trying to write a states > value: that's basically capturing all states but off, I am not sure how to exactly write that

#

Any pointers?

#

or if a value that contains a certain string of text

sharp frigate
#

Is there any docs/guidance on writing messages in templates to handle singular/plural language? I'm writing TTS templates with variable numbers refering to singular or multiple things.

marble jackal
#

I'm not sure I understand what you are asking

#

Do you have an example?

sharp frigate
#

Sure, I want write two different sentences depending on the value of a state. "There are {{ count }} people at the front door" vs "There is someone at the front door" depending on the value of count, which is set from a sensor.

#

Is the (only) way to use if/else?

marble jackal
#

yes, someting like There {{ 'is someone' if count == 1 else ('are ' ~ count ~ ' people') }} at the front door

fickle sand
marble jackal
#

@edgy gorge custom:button-card uses javascript, this channel is for jinja templates. You should ask in #frontend-archived

sharp frigate
mighty ledge
fair wind
marble jackal
#
service: switch.turn_on
data:
  entity_id: >
    {{
      states.sensor
        | rejectattr('attributes.RStatus', 'undefined')
        | selectattr('attributes.RStatus', '==', 'O')
        | map(attribute='entity_id')
        | map('replace', 'sensor.', 'switch.')
        | map('regex_replace', '$', '_FP')
        | list 
    }}
#

@fair wind

frank beacon
#

Howdy. I've created a template to return the timestamp of when a device will finish charging. The charge_rate below is in kW and charge_required is kWh.

{% set charge_rate = states('sensor.battery_charge') | float(default=0) %}
{% set charge_required = states('sensor.kwh_remaining') | float(default=0 %}
{% set time_to_charge = charge_required / charge_rate %}
{% set battery_full_time = now() + timedelta(hours=time_to_charge) %}
{{ battery_full_time }}

You can probably see the issue. It works fine if charge_rate > 0, otherwise there is a divide by 0 involved.

I can do a conditional to only set time_to_charge if charge_rate > 0 but I'm not sure what timestamp to return in that case. Any ideas? Thanks.

#

I guess a simpler way to put the question is, if there is no valid timestamp from the template sensor, what's the best way to handle that? Setting to none maybe?

marsh cairn
#
  unavailable
{% else %}
  {% set time_to_charge = (states('sensor.kwh_remaining') | float(0)) / (states('sensor.battery_charge') | float(0)) %}
  {% set battery_full_time = now() + timedelta(hours=time_to_charge) %}
  {{ battery_full_time }}
{% endif %}```
Would you mind to try this? I'm at work right now and cannot use my template development tab. ๐Ÿ˜†
frank beacon
lofty mason
marsh cairn
#

If it is part of a template sensor, indeed.

frank beacon
#

Ah, I'll give the availability template a try. Does the availability: template get rendered first? i.e. if the output of that is false or 0, it doesn't bother rendering the state: template.

marsh cairn
#

From the template sensor documentation: An availability template may be defined to suppress rendering of the state template.

frank beacon
#

Perfect. Thanks both for your help ๐Ÿ™‚

lament garnet
#

Is it possible to access statistics recorder data in template without defining new template for it? I want to show 5min mean value. Same value you see in a statistics card. Something along the lines:

{{ statistics('sensor.grid_in_power', '5m', 'mean') }}

inner mesa
#

No

torpid mural
# heavy island I have some windows sensor entities that are all of the form `binary_sensor.<roo...

I'm no expert on templates, but does this help you? It returns the number of binary sensor devices that have a device_class of 'door' and are in a particular room ('woonkamer' in my example) and that have a state of 'on'.

{{ states.binary_sensor
    | rejectattr('attributes.device_class', 'undefined') 
    | selectattr('attributes.device_class', 'eq', 'door') 
    | selectattr('entity_id', 'in', area_entities('woonkamer'))
    | selectattr('state', 'eq', 'on')
    | map(attribute='identity_id')
    | list() 
    | length() }}
tulip ridge
#

Hi guys, can I use templates within the automation action "define variables"?

I'am trying to do something like this:

variables:
  user: >
  {% if states.sensor.keypad_code.state.startswith('2865') %}
    {{"Majuss"}}
  {% elif states.sensor.keypad_code.state.startswith('7127') %}
    {{"Sandra"}}
  {% else %}
    {{"Jemand"}}
  {% endif %}
#

so setting a variable based on the keycode and then use it in a TTS message

#

I know that I could use the template directly inside the tts message but It would spare me a lots of code if I just could set a variable..

inner mesa
#

yes:

Variables can be templated.

#

BTW, {{"Majuss"}} is the same as just Majuss

tulip ridge
#

It was a frontend bug for me. When I save the template text 2 out of 3 cases wierd stuff is happening...

glacial lark
#

I'm losing my mind here. But I'm trying very hard to keep it short lol.

  1. Are all sensor values stored as strings? Meaning...if I create a sensor or binary sensor and then try to use that sensors value in another template, will that value always be a string? Or will it be picked up as a boolean?
  2. Depending on the answer to the first question. Is there a way to convert a string boolean value into an actual boolean value?
inner mesa
#

all states are always strings

glacial lark
#

I figured that for "sensor" entities. But I was hoping that would not be the case for "binary_sensor".

inner mesa
#

sure. is_state('input_boolean.whatever', 'on')

#

it's true of every state for everything since the dawn of time ๐Ÿ™‚

glacial lark
#

Okay I'll try that. I've been banging my head on my desk for a while. I'm trying to make a sensor/binary sensor which returns a boolean indicating whether today is a holiday observed by my electric utility. I have all the logic worked out, but trying to use that value in another template has been driving me insane.

inner mesa
#

since it's just a string, any form of comparison will yield a boolean

glacial lark
#

Yeah, I was just trying to be fancy and was hoping I could do something like:

{% if states('binary_sensor.energy_meter_tariff_holiday')  %}
...
inner mesa
#

if you added == 'on', you would have had it ๐Ÿ™‚

#

in any case, all states are strings, and probably will always be

glacial lark
#

Yeah, I see that now. I've been using == true and that's what led me here.

inner mesa
#

you're aware of devtools -> States?

#

it tells you exactly what the state is

glacial lark
#

Yup, but I know YAML and similar can be weird sometimes and will treat certain literals as booleans implicitly

#

So I was hoping true / false would work, and was also hoping it would work without using the comparison.

#

I mean, it's just a few extra characters so it's not a big deal either way.

#

However, I did not think to actually use "on" or "off". For some reason I thought those were just UI conversions from a boolean underneath.

marble jackal
#

But maybe that was already mentioned ๐Ÿ˜…

marble jackal
inner mesa
glacial lark
#

Oh that's interesting, | bool actually converts "on"/"off" properly

inner mesa
#

lots of good stuff in the topic links

glacial lark
#

Yeah, but who reads documentation.....kidding. That's a good link, thanks. I didn't even bother checking the HA docs. I read something about as_bool in the jinja docs a StackOverflow answer, which the HA template editor said wasn't a thing, so I just assumed there was no bool parse function.

plain magnetBOT
arctic quail
#

Whoops, meant to edit before clicking enter. Something like:
temperature: 68
fan_speed: 3
mode: "cool"

ocean tusk
#

i need some help

#

{{ states("input_datetime.inicio_evento_calendario") + timedelta( hours =
states("input_number.duracion_horas_evento_calendario") | float, minutes = states("input_number.duracion_minutos_evento_calendario") | float ) }}

#

im getting this error

#

TypeError: can only concatenate str (not "datetime.timedelta") to str

marble jackal
#

Comment the input datetime state to a datetime first using as_datetime

ocean tusk
#

thanks

plain magnetBOT
silent vector
#

Didn't realize it was that long whoops

plain magnetBOT
silent vector
#

๐Ÿคฆโ€โ™‚๏ธ

ocean tusk
#

one more sorry

#

how can i reset the data after running a script

#

script:
add_calendar_event:
sequence:
service: calendar.create_event
target:
entity_id: calendar.calendar
data:
summary: '{{ states("input_text.titulo_evento_calendario") }}'
description: '{{ states("input_text.descripcion_evento_calendario") }}'
start_date_time: '{{ states("input_datetime.inicio_evento_calendario") }}'
end_date_time: '{{ states("input_datetime.inicio_evento_calendario") | as_datetime + timedelta( hours =
states("input_number.duracion_horas_evento_calendario") | int, minutes = states("input_number.duracion_minutos_evento_calendario") | int ) }}'

inner mesa
#

you want in

ocean tusk
#

i want to reset to defaults

silent vector
#

As in | select('in',second_list)?

inner mesa
#

you need another level

#

random_name['bar'] | selectattr('name', 'in', second_list) | list, I think

#

without testing

silent vector
#

Unless I'm doing something wrong I get an empty list

#

I was doing something wrong lol

plain magnetBOT
ebon peak
#

How do I escape the ">" character?

inner mesa
#

which one?

#

the one that introduces the multiline template?

ebon peak
#

Yes

inner mesa
#

why?

#

it's required

#

escaping will just break it

ebon peak
#

My issue is I am trying to add another sensor, but it seems to be hung up in the multiline

inner mesa
#

that's not the problem

#

the problem is that you're mixing up the old and new template sensor formats

ebon peak
#

Oh lame.

inner mesa
#

what you have is some weird and invalid amalgam

ebon peak
inner mesa
#

yes

ebon peak
#

I'll go from there then. Thank you @inner mesa

ebon peak
#

So based on the new format, I have this in my configuration.yaml:
history: !include history_state_sensors.yaml

#

In that I am trying:

sensor:
  - name: Lamp ON today
    entity_id: light.my_lamp
    state: "on"
    type: time
    start: "{{ now().replace(hour=0, minute=0, second=0) }}"
    end: "{{ now() }}"
#

I have tried history: and history_stats: , but I get the same error as sensor: which is - Invalid config for [history]: [sensor] is an invalid option for [history]

#

Oh wait

#

So I it should be?
history_stats: !include history_state_sensors.yaml

inner mesa
#

I think you're getting mixed up because you had both a history_stats sensor and a template sensor (using the new format) together, and they can't be combined like that

#

just follow the docs for each sensor type

#

I was commenting on your template sensor, not the history_stats sensor

#

as that's the one you were concerned with, and was also wrong

plain magnetBOT
ebon peak
#

So removed history_stats: !include and just added it my configuration.yaml, but no sensor shows

#

Running Check Config results in no errors, and my reload results in no related logs either

#

I'm usually not this dumb, but yea, needed to restart. Thank you.

terse palm
#

hi, i'm having trouble with history_stats, i have a entity (my AC) that always has state="cool" (whether it's running or not) - i want to use history_stats to track when it's running, but the only thing that changes is the "state attribute" hvac_action changes between "idle" and "cool", is there a way to use history_stats to track an attribute of an entity?

lofty mason
terse palm
#

oh great, thanks!

plain magnetBOT
ivory harbor
#

I didnt format right, aprops of above ^ I'm trying to use a template to pull calendar info... it doesnt error but the calendar data doesnt populate. If I go to my calendar dashboard, I notice it takes 2-5 seconds to populate. How should I handle this? can I add some sort of delay in my template?

lost adder
#

Good morning, yesterday I accidentally deleted the energy dashboard, how do I install it again?

plain magnetBOT
normal moat
#

*and I dont know how to use code block on discord ๐Ÿ™„ sorry about that

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.

mighty ledge
#

You don't really explain how you want to use the timestamp, other than you just said you want to use it

normal moat
#

Sorry, the sensor contains all 24h of the current day.
I want to use use the time stampes to plot a graph of todays price.
I got it working with the the unmodified sensor.

mighty ledge
#

Then why do you need the second sensor?

#

If you just want to filter

#

just do it in whatever's plotting, no reason to make a second sensor when you're still just making a list of dicts

normal moat
#

so the tarrifs I want to add change depending on summer/winter and what time of day it is.

mighty ledge
#

yeah, you can do all that, you have to be using something custom to generate the graphs

#

because that's only doable via the energy pannel and you can't use historical data like you are with the energy panel

#

anyways, if you're dead set on the second template..

#
{% set ns = namespace(items=[]) %}
{% set s = today_at() %}
{% set e = s + timedelta(hours=24) %}
{% for price in value_json.prices if s <= price.localTime | as_datetime | as_local <= e %}
  {% set ns.items = ns.items + [{'price': price.rawPriceInclVat, 'time': price.localTime}] %}
{% endfor %}
{{ ns.items }}
#

however, you'll most likely need to use

#

state_attr('xxxx.xxx', 'prices') instead of value_json.prices

#

if it's coming from an entity

normal moat
#

Thanks I'll give it a go

ivory harbor
#

has anyone been able to get a list of daily calendar apts via a template? I'm having trouble iterating the list

marble jackal
#

you cant't using a template, as a calendar enttiy only has one event

#

you can do it using the new service call responses introduced in HA 2023.7 (released yesterday)

ivory harbor
#

what if I only wanted to pull the one event (the one I see when I look at the state of calendar.my_calendar)? shouldn't I be able to get that in a template?

inner mesa
#

Templates only work with what's available in the state machine. They don't communicate with the integration directly

#

If you don't see it in devtools -> States, in general templates can't see it

ivory harbor
ivory harbor
marble jackal
#

you could shedule an automation on a time pattern, or on a state trigger of the calendar entry, use the new service call in the action, and send the results you need in an event

#

then use that event for a trigger based template sensor, and put the data in an attriubute

#

and voilla you have it in the state machine, and get it out using templates ๐Ÿ™‚

ivory harbor
#

makes sense... or I could just fully adopt the new service call which is probably the easiest option ๐Ÿ™‚

#

is stubbon when I want to learn something even if what I want to learn isn't possable ๐Ÿ˜‚

marble jackal
#

depends on where you need it, if you want it in a markdown card for example, you can't run the service call

ivory harbor
#

sorry, @mighty ledge not you - somehow a space got introduced

spiral grove
#

Is there a way to define the possible states for a template sensor?
So, for example, they would should up in the automation visual editor from/to state dropdowns?

lofty mason
silent flicker
#

on my Cards I currently have this - https://i.imgur.com/zoPxLYX.png

when I go into Templates and run

{{ states('climate.bedroom_heater') }}

all I get is

off

Is there a way to retrieve the info like in the card displays?

marsh cairn
#

{{ state_attr('climate.bedroom_heater','temperature') }} for the attribute temperature

#

Or according for whatever attribute you want

silent flicker
#

its a custom integration for the thermostat, so im not sure that works. it currently says NONE when i do that. so i might be out of luck here lol

inner mesa
#

devtools -> States

#

You can get whatever it shows

silent flicker
#

ahh. yeah i forgot about that lol

marsh cairn
#

You need to look at the dev tools for the states. The available attributes are shown there

silent flicker
#

yeah its called "current_temperature: 75"

#

that'll do it

#

thanks

lean turret
#

any hackz0r HA users here who can help me with a template? i have all my sensors in configuration file. is that bad? ๐Ÿ˜„ i'll get errors. duplicated mapping key (66:1) with states and template:

inner mesa
#

were you going to share something?

lean turret
inner mesa
#

you repeated template:, as the error mentioned

#

you also have two different ways of formatting the sensors underneath each

#
template:
 sensor:
   name: "stromverbrauch"
   unit_of_measurement: kWh

and

template:

 - sensor:

     - name: sophamtning_days

       state: >-
#

It shows how to define multiple sensors

lean turret
#

Thanks!

urban mural
#

Hi everybody, I am new to HA and busy with this blueprint: https://community.home-assistant.io/t/zha-lidl-livarnolux-tuya-silvercrest-4-button-remote/372186/12

The problem is buttons 1 and 2 are working properly, but buttons 3 and 4 do nothing on either short or long press.
By using traces I figured that the conditions for button 3 and 4 are wrong, so no action is taken.
I will do anything to solve it and deliver any information necessary and any help or hint will be appreciated, since the original poster doesn't seem to react to this post anymore. I am willing to publish any working solution.

lyric comet
#

You could simply correct the conditions in a copy of the blueprint, if you have worked out what is incorrect. Blueprints are just script files and if you have the File Editor or VScode add in installed you can edit them on your HA instance, or install the Samba Add in to edit them on your normal desktop computer.

mighty ledge
#

That's what I would do

urban mural
#

I have only figured where is goes wrong, but not what is going wrong. As I said: I'm a noob!

mighty ledge
#

Post your trace

#

otherwise we are guessing

urban mural
#

How do I that?

mighty ledge
#

you can share an image or if you know how to get to the text, you can share text

plain magnetBOT
#

Please use imgur or other image sharing web sites, and share the link here.

Image posting is blocked in most channels to discourage people from sharing text as images. Sharing text as images assumes that everybody sees the world as you do, which isn't the case. Some people are colour blind, or have visual impairment that means they can't make sense of an image of text.

#

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

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

urban mural
#

Thanks, gimme a second. I guess the choice step is the one you want to see?

mighty ledge
#

the failed condition

#

or the trigger with the changed variables page shown

#

and the trigger being the 3rd and 4th case

mighty ledge
#

can you show the changed variables tab?

#

you're on the step config tab

#

the lower right set of tabs

#

on the trace

urban mural
#

here for the choice:

command: step
args: '[<StepMode.Up: 0>, 51, 10]'

mighty ledge
#

So the blueprint is now broken because it's using enums instead of strings

#

in the condition for 3, change

  - conditions: '{{  command == ''step'' and stepmode == ''StepMode.Up'' }}'

to

  - conditions: '{{  command == ''step'' and stepmode == 0 }}'
urban mural
#

ok, thank you , the rest has to be changed accordingly?

mighty ledge
#

You'll need to look at the trace again and see what number stepdown mode is, then make similiar changes to that one

mighty ledge
urban mural
#

I will do, as far as I remember it is 1 but I will check again

mighty ledge
#

check again and post the results here

#

you can just copy/paste the args

urban mural
#

Can I do this in the original blueprint.yaml?

mighty ledge
#

I believe so but i'm not 100% sure

urban mural
#

If I want to use long press, then I need to use move and movemode, right?

mighty ledge
#

Not sure

#

it seems like it should just come through as command == 'step'

urban mural
#

Wait I will trigger a long press and post the result

#

Thanks for your patience

floral shuttle
#

is templates still the only way we can do: {{[0,states('sensor.netto_verbruik')|int(default=0)]|max}}? figured Id go the UI helper route, but cant find an option to use 0 there, only entities

mighty ledge
#

no idea what you're asking

lyric comet
#

Quick question, as I am having a brain freeze. I have a string 20230707105416 (2023/07/07 10:54:16) which I need to get to a date time object to use with easy_time, but I can't seem to find the right combination to convert it.

mighty ledge
#

wtf kind of date string is that

lyric comet
#

The filename from a voicemail file which comes in from my phone system

floral shuttle
mighty ledge
#

lol aight, so you'll have to split it because format won't work while it has 2 dates

lyric comet
#

It is one date. the string is 20230707105416 I put the other to show the layout

#

sorry to not being clear

mighty ledge
#
{% set x = value.split()[0] %}
{% set fmat = "%Y%m%d%H%M%S' %}
{% set input = strptime(x, fmat) %}
#

oh ok

#

just use strptime

#

it will be UTC though

#

so you'll need to do | as_local

#

and I might have the arg order wrong on strptime

lyric comet
#

Thanks I was close but I think I had the format wrong ๐Ÿ˜ฆ

marble jackal
mighty ledge
floral shuttle
#

Ha, yes, I was actually writing that up for testing as we speak! seems a bit hacky, but indeed I have a few of those

mighty ledge
#

If I undertand correctly, I don't see that as hacky

floral shuttle
#

its the min/max helper in the Ui, and I want the max of an entity and 0

mighty ledge
#

yes I gathered that after the fes posted

sonic ember
#

I'm getting a "problem" warning about deprecated YAML (command line switch). Does everyone get this, tasteless of whether that YAML is even used in the installation? Asking because I can find any use of it in my YAML, but I still get the warning

urban mural
#

that's a unix timestamp

sonic ember
#

Wondering whether I need to search further, or just ignore it

marble jackal
#

You only get that warning if you have the old format in your config

mighty ledge
#

well, this has nothing to do with templates, but search your files for platform: command_line

sonic ember
#

Oh, I thought it's template related

mighty ledge
#

nope, it's command_line

sonic ember
#

Will search, but I don't think I ever used it.. Don't even know how it works. So maybe in some component or add-on

mighty ledge
#

nope

#

you had to have added it

#

it's yaml only

#

always has been

sonic ember
#

Now I'm starting to doubt my brain rather than my installation

mighty ledge
#

it'll be in your switch section of your configuration.yaml

sonic ember
#

Will go hunting again

marble jackal
mighty ledge
#

it should be easy to find, literally just do a 'find in files' using vscode or notepad++ for platform: command_line

floral shuttle
#

hmm, not that simple apparently,```

  • sensor:

    • unique_id: sensor_zero
      state: 0```
#

and yet the ui helper produces unknown

#

it says max entity_id is sensor.zero, which is correct, because Im returning power to the grid currently

#

could it be it requires the correct and full set of classes before being a valid entity for those helpers?

#

apparently not, Ive set that now, and still the helper remains unknown

#

not sure where the issue lies, is it this template sensor, or the UI helper causing the issue

sonic ember
floral shuttle
#

o well, I deleted it because it showed unit_of_measurement: ERR, which I hadnt seen before. Recreated it using the exact same entities and now it returns a correct value 0.0 (the template returns a clean 0 int, but thats a minor issue probably..)

marble jackal
#

ah apparantly the unit of measurement needs to be the same for all sensors

floral shuttle
#

dont know why that unit would show ERR though, maybe it was the fact I had it created in 2 rounds, and needed to be fixed in 1 go. Anyways, seems to be working now. Hoping the UI helper will be seeing a subtract option too any time in the future

mighty ledge
#

subtract doesn't make sense IMO

#

it'll just raise questions

floral shuttle
#

I can see that could be a bit more complex than sum (needs am entity to subtract from, so not equal entities), but having quite a few of these{{(states('sensor.zp_actuele_opbrengst')|float(0) - states('sensor.netto_verbruik')|float(0))}} would benefit from that subtract

urban mural
#

in the condition for 3 change

floral steeple
#

hi all, how do I use the image entity? Some research has lead me to believe that I need to template it but instructions are very scant

#

in this case, I'd like to convert a camera steam as a single image

keen abyss
#

Hey, I have the following trigger:

platform: state
entity_id:
  - sensor.samsung_last_notification
to: " Someone is at your Front Door "

The notification sometimes contains and sometimes doesn't contain an emoji for some reason, so I'm trying to change this somehow to check if the state contains these words or not

I'm trying to get it to something similar to :

[\w\W]*Someone is at your Front Door[\w\W]*

meaning [anything]Someone is at your Front Door[anything]

Any ideas?

#

Can I add a wildcard somehow?

inner mesa
#

You have to use a template trigger

#

{{ 'some string' in states('sensor.whatever') }}

lyric comet
floral steeple
#

thank you!

ocean tusk
#

what would be the opposite of in?

#

value_template: "{{ (name | lower) in state_attr('sensor.shopping_list2','content') | lower }}"

inner mesa
#

not in

ocean tusk
#

thanks

inner mesa
#

or not xxx in dljadlfj

rare furnace
#

Can an icon color in a button or card be a dynamic RGB color?

Like this rgb_color: '{{state_attr('light.tv','rgb_color')}}'

#

icon_color: |-
{% if is_state('light.hue_play_1', 'on') %}
rgb_color: '{{state_attr('light.tv','rgb_color')}}'
{% endif %}
entity: light.tv

Like this, but ofcourse this doens't work

#

This is in a mushroom template card

inner mesa
#

Where did the 'rgb_color' tag come from?

rare furnace
#

found it in dev tools for my hue light

inner mesa
#

that's completely separate

#

in any case, you can just give it "#xxxxxx"

rare furnace
#

I want it to be dynamic

#

Like follow the color of my lights

inner mesa
#

so if that's what that attributes provides, then get rid of the rgb_color: tag that you added there

#

it has nothing to do with the card

rare furnace
#

I tried that, did not work

inner mesa
#

ok

#

it will

#

you also can't have an "if" with no "else".

rare furnace
#

Tried without the if statement as well

#

didnt work

inner mesa
#

you keep saying that

rare furnace
#

Well yeah, because I did

inner mesa
#

here's an example of a static RGB color that I'm using:

#

icon_color: "{{ 'green' if is_state(entity, 'armed_to_night') else '#696969' }}"

#

you can construct that string from the attribute

rare furnace
#

Its not static, I dont want that

inner mesa
#

look

#

work with it

rare furnace
#

Okay so I just need to make a huge if statement for all my colors

#

?

inner mesa
#
icon_color: >
  {% if is_state('light.hue_play_1', 'on') %}
    #{{state_attr('light.tv','rgb_color')}}
  {% else %}
    red
  {% endif %}
#

I have no idea what that attribute's value is

rare furnace
#

{{state_attr('light.tv','rgb_color')}} = (72, 8, 255)

#

It comes out that, with the parentes

inner mesa
#

alright

rare furnace
#

Do I need to convert the XX,XX,XX to #XXXXXX to make it work?

#

So I need to make a whole program that first converts the value to that then use it in the icon color?

inner mesa
#
{% set value = (72, 8, 255) %}
{{ "#%02x%02x%02x" % (value[0], value[1], value[2]) }}
#

-> #4808ff

ocean tusk
#

is there any way to compare a string in a json file?

inner mesa
#

in theory, {{ "#%02x%02x%02x" % state_attr('light.tv','rgb_color') }}, but I don't have one to test

ocean tusk
#

i want to check before add a new item in the shopping list

inner mesa
ocean tusk
#

the shopping list creates a json file in config/

plain magnetBOT
ocean tusk
#

how can i check before adding a new one if its on the list already?

lyric comet
#

The easier way is to use the remove item for the item you are adding then add it again.

#

You might even find adding the same item again has no effect, but I don't use the shopping list integration.

inner mesa
#

that integration is one of the more primitive and unfriendly ones

#

it needs a service that returns the list, at least

#

now that we can do that

ocean tusk
#

that wolud be nice

floral steeple
rare furnace
#

{% if is_state('light.tv', 'on') %}
{{ "#%02x%02x%02x" % state_attr('light.tv','rgb_color') }}
{% endif %}

How can I add else in here?

      {% if is_state('light.tv', 'on') %}
        {{ "#%02x%02x%02x" % state_attr('light.tv','rgb_color') }}
      else
            grey 
      {% endif %}
lyric comet
#

Use {% else %}

inner mesa
#

I gave you an example above

#

which I just stealthily fixed

rare furnace
#

lol

inner mesa
#

in any case, this is all just Jinja

rare furnace
#

yeah I tried your example first but didnt work ๐Ÿ˜›

inner mesa
#

there are several links in the channel topic

rare furnace
#

Thanks

inner mesa
uneven pendant
#
command_line:
  - sensor:
        name: Media3/G Used
        command: ssh -i /config/.ssh/ha -o 'StrictHostKeyChecking=no' myserver.com "df -k | grep nas | sort -k 6 | awk 'NR==2 {print \$3}'"
        scan_interval: 1800
        unit_of_measurement: "GiB"
        value_template: >-
          {% set data = default.split("\r\n") %}
          {% set data_split = data[1] %}
          {% set data_int = int(data_split) %}
          {{ (data_int / 1048576) | round(2) }}
#

What is the default variable for data passed to a value template?

#

I used to use data.split here, but it stopped working.

uneven pendant
#

so value. thank you

#

i'm guessing the custom integration i used to use had a data variable.

spring thicket
#

Hi, is it possible to make a for loop over every light that is on via templating?

inner mesa
#

Sure

#

Why?

spring thicket
#

And how would one go about the for loop? Cause i tried making a group of all the lights but I couldn't find out how I'd loop though those lights to even check if they were one so

inner mesa
#

You don't necessarily need a loop. Hence the why?

#

The template is trivial

spring thicket
# inner mesa Why?

I'm trying to loop though lights that have been on for longer then 10 minutes and then if it has detect what room its in then call a alexa actionable notifications for that room to ask if i can turn the light off. If no response then turn off etc etc

inner mesa
#

{{ states.light|selectattr('state', 'eq', 'on')|map(attribute='entity_id')|list }}

#

Alright, well, that's a start

spring thicket
#

Is there a way to filter out groups?

inner mesa
#

Yes

#

rejectattr('attributes.entity_id', 'defined')

spring thicket
#

Wait could you explain to me how that works?

#

Are light groups not defined?

inner mesa
#

All groups have that attribute

spring thicket
#

Defined?

inner mesa
#

entity_id

#

Look

spring thicket
#

Yeah but then wouldn't that reject every light? Since they all have that attribute?

inner mesa
#

No

#

Look

spring thicket
#

?

inner mesa
#

I'm saying you can confirm

#

devtools -> States

#

Look at a group, look at a light

spring thicket
#

For some reason its not showing up that entity_id id an state attribute on either

#

Are there any attributes that define how long a light is been on for?

inner mesa