#templates-archived

1 messages Β· Page 123 of 1

nocturne chasm
#

You are probably going to need a template that compares the state of one to the other and is true when they are ==

#

And you are going to need to do some template magic to parse out only the hour
something like this, but you are going to need to play with it in the template editor
{{ (now().hour) == as_timestamp(states.sensor.your_sensor.attributes['your_attribute']) | timestamp_custom("%H") }}

nocturne chasm
#

or this may work also {{ (now().hour) == (state_attr('sensor.your_sensor', 'your_attribute')) }}

unreal merlin
#

howdy πŸ™‚

#

what's the best way to test if a variable is_numeric?

ivory delta
unreal merlin
#

not yet - searched the forums but nothing definite I could find - checking

#

that helped, thanks

formal ember
#

is it possible to create a switch that toggles one script as the On and another as the Off?

ivory delta
#

The only bit that requires a template is the value_template so that it knows when it's on/off.

formal ember
#

ah perfect, thanks mono

#

actually, how do you know a script is on/off? would it be by seeing if any of the entities that the switch turned on are in the on state?

ivory delta
#

A script isn't on/off. You'll need to track the switch state with an input boolean or something.

mighty ledge
#

scripts are only 'on' if there's a delay in the script. Otherwise you'd need to create a boolean that stores your on/off state

ivory delta
#

Snap

formal ember
#

legends, makes complete sense

#

I think πŸ™‚

ivory delta
#

Turn on = run script A, where script A sets a boolean to 'on'.
Turn off = run script B, where script B sets the same boolean to 'off'.
Template value of the template switch is the state of the boolean.

formal ember
#

hmmm for some reason the switch is not calling the script.

    all_ac_thermostat:
      friendly_name: All AC Thermostat
      value_template: "{{ is_state('input_boolean.all_ac_thermostat_script_on', 'on') }}"
      turn_on:
        service: switch.turn_on
        target:
          entity_id: script.all_ac_thermostat_on
      turn_off:
        service: switch.turn_off
        target:
          entity_id: script.all_ac_thermostat_off```
#

oh wait, switch.turn_on and off should be script.toggle or something

mighty ledge
#

no

#

your services need to be script.turn_on because you're turning on a script

#

but you don't even need that because scripts are services

#
    all_ac_thermostat:
      friendly_name: All AC Thermostat
      value_template: "{{ is_state('input_boolean.all_ac_thermostat_script_on', 'on') }}"
      turn_on:
        service: script.all_ac_thermostat_on
      turn_off:
        service: script.all_ac_thermostat_off
formal ember
#

alright, now it works, however it won't turn off... thinking that has something to do with the script though

#

on script turns the ac on, and turns input_boolean to on, but doesn't shut it off when clicked again

#

nor does it change the state of the button in the UI to on

#

but calling the script manually in devtools works....

mighty ledge
#

your template is correct, so the only option is that you ahve a typo

#

also, turning on your input_boolean should be the first service in the turn on script. Turning off should be the last service in the script turn off

formal ember
#

Ah I’ll give that a go

#

Ugh still no good. I would have thought it was my button in the UI but surely I can’t have stuffed that

mighty ledge
#

are you sure you have the correct input boolean name in the template?

formal ember
#

No... looks like when I changed the name of it, it didn’t carry over πŸ˜‚

#

Something so simple, thanks for steering me to look at exactly what was wrong (again)

atomic steeple
#

Hey everyone.
So how would I go about changing the state text shown when a binary sensor is on/off?

For example this binary sensor binary_sensor.octoprint_printing says On and Off, but I would like to change it to Yes when On and No when Off.

coarse tiger
#

you use templates to make a custom state based on a existing entities state, yes

coarse tiger
atomic steeple
#

Many thanks

mighty ledge
inner mesa
#

And on the stone tablet was written this template

mighty ledge
#

I mean, I can... just 5 years ago was ancient times

coarse tiger
kind olive
#

How come my light.turn_on action fails with this option: brightness_pct: {{ states('input_number.wakeup_brightness')|float }}? Error message: Error while executing automation automation.wakeup: expected float for dictionary value @ data['brightness_pct']

marble jackal
#

What does it return when you enter the template in the template checker in developer tools?

kind olive
#

25

marble jackal
#

Okay, I was wondering if it might return an error (maybe because of a littly typo or something). But in this case I also do not know why it doesn't work

#

What is the complete service call in which the template is used?

fossil venture
#

Because you have not put quotes around a single line template.

#

brightness_pct: "{{ states('input_number.wakeup_brightness')|float }}"

kind olive
#

there you go πŸ™‚

#

quite picky this one πŸ˜‰

#

would love for it to understand brightness_pct: input_number.wakeup_brightness

marble jackal
#

Ah, of course.. πŸ™‚ Shouldn't have missed that. But it's still early morning here πŸ™‚

fickle quiver
#

simple question here - I have a sensor and I want it to be in different units

#

sensor.octoprint_time_elapsed shows time in seconds, let's say I want minutes

#

do I need to create a derivative sensor? How do I do this?

#

I can do this in the template editor and it works: {{states.sensor.octoprint_time_elapsed.state |float / 60 }}

#

But how do I integrate it back into my charts or whatever?

inner mesa
#

You use a new sensor

fickle quiver
#

I think I'm getting the concept

#
  - platform: template
    sensors:
      octoprint_time_elapset_min:
        friendly_name: "Octoprint Time Elapsed (min)"
        value_template: >-
          {{states.sensor.octoprint_time_elapsed.state |float / 60 }}
#

at least the config check passed lol

inner mesa
#

Looks ok to me. You may want to add a unit_of_measurement (like β€˜mins) if you want a graph in the history.

fickle quiver
#

Got it - thanks again for your help. I'm feel a little slow getting started at this.

inner mesa
#

No worries, you’re doing great

fickle quiver
#

I think that pretty much answers my noob questions. The next steps are to make some control dashboards. Like you said - I'll probably need to write some scripts to do this.

#

It's really neat to pipe everything into the same "hub" and have it all right there. I didn't consider my house that "connected" before until I started setting all this up.

fossil hearth
#

is there a way to get the last time stamp of a specific state ?

fossil venture
#

Replace domain.object_id with your entity_id and state with your required state in this

{{ if domain.object_id = 'state' as_timestamp(states.domain.object_id.last_changed) else states('domain.object_id') }}
fossil hearth
#

AMAZING

#

❀️

#

i shall try

fossil venture
#

Actually... that else case is not correct. If you wanted the timestamp of the state on it will return a timestamp or off

#

Hmmm. Tricky...

#

That else case needs to be the domain.object_id of the template sensor itself.

fossil hearth
#

yeah it didnt work

fossil venture
#

It would help if you showed what you tried, the full sensor definition.

fossil hearth
#

{{ if sensor.csw4 = 'single' as_timestamp(states.sensor.csw4.last_changed) else states('sensor.csw4') }}
the sensors states are Single Double and LONG its a a button

inner mesa
#

Yeah, that’s not right

fossil venture
fossil hearth
#

should it be states.sensor.csw4.state ? isntead of sensor.csw4

fossil venture
fossil hearth
#

emplateSyntaxError: expected token 'end of print statement', got 'states'

#

i donno about this part is doesnt seem right

#
states('sensor.single_timestamp_sensor')```
fossil venture
#

That's the state of the template sensor itself, this will be returned if the state is not 'single' i.e. no change to the sensor. It returns itself.

fossil hearth
#

so i have to create a template sensor ?

fossil venture
#

Yes, I can't think of another way to not change the state if not 'single'.

ionic hazel
#

I have an Aqara Button that exposes - among many things - this: sensor.pasha_button_click
If I select sensor.pasha_button_click in devtools , & click the button, this will show up: https://imgur.com/a/ZlmZNXr
Otherwise it's this https://imgur.com/a/rpJ9HE8
According to the docs, I think I'm supposed to use the action attribute. https://www.zigbee2mqtt.io/devices/WXKG11LM.html#deprecated-click-event
I assumed that if I did everything right, after pressing the button, having this in my template would Result in "True"
"{{ state_attr('sensor.pasha_button_click', 'click_action') == 'single' }}"
But when I click the button it still says "false"
Should I be using a different attribute?

ivory delta
#

How are you testing it?

ionic hazel
#

by clicking the button

ivory delta
#

How are you checking the template? πŸ˜‰

ionic hazel
#

oh uhh in devtools : template i'm putting that line in the tempalte editor

ivory delta
#

It's probably happening too quickly for you to even see it there. A button is a momentary event.

ionic hazel
#

oh

#

yea you know it was super quick

ivory delta
#

I'd suggest making a template sensor with your template, then seeing what the history for that sensor says after the button is pressed.

#

Honestly, though... you probably don't even need a template for that. I use the same button and just have a state trigger:

