#templates-archived

1 messages Β· Page 139 of 1

true otter
#

no this is not part of custom ui, I actually have no idea what custom ui is. I am using card_mod: style: | :host { --paper-item-icon-color:

mighty ledge
#

then it should be working if your template is correct.

#

you aren't using state_color are you?

#

if you are, you'd want to use --paper-item-active-icon-color

#

it might be --paper-item-icon-active-color, it's one of the 2

true otter
#

i think the template is correct as no errors in Dev>template. here is what i have card_mod: style: | :host { --paper-item-icon-color: {% if is_state('group.security_locks', 'locked') %} green {% elif is_state('group.security_locks', 'unlocked') %} yellow {% elif is_state('group.security_locks', 'unavailable') %} red {% endif %}

mighty ledge
#

again, are you using state_color?

true otter
#

no not that i am aware of. here is the rest of my code - type: state-icon entity: vacuum.roborock_vacuum_s5 icon: mdi:lock-smart style: top: 91.5% left: 51% width: 55px color: white opacity: 0.5 '--mdc-icon-size': 65px card_mod

mighty ledge
#
  - type: state-icon
#

that's not a card

#

are you sure that's the correct card_mod path?

#

Also, pretty sure you have to mod from the card down, not the row on that one

#

actually, that's a picture elements, which has it's own style

#

Just looking at a recent post in the card-mod thread, your selector for the element should be:

      style:
        state-badge:
          $:
            ha-icon:
              $: |
                ha-svg-icon {
                  color: {{ }};
                }
#

Also, the code you are writing doesn't have a closing ;

#

Seems like you need to refresh yourself on card-mod, picture-elements, and generating selectors for each item.

spiral imp
#

Back the drawing board a bit. So the template below works when Glances returns an uptime of greater than 24 hours because the format is "X days, HH:MM:SS". This template returns "3.75 days" for example.

{% set d = states('sensor.glances_ubuntuserver_uptime').split(', ') %}
{% set t = d[1].split(':') %}
{{ (d[0][:2] | float + (t[0] | float / 24) + (t[1] | float / 1440) + (t[2] | float / 86400)) | round(2) }}

But I rebooted the server Glances is running on and when less than 24 hours, it only returns "HH:MM:SS". Any ideas how I can alter my template so I can get the output of "0.75" days for example.

true otter
#

okay cool , I'll did in.

uneven pendant
#

When i place...

#

{% set degree = states('sensor.openweathermap_temperature') | round(1) %}
{% set weather = {
"temperature": degree,
"unit": "Β°C"
} %}

#

at the beginning of my automations.yaml file it throws a bunch of syntax errors.

#

how do i define degree, and weather

buoyant pine
#

That isn't meant to be used by itself. It needs to be in the template that it's associated with

uneven pendant
#

will that insert it into the file on its own

buoyant pine
#

Let's take a step back. What are you trying to use this with?

mighty ledge
spiral imp
#

I believe the .split(',') will return an error if there is no "," correct?

mighty ledge
#

no

uneven pendant
#

I have an automation that updates a text box, i need it to dynamically check the temperature and use the temperature from open weather maps in the string it updates the text box to

spiral imp
# mighty ledge no

In the template editor, I am currently getting "UndefinedError: list object has no element 1" and the uptime sensor is 18:39:37. So .split(',') would be = 0?

mighty ledge
#

FYI I already gave you the answer

#

just reading my initial response, you can gather what d will be without needing to test it, but if you need to test it, test it properly by looking at the value.

spiral imp
# mighty ledge just look at the value of d when you split it

I found this if statement in the forums and it seems to work. Returns 18.78

{% set d = states('sensor.glances_ubuntuserver_uptime').split(', ') %}
{% set x = 1 if 'day' in d[0]|lower else 0 %}
{% set t = d[x].split(':') %}
{{ (d[0][:2] | float + (t[0] | float / 24) + (t[1] | float / 1440) + (t[2] | float / 86400)) | round(2) }}
mighty ledge
#

That's one way to do it, but copying/pasting code will never teach you how to do this

dreamy sinew
#

especially with lazy variables

mighty ledge
#

yep

spiral imp
#

I understand, but that if statement is testing if "day" is present in d[0]. If it is (X Days, HH:MM:SS) then it sets x=1 which makes d[x] in the next line d[1] which is the second split (HH:MM:SS) . If "day" is not present, then it sets x=0 which makes d[x] in the next line d[0] which is the first split (also HH:MM:SS)

#

I understand the logic behind it for sure. What do you mean by lazy variables?

mighty ledge
#

d, t, x

dreamy sinew
#

d/x/t are very bad for readability

mighty ledge
#

doesn't tell you crap

spiral imp
#

gotcha, so spelling them out would be better. Day, time, for example

mighty ledge
#
{% set uptime = states('sensor.glances_ubuntuserver_uptime') %}
{% if uptime not in ['unknown', 'unavailable'] %}
  {% set uptime = uptime.split(', ') %}
  {% set days = uptime[0] if uptime | length == 2 else 0 %}
  {% set hour, minute, second = uptime[-1].split(':') | map('float', 0) %}
  {{ days + hour / 24 + minute / 1440 + second / 86400 }}
{% endif %}
#

much better, easier to understand.

#

if you use an availability template, you can reduce this down to just the meat inside the if statement

spiral imp
#

That is giving the following error in the template editor: TemplateRuntimeError: No filter named 'split' found.

mighty ledge
#

Also. just an FYI adding seconds into your calculation is useless when you round it to 2 decimal places

mighty ledge
#

see if you can spot the split error

#

| means filter

#

one of your splits work, the other doesn't

#

so how would you fix the one that doesnt?

spiral imp
#

the first split (row 3) should work because it is splitting uptime which is set to "X days, HH:MM:SS"

mighty ledge
#

yep

#

but the error has nothing to do with the output of what it's splitting

#

it's a syntax error

#

| means filter

#

your error is: TemplateRuntimeError: No filter named 'split' found.

spiral imp
#

Not sure what happened but when I pasted it, I ended up with `uptime[-1] | split(':') which caused the error

#

I fixed it by removing the | and it works

mighty ledge
#

well you should have changed it from | split to .split

#

I edited the post when you said the error before I pointed you to where the error is

spiral imp
#

Sneaky but helpful πŸ˜‰

mighty ledge
#

πŸ˜‰

spiral imp
#

I understand uptime[0] and uptime[1] with splits. What is uptime[-1]?

mighty ledge
#

you can go backwards in lists

#

forward: [ 0, 1, 2, 3, 4 ... n]

#

backward: [ n ..., -4, -3, -2, -1]

#

so... in your case, if the split worked: [-2, -1], if the split didn't work [-1]

spiral imp
#

but isn't HH:MM:SS uptime[1] after the first split of X Days, HH:MM:SS

mighty ledge
#

it is

#

but time will always be the last item in the list πŸ˜‰

#

uptime (If has a comma)

[ 'x days', 'HH:MM:SS']
#

uptime if it doesn't have a comma

#
[ 'HH:MM:SS' ]
#
{{ [ 'x days', 'HH:MM:SS' ][-1] }} #returns 'HH:MM:SS'
{{ [ 'HH:MM:SS' ][-1] }} #returns 'HH:MM:SS'
#

try it yourself

#

do you use the template editor?

spiral imp
#

yes, but i thought uptime[0] would be the first item in the list and uptime[1] would be the second item in the list. Am I thinking of that wrong?

mighty ledge
#

it is, but you can also access the items backwards

#

did you not read what I wrote?

spiral imp
#

yes, just trying to make sense out if it. I will play around with it in the editor

mighty ledge
#

do you understand forward and backward on a list?

spiral imp
#

yes, i do now

mighty ledge
#

you can access items forwards or backwards

#

a negative determines the direction you're accessing it

spiral imp
#

got it. Makes sense now

mighty ledge
#

0 is the first item, 1 is the second

#

-1 is the last item, -2 is the second to last

#

so you can do it however you want

spiral imp
#

was just going to type that

mighty ledge
#

in your case, time will always be the last item

spiral imp
#

and this filter must provide the position in the split of HH:MM:SS map('float', 0)

mighty ledge
#

no, that maps all values in a list to a float

#

and if it fails, it maps the value to 0

spiral imp
#

and the list is hour, min, sec?

#

mapped to 0,1,2

mighty ledge
#

['0', '1', '2', '3', 'a' ] | map('float', 0) will return [0,1,2,3,0]

#

because a can't convert to a float

spiral imp
#

got it

mighty ledge
#

when using set if you have 3 items, you can list them in the order they come without needing to specify an index

#
{% set a, b, c = 1, 2, 3 %}
#

a will be 1, b will be 2, c will be 3

#

as opposed to doing the following

spiral imp
#

but hours, mins, secs are not "in order" so you have to define an index

mighty ledge
#
{% set a = 1 %}
{% set b = 2 %}
{% set c = 3 %}
#

they are in order

#

the format is HH:MM:SS

#

hours first, minutes second, seconds third

#

when you split 'HH:MM:SS' it will always return ['HH', 'MM', 'SS']

spiral imp
#

Got it. I thought you mean alphabetical order

mighty ledge
#

split does not sort

#

it just splits in the order it gets

dreamy sinew
#

first in, first out

uneven pendant
buoyant pine
uneven pendant
#

kk

hard venture
#

OK, I should have asked here, instead I was thinking out loud in #automations-archived and wandered into the template realm from there. I'm very much a rookie in templates, so I'm not sure if this is possible, but here's the situation and what I'd like to do.

#

For my bath fan, I have a normal toggle switch and a Shelly1 connected to it. Currently, I have an automation that catches the turn on event, turns the fan off, then back on (go see the automation channel for why), sets a 15 min delay then turns it off. This is the "Clear the air" automation.

#

I've got an Rh sensor set to turn the fan on when Rh > 65%

#

I want to use a double-toggle to lock out the Rh sensor for 15 minutes so the bathroom can steam up when desired.

#

I'm thinking I can use the "Turning an event into a binary sensor" section of the template docs to catch the Shelly switching state. If it turns on & Rh < 65%, create a binary_sensor called "ManualOn". If it turns on then off but takes at least 1 second but less than 5 seconds to do so, then create a binary_sensor called "HoldTheFan".

dreamy sinew
#

do you have a motion sensor in the bathroom?

hard venture
#

When "HoldTheFan" is true, start a timer. Finally create a binary_sensor called "TurnOnTheFan" that is ( (Rh > 65% and "HoldTheFanTimer" is idle) or (ManualOn)) which would actually determine if the fan goes on or off.

#

No - no motion sensor.

dreamy sinew
#

that seems reasonable then

hard venture
#

I keep thinking that I need a button shield for the WeMos with the Rh sensor and use one tap on the button for "clear the air" and a double-tap for "steam it up" and just leave the toggle switch out of the equation. However, I don't have that either...

hard venture
dreamy sinew
#

is the event coming in to HA? if so, you could probably skip the sensor and just fire an automation on the event

hard venture
#

I see delay_on in the binary_sensor template parameters, so I think I'll need to use that for the "on" template

#

Part of the problem is that this is a smart fan with its own built-in Rh sensor that doesn't work very well any more. Turn the fan on, the blue light comes on and it's in auto mode. Flip power off, then back on and the yellow light is on and it's in manual on mode. So the automations require a triple-flip dance to get it to come on (for "clear the air", it's catch the switch-on for 5 seconds event, turn power off, delay 500ms, turn power on).

#

So, I have to work around the fact that the power is going off and on multiple times just to get the fan to turn on, and everything I do has to work around that.

dreamy sinew
#

ah ok

hard venture
#

Of course, it might be easier to replace the bloody fan with a stupid-out-of-the-box one instead of stupid-because-it's-broken one, but hey, I'm up for a challenge and not spending extra cash! πŸ˜‰

#

The power-on for 5 seconds is easy to capture and deal with. It's the power-on briefly then off to set the "steam it up" mode that I'm not sure how to best handle. An automation, a template, or what...

#

My thoughts after reading the docs is that a template to determine the ultimate, desired fan status that takes into consideration Rh, manual on, and manual delay is the way to go, I'm just not sure how to get there.

dreamy sinew
#

wonder if you could just replace the controller with a shelly or esp or something

hard venture
#

I've got a Shelly in the box with the switch, and just built an esp as the Rh sensor. Are you talking about replacing the fan's controller with my own hardware?

dreamy sinew
#

there's probably a relay somewhere in there that switches the motor on and off

hard venture
#

Up next on this week's episode of "Hacking bathroom hardware"...

dreamy sinew
#

haha

hard venture
#

I s'pose I could take a look at it. I'm not quite the electrical genius I would like to be. Household wiring? No problem. Actual electronics? I'm... a bit lost...

#

Though I did just solder a couple of wires to my garage door opener switch to be triggered by another ESP out there...

#

Something to think about. The wife is amused and tolerating the playing so far. Blowing up the fan and needing to replace it may be a bridge to far at the moment. πŸ˜„

dreamy sinew
#

so in the unit should be a cuby thing that has wires coming from the mains and going to the motor

hard venture
#

Yeah. I installed it a couple of years back (got tired of people not turning it on or forgetting to turn it off), but I never opened it up to look at the guts of the thing.

dreamy sinew
#

though you would just need to detatch the motor side, run it to your own relay that can handle mains power. run the control signal from some sort of board you control

hard venture
#

and that's exactly where I get lost... 😦

#

Big picture brush strokes like that, I'm with you 100%. Actually figuring it out is the tough part. Sure there's not a software way around it? πŸ™‚

dreamy sinew
#

probably some, but things like shelly and esp make it pretty easy

hard venture
#

OK. Am about done for the night. will set it back up for semi-automatic operation for tomorrow's showers. I might just try popping the box open tomorrow evening to see if it looks obvious enough to attempt a hardware hack. Otherwise, I'll continue to prod at it with HA.

#

thx for the thoughts!

dreamy sinew
#

good luck!

buoyant pine
latent kiln
#

How do I find where this error is coming from? ('from_side' is not anywhere in the yaml files) ```WARNING (MainThread) [homeassistant.helpers.template] Template variable warning: 'dict object' has no attribute 'action_from_side' when rendering '{{ value_json.action_from_side }}'

#

it happens when I run an automation for a xiaomi cube (triggering using rotation, not sides) and possibly prevents it from finishing the automation

uneven pendant
uneven pendant
#

You also taught me, input_text.set_value was a thing. I was using a script i found online.

inner mesa
#

Always chilling words πŸ™‚

uneven pendant
#

guess i need to learn python

shut silo
#

hi. i was wondering if this is possible
{{ is_state('sensor.superb_iv_charger_max_ampere', states('input_number.ampere_step')) }}

#

or should i use {% if ... instead of

#

ah, nevermind. it's working but input_number is 6.0 and not 6

fossil venture
delicate echo
#

any template / sensor gurus around?

inner mesa
#

not a one

silent barnBOT
#

Don't ask to ask, just ask your question. Then people can answer when they're around.

When you do ask a question, try to provide as much background detail as possible. Ask yourself these questions first so that others don't have to:

  1. What version of the Home Assistant are you running? (remember, last isn't a version)
  2. What exactly are you trying to do that won't work?
  3. Is the problem uniform or erratic?
  4. What's the exact error message?
  5. When did it arise?
  6. What exactly don't you "get"?
  7. Can you share sample code, ideally with line errors where the error occurs?
buoyant pine
#

None

delicate echo
inner mesa
#

my eyes, and that lack of any sort of formatting

#

no way I'm messing with that

delicate echo
#

yea im almost at the end of my rope on this one and going to rebuild a new sensor,.... butttt would wbe the most complex thing i've dabbled in

inner mesa
#

I do wish that Thursday was "donderdag", though

#

it would be more fun

delicate echo
#

using attributes, i've never done - wondering if someone would mind throwing me an example bone and i can run from that - or I may just do individual sensors

#

Yea im going to remove the dutch?

inner mesa
delicate echo
#

Thanks @inner mesa

inner mesa
delicate echo
#

I'll start with those - spent like a week on this and his "copy / paste" is not working

#

OK, thinking my install may have an issue now - i removed all other sensors and copied the first example (updated to my phone for both GPS and NMAP device) and i still dont get the template in my entities

tender prawn
#

any ideas on how to specify a default for int here? map('int')

dreamy sinew
#

map('int', 0)

tender prawn
#

i tried that - it didn't seem to like it

dreamy sinew
tender prawn
#

map(('int'),default=0) it what I just used... let me try yours

dreamy sinew
#

{{ ["foo", "9"]|map('int', 45)|list }}

tender prawn
#

hmmm yours works. Thanks.

#

is int(0) valid for normal int?

mighty ledge
#

that makes the default for int 0 when it fails to parse

tender prawn
#

thanks

mighty ledge
#

3rd arg is base

thorny snow
#

very sorry to ask but i'm not getting around it😫 . From restful i am getting this sensor with this attributes: watt_hours_day: '2021-10-28': 7756 '2021-10-29': 3541 '2021-10-30': 3578 '2021-10-31': 3411 friendly_name: FV production estimate SE

#

how can i extract each day and make a sensr template from it? the number of days will vary and every day they will change

#

i can extract the dictionary with the follow jinja code: {{ state_attr("sensor.fv_production_estimate_se", "watt_hours_day") }}

olive rover
#

Hi. As all stupid questions begin, I am very new to this. I have a wifi plug connected via localtuya (HACS). This plug is configured as a switch which has the power statistics as its attributes (current, voltage, current_consumption). My end-goal is to be able to trigger based on something like "average current in the last 15 minutes > 10".

I have added this configuration to my configuration.yaml: ```sensor:

  • platform: template
    sensors:
    washer_power_sensor:
    value_template: {{states.switch.doubleplug.attributes.current}}
    unit_of_measurement: mA

history_graph:
power:
name: Washer Power Graph
entities:
- sensor.washer_power_sensor```
A restart is rejected with the error invalid key: "OrderedDict([('states.switch.doubleplug.attributes.current', None)])" in "/config/configuration.yaml", line 18, column 0.

I found that the documentation says I should probably be using state_attr() instead, so I tried replacing value_template: with something like {{ state_attr('switch.doubleplug', 'current') }} but this fails too with a different error message while parsing a flow mapping in "/config/configuration.yaml", line 18, column 26 expected ',' or '}', but got '<scalar>' in "/config/configuration.yaml", line 18, column 69

#

I somehow found that doing this bespoke with InfluxDB and python was felt less complicated and like less work but I wanted to try a solution like HomeAssistant as it should scale a bit better and be more manageable... Maybe someone can point out where I'm making a dumb mistake πŸ™‚

mighty ledge
mighty ledge
distant plover
#

How can I get rid of this warning every time I boot HA: "Template variable error: 'None' has no attribute 'last_changed' when rendering '<font size=4>......"? It's part of this markdown card: https://pastebin.com/LCCKwL9U

mighty ledge
#

check for none

#

on states.sensor.xxxxxxx before accessing states.sensor.xxxxxxx.last_changed

#

uh that template is odd too

#

but I guess it works so

#

You can also use expand instead

#

which will get around checking for none

#
{%- set fmat = "%d/%m/%Y %H:%M:%S" %}
<font size=1>
{%- for s in expand('sensor.brukskonto_2222', 'sensor.brukskonto_22223') %}
{{ s.name }} endret: {{ as_local(s.last_changed).strftime(fmat) }} | Oppdatert: {{ as_local(s.last_updated).strftime(fmat) }}
{%- endfor %}
</font>
olive rover
mighty ledge
#
"{{ 'inside' }}"
#

as a beginner, I suggest you just use the multiline indicator

#

otherwise you'll get these errors all the time if you don't know how to properly quote.

distant plover
#

What about {% if states.sensor.brukskonto_2222 == None %} Loading... {% else %} <font size ....... {% endif %}?

mighty ledge
#

sure you can do that

#

but it's easier to just use the tools provided, like expand

distant plover
#

I don't understand expand yet πŸ™‚

mighty ledge
#

there's nothing to understand..

#

it gives you a list of entities that you request

#

states.abc.xyz gives you the state object

#

expand('abc.xyz') gives you the state object in a list

#

however expand doesn't return stuff that doesn't exist

#

which avoids your none check

distant plover
#

Ah, I see. Thanks.

olive rover
#

@mighty ledge It was my quoting πŸ€¦β€β™‚οΈ Thank you

worn moss
#

Hi.
I am trying to fix a special name in a entities-card but I cant get it correct. The entity is sensor.balcony_temperature but I want the name to be the state of a sensor named sensor.balcony_temperature_stats_max_age.

I have got the entity to work but not the name.
What am I doing wrong?

  card:
    type: vertical-stack
    cards:
      - type: entities
        card_mod:
          class: content
        entities:
          - entity:  >
              [[[ return entity.entity_id ]]]
            name: Aktuell temperatur
          - entity:  >
              [[[ 
              return entity.entity_id + "_stats_max";
              ]]]
            name:  >
              [[[ 
                return states['sensor.balcony_temperature_stats_max_age'].state;
              ]]]
This works but I want it more like:
            name:  >
              [[[ 
                return states['entity.entity_id + "_stats_max_age"'].state;
inner mesa
#

this channel is really for Jinja templates, not anything from the frontend (as in the topic)

#

In any case, I wasn't aware that that template style was supported there, but the problem with your "I want it more like this" example is probably that you put quotes around the whole expression in the square brackets

#

entity.entity_id is a variable, and you probably want return states[entity.entity_id + "_stats_max_age"].state;. But again, I'm surprised that that template style works at all there

worn moss
#

I will try it tomorrow when I wake up. I thought it was the correct channel since it was template I worked with 😊

I will try it anyway when I wake up, Thx!

floral skiff
#

Hmm, maybe I should put this here, lol
The following template does not appear to be working.. what is wrong with it? value_template: '{{ now().month != 10 and now().day != 31 }}'
It appears to look to see that month IS in fact 10, and just stops.. Should the 'and' not make it look at both?

dreamy sinew
#

you would want OR if you want "either"

inner mesa
thorny snow
# mighty ledge if you're trying to get today: ``` {{ state_attr("sensor.fv_production_estimate...

thank you, i am also trying to assign a name to the sensor with the date embedded on in, i tried sing the unique_id and change the name with a name template like this: `template:

  • sensor:
    • unique_id: pv_forecast_today
      name: "production for: {{ now().strftime('%Y-%m-%d') }}"
      state: >
      {% set day = now().strftime('%Y-%m-%d') %}
      {{ (states.sensor.pv_forecast_rest_se.attributes['result']['watt_hours_day'][day] + states.sensor.pv_forecast_rest_so.attributes['result']['watt_hours_day'][day]) | float() / 1000 }}
      attributes:
      unit_of_measurement: "kWh"
      device_class: power
      icon_template: "mdi:solar-panel" `
#

but the name does not show up

late island
#

Hey! I found Bear Stone's HA Rep and I am trying to use some of his code but first I need to understand it so I can adapt it to my needs. I am especially in love with his speech engine and all that template stuff. I understood the macro he is using but now I don't understand this template(?)
It is getting a little dark inside the house because of the {{trigger.entity_id.split('_')[2]|replace('precip','rain')|replace('counter','lightning')|replace('carlo','rain') }} {{trigger.entity_id.split('_')[3]|replace('intensity',' ')| replace('carlo','and clouds')}} outside. I will turn on some extra lights in the living room.
It's this automation. https://github.com/CCOSTAN/Home-AssistantConfig/blob/0314ddf9ef28f4ab4305983d73365f852713594f/config/automation/dark_rainy_day.yaml
What needs to be changed or what exactly is being done there?

nocturne chasm
#

Look at the triggers in the automation. He is using the name of the trigger in his notify and substituting words that make sense.

#

Google jinja split

late island
#

So basically in this replace('precip','rain') it replaces precip with rain? Where is precip from? From the trigger I guess but why does it just needs precip and not dark_sky_precip? Also what does split('')[2] or split('')[3] do ? Tried googling jinja split but I am more of an user than a dev so its pretty much gibberish for me which I cant apply to my problem.

late island
#

Anyone?

jagged obsidian
#

Buehler...

inner mesa
#

replace('x', 'y') replaces any instances of the substring 'x' in the input with 'y'

#

{{ "foobar"|replace("bar", "blah") }} -> fooblah

#

That jinja expression looks like it's designed for a very specific set of specifically-named entities. It's not any sort of general-purpose template

late island
#

And @naive plank Isnt active anymore :/

mighty ledge
# late island And <@!330946337057275906> Isnt active anymore :/

There's really not much to that and you can tell what it's doing by looking at the triggers. It simply turns on lights if it's dark outside using a lighting counter, rain sensor, and an awake sensor. That template on the other hand is horrendous. You can build a better template now adays using trigger id's instead of parsing the trigger entity_id's apart.

mighty ledge
inner mesa
#

Looks like you can

#

name template (optional)
Defines a template to get the name of the sensor.

#

I thought the same

mighty ledge
#

not sure I believe that

#

you'd get into a chicken - egg scenario if you have a template without a unique_id

#

Yah, looking at the code I don't see how it would be possible

#

you need either the name or the unique id and a name template wouldn't produce a valid unique_id

#

unless it just defaults to senso.template_x

#

which is possible, I'd have to brush up on the unique_id/naming crap they implemented a while back

inner mesa
#

in a quick test, it initially creates the entity_id with the state of the template at time of creation, but future changes to the template create and modify the friendly_name

mighty ledge
#

oof

#

I'd just use friendly_name template

#

I SAW THAT

inner mesa
#

yeah, it was more of my attempt to get Discord support to fix the persistent unread channel issue

#
template:
- sensor:
  - name: foo_{{ states('input_text.test')}}
    state: "foo"
mighty ledge
#

yah, but in @thorny snow 's case, he's using a date. I'm not sure how they attach to the correct unique_id because it's constantly changing

#

restart with input_text set to blah

inner mesa
#

doing it now. I'm betting that it stays with sensor.foo_bar

#

I also didn't give it a unique_id

mighty ledge
#

is yours a dev box?

inner mesa
#

no, it runs my house

mighty ledge
#

ok, do this

#

don't bother restarting if you haven't already

inner mesa
#

ha! it's now sensor.foo_blah

mighty ledge
#

ah it is?

inner mesa
#

!

mighty ledge
#

well, for shits, go into your entity registry

#

er, maybe config entries

inner mesa
#

see if it got a unique_id?

mighty ledge
#

yah

inner mesa
#

kinda had to

mighty ledge
#

it would be in enitty_registry

#

boy that's a bug

#

and why it shouldn't be a template

#

lol

inner mesa
#

that's weird. foo_ is no where in .storage

mighty ledge
#

search for template

#

you'll have to go 1 by 1

inner mesa
#

nothing in the core.* files

#

must be created dynamically, like discovered entities?

mighty ledge
#

πŸ€·β€β™‚οΈ I would assume it has to be in the entity_registry

#

all my templates are there

inner mesa
#

and yet

mighty ledge
#

template entities*

#

I should just update my dev stream

inner mesa
#

and from configuration -> Entities, more-info

#

This entity ('sensor.foo_blah') does not have a unique ID, therefore its settings cannot be managed from the UI. See the documentation for more detail.

You can overwrite some attributes in the entity customizations section.

mighty ledge
#

Oh shit

#

so it's using the config at creation

inner mesa
#

yeah

#

anyway, doesn't seem that useful this way

mighty ledge
#

nope

#

it's useful if you do this tho

#
template:
- sensor:
  - unique_id: foo
    name: "{{ ... }}"
inner mesa
#

lemme see if that makes it more dynamic

mighty ledge
#

that will plop it into the registry

#

because it now has a unique_id

#

i'd wager that your entity_id would be sensor.template_foo or sensor.foo and the unique_id would be foo (in the registry) and you'd be golden because the startup process would always get the same unique_id

inner mesa
#

it's in there now, but the name still doesn't change dynamically

mighty ledge
#

πŸ€·β€β™‚οΈ

#

friendly_name it is

unreal widget
#

Whops, sorry thought I've been there

inner mesa
#

I see little use for this functionality

#

I guess the displayed name will update, if that matters. but it's usually the state that you care about

mighty ledge
#

@floral shuttle has use cases for it

inner mesa
#

no doubt

mighty ledge
#

I've never seen a need

#

well, maybe I had one for firmware

#

er, no

#

πŸ€·β€β™‚οΈ

floral shuttle
#

hahaha, now that you're asking for it:``` - unique_id: dark_sky_forecast_0
name: >
Today: {{states('sensor.dark_sky_forecast_icon_0d').replace('-',' ')|capitalize}}
state: >
{{- states('sensor.dark_sky_forecast_daytime_high_temperature_0d')}}Β°/
{{- states('sensor.dark_sky_forecast_overnight_low_temperature_0d')}}Β°/
{{- states('sensor.dark_sky_forecast_precip_probability_0d')}}%
picture: >
{{'/local/weather/icons/' ~ states('sensor.dark_sky_forecast_icon_0d') ~ '.png'}}

mighty ledge
#

It's always weather related!

floral shuttle
#

ofc.... or pond: - unique_id: sensor_vijverpompen name: > {% set temp = states('sensor.pond_buiten_sensor_calibrated_temperature')|float(0) %} {% set dark = 'Licht' if is_state('binary_sensor.dark_outside','off') else 'Donker'%} {{dark}} en {{temp}}Β°C - Vijverpompen {{'moeten: ' if is_state('binary_sensor.vijverpompen','on') else 'mogen: '}} availability: > {{states('sensor.pond_buiten_sensor_calibrated_temperature') not in ['unknown','unavailable']}} state: > {{'Aan' if is_state('binary_sensor.vijverpompen','on') else 'Uit'}} icon: > {% if is_state('binary_sensor.vijverpompen','on') %} mdi:engine {% else %} mdi:engine-off-outline {% endif %}

#

also some weather....

thorny snow
#

perfect tank you but anyway also with the friendly name the date does not shows up: `template:

  • sensor:
    • name: pv_forecast_today
      state: >
      {% set day = now().strftime('%Y-%m-%d') %}
      {{ (states.sensor.pv_forecast_rest_se.attributes['result']['watt_hours_day'][day] + states.sensor.pv_forecast_rest_so.attributes['result']['watt_hours_day'][day]) | float() / 1000 }}
      attributes:
      friendly_name: "production for: {{ now().strftime('%Y-%m-%d') }}"
      unit_of_measurement: "kWh"
      device_class: power
      icon_template: "mdi:solar-panel"
      `
silent barnBOT
#

@thorny snow Your message has been deleted as it contains a link or a domain name 'pasteboard_dot_co' that is on the blocked list because of: 'Virus detected!'.
Please re-post by removing/changing the domain name/link. Your original message has been DM'ed to you.

thorny snow
#

on friendly name it show the fixed part but the templete does not show up, maybe i am doing something wront on templating the date

thin bronze
#

And is everybody converting their old style sensors to the new template:?

fossil venture
#

Yes you add multiple - trigger: blocks. I cant speak for everyone but I switched all mine over. There was no real reason to, but it did give me a good understanding of the new method.

thin bronze
#

Cool. Thanks Tom.

buoyant pine
#

Conversely, I haven't converted mine because I can't be bothered to lol

thin bronze
#

So, I'm working to consolidate my Templates, and am running into issues. Do you have only a single - sensor:, - binary_sensor: and - trigger: in the template: section, or one for each of the sensors? Only my first Sensor is showing up (after making the various tag name changes).

#

And things like sensor.date and any other sensor that relies on a - platform: must remain in the sensor: section, right, not under template:. For example:

  - platform: time_date
    display_options:
      - 'time'
      - 'date'
inner mesa
#

additional sensors are nested under the type of sensor you're defining - - sensor:, - binary_sensor:

thin bronze
#

That's what I thought, but when I do the following, only the first is valid after reload.

  - sensor:
      - unique_id: solar_angle_st
        name: 'Solar Angle (ST)'
        unit_of_measurement: 'degrees'
        icon: mdi:angle-acute
        state: "{{ state_attr('sun.sun', 'elevation') }}"
      - unique_id: nextsunrise_st
        name: 'Next Sunrise (ST)'
        icon: mdi:weather-sunset-up
        state: "{{ as_timestamp(states.sun.sun.attributes.next_rising) | timestamp_custom(' %I:%M %p') | replace(' 0', '') }}"
thin bronze
#

Oh, wait, I edited a card that was showing unavailable, entere the exact same sensor, and when saved, it appeared OK. The other one is still unavailable. I'll edit it too. sb.

inner mesa
#

best to check in devtools -> States

thin bronze
#

Oh, SHITE! It's not using my unique_id as the entity_id. I thought that was the purpose of it. It changed the entity_id to a conflagration of the name:.

#

well that sucks...

inner mesa
#

the unique ID is just a identifier to uniquely identify that entity and differentiate it from others

#

I don't think it ever had any relationship to the name

#

when you have one, you can edit the name from the UI

#

but it isn't the name

thin bronze
#

Oh, yeah! Forgot about that... πŸ˜†

#

I'm glad I have you, @inner mesa πŸ‘

sleek storm
#

How can I select an entity_id from a drop down?
specifically a media_player, I already have my input_select entity created but I dont know how to create the script systax.
target:
entity_id: '{{???}}'

buoyant pine
#
entity_id: "{{ states('input_select.whatever') }}"
sleek storm
#

and the input select options need to be "media_player.tv"

#

can that have a pretty name?

buoyant pine
#

or if the input_select just says TV you could do

"media_player.{{ states('input_select.whatever').lower() }}"
sleek storm
#

what does .lower() do?

#

lower case?

buoyant pine
#

makes the result lowercase

sleek storm
#

Thanks again Tediore

buoyant pine
silent barnBOT
#

@ruby pollen Your message has been deleted as it contains a link or a domain name 'pasteboard_dot_co' that is on the blocked list because of: 'Virus detected!'.
Please re-post by removing/changing the domain name/link. Your original message has been DM'ed to you.

hexed badger
#
data:
  message: ESP32 Sensor down
``` Is there any nice way to add the sensor name here?
buoyant pine
#
"{{ trigger.to_state.name }}"
frail granite
#

hello one question i have multiply two sensors with this: value_template: β€œ{{ ( (states('sensor.aaa') | float ) * (states('sensor.bbb') | float) ) | round(2) }}”
why i am getting:
β€œ47.16” €

how to get only 47.16 €

inner mesa
#

Where do you see that?

frail granite
inner mesa
#

In a card?

frail granite
inner mesa
#

You will see that in devtools -> templates because it’s just interpreting the template

frail granite
#

in templates i see this: 47.16

#

there it is working but why i am getting in lovelace this apostrophes

frail granite
#

did found my mistake

#

used " instead of "

#

β€œ

floral shuttle
#

Right, my dst sensor is a day off…

#

In 15 hours 😭 now why does is say Fall change is on 2022-11-01.. hmm

#
          {%- set today = strptime(states('sensor.date'),'%Y-%m-%d').astimezone().replace(hour=ns.previous) %}
          {%- for i in range(365) %}
          {%- set day = (today + timedelta(days=i)).astimezone() %}
          {%- if ns.previous - day.hour == -1 %}
          {%- set ns.spring = today + timedelta(days=i) %}
          {%- elif ns.previous - day.hour == 1 %}
          {%- set ns.fall = today + timedelta(days=i) %}
          {%- endif %}
          {%- set ns.previous = day.hour %}
          {%- endfor %}
          {{([ns.spring,ns.fall]|min).isoformat()}}```
#

while this is correct: dst changed today: > {% set dt = now() + timedelta(days=-1) %} {{now().astimezone().tzinfo != dt.astimezone().tzinfo}} and ``` dst change tomorrow: >
{% set dt = now() + timedelta(days=1) %}
{{now().astimezone().tzinfo != dt.astimezone().tzinfo}}

mighty ledge
#

You didn’t set previous properly

#

What time does dst change in your time zone?

#

For me, it changes at 2am, hence I put in 2

#

@floral shuttle

tribal hollow
#

Hello. Can You help me with this error:
Template warning: 'as_timestamp' got invalid input 'unknown' when rendering template '{% if (((states.sensor.hideki_rain_0|float) - (states.sensor.rain_10_minutes_ago.state|float))*6) > 0 %} {{ as_timestamp(now()|timestamp_custom("%Y-%m-%d %H:%M:%S %Z")) | timestamp_local }} {% else %} {{ as_timestamp(states.sensor.last_rain.state|timestamp_custom("%Y-%m-%d %H:%M:%S %Z")) | timestamp_local }} {% endif %}' but no default was specified. Currently 'as_timestamp' will return 'None', however this template will fail to render in Home Assistant core 2021.12

floral shuttle
mighty ledge
#

Yep

#

set it to 4 to be unless you're feeling luckly like myself. I chose exactly on the time it changes

floral shuttle
#

set it t 3 now, and the future times have changed accordingly πŸ˜‰ will check to be sure on the official time site. thx

mighty ledge
#

Are you available to test something?

#

@floral shuttle

floral shuttle
#

sure

mighty ledge
#

Ok give me a minute.

mighty ledge
#

just need a few more

floral shuttle
#

np just ping me

mighty ledge
#
{%- macro tod(day) %}
{%- set day = strptime(day | string, '%Y-%m-%d').astimezone() %}
{%- set ns = namespace(tz=day.strftime('%z') | int, return=none) %}
{%- for i in range(0, 60*24) %}
  {%- set t = (day + timedelta(minutes=i)).astimezone() %}
  {%- set change = t.strftime('%z') | int %}
  {%- if change - ns.tz and ns.return is none %}
  {%- set ns.return = t %}
  {%- endif %}
{%- endfor %}
{{- ns.return.isoformat() }}
{%- endmacro %}

          {%- set ns = namespace(previous = 0, spring=none, fall=none) %}
          {%- set today = strptime(states('sensor.date'), '%Y-%m-%d').astimezone().replace(hour=ns.previous) %}
          {%- for i in range(365) %}
          {%- set day = (today + timedelta(days=i)).astimezone() %}
          {%- if ns.previous - day.hour == -23 %}
          {%- set ns.spring = tod((today + timedelta(days=i-1)).date()) %}
          {%- elif ns.previous - day.hour == 23 %}
          {%- set ns.fall = tod((today + timedelta(days=i-1)).date()) %}
          {%- endif %}
          {%- set ns.previous = day.hour %}
          {%- endfor %}
          {{ [ns.spring, ns.fall] }}
#

paste the results

floral shuttle
#

[
"2021-10-31T02:00:00+01:00",
"2022-03-27T03:00:00+02:00"
]

mighty ledge
#

is that correct?

#

looks like it

floral shuttle
#

well, today is correct, have to lookup the other date πŸ˜‰

#

except it was 3 am

mighty ledge
#

well, it is the exact minute it changes, which drops it or raises it

floral shuttle
#

any specific reason for this change? is it more robust?

mighty ledge
#

it finds your exact minute

#

that the change happens

#
          {%- set today = strptime(states('sensor.date'), '%Y-%m-%d').astimezone() %}
          {%- set ns = namespace(tz = today.strftime('%z') | int, next=[], tz2=none, return=none) %}
          {%- for i in range(365) %}
          {%- set day = (today + timedelta(days=i)).astimezone() %}
          {%- set tz = day.strftime('%z') | int %}
          {%- if ns.tz - tz != 0 %}
          {%- set day = (today + timedelta(days=i-1)).astimezone() %}
          {%- set ns.tz2 = day.strftime('%z') | int  %}
          {%- set ns.return = none %}
          {%- for i in range(0, 60*24) %}
            {%- set t = (day + timedelta(minutes=i)).astimezone() %}
            {%- set change = t.strftime('%z') | int %}
            {%- if change - ns.tz2 and ns.return is none %}
              {%- set ns.return = t %}
              {%- set ns.next = ns.next + [ns.return.isoformat()] %}
            {%- endif %}
          {%- endfor %}
          {%- endif %}
          {%- set ns.tz = tz %}
          {%- endfor %}
          {{ ns.next }}
#

try that

floral shuttle
#

[
"2021-10-31T02:00:00+01:00",
"2022-03-27T03:00:00+02:00"
]

mighty ledge
#

ok, so same times

floral shuttle
#

yes

mighty ledge
floral shuttle
#

Ok will do when I get back from 007 πŸ˜‰

mighty ledge
floral shuttle
#

secret_squirrel me too, have fun

floral shuttle
# mighty ledge Ok, updated and made post, see if it works for you

thanks for all the work on the dst sensors, experimenting right now to see if things change. A related (probably automation trigger question, so please indulge me here): do we still need the - platform: homeassistant event: start - platform: event event_type: call_service event_data: domain: template service: reload on event: start, if the template reload is also there? I mean, doesnt a restart also always cause a template domain to reload by default?

mighty ledge
#

reload is separate from a start

#

so if you reload your templates without restarting, it will update

floral shuttle
#

yes, but i was asking the other way round: on restart, doesn't it also automatically 'reload' templates. And wouldnt it suffice having that in the trigger?

mighty ledge
#

but what happens when you just want to reload the templates

#

it would set those to none

floral shuttle
#

ok, its of no importance really, was just trying to minimize where possible. for now, I can see the 'Daylight Savings: Next' state template in dev-tools, but can not get it to work as template at all

mighty ledge
#

Not sure what you mean

floral shuttle
#

ok so I just restarted, and now have a functional trigger template sensor. However, upon entering the Phrase template in dev tools, I get ValueError: not enough values to unpack (expected 3, got 1)

mighty ledge
#

yah, check out the thread again, changes were made

floral shuttle
#

ok will do. I do believe I copied it from the community post opening post though.. you did edit that did you?

mighty ledge
#

yep

marble jackal
#

I use the following trigger to check for template reloads:

  - platform: event
    event_type: event_template_reloaded
manic vector
#

Hi everybody, dunno what to do with it:
2021-11-01 15:17:26 WARNING (MainThread) [homeassistant.helpers.template] Template warning: 'strptime' got invalid input '2021-11-02T11:45:25+00:00' when rendering template '{{ as_timestamp(strptime(state_attr("sun.sun", "next_noon"), "")) | timestamp_custom("%H:%M") }}' but no default was specified. Currently 'strptime' will return '2021-11-02T11:45:25+00:00', however this template will fail to render in Home Assistant core 2021.12

mighty ledge
#

where did you get that abomination?

#

strptime is doing nothing

#

just remove it

manic vector
#

is this strftime ?

mighty ledge
manic vector
#

Could be replaced by : {{ as_timestamp(states.sun.sun.attributes.next_noon) | timestamp_custom('%H:%M')}} ???

manic vector
#

Yup , thant worked. Thanks Petro πŸ˜‰

mighty ledge
#

np

smoky girder
#

So, i'm tryng to send a sensor's temperature using rest command, but it always sent a [Object object] string,
Tried those, several ways of write the templating, but no luck

The sensor name is 'sensor_botao_temperature'

#

Could any one give some light? Tries google it in the foruns and like by problems

#

This is the right place right? Because my doubt is over the templating aspect of the problem

mighty ledge
willow flower
#

Hopefully someone clever can help - I'm trying my first template.... the plan: on a button press to increase brightness value by 15, but using an if/else condition so that if the brightness value would exceed 255 it would just be 255

https://paste.debian.net/1217685

That's my best attempt so far, although clearly still haven't got it working!

charred dagger
#

{{ min(state_attr('light.light_example', 'brightness') + 10, 255) }}

#

And it's just data. data_template is deprecated.

willow flower
charred dagger
#

Yes. It will always pick the lowest of the two values, which in this case means it maxes out at 255.

willow flower
#

and can presumably switch min to max and set a low point for reducing value too?

charred dagger
#

Indeed. Or max(lowest, min(highest, value)) to clamp value between lowest and highest.

willow flower
#

sounds exactly what I've been trying to badly create!

#

whats the name of teh function so I can read further in docs?

charred dagger
willow flower
charred dagger
willow flower
#

Think it helps when you know what you're looking for!

#

certainly all seems to work when in templating, but when I throw it together in an automation I get error of a missing colon...

  • id: '1016'
    alias: b1 rn 6
    description: 'click b1 rn up'
    trigger:
    • platform: state
      entity_id: binary_sensor.b1_rn_6
      to: "on"
      action:
    • service: light.turn_on
      entity_id: light.bed1_headboard_3
      data_template:
      brightness: '{{ min(state_attr('light.bed1_headboard_3', 'brightness') + 15, 255) }}'
      mode: single
inner mesa
#

you need to mix your quotes

#

and use data: instead of data_template:

topaz galleon
#

I wrote a template sensor to change my gas meter's unit of measurement. Whenever I restart HA I get 0 readings which makes it look like I have had my gas meter's entire history of usage when it restarts.

#

How do I prevent it from considering missing data as zeros?

#

My template state is "{{ (states('sensor.gas_meter') | float * 0.02831684659) | round(3) }}"

#

`template:

  • sensor:
    • name: Gas Meter Metric
      unique_id: gas_meter_metric
      device_class: gas
      unit_of_measurement: "mΒ³"
      state: "{{ (states('sensor.gas_meter') | float * 0.02831684659) | round(3) }}"
      state_class: total_increasing`
topaz galleon
#

Is there a more appropriate place for me to be asking this?

buoyant pine
#

Nope, just gotta be patient

dreamy sinew
#

probably need an availability template

fossil venture
topaz galleon
topaz galleon
#

Cool thanks. I will read that more carefully tomorrow. Obviously I missed the common parts earlier. D'oh.

topaz galleon
#

Thanks!

teal cove
#

Is there a quicker way of doing this? A filter/function?

{% set temp = states('sensor.temperature')|float %}
{% if temp % 1 == 0 -%}
  {{ temp|round }}
{%- else -%}
  {{ temp }}
{%- endif %}

(for sending messages/tts)

mighty ledge
mighty ledge
#

{{ temp|round if not temp % 1 else temp }}

teal cove
#

thanks @mighty ledge , thats pretty close to the imaginary
temp|round(0, if_int) that I had in my head 😁

topaz galleon
#

Yesterday I was asking about a templatized sensor and dropouts being equated to 0. Based on the answers I found here I came up with the following which appears to work.
`template:

  • sensor:
    • name: Gas Meter Metric
      unique_id: gas_meter_metric
      device_class: gas
      state_class: total_increasing
      unit_of_measurement: "mΒ³"
      state: >
      {% if states('sensor.gas_meter') not in ['unavailable', 'unknown', 'none', none] %}
      {{ (float(states('sensor.gas_meter')) * 0.02831684659) | round(3) }}
      {% endif %}
      availability: "{{ states('sensor.gas_meter') not in ['unavailable', 'unknown', 'none', none] }}"`
      I suspect I don't need to check twice for undefined state. Also all the availability examples I could find used 'none' but when using the template designer none didn't equate to 'none'.
mighty ledge
#

none does not equate to 'none'

mighty ledge
#

You'll never get 'none' or none from states() though

#

so all you need for the availability template is

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

and you can change your state to

topaz galleon
#

Is the if statement in the state extraneous?

mighty ledge
#
{{ (states('sensor.gas_meter') | float(0) * 0.02831684659) | round(3) }}
#

it's just not needed

topaz galleon
#

Cool

mighty ledge
#

you can also get rid of availability if you leave the if statement

#

because '' is unavailable

topaz galleon
#

Great, that's what I expected. The availability version is cleaner.

mighty ledge
#

but, i like being explicit

topaz galleon
#

I guess I need to answer what will @topaz galleon have an easier time reading next time.

mighty ledge
#

yep

#

no matter what, you won't like it if it's been a year

topaz galleon
#

Lol. Every once in a while I find old code that I actually like.

#

Not often though

#

Thank you @mighty ledge

mighty ledge
#

np

floral shuttle
mighty ledge
#

is that with the latest?

mellow geode
#

Could anyone spot a mistake, please ? {{ states('counter.sensor_house_power_meter_kwh')int + states('sensor.house_power_meter_kwh')|int }} Me making templates never goes well.

dreamy sinew
#

missing a | before the first int

mellow geode
#

πŸ˜΅β€πŸ’« Jesus

#

Thanks

mellow geode
dreamy sinew
#

ints don't have decimal places

inner mesa
#

You forced it to an int

dreamy sinew
#

if you want the decimals you should use float

mellow geode
dusty hawk
#

I'm calling the zwave_js.setvalue with this script snippit as the value:. zwave_js appears to be interpreting the results of this as a string instead of a boolean based on the error message returned:
value: >-
{% set en = "{{ entity }}" %}
{% if is_state(en, 'on' ) %}
false
{% elif is_state(en, 'off') %}
true
{% else %}
false
{% endif %}

Am I missing something? This resolves OK in the dev tools > template

fossil venture
#

For a boolean use {{true}} or {{false}}

inner mesa
#

also, this is curious: {% set en = "{{ entity }}" %}

#

if it's a variable, use the variable

dusty hawk
#

entity is passed in like this: - service: script.zwave_switches_toggle data: entity: switch.mbath_fan_shower

inner mesa
#

just use entity

fossil venture
#

Also this does the same thing as your whole template {{ is_state(entity, 'off' ) }}

inner mesa
#

you're turning it into a string, then back into a variable

dusty hawk
#

hmmm, actually, I'm also using it in a macro on my floorplan {% macro fan_button(entity, x, y, size, border, background) -%} {# {% if not no_other %} #} - entity: {{entity}} type: custom:button-card style: { left: {{x}}%, top: {{y}}% } show_name: false show_label: false show_entity_picture: true tap_action: {# action: toggle #} action: call-service service: script.zwave_switches_toggle service_data: entity: switch.living_room_fan ...

#

where entity is a variable when im not testing it with a constant

#

I like the simplification tom l. I'll play with that some.

#

Perfect. Thank you both for the help.

stuck remnant
#

hi, tryin to make a sensor via template from a mqtt aircon integration

#

but the lines from HA seem to be different from the ones specified in the docu

#

can someone take a look and tell me how they'd go about making a sensor out of one of these values?

#

f_humidity for instance, tryin to set it up as a sensor but it doesn't even show up in HA (im thinkin cos it's read only)

floral shuttle
mighty ledge
floral shuttle
bright plaza
#

Can anyone help with some templating oddity?

#

I've condensed my problem down to this example: {{ (1 | float /1000) + 1 | round(2) }}

#

with the +1 in there, the round appears not to work. If I remove the + 1 then it works properly. What am I missing?

inner mesa
#

you're rounding the value "1" to 2 decimal places

bright plaza
#

hmm

#

Don't we get 0.001 + 1 then round the result of that?

inner mesa
#

{{ ((1 /1000) + 1) | round(2) }}

#

no

#

| has tight binding

#

order of operations

bright plaza
#

ah ok I think I see where I went wrong in my original code then

#

you really have to bracket everything

#

Thanks for the pointer πŸ˜„

#

I figured it would take everything before the pipe and send that into the round function but it's trying to round the 1 and then adding the result of that to the original unrounded result giving me too many decimal places

#

I spent an hour or so trying to figure this out, playing with the developer tools template etc. Doh

shy badge
#

Can I please have some help with this error?

#

Template warning: 'float' got invalid input 'unknown' when rendering template '{{ states('sensor.washing_machine_energy_power')|float > 10 }}' but no default was specified. Currently 'float' will return '0', however this template will fail to render in Home Assistant core 2022.1

inner mesa
#

your sensor reported "unknown" at some point rather than a number

shy badge
#

This is after a restarted HA

inner mesa
#

you should fix that by adding a default to |float like |float(0.0), or revisit the sensor

#

there's a section in the breaking changes of the last release on this

shy badge
#

Ok RobC, thanks I'll have a play

foggy ore
#

can anyone help with converting value_template: "{{ state_attr('sensor.MainArylic', 'Album') }}" from hex to ascii? current JSON response is in hex.

formal ember
#

I've got a template that selects the next lighting effect on a WLED Light, it achieves the desired result in the template area of developer tools. I would like to know how I can use this triggerd by a button press on an Ikea remote...

  {% set effect = state_attr('light.wled', 'effect') if state_attr('light.wled', 'effect') else effect_list[0]%}
  {{ effect_list[effect_list.index(effect)+1] if effect_list.index(effect) < effect_list|count-1 else effect_list[0]}}
slow knot
#

Hi there! I've created a template, that sums all my sensor.energy (shelly EM x 4); I can't get it in the Energy. Also, I've created tariffs and utility meter, but I can't use it as a cost, it does not show up, except for the "current price" option; any ideas?

#

maybe I should post this in Energy channel

foggy ore
marble jackal
marble jackal
#

I'm getting a warning about this template:

{% set reject_entities = [ 'sensor.tv_lamp_power', 'sensor.samsung_soundbar_power_meter', 'sensor.measured_power', 'sensor.unknown_power', 'sensor.zolder_bol_power' ] %} 
{{ 
  states.sensor | selectattr('entity_id', 'search', '_power') 
                | rejectattr('entity_id', 'search', 'estimated_power') 
                | rejectattr('entity_id', 'in', reject_entities) 
                | selectattr('attributes.state_class', 'eq', 'measurement') 
                | map(attribute='state') 
                | map('int') 
                | sum 
}}```
The warning is: `Template warning: 'int' got invalid input 'unavailable' when rendering template`
#

But I don't use int except to map the values.. Where does this warning come from?

charred dagger
#

That's it. It applies int to each of the items in your list. One of them is unavailable.

#

Another rejectattr('state', 'eq', 'unavailable') might do it.

marble jackal
#

Ah okay, would map('int(0)') also work?

#

I could test that of course, and no, it doesn't πŸ™‚

subtle bronze
#

Does this one make sense as a condition for an automation to run it only when it has not been ran for the last two minutes?
{{ now() > state_attr('automation.oue_varav','last_triggered') + timedelta(minutes=2) }}

mighty ledge
silent barnBOT
gusty nimbus
#

maybe someone could find my template problem? πŸ™‚ its not alot code i think since month 10 i get this error as a warning that things will change
anyone has a fix? πŸ™‚ tx

marble jackal
#

This probably happens after a reboot. The entities used in the template are not ready yet, so the | float part is used on something unknown. To get the result you had without the warnings you can use | float(0) or | float(default=0)

gusty nimbus
#

hm ok tx

floral aurora
#

Hi, I want to use a OR condition in the value_template, but cannot find how. I tried: {% if (states('sensor.pv_power') == 'unknown' OR states('sensor.pv_power') == 'unavailable') %}

marble jackal
#

or should work. You can also use {% if states('sensor.pv_power') in ['unknown', 'unavailable'] %} or {% if is_state('sensor.pv_power', 'unavailalbe') or is_state('sensor.pv_power', 'unknown') %}

floral aurora
thorny snow
#

Is there a way to generate a template to list zwave devices with specific manufacturer / model? I know this used to be possible with the inbuilt zwave, but not sure if it’s still possible with zwave-js. Basically I want something like {{ states.light | selectattr(β€˜model’, β€˜eq’, β€˜LZW31-SN’) }}, but I have no idea If it’s even possible to access device data in a template.

inner mesa
#

I believe that device attributes were added a few months ago for this

#

See the templating docs

thorny snow
#

Why is it that I receive a config error when I set state_class: "measurement" to a template sensor? I want to get longterm statistics from this template sensor as it's a OCR reading of my gas usage but HA will not accept a state class.

inner mesa
#

~share your sensor definition

silent barnBOT
inner mesa
#

and what is the actual error?

thorny snow
inner mesa
#

you can add it as an attribute, though

thorny snow
#

See above, it triggers an error when added. Maybe the documentation lacks details.

inner mesa
#

it's not allow, as per the docs

#

but you can add it as an attribute

#

or, see above πŸ™‚

thorny snow
#

I guess I won't. Thank you. I don't get it.

mighty ledge
pastel moon
#

Hi guys. I have made a little sensor that refuse to pass the ha core check, and can't seem to find why... It works fine in dev_tools... Any idea?

                 {% if is_state('input_boolean.wakeup', 'on') %}               
                    {% if now().isoweekday() in [6,7] %}                               
                      {{ today_at(states('sensor.morning')) + timedelta( hours = 2 ) }}
                    {% else %}                                                                       
                      {{ states('sensor.morning') - timedelta( minutes = 15 ) }}       
                    {% endif %}                                                        
                  {% else %}                                                           
                    {{ states('sensor.morning') }}                                     
                  {% endif %}
#

Error I get is expected <block end>, but found '<block sequence start>', but cannot see I have any open brackets or if's...

pastel moon
#

found it. indentation issue, misplaced by one space

mighty ledge
#
{% set morning = states('sensor.morning') | today_at %}
{% if is_state('input_boolean.wakeup', 'on') and morning %}
  {% set delta = timedelta(hours=2) if now().isoweekday() in [6,7] else timedelta(minutes=15) %}
  {{ morning + delta }}
{% else %}
  {{ morning }}
{% endif %}
#

basically, your template will fail on weekdays because you're missing today_at on the morning in that if statement

#

that's why it's always best to use variables and perform an action once

#

another way to write it

#
{% set morning = states('sensor.morning') | today_at %}
{% set delta = 120 if now().isoweekday() in [6,7] else 15 %}
{% if is_state('input_boolean.wakeup', 'on') and morning %}
  {{ morning + timedelta(minutes=delta) }}
{% else %}
  {{ morning }}
{% endif %}
silent barnBOT
quartz dust
#

How does one format this properly? It is malformed:

service: script.tts_sonos_tts_engine
data_template:
  data: |-
    {%- set room = states("sensor.last_alexa")|replace('media_player.','') -%}
    {%- if room == "bedroom_echo_show" -%}
      speaker: media_player.family_room
      volume: 0.4
      message: Good night Bedroom
    {%- elif room == "theater_echo_show" -%}
      speaker: media_player.theater
      volume: 0.4
      message: Good night Theater
    {%- endif -%}```
quartz dust
buoyant pine
#

you can't template blocks of key-value pairs like that; you have the template the values of each key

#

you should also get rid of data:, and data_template: can just be data:

#
service: script.tts_sonos_tts_engine
data:
  speaker: "media_player.{{ 'family_room' if is_state('sensor.last_alexa', 'media_player.bedroom_echo_show') else 'theater' }}"
  volume: 0.4
  message: "Good night {{ 'Bedroom' if is_state('sensor.last_alexa', 'media_player.bedroom_echo_show') else 'Theater' }}"
stone lintel
#

I have this error in my logs Template warning: 'float' got invalid input 'None' when rendering template '# The heating is set to {{ state_attr('climate.lounge', 'temperature')|float | round(0, default=none) }} degrees.' but no default was specified. Currently 'float' will return '0', however this template will fail to render in Home Assistant core 2022.1 I thought I had read that to resolve it I had to add (0, default=none) but apparently not, does anyone have any tips please?

buoyant pine
#

| float(0)

stone lintel
#

Great thank you!

quartz dust
thorny snow
#

hi guys im hoping someone can help me ... i've been playing with this for some time now and i cant manage to figure it out. i have an mqtt cover which works OK. i want to extract the state (open/close) from that cover into a template binary_sensor so i could show the open/close state seperately. i've been trying different variations of the state parameter but cant seem to get it right, its only showing closed. this is my setup:

cover:

  • platform: mqtt
    name: "Garage 2 door"
    ... etc ...

template:

  • binary_sensor:
    • name: "Garage 2 state"
      device_class: garage_door
      state: "{{ states('cover.garage_2_door') }}"
late island
mighty ledge
thorny snow
#

ohh i see, thanks. works now πŸ˜‰

icy thistle
#

I want to convert a float with values like 0.34999999999999 into an integer like 35, I've typed in this but it doesn't seem to work, why?
"{{ state_attr('media_player.bedroom_speaker', 'volume_level') | round(2) | int }}"

inner mesa
#

The round(2) is unnecessary if you’re just going to truncate with int

#

That will make it 0

icy thistle
#

but wouldn't it convert it to a very long integer if I don't round it?

#

i need it to be between 0 and 100

inner mesa
#

I’m talking about int

#

Which truncates it to 0

#

Then you need to multiply by 100

icy thistle
#

oh, i assumed it would convert 0.35 to 35

#

makes sense

#

thanks

inner mesa
#

you'll still need to round to avoid an epsilon error: {{ 0.58|multiply(100)|round }}

oblique vale
#

Good evening. I was looking at the light group (https://www.home-assistant.io/integrations/light.group/) and the entities property says it takes string or list. So I was wondering if I could do this:

- platform: group
  name: "All Lights"
  entities: >
    {% set domain = 'light' %}
    {{ states[domain] | map(attribute='entity_id') | list }}
#

I'm fairly new to HA, and I'm trying to understand the concept here. I would be grateful for a point in the right direction

inner mesa
#

that's the right idea, but you may need this:

#

actually, looking at the docs, I don't think you can use a template ther

oblique vale
#

_< damn

#

I'm just trying to create an all-lights light group. But been struggling for quite a while now as actually want to understand what I'm doing and not just grab any script.

inner mesa
#

that's a good attitude πŸ™‚

oblique vale
#

indeed

inner mesa
#

you can use group.set, as mentioned further down in that thread, to get a group that will allow you to turn all lights on or off

#

it might even let you add data: to it to set brightness, etc., as I've seen some folks do, even though I don't think that was intended to work

#

if you have a group of just lights, you can provide light-based attributes when turning the group on

oblique vale
#

I see, but they differ from actual light groups, right ?

inner mesa
#

in name only

#

some cards or service calls may restrict entities to light.* entities, which would be problematic

#

I ran a test a while ago making groups of only lights and mixing lights and switches and was able to have them behave just like light.groups

#

you'll just get an error in the log for any entity that's not a light if you specify light attributes, but it still works for the lights in there

oblique vale
#

okay, I'll try that.

#

thanks πŸ™‚

inner mesa
#

dynamically creating a group at startup is kind of a hack, and I do wish that groups and light.groups took templates (in addition to allowing users to create both in the UI)

oblique vale
#

true

dusty hawk
#

Is this the correct way to provide a default value in case the state is, say, unavailable which will break the float filter? states('sensor.bedroom_hallway_4in1_humidity') | float | default(0.0)

inner mesa
#

states('sensor.bedroom_hallway_4in1_humidity') | float(0.0)

#

you can test this in devtools -> Templates

dusty hawk
#

Thanks. I appreciate it.

sinful ridge
#

I'm sure I'm missing something obvious, but I can't get a value to display as an integer. I'm testing it in the templating tool and adding "int" or round(0) doesn't seem to change anything.
value_template: "{{ states('sensor.heatpump_kw') | float * 1000 | int }}"
always results in a value like 216.0

mighty ledge
#

your int is only applied to the 1000

sinful ridge
#

Ah, that I certainly didn't realize πŸ™‚

#

So I need to apply the int to the whole output somehow

mighty ledge
#

pemdas*

quartz dust
#

Have tried to reformat this several ways with no joy to get rid of the HA warning "The entity definition format under template: differs from the platform configuration format." for this template sensor. Any advices?

sensors:
  last_alexa:
    value_template: >
      {{ expand(states.group.echos) | selectattr('attributes.last_called','eq',True) | map(attribute='entity_id') | first }}```
sinful ridge
#

Petro, I see I need to group the float * 1000 together so the int applies to it all. WHat I can't figure out is how. Surrounding it with {{ }} doesn't work in the value template.

mighty ledge
#

It's math, filters apply to the item to the left of the |

#

the item to the int's left is 1000

#

so using parenthesis, how do you apply it to everything?

mighty ledge
#

use the new format or the old format, not both.

sinful ridge
mighty ledge
#

order of operations

#

| float needs to be next to states()... So where should your parenthesis go?

sinful ridge
#

HA!

#

Thank you.

mighty ledge
#

np

sinful ridge
#

And I appreciate you walking me through it and not just giving it to me. I understand the failure in my logic

sinful ridge
#

Is there a template filter that would basically work like a low-pass filter? I know I can use the filter platform to do this at the cost of creating additional sensors for that purpose. I was hoping to take care of it along with the above calculation.

atomic python
#

hey guys, any regex gurus around here? Looking to extract the first number 15 from a sensor with this value: $OK 6 32 15 15^17

buoyant pine
#

assuming there are always three values separated by spaces before the value you want, .split(' ')[3] will work:

{% set val = '$OK 6 32 15 15^17'.split(' ')[3] %}
{{ val }}

that returns the first 15

atomic python
#

nice and and yes the value always contains the format above

buoyant pine
#

cool, you should be good to go then

atomic python
#

{% set val = sensor.gc_return.split(' ')[3] %} is correct for passing in sensor?

buoyant pine
#
{% set val = states('sensor.gc_return').split(' ')[3] %}
atomic python
#

cool will confirm it in the dev tools

#

thx

late island
late island
#

I see this error message: Error: dictionary update sequence element #0 has length 1; 2 is required when I look at Script Debug in HomeAssistant at this Step Config: https://pastebin.com/b6e22Uht

young jacinth
#

i got an error in my automation here and iam 99% sure the error is within the templates....
can somebody take a look?
https://pastebin.com/WSW16Gsk

mighty ledge
inner mesa
nocturne chasm
#

@young jacinth Along with Tediore’s comment, I am guessing this is an issue {% if set_direction == 'close' and == 'off' %}

buoyant pine
#

Indeed

mighty ledge
inner mesa
#

that's the else for the else

#

and it outputs something

mighty ledge
#

It looked like it was paired with the main if and had no else

young jacinth
#

Invalid config for [automation]: invalid template (TemplateSyntaxError: unexpected '==') for dictionary value @ data['variables']['set_position']. Got None. (See ?, line ?).

this is what iam getting with this

https://pastebin.com/nR6T6VxB

#

do i have to use brackets in the variables definition? like:
night: "{{ is_state('binary_sensor.night','on') }}"

inner mesa
#

yes

#

they either need to be strings/values or templates that return a string/value

nocturne chasm
#

Which will change the rest of your template to true/false no?

#

Which is why you always get 100

#

Plug it into the template editor.

young jacinth
#

i did

#

slightly different naming but should return the same results

nocturne chasm
#

You keep changing it. And pictures of text 🀒

young jacinth
nocturne chasm
#

And it is unclear if you are getting an error or the automation isn’t performing as expected

young jacinth
#

the automation is available, gives an error, and does not work the way i expect

nocturne chasm
#

I am not sure about the error but it looks like it is rendering the template properly

young jacinth
#

iam going crazy

nocturne chasm
#

With the error?

young jacinth
#

both. the error and the automation always outputting 100

#

altough the template editor showing the correct results

#

solution

#

i pasted the template editor code into the variable set_position

#

lol

mighty ledge
#

you can't output multiple values in a template

#

you should only be outputting the position for set_position

#

Also, there's no reason to do what you're doing. Just use true/false

#
{% set is_night = is_states('binary_sensor.night', 'on') %}
{% set is_occu = is_states('binary_sensor.eg_occu', 'on') %}
{% set door_open = is_states('binary_sensor.terassentuer', 'on') %}
{% if is_night and not door_open %}
  {% if is_occu %}
    50
  {% else %}
    0
{% else #}
  100
{% endif %}
young jacinth
#

thanks alot that makes it much easier

late island
mighty ledge
#

target needs the entity_id feild

late island
#

That kinda fixed it. Kinda.

#

Fixed it!!!!

modern creek
#

Hi,

#

trying to get a name of a device by {{device_attr('1445ec2c5205bea4e33f286c7dac4bb9','name')}}

#

and it's resulting in an old name (I changed it already from the devices panel)

#

how to force HA to reload new name?

lofty arrow
#

Hello guys:) I found a script to turn off all lights except some excluded. It's working fine but if they're already off it throws an error because of the empty entity_id. Does anyone know a workaround for this?

#

btw. it uses homeassistant.turn_off if that matters

lofty arrow
#

Nevermind. Solved it by using variables and checking my condition (excluded entities list is not empty) before calling homeassistant.turn_on
Even seems cleaner^^

distant plover
#

I want to make sure my grid consumption template sensor becomes unavailable if one of the individual sensors is unavailable: https://pastebin.com/ytFjC70N . Should I add something like this? availability_template: "{{ states('sensor.bad_taklampe_kwh') not in [ 'Unavailable', 'None', 'Unknown' ] and states('sensor.bad_termostat_gulv_kwh') not in [ 'Unavailable', 'None', 'Unknown' ] and states('sensor.entre_taklampe_kwh') not in [ 'Unavailable', 'None', 'Unknown' ] etc...... }}"

dreamy sinew
#

or if you actually want to do a template,

{{ expand(sensors)|selectattr('state', 'in', ['unavailable', 'unknown'])|list|length == 0 }}
#

or put them all in a group and you can skip the list part

tidal heart
#

Regular expression question. Trying to make caldav exclude events with a specific word. I have no clue how to use regular expression so I googled around and found this but it does not seem to do the trick ^(?!.*ignoredword).*

dreamy sinew
#

regex101 is a good resource for testing regex. you put the stuff want to test against in the bottom and your query in the top

#

it has descriptions of the things to use

tidal heart
#

Yeah that's where I'm testing right now and it seems to work there but not in caldav. Might be that caldav does not work with excludes

#

search: "^(?!.*ignoredword).*"

dreamy sinew
quartz dust
#

my log throws this on boot but the sensor works. is there any way to re-write this to eliminate the log error?

'''
Template variable warning: No first item, sequence was empty. when rendering '{{ expand(states.group.echos) | selectattr('attributes.last_called','eq',True) | map(attribute='entity_id') | first }}'
'''

'''
template:

  • sensor:
    • name: last_alexa
      state: "{{ expand(states.group.echos) | selectattr('attributes.last_called','eq',True) | map(attribute='entity_id') | first }}"
      '''
dreamy sinew
#

selectattr returned an empty set

marble jackal
#

Maybe the template sensor was loaded before the Alexa integration did the update of the entities after reboot
You can do something like this (or something smarter probably, but this should work):

{% set echo_last_called =  expand(states.group.echos) | selectattr('attributes.last_called','eq',True) | map(attribute='entity_id') %}
{% if echo_last_called | lenght > 0 %}
  {{ echo_last_called | first }}
{% else %}
  None
{% endif %}
mighty ledge
quartz dust
dreamy sinew
#

Hi folks, came across a bit of a logic puzzle today, with a counter and a boolean switch. The counter moves based on user interaction via other automations. When the boolean switch turns off, I’d like a sensor to equal the highest integer the counter has been at since the boolean was turned on. Any ideas how to grab that?

inner mesa
#

I would use a separate input_number and an automation that triggers whenever the counter changes state, and has a condition that the input_boolean is on. When it triggers, set the input_number helper to the max of the existing value and the new one. Another automation would reset the input_number when the input_boolean turns on

dreamy sinew
#

Or 2 counters 😜

#

Nah, nvm

dreamy sinew
# inner mesa I would use a separate `input_number` and an automation that triggers whenever t...

I think I follow, thanks!

I guess I’d just need an automation in there to change the intermediary input number as the source one changes.

And you can do templating in conditions, right? So I can set a condition that requires my intermediary input number to be less than the source one. As the counter moves up and down, the only changes that the intermediary picks up are the peaks. And then when boolean goes off, move that intermediary to another input number which only records those per-session maximums.

inner mesa
#

that seems overly complicated

#

something like this:

neon barn
#

I added an entity tracking the energy cost from my energy company. in the unit_of_measurement field, should I put the value as {currency}/kWh' or just $/kWh?

dreamy sinew
dreamy sinew
inner mesa
#

it occurs to me that the first one really should be this:

#
- alias: initialize
  trigger:
    platform: state
    entity_id: input_boolean.blah
    to: 'on'
  action:
    - service: input_number.set_value
      data:
        entity_id: input_number.max
        value: "{{ states('counter.xxx')|float }}"
pastel moon
quartz dust
#

Still learning syntax πŸ™‚ Why does peck evaluate properly to the integer 4 and peckc evaluates to 'unknown'?

{{ peck }}

{% set pecka = 'theater_symfonisk' %}
{{ pecka }}
{% set peckb = 'media_player.' + pecka + '.attributes.media_duration' %}
{{ peckb }}
{% set peckc = states('peckb') %}
{{ peckc }}```
fossil venture
#

Because you are doing states('media_player.theater_symfonisk.attributes.media_duration') Which is just not right. You can do states.media_player.theater_symfonisk.attributes.media_duration or better yet use state_attr('<entity_id>', '<attribute>')

quartz dust
quartz dust
fossil venture
#

Don't quote your variable {% set peckc = state_attr(peckb, 'media_duration') %}

#

Otherwise state_att() will use the literal string 'peckb' as the entity_id instead of it's contents.

quartz dust
bronze tide
#

I found the following warning in my HA log file and wonder how to solve the problem. I am pretty sure that I saw a suggestion while doing some RTFM quite a while ago, but I cannot find it anymore. Nice that HA lets one know when the template is going to fail, but I would have appreciated a hint towards solving the problem rather.

Here is the warning from the log file:

Template warning: 'int' got invalid input 'unavailable' when rendering template '{{ states('sensor.xiaomi_l2_bathroom_battery') | int < 20 }}' but no default was specified. Currently 'int' will return '0', however this template will fail to render in Home Assistant core 2022.1

I created a few binary sensors using the template this way:

- binary_sensor:
  - platform: template
    sensors:
      xiaomi_low_battery_l2_bathroom:
        friendly_name: Xiaomi low battery L2 bathroom
        value_template: >-
          {{ states('sensor.xiaomi_l2_bathroom_battery') | int < 20 }}
buoyant pine
#

change it to | int(0)

rotund gust
#

I am attempting my first regex (template calculation) to calculate my current stock totals($). I am playing in regex101 and I think I am getting worse not better. haha Any tips on best places to read up and learn more would be appreciated.

    - name: 'PTN Stock Total'
      unit_of_measurement: "$"
      state: >
        {% if is_number(states('sensor.yahoofinance_ptn')) and is_number(states('input_text.ptn_shares')) %}
          {{ (states('sensor.yahoofinance_ptn') * states('input_text.ptn_shares')) }}
        {% else %}
          None
        {% endif %}```
inner mesa
#

I don’t see any regex there

#

In any case, you need to convert the states to numbers before doing math. Add |float to each states() call that needs a number

spiral imp
#

I have this template: https://paste.debian.net/1218990/
It takes three attributes of a single sensor, determines the one occurring next and sets a state and attribute with the numbers of days (state) and due date (attribute). You will see in the template that each attribute in the original sensor is defined as chore[#].attribute. Each chore has an id: attribute as well. Is there a way to set as an attribute in the new sensor, the id: of the chore that is occurring next? I hope that makes sense

rotund gust
inner mesa
#

you didn't add them in the right place

#

{{ (states('sensor.yahoofinance_ptn') * states('input_text.ptn_shares')) }}

#

that's multiplying two strings together

#

and you don't put filters inside the function call

#

{{ states('sensor.yahoofinance_ptn')|float(0.0) * states('input_text.ptn_shares')|float(0.0) }}

#

I added defaults to handle the case where the states aren't numeric values, which is one way to accommodate that case

rotund gust
rotund gust
spiral imp
#

From my earlier specific example, what I need to do is compare a time sub-attribute from three different attributes (same sensor) and return a different sub-attribute for the earliest of the three time sub-attributes

versed maple
#

So I have been searching all day trying to find a way to get the modulus of two helpers. One(numerator) Is a counter for the number of minutes a workout is going and the other(denominator) is a specified number for modulus. I am using this to control how often Alexa Media will announce the time. Currently I use two scripts (one calls the other until the workout helper button is turned off and each count a minute and do updates to the counter...alexa...etc. I have tried several ways of templates which seem to change based on each page for format and none work. Several (even though both of these helpers are never 0 have cause Division by Zero errors). They never call alexa though. This is my most recent...I removed "states(" from it before this. This is driving me nuts. I even tried to avoid templates which I am not liking since as stated their formatting seems flexible enough to cause variable examples) using variables in my script but they did me no good either...plus..they were of course templates as well.
"{{ (('counter.workoutcount') | int) % (('input_number.workouttimettsmins') | int)==0 }}"

I do realize I may be doing this all wrong but if there is a comprehensive documentation for templates (not a 2 page with few examples) that can explain all of the varying types of them...please point me to it

inner mesa
#

this wasn't corrrect:

#

This is my most recent...I removed "states(" from it before this.

versed maple
#

πŸ™‚ Only did it cause states wasnt working either. I had states over each () as well as another with one states( over the whole list. I have been programming for over 20 years....I dont give up to much....but I just aint getting it

#

worst part too is I love the debugger but I couldnt find any way to get it to tell me the states of the template variables...so I am working in the dark

#

Here are the three different ways I templated in Developers Console and none of them work in the script:
{{ (states('counter.workoutcount') | int) % (states('input_number.workouttimeannouncemins') | int) }}
{{ workoutTime%workouttimeannouncemins }}
{% if (states('counter.workoutcount') | int) % (states('input_number.workouttimeannouncemins') | int)==0 -%}
Its Zero!!
{%- endif %}

#

I also used another example that just didnt seem right to me but it worked in the developers console too...something like {{ "1" if (states('counter.workoutcount') | int) % (states('input_number.workouttimeannouncemins') | int)!==0 else (states('counter.workoutcount') | int) % (states('input_number.workouttimeannouncemins') | int)}}

#

thats from memory but I did copy off of several pages...it seems quite useful but the syntax seems backwards to me πŸ™‚

kindred moss
#

Hey guys, quick question regarding triggers. Is there a speed difference between using an event (template ;p) trigger compared to a state trigger ? Im guessing the event happens then the state is changed but are we talking noticeable difference?

#

prob best to ask this in automation's ehehe

spiral imp
#

I have this script using a template:

execute_chore:
  sequence:
    service: grocy.execute_chore
    data_template:
      chore_id: >
          {{ state_attr('sensor.spa_water', 'next_id') }}

But I am getting this error (missed comma between flow collection entries at line 743, column 51:
... tr('sensor.spa_water', 'next_id') }}

#

The carrot is pointing between the t & e in water. Not sure what I am missing here

mighty ledge
buoyant pine
#

The...what?

mighty ledge
mighty ledge
# buoyant pine The...what?

The "I'm going to only post the information that I think is relevant but I didn't so the helpers are left guessing" error

buoyant pine
#

Oh lol

jagged obsidian
#

i'm stealing that line

spiral imp
#

that was all that the pop up in file editor showed

mighty ledge
#

post the error from the log

spiral imp
#

I changed from data_template to service_template and am no longer getting the error in file editor

#

there was no error in the log, I got the error as I was typing out the code in file editor

mighty ledge
#

is that an addon or something?

#

vscode addon?

spiral imp
#

it is just enabled in configuration.yaml..i thought

mighty ledge
#

I'm trying to find out where this error is coming from

#

what utility are you using to edit configuration.yaml

spiral imp
#

File Editor. it is in my side bar

mighty ledge
#

Yes, is that an addon?

#

Only you have the answer to this, that's not a standard item.

#

and it's not an integration.

#

I guess we have to assume its the file editor addon

spiral imp
#

yes, official add on. Sorry

mighty ledge
#

Ok, sorry don't have experience with Ace Editor's yaml linting.

sly raft
#

Hi, Unable to parse output as JSON: Invalid macro definition. Does anyone know what macro definition this is referring to? It is (and has been for a long time) a valid JSON output it is complaining about: {"cpu_percent": "63", "hdd_percent": "17.1", "ram_percent": "40.8", "cpu_temp": "65.75", "uptime": "14:43:10"}

spiral imp
#

no problem, I am not getting the error now. For that script, would I needto use data_template or service_template? I do not understand the difference

mighty ledge
#

both data_template and service_template are deprecated

#

you should be using service or data

#

do you understand the difference between service and data?

spiral imp
#

yes, can i use a template in data

mighty ledge
#

you can use a template in both

#

the difference is: Service is the service you are using, data is the data that goes along with the service

spiral imp
#

i understand that so my script should just be:

execute_chore:
  sequence:
    service: grocy.execute_chore
    data:
      chore_id: >-
        {{ state_attr('sensor.spa_water', 'next_id') }}
mighty ledge
#

yep

mighty ledge
spiral imp
#

I have used variables in scripts before. I have multiple sensors that could use this script. Can I put a variable in place of "spa_water" so that I don't need to have multiple scripts?

mighty ledge
#

yep, it would probably be easier to just replace the entire entity_id

#

unless they are all going to be sensors

spiral imp
#

they are all sensors: sensor.spa_water, sensor.spa_filer, sensor.lawn_fertilizer, etc

sly raft
#

the weird thing is, I never changed that ancient script since forever and suddenly it complains about a macro. The json comes from a command line sensor that connects via ssh to a remote machine. Now even running that command line in the hass terminal complains about "Invalid macro definition". ponder

#

I'm not sure what "macro" is meant here

mighty ledge
#

hmm, no clue then.

mighty ledge
spiral imp
#

I am not familiar with that syntax

mighty ledge
#

well it's a good thing I gave it to you then

spiral imp
#

so like this:

execute_chore:
  sequence:
    service: grocy.execute_chore
    service_data:
      chore_id: >-
        {{ state_attr('sensor.'~ chore, 'next_id') }}
mighty ledge
#

yep

spiral imp
#

and a tap_action would look like:

        tap_action:
          action: call-service
          service: grocy.execute_chore
          data: 
            chore: spa_water
mighty ledge
#

nope

spiral imp
#

oops sorry

mighty ledge
#

check the tap action docs

spiral imp
#

pasted too fast

mighty ledge
#

there's only 1 error in that

#

and it's a field name

inner mesa
#

You get one guess! Make it count!

#

<I know! I know!>

spiral imp
#
tap_action:
  action: call-service
  service: script.execute_chore
  data:
    chore: spa_water
mighty ledge
#

nope

#

.tap-action

spiral imp
#

action can be removed now right?

mighty ledge
#

nope

#

it's a field name

#

one of them is wrong, and it's covered in the tap action documentation

#

.tap_action

#

bah, @arctic sorrel fix bot

inner mesa
#

I don’t think that’s ever been a thing

mighty ledge
#

probably not, but it should be

spiral imp
#

looking at the docs now

#

I'm not seeing it, sorry

mighty ledge
#

no u, i just wanted to ping you

spiral imp
#

oh, here i have to use service_data?

mighty ledge
#

yes

spiral imp
#

got it, thanks

ruby peak
#

Does anyone know how to do a comparison between dates in a template sensor? The API returns a date in a string format such as 22/11/2021 but I then need to calculate the days between todays date and that date, and then return Today, Tomorrow, X days time

mighty ledge
ruby peak
#

date: 2021-11-22T00:00:00.000Z like that

mighty ledge
#
{% set time1 = strptime(whereveryougotyourdate, '%d/%m/%Y', none) %}
{% set time2 = strptime(whereveryougotyourdate, '%d/%m/%Y', none) %}
{% if time1 and time2 %}
  {% set delta = time2 - time1 %}
  {% if delta.days = 1 %}
    Tomorrow
  {% elif delta.days = 0 %}
    Today
  {% else %}
    {{ delta.days }} days time
  {% endif %}
{% endif %}
#

if you use isoformat, it would simply be:

#
{% set time1 = whereveryougotyourdate | as_datetime | as_local %}
{% set time2 = whereveryougotyourdate | as_datetime | as_local %}
{% if time1 and time2 %}
  {% set delta = time2 - time1 %}
  {% if delta.days = 1 %}
    Tomorrow
  {% elif delta.days = 0 %}
    Today
  {% else %}
    {{ delta.days }} days time
  {% endif %}
{% endif %}
#

if you rtimezone is utc you can drop the as_local

ruby peak
#

is there no way to get current date/time within jinja?

mighty ledge
#

there is

#

now()

#

but you said you're getting it from an api

#

if you want to compare it to now, then replace time1 with now

#
{% set t = whereveryougotyourdate | as_datetime | as_local %}
{% if t %}
  {% set delta = t - now() %}
  {% if delta.days == 1 %}
    Tomorrow
  {% elif delta.days == 0 %}
    Today
  {% else %}
    {{ delta.days }} days time
  {% endif %}
{% endif %}
ruby peak
#

Yeah sorry, 1 time comes from API, and to compare it against now

#

MMmm TemplateSyntaxError: expected token 'end of statement block', got '='

mighty ledge
#

i'm guessing you didn't use the multiline indicator for the yaml

#

also, i left out ==

ruby peak
#

ah yeah of course

#

OK that works perfectly. Thanks πŸ™‚

sly raft
#

Hm, i think my error message is from ssh. Even just ssh user@host python -V asks for the pw and then before printing the python version "Invalid macro definition"

#

Is there a way to prune that message before setting the value here? value_template: "{{ value_json.pc_data }}"

#

something like {% set value_json = "my perfectly nice json just without that weird line" %} ? πŸ˜†

bright plaza
#

I'm really puzzled with this bit of code - can anyone help?

#

{{ ((('574115881' | float) /100000000) | round(2) ) + 17 }} In dev tools templating, this doesn't seem to round properly

#

but if I remove the + 17 or change the round(2) to 1 or 3 it does work as you'd expect. But why doesn't 2 work? It had been working for the last 2 weeks and now today it's not rounding properly

#

I enquired about something similar here a week or two ago and discovered I hadn't bracketted properly which I fixed and you can see above everything should be fully bracketted

mighty ledge
#

Aka order of operations with math equations

#

If you don’t know what pedmas is, Google it

bright plaza
#

are you sure?

#

I thought I had parentheses around the whole conversion to float and division

#

then piped the result of that section to the round function

marble jackal
#

I also thought that for a moment, but you are not.
But you have some unneeded parantheses.
{{ ('574115881' | float /100000000) | round(2) + 17 }} will do the same

bright plaza
#

then the end result of that I add 17 to by bracketing the end result

#

When I asked the other week here I was told that you need strict parenthesis so I just made sure everything was done to ensure the groupings were explicit

#

Also, my rest sensor template the above is taken from to test with is working again to 2 decimal places. The only thing that has changed is the first number in single quotes

marble jackal
#

There is indeed something strange here, I checked in developer tools, and it works with round(1) and round(3) and without the +17 (like you already said). But not with round(2)
This does work though {{ (('574115881' | float /100000000) +17) | round(2) }}

bright plaza
#

and why would changing round(2) to round(1) and round(3) in the above example work correctly - but not round(2)

#

yes

#

it's very weird

#

Your working suggestion looks more readable and tidier so I can use that. But I'm still trying to get my head around why it behaved like this in the first place

#

it seems that the behaviour changed based on that first number as it changed. So perhaps some very specific values are doing something odd

marble jackal
#

You can remove some parantheses there as well: {{ ('574115881' | float / 100000000 +17) | round(2) }} (because of pedmas)

bright plaza
#

I tend to prefer explicit parentheses because it's easier at a glance to see what the order of execution is without having to remember which operators take precedence over others

#

do exactly the same thing with the number 587361197 and it works fine - to 2 decimal places

mighty ledge
#

multiple parenthesis usually takes longer to read, especially if you don't have a linter

marble jackal
#

I assume that instead of '574115881' you will use a entity state? You might want to add a default for the float then to avoid template warnings (and errors after 2022.1 or something)

bright plaza
#

yes - it's from a rest api - I presume it therefore comes back as a string

#

so for testing purposes (and you can't integrate a rest call into the template dev tool that I know about) I just hard coded the json value applicable

mighty ledge
#

rest has the ability to return json, so it could be a number, but it depends on the output of the rest endpoint

#

value is always a string, but value_json will be json

bright plaza
#

the rest api would return this (when the url called from a browser): {"data":{"balance":587361197}}

mighty ledge
#

thats json

#

and that's a number

bright plaza
#

Is what I have in the code value_json.data.balance

mighty ledge
#

yes, but you won't need the float

#

it's already an int

bright plaza
#

ah ok

#

probably because I cut and copied from another bit of code I had somewhere else

mighty ledge
#

{{ (value_json.data.balance / 100000000 + 17) | round(2) }}

regal temple
#

I am trying to write to a file with a shell command using an input_number. Writing to the file is not a problem, like this:

shell_command:
  set_brightness: β€˜echo 80 > /config/screen_settings/brightness’

But it fails if I try to use an input_number value:

shell_command:
  set_brightness: β€˜echo {{ states(β€œinput_number.brightness”) }} > /config/screen_settings/brightness’

Anyone knows what I am doing wrong??? Help is very much appreciated!

bright plaza
#

so these two examples: one returns 2 dp, th other lots:

#

{{ (((574115881) /100000000) | round(2) ) + 17 }}
{{ (((587361197) /100000000) | round(2) ) + 17 }}

mighty ledge
#

because you aren't rounding the entire equation...

bright plaza
#

I only need to round the big number/1000000000 don't I, not the +17

mighty ledge
#

you need to round it all

#

if you add an integer to a float, you can end up with epsilon error

#

which is what you're seeing

bright plaza
#

if I get 5.65 out which I imagine is a float, then add +17 I should get 22.65

mighty ledge
#

epsilon error is error induced by computers when performing math

bright plaza
#

if I did +17.0 then it would be ok? (in theory) πŸ™‚

mighty ledge
#

its usually on the order of 1e-10ish

#

no, you need to round the entire equation

bright plaza
#

got it

#

Think I put the +17 there to try and simplify the problem previously when I had precedence issues due to a lack of bracketing

mighty ledge
bright plaza
#

so was I hitting that episilon error with a certain number then?

marble jackal
#

Learning stuff everyday! Now I understand why Excel sometimes gives these strange results when adding cells, it's an epsilon error πŸ™‚

mighty ledge
#

you're hitting epsilon error in general

bright plaza
#

With the following it gives 2dp with both the test numbers correctly:

#

{{ ((((574115881) /100000000) +17) | round(2) ) }}
{{ ((((587361197) /100000000) +17) | round(2) ) }}

#

but with that +17 the other side of the round(2) one is rounded the other is not

mighty ledge
#

why do you have a parenthesis around the first number

bright plaza
#

agreed - pointless πŸ™‚

#

episolon error explanation looks a bit over my head

mighty ledge
#

it's just what computers do

#

if you don't want to learn about bytes and how numbers are represented in memory, then there's no point in learning about epsilon error. All you need to remember is to round the entire equation

bright plaza
#

Thanks. Memo to self - make sure you do your rounding on the final result

regal temple
regal temple
#

I read something similar on the integrations page for shell_command

#

set_ac_to_slider: 'irsend SEND_ONCE DELONGHI AC_{{ states("input_number.ac_temperature") }}_AUTO'

marble jackal
#

no fancy quotes there πŸ™‚

mighty ledge
bright plaza
#

I'm still pretty new to templating

mighty ledge
bright plaza
#

Time to get googling. Not heard of those

#

Yep - makes sense

mighty ledge
#

well, its not available on rest sensors, however you can return none and it will be unavailable

regal temple
mighty ledge
#

quotes like this ’ are invalid in yaml

#

they ONLY come from microsoft word when using quotes or a forum post with unformatted code

#

' correct quote type

#

notice the difference

#

so your original code that you posted above will not work with those bad quotes and they appear after you used backtics

#

which means you copied it from an unformatted code source like the forums or microsoft word

#

or an email

#

or anything that formats text as you type

regal temple
#

My god, I didn't know they were different, I could not tell the difference... So if I replace these quote characters the shell command should work?

mighty ledge
#

yes

#

and never copy unformatted code again

#

this is why everyone gets bent out of shape when new people don't take the time to format the code with backticks

#

because it just leads to more questions and screwups

regal temple
#

Does this still contain the wrong quote characters? 'echo {{ states("input_number.screen_brightness") }} > /config/rpi_brightness/bright' Please forgive me my ignorance...

mighty ledge
#

edit that and use backtics before and after

#

single backtick before 'echo and single backtick after bright'