#templates-archived

1 messages Β· Page 120 of 1

gray loom
#

so below sensors: i declare the name, then a friendly name, and then in value_template the actual entity_id from which data i need to pull

#

it works, i got the sensor but its not reacting to my movements 😦

#

i see it trough the ssh, and terminal tho

#

i got the hang of template at least πŸ™‚

fossil totem
#

oh it gets so much worse lol πŸ˜„

#

so, switch.motion_sensor_10981222 - is that reacting to your movements?

#

like, does the source device connected to tellstick change state?

gray loom
#

noo the switch is not reacting

#

i only see it working trough ssh terminal

#

when i wave my hand

fossil totem
#

ok well, that's another problem to tackle i guess.

gray loom
#

πŸ™‚

#

thanks for help

fossil totem
#

are other tellstick devices working?

gray loom
#

yes

#

and they are all intergrated the same way, through the addon

fossil totem
#

i just had to google WTF a tellstick is so... probably not going to be much further help lol

gray loom
#

i have a wall switch, when i click it i see it change in HA

#

but not the motion sensor

fossil totem
#

but now you know how to make a template!

gray loom
#

thank you anyways πŸ™‚

#

yes

#

i have like 4 other motion sensors i can make a template from

#

😎 as soon as i get this one working

#

gonna try and add a unique id to the one i just made

mighty ledge
#

the name of the sensor contains a dot. Remove it

#
binary_sensor:
  - platform: template
    sensors:
      switch.motion_sensor_10981222:
            ^
            |
      REMOVE THIS, NOT ALLOWED
        friendly_name: "Motion Sensor1"
        device_class: motion
        value_template: "{{ states('switch.motion_sensor_10981222') }}"
narrow glacier
#

They had a slightly different misunderstanding, they've got it handled now

versed idol
#

works great, thanks πŸ‘

lusty flax
#

Is it expected that values in Helpers ( eg input_number & input_select) are not usable in templates?

#

In the template editor I input something like this {{ states.input_number.test_number}} and my output is:

<template TemplateState(<state input_number.test_number=27.0; initial=None, editable=True, min=1.0, max=100.0, step=1.0, mode=box, unit_of_measurement=pokemons, friendly_name=test_number @ 2021-02-20T05:51:31.623445-06:00>)>This template does not listen for any events and will not update automatically.```
#

my desired output would be 27

ivory delta
#

Not usable... πŸ€”

#

They are. And you're not using the proper method of retrieving states.

lusty flax
#

So what object would I be looking for, also tried using {{ states('input_number.test_number') }}

#

which is what the documentation says should return as a string

vestal roost
#

Hi, I would like to log the wattage used by a HS110 via the tplink integration and would like to send the wattage to influx DB. Wattage shows up in the entities attributes but does going to influx. Can anyone point me in the right direction?

ivory delta
fossil totem
#

i think the real question here is how does unit_of_measurement=pokemons render in the UI

ivory delta
#

Or not.

coarse tiger
#

and I thought I'd go max crazy by connecting my toothbrush to HA

ivory delta
#

Make it set off the house alarm when you don't brush long enough.

coarse tiger
#

others fetch pokemons 🀣

#

I actually turn off lights by brushing > 2 mins

fossil totem
#

apparently i don't understand lists very well because i have what i suspect is a simple use case but just can't seem to come up w/ a solution.

#

i have a list, it might look something like this:

#
{% set testlist = ['binary_sensor.plate02_connected', 'light.plate02_backlight', 'sensor.plate02_sensor', 'number.plate02_active_page', 'light.plate02_selected_foreground_color', 'light.plate02_selected_background_color', 'light.plate02_unselected_foreground_color', 'light.plate02_unselected_background_color'] %}
#

in that list, the _plate02 bit will be different each time. I want to select sensor.plate02_sensor from that list, and i don't know the value plate02 ahead of time

#

so, regex ^sensor\..+_sensor$ if that makes sense

ivory delta
#

So use regex πŸ€·β€β™‚οΈ

#

But since you haven't said what you're actually trying to achieve, it's going to be hard for anyone to help.

fossil totem
#

goal is to capture the value sensor.plate02_sensor from the list presented above

ivory delta
#

Just the string for that entity ID?

fossil totem
#

correct, the string is fine. the list is a jinja list, each contains an entity name, but that's kind of irrelevant. it has a list of strings, i want to apply a regex test against each item in the list, and return the item that matches.

#

if there is more than one match, either return them all or just the first or whatever

#

some things i'm trying: {{ testlist| regex_search("sensor\..+_sensor") }} returns true, as it's a test

#

adding regex to match start of line and end of line makes that test return false: {{ testlist| regex_search("^sensor\..+_sensor$") }}

#

{{ testlist| regex_findall_index("sensor\..+_sensor") }} returns sensor.plate02_connected', 'light.plate02_backlight', 'sensor.plate02_sensor which tells me it's processing the entire list as one long string (not handling each element in the list separately)

#

which i suspect is my problem here. tl;dr - i'm doing it wrong but not sure where

#

here's one approach that feels a little gross but does the thing

#
{% for entity in testlist -%}
  {%- if entity|regex_search("^sensor\..+_sensor$") -%}
    {{entity}}
  {%- endif -%}
{%- endfor %}
ivory delta
#

This works just fine to replace everything after the first match with nothing:
list | regex_findall_index('switch\.bedroom.*') | regex_replace('\'.*', '')

shut silo
#

is it possible to disable sensors to get data? i'm working on an template in dev tools and have to set some data to test it. but every minute the sensor gets its date from integration?

ivory delta
#

No, you can't 'pause' them. They're enabled or not - and if they're not, you can't even find the entity.

#

Why do you want to pause it? What's giving you trouble?

shut silo
#

as i said. i working on a template and wants to test it

#

so i have to test with hard values instead of sensors?

ivory delta
#

That depends what you're doing...

shut silo
#

i would like to add a binary sensor depending on some other sensors.

#

can i fake/set their values in the template?

ivory delta
#

You can fake anything... but you might end up with something that looks completely different to what you need.

#

Share what you have so far and explain why it's a problem.

shut silo
#
  {% if is_state('sensor.superb_iv_charger_max_ampere','Reduced') %}
    {{ states('sensor.charging_current_winter') | float >= 0 }}
  {% endif %}
{% else %}
  {{ states('sensor.charging_current_winter') | float >= states('input_number.threshold_reduced_charging') | float }}
{% endif %}```
#

thats what i have

ivory delta
#

Triple backticks to format as a block please. Easier to read πŸ™‚

shut silo
#

done πŸ˜‰

#

and now i want to set some test values to see, if this is working

ivory delta
#

Gimme a sec

shut silo
#

you'll get two, if you need πŸ˜„

ivory delta
#

As long as I've not made any mistakes, this should have the same meaning:

{% set charging = is_state('switch.superb_iv_charging','on') %}
{% set reduced = is_state('sensor.superb_iv_charger_max_ampere','Reduced') %}
{% set winter = states('sensor.charging_current_winter') | float %}
{% set threshold = states('input_number.threshold_reduced_charging') %}

{{ winter >= 0 if charging and reduced else winter >= threshold }}```
#

And now you can just change the right hand side of any of the first 4 lines for testing.

shut silo
#

look good.

#

i will try with that. thanks

#

does the if statement work with the condition before "if"?

#

never seen

ivory delta
#

It's basically Python's version of the ternary operator.
a if x else b
This will check if x is a 'truthy' value, returning a if it is. Otherwise, it'll return b.

#

Truthy values are things like non-empty strings, as well as the boolean True.

shut silo
#

got it.

#

is there another option for a short if then else?

#

without lots of bracket as i did before?

#

just want to be sure, that I understand it when i read it in a month or further future

ivory delta
#

That is the short option to avoid if/else πŸ˜„

#

If you're doing multiple checks, sometimes you need more... like if you're going to do: 'if Monday, do this, else if Tuesday, do this, else if... end if'

#

But with only two possible options? Use ternary πŸ™‚

shut silo
#

okay what about this? two more values (maximum and threshold_maximum) and one more if.

  {%- if is_state('sensor.superb_iv_charger_max_ampere','Maximum') -%}
    {{ states('sensor.charging_current_winter') | float >= 0 }}
  {%- endif -%}
  {%- if is_state('sensor.superb_iv_charger_max_ampere','Reduced') -%}
    {{ states('sensor.charging_current_winter') | float >= (states('input_number.threshold_maximum_charging') | float - states('input_number.threshold_reduced_charging') | float) }}
  {%- endif -%}
{%- else -%}
  {{ states('sensor.charging_current_winter') | float >= states('input_number.threshold_maximum_charging') | float }}
{%- endif -%}```
#

doesn't work with ternary, does it?

shut silo
ivory delta
#

There are probably a hundred ways to write your template. The more detail you add, the more that number grows.

#

But yes, you'll probably have to use some if/else in there at some point.

#

And you should keep it simple like the version I gave you. That template is hard to read because you have such long names everywhere.

#

Use variables πŸ˜‰

shut silo
#

I got that point. But searching for the shortest way of if-then-else.

#
{% set reduced = is_state('sensor.superb_iv_charger_max_ampere','Reduced') %}
{% set maximum = is_state('sensor.superb_iv_charger_max_ampere','Maximum') %}
{% set winter_current = states('sensor.charging_current_winter') | float %}
{% set threshold_reduced = states('input_number.threshold_reduced_charging') | float %}
{% set threshold_maximum = states('input_number.threshold_maximum_charging') | float %}

{% if charging and reduced %}
  {{ winter_current >= 0 }}
{% else %}
  {{ winter_current >= threshold_reduced }}
{% endif %}

{% if charging %}
  {% if maximum %} {{ winter_current >= 0 }} {%- endif -%}
  {% if reduced %} {{ winter_current >= (threshold_maximum - threshold_reduced) }} {%- endif -%}
{% else %}
  {{ winter_current >= threshold_maximum }}
{% endif %}```
Now I have this. First block I could write in ternary, too. But I want to write both in the same way. any suggetions for shortening?
ivory delta
#

What's the difference? Are they going to be different templates or are you hoping that returns one valid template? πŸ€”

#

Do you just want the last 6 lines to be shorter?

#

In a lesson on how not to write templates... you wanted short:

{% set s, i = states, is_state %}
{% set a = i('switch.superb_iv_charging','on') %}
{% set b = i('sensor.superb_iv_charger_max_ampere','Reduced') %}
{% set c = i('sensor.superb_iv_charger_max_ampere','Maximum') %}
{% set d = s('sensor.charging_current_winter') | float %}
{% set e = s('input_number.threshold_reduced_charging') | float %}
{% set f = s('input_number.threshold_maximum_charging') | float %}

{{ (d >= 0 if c else d >= (f - e)) if a else d >= f }}```
#

Made your last 6 lines tiny 🀏

#

Good luck maintaining it now πŸ˜‰

waxen rune
#

Can I somehow include which user that executed a script?
Like "The alarm was activated {{ now().strftime('%Y-%m-%d %H:%M:%S') }} by {{ < triggered by user > }}