- to: 'single'
  entity_id: sensor.0x00158d000401926f_click
  platform: state```
ionic hazel
#

are you serious?

#

just to be clear, for me, in devtools I don't get anything in the state field, when i click the button; only in attributes

#

Tinkerer thought maybe it was in the way that I set it up, that it does only in attributes

ivory delta
#

I don't know how your sensor was created... I'm using Z2M too πŸ€·β€β™‚οΈ

#

You don't have any that end with _click?

gusty nimbus
#

Hey,

#

anyone an idea how to show the cryptocurrency value of Holo (HOT) EUR ?

#

in a sensor

ionic hazel
ionic hazel
plucky wyvern
#

Hi, how can I round all entities of sensor with type power?

#
- name: "EG Gast Licht Decke Leistungswert"
  state_address: "1/7/7"
  type: power
  sync_state: false
  value_template: "{{ (states('sensor.eg_gast_licht_decke_leistungswert') | float ) | round(1) }}"
#

This is not working and only for one entity

inner mesa
#

I don’t think you can. You have to define each one

plucky wyvern
#

ok

#

any idea why my example above is not working? maybe a typo somewhere?

ivory delta
#

To check what attributes actually exist, go to the Dev Tools > States

ionic hazel
#

If i wasn't seeing it I wouldn't believe it. Is that normal?

ionic hazel
#

And when i click the button, the field next to click changes to "single" *and a new action attribute pops up, also with "single" https://imgur.com/a/ZlmZNXr

ionic hazel
ivory delta
#

It doesn't matter what I see, only what attributes your sensors have

#

Don't guess. Check.

ionic hazel
#

Here's what I see in devtools attributes

- battery: 100
- click:
- linkquality: 84
- voltage: 3075
- friendly_name: pasha_button_click
- icon: mdi:toggle-switch
#

And here's what I see in devtools (for about .01 seconds) when I click the button:

- action: single
- battery: 100
- click: single
- linkquality: 84
- voltage: 3075
- friendly_name: pasha_button_click
- icon: mdi:toggle-switch
ivory delta
#

So you're after click πŸ˜‰

#

It's also going to be the state for that brief time too, which is why templates are unnecessary and you could just be copying my example from earlier.

ionic hazel
ivory delta
#

No no no no no

#

There is zero need for a template where you're just after a simple state/attribute trigger.

ionic hazel
#

Okay...I hear you, I swear to god I am listening, and I'm really sorry if this is retarded, but I thought you were saying that example would only work if I had something in devtools states, instead of attributes ?

fossil venture
#

It will work for an attribute too.

ionic hazel
#

oh. sweet. Im an idiot

ivory delta
#

Using attributes used to need a template. It changed quite a while back.

#

You might still see examples that use templates but you shouldn't trust old examples - always check the docs.

fossil venture
#

Relatively recent in HA terms.

ivory delta
#

Months... πŸ˜„

#

That's a pretty long time in HA world

fossil venture
#

Was it WTH month?

ionic hazel
#

Gotcha. I was probably checking the wrong docs, i searched attributes+automations

#

and was def looking at some forum posts from 2019

#

Thanks for all your help, mono!!!

silent barnBOT
final abyss
#

Any suggestions on tiding up this nice template from the past ☝️ ?

ivory delta
#

Padawans posting code walls? Shame on you!

teal umbra
#

Can somebody please help 😦 I cannot figure out whats going wrong here
it simply just don't work

  • platform: mqtt
    name: "Nick is home"
    state_topic: "ai/Default/motion/"
    value_template: >
    {% set ns = namespace(found = false) %}
    {% for match in camera_json.predictions %}
    {% if match.label == 'Nick' and match.confidence >=10 %}
    {% set ns.found = true %}
    true
    {% endif %}
    {% endfor %}
ivory delta
#

Looks pretty tidy already. You could maybe assign the state to a variable just so you're not repeating a long ugly string but the functionality looks fine, sjabby.

final abyss
#

Its barking at me after the update:
2021-04-07 20:58:15 WARNING (MainThread) [homeassistant.helpers.template] Template variable warning: 'mappingproxy object' has no attribute 'game' when rendering '{% if states.sensor.steam_7

#

the attribute only exists when a game is actually played, otherwise the attribute is not present

ivory delta
#

Then you'll need to chain your accessors, I guess...
{% if states.sensor.steam_76x50.attributes and states.sensor.steam_76x50.attributes.game -%}

#

It shouldn't be going any further in your nested template if the first check fails.

final abyss
#

Same 😦

sonic oracle
#
value_template: >-
          {% set consumption = states('sensor.consumer1') + states('sensor.consumer2') %}
          {% set production = states('sensor.prod1') + states('sensor.prod2') %}
          {{ consumption + production }}

How can i force to not concatenate the values but add them together instead?

#

or where do i need to add | float

ivory delta
#

Add the filter after everything that would return a string.

sonic oracle
#
{{ (states('sensor.demo_battery') |float) + (states('sensor.demo_grid') |float) }}

?

ivory delta
#

In your case, that's each of the 4 state functions.

sonic oracle
#

k thy

mighty ledge
final abyss
#

thx!

mighty ledge
#

er, nevermind

#

forgot the not πŸ˜‰

scenic wedge
#

Just upgraded to 2021.4.0 and get 3 occurances of
WARNING (MainThread) [homeassistant.helpers.template] Template variable warning: 'dict object' has no attribute 'action' when rendering '{{ value_json.action }}'
in my logs at start up and then again at random times after that. None of my yaml files have the string value_json.action in them and I've tried removed every yaml file that contains the string "template" but I'm still seeing the warnings.
any pointers on where else to look.

scenic wedge
#

@sly seal You are a god ... yes I am ... many thanks

misty pasture
#

what's the most straightforward way to reduce on all states for a given device class? for example, I want to check whether any device_class: moisture sensors have an on state

#

hmm there's gotta be a more elegant approach. especially when it comes to outputting a different string if none are on

{% for state in states.binary_sensor %}
  {%- if state.attributes.device_class == 'moisture' and
         state.state == 'on' %}{{ state.name }}
  {%- endif -%}
{%- endfor %}
unique elm
#

Is there a simple guide to templates as I cannot find in the documentation how to do really simple operations. My SNMP request returns a voltage as an integer as 2380. This is 238.0 volts. I tried:
value_template: '{{ (val | int /10 ) }}'

#

It gave an error and will not read. I tried val | float / 10 | round(0) still no luck

#

If I do not use value_template at all it happily returns 2380

inner mesa
#

you're rounding 10 in the last one

fossil venture
#

The first one is almost right except val should be value

unique elm
#

Perfect! That worked, thanks

analog plover
#

I have an MQTT-device which reports a number of json-values. What is it called if I want to create a custom sensor which has all of the json values integrated? I don't want separate sensors for each json-value from the device if you get what I mean.

ruby crane
#

How would one go about retrieving attributes from a sensor (online weather in this case) that are not "top level" attributes? They are under the attribute "forecast", and then listed per day.

ruby crane
#

Found it on the forum!

grim flicker
#

I have this code:
{{ as_timestamp(now()) | timestamp_custom('%d''-''%m''-''%Y') -}}
which gives: 08-04-2021
now i would like to have the date before today in here. so day -1
could some one tell me how i do this?

ivory delta
#

Use a timedelta on the date object (now()).

mighty ledge
#

and for the previous day... {{ as_timestamp(now()-timedelta(days=1)) | timestamp_custom('%d-%m-%Y') }}"

grim flicker
#

thanks for all the info

reef ferry
#

I have a hopefully easy question to answer. How do you access the first element on an array? {{ state_attr('weather.kvay_hourly', 'forecast') }} does return the full array, but {{ state_attr('weather.kvay_hourly', 'forecast[0]') }} return none just for reference I am trying to get the value for weather.kvay_hourly.forecast[0].precipitation_probability

ivory delta
#

You need to access the array element after you've retrieved it. Your second example is trying to get an attribute with the name 'forecast[0]' which doesn't exist.
Something like this should work:
state_attr('weather.kvay_hourly', 'forecast')[0] }}

honest mauve
#

Hey

#

can I run different rest command in a script, depending on status of a sensor?

ivory delta
honest mauve
#

not automation... but scripts....

#

so templating an if then else

#

in the scripts

#

make one call instead of another

ivory delta
unique harbor
#

Hi all, quick Q, I seem to be not grasping what I know is a simple solution here. I need to present the following string in timestamp_local, but can't get the syntax right.
{{ now().timestamp() + state_attr('sensor.travel_time_home_to_hospital', 'value') }}. I thought it would be as simple as adding | timestamp_local at the end, but that obv just throws me that float and str is unnsuported operand for +

ivory delta
#

You need to use timedeltas to manipulate dates. Scroll up a little, there was a discussion today about it.

unique harbor
#

Thanks mate

#

Jesus, that was literally right above me, sorry, I'm blind

ivory delta
#

It happens

zealous tapir
#

I was able to get an LED light to work using the IR remote function provided by the Broadlink integration, and made a light_template so it could be an entity. The light has options for various colors as well as color temperatures of white. However, it's all based on buttons from the IR remote, learned by the Broadlink integration. Now I'm trying to fine tune this, since the various light_template options don't seem to fit well. Not sure if I should just set the light_template to turn on and off β€” and then use automations to set up the various white or RGB colors, modes, etc. All of those are individual buttons on the IR remote.

zealous tapir
#

I've now done something similar for a fan_template. The remote for that has 3 buttons, one for power, one for speed, and one for a built-in timer. The fan_template doesn't seem to map well to this.

nocturne chasm
#

If the ir remote you are talking about is for the light, you are prob going to have to learn all the commands into the broadlink and then call each command in an automation.

silent barnBOT
unique elm
#

Can I use icon templates with snmp sensors? My code example is above (abbreviated)

#

I am also trying to structure the code correctly in yaml, hopefully you can see what I am trying to achieve

silent barnBOT
unique elm
#

...and I will use pastebin in the future...sorry

unreal merlin
#

Howdy πŸ™‚

#

I watched the release party video on youtube and have a question about trigger based template entities - I don't fully gasp it just yet.

#

Is this to solve the problem of updating template sensors based on certain triggers?

#

What I've got in mind is to create a daily average, mean, min and max temperature template sensors, and while my template seems to be working now, updating it is actually the next step - so ideally any change in metno's hourly values would kick an update (e.g. recalculate as prediction gets closer to reality)

#

or I'm completely in the dark and template triggers are for something completely different? like for the opposite of that?

#

(which can be as trigger platform template is something that's been around for a while)

silent barnBOT
silent barnBOT
ruby crane
#

If a template sensors history isn't displayed as a graph, does it mean it's not a number?

ivory delta
#

Not numbers... it means it doesn't have a unit of measure.

unreal merlin
#

Is there an easy way to access historical information on weather?

#

How much rain has fallen today is what I'm after as a template sensor

#

(or snow)

#

sensor.openweathermap_rain has historical info on this, haven't seen anything for met.no

#

but over 90% relative humidity by external sensors is a positive sign

ivory delta
#

It all depends on the data provided by the integration. Anything else would just be guessing.

#

There's nothing stopping you using multiple weather integrations and picking the data you want from each.

unreal merlin
#

that's close to what I'm trying to do, yeah: iterate through all the weather state_attr and use one or combine in case they are not "none" or "unavailable" or anything weird - survives anything lol

#

however, how can I access historical data?

#

I see the entity showing history back 8 hours or so, is that available for templates (w/o configuring a historical data/stats integration)?

ivory delta
#

Templates can only change how current data is represented. You'll need an integration for that.

marble surge
#

guys

#

I have this automation

#

if the received MQTT message does not contain whitetemp

#

I see this error in logs

#

Error evaluating condition in 'Set HA WhiteTemp': In 'condition': In 'template' condition: UndefinedError: 'dict object' has no attribute 'payload_json'

#

how can I say to the automation to skip everything if the json does not contain the "whitetemp"?

unreal merlin
#

that sound about right?

ruby crane
#

@ivory delta Got it, thanks

nocturne chasm
nocturne chasm
lethal galleon
#

Seeing this in the logs. What am I doing wrong??

2021-04-09 17:11:03 WARNING (MainThread) [homeassistant.components.template.trigger] Error initializing 'template' trigger for 'SYT - Two hours before': TypeError: can only concatenate str (not "datetime.timedelta") to str
2021-04-09 17:11:03 ERROR (MainThread) [homeassistant.helpers.event] Error while processing template: Template("{% set cl = strptime(states('sensor.jewish_calendar_upcoming_candle_lighting'), '%Y-%m-%d %H:%M:%S%z') + timedelta(hours=-2) %}
{% set now = strptime(states('sensor.jewish_calendar_now'), '%Y-%m-%d %H:%M:%S%z') %}
{{ cl == now}}")
ivory delta
#

What's the value of sensor.jewish_calendar_upcoming_candle_lighting right now?

lethal galleon
#

2021-04-09 15:22:00+00:00

ivory delta
#

Seems okay to me. I just did this to fake the sensor, since I don't have it:

{% set datetime = '2021-04-09 15:22:00+00:00' %}
{% set cl = strptime(datetime, '%Y-%m-%d %H:%M:%S%z') + timedelta(hours=-2) %}
{{ cl }}```
#

The last line outputs a time two hours before datetime.

#

Do you see the problem all the time or does the template sometimes work?

unreal merlin
lethal galleon
ivory delta
#

That wasn't the question

#

Try your template in the Dev Tools, see what it says there. It works for me πŸ€·β€β™‚οΈ

mighty ledge
#

depends on whwere the timestamp is coming from

#

Sometimes they have a T in the format

#

2021-04-09 15:22:00+00:00 vs 2021-04-09T15:22:00+00:00

#

gotta account for that in the format

ivory delta
#

I was using their value from their state. The reason I asked if it happens all the time is in case the state isn't always a datetime in the same format they expect.

fast mason
#

Mono you would be so proud of me. I managed to use regex all by myself to extract a value from a text sensor πŸ₯²

ivory delta
#

RegEx is amazing once you appreciate what it can to. It can often replace a lot of code.

fast mason
#

Still very new to it. Took me an hour

#

stupid backslashes interfering with quotes

