#templates-archived

1 messages ยท Page 22 of 1

earnest cosmos
#

Remember I need to use this in an automation/script controlling the lighting, So I need to set some sort of status here.

silent seal
#

You could also just set a boolean helper to start with instead of going through MQTT

earnest cosmos
#

Ah. OK that makes sense, just setting the state for the tracker. I already have a tracker on her device, but I would probably do this for person.xxx

silent seal
#

I wouldn't modify an existing device, or the person.

#

Mostly because if the device updates, the person will update and it will assume you're home

earnest cosmos
#

Sure. I could just make a new boolean to tell.

silent seal
#

Yup ๐Ÿ™‚

earnest cosmos
#

It makes me re-think this, though

#

I have a presence/tracker for my mother which uses connected to my WiFi as device tracker/trigger

#

And it triggers when her iPhone reconnects to my WiFi, making it appear like se is coming to our house. Happends several times, and would be nice to by-pass. I do not want to install the app on her iPhone

silent seal
#

How are you doing the connected to wifi test? I presume through a router integration?

rose scroll
# earnest cosmos It makes me re-think this, though

In addition to Rosemary's suggestion on a prompt for a user to manually confirm if the house is empty, do you also have internal sensors that can tell if the house is occupied? Eg. PIR sensors. If the max time your daughter spends without moving is 20min, you could set the house to shut down if all PIR sensors are off for >30min.

silent seal
#

I would be careful with that, if she's home sick or asleep then that might have undesired results

rose scroll
#

That's true too.

willow belfry
#

Can anyone clarify why this template would return a valid result in the Template Developer tool but cause the Check Configuration feature to fail?

  sensors:
    sensor name: 
      friendly_name: "Outside Temp"
      value_template: "{{ state_attr('weather.home','temperature') }}"
#

Check configuration returns this specific error.
Invalid config for [sensor.template]: invalid slug sensor name (try sensor_name) for dictionary value @ data['sensors']. Got OrderedDict([('sensor name', OrderedDict([('friendly_name', 'Outside Temp'), ('value_template', "{{ state_attr('weather.home','temperature') }}")]))]). (See ?, line ?).

silent seal
#

Because you've mismashed the old and the new template sensor format

#
template:
  - sensor:
      - name: "Outside Temp"
        state: "{{ state_attr('weather.home','temperature') }}"
willow belfry
#

Interesting. And here I thought the VS Code addon was doing me a favor by "auto-completing" the template format.

silent seal
#

It's only as good as it can be, there are other sensors which use a similarish format, but in general try to copy and paste from the docs and then modify if you don't know the syntax

#

Also, you can tell it's 3am, I messed up with the value_template above, it's state

obsidian lintel
#

{{ expand(states.media_player) | selectattr('state','eq','on') | rejectattr('attributes.browserID', 'defined') | list | count }}

How do I select all media player that is "on" and "playing"

inner mesa
#

selectattr('state', 'in', ['on', 'playing'])

obsidian lintel
#

Thanks RobC!

inner mesa
#

Actually I think you edited that?

#

Is 'on' and 'playing' just 'playing'?

obsidian lintel
#

on and playing

inner mesa
#

Right, what does that mean?

#

What do you test for that?

obsidian lintel
#

Any device that has the states, "on" and "playing" will be counted

#

media_players specifically

inner mesa
#

My guess is a state of 'playing'

obsidian lintel
#

Yup

inner mesa
#

Anyway, that will do 'on' or 'playing'

obsidian lintel
#

ah, how do I do and

inner mesa
#

What, exactly, do you want to test, and for what?

obsidian lintel
#

Trying to create a card that tells me the number of devices that are turned on, or playing some media.

inner mesa
#

I think you mean 'or', anyway

obsidian lintel
#

Oh yeah

inner mesa
#

You keep dodging

obsidian lintel
#

states cant have 2 states, thats why

inner mesa
#

Alright

obsidian lintel
#

You are right, my bad, I phrased the question wrongly

#

What you gave was exactly what I wanted

#

Thanks!

#

I have one more question however.

#

{{ expand(states.binary_sensor) | selectattr('state','eq','on') | selectattr('attributes.device_class', 'eq', 'motion') | rejectattr('attributes.browserID', 'defined') |ย listย |ย countย }} Detected

How do I only display the motion sensors?

inner mesa
#

Probably that

obsidian lintel
#

UndefinedError: 'homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'device_class'

#

Getting this error tho

#

Ah nvm, I got it

inner mesa
#

You need to add a rejectattr like you already have

obsidian lintel
#

Oh wait

inner mesa
#

Or the opposite

obsidian lintel
#

Yeah I didnt, you are right about the reject

ember cloud
#

Thanks. Yes this is binary_sensor.door_window_open a group indeed. I got this now TypeError: '<=' not supported between instances of 'int' and 'str'

inner mesa
#

Remove the quotes around 3

ember cloud
#

Just figured that thanks.

steel socket
#