ivory delta
#

Ah, the dev docs... the docs for devs.

#

It's the front-end that knows who's logged in, not your script.

waxen rune
#

And I can't pass it on?

ivory delta
#

If you want to provide that information to your script, the card/whatever that's calling the script needs to provide it.

#

Does your card provide it?

waxen rune
#

No idea, but it would be exactly that I want. Don't really see where to start looking.

#

Found a few community posts, but only questions, no answers

ivory delta
#

Because it's not currently possible.

waxen rune
#

Ok, well that's good to know.

#

No need to spend more time with that then.

shut silo
shut silo
ivory delta
#

Don't do what I just shared. It's stupid.

#

It's an example of how you can optimise code too much and make it too difficult to read πŸ˜‰

#

Your 'long' one is fine if you can read it and understand it. Shorter isn't always better.

shut silo
#

i won't do that a, b, c, d thing. but maybe that one-liner with former variables.

#

but i got the point, thanks

gray loom
#

Can i make a light entity with template? I only see examples with a "sensor:"

ivory delta
gray loom
#

I have a wall outlet that is a switch entity in HA. I'd want it to be a light so its easier to make automations

ivory delta
#

loef - I've saved you another 50 characters:

{% set s, i = states, is_state %}
{% set x,y,z = 'switch.','sensor.','input_number.' %}
{% set t,u,v = 'threshold_','charging','superb_iv_charger_max_ampere' %}
{% set a = i(x~'superb_iv'~u,'on') %}
{% set b = i(y~v,'Reduced') %}
{% set c = i(y~v,'Maximum') %}
{% set d = s(y~u~'_current_winter') | float %}
{% set e = s(z~t~'reduced_') | float %}
{% set f = s(z~t~'maximum_'~u) | float %}

{{ (d >= 0 if c else d >= (f - e)) if a else d >= f }}```
gray loom
#

I jsut need to know if i can write light: instead of a sensor:

ivory delta
gray loom
#

i Am making a template dude

ivory delta
#

You will eventually need a template for what you're doing. Your question is about the integration. πŸ€¦β€β™‚οΈ

crystal kindle
#

Hey guys, I'm struggling to use jinja2 to split an area into individual entities for the snapshot_entities variable in scene.create. I think part of my problem is it's just hard for me to test and see the output I'm getting and what dictionary keys I have access to when handling an area of entities.
What I have is basically this:

{% for entity in expand(area) %}
  # filter entities if I don't want them
    # If I just 'print' entity here, it doesn't work because it's not presented as a list in the yaml, and I don't think what I have below is the correct way to expand it to a list, but it's an example of something I tried
    '{{ "- " + entity + "\n" }}'
{% endfor %}
#

Consider it pseudo-code, I just wrote it from memory and I know it's not right, my focus is on expanding the area to a list of entities that is valid yaml.

glad geode
#

Hi Dom. For testing it's a good idea to use TEMPLATE in the developer tools

crystal kindle
#

oh yeah I saw that a while ago but I completely forgot about it, thank you

glad geode
#

And if area is a list of entities then you can probably do area|select() . If it's a list of dicts rather than strings you can then chain that with |map()

#

Check the list of built-ins in the pinned posts

crystal kindle
#

Yeah I'm expecting an area from a selector

glad geode
crystal kindle
#

ok the templating developer tool is helpful, I'll have to poke some more with this template debugger and make sure everything I'm doing is what I thought I was doing πŸ˜…

glad geode
#

Excellent

crystal kindle
#

a blueprint selector is what I mean, so I enter a room in a blueprint, and that's what I'm parsing in the jinja

thin vine
#

I don't think you can play with area's in the template developer tool

crystal kindle
#

Yeah that's what I'm finding, part of my disconnect was also that I didn't realize the selector I was using was returning a 'target'

#

So I don't think what I wanted to do is going to work

#

I may be digging this hole too deep. I'm still new to scripting/templating in hass, so maybe I'm missing something, but it seems like there should be a better way to create a scene on the fly that can take a target as well as discrete entities.

glad geode
#

is it possible to regex match entity ids in a states()?

glad geode
#

Or any sort of wildcard?

ivory delta
#

Yes

#

But... what are you trying to do?

glad geode
#

well my immediate need escapes me now, I've switched focus. But how is it possible? I've tried a regex in there, I've tried map filters and select filters

ivory delta
#

No-one can possibly answer 'how is it possible' without first knowing what 'it' is.

#

There's so many ways you could apply regexes and they'll all be completely different depending on what you're trying to do.

glad geode
#

Right, let me try to find an example

ivory delta
#

I could give you an example... but there are going to be hundreds more πŸ˜‰

{{ states | map(attribute="entity_id") | map('regex_search','switch\.bedroom.*') | select('true') | list | count }}```
#

The catch is that you have to pay attention to what each filter or map is doing and the data type returned. You can't get back from that one to the names of the entities it found.

glad geode
#

Ah, ok. Something like states('binary_sensor.light_profile__.*')|select_attr('state')|map(attribute='entity_id')|list[0]

ivory delta
#

No, nothing like that

#

afaik, you can't wildcard in states(), and your filters aren't going to return what you think they are.

#

But... you have the Dev Tools to experiment in.

glad geode
#

yeah, i've been trying all sorts

#

at the moment it just seems easier to use an sql sensor

ivory delta
#

If that's what works for you, go for it. There's no 'best' solution.

glad geode
#

A I supposed to be able to use the value from value_template in an attribute_template in the same template sensor?

ivory delta
#

The value returned by value_template becomes the state. Why would you want to have the same value in an attribute?

glad geode
#

I want to use the value in an attribute to calculate other stuff

ivory delta
#

Give me an example of what you're trying to do

silk smelt
#

Hi people! I'd like to set the value of an entity at a certain time. How can I do this with a template? I would like to store the state as "value_yesterday" at 23:59

fossil totem
#

what kind of data is value_yesterday? a number? a date/time? a string of text?

#

in general, what i think you'd probably want to do is to create a helper object to store your data, then an automation which triggers at 23:59, reads your entity value, and saves that value into the helper object

silk smelt
#

thanks! how do I create an automation trigger?

fossil totem
#

time trigger

silk smelt
#

value_yesterday is a number

fossil totem
#

float? integer? range of possible values?

silk smelt
#

the template itself is OK, I am just after the time trigger!

#

thank you!!!

#

do you always use YAML for this or do you ever use node-RED?

#