ivory delta
#

I'm sure there are many similar sites but I love regex101 as a playground for testing them.

#

You can stick a bunch of test strings in the main panel and it'll show you which of them are matched by your pattern, as well as explain how your pattern works.

fast mason
#

I have that bookmarked from last time we were discussing regex πŸ˜†

ivory delta
#

Yup πŸ˜‚ RegEx DoS attacks...

quartz pine
#

Is there any easy way to display the last known state of a sensor when it becomes unavailable?

mighty ledge
#

you can make an automation that triggers off it changing to unavailable and display the from state

#

actually, you can use the new template integration

#

if you want to store it in a sensor

#

otherwise just make a notification automation

quartz pine
#

Thank you I'll try that!

unique elm
fossil venture
#

This will give you an icon that changes with battery %

elfin ledge
#

Has anyone seen state_attr return null instead of the correct value with 2021.4.x?
I'm using the template {{ state_attr('trigger.event.data', 'actions') }} and it returns null despite actions being defined.

inner mesa
#

I doubt that’s an attribute

#

States have attributes. You can just use trigger.event.data.actions

elfin ledge
#

I've added actions to my event data. And it works if I used it directly as you suggest, but if I wan't to test if it is there i.e. {{ state_attr('trigger.event.data', 'actions') != None }} I get False.

elfin ledge
#

I figured out a solution: {{ trigger.event.data.actions != null }}

waxen rune
#

I'd like some help to think straight. I have a moisture sensor that shows 0,35 when the plant is well moistured, and 0,5 when it really needs more water.
I want to create a ninverted sensor that shows 0 when the actual value is 0,5 and 1 when the actual value is 0,35. And linear values in between.
Something like the "water need" is between 0 % and 100%. I'm stuck in a mind loop I can't get out of so all help is appreciated. Suggestions?

fossil venture
#

water_need = -6.667 * sensor_value + 3.333

waxen rune
#

Thanks! I just got to the same conclusion in Excel. Needed a break to see things clearly.

upper raptor
#

hey everyone, trying to get a list of entity ids for binary sensors that have a certain attribute as true

#

using:

#

however, not all binary sensors have this attribute, so I'm getting a [homeassistant.helpers.template] Template variable warning: 'mappingproxy object' has no attribute 'attr' when rendering

#

any ideas how to resolve?

lime grove
#

What is the equivalent of javascripts math.exp() in home assistants templating?

cunning bramble
#

Is it possible to if-else-Template a service call in a automation action section?

fossil venture
#

Yes

cunning bramble
#

oh nice!

#

thank you

fossil venture
cunning bramble
#

It's probably just a small stupid mistake on my side

fossil venture
#

Sorry. Github is blocked where I am at the moment.

silent barnBOT
#

Please use https://paste.ubuntu.com/ to share code or logs. Please don't use Pastebin, since it can randomly add spaces to the main view.

cunning bramble
fossil venture
#

Stand by... it also takes ages for pages to load.

cunning bramble
#

No worries! I am not running away and it's not urgent πŸ™‚

fossil venture
#

Indentation is a bit off (should be 2 spaces not 3) but hopefully you get the idea

cunning bramble
#

ahhh, yea, that makes way more sense

#

thank you!

fossil venture
#

Target should be inline with service.

cunning bramble
#

Thanks. Gonna try it out!

cunning bramble
autumn grotto
#

Ok, I've got this in the message for a cloud TTS action in a script but it's only ever saying "unknown" even though the entity is set.
{{ states('input_select.test') }}
It is evaluating to a state but, so not sure what I've got wrong

blazing patrol
#

OK, I have been informed to place this here.

#

OK, this is likely in the wrong place so please correct me. I have had this error since updating to 2021.4.3 Logger: homeassistant.helpers.template
Source: helpers/template.py:1335
First occurred: 14:12:13 (9 occurrences)
Last logged: 14:19:05

Template variable warning: 'dict object' has no attribute 'led_indication' when rendering '{{ value_json.led_indication }}'
Template variable warning: dict object has no element Undefined when rendering '{% set values = {'idle':'off','heat':'heating','cool':'cooling','fan only':'fan'} %}{{ values[value_json.running_state] }}'
[2:27 PM]
Thing is I don't knowingly have a helper and I don't have a fan. Please can someone tell me the best place to look to fix the issue. Running supervised on Ubuntu 20.04 dedicated machine with supervisor. Thanks

#

I don't have any intentional templates co this is confusing me

ivory delta
#

If you've added no templates of your own, check Dev Tools > Templates and see what's going on in there. If there are broken templates there, it'll tell you over on the right.

#

It's basically a playground to experiment with templates. The style of the templates in your error messages looks pretty similar to the test ones.

blazing patrol
#

I am looking at it now and I see something to do with weather, it looks like an example with 'set my_test_json' in purple for example. I'm tempted to remove it but concerned it may have something to do with my weather intigration.

ivory delta
#

If it's in the Dev Tools screens, it's safe to edit, delete or otherwise fuck up. Like I said, it's a playground.

blazing patrol
#

Thanks, deleted it to see if that makes a difference

regal temple
#

I specified a template as {{ (states("input_number.low_value") | float + 4 | float ) }} and it works in the developer tools. But when I use it as a value in an automation trigger for numeric_value I receive the message: "Message malformed: expected float for dictionary value." Anyone an idea of what I should do to fix the template?

blazing patrol
#

Unfortuantely I am still getting the error "Template variable warning: 'dict object' has no attribute 'led_indication' when rendering '{{ value_json.led_indication }}'"

ivory delta
#

Then something is using a template πŸ€·β€β™‚οΈ

#

You can search your config for curly braces but it's up to you to find it.

blazing patrol
#

OK, thanks. just looking for curly braces as narrowed the search down

mighty ledge
spare lichen
#

Template variable warning: 'break' is undefined when rendering '{%- set activepage = namespace() -%} {%- for entity in device_entities(haspdevice) -%} {%- if entity|regex_search("^number..*_activepage(?:\d+|)$") -%} {%- set activepage.entity=entity -%} {{ break }} {%- endif -%} {%- endfor -%} {% if states(activepage.entity)|lower == "none" %}-1{% else %}{{ states(activepage.entity) | int }}{% endif %}'
when trying to stream onvif camera

mighty ledge
#

yeah, break is undefined yet you are trying to output it. Also, please format the code next time or share it on a codeshare site

silent barnBOT
#

Please use https://paste.ubuntu.com/ to share code or logs. Please don't use Pastebin, since it can randomly add spaces to the main view.

spare lichen
#

what should i do to stream my camera?

blazing patrol
mighty ledge
#

ok, and how did you integrate it in HA?

blazing patrol
#

it is zigbee2mqtt which is why I am thinking it could be that

mighty ledge
#

right, but did you use discovery or did you manually add it

#

for MQTT

#

simple question

#

"I don't know" is a valid answer too πŸ˜‰

blazing patrol
#

I used discovery, when I installed zigbee2mqtt there is a automation to discover new devices

mighty ledge
#

Ok, then write up an issue against zigbee2mqtt unless you manually configured this device in that platform

#

if you manually configured the discovery settings on that system, then you just need to update your templates there

elder moon
#

im trying to set up an automation which would be triggered every time when a state of any entity with a name ending with _overcurrent suffix changes

#

is that even possible?

mighty ledge
frank gale
#

Can I template the initial value for input_text in configuration.yaml ?
I'm getting errors by configuration check

frank gale
#

@mighty ledge thank you! you were clear πŸ™‚

clever fulcrum
#

Hey all, Sorry for my ignorance but I'm trying to modify the output of one of my sensors.

In the RAW configuration editor for a room I have:

  - entities:
      - entity: sensor.balcony_temperature
      - entity: sensor.balcony_humidity
    title: Balcony Sensors
    type: entities

However the temperature is always 1.5 degrees C too high, so I'd like to subtract that value before output if possible.
Any help appreciated πŸ˜„

inner mesa
#

as mentioned earlier, you'll need to create a template sensor to adjust the value

#

that's why he sent you here, but you'll need to do some research

ivory delta
#

To be fair, I only said to come here for help with the template itself πŸ˜„

clever fulcrum
earnest arrow
#

elementary template question 😁

#
{% if trigger.event.data.parameters.userId is not none %}
  User Code {{ trigger.event.data.parameters.userId }}
{% endif %}
#

the user code text still gets included in the message even if trigger.event.data.parameters.userId doesn't exist

inner mesa
#

None

#

maybe?

wooden tendon
#

Hi. This might be a generic configuration question, but I can't find a more general channel, so asking here since it's for a template.
I get a DEPRECATED (seince 2021.3) warning on the value of my value_template in VSCode for the following. I'm still looking but can't see what's wrong yet. It works. Can anyone help me understand and fix it please?

cover:
  - platform: mqtt
    name: "Garage Door"
    command_topic: "garadget/lionhousegaragedoor/command"
    state_topic: "garadget/lionhousegaragedoor/status"
    payload_open: "open"
    payload_close: "close"
    state_open: "open"
    state_closed: "closed"
    value_template: "{{ 'open' if 'open' in value_json.status else 'closed' }}"

EDIT: found it in https://www.home-assistant.io/blog/2021/03/03/release-20213/#breaking-changes - replace value_template with position_template.

earnest arrow
# inner mesa `None`

Invalid config for [automation]: invalid template (TemplateAssertionError: no test named 'None') for dictionary value @ data['action'][0]['data_template']. Got None. (See ?, line ?).

inner mesa
#

there's clearly more to that automation than was posted πŸ™‚

earnest arrow
#
action:
    service: notify.ios
    data_template:
      title: Door Lock Notification
      message: >
        {{ trigger.event.data.event_label }}
        {% if trigger.event.data.parameters.userId is not None %}
          User Code {{ trigger.event.data.parameters.userId }}
        {% endif %}
#

trigger is zwave_js_notification event

inner mesa
#

first, data_template:->data:, but that's not the problem

#

I would just do {% if trigger.event.data.parameters.userId %}

clever fulcrum
#

Is there somewhere more basic I can go to understand the basics of this language as none of this means a thing to me. The documentation doesn't help at all, as it doesn't explain the language, what it can do or how it's done. No one has ever explained the basics of what the fek is going on. A sensible list of commands would be nice, some sort of grounding would be a good start.... πŸ˜‰

silent barnBOT
#

YAML is the mark up language used by Home Assistant, consistent indenting (two spaces per level) is key. Here is a primer, and this explains multi-line templates. For validating YAML see YAML Lint.

inner mesa
#

it's called "Jinja" and there's a ton of documentation on it

#

other links are in the topic

silent barnBOT
clever fulcrum
#

Ok, I'll take a look. The 'templating' page on the HA website doesn't really explain anything I'm afraid.

inner mesa
#

the one above?

clever fulcrum
#

Yes. Id doesn't explain the commands, the structure, memory, variables, arithmetic or anything really it's just vague and meaningless to me I'm afraid...

inner mesa
#

ok

#

it's remarkably detailed

#

and there are endless examples on the forum

silent barnBOT
clever fulcrum
#

Does it show how to subtract 1.5 from the value provides by a sensor? I can't find it...

#

excuse my typing 😦

inner mesa
#

{{ states('sensor.foobar')|float - 1.5 }}

clever fulcrum
#

Thanks RobC πŸ˜„

#

Still can't get anything working. I think I need to start from the beginning in a different environment to get the hang of how this language actually works.

ivory delta
#

Use the Dev Tools while you're experimenting. Don't start by trying to make a template sensor from scratch.