hey all newb here, quick Q. And/OR is there a special for it? some way to (is_state('device_tracker.me', home) and/or is_state('device_tracker.partner',home)
or
((is_state('device_tracker.me', home) and is_state('device_tracker.partner',home)) or ((!is_state('device_tracker.me', home) and !is_state('device_tracker.partner',home))
thanks!

inner mesa
#

Replace ! with not?

#

Not sure what you're asking

steel socket
#

OH right

#

uh askin if it's... well... guess i was askin how i do? but i guess it's #2 via s/!/not and that'll do yeah?

solemn frost
#

If you're just checking for whether either one of two people is home, you can use the state of zone.home to see how many people are home

steel socket
#

well that's helpful

#

danke

solemn frost
#

If you need to do more advanced things like check if specific people are home, while excluding others, then you'd have to resort to templates or other methods

steel socket
#

i want to hide the map if we're both home or we're both out is all

#

so if zone.home's count is 1 then show, essentially.

#

yeah that works. danke

analog mulch
#

I have a scraper that produces a list of times over the next 24 hours in the format HH:MM. I would like to convert it to timestamps. For the times today, this is easy using the today_at filter, but whatโ€™s the efficient way of doing it for the whole upcoming 24 -hour period.

sacred sparrow
#

I have a Zigbee2MQTT switch that changes from the state of the button that was pressed to blank so I made this:

    - name: Living Room Table Switch
      icon: hue:dimmer-switch
      state: >
        {% set action = states('sensor.living_room_table_switch') %}
        {{ this.state if action is none else action  }}

for some reason it won't work

#

I want the template to not show the state if its none

plain magnetBOT
thorny snow
#

I have problems with using the new template format in packages.
I get "expected a dictionary for dictionary value @ data['packages']['sensor']"
It was supposed to be solved a year ago but dunno if it got broken again? https://github.com/home-assistant/core/issues/49212

#
#OPTION 1
#configuration.yaml
homeassistant:
  packages: !include_dir_merge_named packages/
โ€‹
#packages/solar.yaml
template:
  sensor:
    - name: "power solar total"
      unit_of_measurement: "kW"
      device_class: power
      state: >-
        {% set solar = states('sensor.inverter_active_power') | float*1000 %}
        {{ (solar if (solar > 0) else 0 }}
#
#OPTION 2
#configuration.yaml
homeassistant:
  packages: !include_dir_merge_named packages/
โ€‹
#packages/solar.yaml
template:
  - sensor:
    - name: "power solar total"
      unit_of_measurement: "kW"
      device_class: power
      state: >-
        {% set solar = states('sensor.inverter_active_power') | float*1000 %}
        {{ (solar if (solar > 0) else 0 }}
marble jackal
#

I don't think it's this file which causes that error. But I do see some issues here. I don't think you can use the same key twice in a package, and you are using template: twice

#

And please format your code as code

plain magnetBOT
#

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

thorny snow
marble jackal
#

Without the second key it won't work because you formatted them differently

#

One with - before sensor, one without

thorny snow
marble jackal
#

Well, I'm sure that template works in packages, because I use it myself

#

Option 2 is correct btw, with the -

thorny snow
marble jackal
#

Yes, and because it doesn't say ['packages']['template']['sensor'] I would say it's caused by something else based on this error

thorny snow
#

hmm ok thanks I trust you and will continue to look ๐Ÿ˜‰

marble jackal
#

Wait, I see the problem

marble jackal
#

With this include it doesn't use the filename as name of the package

#

So you now named the package template

#

And then you are using the sensor integration, which is indeed expecting a dict and not a list

#

So you need to use

solar:
  template:
    - sensor:
        - name: ...
#

Which will name the package solar

#

Or you need to use !include_dir_named

thorny snow
#

Ahhhh! Thanks!! Now it finally seems to work! ๐Ÿ˜„

#

Ok followup question... which is correct?

#OPTION 1

template:
  - sensor:
    - name: "power solar total"
    - name: "power solar consumed"

#OPTION 2

template:
  - sensor:
    - name: "power solar total"
  - sensor:
    - name: "power solar consumed"
marble jackal
#

None of those is incorrect

#

But I would use the first one when creating two (or more) template sensors in the same YAML file

thorny snow
#

nice, thanks!

thorny snow
# marble jackal None of those is incorrect

Hmm it seems that the sensor.power_solar_total will not show up and there is no error message. Isn't it supposed to be "0" at least at all times?
How do i error seek if I get no error?
homeassistant:
packages: !include_dir_named packages/

template:
  - sensor:
    - name: "power solar total"
      unit_of_measurement: "kW"
      device_class: power
      state: >-
        {% set solar = states('sensor.inverter_active_power') | float*1000 %}
        {{ (solar if (solar > 0) else 0 }}
marble jackal
#

If you are still using include_dir_merge_named you still need to add the package name in the YAML

#

And it will be sensor.power_solar_total

thorny snow
thorny snow
#

configuration.yaml

homeassistant:
  packages: !include_dir_named packages/

packages/solar.yaml

template:
  - sensor:
    - name: "power solar total"
      unit_of_measurement: "kW"
      device_class: power
      state: >-
        {% set solar = states('sensor.inverter_active_power') | float*1000 %}
        {{ (solar if (solar > 0) else 0 }}
marble jackal
#

Did you reload template entities from devtools > yaml?

thorny snow
# marble jackal Did you reload template entities from devtools > yaml?

Yes, and that shows no error. However it seems like i get error if I restart the whole HA

Logger: homeassistant.config
Source: config.py:865
First occurred: 12:42:20 (1 occurrences)
Last logged: 12:42:20

Invalid config for [template]: invalid template (TemplateSyntaxError: unexpected '}', expected ')') for dictionary value @ data['sensor'][0]['state']. Got "{% set solar = states('sensor.inverter_active_power') | float*1000 %} {{ (solar if (solar > 0) else 0 }}". (See /config/packages/solar.yaml, line 31).

marble jackal
#

Yes, you are missing a closing parenthesis in the last line

thorny snow
marble jackal
#

You could also do this BTW

state: "{{ [0,  states('sensor.inverter_active_power') | float*1000] | max }}"
thorny snow
knotty plank
#

hi comunity
have a question about a counter i did
{{states.light | selectattr('state','eq','on') | list | count}}

do somebody know if it is possible to take away entitys inside the code?

mighty ledge
#

rejectattr('entity_id', 'in', ['light.foobar'])

knotty plank
#

Thx @mighty ledge i will test it ๐Ÿ™๐Ÿป

fading patio
#

This is likely very easy for you all... is using is_state() better or is the way I am trying sufficient as well? Also getting the error below when trying to add the second condition.
{{ trigger.to_state.state == "Charging" && trigger.from_state.state != "Fully Charged" }}
says "Message malformed: invalid template (TemplateSyntaxError: unexpected char '&' at 40) for dictionary value @ data['condition'][0]['conditions'][0]['conditions'][1]['value_template']"

silent seal
#

Here you need to use == because it's a trigger variable

#

If you were using an entity (e.g. light.bedroom), then you would want to use is_state because it will fail gracefully if that device is not available/ready yet (e.g. on startup) instead of causing errors

fading patio
#

Why is it balking at my && is that not the correct connector?

#

oh geez, do I just use and instead of &&?

mighty ledge
#

it's jinja. and, or, if, else etc all words

fading patio
#

How do I debounce this template so that it only says "Fully Charged" after it has been in that state for say 5 minutes

        {% set chg_on = is_state('switch.wheelchair_charger_plug_relay', 'on') %}
        {% set chg_current = (states('sensor.wheelchair_charger_plug_current') | float) %}
        {% set chg_power = (states('sensor.wheelchair_charger_plug_power') | float) %}
        {% if not chg_on %}
          Off
        {% elif chg_on and chg_power < 2.00 %}
          Idle
        {% elif chg_on and chg_power > 6.00 %}
          Charging
        {% elif chg_on and 2.00 <= chg_power <= 6.00 %}
          Fully Charged
        {% else %}
          Error
        {% endif %}
mighty ledge
#

You have to switch to trigger based templates or track the time using math

fading patio
#

Which would you suggest? This is just used to visually give a text representation of the power. I am not aware of triggers for template other than in an automation and this is just like a text sensor. Could you provide an example?
Trying to debounce this: https://imgur.com/a/jCW2szq

marble jackal
#

The docs explain it quite well, you can use the same triggers as you can in an automation

plain magnetBOT
plain magnetBOT
spark wigeon
#

I'm missing something, how do I set value_template based on something that is parsed to attributes?

inner mesa
#

{{ value_json.value }} or whatever

#

I'm not sure how that relates to the json_attributes_path, though

#

you'll need to factor that into the expression

spark wigeon
#

value_json[0].value kinda works, but gets the one that's the first one in json, not the one that is parsed as attributes. I'm wondering if I can access those in the value_template in any way.

inner mesa
#

not that I'm aware of

spark wigeon
#

Oh man ๐Ÿ˜ฆ

inner mesa
#

but you should be able to represent that path in the reference in value_template

#

it's just JSON, after all

spark wigeon
#

What the are attributes used for at all then? ๐Ÿ˜ฆ

inner mesa
#

for the entity that you're creating

#

And whatever you wanted to do with them. It's not just creating variables for you to reference later

#

in other words, just not for the use that you immediately have

plain magnetBOT
mint drift
#

With these changes, the template will only display "Fully Charged" if the "Fully Charged" state has been reached for at least 5 minutes.

pseudo steeple
#

Getting weird reading for a templated sensor https://photos.app.goo.gl/RzrkqEmV6PieVCU5A afaik the binary sensor it is using is staying in state on

- platform: template
  sensors:
    dryer_runtime:
      friendly_name: Dryer Runtime
      value_template: >
        {% set x = states('sensor.time') %}
        {% set t = 0 if states('binary_sensor.dryer_status') == 'off' else now().timestamp() - states.binary_sensor.dryer_status.last_changed.timestamp() %}
        {{ t | timestamp_custom('%H:%M', false) }}
      icon_template: >-
        {{ 'mdi:tumble-dryer' if is_state('binary_sensor.washer_status','on') else 'mdi:tumble-dryer-off' }}
- platform: template
  sensors:
    washer_runtime:
      friendly_name: Washer Runtime
      value_template: >
        {% set x = states('sensor.time') %}
        {% set t = 0 if states('binary_sensor.washer_status') == 'off' else now().timestamp() - states.binary_sensor.washer_status.last_changed.timestamp() %}
        {{ t | timestamp_custom('%H:%M', false) }}
      icon_template: >-
        {{ 'mdi:washing-machine' if is_state('binary_sensor.washer_status','on') else 'mdi:washing-machine-off' }}
#

anyone have any thoughts?

plain magnetBOT
obtuse zephyr
#

Pretty sure last_changed isn't just a state change, too. It could update and the state remains the same

pseudo steeple
#

Oh neat! Thanks i'll take a peak

#

โค๏ธ

void idol
#

Hi there

#

How do I hide a custom template sensor from the UI?

#

In the GUI, it doesn't seem to have the radio buttons for "Enabled", "Hidden" and "Disabled"

obtuse zephyr
# void idol Hi there

Hmm... Settings -> Advanced Settings, you don't see the radios? Does it not have a unique_id?

marble jackal
obtuse zephyr
void idol
obtuse zephyr
#

Yep

void idol
#

Ah ok

#

Will update it in the morning and report back

#

Thank you

obtuse zephyr
#

You're welcome

void idol
#

Will I set the unique id to something like sensor.name_goes_here?

obtuse zephyr
#

Can be pretty much anything you want, some use the sensorname w/ underscore like you've got, others use a GUID, but yeah that's fine

void idol
#

Got it, will try that

plain magnetBOT
inner mesa
#

seems not

sacred sparrow
#

I have a Zigbee2MQTT switch that changes from the state of the button that was pressed to blank so I made this: - name: Living Room Table Switch icon: hue:dimmer-switch state: > {% set action = states('sensor.living_room_table_switch_action') %} {{ this.state if action is none else action }}

for some reason it won't work
I want the template to not show the state if its none

inner mesa
#

If you want to test "blank", then use ""

#

and test it in devtools -> Templates first

sacred sparrow
#
{{ this.state if action is "" else action  }}```
#

I tried that yesterday and go "TemplateSyntaxError: expected token 'name', got 'string'"

inner mesa
#

use "==" instead of "is"

sacred sparrow
#
{{ this.state if action == "" else action  }}```
#

worked for the first initial press

#

but now its not changing

inner mesa
#

what do you mean?

sacred sparrow
#

it changed to "off_press" now it wont change to anything else

#

I am pressing the other buttons and its not changing

#

it should show "off_press_release" etc

sacred sparrow
#

is there a way to get the state from the event sensor?

event_type: state_changed
data:
  entity id: sensor.living_room_table_switch_action
  old state:
    entity_id: sensor.living_room_table_switch_action
    state: off_hold_release```
inner mesa
#

of course, but that's not your problem here

#

and there's no need to use the event to get the state

sacred sparrow
#

If I can just use the "old_state" that doesnt change like the state of the switch

inner mesa
#

use a state trigger and use trigger.from_state.state

sacred sparrow
#

I'll have to find some examples - I have never used trigger.from_state.state

inner mesa
#

there are lots of examples in the third link in the channel topic

sacred sparrow
#

already looking at them ๐Ÿ™‚ just trying to get my head around how I can use it here

sacred sparrow
#
- trigger:
    - platform: state
      entity_id: sensor.living_room_table_switch_action
  sensor:
    - name: Living Room Table Switch
      icon: hue:dimmer-switch
      state: >
        {% set action = states('sensor.living_room_table_switch_action') %}
        {{ trigger.from_state.state if action == "" else action  }}
#

worked perfectly ๐Ÿ™‚

plain magnetBOT
devout haven
#

that's annoying. here i was thinking i was helping by putting the entire situation in a single post. now it's sort of impossible to read.

obtuse zephyr
#

It's best to put the code into a site like pastebin

devout haven
#

i did.. it's in github gists. if you want i can re-paste the links.

obtuse zephyr
#

Mainly the last service call piece

devout haven
silent seal
#

Have you tried to fix the #zigbee-archived light directly with say a quirk or similar?

devout haven
silent seal
#

That I'm not 100% sure on, I use Zigbee2MQTT myself. But someone in the #zigbee-archived channel can likely point you in the right direction ๐Ÿ™‚

devout haven
silent seal
#

I suspect, but this is without diving too deep, that your params section isn't what it expects

#
              hue: -{%- h %}
              saturation: -{%- s %}
              transition_time: -{%- transition %}`

h, s and transition are not defined here, and you're also not outputting data.

#

To output data you use {{ double curly brackets }}

obtuse zephyr
#

and the template isn't a string

devout haven
#

you are correct. it was that params. the error was pointing me to the parent data map so i never looked at thos.

silent seal
#

Lucky guess points to me ๐Ÿ˜‚

devout haven
#

so, the reason i used the script syntax there was because i tried to {{ h }} and {{ s }} there but then it complained that h and s weren't defined. i coudln't figure out what is passed from the ui i guess.

#

i saw other templates that used {{ h }} and {{ s }}. i guess i should have asked first why neither one was defined for me.

#

the exact error message is Error loading /config/configuration.yaml: invalid key: "OrderedDict([('h', None)])" in "/config/gledopto_family_room_display.yaml", line 79, column 0

obtuse zephyr
#

Kind of sounds like something isn't quoted

#

What does the YAML look like

devout haven
#

it's updated at that gist url

obtuse zephyr
#

You have to quote the templates

#

"{{ h }}"

devout haven
#

yeah, that was it. i guess i didn't understand why some were quoted and some weren't either. whatever the > is doing after a key seems to be like a multi-line string i guess?

silent seal
#

It is indeed

devout haven
#

i do not understand enough yaml. probably best for me to go do some reading there.

silent seal
#

There are some useful links in the pinned posts ๐Ÿ™‚

devout haven
silent seal
#

You're welcome ๐Ÿ™‚

devout haven
#

i can't get the quirk to work and the zigbee channel seems busy or uninterested. i have the template working however. the problem i have now though is that since i'm not giving definitions for level_template, temperature_template and color_template any time i go back to the entity the values are reset and are not synced to the device's state. what is the best way to solve this? should i create helpers to store the values or should i make zigbee calls to read the attributes? here is the updated template btw https://gist.github.com/codahq/dbc5865f5081022bf6c362f621c5929f

plain magnetBOT
frosty grotto
heavy crown
#

try this...

#

change value_template: "Road name: {{ value_json['data']['place'] }}" in value_template: "{{ value_json['data']['place'] }}"

#

change resource: https://nominatim.openstreetmap.org/search?q= "{{ value_json['data']['place'] }}"&format=xml&polygon_geojson=1&addressdetails=1

#

in resource: https://nominatim.openstreetmap.org/search?q= {{states('sensor.location')}}"&format=xml&polygon_geojson=1&addressdetails=1

#

I cannot test the first sensor, no clue how to do this so am assuming it works and kicks back a streetname....you do not need the words "Road name" in its state imo...just the plain streetname

frosty grotto
frosty grotto
# heavy crown in ```resource: https://nominatim.openstreetmap.org/search?q= {{states('sensor.l...

I got these from the log

2022-12-29 16:20:13.010 DEBUG (MainThread) [homeassistant.components.rest.data] Updating from https://nominatim.openstreetmap.org/search?q= {{states('sensor.location')}}"&format=xml&polygon_geojson=1&addressdetails=1
2022-12-29 16:20:13.585 DEBUG (MainThread) [httpx._client] HTTP Request: GET https://nominatim.openstreetmap.org/search?q=%20%7B%7Bstates('sensor.location')%7D%7D%22&format=xml&polygon_geojson=1&addressdetails=1 "HTTP/1.1 200 OK"
2022-12-29 16:20:13.592 DEBUG (MainThread) [homeassistant.components.rest] Finished fetching rest data data in 0.582 seconds (success: True)
2022-12-29 16:20:13.593 DEBUG (MainThread) [homeassistant.components.rest.sensor] Data fetched from resource: <?xml version="1.0" encoding="UTF-8" ?>
2022-12-29 16:20:13.594 DEBUG (MainThread) [homeassistant.components.rest.sensor] JSON converted from XML: {"searchresults":{"@timestamp":"Thu, 29 Dec 22 08:20:13 +0000","@attribution":"Data ยฉ OpenStreetMap contributors, ODbL 1.0. http://www.openstreetmap.org/copyright","@querystring":" {{states('sensor.location')}}\"","@more_url":"https://nominatim.openstreetmap.org/search/?q=+%7B%7Bstates%28%27sensor.location%27%29%7D%7D%22&addressdetails=1&polygon_geojson=1&format=xml"}}
2022-12-29 16:20:13.595 DEBUG (MainThread) [homeassistant.components.rest.sensor] Data fetched from resource: <?xml version="1.0" encoding="UTF-8" ?>
2022-12-29 16:20:13.596 DEBUG (MainThread) [homeassistant.components.rest.sensor] JSON converted from XML: {"searchresults":{"@timestamp":"Thu, 29 Dec 22 08:20:13 +0000","@attribution":"Data ยฉ OpenStreetMap contributors, ODbL 1.0. http://www.openstreetmap.org/copyright","@querystring":" {{states('sensor.location')}}\"","@more_url":"https://nominatim.openstreetmap.org/search/?q=+%7B%7Bstates%28%27sensor.location%27%29%7D%7D%22&addressdetails=1&polygon_geojson=1&format=xml"}}
#

It seems taking it as string as well? Since the road name is None now, should't it be none as well? I expect it become like this:
https://nominatim.openstreetmap.org/search?q= none&format=xml&polygon_geojson=1&addressdetails=1

mint drift
# plain magnet <@195697837277708288> I converted your message into a file since it's above 15 l...

rest:

heavy crown
#

But 'ๆ–ฐๅŒ—ๅธ‚ๆž—ๅฃๅ€ๆ–‡ๅŒ–ๅŒ—่ทฏไธ€ๆฎต299ๅทท20่™Ÿ' cannot be used as string in the second sensor (not with me in EU)

#

This one seems to work wrt to getting the data, still openstreetmap cannot handle the non-latin part

plain magnetBOT
heavy crown
#

when I use it for local street, it works fine for me

frosty grotto
#

I probably need to convert the characters in to web based encoding

void idol
obtuse zephyr
#

awesome

fading patio
# mint drift With these changes, the template will only display "Fully Charged" if the "Fully...

OK, thanks @mint drift ! However, a few things I could use assistance understanding as I am not following the logic. First, for the {% set fully_charged_timer = fully_charged_timer + 1 %} to work, that means the script is reloaded/checked every second, correct? Assuming that answer is true, wouldn't the {% set fully_charged_timer = 0 %} and {% set fully_charged_flag = false %} be setting it back to zero and false respectively every iteration? The Fully Charged inside the {% elif chg_on and 2.00 <= chg_power <= 6.00 %} shouldn't that be Charging since it hasn't hit the 5 minute mark it should not yet be considered Fully Charged. Lastly, I don' see how the code will ever get to {% elif fully_charged_flag %} since logically it will always hit the elif prior because they have the proper values. Thanks in advance for your feedback and for trying to help me out!

mint drift
# fading patio OK, thanks <@634498484828897305> ! However, a few things I could use assistance...

You're correct that the script is reloaded/checked every second in this case.

Regarding the {% set fully_charged_timer = 0 %} and {% set fully_charged_flag = false %} statements, these are only executed when the charging process has stopped, as indicated by the if not chg_on condition. When the charging process is stopped, the timer and flag are reset to their default values.

Regarding the {% elif chg_on and 2.00 <= chg_power <= 6.00 %} condition, you are also correct that this block of code should be executed when the device is "Charging" rather than "Fully Charged". The current condition only checks if the device is still charging (chg_on is True) and that the charging power is between 2.00 and 6.00. This block of code does not check if the charging process has reached the 5 minute mark.

Finally, regarding the {% elif fully_charged_flag %} condition, you are correct that this block of code may not be reached if the charging process is still ongoing and the charging power is between 2.00 and 6.00. However, if the charging process is stopped before the 5 minute mark (as indicated by the if not chg_on condition), or if the charging process reaches the 5 minute mark and the fully_charged_flag is set to True, this block of code will be executed.

thorny snow
#

Hi I am trying to acces Weather entity values by using a text sensor and I was wondering wether it would only work with templating. I am driving a nextion disaply with a ESP32devkit1 ```
text_sensor:

  • platform: homeassistant
    id: tempo
    entity_id: weather.casa trying to publish it (i.e. 'rainy') to a display using lambdas but no luck
    then:
    lambda: |-
    ESP_LOGI("main", "Value of my sensor:", id(tempo).state.c_str());
    id(nextion1).set_component_text("stanza.t3",id(tempo).state.c_str());```
    This method works fine for me with other sensor which are reacheabel using the native API, so it must be something with the weather entity. Any hint? thanks
fading patio
# mint drift You're correct that the script is reloaded/checked every second in this case. R...

So I guess the problem is it never leaves that block of code with the 2 to 6 until I unplug the charger entirely. As long as it stays plugged in it has like a trickle charge that continually stays in that range. So without some other logic it will never get outside of that to see fully charged down below. Possibly moving the fully charged to above that so that when itโ€™s true it hits it before it gets back down to the 2 to 6? Also the charger power is always on until a different automation turns the power plug off at which time the charger says itโ€™s been idle for 10 minutes. so when I unplug the chair it says Idle, and then after the 10 minutes is when the actual power plug is turned off. Iโ€™ll look over what you said in more depth once I get back to my computer. Thanks for the additional info, I think Iโ€™ll still have some more questions once I get to look at the code again.

#

Again without looking at the code on the computer, I still think that if the power goes back up to above six, something needs to reset the timer to zero so that the five minute timer starts again when it gets back inside the 2 to 6. Otherwise it seems as though thatโ€™s just a cumulative five minutes even if it has bounced out of that range say up above seven for a few minutes in between times that it goes back into the 2 to 6. Hopefully Iโ€™m making sense here.

fierce hornet
#

What is going wrong here? I have a counter entity that counts seconds. I'm trying to render it as minutes so used the following template: {{states('counter.badkamer_in_gebruik_seconden') | float / 60 | round(1)}} But for some reason it sometimes outputs values like '2.8333333333333335'

#

The rounding works fine on other sensors like a temp sensor

buoyant pine
#

you're only rounding the 60 to 1 place with that template

fierce hornet
#

ahh

buoyant pine
#
{{ (states('counter.badkamer_in_gebruik_seconden') | float / 60) | round(1) }} 
#

you should really set a default though for that float filter

fierce hornet
#

Thanks!

drifting kraken
#

I'm considering making a template that combines two switches (one that powers my PC on and one that shuts it down) but before I do so does anyone know of a way to accomplish this with a helper?

solemn frost
spice jasper
#

i am trying this

{{ย data.battery }}

but i get an error of "Input must be bytes, bytearray, memoryview, or str"

if i remove the from_json to decode the json, i see the data:

  "msg_ver": 2,
  "msg_seq": 1816,
  "state": 8,
  "battery": 64,
  [...]
#

what am I doing wrong?

#

ah, it seems you have to | to_json | from_json for whatever reason

silent seal
#

Are you sure it isn't JSON already?

marble jackal
#

You can probably just do {{ state_attr('vacuum.alfred', 'data').battery }}

#

When using to_json you made it a string

#

And when using from_json you turned it back into a dictionary

mighty ledge
mint drift
# spice jasper i am trying this ```{% set data = state_attr('vacuum.alfred', 'data') | from_jso...

{% set data = {
"msg_ver": 2,
"msg_seq": 1816,
"state": 8,
"battery": 64,
...
} %}

{# Encode the data dictionary as a JSON string and store it in the data attribute #}
{{ data | to_json | set_state('vacuum.alfred', 'data') }}

{# Decode the JSON string stored in the data attribute and access the battery field #}
{% set data = state_attr('vacuum.alfred', 'data') | from_json %}
Battery level: {{ data.battery }}

sacred sparrow
#

Is there a way to keep the previous state even after a HA restart? Every time I restart HA the state changes to โ€œNoneโ€```

  • trigger:
    • platform: state
      entity_id: sensor.living_room_table_switch_action
      sensor:
    • name: Living Room Table Switch
      icon: hue:dimmer-switch
      state: >
      {% set action = states('sensor.living_room_table_switch_action') %}
      {{ trigger.from_state.state if action == "" else action }}
silent seal
sacred sparrow
#

Why would mine go back to โ€œNoneโ€ after reset?

silent seal
#

Probably because your trigger doesn't filter out the invalid states

sacred sparrow
#

What would be the best way to do that?

silent seal
#

Well, what does it appear as when you restart HA?

sacred sparrow
#

it just says "None"

silent seal
#

Well you can exclude that from the triggers.

leaden harness
inner mesa
#

I'm not following the problem

silent seal
#

now().strftime('insert format here')?

inner mesa
#

like this? {{ now().strftime("%d-%m-%Y") }}

silent seal
#

I suspect so ๐Ÿ‘€

inner mesa
#

this part confused me:

but I don't see any way to insert the todays date (29)

#

but anyway...

silent seal
#

Indeed, it seems very strange.

leaden harness
inner mesa
#

There's a whole website ๐Ÿ™‚

marble jackal
sacred sparrow
#

Just checked and I think that worked. That was much easier! haha

mint drift
#

example of the yaml entity: light.living_room toggle: 'on' type: custom:slider-entity-row icon: mdi:sofa secondary_info: last-changed

late island
#

I guess this fits in here. I got my automation and it throws the following error: I dont really find anything to fix it. It throws the following error:


In 'condition':

  In 'template' condition: TypeError: is_state() takes 3 positional arguments but 4 were given```

https://hastebin.com/ugomozulep.yaml
silent seal
#

What is this supposed to be doing?

value_template: "{{ is_state('sensor.room_brightness_' ~ trigger.entity_id.split('_')[2], 'below', 50) }}"
late island
#

use the trigger to check the brightness in the room that triggered and give true if the state is below 50

silent seal
#

I would try

value_template:  > 
  {% set brightness = trigger.entity_id | replace('binary_sensor.motion', 'sensor.room_brightness'') %}
  {{ is_state(brightness, '<', 50) }}"

(Untested as I'm on mobile.)

late island
#

That, with the fixed quotes still throws the same error somehow..

silent seal
#

Then perhaps:

value_template:  > 
  {% set brightness = trigger.entity_id | replace('binary_sensor.motion', 'sensor.room_brightness') %}
  {{ states(brightness) | int  < 50 }}"

(Untested as I'm on mobile.)

waxen rune
#

I have a template that show all devices where at least one entity state is unavailable or unknown. https://hatebin.com/gqqvflvlot
That works fine, but since a few devices tend to be unavailable for only a few seconds (android_tv for exemple) clutter the result, I would now like to only fetch the ones with that have been unavailable/unknown for at least 2 minutes.
Suggestions how?

late island
#
{% for device in states | selectattr('state', 'in', ['unavailable', 'unknown']) %}
  {% set elapsed_time = as_timestamp(now()) - as_timestamp(device.last_changed) %}
  {% if elapsed_time >= 120 %}
    {% set ns.items = ns.items + [ device_attr(device.entity_id | device_id, 'name') ] %}
  {% endif %}
{%- endfor %}
{{ ns.items }}```

Try this.. Not sure though
marble jackal
marble jackal
mint drift
#
entity: light.living_room
name: Living Room Light
icon: mdi:sofa
secondary_info: last-changed
state_filter:
  - 'unavailable'
#

for example but I spose entity doesn't support sendary_info I think

silent seal
#

You can't just throw any keys into any card, check what the card supports.

mint drift
silent seal
#

Depending on your sensor that might not be possible. But one reason I use #zigbee-archived and specifically Z2M for my temperature sensors

marble jackal
mint drift
#

allow to ignore unknown state?

lethal bison
#
trigger:
  - platform: event
    event_type: esphome.switch
    event_data: {}
condition:
  - "{{ trigger.event.data.hostname.startswith('s-')  }}"
action:
  - service: light.toggle
    data_template:
      entity_id: light.{{ trigger.event.data.device }}```
I'm being told that `data_template` has long been depreciated, but random google hit says `data`  will not work if you use a template. What would be the proper method of calling the entity provided by the trigger template?
silent seal
#

Don't look randomly on google, check the docs

#

Is this an automation or a trigger template?

lethal bison
#

automation

silent seal
#

As the docs page specifies that it takes the same parameters as light turn on, update your toggle with that

lethal bison
#

Not really worried about brightness/color/effects yet, if I can toggle state I'll be happy with the progress. It looks like I can just get rid of data_template completely?

action:
  - service: light.toggle
    target:
      entity_id: light.{{ trigger.event.data.device }}```
silent seal
#

Probably, assuming that device exists ๐Ÿ™‚

lethal bison
#

ahh, now I see the use case for data in the example, as opposed to data_template. I was using it incorrectly from the start

#

these are esphome devices, I'm using standardized naming to make sure the device exists ๐Ÿ™‚ . I'll probably create a blueprint to create the light group if a new switch is added, but I'd really love to stumble on a method of handling it all without user interaction

plain magnetBOT
undone jungle
#

in short is this correct:

        state: >-
          {% if is_state('binary_sensor.ventilation_bypass', 'off') and is_state('binary_sensor.fan_operational', 'on') %}
            {% set strumienN = states('sensor.air_supply_flow') | float %}
            {% set tcz = states('sensor.incoming_air_temperature') | float %}
            {% set tn = states('sensor.room_supply_temperature') | float %}
            {% if states('sensor.incoming_air_temperature')|float < states('sensor.air_supply_flow')|float %}
                {{ ((((tn - tcz) * strumienN * 1200) / 3600)|float) | round(2, default=0) }}
            {% else %}
                {{ (((((tn - tcz) * strumienN * 1200) / 3600) * -1)|float) | round(2, default=0) }}
            {% endif %}
          {% else %}
            0
          {% endif %}
#

Or should there be another if resulting in :

{% if is_state('binary_sensor.ventilation_bypass', 'off') and **if** is_state('binary_sensor.fan_operational', 'on') %}
lethal bison
#

Hmm, apparently the template won't convert spaces to underscored automatically. I'll have to re-think this

jagged obsidian
#

| slugify

lethal bison
bronze prawn
#

{% for chore in state_attr('sensor.grocy_chores','chores') if
chore.next_execution_assigned_to_user_id == 3 and
strptime(chore.next_estimated_execution_time,'%Y-%m-%dT%H:%M:%S')|as_local
<= today_at('23:59:59') and (chore.next_execution_assigned_to_user_id, '3')
%}{{chore.name}}{% else %} No chores for you today! {% endfor %}

#

Need a carriage return after chore.name and nothing I've tried has provided that. tried \n and <br> and always showing results running into themselves

#

Kitchen - Wipe CountersKitchen - Clean stove top

Should read:
Kitchen - Wipe Counters
Kitchen - Clean stove top

lethal bison
#

Just a wild guess, but maybe pipe it into a list?

#

%}{{chore.name | list}}{% else %} No chores for you today! {% endfor %}

bronze prawn
#

Ah, let me give that a try

solemn frost
waxen rune
marble jackal
bronze prawn
#

['K', 'i', 't', 'c', 'h', 'e', 'n', ' ', '-', ' ', 'W', 'i', 'p', 'e', ' ', 'C', 'o', 'u', 'n', 't', 'e', 'r', 's']['K', 'i', 't', 'c', 'h', 'e', 'n', ' ', '-', ' ', 'C', 'l', 'e', 'a', 'n', ' ', 's', 't', 'o', 'v', 'e', ' ', 't', 'o', 'p']

Hahaha

lethal bison
#

It's not a bug, it's an undocumented feature

bronze prawn
#

Thanks @marble jackal That did the trick! and thanks to you all

plush willow
#

Just to be sure, this template is correct?

template:

  • sensor:
    • name: "woonkamer_total_covers_closed"
      state: >
      {{ expand(states.cover.woonkamer_covers) | selectattr('attributes.current_position', 'eq', 0) | list | count | int }}

I have problems in the frontend that when the sensor is zero (it gives really zero in the developer tools) it doesn't show it.

marble jackal
waxen rune
# undone jungle Any ideas??

The first one is correct. Since you ask, I assume it doesn't work, but then it's probably in the rest of the conditions. If I replace your entities with values like below, it returns -0.67. {% if 1==1 and 2==2 %} {% set strumienN = 1 | float %} {% set tcz = 2 | float %} {% set tn = 4 | float %} {% if tcz < strumienN %} {{ ((((tn - tcz) * strumienN * 1200) / 3600)|float) | round(2, default=0) }} {% else %} {{ (((((tn - tcz) * strumienN * 1200) / 3600) * -1)|float) | round(2, default=0) }} {% endif %} {% else %} 0 {% endif %}

plush willow
undone jungle
marble jackal
undone jungle
#

While I have you, I have one follow up. Since this sensor is recording recovered energy, I wouldn't want it to return a 0 when the HVAC is off, since it will 'dilute' the value if pulled into a mean later on.

#

Is it OK to follow the else with unknown instead

#

Or will this cause issue when trying to use it for later calculations, since it's a non-numerical value

#

Would giving it a unavailable instead be a better idea?

#

Good example is here:

#
      - name: "Ventilation energy efficiency"
        unique_id: "recu_energy_efficiency"
        icon: "mdi:percent"
        unit_of_measurement: "%"
        state: >-
          {% if is_state('binary_sensor.ventilation_bypass', 'off') and is_state('binary_sensor.fan_operational', 'on') %}
            {% set t1 = states('sensor.incoming_air_temperature') | float %}
            {% set t2 = states('sensor.room_supply_temperature') | float %}
            {% set t3 = states('sensor.room_exhaust_temperature') | float %}
            {{ (((t2 - t1) / (t3 - t1)) * 100|float) | round(2, default=0) }}
          {% else %}
            0
          {% endif %}
#

I don't want the efficiency to drop to zero when the HVAC is off

#

It should become unknown since the energy exchange simply doesn't happen, so we don't know what the value is at the time on the HVAC unit.

marble jackal
#

Well, then it is indeed an issue with the card. What is de code of the card

plush willow
#

type: custom:mushroom-chips-card
chips:

  • type: template
    content: >-
    {{ states('sensor.woonkamer_total_covers_closed') }}
marble jackal
#

and that also returns 0 in devtools > templates?

#

What if you just use the template for the template sensor in you chip?

plush willow
#

yes

waxen rune
plain magnetBOT
waxen rune
#

You can use whatever you want, you decide. Personally, I avoid unknown and unavailable since that often indicate that something's wrong.

undone jungle
#

If I remove the else all together, I will probably see nothing there.

#

Need to play with it a little.

#

Maybe using the template editor in the Developer tool will be a good idea

waxen rune
#

Always

plain magnetBOT
thorny snow
#

hey guys. I'm new and discovering Discord and found HA is here. Great. Maybe someone is able to help me with a sensor issue?
I monitor RPi's and as soon as it goes offline, I want the "last seen" date/time to be there. Date/time is one of the attr of the MQTT message.
So how to create a "last seen" sensor with date/time which is updated only when the RPi is Up?

undone jungle
lethal bison
#

Brainstorming... I have a working event trigger automation that listens for switch entities and activates light.{{entity}}.
What I'd like to do instead is return a list of devices. Effectively the same functionality as a light group, but this way I don't have to create a matching light group for each of my switches

inner mesa
#

"return"?

#

or "activate"? (which I guess means turn on/off)

#

you want some way to correlate a switch with a set of lights?

undone jungle
#

Is the Availability:False the correct output when availability is used in the template?

plain magnetBOT
undone jungle
#

What am I doing wrong here? Shouldn't it return unavailable?

#

I am wondering if the statement after availability: should be in parentheses?

inner mesa
#

you need to surround the template in quotes

lethal bison
#

@inner mesa Here's an partial automation example that does not work, but I can't understand what the error not a valid value for dictionary value means.

action:
  - service: light.toggle
    target:
      entity_id: {{ states.light | selectattr('entity_id', 'search', trigger.event.data.device | slugify ) | map(attribute='entity_id') | list }}```
inner mesa
#

again, you need to surround the template in quotes

#

it's rule #1

lethal bison
#

oh, QUOTES

inner mesa
#

oh, sorry, that was the other guy

#

you both need to read the docs ๐Ÿ™‚

lethal bison
#

I was reading quote and thinking brace

#

I'm reading, but I'm having a hard time comprehending

inner mesa
#

this bit:

You must surround single-line templates with double quotes (") or single quotes (').

lethal bison
#

so I guess step one: nomenclature. What exactly is considered the template in that line? Just the 'trigger.event.data.device' ? or the entire line from opening double-brace to closing double-brace?

inner mesa
#

everything in '{{ }}'

#

that's Jinja

#

first link in the channel topic

#

Also, without knowing what your event structure looks like, I can't tell if this is really doing what you expect: selectattr('entity_id', 'search', trigger.event.data.device | slugify ).

#

I suspect not, but ๐Ÿคท

lethal bison
#

{{ trigger.event.data.device | slugify }} returns the event.data.device tag for the entity that called the event. In this case, for simplicity, it returns the string 'diningroom'

#

so my logic is to search all entity_ids for 'diningroom', and return a list of matches

inner mesa
#

ok

late wolf
#

Hey everyone! {{input_datetime.last_irobot_run<now() - timedelta( hours = 12 )}}
First time using template, I'm getting this error: UndefinedError: 'input_datetime' is undefined. What am I doing wrong?

#

That entity id exists and has a value

inner mesa
#

Right, that's the wrong syntax

#

Second link in the channel topic

undone jungle
#

I hope that question will not fall under 'you didn't read the documentation right', since I did look for it:
What is the risk of having several template sensors under one - sensor: headers? They all seem to work just fine.

plain magnetBOT
inner mesa
#

no problem at all

#

that's what I do

undone jungle
inner mesa
#

yes

undone jungle
#

OK, any reason why a sensor header for each vs. one for all is beneficial?

inner mesa
#

no

undone jungle
#

Beyond code beautification...

late wolf
#

Thanks Rob!

inner mesa
#

presumably it's that way because you can provide an optional trigger and those blocks can be different, but there's no problem repeating the sensor: header other than extra typing

rustic raft
#

how is this template invalid? it's part of a blueprint's action

              - if:
                    condition: numeric_state
                    entity_id: !input main_light
                    attribute: brightness
                    above: "{{ complimenting_brightness * 2.55 }}"```
complimenting_brightness is equivalent to `10`, and is being setup as a template var from a blueprint's input correctly, but the blueprint is erroring out saying `above` is `None`
inner mesa
#

You can't use a template there

rustic raft
#

Thanks, super helpful! Now trying to use value_template in numeric-state-condition to multiply the brightness attribute by 2.55. Have not been successful in fixing the errors yet.

See YAML code sample and value of state @: https://dpaste.org/sR9Q0
Problem is state.state appears to be referring to the on/off status of the light, and state.brightness claims it doesn't exist - despite it appearing in the value of state. (The value of state in the dpaste comes from {{ state }}.)

undone jungle
#

Not sure if this question is for that channel, but I'll give it a try:
https://i.imgur.com/MT3mIeB.png
When a templeted sensors becomes unavailable, it continues to assume the last known value and when used for any calculations, I think it will return this value back for these calculations.
In some cases though sensors stop plotting the value all together (unknown), for example MQTT sensors do that.
Is it possible to use a similar mechanism as availability: to produce an unknown value when certain conditions are not met?

inner mesa
thorny snow
#

quick one..
{{ states('sensor.octopi_model') ,states('sensor.octopi_model')}}
gives output with braces -> ('RPi 3 Model B+r1.3', 'RPi 3 Model B+r1.3')
How to remove these?

obtuse zephyr
undone jungle
#

OK! I am sorry for not knowing how to test it myself, but will any algebraic operation on this block return an error/dev-by-zero/etc. when the sensor becomes available again?

#

My concern is that it will return a value of an extrapolation between the last known value and the one that succeeded it when the sensor return to life.

#

Something down the line of:

  • it was 10
  • it died for some time
  • it returned as 1000
    so the operation on the time between the 10 and 1000 return a value of a y=ax+b slope.
#

While it should return some form of error since there is no data for this block of time..

obtuse zephyr
#

What do you have using it? If a template is using it, you can define a default value, for example {{ 100 / states('sensor.unavail_sensor') | int(-5) }} will use -5 as the denominator if the sensor has a non-integer value.

inner mesa
thorny snow
inner mesa
#

ok

undone jungle
#

Also, I am not sure how would this block be added to a standard numerical sensor. Do you have an example where you are using it?

obtuse zephyr
#

This might be related https://github.com/home-assistant/frontend/issues/14331

But, I guess the point is from what I see is that how an unavailable state is displayed/interpreted depends on who's reading it. The frontend decides to sometimes interpolate or maintain the existing value, but something like the energy component likely handles unavailable in a different manner.

lethal bison
#

This is an absolute hack, but it works!

action:
  - service: light.toggle
    target:
      entity_id: |-
        {{ states | selectattr('entity_id','gt','light.dining') | selectattr('entity_id','lt','light.diningzzz') |  map(attribute='entity_id') | list }}
undone jungle
obtuse zephyr
lethal bison
#

Well, hell. I didn't think about regex

obtuse zephyr
#

We try not to ๐Ÿ™ƒ

lethal bison
#

aand I got the single-line quoting wrong again

#

{{ states | selectattr('entity_id','match','^light.{{ trigger.event.data.device | slugify }}') | map(attribute='entity_id') | list }}

inner mesa
#

gack. now you're nesting templates

obtuse zephyr
#

{{ states | selectattr('entity_id','match','^light.' + trigger.event.data.device | slugify) | map(attribute='entity_id') | list }} should work

#

might be better looking if you compute the match outside

lethal bison
inner mesa
#

you can further optimize that like this:
{{ states.light | selectattr('object_id','match',trigger.event.data.device | slugify) | map(attribute='entity_id') | list }}

solemn frost
#

Somewhat new to templating, is there a more efficient/neater way to do this? It does work as-is, but I feel like I may have made it overly complicated

{{ expand('group.lights_all') | rejectattr('entity_id', 'in',
    expand('light.bedside') | map(attribute='entity_id') | list) |
    map(attribute='entity_id') | list }}

For context, group.lights_all is a YAML defined group of several switches and lights, light.bedside is a light group created via the UI consisting of 2 lights. The goal is to get a list of entity IDs, excluding the bedside ones, that I can pass to the light.turn_off service

inner mesa
#

yes, that can be greatly simplified

#

{{ state_attr('group.fr', 'entity_id')|reject('in', state_attr('group.fr', 'entity_id'))|list }}

#

that excludes everything in the group, but hopefully you get the idea

lethal bison
#

object_id alone helps greatly. I honestly stopped looking after I found the first name-based field

undone jungle
#

Is there any way to specify the icons for the template:lock in the same way as template:cover?

#

I am using it for a simple buzzer style side gate, but it's only turning the icon red as opposed to using the animation

plain magnetBOT
undone jungle
#

Here the template lock:

lock:
  - platform: template
    name: Side gate
    value_template: "{{ is_state('switch.side_gate', 'off') }}"
    unlock:
      service: switch.turn_on
      target:
        entity_id: switch.side_gate
    lock:
      service: switch.turn_off
      target:
        entity_id: switch.side_gate
solemn frost
brisk lava
#

Is is possible to use multiple value.split calls to pull the information before and after a symbol?
Current yaml is

      - unique_id: milk_price
        name: Milk Price
        select: "data.kds-Price:nth-child(2)"
        value_template: '{{ (value.split(":")[1]) }}'```
and I'm trying to pull the price which is listed in `value:"x.xx"` but not the quotation marks.
inner mesa
#

pfft, had to search for that

#

anyway, they're in the docs in the first link in the channel topic

inner mesa
brisk lava
#

Do you need single quotes around double quotes?

inner mesa
#

in the split()?

#

you need to provide a character/string to split on, and you do that by surrounding it in quotes

brisk lava
#

and if the character is in fact a " , I'd need .split(""")?

inner mesa
#

no, you'd use what I gave you above

#

""" can't be parsed

brisk lava
#

my issue must be with the select then.

inner mesa
#

or the output isn't really what you said it was

brisk lava
#

Most likely, as the sensor just shows unavailable after calling the update service.

quiet creek
#

Is there a way to make a script to cycle through different wled effects when it is run?

timber fiber
#

I need a template for a calendar event, that identifies whether it's the day of or day after a specific calendar event. Where can I find some examples?

silent seal
#

What is the use case?

timber fiber
#

series of repeating events in local calendar. need a trigger to identify when to send a tts notification to Alexa

silent seal
#

You're still not really providing an example that someone can really envision ๐Ÿ˜‰

timber fiber
#

the visual editor for automations doesn't offer much for calendar triggers

#

it lets you trigger based off of IF an event is active...but not choose which event is active

silent seal
timber fiber
#

yes... that, again, triggers if there is an event... which does NOT specify WHICH event

silent seal
#

Ahem, did you read the WHOLE example?

#

The condition explicitly looks at which calendar title it was ๐Ÿ˜‰

timber fiber
#

okay, that's my question that I am asking here - it's not clear where exactly that is

timber fiber
#

RTFM - got it, ty

silent seal
#

It expects you to understand enough of the automation syntax to see the condition, and then keep reading ๐Ÿ™‚

pastel moon
#

Hi, is there a nice way to see when (time/date) a script was last executed? I'd like to have this to calculate other stuff from it...

silent seal
#

Yup, it shows in the UI for starters

pastel moon
#

True, but if I need it in a script/automation?

waxen rune
#

attribute: last_triggered

solemn frost
#

You can see all the attributes for an entity in the Developer Tools menu

silent seal
#
{{ state_attr('automation.back_bedroom_button', 'last_triggered' }}
pastel moon
#

Very nice, thank you! ๐Ÿ™‚

undone jungle
silent seal
#

I'm not sure why you're tagging me, but simply put: if it's not in the docs then it's not supported.

undone jungle
#

My apologies! You were the mod 'on duty' dealing out advice, so I thought I'd ask, since no one responded for a few hours.

plain magnetBOT
undone jungle
#

I apologize if I broke any unspoken rules.

buoyant pine
#

You can (should) always run that โ˜๏ธ anyway

undone jungle
#

I am not sure how it relates? Would you mind expanding?

#

The config check is required to reboot HAOS so it's definitely being run on my end.

buoyant pine
#

The config check will tell you if your configuration is correct or not. If you have something invalid in it, it will let you know

undone jungle
#

Absolutely, but it's a positive check of the used syntax, you cannot check what you didn't type correctly this way.

buoyant pine
#

It would complain about icon_template not being supported for that

undone jungle
#

If there is no clear syntax outlined in the docs there may be 'workarounds' how people do it, or 10 different ways to skin the can as is often the case in templates.

undone jungle
buoyant pine
#

That's not the config check though

#

VSC shouldn't be your source of truth. It's not always accurate

undone jungle
#

I understand, but if it already complained there, I assumed it would elsewhere

buoyant pine
#

Not necessarily. It sometimes complains about stuff that's valid

undone jungle
#

This said, knowing this most likely will not work, I was wondering if there is a workaround. In this case it does complain in the config check, so it's kind of a moot point, but I take the criticism not to always trust it.

buoyant pine
#

To clarify, the config check is accurate, but VSC is not necessarily accurate

undone jungle
#

Yes, I did get that.

#

But as I said, in this case both indicated the same thing, so we are on the same page. In the future, I'll make sure to check both, though it's not really progressing the conversation in this particular situation. ๐Ÿ˜‰

#

It's kind of a long way of arriving at - NO, there is no way to specify the icons.

buoyant pine
#

tbh I'd say disregard VSC and only pay attention to the docs and the config check

undone jungle
#

I'll consider your advice - thank you!

woeful socket
#

I have a question:
I have an input NUMBER helper "input_number.minutes_after_motion" that I'd like to set as a duration condition.
But I keep getting the error: ***"Message malformed: expected float for dictionary value @ data['for']['minutes']" when I do this: ***

type: no_motion
platform: device
device_id: 7b98fc28dccab869717ad5a82959aa78
entity_id: binary_sensor.hue_motion_sensor_entre_motion
domain: binary_sensor
for:
  minutes: {{ input_number.minutes_after_motion | float }}

Can anyone help me?

solemn frost
#

Try surrounding the entire template with double quotes

woeful socket
#

Same result

#

The value is '5' btw, if this somehow requires zero padding?

solemn frost
#

If you want the state, you'll need states('input_number.etcetc')

woeful socket
#
for:
  minutes: {{ states('input_number.minutter_etter_bevegelse') | float }}

Same error message ๐Ÿ˜ฆ

solemn frost
#

You still need double quotes around the whole thing

woeful socket
#

Same message, with double quotes, single quotes and no quotes

#

maybe the for.minutes does not accept automation? - it accepts the value 5 without any issues

arctic sorrel
#

Device triggers don't like templates - use a state trigger

woeful socket
#

oh!

#

for the hue motion sensor, do I then ask the sensor attribute 'motion_valid' or just go with 'off' for binary_sensor.hue_motion_sensor_entre when I want to check for no motion?

arctic sorrel
#

Simple state trigger on that entity

woeful socket
#
platform: state
entity_id: binary_sensor.hue_motion_sensor_entre_motion
from: 'On'
to: 'Off'
for:
  minutes: '{{ states(''input_number.minutter_etter_bevegelse'') | int }}'

Well, it accepts it, hopefully it'll work too ๐Ÿ™‚

arctic sorrel
#

It won't

woeful socket
#

And it didn't ๐Ÿ˜„

arctic sorrel
#

On isn't the actual state, and neither is Off

plain magnetBOT
woeful socket
#

AAH, there they are!!

devout haven
#

i don't understand what's going on here. with the expression "{{ color == '-1' }}" when color has the value -1 as a string it evaluates to false. if i do "{{ '-1' in color }}" it evaluates to true. if i cast both sides to an int and do the comparison it evaluates to true. is there a .equals method like in java that i need to use to compare the values so that a more correct comparison is done?

marble jackal
woeful socket
#

Mine is showing as 'off' currently

marble jackal
marble jackal
#

Or unavailable or unknown

#

Or badly programmed ๐Ÿ˜…

woeful socket
#
platform: state
entity_id: binary_sensor.hue_motion_sensor_entre_motion
from: 'on'
to: 'off'
for:
  minutes: '{{ states(''input_number.minutter_etter_bevegelse'') | int }}'

So this should be correct then ๐Ÿ™‚

devout haven
plain magnetBOT
devout haven
#

weird... apparently in jinja i have to cast both sides to strings. why is this?

#

they are already strings

#

oh, well. i guess i don't care. it's jinja and in somebody's eyes '-1' does not have a type

#

thank you everyone

marble jackal
devout haven
#

unrelated new question, i am creating a template light to fix some weirdness in a firmware of a zwave device. the zwave device only has a "brightness" state attribute when the light is on and the brightness attribute is not defined when the device is off. maybe this is normal. that's not important to the question. i have a level_template like this: level_template: "{{ state_attr('light.entityofthething', 'brightness')|int }}" which works fine when the device is on but results in an evaluation error in jinja when the device is off because i have no default. any idea if there will be ill effects if i provide default(0)|int so that level is always defined? are there parts of home assistant that will consider the light to be on if it has a value or any weird gotchas like that?

ivory lotus
#

Hi all, why is this template binary sensor not working?

#

template:

  • binary_sensor:
    • name: "Badezimmerlรผfter_State"
      unique_id: BadezimmerluefterState
      state: >
      {% if states('sensor.lufterbadsupply_power') | float <= 0.6 %}
      {{off}}
      {% else %}
      {{on}}
      {% endif %}
#

I always get 'UndefinedError: 'on' is undefined' as error

#

fixed it --> instead of off/on I had to use false/true

marble jackal
plain magnetBOT
#

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

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

marble jackal
pastel moon
#

Hi guys, how can I get this to do what I need please? https://paste.debian.net/hidden/c8dccb18/
I have the time of the last triggered, and want to add a random time (delta) to that. It is added twice on purpose to compensate for the transition time (light register as off despite still emitting light)

#

I have been testing in dev-tools a lot, but (as of yet) failed to get it right

marble jackal
#

last_triggered is already a datetime, but for some reason that doesn't work in devtools

pastel moon
#

Ok. Perhaps converting to timestamps would work better?

marble jackal
#

Also you were adding the timedelta to a string at the end

#
{% set delta = timedelta(minutes=range(1,9)|random * 2) %}
{{ (state_attr('script.lights_off', 'last_triggered') | as_local + delta).strftime('%Y-%m-%d %H:%M:%S') }}
#

This will not work in devtools, but it will in the automation

#

Where are you using this BTW? In the same automation?

pastel moon
#

It is kind of cross automations, used to calculate other scripts to run after lights go out

#

I am setting a datetime helper, which then is read by other scripts

marble jackal
#

Why are you converting it to a string then? The input_datetime service call accepts a datetime

#
{% set delta = timedelta(minutes=range(1,9)|random * 2) %}
{{ state_attr('script.lights_off', 'last_triggered') | as_local + delta }}
pastel moon
#

Good question. I was trying back and forth and ended up with that

#

This looks much better, thanks for the help! ๐Ÿ™‚

loud wave
#

I'm currently learning templating and was wondering if there is currently a source or list of all templating functions like is_state?

grizzled grove
#

Can someone give an idea for a template? 4.186(80000[60-'sensor_state'])/1500= value

obtuse zephyr
grizzled grove
loud wave
#

I'm following a youtube vid that has this code:

{% set output = namespace(sensors=[]) %}
{% for state in states.sensor | selectattr('attributes.device_class') %}
{{ state.name }}
{% endfor %}

But my output is:

UndefinedError: 'homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'device_class'

Any ideas what I'm missing?

obtuse zephyr
#
{% set output = namespace(sensors=[]) %}
{% for state in states.sensor | selectattr('attributes.device_class', 'defined') %}
{{ state.name }}
{% endfor %}
#

Assuming there's more to that template? Otherwise... seems odd

loud wave
#

Its just the beginning

loud wave
jagged obsidian
#

probably 10 months out of date

loud wave
#

@obtuse zephyr I really appreciate all your help

obtuse zephyr
#

Possibly ๐Ÿคทโ€โ™‚๏ธ Or he's only got sensors that have a device class

loud wave
obtuse zephyr
#

Everyone's set up is different, you'll find that videos can be frustrating at times

#

Definitely a good idea to read through that templating doc, so even if you do check out videos, you can understand what might be going wrong and what options there are to fix

loud wave
#

What if I want to filter for "battery"?

#

Maybe selectattr('attributes.device_class','eq','battery')

#

Hmm no

grizzled grove
#

Sorry, can't seem to get it right...

obtuse zephyr
#

{{ 4.186*(80000*(60-states('sensor.your_sensor')|float))/states('sensor.your_other_sensor')|float }}

grizzled grove
#

... damn. Let me try it.

#

Yep; that's it. Thanks!

loud wave
#

@obtuse zephyr What if I want to test for 'battery' in:

{% for state in states.sensor | selectattr('attributes.device_class', 'defined') %}

obtuse zephyr
#

states.sensor | selectattr('attributes.battery', 'defined') ?

inner mesa
#

...or
|selectattr('attributes.device_class', 'eq', 'battery')

loud wave
inner mesa
#

You need both...

#

Put them together

loud wave
inner mesa
#

Understand what they're doing...

#

Don't just copy and paste

loud wave
# inner mesa Don't just copy and paste

{% for state in states.sensor | selectattr('attributes.device_class', 'eq', 'battery') %}

UndefinedError: 'homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'device_class'

#

Am I misunderstanding?

peak juniper
#
  - sensor:
    - name: Steam Online
      state: >
        {{ states.sensor | select('search', 'steamid_') 
        | selectattr('state', 'eq', 'Online') | list | count }}

Can't find the answer online but looking to get all state that DO NOT equal "online". Any ideas?

inner mesa
#

The point is: you need to select for the attribute to be defined, then that it is what you want

#

2+2

loud wave
obtuse zephyr
#

Are you looking for device_class: battery?

inner mesa
#

here

obtuse zephyr
#

Then you need Rob's

inner mesa
#

{% for state in states.sensor | selectattr('attributes.device_class', 'defined') |selectattr('attributes.device_class', 'eq', 'battery')|list %}

peak juniper
#

thanks @obtuse zephyr another great page for my bookmarks ๐Ÿ™‚

loud wave
solemn frost
loud wave
obtuse zephyr
#

That it does

loud wave
#

Wish I could buy you guys some beers

#

In this tutorial is the following:

{% if 0 <= state.state | int(-1) %}

Is "unknown" considered "less than zero"?

#

It was used to remove unknown values

inner mesa
#

"unknown" (the string) will result in that evaluating to -1

#

which will make that "false"

loud wave
#

Thx Rob.. This is all jinja-related stuff, right?

inner mesa
#

yes

loud wave
#

If so I can attack that manual

loud wave
inner mesa
#

see the links in the channel topic

loud wave
grizzled grove
#

What would be the best way to resolve: TemplateError('ZeroDivisionError: float division by zero') while processing template?

#

I've tried with availability_template, but no luck.

#
availability_template: "{{ states('sensor.2')|float != 0 }}"```
plain magnetBOT
#

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

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

silent seal
#

Please share the YAML of your template ๐Ÿ™‚

grizzled grove
#

value_template: "{{ (4.186*(80000*(60-states('sensor.1')|float))/states('sensor.2')|float) | round(0) }}"

silent seal
#

That's not the whole template sensor/config ๐Ÿ™‚

#

Also, sensor.1 is not the world's greatest name. I recommend sensor.bedroom_temperature, binary_sensor.bathroom_occupancy, etc. as names.

grizzled grove
#
    sensors: 
      time_heater_seconds:
        value_template: "{{ (4.186*(80000*(60-states('sensor.shelly1pm_e8db84d807c5_temperature')|float))/states('sensor.heater_watts')|float) | round(0) }}"
        #availability_template: "{{ states('sensor.heater_watts') not in ['0', 'unavailable', 'unknown', 'none'] }}"
        availability_template: "{{ states('sensor.heater_watts')|float != 0 }}"```
silent seal
#

That's using the old config, so I recommend looking at the new syntax as a side note ๐Ÿ™‚

#

You don't have any defaults for the floats.

grizzled grove
#

Isn't the default float(0) ?

silent seal
#
{{ (4.186*(80000*(60-states('sensor.shelly1pm_e8db84d807c5_temperature')|float(0)))/states('sensor.heater_watts')|float(0)) | round(0) }}
#

That might fix it.

#

No, if the sensor is outputting unavailable then it won't be parseable as a float.

grizzled grove
#

I think I tried, just in case, but it didn't work. Let me check again...

silent seal
#
template:
  - sensor:
      - name: "Time Heater Seconds"
        unique_id: time_heater_seconds
        state: >
          {{ (4.186*(80000*(60-states('sensor.shelly1pm_e8db84d807c5_temperature')|float(0)))/states('sensor.heater_watts')|float(0)) | round(0) }}
        availability: "{{ states('sensor.heater_watts') not in ['0', 'unavailable', 'unknown', 'none'] }}"
#

This would be the new syntax (I'm not 100% sure on the seconds, I'm going from memory there)

grizzled grove
#

Oh, it did the trick!

silent seal
#

I'm glad to hear it ๐Ÿ™‚

grizzled grove
#

Thanks!

silent seal
grizzled grove
#

Yeah, will do.

loud wave
#

Can I change a button icon on a card on the dash board from a script?

silent seal
#

When you say change an icon, what is the button linked to?

loud wave
silent seal
#

Well the template sensor can have a custom icon based on the state

loud wave
#

Yeah, I just didn't know if I could update that icon from another method or if I have to include all of my icon logic in the template sensor

silent seal
#

You can't change it another way, no

loud wave
#

I've been diving pretty hard in to templates and I'm currently reading up on jinja. I found a reference to the split function but I don't see it listed anywhere in the documentation. Am I missing it?

silent seal
#

You mean the split config?

plain magnetBOT
loud wave
#

No like providing a value and separating it into independent values with a delimiter

#

00:00:00 into three separate values using: as the delimiter

#

customer.date_of_birth.split('-') etc

#

Seems:

"A string variable can be split into a list by using the split function (it can contain similar values, set is for the assignment) . I haven't found this function in the official documentation but it works similar to normal Python. The items can be called via an index, used in a loop or like Dave suggested if you know the values, it can set variables like a tuple."

https://stackoverflow.com/questions/30515456/split-string-into-list-in-jinja

#

Lemmie tell you how easy stuff is to learn when it's not documented lol

heavy crown
inner mesa
#

Jinja uses Python objects, so (in general) you can use any method supported by those objects

heavy crown
#

Thanks but .. 'any method'... this leaves the whole set of options wide open. For me (at least) as a slightly advanced / mediocrate jinja user, how would i know where to look and what method to be able to applu in jinja? Is thi sjust a question of eperience or is there readable guidance in this area.

inner mesa
#

Some of it is experience, but in general you can stick a template in devtools -> Templates and it will tell you the object type. Then you can search for Python methods that apply to that object

#

Unfortunately, that's not always a reliable way to identify the object type because it tells you the type of the output, and not necessarily the object that it came from. An example of that is {{ now() }}, where now() returns a datetimePython object, but the devtool displays it as a string, and tells you that it's a string

shell fractal
#

I have a sensor consisting of the product of two input numbers.

Calculation of Total Savings in โ‚ฌ
dogalgaz_fatura_accounting:
friendly_name: 'dogalgaz_fatura_hesaplama TL'
unit_of_measurement: 'โ‚บ'
value_template: >-
{{ (float(states.input_number.dogalgaz_ilk_sayac.state) * float(states.input_number.dogalgaz_guncel_sayac.state) * 5.85) | round(3) }}

Even if I add a round, I have trouble rounding...

Result: 28.867.889,7 โ‚บ
My desired outcome: 288โ‚บ

heavy crown
inner mesa
#

I can't tell what that number actually is based on the separators and groupings

#

What does it say in devtools -> Templates?

#

When used like that, round() acts on the fractional part of the value. It sounds like you want to round the whole part of the value, which I believe you can do by providing negative values to round()

shell fractal
inner mesa
#

See last message

shell fractal
#

giving negative values did not work.

#

round(-3) value and this is the result: 28868000.0

inner mesa
#

so keep going

#

{{ 28867890|round(-5) }} -> 28900000

#

same with {{ 28867890.0|round(-5) }}

shell fractal
#

I kept going, I tested down to -60s. We got rid of the punctuation:) Now the result is good... Only how can I get it down to 3 digits, that's the problem now...

inner mesa
#

I don't know whether there's supposed to be a decimal part to this or not ,288TL

#

I don't know what the comma is there

#

divide it

#

{{ (28867890.0|round(-5))/100000 }} -> 289

#

or just {{ (28867890/100000)|int }}

#

-> 288

shell fractal
#

Should I create a template sensor again for this last code you wrote?

Actually, let me put it like this.

I don't need decimals.

I don't want to give you a headache, but the result I want to achieve... My goal is to calculate my natural gas bill. I have two input numbers. They are 4 digit input numbers. One represents the first meter and the other represents the current meter value... With the difference between the two, I find my natural gas consumption value, where an increase of the last value by one value corresponds to an increase of one cubic meter of natural gas. One cubic meter of natural gas is 5,85TL... These two input numbers

dogalgaz_fatura_accounting:
friendly_name: 'dogalgaz_fatura_hesaplama TL'
unit_of_measurement: 'โ‚บ'
value_template: >-
{{ (float(states.input_number.dogalgaz_ilk_sayac.state) * float(states.input_number.dogalgaz_guncel_sayac.state) * 5.85) | round(3) }}

I multiply it by the sensor and the result will represent my natural gas bill for this month... But the result has both fractional and incorrect decimal values. Obviously, this does not satisfy me... With my Sonoff device that measures energy on the boiler, as the energy values increase, the input number will be updated and my natural gas bill will automatically appear on the screen... This is a stupid and simple method I think... If there is a simpler one you know you can direct me... Thank you for your answers...

loud wave
#

Is there an easy way to permanently increase the size of the template editor in home assistant?

loud wave
#

Another question, we assigned devices to a room but I don't see any reference to the rooms anywhere. Is there a way to see a list of all devices in each room?

solemn frost
plain magnetBOT
floral blaze
#

im trying to get this icon to 'boink' but for some reason it wont work out.

paper hazel
#

How do I get this to show XX:XX:XX format without the microseconds? Still a bit in the dark around the time manipulation with templates... ๐Ÿ˜ณ ```
{{ now() - states.input_boolean.test.last_changed }}

solemn frost
#

You can make any time format you want with timestamp_custom()

paper hazel
#

Thx - I tried this, but it errors out on me, and I can seem to figure out why```
{{ now() - states.input_boolean.test.last_changed |timestamp_custom("%H:%M:%S") }}

solemn frost
#

It takes a UNIX timestamp, so you need to wrap your time in as_timestamp()

paper hazel
#

Do I wrap the whole thing or each one separately?```
{{ as_timestamp(now()) - as_timestamp(states.input_boolean.test.last_changed) |timestamp_custom("%H:%M:%S") }}
OR
{{ as_timestamp(now() - states.input_boolean.test.last_changed) |timestamp_custom("%H:%M:%S") }}

#

Both dont seem to work when testing them?

inner mesa
#

{{ (utcnow()|as_timestamp - states.input_boolean.dark.last_changed|as_timestamp)|timestamp_custom("%H:%M:%S") }}

#

(using my entities)

fiery sage
#

I know I can do now().timestamp() in a template to get the current timestamp, but what's the easiest way to get the timestamp without the time component (e.g. 00:00:00)?

inner mesa
#

so, today's date?

#

or today_at("00:00")?

fiery sage
#

but I need a timestamp of it

inner mesa
#

so...

#

{{ today_at("00:00")|as_timestamp }}

fiery sage
#

Ah I see, today_at returns a datetime I can convert, perfect!

inner mesa
#

you already had that

#

yes

fiery sage
#

didn't know about today_at, that's perfect, thanks

paper hazel
#

I am wanting to use this in a sensor as a type of stop watch - If I understand correctly now() will not update by itself, and I should rather use sensor.time, is that correct?

#

The sensor will be displayed on a dashboard showing the time which has elapsed.

inner mesa
#

now() updates every minute

#

aside from the docs, the template dev tool tells you that:

paper hazel
#

Is it possible to get an update every second?

inner mesa
#

Set a timer for the duration and display the timer

paper hazel
#

That was my initial thought, but there is no set time for the timer, as the duration is dynamic

inner mesa
#

There is

#

When you start it

paper hazel
#

I think I might have expressed myself wrongly - On the dashbord there is a button, once the button is pushed a "stopwatch" should appear showing the time elapsed in the XX:XX:XX format ticking up, until the stop button is pressed.

inner mesa
#

Stopwatches usually count up...

#

In any case, you can do what I've done before and do a brute force solution with an input_number and automation with a time_pattern trigger that increments it

paper hazel
#

Counting up is exactly what I am looking for ๐Ÿ™‚ Do you perhaps have an example of your brute force solution?

inner mesa
#

It's pretty straightforward

paper hazel
#

thx!

gray crane
#

Anyone know card-mod? I want to change the background color of a gauge card based on the value of the entitiy.

#

type: gauge
entity: sensor.cell_1_voltage
card_mod:
style: |
ha-card {
--ha-card-background: teal;
color: var(--primary-color);
}

#

That gets me a teal background, but how can I change the color based on the value of the entitiy instead?

timber prism
#

Hey, anyone know how to read out the state icon of an entity that doesnt have the icon as an attribute?

tired berry
#

What am I doing wrong here pls? I have default defined ... TemplateError('ValueError: Template error: int got invalid input 'unavailable' when rendering template 'Hugo potล™ebuje vymฤ›nit hlavnรญ kartรกฤ (zbรฝvรก {{ ( states('sensor.roborock_vacuum_s5e_main_brush_left') | default(3600*100,True) | int / 3600 ) | round(1) }}h)' but no default was specified')

sacred sparrow
#
- trigger:
    - platform: state
      entity_id: sensor.office_desk_switch_action
      not_from:
        - unavailable
        - unknown
  sensor:
    - name: Office Desk Switch
      icon: hue:dimmer-switch
      state: >
        {% set action = states('sensor.office_desk_switch_action') %}
        {{ trigger.from_state.state if action == "" else action  }}

Can anyone tell me why this trigger sensor is "unavailable" after a restart?
As soon as I press a button on the dimmer switch it comes alive again

marble jackal
#

the default you applied doesn't work as you intented, because unavailable is a perfectly correct state, so the default will not be applied

#

use this instead (to apply the default value to the int filter):
{{ ( states('sensor.roborock_vacuum_s5e_main_brush_left') | int(360000) / 3600 ) | round(1) }}

marble jackal
#

you can then use the automation to debug the template sensor, as there are no traces for template sensors

grand storm
#

How can I make a "cheapest_hour" sensor with a variable for "number of hours"?
So I can make an automation that says "Run the heater on the X cheapest hours"
(Later I want to make X depend on the out-door temperature.)

https://dpaste.org/jeBVr

marble jackal
#

Not sure what you mean with number of hours here.
The code you provided seems to create 3 sensors which retrurn True or False

#

line 36 is wrong though, it had the platform: template part of the next sensor

#

I would suggest to create binary sensors instead of sensors returning true or false

marble jackal
#

I also think you can simplify your templates to this:

{%- set prices = state_attr('sensor.nordpool_kwh_se4_sek_2_10_025', 'raw_today') %}
{%- set ns = namespace(hour_price=[]) %}
{%- for i in range(0, 24) %}
    {%- set ns.hour_price = ns.hour_price + [(i, prices[i]).value] %}
{%- endfor %}
{%- set sorted_hour_price = ns.hour_price | sort(attribute='1') %}
{{ now().hour in sorted_hour_price[:5] | map(attribute='0') | list }}
#

What you can do is create an input_number to set the number of hours you want to use (in the template above this is 5)

floral blaze
#

hey guys, i need a second pair of eyes on this one. Im trying to get this 'boink' animation to work on a specific state, it doesnt seem to work.

plain magnetBOT
grand storm
#

Ok.
So first i make an "input_number" that depends on the outside temperature.

Then I want to say:
Set the cheapest_hours to "true" for
{{ now().hour in sorted_hour_price[:"input_number"] | map(attribute='0') | list }}

marble jackal
#

almost ๐Ÿ™‚

#
template:
  - binary_sensor:
      - name: Cheapest Hours
        unique_id: binary_sensor_cheapest_hours
        state: >
          {{ now().hour in this.attributes.get('cheapest_hours', []) }}
        attributes:
          hours_used: "{{ states('input_number.hours_to_check') | int(0) }}"
          cheapest_hours: >
            {%- set prices = state_attr('sensor.nordpool_kwh_se4_sek_2_10_025', 'raw_today') %}
            {%- set hours_to_check = this.attributes.get('hours_used', 0) %}
            {%- set ns = namespace(hour_price=[]) %}
            {%- for i in prices %}
                {%- set ns.hour_price = ns.hour_price + [(loop.index0, i.value)] %}
            {%- endfor %}
            {{ (ns.hour_price | sort(attribute='1') | map(attribute='0') | list)[:hours_to_check] | sort }}
#

this gives you a binary_sensor which is on during the cheapest X hours (where X is based on input_number.hours_to_check)

#

it has an attribute cheapest_hours in which the cheapest X hours are shown

#

and it uses the new template sensor format (so don't place it in sensor.yaml, you can place this code direcptly in configuration.yaml, unless you already have template in there)

grand storm
#

Wow. Tnx.
I will have a real look at this later.

and the input_number.hours_to_check is set thru an automation?

marble jackal
#

made some adjustments

#

it's set however you want

#

manually from your dashboard, once, or through an automation

grand storm
#

why canยดt i put this in sensor.yaml?
I canยดt have both
template:

  • binary_sensor:
    and
  • platform: template
    sensors:
    in the same yaml-file?
marble jackal
#

because the new format is part of the template integration, and not the sensor integration

#

it's a whole new integration

#

and sensor.yaml has the code for the sensor integration

grand storm
#

Ah.
I think I understand.

A big thx!

marble jackal
#

you can create a template.yaml though, and include that one as well from configuration.yaml

#

I made a last minor change to the code above

analog nova
#

hi everyone, I am struggling setting a template up for a restful notification integration (https://www.home-assistant.io/integrations/notify.rest/).
The api of the chat platform I am trying to use takes a message and a target - as usual - but optionally it also takes a bunch of extra fields (ie icon_url) that I am trying to map/pass to the data field

#

it currently looks something like

- platform: rest
  name: chat
  resource: https://xxxxxxxxxxx/hooks/xxxxxxxxxxxxx
  method: POST_JSON
  target_param_name: channel
  message_param_name: text
  data:
    icon_url: '{{ data.icon_url|default("") }}'
    icon_emoji: '{{ data.icon_emoji|default("") }}'
#

seems like this is not the right way to pass a default value in the post message, since I am getting Template variable warning: 'None' has no attribute 'icon_url' when rendering '{{ data.icon_url }}'

#

My ideal goal would be to be able to send a message such as

service: notify.chat
data:
  message: hello

or

service: notify.chat
data:
  message: hello
  data:
    icon_url: 'whatever'
#

and have either of them work

analog nova
#

@inner mesa well the integration says that it takes a template in the data field, so that's basically what I am trying to figure out, I have never done this so I am equally confused

inner mesa
#

yes, I was wrong. I haven't used that integration before

dense swan
#

So how do I implement a template? I have one created but not sure how to actually install it.

inner mesa
#

?

#

what do you mean by "install"? You put what you mentioned in #general-archived in your configuration.yaml

dense swan
#

Ok so I have to put it in the yaml, gotcha.

#

Huzzah it worked.

#

Thanks @inner mesa

#

So for each template do I just place them under the existing template: header?

inner mesa
#

yes

dense swan
#

Ok that is cool

muted halo
#

Hello, I have an error message "key error" with the follonwing tempalte :
{% set entity = states.sensor.a52s_last_notification | selectattr("attributes.android.text*", "search", "avant pleine") | selectattr("attributes.android.text*", "search", "Bruit dรฉtectรฉ") | list %}
{% if entity | length > 0 %}
{% else %}
{{ entity[0].attributes.notifA52 }}: {{ entity[0].state }}
{% endif %}

#

Somebody could help me please ? thanks

inner mesa
#

You have nothing in the 'if' branch

#

But your issue is that you need |selectattr('attributes.android.text', 'defined')

muted halo
#

hello, the empty if branchh is normal i don't want any action inthere

#

in don't understant the issue selectattr('attributes.android.text', 'defined')

inner mesa
#

Ok

#

What's confusing?

#

And having the 'if' evaluate to nothing is broken

mighty ledge
muted halo
#

in the dev tools tab envent i have : KeyError:

marble jackal
#

the problem is that you do nothing if entity actually contains data, and if it doesn't you try do do stuff on an empty list

shell fractal
#

{% if states.binary_sensor.pir_sensor_4.state == 'on' and ({{ as_timestamp(now()) | float }} - states.binary_sensor.pir_sensor_4.last_changed | float) < 900 %}
True
{% else %}
False
{% endif %}

in this sensor I get the error TemplateSyntaxError: expected token ':', got '}.

inner mesa
#

Gack

#

{{ is_state('binary_sensor.pir_sensor_4', 'on') and (now() - states.binary_sensor.pir_sensor_4.last_changed).seconds < 900 }}

muted halo
marble jackal
#

I don't think you understand your template:

{% set list = [] %}
{% if list | length > 0 %}
  {# do nothing #}
{% else %}
  {{ list[0] }}
{% endif %}

This is basically what you are doing, which will never work, because your list will be empty when you want to work with it

muted halo
marble jackal
#

It won't be empty, but you built your template do it doesn't do anything when it's not empty

muted halo
marble jackal
#

Btw, the key error is probably caused by the . in the attribute key

#

I think you want something like this

{% set entity = 'sensor.a52s_last_notification' %}
{% set last = state_attr(entity, 'android.text') %}
{% if 'Bruit dรฉtectรฉ' in last and 'avant pleine' in last %}
  {{ state_attr(entity, 'notifA52') }}: {{ states(entity) }}
{% endif %}
#

Not sure about this notifA52 attribute though, took that from your template

nimble copper
#

I have an array of weather forecasting data. How can I select the entries that are tomorrow at 06:00 or 09:00 and then apply a test to the precipitation_probability to see if it's above or below a certain threshold?

#
[[{'datetime': '2023-01-03T00:00:00+00:00', 'condition': 'clear-night', 'precipitation_probability': 0, 'wind_bearing': 'SSE', 'temperature': 3.0, 'wind_speed': 11.27}, {'datetime': '2023-01-03T03:00:00+00:00', 'condition': 'cloudy', 'precipitation_probability': 7, 'wind_bearing': 'SE', 'temperature': 3.0, 'wind_speed': 14.48}, {'datetime': '2023-01-03T06:00:00+00:00', 'condition': 'pouring', 'precipitation_probability': 88, 'wind_bearing': 'SSE', 'temperature': 4.0, 'wind_speed': 25.75}, {'datetime': '2023-01-03T09:00:00+00:00', 'condition': 'cloudy', 'precipitation_probability': 37, 'wind_bearing': 'S', 'temperature': 6.0, 'wind_speed': 20.92}, {'datetime': '2023-01-03T12:00:00+00:00', 'condition': 'pouring', 'precipitation_probability': 85, 'wind_bearing': 'SSW', 'temperature': 8.0, 'wind_speed': 14.48}, {'datetime': '2023-01-03T15:00:00+00:00', 'condition': 'pouring', 'precipitation_probability': 89, 'wind_bearing': 'SSE', 'temperature': 8.0, 'wind_speed': 11.27}, {'datetime': '2023-01-03T18:00:00+00:00', 'condition': 'pouring', 'precipitation_probability': 92, 'wind_bearing': 'SSE', 'temperature': 9.0, 'wind_speed': 11.27}, {'datetime': '2023-01-03T21:00:00+00:00', 'condition': 'pouring', 'precipitation_probability': 92, 'wind_bearing': 'SSW', 'temperature': 10.0, 'wind_speed': 17.7},]
#

So far I've been able to get part of the way, extracting the corresponding datetiimes that match 06:00.

| selectattr('datetime', 'match', '^.*06:00') 
| list
}}
silent seal
#
{{ weather | selectattr('datetime', 'match', '^.*0(3|6):00') | map(attribute='precipitation_probability') | list }}

Only you'd probably want to use selectattr on the precipitation_probability with > to check if it's above a certain number

nimble copper
#

Thank you @silent seal

#

Is there a way I can only focus on those datetimes that match tomorrows date ?

inner mesa
#

you can do something like this:

{% set tomorrow_6 = (today_at('06:00') + timedelta(days=1)).astimezone(utcnow().tzinfo).isoformat() %}
{% set tomorrow_9 = (today_at('09:00') + timedelta(days=1)).astimezone(utcnow().tzinfo).isoformat()  %}
{{ state_attr('weather.home', 'forecast')|selectattr('datetime', 'in', [tomorrow_6, tomorrow_9])|selectattr('precipitation_probability', 'gt', 0.5)|list }}
silent seal
#

Yup

{% set tomorrow = (today_at('00:00') + timedelta(days=1)).strftime('%F') %}
{{ weather | selectattr('datetime', 'match', '^'~tomorrow) | selectattr('datetime', 'match', '^.*0(3|6):00') | map(attribute='precipitation_probability') | list }}
nimble copper
#

Thank you. @silent seal I'd been struggling to find out a way to do date additions. Big help!

silent seal
#

Or do what Rob said, he's much better at templates than I am!

inner mesa
#

mine's certainly more complicated and I'm not yet convinced that it's better. I hadn't thought about doing it with a regex

south cosmos
#

I think(?) I need template help for something that seems like it should be straight forward. I want to do something like this:

sequence:
 - service: input_number.set_value
 data: {value: "{{ sensor.ecobee_temperature }}"}
  target:
   entity_id: input_number.targettemp```
Where I essentially set an input_number helper's value to the current temperature from a sensor?  But I don't quite understand how to structure it from the documentation.
inner mesa
#

your indentation is all over the place there

#
alias: Set Current Temp
sequence:
 - service: input_number.set_value
   data:
     value: "{{ states('sensor.ecobee_temperature') }}"
   target:
     entity_id: input_number.targettemp
#

There's a big section on how to retrieve a state in the docs

#

and the rest of that page

south cosmos
#

apologies, the translation out of the yaml view to discord code wasn't a clean paste process lol. I'll take a look, thank you.

inner mesa
#

they have an example in the docs, too:

automation:
  - alias: "Set temp slider"
    trigger:
      platform: mqtt
      topic: "setTemperature"
    action:
      service: input_number.set_value
      target:
        entity_id: input_number.target_temp
      data:
        value: "{{ trigger.payload }}"
south cosmos
#

That's exactly the one I was trying to use as a template

inner mesa
#

but you had this:
data: {value: "{{ sensor.ecobee_temperature }}"}

#

doesn't look like that

#

anyway, use what I provided and review the link above

south cosmos
#

it was my best guess going from a completely unrelated MQTT "trigger.payload"

south cosmos
teal umbra
#

I followed the docs but I still having troubles to get it working

{% set tarief_per_kwh = 0.36 %}

{% set kwh = sensorwaarde_per_uur / 1000 %}
{% set kosten = kwh | int * tarief_per_kwh %}

{% set kosten_afgerond = kosten | round(2) %}

De kosten zijn {{ kosten_afgerond }} EUR.

TypeError: unsupported operand type(s) for /: 'str' and 'int'

What am I not seeing?

obtuse zephyr
#

{% set sensorwaarde_per_uur = states.sensor.met_vermogen_per_uur.attributes.last_period | float %}

#

its a string right now

#

also {% set sensorwaarde_per_uur = state_attr('sensor.met_vermogen_per_uur','last_period') | float %}

#

Don't access states directly if you don't have to

teal umbra
#

Oke still learning but thanks

plain magnetBOT
#

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

silent seal
#

This may be useful while you're learning things ๐Ÿ™‚

teal umbra
#

Ahhh thx @silent seal

marble jackal
#

I'm a bit surprised why they didn't convert the value in the last_period attribute to a number already, as that is allowed in an attribute.

pastel moon
#

Hi guys. Had some help with this the other day but found out yesterday that it did in fact not work as intended after all. I need to set a simple datetime helper, but it fails in the calculation. Dev-tools thinks not what the interpreter does... Any ideas please? https://paste.debian.net/hidden/f8c1a74d/

inner mesa
#

The two timedelta() calls are weird

#

I would also put |as_datetime before |as_local

pastel moon
#

Well, how can that be changed in a good way then? I have two sets of minutes from other variables...

inner mesa
#

That isn't clear from the code

#

You have 3 and 7

#

Which is 10

pastel moon
#

No sorry for that. The whole thing is huge

inner mesa
#

You've only said 'fails the calculation'

#

Anyway,

I would also put |as_datetime before |as_local

pastel moon
pastel moon
mighty ledge
pastel moon
#

Ok thanks, will try with that

#

Well, it gave an other error, so progress ๐Ÿ™‚ Error executing script. Invalid data for call_service at pos 3: Invalid datetime specified: ((state_attr('script.lights_off', 'last_triggered') | as_datetime | as_local) + (timedelta(minutes=3) + timedelta(minutes=7))).strftime('%Y-%m-%d %H:%M:%S') for dictionary value @ data['datetime']

inner mesa
#

you don't need the strftime() at all - you can just pass the datetime object

pastel moon
#

I added that to format the output for display purpose, but can remove it if it helps this

mighty ledge
#

you have to remove it

#

the error is telling you it wants a datetime

#

you're changing it to a string

#

when you format it

inner mesa
#

as I recall, if you provide a datetime, it just uses it. otherwise, it tries to convert the string to a datetime

#

seems like "%Y-%m-%d %H:%M:%S" should work, but only if the value you're passing in is valid

mighty ledge
#

well, then his issue is simpler than that

#

he's not making it a template

#

i.e. {{ and }} are missing

inner mesa
#

oh, lol

#

duh

mighty ledge
#

yah the error is lacking {{ and }}

#

so it's just seeing that whole mess

pastel moon
#

Hm. that is obviously not great... Thanks for pointing that out. Will change into a template and retry

inner mesa
#

that would have been clear if the "template" had been tested in the dev tool

#

I saw the "((" at the beginning and was confused by it ๐Ÿ™‚

pastel moon
#

Seems I have tested with {{}} in dev tools, just didn't copy them into the script ๐Ÿ˜ฆ

mighty ledge
#

Make sure you wrap it in quotes or use multiline yaml notation

pastel moon
#

More data type issues? {{ state_attr('script.lights_off', 'last_triggered') | as_datetime | as_local }} reders error TypeError: float() argument must be a string or a real number, not 'datetime.datetime'

inner mesa
#

looks like it's already a datetime object, so now back to your original template with just |as_local

#

|as_datetime gives that nonsense error if it's provided a datetime object, rather than just passing it through as-is ๐Ÿคท

#

One day my long-standing PR to fix |expand and friends will be merged and I'll be more likely to "fix" more template issues like that

#

(or not)

pastel moon
#

This was it: {{ state_attr('script.lights_off', 'last_triggered') | as_local + (timedelta(minutes=3) + timedelta(minutes=7)) }} Thanks a lot @inner mesa & @mighty ledge !

mighty ledge
#

pretty sure last_triggered attribute can be a string or a datetime

#

๐Ÿ”ง

marble jackal
#

The funny thing with those is that it's not recognized as datetime in devtools, but then it errors in the actual script/automation

#

No, I'm wrong here

#

It also fails in devtools

inner mesa
#

you technically can't have a datetime object as an attribute because it's not serializable

#

or "aren't allowed to"

#

you can

plush willow
#

Can anyone tell me wat I do wrong? First I had created groups in Home Assistant (they give me the correct light count). Now I have deleted those and uses the groups of the Hue lights

{% set lightcount = expand('light.woonkamer') | selectattr( 'state', 'eq', 'on') | list | count %}
{{ lightcount }}

this gives me 1 light but there are 8 lights in the Hue group light.woonkamer

mighty ledge
#

hue groups also don't have entities attached to them so expand won't work

#

i.e. you'll still need your HA groups

plush willow
#

oh serious ๐Ÿ™‚ ... I just deleted all my groups in HA

mighty ledge
#

you should check out the docs before making a switch like that ๐Ÿ™‚

plush willow
#

But when I check the state of light.woonkamer in the developer tools I get all the entities printed of that Hue group

#

so the system knows which entity belong to that Hue group

mighty ledge
#

is it in the entity_id attribute?

#

that's all expand expands

#

no attr -> no expand

plush willow
#

lights:

  • Voorraam woonkamer kleine raam
  • Voorraam woonkamer grote raam
  • Achterraam woonkamer deur
  • Achterraam woonkamer muur
  • Openhaard muur
  • Servieskast strip
  • Openhaard deur
  • Tv ledstrip
mighty ledge
#

right, tha'ts not entity_ids

plush willow
#

that are exactle all the 8 lights in the group

mighty ledge
#

and that attribute is named lights

plush willow
#

yes

mighty ledge
#

ok, then expand won't work

#

expand only expands the entity_id attribute and it needs to have valid entity_ids

#

which that is not

plush willow
#

okay. So I have to create all groups in Home Assitant. Then the Hue group (which is default disabled) you have to use to have a better experience on setting all the lights on/off at one? Am i right?

mighty ledge
#

Not sure I follow you

#

I don't use hue

plush willow
#

okay

silent seal
#

What is your aim?

plush willow
#

my aim is that I have some sensor that count how many lights are on in a specific group. That was working perfect with the HA groups but now with the Hue groups Iit don't work ant more. But petro explained that that kind of information is not avilable from the hue group

#

So I will go recreate them, so that I can use the HA groups for counting lights and the Hue Groups to enable/disable the group (for a better experience what I have read)

obtuse zephyr
#

If those lights are available in the Hue group in a separate attribute, couldn't you just grab that attr using state_attr and then use expand on the array from that?

mighty ledge
#

it lists friendly hue light names

obtuse zephyr
#

Ah, not the entity ids

mighty ledge
#

yep, so it could be done only if the hue entities had a 'hue_friendly_name' attribute or something like that

plush willow
#

a hue light has this attribute:

friendly_name: Openhaard deur

mighty ledge
#

that's the home assistant friendly name

#

it needs to be the name that comes from hue

plush willow
#

nope that don't exists

mighty ledge
#

if you don't alter the names that come from hue, then you could potentially do it

plush willow
#

okay but I think I'm going to restore my HA light groups (I have all text in my notepad) Then it will work again

mighty ledge
#

and I don't know what would happen if you changed the name in hue

plush willow
#

thanks for the help!

mighty ledge
#

np

spark stirrup
#

Hi!

How would one build a sensor that tells if a states value is at a "low point" given X amount of time? Example: Trigger automation when fuel price sensor is at 7-day-low.. Any ideas?

Thanks!

obtuse zephyr
#

If you trigger directly on it though, you'll need to figure out what you want to do if the value continues to decrease though.... otherwise, you'll see repeating triggers every time it updates. Whereas if you base it on the template sensor, you could trigger once the first time it is equal and not continue to trigger until it rises again.

mortal plinth
#

I am very new to Home assistant. Just created a new sensors.yaml and pointed at in the configurations.
Treid to use code provided on home assistant page for 3em integrations. But i get "missing property platform" and "propterty utility meter not allowed" Where do i start ๐Ÿ™‚ Hope by posting on correct supprt channel in discord lol

obtuse zephyr
plain magnetBOT
#

Sadly we're not mind readers (any more anyway, not after the last time we tried). Please share the YAML and any errors so we can see what you've done.

mortal plinth
obtuse zephyr
#

Click the link from the message, paste it in a code sharing site

#

and share the link

mortal plinth
obtuse zephyr
#

That section is technically a snip directly from a configuration.yaml

#

If you included a new sensor.yaml file and pasted it all in there, it wouldn't work

#

Only the section prior to utility_meter is for sensor

#

Was all of that pasted in sensors.yaml?

mortal plinth
#

Yes.

obtuse zephyr
#

How is your configuration.yaml referencing the sensors.yaml file? sensor: !include sensors.yaml? Or something different

mortal plinth
#

like this| sensor: !include sensors.yaml

obtuse zephyr
#

The utility_meter stuff needs to either be put in the configuration.yaml directly, or split out similar to how you did it w/ sensors

mortal plinth
#

Thank you. I have pasted this in sensors.yaml and have update the utility stuff in Chonfigurations.yaml.

In config yaml there is no error.

However in the sensors.yaml i have 9 errors most of them are stating: end of the stream or adocument seperator is expected. And one is line 38 power_consumptions Missing property "platform"

Oh what have i started at ๐Ÿ™‚

obtuse zephyr
mortal plinth
#

Wired that the code itself is doing this as it is posted to so many. I think you got 3 out of 9 issues. As it is know only showing 6 issues.
For this i think it may be easy to show in a picture

obtuse zephyr
#

You can upload to imgur or another sharing site

mortal plinth
#

thnaks for the suggestion

obtuse zephyr
#

Did you paste again from my update?

#

eh... i think it's dpaste

#

Use that

mortal plinth
#

INdeed it was probably dpast. TIL alot ๐Ÿ™‚ Dpast can show raw and use taht for future things haha

Thank you so much for your help and time.

I dont want to fiddel with it know that it works. However, i am curious to how easy it would be to copy the original code directly to configurations.yaml. I treid that in the start aswell with some errors. Does not seem on the forum that any others are having the issue ๐Ÿ™‚

obtuse zephyr
#

If you just pasted that snippet as into into configuration.yaml, it should've worked. However, as you use HA more and more, you would've done what you did here by splitting the configuration

#

It makes it much easier in the long term to manage things

mortal plinth
#

Oh i got it working know, tried both had to learn lol. Nice to know i am on the right track.
Again thank you very much for your help ๐Ÿ™‚

obtuse zephyr
#

Awesome, glad to hear, you're welcome

sacred sparrow
#

is there a better way to do this:

        {% if bed 'unavailable' or 'off' or 'unknown' %}
          Out
        {% elif bed 'off' %}
          Out
        {% else %}
          In
        {% endif %}```
silent seal
#

Well, your elif will never be true

#
{{ is_state('binary_sensor.withings_in_bed_sensor', 'on') | iif("In", "Out") }}

This will be equivalent ๐Ÿ™‚

sacred sparrow
#

oh of course - thank you!

marble jackal
#

You were missing ==
bed == 'off', not just bed 'off'

#

But the solution of Rosemary is a lot better

rare sage
#

Good Day All, I had this tamplate that monitored how long my power was off but is no longer working.

#
example: 
  - platform: history_stats
    entity_id: sensor.grid_frequency
    name: no_mains
    state: 0
    type: time
    start: "{{ now().replace(hour=0, minute=0, second=0) }}"
    end: "{{ now() }}"
#

Any advise