will this work?

  sensors:
    power_cost_yesterday_total:
      friendly_name: "Total kost i gΓ₯r"
      unit_of_measurement: "kr"
      icon_template: "mdi:cash-multiple"
      value_template: >-
        {% if is_state('sensor.time', '23:59') %}
          {{ (states('sensor.power_cost_today_total')) }} 
        {% endif %}```
#

ahhh, no it won't. some more research. thanks luma πŸ™‚

silk smelt
#

Can't wrap my head around this. How can I trigger a template like the above with a timed trigger?

ivory delta
#

You don't trigger templates. Templates just are.

silk smelt
#

ah, thank you mono πŸ™‚ My always guiding light πŸ˜‰

carmine aspen
#

Hi all, I have a template sensor that works perfectly in the template editor, passes the config check, but doesn't work in production. I get the following error: TypeError: 'NoneType' object is not callable. Any ideas?

ivory delta
#

Without seeing it? Nope.

carmine aspen
#

What's the best way to send a large text block?

ivory delta
#

A code share site like the ones linked in the topic.

carmine aspen
#

huh i'm trying to use this hastebin one but it won't give me a url to share

#

one sec

#

The UI reports 'Unknown' but the template editor shows the correct states

ivory delta
#

hastebin sucks, tbh. Doesn't always work, even after the UI loads. I prefer hatebin.com

carmine aspen
#

didn't know that was a thing. will use from now on

ivory delta
#

Prettier too πŸ‘Œ

carmine aspen
#

agreed!

ivory delta
#

Your YAML looks okay to me. What's the full error you're getting?

carmine aspen
#

the error occurs when I call the homeassistant.update_entity on that sensor i created

#

i'll copy , one sec

#

again, I copy and paste the sensor data into the template editor and it works perfectly

#

but when I call to update the sensor to get the latest value, I get that error

ivory delta
#

You could try stripping the whitespace inside your template but I don't think it should cause that error.

#

This will remove the whitespace in whatever precedes or follows this line:
{%- something something -%}

#

Although I think your >- is supposed to do the same.

#

I'm not sure what else it could be. I'll leave it to the big brains.

carmine aspen
#

thanks for taking a look

#

ding ding ding i think I found it

fast steppe
#

how do I round a value within a template? {{ (value_json["service"]["storage"]["/media/frigate/recordings"]["used"] / value_json["service"]["storage"]["/media/frigate/recordings"]["total"]) * 100 | round(0) }}

dreamy sinew
#

Order of operations

#

You're rounding 100 as written

fast steppe
#

I think this is working value_template: '{{ ((value_json["service"]["storage"]["/media/frigate/recordings"]["used"] / value_json["service"]["storage"]["/media/frigate/recordings"]["total"]) * 100|float)|round(0) }}'

#

thanks

lusty flax
#

Hey all! I've got an automation with a zwave scene trigger for a battery operated switch. I'd like to just use 1 automation but need to route to perform different actions based on values in the triggering scene_id and scene_data. Does anyone have any examples of what that might look like from a syntax standpoint?

glad geode
#

Is there a way to reference the entity name in a template sensor's value_template and attribute_templates? Or the area that the entity is in? Eg:

- platform: template
  sensors:
    lounge_lux_difference:
      unit_of_measurement: lx
      value_template: >-
        {% set room = self.entity_id|regex_search('^sensor.([_a-z]+)_lux_difference %}
        {{ states('input_number.'+room+'_lux_target')|float - states('sensor.'+room+'_lux')|float }}
#

Reason: I've got the same thing in multiple rooms and I want to use the same yaml block for each

glad geode
slate whale
#

hi, a question with templating a sensor, im wondering if it is possible to do the following checks

  1. check iff (states('now().day()')==X , where x is todays day of the week
  2. based on that check in 1 pick time from an input_datetime., in total i have 7 different input datetime for each day of the week

I can make it work if i just use one, but im creating a schdeule with different times like to have it so that i can pick different times based on the weekday. So would i need to have 7 different sensors or can i template it into one to avoid the massive bulks of code ?

glad geode
#

If the schedules aren't going to change much and you don't need to configure them in the UI of course.

slate whale
#

Hi, thanks for the response, that sounds like a nice solution however im not the only one that will use it and it has to be quite easy and flexible so im going to use the ui for each of the time each day, but i think i found a simple "not so good looking" solution for it now, just need to test it out over a couple of days now to see if it triggers correcly πŸ˜›

glad geode
#

There's a scheduler integration on HACS

slate whale
#

oh i did not know πŸ™‚ i will check that out as well πŸ˜„

#

thanks

glad geode
#

πŸ‘

drifting tapir
#

Hi guys, my plan is to write a template which will change the rgb colour dependant from the humidity measurement. My first problem is where to put this template. (its my first try with a template). Will it just be entered in the configuration.yaml ? and if so how can I set value for the 3 rgb parameters and how can I get them back in the automation?

ivory delta
#

Trying to get clever and have self-references for something like that seems pretty daft.

#

You're going to copy/paste that block with a new name. It'll take you an extra two seconds to use that name in the other places it's relevant.

glad geode
ivory delta
#

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

glad geode
#

But yeah, I'll just modify my bash template

#

Just wanted to confirm if there was a way or not

ivory delta
#

Nope. The scope for templates is the entire state machine of HA.

glad geode
#

But I don't think it's daft if it's possible

ivory delta
#

There's no 'self', even once the sensor is initialised.

glad geode
#

Cool cool, fair enough

spiral flax
#

hi, is there any execution order between the value_template and attribute_tempate? Can I rely on that I can update somehow the value of the sensor if the attributes were updated? (in a custom mqtt sensor integration)

ivory delta
#

If anything changes, the sensor is considered changed. If you're using that sensor in an automation, it'll check the triggers whether it was the state or the attributes that change.

spiral flax
#

I have two data sent separately, depending on which one was updated, these are the hue and the saturation. I want these as attributes of my color sensor and from this I want to make a hex rgb value as the sensor value regardless which one changed

ivory delta
#

That should be fine

fleet wyvern
#

hello, I am trying to change the value of an input number based on the difference between two values

#

currently, the code looks like this

#

is there anyway i can compress the action template to use trigger.to_state.state instead of the difference between the two sensor values ?

#

I have tried setting the action template to this:

#

however I am getting the following error: invalid template (TemplateSyntaxError: expected token ':', got '}') for dictionary value @ data['action'][0]['data']. Got None.

coarse tiger
#

please do not post codewalls

#

use paste.ubuntu.com and remove this. the server rules do not allow more than 15 lines for a reason

fleet wyvern
#

sorry, done, any hints?

ivory delta
#

Yeah, that's not how you do a multi-line value in YAML πŸ˜‰

#

Use the > symbol and remove the quotes.

fleet wyvern
ivory delta
#

Now you need to fix the indentation of line 5 πŸ˜‰

fleet wyvern
#

thanks mono, but it's not that, paste.ubuntu is actually screwing the indentation. Here is a copy-paste of the complete automation, which shows correct indentation

ivory delta
#

Then you're not getting the same error as before.

fleet wyvern
#

This is the error i am getting when reloading automations: Invalid config for [automation]: invalid template (TemplateSyntaxError: expected token ':', got '}') for dictionary value @ data['action'][0]['data']. Got None.

#

if i replace {{ trigger.to_state.state }} with state_attr('climate.termostat_living', 'temperature')|float - states('sensor.multisensor_living_temperature_air')|float everything works fine

ivory delta
#

Oh... you're nesting templates 🀣

#

{% if trigger.to_state.state > 1 %}

#

{% %} to 'calculate' something
{{ }} to return something

fleet wyvern
#

ok, getting closer

#

now i can reload the automation without any erros

#

however when i am triggering the automation i am getting Error while executing automation automation.automatizare_trv_living_procentaj: Error rendering data template: TypeError: '>' not supported between instances of 'str' and 'int'

ivory delta
#

States are always strings. You need to convert then using | int

fleet wyvern
#

i need to use float, something like this, right?

#

{% if trigger.to_state.state| float > 1 %}

ivory delta
#

Or use what I just said... convert to int.

#

not supported between instances of 'str' and 'int'

#

So make it int and int.

fleet wyvern
#

finally works!

#

thanks a lot mono!

#

i learnt something new today

fleet wyvern
#

any idea why the automation only returns 30 even though the trigger is 2 for example?

#

when running the following code through the developers > template section i get 30 output in case the trigger is a string, could this be the cause?

fleet tinsel
#

Hello can someone tell me if it's possible to pass in the entity_id of the google speaker you are trying to initiate a script in Home Assistant from so it plays back on that speaker on not a speaker group. I have tried using the trigger.entity_id and this fails to work which I could got from the article https://www.home-assistant.io/docs/automation/templating/
This is my script right now that I am passing the the TTS service:

entity_id: trigger.entity_id
message: >-
We have received {{ states('sensor.rainfall_today') }} mm today and based on
the time between the last 3 tip rates it's raining at {{
states('sensor.rain_pr_hour') }} mm per hour

marble jackal
# ivory delta So make it int and int.

You can compare a float with an integer. In case the state will be e.g. 1.4, state|int > 1 will be false, and state|float > 1 will be true
If @fleet wyvern really wants to use int, I think {% if trigger.to_state.state| int >= 1 %} would be better.

marble jackal
marble jackal
fleet tinsel
#

Actually that makes sense now regarding the piece about the trigger. You’re right all I am doing is turning on the script. I am really interested to see how this can be done as you may have echo / google devices all round your house and if you want to call scripts that read back template values I would think you would want it to play back on the speaker your talking too and not a pre set speaker group. Hopefully someone will read this and propose a solution πŸ™‚

mighty ledge
marble jackal
# mighty ledge ``` - service: script.myscript data: entity: "{{ trigger.entity_id }}" ```...

As far as I understood @fleet tinsel SteveA correctly (and how I also would like to have it) is when I talk to my Google Home, and say something like "Hey Google, next garbage day" the Google Home will start a so called routine, which will start a script in HA. Included in this script is a TTS action which will respond to the Google Home something like "next Monday you need to take out the paper waste".
It would be great if HA somehow knows I'm asking this to the Google Home in the kitchen, and respond to that specific Google Home, and not to all, or to a predefined one in the script (e.g. Google Home Livingroom).
But as far as I know there is no way to determine from which Google Home/Google Nest device in your home the routine was started, and to send the TTS to that specific Google Home.

fringe leaf
#

Hi, trying to figure out how to get the name attribute to be sent in the notify message..
The automation works, meaning the Trigger works, but I'm getting an error about the message as follow:
Error while executing automation automation.automation_44: Error rendering data template: UndefinedError: 'dict object' has no attribute 'item'

https://paste.ubuntu.com/p/X4F2qfcF58/

Any help will be much appreciated. πŸ™‚

#

Never mind, got it! πŸ™‚

mighty ledge
#

trigger.event.data.item...

surreal sandal
#

I am trying to set up a bond light to have multiple "states" for the brightness, in much the same way that there are speeds for a fan.

Getting a functional light working with bond that only does ON/OFF was trivial. But I can't quite seem to grasp how to set an attribute to a light that persists so I can compare current brightness to the brightness I am setting it to.

Where have I gone sideways?

https://pastebin.com/8bJZG8m3

This fails silently.

#

If however I do a light.turn_on without setting a brightness as part of the command I am told template rendered and invalid service curl <snip command>

surreal sandal
#

Update: By wrapping the curl commands in a shell_command I can get the turn on / off logic working.

However it is still not reading the brightness accurately as it seems to default to the "Brightness is currently 0" control block

mighty ledge
#

your brightness statements are whacky

#
  1. you're getting an attribute 'brightness' back from the set_level
surreal sandal
#

How do I unwhack them?

mighty ledge
#

you do not need to access it from the state machine

#

2 you should completely remove the logic of the input_number inside that

#

that light will contain it's own slider. If you want a slider to adjust the light, then you should make an automation

#

if you need the input_number so that the light can have a slider, then you need to add a service that sets that

#

you also need a level_template

#

nevemrind, it was above

surreal sandal
#

I don't need a slider explicitly. I just need the option to set the state to OFF, DIM, BRIGHT

mighty ledge
#

so, where are you getting the state OFF, DIM, and BRIGHT from?

surreal sandal
#

This particular light has (with a bit of fudgery) 2 buttons set up in Bond, one toggles Bright / Off, the other toggles Dim / Off

I am trying to wrap those 2 buttons into a single 3 state light.

mighty ledge
#

yes, but can you read the state of those devices?

surreal sandal
#

no

mighty ledge
#

ok

surreal sandal
#

In my head cannon (without knowing all the tools available in HA), I need some variable to store the assumed state of the object (which I am attempting to use the input_number to do).

#

but, doing it poorly to say the least.

mighty ledge
#

your set_level should be:

  set_level:
  - service: >
      {% if brightness > 128 %}
        ...
      {% endif %}
    data:
      brightness: "{{ brightness }}"
  - service: input_number.set_value:
    data:
      entity_id: input_number.master_bedroom_fan_light_level
      value: "{{ brightness }}"
#

but I don't think you need the data: brightness for your shell commands unless you use brightness in the shell command

surreal sandal
#

I do not. The shell commands are just button toggles

mighty ledge
#

then it's simply:

  set_level:
  - service: >
      {% if brightness > 128 %}
        ...
      {% endif %}
  - service: input_number.set_value:
    data:
      entity_id: input_number.master_bedroom_fan_light_level
      value: "{{ brightness }}"
#

Don't use the input_number in your logic for calling the shell commands

#

and don't put the input number in your UI

surreal sandal
#

how do I get the previous brightness level as part of my command then?

mighty ledge
#

the light will control everything, not the input number. The input number is to simply store the current brightness for the light

surreal sandal
#

That is my end goal, so I appreciate the confirmation.

mighty ledge
#

what do you mean "previous brightness"?

#

why do you need that?

surreal sandal
#

as an example:
If the light is currently dim, and I want to make it bright.
toggle dim, and toggle bright.
If the light is currently off, and I want to make it bright.
toggle bright

#

the steps I take are dependent on the current state.

mighty ledge
#

I think your intended use case is going to be wonky

#

if that's what you want, you should just make buttons in the UI

#

no point in making a light template

surreal sandal
#

My use case is "I have a stateless dimming light that I want to be able to control into 3 known states"

mighty ledge
#

and what happens when you are on the upper state and restart?

#

you'll now have 3 known states 1 which is useless

#

or worse case, you're at the upper limit and it thinks your on the lower limit

#

now you have 1 state with 2 useless states

surreal sandal
#

agreed, it is imperfect. But I have a manual override in that event (via the remote)

mighty ledge
#

not to mention a slider won't work like that

#

once you increase the slider to max, it's not going to magically drop down

surreal sandal
#

I am not following

mighty ledge
#

the range of your brightness is zero to 255

surreal sandal
#

I would be fine if it was 0-2

mighty ledge
#

not possible, lights inherently have 0-255 in HA

surreal sandal
#

no problem

mighty ledge
#

so, you're at 0, 255/2, and 255

surreal sandal
#

yep

mighty ledge
#

ok, if you increase it from 255/2 to 255. The slider position will now be at 255. You can't increase it anymore

surreal sandal
#

im following so far.

mighty ledge
#

Ok, so if that's what you want then what I posted is all you need and you don't need the previous state.

surreal sandal
#

i still don't see how I would not need the previous state

mighty ledge
#

0 on the slider is zero

#

if brightness = zero run script a

#

if brightness = 255/2 run script b

#

if brightness = 255 run script c

#

nothing more

#

if you want the values between, you have to do math

#

and I can help you with that

surreal sandal
#

in this case is the slider and brightness representing different values?

mighty ledge
#

the slider would be set to 24 and you'd have to decide how you'd want that to translate to script a

#

is script a 0 to half of 255/2?

#

you have a full range of numbers. 0 to 255, how does each number map to the script you want to run?

#

the first 33% is script a?

#

the second 33% script b?

#

you follow?

surreal sandal
#

If I set the slider to anything between 1-255/2 I want the exact same thing to happen>
HOWEVER: If the current brightness value was 200... it does different stuff than if it was 100

mighty ledge
#

yes

surreal sandal
#

Put another way
200 -> 0 runs script A
100 -> 0 runs B

mighty ledge
#
{% if brightness < 84 %}
  script.a
{% elif 84 <= brightness < 168 %}
  script.b
{% else %}
  script.c
{% endif %}
#

that simple

surreal sandal
#

I am like 99% sure that doesnt work

mighty ledge
#

i'm 99% sure that does

surreal sandal
#

I am putting it in now just to smoke test it, but I need to run different commands based off the previous state of the light.

#

and I cannot logically see how that works here.

mighty ledge
#
  set_level:
  - service: >
      {% if brightness < 84 %}
        script.a
      {% elif 84 <= brightness < 168 %}
        script.b
      {% else %}
        script.c
      {% endif %}
  - service: input_number.set_value:
    data:
      entity_id: input_number.master_bedroom_fan_light_level
      value: "{{ brightness }}"
#

remember, you'll be adjusting the brightness on the light, not the input_number.

surreal sandal
#

right, but my script says "toggle this thing that I dont know the state of"

mighty ledge
#

yep

surreal sandal
#

so if I say "turn off the top light, and turn off the bottom light" since they are the same physical bulb... it turns off the bulb, then turns it right back on

mighty ledge
#

what the hell are you talking about?

surreal sandal
#

the part of this that makes this system difficult.

mighty ledge
#

dude

#

make 2 lights

#

then make a group light

surreal sandal
#

I found that my remote sends 2 different signals based off a hardware toggle inside of the remote itself (after opening it up).

Signal A: Toggles the light between full bright, and off
Signal B: Toggles the light between some preset dimness, and off.

mighty ledge
#

2 input_numbers, 2 lights, then a single light group

surreal sandal
#

I mapped those signals to 2 different buttons. But since they are both the same toggle, turning A on when B is already on actually sets both lights to on, but the physical light is off.

#

Is that the better way to be doing this? I know nothing about light groups.

mighty ledge
#

wait, no. Don't make a light group, it's just impossible to follow this code and your description.

surreal sandal
#

Can I make a light group with mutually exclusive order dependent lights?

mighty ledge
#

so let me see if I follow this now

#

You have 4 commands

#

shell_command.master_bedroom_fan_downlight_off
shell_command.master_bedroom_fan_downlight_on
shell_command.master_bedroom_fan_uplight_on
shell_command.master_bedroom_fan_uplight_off

surreal sandal
#

yes

mighty ledge
#

you want combinations of them to equal brightnesses

surreal sandal
#

you could think of it that way.
Perhaps my naming is poor. They are named as such because that is the name of the virtual button I bound them to using Bond. (Up Light, Down Light)... but they are 1 physical bulb, the names don't matter. It could be mapped to FanSpeed1, FanSpeed8. I just needed buttons.

mighty ledge
#

ok, so does on increase the brightness of downlight?

surreal sandal
#

DownLight is a toggle switch click it, it goes dim. click it it goes black, dim, black, dim, black.

#

UpLight is a toggle that goes bright, black, bright, black.

mighty ledge
#

how many clicks to go to max brightness from off?

#

and vice versa

surreal sandal
#

There is no brightness adjustment, I have no control over variable brightness

#

I can toggle between 0 and 50, or 0 and 255 depending on the button.

mighty ledge
#

right i get that, it's a static change

#

but if you click the up brightness once from off position, is it fully on at max brightness?

surreal sandal
#

yes

mighty ledge
#

ok, then you only have 4 states. [ 0, 0], [ 0, 1], [ 1, 0], [1 ,1 ]

surreal sandal
#

not quite. Logically yes, but things get odd

mighty ledge
#

how do they get odd?

surreal sandal
#

Lets start at brightness 0, both lights off.
DownLight = 50
DownLight = 0
UpLight = 255
UpLight = 0
UpLight = 255
DownLight = 0 <- At this point Uplight and Downlight would be on, but the brightness is 0 because the bulb sees them as the same button, thus toggled it off.

#

Or more simply
Down: 0->50
Up: 50->0 (But I want 50->250)

mighty ledge
#

I still don't follow

#

are you saying when you turn one on the other turns off?

surreal sandal
#

only if the other is already on.

mighty ledge
#

ok, then you need to incorporate the previous value

surreal sandal
#
All states start at 0 with both toggles assumed off
D toggles the light between 0 and 100
U toggles the light between 0 and 255

Now:
D -> D: 0 -> 100 -> 0
U -> U: 0 -> 255 -> 0
D -> U: 0 -> 100 -> 0
U -> D: 0 -> 255 -> 0

Goal:
D -> D: 0 -> 100 -> 0
U -> U: 0 -> 255 -> 0
D -> U: 0 -> 100 -> 255
U -> D: 0 -> 255 -> 100
mighty ledge
#
{% set previous = states('input_number.master_bedroom_fan_light_level') | int %}

then perform your logic

#

but you still need to set the slider

#

with a service call. It has to be after you call your scripts

#

like I posted above

surreal sandal
#
- service: input_number.set_value:
          data:
            entity_id: input_number.master_bedroom_fan_light_level
            value: "{{ brightness }}"

this one?

mighty ledge
#

The reason you aren't getting brigthness updates on your light is because you aren't calling the input_number.set_value service where you set the brightness on the slider. This will act as your stored brightness state and your level_template will feed off it and use that as a representation of your current brightness level

#

yes that one

surreal sandal
#

and how do I use the set previous? it is another input_number?

#

It makes sense what you are saying about the brigtness not being saved because I was not setting the value.

mighty ledge
#

no, when the template executes, input_last number will have your previous brightness

#

so just grab the information from that input_number

#
{% set previous = states('input_number.master_bedroom_fan_light_level') | int %}
{% if brightness > 128 and previous > 128 %}
  ...
#

then your service call will update the input_number after that template is executed and your scripts are called. Effectively changing your previous value to a new value.

surreal sandal
#

I did not know I could set variables like that. I assume "previous" gets cleared out once the template is finished executing?

mighty ledge
#

You as a user move the Light slider -> home assistant excutes template with brightness as an incoming variable in the first service call that calls your script -> then input_number is updated with brightness

#

1 action performed by you. 2 service calls performed in the background.

surreal sandal
#

When there are multiple service calls, it needs the preceding dash?
I am trying to figure out my indentation cause adding in those dashes made it a bit funky

mighty ledge
#

yeah but you should remove data: brightness for the script call

surreal sandal
#

bad indentation of a sequence entry at line 122, column 40: ... service: input_number.set_value:

#

done

mighty ledge
#

hold on

surreal sandal
#

I appreciate your help btw.
I am sure you jumped in for an easy win... and this was not that.

mighty ledge
#
      set_level:
      - service: >
          {% set previous = states('input_number.master_bedroom_fan_light_level') | int %}
          {% if brightness > 128 and previous > 128 %}
            script.noop
          {% if brightness > 128 and previous > 0 %}
            shell_command.master_bedroom_fan_downlight_off
            shell_command.master_bedroom_fan_uplight_on
          {% elif brightness > 128 and previous == 0 %}
            shell_command.master_bedroom_fan_uplight_on
          {% elif brightness > 0 and previous > 128 %}
            shell_command.master_bedroom_fan_uplight_off
            shell_command.master_bedroom_fan_downlight_on
          {% elif brightness > 0  and previous > 0 %}
            script.noop
          {% elif brightness 0 and previous == 0 %}
            shell_command.master_bedroom_fan_downlight_on
          {% elif brightness == 0 and previous > 128 %}
            shell_command.master_bedroom_fan_uplight_off
          {% elif brightness == 0 and previous > 0 %}
            shell_command.master_bedroom_fan_downlight_off
          {% elif brightness == 0  and previous == 0 %}
            script.noop
          {% else %}
            script.noop
          {% endif %}
      - service: input_number.set_value:
        data:
          entity_id: input_number.master_bedroom_fan_light_level
          value: "{{ brightness }}"
#

that should work out of the box

#

if your logic is correct

#

to me, it seems like it can be streamlined and simplified becaus eyou have a few noops that can be lumped into 1 if statement

surreal sandal
#

I am still getting an indentation error here.

mighty ledge
#

did you copy/paste what I wrote?

surreal sandal
#

Yes. I 100% can clean it up. It is in an expanded state while I figured out the logic.

#

Yes

mighty ledge
#

paste the error

surreal sandal
#
bad indentation of a sequence entry at line 120, column 40:
     ...  service: input_number.set_value:
#

is it the trailing colon?

mighty ledge
#

ah yep

surreal sandal
#
does not match format <domain>.<name> for dictionary value @ data['lights']['master_bedroom_fan_dimmable']['set_level'][0]['service']. Got "{% set previous = states('input_number.master_bedroom_fan_light_level') | int %} {% if brightness > 128 and previous > 128 %}\n script.noop\n{% if brightness > 128 and previous > 0 %}\n shell_command.master_bedroom_fan_downlight_off\n shell_command.master_bedroom_fan_uplight_on\n{% elif brightness > 128 and previous == 0 %}\n shell_command.master_bedroom_fan_uplight_on\n{% elif brightness > 0 and previous > 128 %}\n shell_command.master_bedroom_fan_uplight_off\n shell_command.master_be.... (See ?, line ?).
mighty ledge
#

ah

#

so, you'll have to adjust this a big

#

bit*

surreal sandal
#

Every if/else combo is accounted for, and all cases follow that pattern

#

is it due to the setting of previous?

mighty ledge
#

you can't have double service calls

surreal sandal
#

bummer

mighty ledge
#

make a script

#
script:
  service_caller:
    variables:
      services: "{{ services | default(['script.noop']) }}"
    sequence:
    - repeat:
        count: "{{ services | length }}"
        sequence:
        - service: "{{ services[repeat.index - 1] }}"
#

then, use that as your service

#

and change your template to...

surreal sandal
#

Im going to need some talking through of this one.
I am not quite following what your script is doing.

#

It calls in reverse order an array of services?

mighty ledge
#

not sure where you're getting reverse order

surreal sandal
#

it looks like it was recursive counting down (idx-1)

mighty ledge
#
      set_level:
      - service: script.service_caller
        data:
          services:
            {% set previous = states('input_number.master_bedroom_fan_light_level') | int %}
            {% if brightness > 128 and previous > 128 %}
              [ 'script.noop' ]
            {% if brightness > 128 and previous > 0 %}
              ['shell_command.master_bedroom_fan_downlight_off', 'shell_command.master_bedroom_fan_uplight_on']
            {% elif brightness > 128 and previous == 0 %}
              ['shell_command.master_bedroom_fan_uplight_on']
            {% elif brightness > 0 and previous > 128 %}
              ['shell_command.master_bedroom_fan_uplight_off', 'shell_command.master_bedroom_fan_downlight_on']
            {% elif brightness > 0  and previous > 0 %}
              ['script.noop']
            {% elif brightness 0 and previous == 0 %}
              ['shell_command.master_bedroom_fan_downlight_on']
            {% elif brightness == 0 and previous > 128 %}
              ['shell_command.master_bedroom_fan_uplight_off']
            {% elif brightness == 0 and previous > 0 %}
              ['shell_command.master_bedroom_fan_downlight_off']
            {% elif brightness == 0  and previous == 0 %}
              ['script.noop']
            {% else %}
              ['script.noop']
            {% endif %}
      - service: input_number.set_value:
        data:
          entity_id: input_number.master_bedroom_fan_light_level
          value: "{{ brightness }}"
surreal sandal
#

but I could be misunderstanding how it functions

mighty ledge
#

repeat.index starts at 1

#

so repeat.index - 1

surreal sandal
#

lol, well that solves it

#

2 quick fixes:
Remove the colon after set value
Add a > after the first services

mighty ledge
#

yea yea

#

Technically... you can omit the last 2 if statements too

#

because it defaults to noop

surreal sandal
#
Invalid config for [light.template]: invalid template (TemplateSyntaxError: expected token 'end of statement block', got 'integer') for dictionary value @ data['lights']['master_bedroom_fan_dimmable']['set_level'][0]['data']. Got OrderedDict([('services', "{% set previous = states('input_number.master_bedroom_fan_light_level') | int %} {% if brightness > 128 and previous > 128 %}\n [ 'script.noop' ]\n{% if brightness > 128 and previous > 0 %}\n ['shell_command.master_bedroom_fan_downlight_off', 'shell_command.master_bedroom_fan_uplight_on']\n{% elif brightness > 128 and previous == 0 %}\n ['shell_command.master_bedroom_fan_uplight_on']\n{% elif brightness > 0 and previous > 128 %}\n ['shell_command.master_bedroom_.... (See ?, line ?).
#

I will keep that in mind when I start pairing it down

#

Oops there was a dropped > in the comparisons.

#

didnt solve the error, but it would have become one.

mighty ledge
#

is that still the error?

surreal sandal
#

yes

mighty ledge
#

can you post the code?

surreal sandal
#

1 second... I forgot there was a Templete Editor and it was a bit more readable that way.

brightness is undefined is where I am now.

#

pasteing code

mighty ledge
#

is the light created?

surreal sandal
#

In the Template Editor I get UndefinedError: 'brightness' is undefined
If I Check Configuration I get the above longer error.

Do you wish for me to reload the templates anyways to check the light?

#

Sorry... It is a new error now.

Invalid config for [light.template]: invalid template (TemplateSyntaxError: Unexpected end of template. Jinja was looking for the following tags: 'elif' or 'else' or 'endif'. The innermost block that needs to be closed is 'if'.) for dictionary value @ data['lights']['master_bedroom_fan_dimmable']['set_level'][0]['data']. Got OrderedDict([('services', "{% set previous = states('input_number.master_bedroom_fan_light_level') | int %} {% if brightness > 128 and previous > 128 %}\n [ 'script.noop' ]\n{% if brightness > 128 and previous > 0 %}\n ['shell_command.master_bedroom_fan_downlight_off', 'shell_command.master_bedroom_fan_uplight_on']\n{% elif brightness > 128 and previous == 0 %}\n ['shell_command.master_bedroom_fan_uplight_on']\n{% elif brightness > 0 and previous > 128 %}\n ['shell_command.master_bedroom_.... (See ?, line ?).
mighty ledge
#

brightness won't be defined inside the template editor

#

because brightness ojnly exists in the set_level environment

surreal sandal
#

that makes sense

#

alrighty, solved some errors.

mighty ledge
#

still same error? template looks fine

surreal sandal
#

nope all configs fixed.

mighty ledge
#

oh duh

surreal sandal
#

there was multiple if statements when we meant elif

mighty ledge
#

yes, just saw that

#

still looking

surreal sandal
#

I have a light

mighty ledge
#

ah, duh

#

5th elif

#

elif brightness 0

surreal sandal
#

Good catch!

#

Ok...

#

So first thing I notice, the light has a button and a slider

mighty ledge
#

yep

#

sliding the slider should perform those actions

#

now at this point you need to verify your logic is correct

#

now that you have the format down

surreal sandal
#

the slider can only go from 1-100

mighty ledge
#

Well that's new

#

the brightness should still be 0 to 255

#

so none of that should change but the values in your head will change

surreal sandal
#

well, it is going to change the value template logic

mighty ledge
#

nope

surreal sandal
#

do tell

mighty ledge
#

brightness should still come across as 0 to 255

#

the slider is for the UI

#

it's translated for the user

#

you can verify that by looking at the input_number

#

just don't adjust the input_number

surreal sandal
#

Ahh, I need to also set the input_number when I call turn_on and turn_off

mighty ledge
#

you might have to as well

#

well, not might have to, you do

surreal sandal
#

otherwise the number will never hit 0

mighty ledge
#

either way, you should understand enough to move forward

surreal sandal
#

It is actually working. It is a bit janky and there are a few bugs, but it is doing what I want it to do.

#

My hero petro

mighty ledge
#

nice, i'm not responding next time πŸ˜‚

surreal sandal
#

hahaha

mighty ledge
#

what kind of light is that?

#

so I can avoid buying it

surreal sandal
#

I am sorry that was such a nightmare. I will work on trying to more accurately describe the uniqueness of the problem.

mighty ledge
#

not your fault, it's the light

mighty ledge
#

Ah

#

so, i went a different route

#

I have a similar fan

#

I connected a device that uses the current to detect the state

#

removed that stupid remote

surreal sandal
#

link the device?

mighty ledge
#

however I had a traveler for the light and the fan, do you have that?

#

(new build)

surreal sandal
#

I thought about that, but without really tearing the thing apart... I couldnt

#

nope

mighty ledge
#

yeah, then you can't do what I did

#

fwiw, I tethered both lights together

#

hahaha

surreal sandal
#

we bought the fan and installed it, then went to hook it up to the "dead lightswitch" we had which we thought was a traveller to the fan, just to find it was to an outlet that got removed during an addition.

mighty ledge
#

oof

#

so in my case, I can't turn them on independently

surreal sandal
#

so we only have a 3 wire going up to fan, not a 4 (hot, copper, neutral)

mighty ledge
#

ah, yeah I have 4

#

but I had a choice... do I power both lights with 1 input or use the stupid remote

#

I chose 1 input

surreal sandal
#

for me, I only have 1 light

mighty ledge
#

ah but the fan is the other light in your situation?

#

you don't have a light that projects out the top and a light that projects out the bottom?

surreal sandal
#

I do not

mighty ledge
#

ah

surreal sandal
#

but I have a hardware switch that changes how the remote functions.

mighty ledge
#

ah

#

so, did Minka aire rebrand?

surreal sandal
#

so I digitally 'wired' the dim light to that "upper light" you mentioned

mighty ledge
#

cause my fan is Minka Aire, not Aire a Minka Group Design

#

seems fishy

surreal sandal
#

dunno

mighty ledge
#

hmm, odd

#

well either way, you're up and running

surreal sandal
#

I am, it works as horribly as I could have hoped.

mighty ledge
#

Lol

#

and it only took ages to work out

#

typical home automation!

surreal sandal
#

If you have any thoughts in the future about devices I could wire in to make this less stupid let me know.

mighty ledge
#

I'd check out ESPHome devices

surreal sandal
#

Right, the time I lost programming it was greater than my lifetime of hitting the switch!

mighty ledge
#

they are DIY, but you can basically build anything you want

#

you could also look into sonoff relays

#

not sure how they are powered though

surreal sandal
#

ESP had the same problem, it was limited to the commands that my fan would take... and it only would take this odd toggle on/off garbage.

#

now... if there was a super small one I could wire directly behind the lightbulb (microshelly)... I could make something work.

#

Yea I would need something like 10% the size of a sonoff, or to do some serious re-wiring within the fan to get that working.

#

But I have 4 more fans to install, so I will look into hardware mods I can make before the install on those.

#

Thanks again.

mighty ledge
#

Yeah np

surreal sandal
#

If you ever run into me on the street... I'll buy you a coffee, or I dunno... a contact sensor.

mighty ledge
surreal sandal
#

(I don't want you to think it was all for naught... but I think it might have been all for naught)

#

I tested the automation needed to tie it into an working switch... and it was awful... Took like 3 seconds to turn on the light from a switch, and the room goes totally dark for 2-3 seconds when the light goes from dim to bright.

ivory pawn
#

hello, is it possible to test a rest get json template in dev tab? im trying to extract data from a json nested dictionary using an api http get request.

dreamy sinew
#
{{ value_json.dump }}```
ivory pawn
#