clever fulcrum
#

Jinja Dev Tools?

fossil venture
#

Home Assistant Developer Tools βš’οΈ

#

Specifically the Template Editor.

clever fulcrum
#

I see, that's a starting point. Thanks for that Tom

#

Yay! Got something πŸ˜‰ Thanks guys

autumn grotto
inner mesa
#

no, that's my mistake

#

fixed, thanks for the heads up

autumn grotto
#

All good. Thought it might have been a typo :)

karmic oar
#

Is there a way using a template I can reference the value of an entity from, say, 24 hours ago? Maybe reference a previous logged entry in the DB?

inner mesa
karmic oar
#

I've been using input_number to save the data at different points and then referencing that. It's cumbersome to make some many new entities

inner mesa
#

you can try a custom button card. it might use a local timer

west ice
#

Hi. Using HA supervised since one month ago. Love the idea of HA, but struggling with creating a light template of my liking. Is there anyone that could help me find any tutorials including code etc for creating a simple square light button (I'm using button-card) with info on how to change icon and text positions and size?
Yes, I've read the docs and I'm trying everything out as i go)

fossil venture
west ice
fossil venture
grim flicker
#

i would like to use a filter entity-card to show a card only when the entity (which is a date) matches the current date. Is there a way to use a template in state_filter?

waxen rune
#

@grim flicker Knowing I don't actually answer your question, I have another suggestion: a template binary sensor that defines if the entity date matches today and then a conditional card https://www.home-assistant.io/lovelace/conditional/that only show the entities when the binary_sensor is on.

grim flicker
#

That is indeed a good idea! Thanks

neon peak
#

I have taken two rest api calls and extracted one value from each and am able to refer to them from their original entities. I get one out as a state attribute and can use it in the developer tools template editor as {% x = states.sensor.collected.state | float %} (this reports a string that I can cast | to a float). And the other one is a state attribute and I retrieve it's value from another sensor {% y = state_attr('sensor.factor','multiply') | float %}. Each of these are defined within their own definition in config.yaml under the platform: rest banner.

How do I use those values to present on a card as {{ x * y }}...

I can do all of the above in the template playground, but I don't know how to pull the calculation into a card when that calculation itself isn't defined in my config file

#

I feel like I'm close, but I think I must have to create a platform: template and somehow merge those into a new sensor result??

ivory delta
#

You either use a card that allows templates (limiting you to a subset of custom cards) or you make a template sensor that does the work for you.

#

Check out the integration docs for template sensors.

neon peak
#

ok, so I am close

ivory delta
#

Indeed, you're on the right track.

neon peak
#

ok, I'll keep looking then, I just didn't want to go hunting up the wrong path, thanks

#

for this am I going to use value_template and then insert a multiline jinja piece of code? and does that need to be surrounded in quotes?

ivory delta
#

If you're using multiline, drop the surrounding quotes.

neon peak
#

any chance you could point me to such a template for ref?

inner mesa
neon peak
#