thanks @dreamy sinew , do i specify the rest platform and http resource in dev tools template?

dreamy sinew
#

you using the template tester right?

ivory pawn
#

yeah, the tab in developer tools

#

template editor is the title

dreamy sinew
#

make the rest call manually and get the response. Dump that response into a var. write a template to process

#

you don't need anything else

ivory pawn
#

@dreamy sinew understood.. cheers

ivory pawn
#

hi, this gets me the value of' 'n' from a nested dictionary whos key is '1' . how can i get all the keys and corresponding 'n' values if i dont know the key values beforehand?
{{ value_json["1"]["n"] }}

dreamy sinew
#

.share the payload you're parsing

#

bot's dead....
Please use a code sharing site for the response payload

#

paste.ubuntu or hastebin

ivory pawn
dreamy sinew
#

that's pretty terrible

ivory pawn
#

πŸ™‚ ... i know

dreamy sinew
#

what key do you want?

ivory pawn
#

the keys are 0, 1, 2, 3 in this example but can be anything like A, BB, 3C etc. I want to read these keys and also their 'n' value from their nested dict. thanks

dreamy sinew
#

oh there's a n in there

#

i didn't see it at first

ivory pawn
#

its the name given to the preset id (key). the preset and name can be any value .

dreamy sinew
#

{{ value_json.values()|reject('eq', {})|map(attribute='n')|list }}

#

gives you a list of the n values

#

but you want the keys too?

ivory pawn
#

yes, was just about to ask that after testing it , cheers

dreamy sinew
#

i don't think that's going to be possible

#

how are you going to use this?

ivory pawn
#

my light hub gives each light an id and I can then assign that id with a name (kind of like friendly name for entitres in HA). I want to have an input select list of available lights in their friendly name format but then also know which id they correspond to since any put api requests i make need the id for the light hub to execute

dreamy sinew
#

yeah this isn't going to work then

#

probably need a custom component or something to pull this out in python

ivory pawn
#

ok, trying to avoid appd unless absolutley necessary.
if i keep it simple so that the id are just number from say 0 to 20 then I could loop with some sort of incremental count but not sure how to deal with missing ids ie 3 missing in 1, 2, 4,5. is there a way to program next key instead of the counting method?

dreamy sinew
#

dictionaries are immutable in jinja

#

so you can't loop through to build a new one

ivory pawn
#

thanks @dreamy sinew ... shame there isn't a way to just extract keys as that would be more useful than the 'n' values

dreamy sinew
#

you can get either and make a list but you can't then put them back together

ivory pawn
#

that may work ... how do I change your earlier code to get just the keys ?