AHHHHHHH >- I saw that page early in putting this togerther, long since forgot about it, thanks! (I have LOTs of tabs open here, it's a nightmare) THANKS!

neon peak
#

I'm still drawing a blank on this. But I think it's ion the reloading, which "YAML configuration reloading" is it for templates?

#

I've clicked them all and none of them appear to be loading templates, unless I'm doing something else wrong (which is certainly on the cards)

#

lol

ivory delta
#

You need to restart HA to pick up new sensors.

neon peak
#

this code works perfectly in the template playground, I get the expected result:

{{ (states.sensor.mined.state | float ) * (state_attr('sensor.ethaud','price') | float)}}

But in the config yaml, it never loads

inner mesa
#

The one that says β€˜template entities’

#

We’d need to see the rest of the sensor definition.

#

And of course

silent barnBOT
#

Always run the configuration check command when you make changes. Don't trust the UI check - it misses some problems.

neon peak
#

my workflow for the rest sensors has worked perfectly, I go through each tab, from file editor, to config check (under server controls), and hit reload, then jump to the dev tools , I have a tab for states and templates..

#

under the YAML reloading, I thought there was a templates section before, but , I'll give it a restart

inner mesa
#

There is a template entities reload option there

#

Also, see the bot message where it says not to trust the UI check

ivory delta
neon peak
#

AHHHHH, this is my first, good point

inner mesa
#

Well, that could be

#

You have to load before you can reload πŸ™‚

neon peak
#

that's a good point, doing it now, thanks. I knew I'd seen it before, I'm currently rebuilding from scratch to try and "clean" it up lol

#

Well I'll be, thanks very much guys 🍺

#

tricks to make unit of measurement appear BEFORE the value?

jagged obsidian
#

put it before the value in the template

neon peak
#

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

#

thx

glad raft
#

Hi y'all... having some trouble getting variables into discord notifier? Am I missing something or isn't it implemented yet?

{
    "message": "Test: {{payload}}" ,
    "target": "666666666666666666"
}
mighty ledge
#

it's implemented

glad raft
#

Soooo, i'm missing the point somewhere... got it.... 'll dig a bit deeper

elder moon
#

i've got the following in my template {{ trigger.event.data.new_state.attributes.friendly_name.split()[-1:] }} but displays "['plant']" string instead of "plant". I have already tried {{ trigger.event.data.new_state.attributes.friendly_name.split()[-1:] | string }} but it doesnt help

#

is there a way of converting a list to string in Jinga2

inner mesa
#

[0]

ivory delta
#

Just for clarity, that's not converting, that's accessing the first element of a list (which in your case happens to be a string).

fiery schooner
#
"d": "{\"list\":[\"Mandag den 12-04-2021\",\"Mandag den 19-04-2021\",\"Mandag den 26-04-2021\",\"Mandag den 03-05-2021\",\"Mandag den 10-05-2021\",\"Mandag den 17-05-2021\",\"Mandag den 24-05-2021\",\"Mandag den 31-05-2021\",\"Mandag den 07-06-2021\",\"Mandag den 14-06-2021\",\"Mandag den 21-06-2021\",\"Mandag den 28-06-2021\",\"Mandag den 05-07-2021\",\"Mandag den 12-07-2021\",\"Mandag den 19-07-2021\",\"Mandag den 26-07-2021\",\"Mandag den 02-08-2021\",\"Mandag den 09-08-2021\",\"Mandag den 16-08-2021\",\"Mandag den 23-08-2021\",\"Mandag den 30-08-2021\",\"Mandag den 06-09-2021\",\"Mandag den 13-09-2021\",\"Mandag den 20-09-2021\",\"Mandag den 27-09-2021\",\"Mandag den 04-10-2021\"]}"

Anyone who could help me getting the first element from this list as a date? (Or even better, converting all the dates to a list of dates, that I can manipulate).

It's a response from a REST call. Thanks!

#

It seems like it's nested JSON with an outer "d" and an inner "list"

#

But everything in the inner part is a string

#

Apparently that is the way ASPNET returns data, by packing it in an outer "d"

ivory delta
#

Let's pretend the entire object is called x, getting to the first comma-separated value inside your example would be something like this:
{{ x.d.list.split(',')[0] }}

#

You can test that in the Dev Tools by setting that JSON to a variable and then playing around.

fiery schooner
#

The problem seems to be that the inner list is actually a string, so I need to parse it as JSON

ivory delta
#

Although judging by all the escape characters, you might have to parse the inner stuff.

#

Aye

fiery schooner
#

Googling returns nothing

ivory delta
#

Same idea, just pipe it through tojson first.

#

You check the pins in here yet? πŸ˜‰

#

HA templates just use Jinja and I know the built-in filters are pinned.

fiery schooner
#
"{\"list\":[\"Mandag den 12-04-2021\",\"Mandag den 19-04-2021\",\"Mandag den 26-04-2021\",\"Mandag den 03-05-2021\",\"Mandag den 10-05-2021\",\"Mandag den 17-05-2021\",\"Mandag den 24-05-2021\",\"Mandag den 31-05-2021\",\"Mandag den 07-06-2021\",\"Mandag den 14-06-2021\",\"Mandag den 21-06-2021\",\"Mandag den 28-06-2021\",\"Mandag den 05-07-2021\",\"Mandag den 12-07-2021\",\"Mandag den 19-07-2021\",\"Mandag den 26-07-2021\",\"Mandag den 02-08-2021\",\"Mandag den 09-08-2021\",\"Mandag den 16-08-2021\",\"Mandag den 23-08-2021\",\"Mandag den 30-08-2021\",\"Mandag den 06-09-2021\",\"Mandag den 13-09-2021\",\"Mandag den 20-09-2021\",\"Mandag den 27-09-2021\",\"Mandag den 04-10-2021\"]}"
#

This is the output of tojson

#

So it looks like the output of tojson is still a string

ivory delta
#

The output of all templates is a string πŸ˜‰ Do the rest of your processing and see what you get back.

fiery schooner
#

trying to access list just returns an empty string

#

or maybe i just don't know how to acess the result of tojson

#

What do i pipe it into to access the dict elements?

ivory delta
#

It should just be something like this but I'm seeing the same thing as you:

{% set list = (x.d | tojson).list %}
{{ list }}```
fiery schooner
#

Yeah it seems like it keeps the object as a string and does not want to parse it as json

ivory delta
#

I'll let someone smarter than me have a go.

fiery schooner
#

This was so close to being very easy, but then of course they have to do this πŸ˜›

mighty ledge
#
{% set value = "{\"list\":[\"Mandag den 12-04-2021\",\"Mandag den 19-04-2021\",\"Mandag den 26-04-2021\",\"Mandag den 03-05-2021\",\"Mandag den 10-05-2021\",\"Mandag den 17-05-2021\",\"Mandag den 24-05-2021\",\"Mandag den 31-05-2021\",\"Mandag den 07-06-2021\",\"Mandag den 14-06-2021\",\"Mandag den 21-06-2021\",\"Mandag den 28-06-2021\",\"Mandag den 05-07-2021\",\"Mandag den 12-07-2021\",\"Mandag den 19-07-2021\",\"Mandag den 26-07-2021\",\"Mandag den 02-08-2021\",\"Mandag den 09-08-2021\",\"Mandag den 16-08-2021\",\"Mandag den 23-08-2021\",\"Mandag den 30-08-2021\",\"Mandag den 06-09-2021\",\"Mandag den 13-09-2021\",\"Mandag den 20-09-2021\",\"Mandag den 27-09-2021\",\"Mandag den 04-10-2021\"]}" %}
{% set value = value | from_json %}
{{ value.list }}
mighty ledge
#

you just had them backwards

mighty ledge
fiery schooner
#

@mighty ledge ```json
{
"d": "{"list":["Mandag den 12-04-2021","Mandag den 19-04-2021","Mandag den 26-04-2021","Mandag den 03-05-2021","Mandag den 10-05-2021","Mandag den 17-05-2021","Mandag den 24-05-2021","Mandag den 31-05-2021","Mandag den 07-06-2021","Mandag den 14-06-2021","Mandag den 21-06-2021","Mandag den 28-06-2021","Mandag den 05-07-2021","Mandag den 12-07-2021","Mandag den 19-07-2021","Mandag den 26-07-2021","Mandag den 02-08-2021","Mandag den 09-08-2021","Mandag den 16-08-2021","Mandag den 23-08-2021","Mandag den 30-08-2021","Mandag den 06-09-2021","Mandag den 13-09-2021","Mandag den 20-09-2021","Mandag den 27-09-2021","Mandag den 04-10-2021"]}"
}

mighty ledge
#

ok, so

fiery schooner
#

The input is wrapped in an outer d, so value_json.d would still return a string, right?

#

It's a REST sensor

mighty ledge
#
{% set value_json = value_json.d | from_json %}
{{ value_json.list }}
fiery schooner
#

I'll try that πŸ‘

ivory delta
#

This'll make it tricky:

TemplateAssertionError: no filter named 'fromjson'

mighty ledge
#

forgot _

#

edited

fiery schooner
#

Does any of you know if it's possible to take that list of dates and add it to a calendar?

#

My other idea for that would be to write a small python program that just presents a webserver that serves an ics file with the data

ivory delta
#

If you're going to write something custom, maybe go with CalDAV

fiery schooner
#

Ah yeah probably a better idea, I just don't know a better way to present multiple dates that goes into the future

ivory delta
#

It all depends what you want to do with it. If you come up with a way to get that list in a format you can work with, you might be able to make do with a template sensor and have other things take care of the logic around 'next date, following date, etc'

fiery schooner
#

The good news is that @mighty ledge 's solution worked, so now I at least have the "next" date in a sensor

wicked smelt
#

I'm trying to get a automation to work with a template condition. I have one light and I want to check if the brightness is equal to one of the two values(input_number), but there is not possible to use XOR. Any suggestions?

fiery schooner
#

So thanks guys, now I have something to build upon!

ivory delta
#

You could make it a one-liner but I broke it out for legibility. Essentially an XOR of two things is just checking that there is only a single thing that evaluates to true.

wicked smelt
#

Nice, thank you. Will try that! πŸ™‚

ivory delta
#

Last line could equally be this (but it wouldn't scale as well with multiple values):
{{ (a and not b) or (b and not a) }}

#

Not sure you actually need to emulate an XOR in your scenario either:
{{ is_state_attr('light.a', 'brightness', 'value a') or is_state_attr('light.a', 'brightness', 'value b') }}

wicked smelt
#

that could also work

edgy umbra
#

Anyone knows why this is not working for my custom:button-card? πŸ™‚

#
  - operator: template
    value: |
      [[[ 
        return 
          states['sensor.recycleapp_xxxx_gft'].attributes.Days-until < '2' 
      ]]]
    icon: 'mdi:delete-emtpy'
  - operator: default
    icon: 'mdi:delete'```
ivory delta
#

Until you say what it's supposed to do and what it's actually doing, it'll be hard for anyone to explain the difference in behaviour.

edgy umbra
#

Well i'm trying to change the icon based on the attribute of the sensor. If there is a trash collection in the next 2 days set mdi:delete-empty, otherwise show mdi:delete. πŸ™‚

unique elm
#

I have been working on changing the icon for my battery status, based on @fossil venture above I looked at using 'customize' which I have used in the past. However when I put my ```
sensor.ups_battery_capacity:

into customize it fails and says "Incorrect type:  Expect Object".  Where am I going wrong?
inner mesa
#

@edgy umbra You're quoting "2", turning it into a string.

#

if the attribute is an integer, you should just use 2

unique elm
#

I can display the value of sensor.ups_battery_capacity on an entity card just fine. It comes from:

  - platform: snmp
    host: 192.168.1.7
    baseoid: .1.3.6.1.4.1.3808.1.1.1.2.2.1.0
    community: public
    port: 161
    name: UPS Battery Capacity
    value_template: '{{ (value | float) }}'
    unit_of_measurement: "%"
edgy umbra
inner mesa
#

what is the value of the attribute?

edgy umbra
#

This is the sensor info from dev tools.

#

sensor.limburg_net_afvalophaling_gft 20-04-2021 Wastecollector: limburg.net
Hidden: false
Sort-date: 20210420
Days-until: 9
unit_of_measurement:
friendly_name: limburg.net Afvalophaling gft
icon: mdi:delete

inner mesa
#

you have a typo: icon: 'mdi:delete-emtpy'

#

if that doesn't work, try replacing the states[] bit with 9 and make sure that works

edgy umbra
#

Sorry i fixed that allready, this don't seem to change the icon.

inner mesa
#

you may need to cast it to float()

edgy umbra
#

Also tried changing it to 9

edgy umbra
inner mesa
#

no, I mean doing float(states[xxx].attributes..xx)

#

if you write return 9 < 2 and it doesn't use the default case, then you have other issues

ivory delta
#

cough parseFloat cough

inner mesa
#

or that

#

JS is not my first language

edgy umbra
#

Guy's sorry but i'm not so good at this, i have now this but it gives a error in the card layout.

#
  - operator: template
    value: |
      [[[ 
        float(states[sensor.limburg_net_afvalophaling_gft].attributes.Days-until) return 9 < 2
      ]]]
    icon: 'mdi:delete-empty'```
#

Error: ButtonCardJSTemplateError: SyntaxError: Unexpected token 'return' in 'float(states[sensor.limburg_net_afvalophaling_gft].attributes.Days-until) return 9 < 2'

inner mesa
#

that's not what I meant at all πŸ™‚

ivory delta
#
    value: |
      [[[ 
        return parseFloat(states[sensor.limburg_net_afvalophaling_gft].attributes.Days-until) < 2
      ]]]```
inner mesa
#

that's better

#

my point was to simplify the case until you get a rational result, and then add stuff back

edgy umbra
#

Now it gives this error. πŸ™‚

#

ButtonCardJSTemplateError: ReferenceError: sensor is not defined in 'return parseFloat(states[sensor.limburg_net_afvalophaling_gft].attributes.Days-until) < 2'

inner mesa
#

you removed the quotes for some reazon

#

oh, it's because Mono did

#

you're absolved

ivory delta
#

No...

#

Don't blame me, I copypastad his bad code.

edgy umbra
#

πŸ˜„

inner mesa
#

oh, nevermind. you're based on the hook

edgy umbra
#

Sorry guy's πŸ™‚

#

I have now this.

inner mesa
#

you keep abusing that apostrophe

edgy umbra
#
  - operator: template
    value: |
      [[[ 
        return 
      parseFloat(states[sensor.limburg_net_afvalophaling_gft].attributes.Days-until) < 9
      ]]]
    icon: 'mdi:delete-empty'```
ivory delta
#

Whi'ch ap'ost'rophe?

inner mesa
#

still missing the quotes

#

you have too many quotes in some places, too few in others

edgy umbra
#

Can you please show a example? πŸ™‚

#

I'm so bad at this i'm sorry.

inner mesa
#

you started with this:

#

states['sensor.recycleapp_xxxx_gft'].attributes.Days-until < '2'

#

and you then removed all the quotes.

edgy umbra
#

Oh i thought i just used the code from mono. πŸ™‚

inner mesa
#
state:
  - operator: template
    value: |
      [[[ 
        return 
      parseFloat(states['sensor.limburg_net_afvalophaling_gft'].attributes.Days-until) < 9
      ]]]
    icon: 'mdi:delete-empty'
#

anyway

edgy umbra
#

Don't seems to work, still showing the mdi:delete icon

inner mesa
#

dunno

#

here's one of mine:

#
                      state:
                        - value: "[[[ return states['automation.away_timer'].state === 'on'; ]]]"
                          operator: 'template'
                          name: "[[[ return parseInt(states['input_number.away'].state) + 's'; ]]]"
                          icon: "mdi:timer"
                          color: yellow
                        - value: "[[[ return parseInt(states['input_number.away'].state) === 0; ]]]"
                          operator: 'template'
                          name: "Away"
                          icon: "mdi:home-export-outline"
                          color: "red"
                        - operator: 'default'
                          color: green
                          name: "Home"
                          icon: "mdi:home"
#

works fine

#

maybe it doesn't like the "-" in the attribute name 🀷

#

you could do states['sensor.limburg_net_afvalophaling_gft'].attributes['Days-until']

edgy umbra
#

Thanks tried but don't seems to work, i gues there is something not good with the name of the attribute, i have another card for my thermostat which works fine with the same template layout.

#

Instead using a - in the attribute name the thermostat is using _ so maybe there is the difference

inner mesa
#

you can try using that attribute as the name to see that it resolves to something useful

edgy umbra
#

Think i'm giving up for now, taked way to long. πŸ™‚

#

Thanks both for the help and assist! πŸ˜‰

fossil venture
unique elm
#

Thanks @fossil venture . This is now working.

#

Woops. I take that back. The icon has now changed to a 100% full battery and not my battery charging icons

fossil venture
#

The device class uses mdi icons.

edgy umbra
inner mesa
#

weird. I guess it just ignores the "-"

edgy umbra
#

No i mean in the code of the integration. πŸ™‚

unique elm
edgy umbra
#

I have some different battery cards with the same you want

unique elm
#

Entities card

#
type: entities
entities:
  - entity: sensor.ups_model
    name: Model
    icon: 'mdi:power-plug'
  - entity: sensor.ups_status
    name: Status
    icon: 'mdi:power'
  - entity: sensor.ups_battery_capacity
    name: Battery Capacity
edgy umbra
#

That will do it all for you without any extra code needed

unique elm
#

Its my UPS so has lots of UPS specific information on the card

edgy umbra
#

Than use a custom:auto-entities card

#

With a template

#

Thats the way i'm doing it

silent barnBOT
#

@unique elm 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.

unique elm
#

@edgy umbra Do you have code you could share so it is a little clearer for me?

edgy umbra
#

Will share it in a minute.

unique elm
#

I installed 'battery-state-card' with HACS. Restarted HA. Tried it on an entities card and its says "Custom element doesn't exist: battery-state-card." Yet is shows under HACS frontend as installed (mind you it calls it 'battery state card/entity row"

edgy umbra
#

Check my template sensors and card. It will show all mdi:battery icons, changing colors on battery %, shows charging icon if phone is charging and turns color to yellow if low power mode is on.

unique elm
#

Trying it now

edgy umbra
#

Be sure to install custom:auto-entities card....

edgy umbra
inner mesa
#

yes, you'd need that

#

that was in almost all of the quoted code

#

that was just a snippet

edgy umbra
#

My bad, have changed the integration code back to normal and used that template because if the integration will be ever updated my template with fixed code will no longer work.

inner mesa
#

right

unique elm
#

I have done this. First "sensor.ups_battery_capacity no longer works or shows anything. There is a new sensor, "ups_battery_capacity_2" and this shows my battery level as a value but has no icon

#

I added this to 'sensors" in my configuration.yaml

  - platform: template
    sensors:
      ups_battery_capacity:
        unit_of_measurement: "%"
        value_template: "{{ states('sensor.ups_battery_capacity') }}"
        friendly_name: "Battery Capacity"
        icon_template: >
          {% set level = states('sensor.ups_battery_capacity') | float | multiply(0.1) | round(0,"floor") | multiply(10)| round(0) %}
            mdi:battery-charging-{{level}}
#

since a UPS battery is always charging I skipped all of the other options

inner mesa
#

what does that template show in devtools -> Templates?

#

you may need ">-" instead of ">"

unique elm
#
ups_battery_capacity:
        unit_of_measurement: "%"
        value_template: "unknown"
        friendly_name: "Battery Capacity"
        icon_template: >
          
            mdi:battery-charging-0
inner mesa
#

well, that doesn't exist

#

that calculation must be wrong. debug it bit by bit

#

didn't you say that you now have that sensor with "_2" on the end?

#

I have done this. First "sensor.ups_battery_capacity no longer works or shows anything. There is a new sensor, "ups_battery_capacity_2" and this shows my battery level as a value but has no icon

#

so...

unique elm
#

Yep, that did it. I now have:

ups_battery_capacity:
        unit_of_measurement: "%"
        value_template: "{{ states('sensor.ups_battery_capacity_2') }}"
        friendly_name: "Battery Capacity"
        icon_template: >
          {% set level = states('sensor.ups_battery_capacity_2') | float | multiply(0.1) | round(0,"floor") | multiply(10)| round(0) %}
            mdi:battery-charging-{{level}}

and it correctly works in developer...template

#

It also works on my entity card if I display 'ups_battery_capacity' but not if I display 'ups_battery_capacity_2' I get confused as to how the naming works, is this because the template is called 'ups_battery_capacity'?

inner mesa
#

you're probably causing a name collision

unique elm
#

Should I name the template something else?

inner mesa
#

if you want, and don't want to cause a naming collision

unique elm
#

I never explicitly named a sensor 'ups_battery_capacity' under 'snmp' it seems to have inherited this name as I had:

    host: 192.168.1.7
    baseoid: .1.3.6.1.4.1.3808.1.1.1.2.2.1.0
    community: public
    port: 161
    name: UPS Battery Capacity

which I assume used 'name' and just added the underscores?

#

Then when I added the template you gave me I assume HA auto renamed the snmp sensor as 'ups_battery_capacity_2"

inner mesa
#

yes

#

that's how it names things

unique elm
#

I will leave it as it is as it is working. Thanks for your help. I might add your code that once it reaches 100% it probably isn't charging. In fact if I want to spend a few hours I could use the status and if it is 'on battery' I don't use the charging icon and if 'online' it does. That will keep me busy for a while πŸ™‚

unique elm
#

I tried this in 'developer tools...templates' and it works

      ups_battery_capacity:
        unit_of_measurement: "%"
        value_template: "{{ states('sensor.ups_battery_capacity_2') }}"
        value_template: "{{ states('sensor.ups_status') }}"
        friendly_name: "Battery Capacity"
        icon_template: >
          {% set level = states('sensor.ups_battery_capacity_2') | float | multiply(0.1) | round(0,"floor") | multiply(10)| round(0) %}
          {% set status = states('sensor.ups_status')%}
          {% if is_state('sensor.ups_status', 'onLine') %}
            mdi:battery-charging-{{level}}
          {% elif states('sensor.ups_status' != 'onLine') %}
              mdi:battery-{{level}}
          {% endif %}

But in configuration.yaml I pasted this back in and it says 'error duplicate key' on both lines where I have 'value_template'

inner mesa
#

well, yeah

#

you can't have two value_template lines

#

a sensor has one value

unique elm
#

I thought 'value_template' was a command but I probably don't need it right?

inner mesa
#

it determines the state of the sensor

#

you need exactly one

unique elm
#

This will work, right?

      ups_battery_capacity:
        unit_of_measurement: "%"
        value_template: "{{ states('sensor.ups_battery_capacity_2') }}"
        friendly_name: "Battery Capacity"
        icon_template: >
          {% set level = states('sensor.ups_battery_capacity_2') | float | multiply(0.1) | round(0,"floor") | multiply(10)| round(0) %}
          {% if is_state('sensor.ups_status', 'onLine') %}
            mdi:battery-charging-{{level}}
          {% else %}
              mdi:battery-{{level}}
          {% endif %}
inner mesa
#

your spacing in teh template is a little inconsistent, but it might work

small hatch
#

hi all i scraped my power usage off my local provider. The data is present the data table and update it daily. So I cant find a way to scrape only single day. What i did was scraped the entire table and and format into an 2 column array [[date, value] ,[date, value],[........]x 20. I'm going to send this data array to hassio via mqtt, but have no idea how to template it on hassio side.

#

let say i know how to template if it a single value but the data is send over as an array so i have no idea where to start.

unique elm
inner mesa
#

@small hatch A similar sounding issue was described in this channel earlier today

small hatch
#

oh let me check the history thank. did he/she got it working?

inner mesa
#

they're all unique, but perhaps it will point you in the right direction

#

and yes

small hatch
#

haha thank last long as it give me some hint on how to deal with data array it should be ok.

night warren
#

Howdy, can someone help with a webhook trigger

service: notify.mobile_app_pixel_5
data:
title: Incoming Call
message: 'Call from {{trigger.payload}}'

For some reason, the payload is empty

fossil venture
#

Can we see the trigger please?

silent barnBOT
fossil venture
#

It's trigger.data not trigger.payload

silent barnBOT
night warren
#

I think I tried that too.... Let me try again though

#

Yeah - I only get a 'Call from'

fossil venture
#

Yeah I just read my own link. trigger.data has to be in form format. The only other option for webhook triggers is trigger.json and your data does not appear to be in json format either. So I don't know what you can do πŸ€·β€β™‚οΈ

night warren
#

Ah,.....I tried trigger.json but no joy - just in case

small hatch
#

i not sure is it issue with my data array that is being push over or hassio template. Or both

ivory delta
#

Can't see the image you shared. Also, please don't share text as images - just share both in a paste tool.

small hatch
ivory delta
#

And stop sharing images πŸ€¦β€β™‚οΈ

small hatch
#

ok but i just want to know if the data is format correctly

#

im ok on the node red side. just hassio template side im dont quite know how to handle the data

#

i got it working if i just send over one single data point but not sure how to get hassio read and store array of data point

#

i want to use the data to show a graph vs my solar production graph

ivory delta
#

Share only the data you're trying to use in the template. None of the extra surrounding information.

#

I'm not interested in all the other lines about dates, msgid, etc.

#

And seeing array[21] doesn't help if I don't know what's inside the array. If all you want to do is access the first entry in an array, you just use [0] to do that.

small hatch
#

the array as this [[date: "date", usage: float_value],[...]]

#

if i send just one data point explain just [date: "4/1/2021, usage: 17] i can get it template will so what i can only get value state templated but still having issue trying to get date to be templated as attributes

#

but if i send the entire array over i get no value at all

#

or should the data array be formatted as [[date, usage],["date",float_value],["date", float_value].....]

ivory delta
#

Neither look like sensible data though.

small hatch
#

yes just an two column array in this case is a 2 x 21 matrix. first col is date: "m/d/yyyy" and 2nd is usage: float_value

#

i think i'll give up on the array and make it simple and just populate the sensor daily from now on by sending the last array value point from now on. So how do i get the date template as an attributes? If let say the data is send over like [date: "4/1/2021", usage: 17]. via this template https://ghostbin.co/paste/k57bfas

rose brook
#

Not sure this is correct channel but could someone help me parse this?

</ha-icon><span>: ${states['sensor.1_iphone'].attributes['Street Number','Street','City']} </span>`

I am trying to get it to display like:
Street Number Street
City State

#

better yet... a way to parse 1 attribute that has too much info...

Formatted Address: '555 lost St, broken dreams, AA 55555, USA'

555 lost St
broken dreams, AA

So in displays on two lines but no zip or country.

small hatch
#

try doing per each attribute.. </ha-icon><span>: ${states['sensor.1_iphone'].attributes.streetnumber}, ${states['sensor.1_iphone'].attributes.street}, ${states['sensor.1_iphone'].attributes.city} </span>`

rose brook
small hatch
#

check the attributes name of your sensor maybe is written as street_number

rose brook
#

no such luck its...

Street Number: 555-500
#

actually it shows as undefined, undefined, undefined

small hatch
#

do you actually have all those attributes in your sensor

rose brook
#

yea

#
Street Number: 555-500
Street: Hopeless Street
City: Broken Dreams
Postal Town: null
Postal Code: 55555
State: Screwed
#

I swear just when I think I get things figured yaml finds another way to screw with me.

small hatch
#

city and street doesnt have spacing and it not show up?

rose brook
#

SMH so city and state show up when i do caps So City State instead of city state

#

but nothing I do with Street Number works.

#

ah gotta do ['Street Number"] thank you

#

dont under stand why the return of the attribute "Formatted Address:" shows 555 street etc... but the fracking attribute Street Number: shows a range like 555 - 500

#

smh

#

oh well... this helps alote thank you Moto!

small hatch
#

no problem im trying to figure some of these thing out too haha.

rose brook
#

Drives me crazy as its hard to ask Mr google when you dont know what to search ya know.

rose brook
#

anyone know how I could get this to txt wrap?

#
 location: |
    [[[
      return `<ha-icon
        icon="mdi:map"
        style="width: 12px; height: 12px; color: red"> 
        </ha-icon><span>: ${states['sensor.g3_1_iphone'].attributes['Formatted Address']}<span>`
inner mesa
bronze horizon
#

Using the template {{ states.sensor.emby_latest_tv_shows.attributes.data }} gives me what appears to be a list of json objects, and the template editor says "Result type: list", so I thought {{ states.sensor.emby_latest_tv_shows.attributes.data.1 }} would give me the 2nd json object, but it instead gives me the 2nd character. Tried a few different things from the forums/doco but no luck... Is it possible to pull the Nth list object rather than the Nth character?

inner mesa
#

try {{ state_attr('sensor.emby_latest_tv_shows', 'data')[1] }}

#

what are you trying to do with it? The upcoming media card knows how to parse that stuff, and that integration is designed to feed it

#

I wrote an integration for another media source that has the same format

#

here's an example of my attributes, with a format string and one show:

#

my template above works fine to extract the second item in the list

bronze horizon
#

Yah, I've got it displaying nice enough in the upcoming media card, but I'd like to use the button-card to make individual cards for each entry that can be arranged and scrolled horizontally.

#

Giving that template a shot now, though

inner mesa
#

it's almost like the integration is creating a list of strings, rather than dicts

#

but if upcoming_media_card is able to parse it, it's doing its primary job and there's little incentive to "fix" it. the integration that I wrote does the right thing, but it's for Channels DVR

#

you should submit a PR to fix it πŸ™‚

#

why the hell is it doing this?

#

attributes["data"] = json.dumps(card_json)

#

there's your problem right there

#

it makes a nice dict and then turns it into a string

bronze horizon
#

Interesting, maybe I could fix it since that guy puts a prospective solution in there.

inner mesa
#

go fix that

#

You might be able to use |from_json in the template to parse it. It’s just silly

#

Basically, a json.loads

bronze horizon
#

Hah that fix worked.

inner mesa
#

Ha, didn’t even see that πŸ™‚

#

I just looked through the code.

#

Indeed, that should do it

bronze horizon
#

Kinda bummed but there doesn't seem to be a way to slow down the transitions, I had a news ticker vibe in mind, but that's not a #templates-archived issue!

silent barnBOT
stone lintel
deft timber
#

You could create several REST sensor giving a value_template to get what you want in the json

stone lintel
#

Oh cool thanks, will give that a go!

rugged bone
#

I am trying find the issue with this template.

#
2021-04-13 12:34:24 INFO (MainThread) [homeassistant.components.mqtt.binary_sensor] No matching payload found for entity: motion_04 with state topic: tele/zigbridge_01/zb_motion_03/SENSOR. Payload: '{"ZbInfo":{"zb_motion_03":{"Device":"0x4ED2","Name":"zb_motion_03","IEEEAddr":"0x00124B002267B6F5","ModelId":"MS01","Manufacturer":"eWeLink","Endpoints":[1],"Config":["A01.1","I01"],"ZoneType":13,"ZoneStatus":12592,"Occupancy":0,"Reachable":true,"BatteryPercentage":100,"LastSeen":1043014,"LastSeenEpoch":1617288461,"LinkQuality":21}}}', template output: 'unknown', with value template 'Template("{% if value_json is defined and value_json.ZbReceived is defined %}
    {% if value_json.ZbReceived.zb_motion_03.Occupancy == 1 %}ON{% else %}OFF{% endif %}
{%- else %}
  {{ states('binary_sensor.motion_04') }}
{%- endif %}")'
#

ZbInfo is not what I am looking for its ZbReceived, when I run this template test it works fine.

#

but in the sensor it returns 'unknown'

#

can anyone help me find out what?

silent barnBOT
naive hatch
#

Basic template question: I have a template switch, but it's state usually doesn't correspond with the two switches it controls. Is there a way to set the state of the switch to the same as one of the switches? Code is above ^ (Thanks HassBot :)

#

*I figured it out, using value_template

shell ferry
#

Could someone help me with this script/templating? I'm not sure whether this can be done in a way I'd like to achieve, but I'm running out of ideas anyway.
The script: https://paste.ubuntu.com/p/rRMH9W5DT9/
The error: Invalid config for [script]: not a valid value for dictionary value @ data['sequence'][1]['entity_id']. Got None. (See /config/configuration.yaml, line 18).
I've tried pretty much every possible way I just could think of, to define a variable, concatenating 2 strings + 1 script variable and later in the script use the newly defined variable as an entity_id

#

I have 2 devices, such as fan.xiaomi_blaa_blaa_bedroom and fan.xiaomi_blaa_blaa_another and the sensors are alike (sensor.bla_bla_bedroom_bla and sensor.bla_bla_another_bla), so I would like to avoid repeating myself (DRY) and just pass bedroom or another as a script variable and within the script I'd like to "construct" the entity id's based on this variable.
I know I could just pass 2 separate variables for the script, containing the entity_id's themselves, but I'd like to avoid that, to "keep my codebase at least slightly more maintainable", if it's possible

mighty ledge
shell ferry
#

I know it's telling me my entity_id: "{{ entity_id }}" is the issue

#

that's why I'm asking can this even be achieved or not

mighty ledge
#

ok, but do you know which one?

#

1 is correct, the other is not

#

you can copy the 1 to the other and it will work for both

#

but the error is telling you which one is invalid

shell ferry
#

but they're both the same aren't they?

mighty ledge
#

nope

#

you need to expand what you're looking at

#

what's different about the fan.set_preset_mod service call and the xiaomi_miio.fan_set_favorite_level service call?

shell ferry
#

other one has target, other one don't

mighty ledge
#

Alright, so which one is correct? The error tells you which one is not

mighty ledge
#

Nope, templates are not allowed in one of the versions, I'm trying to get you to read the error message so that you can decipher this in the future

shell ferry
#

well it says the sequence 1 entity_id is the problem

mighty ledge
#

exactly, ok, so which one is 1? This is something you may not know

shell ferry
#

meaning the latter, if the indexes in the error starts from 0, as in programming usually

mighty ledge
#

lists in python start at 0

#

yes

#

So, to recap, use the target version as that is the correct method

#

with templates

#

without templates both are correct

#

Also, theres a 3rd option. You can put entity_id inside data/data_template

shell ferry
#

oh

mighty ledge
#

and templates will work with that as well

shell ferry
#

that'd be cleaner/cleanest

mighty ledge
#

so, templates only work with target, and data/data_template.

#

also, you should switch data_template to data

#

that's no longer needed

shell ferry
mighty ledge
#

yep

shell ferry
#

nice!

mighty ledge
#

but you should switch

    - service: xiaomi_miio.fan_set_favorite_level
      data_template:
#

to

#
    - service: xiaomi_miio.fan_set_favorite_level
      data:
shell ferry
#

ah

#

at least no more error! thanks a bunch, gonna give the script a shot soon-ish, once I'm done eating πŸ˜… on a side note, that's a bit confusing that there's like 3, if not even more ways to define the exact same thing (and that the documentations are not up-to-date either(?)). the script worked like a charm with hard coded entity_id's before, that's why I was puzzled that why is it not working and that am I trying to do something that shouldn't even be possible

mighty ledge
shell ferry
#

ah, so I should start using the target one then instead. good to know :)

mighty ledge
#

all 3 will exist forever

#

so, it really doesn't matter which one you use

#

entity_id at the root level is the only limited one

smoky idol
#

Hi guys. If I want to make this - 'Home'
To this - Home
Can I use this template:
'{{ trigger.to_state.state | regex_replace(find="'", replace="") }}'

Thanks!

shell ferry
mighty ledge
mighty ledge
smoky idol
#

long story... I extract the state to an Input_text, and it saved with the quotes

#

I am trying to build a way to get updates of my devices when they change locations. because each have more than one GPS trackers, every update I get notified... even if they dont change location (Moved from Home to Home)

So, I created an automation to act as a proxy...

ivory delta
#

That all sounds like a waste of time. There are ways to avoid getting notifications when the new state is the same as the old state.

smoky idol
#

Well, I asked several times about it and got the same answers. One even built a custom component to solve it...

But it looks like my template is still not working. The quotes are still there

ivory delta
#

A custom component to do something HA can do natively? That also seems like a massive waste of time.

#

What device tracker is reporting locations?

shell ferry
#

Can't you just group device_trackers for whatever you want and then create a trigger such as:

trigger:
  - platform: state
    entity_id: group.devices_to_track
    to: "not_home"
#

and groups as:

devices_to_track:
  name: Devices to track
  entities:
    - device_tracker.device1
    - device_tracker.device2
#

not sure if I even understood correctly...

#

or use person if you want to bind multiple devices into one person and track if that person is home/at work/at school/not in predefined location

smoky idol
#

The person entity suffer from the same problem. it changes state every time a GPS tracker updates. Tried it before... even if it in the same location....

But grouping all the GPS tracker for each device might do the same as what I am trying do and mediate between the changes and the notifications. I will try it

ivory delta
#

it changes state every time a GPS tracker updates. Tried it before... even if it in the same location....
Wrong, wrong, wrong.

#

It might change attributes but the state isn't changing. And if your automation is triggering because you're listening to all changes, that's a flaw in your automation.

#

All it takes to ignore changes that have the same before and after value for state is a simple template condition that checks the two are different.

#

{{ trigger.from_state.state != trigger.to_state.state }}

#

Job done.

sonic nimbus
#

can I create a sensor which will be telling me a state (on, off) based on some template?

shell ferry
#

I have a feeling you're doing something wrong, but as I don't know for a fact, I don't know. at least it works for me. I have 4 devices bind to me, 2 for my wife and 2 for our kid. for example, the "left home" gets triggered only if none of the devices is saying "im home" and vice versa: "arrived home" triggers if at least one of all the bound devices tells HA "i'm home". and the very same "Kirbo is at home" doesn't get triggered more than once, as long as at least one of all of my 4 device_trackers (gps from phone, gps from watch, unifi presence for phone and unifi presence for watch) states that they're home.

smoky idol
shell ferry
#

The examples I wrote above

smoky idol
#

Have you used the person state trigger and all the trackers are inside it?

formal stone
shell ferry
smoky idol
#

so thats maybe my problem. I tried to avoid using many automations so I 'templated myself to complicated death'. I used one automation and tried to identify each event and build the notification according to it...

sonic nimbus
#

why this sensor returns off status

#
  sensors:
    kitchen_stove_state:
      friendly_name: "Kitchen Stove Status"
      device_class: Power
      value_template: >-
        {{ states('sensor.kitchen_stove_energy_power') | float > 90 }}```
shell ferry
#

well, my example might be one way of doing the same thing. there could be easier ways as well, idk.. at least you could add multiple triggers, something like: https://paste.ubuntu.com/p/wyFyWhFTFr/

sonic nimbus
#

{{ states('sensor.kitchen_stove_energy_power') | float > 90 }} is true..its not false

shell ferry
shell ferry
humble beacon
#

Ludeeus told me, to add mor guards to the automation. But I don’t know how and what.

shell ferry
inner mesa
#

@humble beacon Do you know when you see that error message? It implies that the automation is trigger for something other than an event, but I don't see how that can happen

#

this is the code that fires the event:

#
            hacs.hass.bus.async_fire(
                "hacs/repository",
                {
                    "action": "registration",
                    "repository": repository.data.full_name,
                    "repository_id": repository.data.id,
                },
            )

#

it makes me think that that's not the automation that's causing that error

rose brook
#

Can anyone help with this?

#
  ln1: |
    [[[
      return `<img
        src='https://developers.google.com/maps/images/maps-icon.svg'
          style="width:12px;height:12px">
        </ha-icon> ${states['sensor.g3_1_iphone'].attributes.Street}, ${states['sensor.g3_1_iphone'].attributes.City}<br>${states['sensor.g3_1_iphone'].attributes.State}, ${states['sensor.g3_1_iphone'].attributes['Postal Code']}`
    ]]]
#

for some reason the text after the <br> is centered

#

but this...

    ln1:
      - font-size: 11px
      - align-self: start
      - justify-self: start
      - padding-botom: 4px

... tells it to align with start.

humble beacon
thorny snow
#
platform: numeric_state
entity_id: light.pc_light
value_template: '{{ state.attributes.brightness }}'
above: '253'

trigger: In 'numeric_state' condition: attribute 'brightness' (of entity light.pc_light) does not exist

#

Can anyone help to write a template based on the brightness. Would sincerely appreciate it! THank you

dawn relic
#

Is anyone familiar with the scrape sensor? For some reason, they dont work anymore

#

My scrape sensors were working fine, but after a restart they read 0.0

thorny snow
#

Just disappeared on me

deft timber
#

yes I removed it πŸ™‚ I suggested you use the tag attribute:, this is needed for your automation to trigger when only the attribute changes

#

what surprise me a it is that the error mentions a condition. Could you share your whole automation?

thorny snow
#

I had the attribute and it was giving me the same error

#

I think the attribute only works if the light is already on. I’ll post it in 10 minutes l, just stepped away from pc I’m sorry

deft timber
#

indeed you are right. If the light is off -> no attribute brightness

#

you could then replace the value_template with smth like {{ state.attributes.brightness if 'brightness' in state.attributes else 0 }}

thorny snow
#

I’ll give it a shot. Thanks Slash

tough ice
#

OK, gurus, I need help in making this code more compact. What I am trying to do is compare the current temp of a thermostat to the set temp and return True/False. I'm sure there are more effective ways of doing this, hopefully a single line with piping.
https://paste.ubuntu.com/p/fq4n7F2FQn/

dreamy sinew
#

looks like you're filtering down to a single entity already based on that name

#

could drop the loop completely and just use that one entity

#

or do you have multiple entities with the name HW?

inland hazel
#

@thorny snow A shorter and more readable version of this could be written as {{ state.attributes.brightness|default(0) }}

inland hazel
#

I think the shortest you can get it without knowing the entity ID is:

{% set hw = states|selectattr('name', '==', 'HW')|list|first %}
{{ hw.attributes.current_temperature|default(0)|float < hw.attributes.temperature|default(0)|float }}

If there is more than one entity named 'HW', it will take only the first one into consideration.

weary drift
#

I have a cover thats stuck at opening/closing instead of change to opened/closed. I guess it is possible to create a template where it sets value based on position?

grim flicker
#

Im trying to get this to work:

  url: http://192.168.178.54:16021/api/v1/token/effects
  method: PUT
  payload: >
    {  "write" : {"command": "display", "animType": "static", "animData": "18 
    {% set paneel1 = {{paneel1_rood}} %}
    {% if paneel1 != '' %}
      36776 1 {{paneel1_rood}} {{paneel1_groen}} {{paneel1_blauw}} 0 20 
    {% endif %}```
#

but the line {% set paneel1 = {{paneel1_rood}} %} is giving errors

#

I want to check if the automation sends paneel1_rood data to the rest command and if it does adds the line else it ignores it

#

If i get this to work i can successfully control my nanoleaf hexagon tiles seperately

#

This is the complete restcommand without the if statements. This does work but for it to work all values need to be filled so all 3 colors for all 18 hexagon tiles. i want to make a restcommand that also makes the correct code if only 1 tile gets the RGB colors from the automation. But it has to ignore all lines it doesnt get info from or the code will give an error in the nanoleaf controller. https://pastebin.com/aeUQN19T

ivory delta
#

is giving errors
What errors...? πŸ€”

#

Hard to say what's wrong if you don't explain the problem.

grim flicker
#

that is expecting a : and got a }

#

i filled it in on the test template page

#

im not really sure if {% set paneel1 = {{paneel1_rood}} %} can be written this way

ivory delta
#

Well this is your problem:
{% set paneel1 = {{paneel1_rood}} %}
You can't nest templates.

grim flicker
#

ok then thats my problem

ivory delta
#

What is paneel1_rood?

grim flicker
#

i have an automation calling a rest command and in the data part i have this

data:
  paneel1_rood: '255'

paneel1_rood is used for RGB colors so its a number

#

but i would like to being able to just give for example only tile 3 the

data:
  panel3_red: '255'
  panel3_green: '255'
  panel3_blue: '255'

did it in english so you can understand what i mean

#

is there another way to check if a value is given from an automation yes or no and if not skip a line?

#

hmm why do i always have questions no one knows the answer to πŸ˜…

mighty ledge
#

well the question doesn't really make sense

grim flicker
#

it does but i cant really explain the whole situation well enough

#

but when using this i need to send every tile all 3 colors in every automation i use

#

if i leave one blank i get an 400 bad request error.

#

It also doesnt make sense to give a tile a command if it allready is that color

mighty ledge
#

change each {{paneel1_rood}} to {{paneel1_rood|default(0)}}

#

and it'll be zero when not provided

grim flicker
#

yeah this will turn off all tiles if there is no value. The trick would be to being able to just change one tile and leave the rest as is

#

an RGB of 0,0,0 will result in the tile go off

mighty ledge
#

does the device support that?

#

you're writing a ton out, what happens if you only write one out? Does it still work? If yes then make a script for each one

grim flicker
#

i guess there seems to be no other way then to do that

mighty ledge
#

if the device requires all inputs, then that's what you'd have to send

#

I just looked up nanoleafs, they look pretty cool

#

didn't even know they existed

#

Your other option is to store all the values that you send to the nanoleaf in helpers, and then use the helpers as default values

#

an input_number for each one

#

it woudl be alot of work, but I think it would be worth the effort

dapper aurora
#

Any idea why this tempalte is evaluating to false? value_template: "{{ states('sensor.s31_251_br_tv_power_energy_apparentpower')|float > 60 }}"

#

when the apparentpower in dev tools is showing > 60

mighty ledge
#

is apparent power an attribute?

#

if yes, then the template is wrong

dapper aurora
#

no its a state

mighty ledge
#

then it should be working, take a screenshot of it in developer tools

naive hatch
#

Can someone help me out with a javascript template? This is returning "One" when the entity.state is 4

                            if (entity.state == 0)
                              return 'Zero'
                            if (entity.state == 1)
                              return 'One'
                            if (entity.state == 2)
                              return 'Two'
                            if (entity.state == 3)
                              return 'Three'
                            if (entity.state == 4)
                              return 'Four'
                            ]]]```
mighty ledge
#

states are strings

naive hatch
#

Ohh

mighty ledge
#

also, you need terminations

naive hatch
mighty ledge
#

;

naive hatch
#

It's working without them :/

mighty ledge
#

at the end of each return

naive hatch
#

πŸ‘

#

Working now, thanks a ton <3

crude crest
#

The template condition that I'm using is "{{ trigger.event.data.actionName == "ALERT_TEST_YES" }}", but it's not hitting the conditional correctly. Is there something I'm missing?

naive hatch
#

Nevermind, my sensor is just broken

#

I would appreciate some help with this template

shell ferry
crude crest
#

@naive hatch That template seems to execute fine. What is the entity_id: sensor.time in the configuration for?

naive hatch
#

I removed it, and it's still 0, even though the 4 people in the group are all home

crude crest
crude crest
#

And if you execute that template in the dev tools?

naive hatch
#
  friendly_name: "People Home"
  value_template: >
    4```
#

???

#

The sensor.number_of_persons_home is still reporting 0

crude crest
naive hatch
#

Yes, in groups.yaml

#

And I've !included groups.yaml in my config

crude crest
#

And you've verified that the group.people entity is present?

naive hatch
#

Yes, it exists. All 4 states are "Home"

grim flicker
#

Petro it doesnt really need all the info but every line in the code is more then just the RGB numbers. So if the RGB numbers of a specific tile are not set by the automation, it needs to skip the id number etc. thats why i wanted to skip a line when the data for that tile wasnt sent. This way i could make one setup in the rest command and use it for every automation i use without having to put all data in every time. And yes they are pretty cool indeed. To bad the integration in home assistant isnt supporting every tile as a seperate light. That would have been freaking awsome

crude crest
#

@naive hatch okay so the template executes, but the sensor is reporting 0. You've restarted HA? Not just reloading?

naive hatch
crude crest
#

Yeah, try restarting. Honestly, the restart has gotten so quick that I don't mind anymore. The reloads don't seem to catch everything.

naive hatch
#

I just put in an SSD yesterday, they're lightning fast :)

#

Although I bought the wrong adapter so I have to use USB-2

#

It looks like it's working now :)

#

Thanks for the help!

crude crest
#

So if you notice on the dev tools page, the template monitors for state change events, so we don't have to specify an entity_id anymore.

#

So, it'll actually watch for the states to change of any entities within group.people.

naive hatch
#

I just grabbed this code from an older forum thread, so it's good to know :)

crude crest
#

The devs did some major cleanup on the templating engine last year I think, and it sped a lot of that up.

naive hatch
#

I honestly love templates, but I don't understand the language very well :/

crude crest
#

For the most part, it's just Python.

naive hatch
#

Cool :)

ivory delta
#

For the most part, it's Jinja πŸ˜‰

crude crest
#

It really is its own thing, but it at least lines up with a lot of the basic Python expressions.

grim flicker
#

Maybe its a stupid question. But why is something like {% set paneel1 = {{paneel1_rood}} %} not possible? Is it something none of the devs havent thought about or is it doing somethign strange in the background

crude crest
#

try {% set paneel1 = paneel1_rood %}

ivory delta
crude crest
grim flicker
#

You can use {{paneel1_rood}} in a template. why cant i use it to set a variable

ivory delta
#

There is no need to have a template inside a template. The braces around a template just tell Jinja that the thing inside is an expression of some kind. It makes zero sense to have a template inside a template.

#

No. You can't use {{paneel1_rood}} in a template. {{paneel1_rood}} IS the template.

#

It's the braces around it that make it a template. Everything inside is just an expression.

crude crest
#

{{ everything in here is the template }}

ivory delta
grim flicker
#

if i put in paneel1_rood in my template the data from the automation isnt put in there

ivory delta
#

Because you're doing something else wrong πŸ€·β€β™‚οΈ

#

You can't just make stuff up.

#

I had to leave earlier... what is paneel1_rood?

crude crest
#

his variable name

ivory delta
#

Well, yeah... but where does it come from?

grim flicker
#

i have a restcommand with this template:

{  "write" : {"command": "display", "animType": "static", "animData": "18 
    36776 1 {{paneel1_rood}} {{paneel1_groen}} {{paneel1_blauw}} 0 20 
    40379 1 {{paneel2_rood}} {{paneel2_groen}} {{paneel2_blauw}} 0 20 
    ", "loop": false, "palette": [], "colorType": "HSB"}```
#

i shortened it

#

in an automation i run service: restcommand and in the data i put:

data:
  paneel1_rood: '255'
  paneel1_groen: '0'
  paneel1_blauw: '0'
``` and so on
#

so these values are filled in the rest commandf

#

i need to use {{ }} or else the template does not see them als variables coming from the automation

ivory delta
#

No. Stop.

#

Anything inside { } will be interpreted as Jinja. Something inside {{ }} gets returned, something inside {% %} just gets evaluated.

#
{% set b = 3 %}
{{ a * b }}```
This will return 15. The first two get evaluated, the last one gets returned.
#

I don't wrap 3 and 5 in {{}}

#

Share your script in a paste bin.

grim flicker
#

Ok.. makes sense. now i want to evalute it {{paneel1_rood}} is indeed returning something and if not skip the whole line

ivory delta
#

You're not giving anything any variables. You're just writing random crap in a template and hoping for the best.

grim flicker
#

this isnt random. this is how it needs te be written and it does work.

#

but i want to be able to let the template skip lines

#

the top line: { "write" : {"command": "display", "animType": "static", "animData": "18 is always the same

ivory delta
#

{% set paneel1 = {{paneel1_rood}} %} = bad
{% set paneel1 = paneel1_rood %} = good
But there's no point assigning one value to another variable. Variables are only useful when you use them more than once.

grim flicker
#

then the lines beneath are the tiles every line corresponds with a id, frame, R, G, B, 0, and a transition time

#

the RGB needs to be changed with the automation

#

but when an automation does not send the RGB of the specific tile. it needs to skip that whole line in the template

#

so {% set paneel1 = paneel1_rood %} will get the data out of the automation and set it to paneel1?

#

after that i can check if its != ''

mighty ledge
#

are you still on this?

grim flicker
#

yes i cant accept that this isnt possible

ivory delta
#

But there's no point assigning one value to another variable. Variables are only useful when you use them more than once.

#

It's all possible. You're just doing it wrong πŸ€·β€β™‚οΈ

mighty ledge
#

can you send this:

    {  "write" : {"command": "display", "animType": "static", "animData": "18 
    36776 1 {{paneel1_rood}} {{paneel1_groen}} {{paneel1_blauw}} 0 20 
    ", "loop": false, "palette": [], "colorType": "HSB"}
ivory delta
#

Why do you need to skip things?

mighty ledge
#

will it error?

grim flicker
#

no

mighty ledge
#

then there's nothing you can do

grim flicker
#

this will work fine

mighty ledge
#

period

ivory delta
grim flicker
#

ok but then i have to write 18 rest commands for every tile

#

and when i want to change 10 tiles a different color i have to call 10 restcommands in an automation

#

while it should be send in one message

ivory delta
#

If you're going to ignore my questions, I'm done here.

#

Good luck. πŸ‘‹

mighty ledge
#

wait

#

is the 18 the number of things your sending?

grim flicker
#

no its the number of the tiles set in the controller of the nanoleaf. it doesnt really matter what number stands there. as long as its higher then the amount of tiles i want to control at the same time.

#

or equal

#

so when i change 2 tiles from red to green the number needs to be atleast 2 but can also be 18

mighty ledge
#

so you can only send something like this? I'm getting mixed answers here

    {  "write" : {"command": "display", "animType": "static", "animData": "18 
    36776 1 {{paneel1_rood}} {{paneel1_groen}} {{paneel1_blauw}} 0 20 
    ", "loop": false, "palette": [], "colorType": "HSB"}