ivory pawn
#

@dreamy sinew this seems to be on the right track for getting key and nested dict. can it be edited to give n instead of the whole nested dict per key?

   {% for key, value in dict_item.items() %}
      {{key}} 
      {{value}}
   {% endfor %}
{% endfor %}```
dreamy sinew
#

that'll print a bunch of stuff out but you won't be able to use it

glad geode
#

You could create a dummy template sensor with that as an attribute_template

#

Or better, format it as json output

earnest cosmos
#

Hi there! I need to test for two states like below, but unfortunatelly this syntax is wrong.
How can I accomplish this?

{% if is_state('light.lys_tilleggslys', 'off') AND is_state('binary_sensor.dark_inside_2', 'off') %}
#

Entire service call in the script:

  - service: >
      {% if is_state('light.lys_tilleggslys', 'off') %}
          script.lys_tilleggslys_on
      {% else %}
          script.lys_tilleggslys_off
      {% endif %}
#

I think I found the error: must be lower case and

glad geode
#

yup

glossy viper
#

can i "convert" a threshold sensor into a binary sensor using template?

ivory delta
#

A threshold sensor is already binary. It only shows on/off.

#

It’s an alternative to the template binary sensor’s value_template: to get the abnormal/too high/too low states.

glossy viper
#

yup...but ha says...u cannot use icon_template for threshold

#

πŸ™‚

ivory delta
#

But you're using custom cards, right? You can customise everything πŸ˜„

glossy viper
#

oh...put template in card directly

#

u smart mono πŸ˜—

ivory delta
#

To answer your original question... yes, you can create a template binary sensor... but don't try to convert the threshold sensor, just make a template binary sensor that does what you want.

glossy viper
#

did ...is working...but don't like icon of them πŸ™‚

glad geode
#

mono, how do you feel about wrapping sensors in other sensors?

ivory delta
#

What's the context? πŸ€”

#

Most of the time, there's no need. However, if you're trying to create a binary sensor out of information from a non-binary sensor, that's a valid use case.

#

Want a binary sensor that you can use everywhere when the humidity is over 80%? Binary sensor wrapping the humidity sensor. Of course, you could use templates everywhere instead... but having the binary sensor makes it explicit and easier to use.

glad geode
#

Using the value of the inner sensor to populate data in the outer sensor (for node-red automations)

ivory delta
#

NR? 🀒

glad geode
#

πŸ˜‚

#

Not a fan?

ivory delta
#

I thought NR could do everything so much more easily than HA alone? Why does it need you to wrap sensors?

#

All the NR fanboys talk like it's a one-stop shop and can do everything πŸ€·β€β™‚οΈ

glad geode
#

I do like the draggy-droppy UI

#

I spend enough of my life staring at yaml already

ivory delta
#

Meh. I like to be in control and I don't need a visual tool holding my hand... but to each their own.

glad geode
#

TBF before I wrapped these sensors with the correct data nicely I was mostly writing big blocks of javascript for it

#

I am intrigued by the automation blueprints though

valid mist
#

HI i am getting a warning log which from what i have read relates to templates but i do not have any. PLease somebody help me fix the issue or point me to relevant article?

#

Logger: homeassistant.components.template.sensor
Source: helpers/config_validation.py:751
Integration: template (documentation, issues)
First occurred: 12:48:21 (2 occurrences)
Last logged: 12:48:21
The 'entity_id' option is deprecated, please remove it from your configuration

ivory delta
#

Looks like it's about a sensor. Share the config that it's complaining about and we'll have a better idea.

valid mist
#

Sorry i have no idea what config is it referring to

glad geode
#

Looks like you have a template sensor in which you're setting entity_id . Have you looked through your template sensors?

valid mist
#

i don’t use templates

ivory delta
#

You clearly do.

#

The log isn't complaining about something you don't have.

glad geode
#

Try using dev tools to set the logger level to debug for homeassistant.components.template.sensor and run the config check

valid mist
#

Let me re phrase it i am on week 3 of HA i have not set up any templates

ivory delta
#

Somewhere in your config, you have something with platform: template written in it. Find that thing.

#

Ah, week 3. Templates aren't used until week 6 of the course.

fast mason
#

Don't skip ahead in the syllabus πŸ˜‚

valid mist
#

lol

glad geode
#

If you're on any Linux based install then cd to your config directory and grep -r 'platform: template' *

arctic sorrel
#

You've been here since September... did you fall asleep πŸ€”

mighty ledge
#

if you add up all the days on discord, it's 3 weeks

glad geode
#

The first few months are the theoretical part of the course. You don't get practical till later

mighty ledge
#

missing value templates

#

so it won't know the state

glad geode
#

Do template switches use sensors under the hood?

mighty ledge
#

no

#

it uses templates

ivory delta
#

They have to read from something. That something might be another sensor.

mighty ledge
#

sensors use templates under the hood

glad geode
#

Indeed, but it's template.sensor that's complaining, not template.switch

mighty ledge
#

yep, so that's where he should be looking for the entity_id field that he needs to remove

glad geode
#

There you go

mighty ledge
#

yeah, remove entity_id: sun.sun, pretty self explanatory

#

and before you ask, no you don't need to alter the template

valid mist
#

? Just remove the line from my sensors.yaml file

mighty ledge
#

yes

glad geode
#

Although if you look at the style guides in the docs you should probably change states.sun.sun.attributes to state_attr('sun.sun, 'next_rising')

valid mist
#

getting a code error must be the yaml

mighty ledge
#

use your eyes and look at the next template

#

you only removed one of them

#

there were 2

valid mist
#

still not liking it

mighty ledge
# valid mist still not liking it

everything you posted is fine. Also saying "still not liking it" without posting an error isn't really helpful. Lastly, make sure you aren't looking at the old error.

ivory delta
#

Missing a single quote after sun.sun

valid mist
#

i mean config validation

ivory delta
#

state_attr('sun.sun, 'next_rising') isn't valid πŸ˜‰

arctic sorrel
glad geode
#

Totally my fault

ivory delta
#

Get outta here!

#

Trouble maker.

glad geode
#

/chaosmonkey

valid mist
#

you mean like this (state_attr('sun.sun', 'next_rising')

#

😦

mighty ledge
#

missing closing ) on as_timestamp

mighty ledge
glad geode
#

Still

mighty ledge
#

remove the ) at the end after the }} too, that's the wrong spot

#

Do you understand how () work?

coarse tiger
#

it's like boxes in boxes, you never know what you will get

glad geode
#

Yeah you do

#

A smaller box

valid mist
#

{{ as_timestamp(state_attr('sun.sun', 'next_rising') | timestamp_custom)(' %I:%M %p') | replace(" 0", "") }}
icon_template: mdi:weather-sunset-up

glad geode
#

as_timestamp(state_attr('sun.sun', 'next_rising') |
Count the opening and closing brackets

#

Also, timestamp_custom(' %-I:%M %p')
Notice the - between the % and I

mighty ledge
#

I think he's given up?

valid mist
#

nope

ivory delta
#

If you're new to templates... test them in the Dev Tools πŸ˜‰

#

Don't keep guessing and having to reload your config.

mighty ledge
#

ok, are you understanding?

valid mist
#

trying

mighty ledge
#

ok

valid mist
#

confused this has been working for weeks then i remove enitity id and it now is all wrong

mighty ledge
#

so, when you have a method or a function that you call, and it has items that you pass into it, you pass them inside opening and closing ()

#

It's only not working because @glad geode (evil) suggested making edits to the template

#

You didn't need to make edits, you could have left the template the same

mighty ledge
#

Lol

#

anyways, back to the function or method. You have 2 functions you're dealing with

#

as_timestamp()

#

and

#

state_attr()

#

when you put a function inside another function, you have to make sure opening and closing () exist for each function.

glad geode
mighty ledge
#

You have as_timestamp(state_attr('sun.sun', 'next_rising')

#

so what's missing?

valid mist
#

In my head another )

glad geode
#

yup

mighty ledge
#

Right

#

so where do you put it

#

remember

#

you have

#

as_timestamp(state_attr('sun.sun', 'next_rising')

valid mist
#

after next rising

mighty ledge
#

Yes

valid mist
#

bigger error now

mighty ledge
#

did you leave the ) after the }} when you made the initial mistake?

mighty ledge
#

You left in all your ) mistakes

valid mist
#

you just said i needed to put in 'next_rising'))

mighty ledge
#

Right

#

but you made a bunch of ) errors when you were trying things out

#

and you didn't remove them

#

I count 2

valid mist
#

value_template: >
{{ as_timestamp(state_attr('sun.sun', 'next_rising')) | timestamp_custom)(' %I:%M %p') | replace(" 0", "") }}

mighty ledge
#

still see 1

valid mist
#

arrh after custom

mighty ledge
#

yep

valid mist
#

Invalid config for [sensor.template]: [nextsunset] is an invalid option for [sensor.template]. Check: sensor.template->sensors->nextsunrise->nextsunset. (See ?, line ?).

mighty ledge
#

Do yourself a favor, use a text editing software that highlights opening and closing brackets, quotes and {}

valid mist
#

using vsc

mighty ledge
#

now you have to fix nextsunset

#

with the same things you fixed in next rising

ivory delta
#

But first, fix the indentation πŸ˜‰

valid mist
#

{{ as_timestamp(state_attr('sun.sun', 'next_rising')) | timestamp_custom (' %I:%M %p') | replace(" 0", "") }}
icon_template: mdi:weather-sunset-down

ivory delta
#

It thinks nextsunset is a child of nextsunrise

valid mist
#

already had done that

mighty ledge
#

that looks good

#

but it has next_rising not whatever the key is for next sunset

valid mist
#

config passed now adjusted spaces

#

but yes it has wrong name

#

next_rising should it be next_setting?

glad geode
#

Yeah, it should

valid mist
#

done error gone

#

i have one more but not sure if it is a template issue

#

Logger: homeassistant.components.sonos.media_player
Source: components/sonos/media_player.py:692
Integration: Sonos (documentation, issues)
First occurred: 14:40:09 (2 occurrences)
Last logged: 14:40:09

Unhandled favorite 'Episode Five: Cyber Power (Part II) - Hacking ISIS': Unknown UPnP class: object.item.audioItem.podcast

#

I have checked the Sonos and removed the podcast from the playlist re powered it but error still keeps popping up

glad geode
valid mist
#

cheers for you help

glad geode
#

πŸ‘

granite whale
#

hello I have a list of sensors with different numeric attributes and I would like to sort the sensors in ascending order on an attribute how can I proceed?

ivory delta
#

Have you checked the pins? There's a bunch of filters you can use for utility stuff like that.

brisk nebula
#

Hi everyone, I'm having a small problem with a value_template of a mqtt sensor that receives data in the json format. My themplate is the following: "{% if value_json['State'] == '7' %}{{now()}}{% endif %}" THe sensor value is always null. Is there something wrong with the template?

#

Just found the problem. There should be no '' around 7.

brisk nebula
#

So now the sensor gets updated everytime mqtt message arrives with either now() or None. Is there a way it retains its previous value in case the if evaluates to false?

dreamy sinew
#

not unless you save that value somewhere else to pull from

brisk nebula
#

got it!

granite whale
#

hello how to have a random time?

ivory delta
#

Random time of day? Random time from all history?

granite whale
#

Of day for presence simulation

sly thistle
#

I have a template sensor that is retrieving an attribute from a device, and sometimes the value changes quickly from one value to another. Is there a way to make sure every change is captured in the sensor history?

gaunt vector
#

I am using the Uptime Robot integration to pull the online status. The status shows as "Connected", but I'd like it to display "Online" instead. I tried this, but it is displaying Issues when it should be showing as Online.

sensor:
  - platform: template
    sensors:
      my_personal_website_status:
        friendly_name: "My personal website status"
        value_template: >-
          {% if is_state('binary_sensor.my_personal_website', 'Connected') %}
            Online
          {% else %}
            Issues
          {% endif %}

Is it because uptimerobot is a binary_sensor & I made the template within sensor?

sly thistle
#

Put that in your template screen and you will see my_personal_website is not what you expected

gaunt vector
#

I put this into Developer tools > Template:

My website is: {{ binary_sensor.my_personal_website }}

{% if is_state('binary_sensor.my_personal_website', 'Connected') %}
  Online
{% else %}
  Issues
{% endif %}

I got this result: UndefinedError: 'binary_sensor' is undefined but I am using binary_sensor.my_personal_website to display Connected in LoveLace currently. Why is that? Forgive me, I am very new to this.

dreamy sinew
#

since you put it inside {{}} it thinks its a variable which it isn't and fails

gaunt vector
#

{{ states.binary_sensor.my_personal_website }} seems to return:

<template TemplateState(<state binary_sensor.my_personal_website=on; attribution=Data provided by Uptime Robot, target=https://mypersonalwebsite.com, friendly_name=My personal website, device_class=connectivity @ 2021-02-24T19:39:22.361753-05:00>)>
#

I'm not sure where to find the "Connected" status that binary_sensor.my_personal_website is reporting in lovelace.

#

AHA, just figured it out.

{% if is_state('binary_sensor.my_personal_website', 'on') -%}
  Online
{%- else -%}
  Offline
{%- endif %}

It is reporting as On, not Connected.

iron night
#

Hello everybody.

#

I have this timer:

time_warm_floor:
name: Π’Π΅ΠΏΠ»Ρ‹ΠΉ ΠΏΠΎΠ» Π²Ρ‹ΠΊΠ» Ρ‡Π΅Ρ€Π΅Π· -
duration: '05:00:00'

Its working, but I need to enter this parameter manually from Lovelace. I create input_datetime:

input_time_timerwarmfloor:
name: Π’Π°ΠΉΠΌΠ΅Ρ€ Ρ‚Π΅ΠΏΠ»ΠΎΠ³ΠΎ ΠΏΠΎΠ»Π°
has_date: false
has_time: true

I change the timer parameters to:

time_warm_floor:
name: Π’Π΅ΠΏΠ»Ρ‹ΠΉ ΠΏΠΎΠ» Π²Ρ‹ΠΊΠ» Ρ‡Π΅Ρ€Π΅Π· -
duration: '{{ states("input_datetime.input_time_timerwarmfloor") }}'

And I get a configuration error:
Invalid config for [timer]: offset {{ states("input_datetime.input_time_timerwarmfloor") }} should be format 'HH:MM', 'HH:MM:SS' or 'HH:MM:SS.F' for dictionary value @ data['timer']['time_warm_floor']['duration']. Got '{{ states("input_datetime.input_time_timerwarmfloor") }}'. (See /config/configuration.yaml, line 9).

Help me please.

glossy viper
#

@iron night put your code on share code site like pastebin.ubuntu

thorny snow
#

My power supply company has an API from where I can read my power consumption, grouped in 15 min intervals.
But the data is not up-to-date, as they have a time delay of ~8h.
Does anybody know how could I tell HA to time-shift the values?

iron night
iron night
glossy viper
#

as far as my knowledge is very limited in this i can see that offset should be in another format , not jinja, but time

#

but i cannot help you

median citrus
#

can someone give me a hint? I have an entity with lots of attributes. If I use
{{state_attr('weather.dwd_weather_duesseldorf', 'forecast')}}
it returns

  {
    "datetime": "2021-02-25",
    "condition": "rainy",
    "temperature": 18,
    "templow": 11,
    "precipitation": 1.1,
    "precipitation_probability": 58
  },
  {
    "datetime": "2021-02-26",
    "condition": "rainy",
    "temperature": 11,
    "templow": 4,
    "precipitation": 2.8,
    "precipitation_probability": 74
  }]```
however I only want to recieve the value of precipitation_probability for today. how do i do that?
glossy viper
#

maybe u can try '{{ states.sensor.dwd_weather_duesseldorf.attributes["precipitation_probability"]}}'

median citrus
#

{{states.weather.dwd_weather_duesseldorf.attributes["precipitation_probability"]}} gives no result

glossy viper
#

u put ' ' ?

median citrus
#

im trying in the template editor in lovelace

#

i think the " are only necessary in the yaml or?

glossy viper
#

oh...delete weather

#

states of sensor

#

not needed wather.dwd_weather

median citrus
#

{{states.dwd_weather_duesseldorf.attributes["precipitation_probability"]}}``` still no output
glossy viper
#

hmm...forecast needed...

median citrus
#

if i check the entity in lovelace the structure looks like this:

humidity: 66
pressure: 1026.8
wind_bearing: 161
wind_speed: 16.7
visibility: 34.7
attribution: Data provided by Deutscher Wetterdienst (DWD)
forecast:
  - datetime: '2021-02-25'
    condition: rainy
    temperature: 18
    templow: 11
    precipitation: 1.1
    precipitation_probability: 58
  - datetime: '2021-02-26'
    condition: rainy
    temperature: 11
    templow: 4
    precipitation: 2.8
    precipitation_probability: 74```
#

and i want to template in particular the precipitation probability of today and get it as a number to use it in another system

glossy viper
#

properties are on the same level as forecast for you

#

and u need an attribute of forecast

loud otter
#

Hi all, I'm trying to set up a light template and I cannot understand how to use set_color. This is the code I've done so far but it doesn't work:

    set_color:
        - service: light.turn_off
          data:
            entity_id: light.striscia_led_cucina_bianco
        - service: light.turn_on
          data:
            entity_id: light.striscia_led_cucina_rgb
            hs_color: "({{ h }}, {{ s }})"

Can someone please support me?

median citrus
#

maybe this helps you:

  action:
  - data:
      brightness: '{{states("input_number.hue_sunrise_brightness")| int}}'
      color_temp: '{{states("input_number.hue_sunrise_color") | int}}'
      transition: '{{(states(''input_number.alarm_clock_tado_wd_fadelight'')| int
        *60)}}'
    entity_id: light.bett
    service: light.turn_on
#

brightness and color_temp are integers 0-255

loud otter
#

are somehow "mandatory"?

median citrus
#

i have them exposed in lovelace so i can manually set them

loud otter
#

ah ok so you use them to change brightness for example. But how can I use color whell in webui for example?

#

color *wheel

median citrus
loud otter
#

sure but it will be impossible to set color via voice control isn't it?

median citrus
#

mhm ok i do this via siri

#

but never actually use it

#

homekit & siri natively can set lamps to defined colors

loud otter
#

so with siri you can set light color even if values are set via input_numbers??

normal badge
#

Hello!

I have the following incoming byte (the following comes all together and keeps updated) through serial as follows for example:

EE 234
AA 1234
BB 4321
CS 1264
SYS ON
HSDS 3321
PID 555
I am successfully decoding the serial and added it as a sensor. It does not show all values at once the hassio but I see it quickly go through all the lines, i.e.:

#

VoltageFriendly HSDS 3321

#

How can I parse all the above key values into separate sensors?

#

I tried the following:

-   platform: template
    sensors:
        mysensororvoltage:
            friendly_name: VoltageFriendly
            unit_of_measurement: "mV"

value_template: "{{ states('sensor.500w_rs232').split('\n')[1]}}"

            value_template: "{{ state_attr('sensor.500w_rs232','PID') }}"
dreamy sinew
#

one sensor with the raw values and then individual sensors that parse that one for their targeted values

normal badge
# dreamy sinew one sensor with the raw values and then individual sensors that parse that one f...

That is an interesting idea.

  -   platform: template
        sensors:
            myrawsensor:
                 value_template: "{{ states('sensor.500w_rs232')}}"
            mysensororvoltage:
                friendly_name: VoltageFriendly
                unit_of_measurement: "mV"
#                value_template: "{{ states('sensor.500w_rs232').split('\n')[1]}}"
                value_template: "{{ state_attr('sensor.500w_rs232','PID') }}"

How can I target VoltageFriendly to one parameter in the raw sensor?

dreamy sinew
#

what are the actual control charecters in that string? is it \n?

normal badge
#

Each byte is sent with the above string I showed as a block. Between each parameter and it is value (separated by tab) there is \n

#

So for example (from the above string), the goal is to create sensors as follows:
sensorEE = 234, sensorAA=1234, and so on..

dreamy sinew
#

yeah, this is kinda tricky to deal with

#
{{ value.split()[-1] }}
{% endfor %}```
#

replace sensor with states('sensor.myrawsensor')

#

replace PID with whatever one you're wanting to pull

#

that's as concise as i could get it

normal badge
crimson sun
#

Hey everyone! Im a complete beginner if it comes to Home Assistant and i cant get a template to work. I got my Fritz!DECT 210 Today. It works fine with my Fritz!box and i can also turn it on and off on Home Assistant. But i try to get the current_power_w, total_consumption and such. so i can display them better.

sensor:
  - platform: template
    sensors:
      fritz_dect_210_1_watts:
        friendly_name_template: "{{ states.switch.fritz_dect_210_1.name}} Aktueller Verbrauch"
        value_template: '{{ states.switch.fritz_dect_210_1.attributes["current_power_w"]}}'
        unit_of_measurement: "W"
      fritz_dect_210_1_total_kWh:
        friendly_name_template: "{{ states.switch.fritz_dect_210_1.name}} Gesamt Verbrauch"
        value_template: '{{ states.switch.fritz_dect_210_1.attributes["total_consumption"]}}'
        unit_of_measurement: "kWh"
      fritz_dect_210_1_temperature:
        friendly_name_template: "{{ states.switch.fritz_dect_210_1.name}} Aktuelle Temperatur"
        value_template: '{{ states.switch.fritz_dect_210_1.attributes["temperature"]}}'
        unit_of_measurement: "Β°C"
#

thats my config, but i always get the error

Invalid config for [sensor.template]: invalid slug fritz_dect_210_1_total_kWh (try fritz_dect_210_1_total_kwh) for dictionary value @ data['sensors']. Got OrderedDict([('fritz_dect_210_1_watts', OrderedDict([('friendly_name_template', '{{ states.switch.fritz_dect_210_1.name}} Aktueller Verbrauch'), ('value_template', '{{ states.switch.fritz_dect_210_1.attributes["current_power_w"]}}'), ('unit_of_measurement', 'W')])), ('fritz_dect_210_1_total_kWh', OrderedDict([('friendly_name_template', '{{ states.switch.fritz_dect_210_1.name}} Gesamt Verbrauch'), ('value_template', '{{ states.switch.fritz_dect_210_1.attributes["total_consumption"]}}'), ('unit.... (See /config/configuration.yaml, line 13). Please check the docs at https://www.home-assistant.io/integrations/template

I cant read what is wrong. Can someone help me out here to understand what the issue is?

mighty ledge
#

The error literally tells you what to do.

#

just humor me and read the first line of your error

#

it even gives you a suggestion on how to fix it.

crimson sun
#

yeah but its literally the same thing, isnt it? i did a search and replace nothing changed

mighty ledge
#

it's not

crimson sun
#

okay then im blind...

mighty ledge
#
fritz_dect_210_1_total_kWh
fritz_dect_210_1_total_kwh
#

there's a difference.

#

go character by character if you have to

crimson sun
#

no way...

mighty ledge
#

Yes way.

crimson sun
#

the fing w

mighty ledge
#

always pays to read the errors!

crimson sun
#

yeah okay now i know why my vscode told me that they are the same...

mighty ledge
#

FYI, capitals are not allowed in any field name for HA

crimson sun
#

thanks for the tipp!

#

jesus..

mighty ledge
#

np

#

how many hours you spend on that?

#

we've all done it btw

crimson sun
#

nearly 1h? xD

#

btw is there a better way to realod the config? i allways read to restart the server

#

it seams like a inefficient way

mighty ledge
#

for templates there's a template.reload service you can call from the service caller in dev tools

dreamy sinew
#

or a restart of the service vs the server

crimson sun
#

ah thanks

restive parrot
#

I want to make a copy of a fan, but with it speed in numbers instead of in words so google home/assistant can control it. This is what I have done so far:

fan:
  - platform: template
    fans:
      fan_google:
        friendly_name: "Livingroom Fan"
        value_template: "{{ if_state('fan.livingroom', 'on') }}"
        turn_on:
          service: fan.turn_on
          entity_id: fan.livingroom
        turn_off:
          service: fan.turn_off
          entity_id: fan.livingroom

It isn't working like this, and I also don't know how to the speeds.

dreamy sinew
#

if the original fan is in the fan domain it should work in google on its own

#

if it doesn't, it might be better off opening an issue to get that sorted properly rather than trying to hack around it

restive parrot
#

It shows up, but you can only turn it on and off, and it's still a little buggy

#

And well, I don't mind opening an issue, but I would like to have a workaround until the bug is fixed

dreamy sinew
#

you can set the speeds via voice

restive parrot
#

What

ivory delta
#

πŸͺ„

restive parrot
#

But speeds should show in the google home up right?

#

I mind, I don't mind, I'm using lovelace, but I want to know so I can submit an issue

dreamy sinew
#

i think its a google side thing. We use the trait correctly

#

the google things with screens show the speeds correctly but the phone apps don't for some reason

restive parrot
#

Okay, I only wanted voice control out of it anyway, so thank you for saving me the time of creating a workaround

median citrus
#

can someone help me? I have a weather entity that has a state attributes that look like this

humidity: 78
forecast:
  - datetime: '2021-02-25'
    precipitation_probability: 61
  - datetime: '2021-02-26'
    precipitation_probability: 70```

How can i setup a template that always provides the ```precipitation_probability``` of the first entry (today)
#

i cant wrap my mind around how to select a particular attribute out of the forecast list...

ivory delta
#

You access list items by their index. The first list item under forecast would be forecast[0] (don't ask why computers always count from 0...).

#

From there, you'd access the keys of dictionaries by name: forecast[0].precipitation_probability

glossy viper
#

i gave you exampel in the morning

median citrus
#

@ivory delta thanks, @glossy viper, yes you did but i didt not manage to get it working πŸ˜₯

glossy viper
#

mono...if u put state of forecast[3].precipitation_probability it will be second datetime line ?

#

or the 3rd line that has precipitation_probability?

median citrus
#

so {{states("dwd_weather_duesseldorf.attributes.forecast[0].precipitation_probability")}} ??

#

returns unknown

glossy viper
#

states sensor.dwd...

#

'{{ states.sensor

median citrus
#

{{states.sensor.dwd_weather_duesseldorf.attributes.forecast[0].precipitation_probability}}

#

'None' has no attribute 'attributes'

#

somehow I'm too stupid for this syntax 😫

#

GOT IT

#

its not sensor.XXXX but weather.XXXX

#

wrong domain!

glossy viper
#

oh...sorry...

median citrus
#

dont be sorry, you helped me! THNX!

#

and i learned something new!

glossy viper
#

πŸ™‚

#

sorry for not being profficient enough πŸ™‚

#

{{states.weather.dwd_weather_duesseldorf.attributes.forecast[0].precipitation_probability}}

#

this is it ?

median citrus
#

this did the trick:
{{states.weather.dwd_weather_duesseldorf.attributes.forecast[0].precipitation_probability}}

glossy viper
#

if u put forecast2...what it returns?

median citrus
#

the vlaue of precipitation_probability of the third entry in the forecast list

glossy viper
#

nice. ty

median citrus
#

NP

true otter
#

hey guys looking for some help with this template. I want an icon to change colors from red to green is the script's state is = on or vice versa. I tested this in templates and got no errors but obviously it not doing what I want it to. {% if is_state('script.1577302825981', 'on') %} green {% else %} red {% endif %} }

#

can anyone help me sort this out

dreamy sinew
#

{{ 'green' if is_state('script.1577302825981', 'on') else 'red' }}

#

probably not liking the extra spaces

true otter
#

so I just tried it out in the new card-mod 3.0 style: | :host { --icon-color:{{ 'green' if is_state('script.1577302825981', 'on') else 'red' }}

#

but unfortunately it is still not changing the color of the icon.

glad geode
#

You know you're setting weather twice, right?

median citrus
#

could i be that some " are missing? message: The print is '{{states("sensor.octoprint_jobpercentage_round")}}' completed

#

this is a message with a template that works for me

glossy viper
#

message: 'the print is: {{states(''sensor.immax_temperature'')}} completed'

gray loom
#

is there a device_class: magnet for magnets?

jagged obsidian
#

you have smart magnets?

gray loom
#

i have bought one and glued it to the door, now im making a template for it since its a switch

jagged obsidian
#

then you use device class door or opening

gray loom
#

thanks

#

but is it a binary_sensor?

jagged obsidian
#

does it have more than two states?

gray loom
#

open and closed

jagged obsidian
#

sounds pretty binary to me

silk smelt
#

Is it possible to create and update an entity with numerous attributes based on different sensors?

ionic grotto
#

Hello, i have a question, hope somebody can help me. I have a Shelly 3EM power monitor, which gives me three values for my three phases power line (so current consumption Phase 1-3). I want to have a power metering over all three phases. I tried the following as a sensor:

  • platform: template
    sensors:
    haupthaus_kw:
    friendly_name: "Haupthaus kWh"
    unit_of_measurement: "W"
    value_template: "{{ states('states.sensor.shelly_shem_3_84cca8ad55d3_1_current_consumption') + states('sensor.shelly_shem_3_84cca8ad55d3_2_current_consumption') + states('sensor.shelly_shem_3_84cca8ad55d3_3_current_consumption') }}"
    this did not work.
dreamy sinew
#

string math

#

you need to convert those values to int/float to add them

ionic grotto
#

soo, like
value_template: "{{ states('states.sensor.shelly_shem_3_84cca8ad55d3_1_current_consumption')| int + states('sensor.shelly_shem_3_84cca8ad55d3_2_current_consumption')|int + states('sensor.shelly_shem_3_84cca8ad55d3_3_current_consumption')|int }}"
?

#

that seems to work πŸ™‚

bright quarry
#

how do i insert a linebreak in this part of my automation? ex;

      - service: input_text.set_value
        data:
          value: Basement Motion Sensor on {{ now().strftime("%a, %b %d at %I:%M %p")}}
        entity_id: input_text.lastusedss

after "Basement Motion Sensor" i want a line break.

ionic grotto
#

just a hunch, did you try \n ? like "Basement Motion Sensor\n on "? \n ist newline in most programming languages.

bright quarry
#

do i have to put it in apostrophe or quotes?

#

didn't work. 😦

#

also put in quotes and doesn't work.

ivory delta
#

I don't think an input text can have a multi-line value πŸ€·β€β™‚οΈ

#

Test it in Dev Tools.

bright quarry
#

i've tried quote and apostrophe but it parses in the card view as Justin South Window'\n' on Fri, Feb 26 at 12:56 PM

dreamy sinew
#
      - service: input_text.set_value
        data:
          value: "{{ 'Basement Motion Sensor on \n {}'.format(now().strftime('%a, %b %d at %I:%M %p')) }}"
        entity_id: input_text.lastusedss
#

try that

bright quarry
#

looks good, thank you. @dreamy sinew

dreamy sinew
#

need to construct the full string in one go otherwise weirdness happens

ivory delta
#

Delete that and share it with a code sharing tool, please. The rules are no code walls over 15 lines (see #rules )

pure pulsar
#

ok

#

I have to figure out how to use a code sharing tool, thanks

stone lintel
#

I’m trying to reverse this automation with templates so that it triggers when a device comes back online, does anyone have any advice or should I look at a new automation? https://pastebin.com/Z7u1EjY1

true otter
#

Can anyone help sort this out. I am using this template to change the color of icon elements based on the state of of the entity. It appears that the first 2 conditions work , but for the idle state I want the icon to change to green and that is not working {% if is_state_attr('climate.ecobee_lite3', 'hvac_action', 'cooling') %} 'blue' {% elif is_state_attr('climate.ecobee_lite3','hvac_action', 'heating') %} 'orange' {% elif is_state_attr('climate.ecobee_lite3', 'hvac_action', 'idle') %} else 'green' {% endif %}

#

I am not getting any error messages when I check it in templates, is there any where else I can validate the the string is correct?

dreamy sinew
#

You're not handling your else properly

#

But that can be simplified anyway