#templates-archived

1 messages · Page 137 of 1

mighty ledge
#

just have:

cover:
  - platform: template
    covers:
      garage_door:
        device_class: garage
        friendly_name: "Garage Door Large Combined"
        value_template: "{{ is_state('binary_sensor.large_garage_door_access_control','off') }}"
        open_cover:
          service: switch.turn_on
          target:
            entity_id: switch.garage_door_large
        close_cover:
          service: switch.turn_on
          target:
            entity_id: switch.garage_door_large
        stop_cover:
          service: switch.turn_on
          target:
            entity_id: switch.garage_door_large
#

If you want to learn about yaml anchors, you can simplify that even further

#
cover:
  - platform: template
    covers:
      garage_door:
        device_class: garage
        friendly_name: "Garage Door Large Combined"
        value_template: "{{ is_state('binary_sensor.large_garage_door_access_control','off') }}"
        open_cover: &garage_cover_service
          service: switch.turn_on
          target:
            entity_id: switch.garage_door_large
        close_cover: *garage_cover_service
        stop_cover: *garage_cover_service
#

but that's advanced

foggy veldt
#

will get back to you in a minute

#

awesome that seemed to do it! now i just need to change the icons up a bit and i'll have er where i want it. thank you greatly

mighty ledge
#

np, now that you somewhat understand what the templates are doing, you should be able to use the template editor to get you what you want

foggy veldt
#

where can i go to see how that works? happy to read it myself you've been more than enough help

inner mesa
#

YAML anchors?

foggy veldt
#

Template editor

inner mesa
#

devtools -> Templates

#

nothing much to read, just go and do

foggy veldt
#

whats really weird is i have two of the exact same ecolink sensor one shows up as binary and one as just sensor not sure why that would be.

mighty ledge
#

How are they integrated?

foggy veldt
#

both were added the exact same through Z-Wave JS

mighty ledge
#

Zwave? zwave js?

#

K

foggy veldt
#

but both appear to work just an interesting nuance

inner mesa
#

See if there are disabled entities

mighty ledge
#

Same firmware?

foggy veldt
#

there are quite a few on both sensors. yes same firmware

mighty ledge
#

Probably in disabled entities the

#

Then*

#

Or the inclusion process didn’t finish on one

foggy veldt
#

ONe shows Window/door is closed on the access control. Just looks different than the same exact sensor on the door next to it. not that its an issue per say just intersting

mighty ledge
#

Take a screenshot of both and post to Imgur and link here

#

I’m interested in what you’re talking about

foggy veldt
#

ok hold on quick i've never used imgur so itll take me a minute

#

Two screenshots from each sensor

#

or rather device

inner mesa
#

Which there are

mighty ledge
#

Ya, it’s definitely in the disabled entities

#

The one has 8 vs 6

foggy veldt
#

yes i know. What i was getting at though is they all show up as sensors not binary sensors

#

anyway though it works. Thanks again for the patience and helping me through all of it. Greatly appreciated.

torpid cloud
#

am not sure this is the right place to ask. But still try some who have a go icon package they can recommend? Seemed mdi does not meet all my requirements

inner mesa
silent barnBOT
fickle knoll
#

I'm posting LESS than 15 lines of code!

north locust
#

having trouble with my alarm_clock template, it displays the alarm in negative values when dismissing an alarm on our android phones, have nex_alarm sensor enabled in HA companion app, is this normal behaviour for the alarm apps on our phones or something wrong with my template ?
https://pastebin.ubuntu.com/p/2MsrwVBdrZ/

#

is there an interval at which HA app updates next_alarm to HA ?

#

i sometimes have an alarm set 1 hour apart from my wife , and it doesn't update when wife's alarm was dismissed...

half pendant
#

is there a way to group several of the same devices into one? For instance i have two exact same heaters in one room and i'd like to control them as one, is there a way to create a device that holds the others?

mighty ledge
foggy veldt
#

Cover Template: thanks to the help in here yesterday i was able to get it figured out and was able to get the icons to display as i wanted them. But now i am wanting to change the icon color based on the door status. The code i have been trying does not appear to be the correct syntax (i based it on the icon template syntax) icon_color: >- {% if is_state('binary_sensor.large_garage_door_access_control','off') %} return: 'green' {% else %} return: 'red' {% endif %}

mighty ledge
foggy veldt
#

gotcha. makes sense. i did put in a custom card i'll look more into that and see if that card has the option to change color of the icon i wasnt seeing it there.

nocturne chasm
#

state_color: true

odd maple
#

is there a jinja filter similar to the python function of all() ?

inner mesa
#

something like |select('eq', false)|length == 0

mighty ledge
#

or comp the generated list length to input list length

mighty ledge
#

I'm curious now

odd maple
#

I scraped that method of thinking 😛

#

wanted to do a if any of [list of sensors] == "unknown" return false

#

for an availability template

mighty ledge
#
{{ blah | selectattr('state','in', ['unknown','unavailable']) | list | length > 0 }}
#

add a not in there

#

for false 😉

oak tiger
#

Hello. Little tip please if I am going in right direction. I create a new template sensor that stores a list of entity names. Media player entitiy names. List is based on room motion. If there is a motion in room, this sensor will hold list off media_player entities. Next I wish to use media_player.volume_set with this template sensor entity, but nothing happens and log is also empty. Same goes with tts.cloud_say.

#
  • service: tts.cloud_say
    data_template:
    entity_id: sensor.active_google_speakers
#

Value of sensor.active_google_speakers is currently ['media_player.google_living'].

#

Not sure where to look for this solution. I can not use a list for entity_id?

#

I think I figured it out.

#

entity_id: >-
{{ states('sensor.active_google_speakers') }}

inner mesa
#

and data: instead of data_template:

silent barnBOT
mighty ledge
#

value_template needs to be a string

#

that returns a list

#

FYI

#

you can simplify that

#
        {% set data = namespace(entities=[]) %}
        {% set exclude_list = ['camera.rockrobo_map', 'camera.pc_ambilight'] %}
        {% for state in states.light | rejectattr('entity_id', 'in', exclude_list) if device_id(state.entity_id) is not none %}
        {% set data.entities = data.entities + device_entities(state.entity_id) %}
        {% endfor %}
        {{ data.entities | unique | list | join(', ') }}
#

but, you probably don't need to reject the cameras

#

because states.light filters to only light entities

#
        {% set data = namespace(entities=[]) %}
        {% for state in states.light if device_id(state.entity_id) is not none %}
        {% set data.entities = data.entities + device_entities(state.entity_id) %}
        {% endfor %}
        {{ data.entities | unique | list | join(', ') }}
oak tiger
#

Instead of {% set data = namespace(media_players=[]) %} ... {{ data.media_players }} I should store in sensor {{ data.media_players | unique | list | join(', ') }}?

mighty ledge
#

Not sure what you mean

#

There are very few usecases currently to use namespace

oak tiger
#

I store a list in template sensor. I should store a string with comma seperated entitiy_ids?

mighty ledge
#

a string with comma separations will convert to a list anyways

#

so, it doesn't matter

#

if you're storing it in an attribute, you can just use

#
{{ data.media_players | unique | list }}
oak tiger
mighty ledge
#

holy

oak tiger
#

And this seems to be working. Need to find a way now disable the anoying google speakers bling sound when they turn on.

#

🙂

#

I over complicate things I know. Goal is to have google tts notifications working on speakers in rooms where there is motion.

#

And they should fire all in same time on all speakers. So I created every possible room combination speaker groups.

mighty ledge
#

you should break it down by room with if statements and have the people check as variables

#

but if it works for you

#

come back to that in a year and you'll have a headache

oak tiger
#

Hehe. Imaging adding a speaker in another room...

#

Can not see other way to optimize this.

#

Now to disable the bling! sound when speaker turns on.

#

Thank you.

jagged obsidian
#

when you find out let me know 😁

oak tiger
#

There are forum topics about this.

#

Need to test this.

#

For example.

jagged obsidian
#

let me rephrase: when you find a simple way 😛

oak tiger
#

Well on forum is per speaker only. I only wish to set volume twice per day. In morning and in evening.

#

Without waking up entire house.

slim holly
# mighty ledge ``` {% set data = namespace(entities=[]) %} {% set exclude_list ...

@mighty ledge thank you for your answer. With your code i have exactly the same problem as with my code. In the developer tools the code is working, but as value_template it does not work. The state in the sensor show nothing.

platform: template
sensors:
  exclude_activity_entity_list:
    value_template: >-
      {% set data = namespace() %}
      {% set data.entities=[] %}
      {% set data.status="" %}
      {% for state in states if state.entity_id.startswith('light.') and device_id(state.entity_id) is not none %}
      {% set data.entities = data.entities + device_entities( device_id(state.entity_id)) %}
      {% endfor %}
      {{ data.entities | unique | list | join(', ') }}
mighty ledge
#
{% set zan = 'zan' is_state('binary_sensor.motion_zan_occupancy', 'on') else '' %}
{% set lara = 'lara' is_state('binary_sensor.motion_lara_eva_occupancy', 'on') else '' %}
{% set bedroom = 'bedroom' if is_state('binary_sensor.motion_bedroom_occupancy', 'on') else '' %}
{% set bathroom = 'bathroom' if is_state('binary_sensor.motion_bathroom_occupancy', 'on') else '' %}
{% set players = [ zan, lara, bedroom, bathroom ] | reject('eq', '') | list %}
{% set data = namespace(media_players=[]) %}
{% set p for p in players %}
  {% if 8 <= now().hour < 20 %}
    {% set data.media_players = data.media_players + [ 'media_player.google_' ~ p ] %}
    {% for p2 in players | reject('eq', p) %}
      {% set data.media_players = data.media_players + [ 'media_player.' ~ p ~ '_' ~ p2 ] %}
    {% endfor %}
  {% endif %}
{% endfor %}
#

your second part could be simplified if you named your media_players better

#

like you did in the first part

#

FYI, your current template is incorrect with how you're using and now().strftime("%H")|int >= 8 and now().strftime("%H")|int < 20 %}

#

that portion is never used because the first part resolves true and that's the action that is being taken.

mighty ledge
#

instead of a ,

slim holly
mighty ledge
#

Post what you doing when you place it under value template

slim holly
# mighty ledge Post what you doing when you place it under value template
platform: template
sensors:
  exclude_activity_entity_list:
    value_template: >-
      {% set data = namespace() %}
      {% set data.entities=[] %}
      {% set data.status="" %}
      {% for state in states if state.entity_id.startswith('light.') and device_id(state.entity_id) is not none %}
      {% set data.entities = data.entities + device_entities( device_id(state.entity_id)) %}
      {% endfor %}
      {{ data.entities | unique | list | join(', ') }}

If i replace the last line of code with "test" the state of the sensor is showing "test", so the problem must be the last line.

mighty ledge
#

replace the , with a |

#

in the last line

#

also, that template will only update once per minute at most

#

unless you make the changes I suggested earlier

slim holly
mighty ledge
#

that doesn't make sense

#

are there errors in your logs?

#

also, have you made the changes I suggested or are you ok with at most 1 update per minute?

slim holly
# mighty ledge are there errors in your logs?

This was the right tipp, i'm so stupid. The result of the template was longer than 255 chars! homeassistant.exceptions.InvalidStateError: Invalid state encountered for entity ID: sensor.exclude_activity_entity_list. State max length is 255 characters. Sorry that i waste your time 😦

mighty ledge
#

no waste

#

but you need ot realise when you use states in a template, the template is throttled to 1 update per minute

#

that means if you have 10000 updates over the single minute, you'll only see the first one.

slim holly
#

I used "reload template entities" from the server tools without problems so far.

mighty ledge
#

ok, but you still aren't understanding

#

the template sensor you are creating

#

will only update once per minute, maximum

#

if you need instantaneous updates on that sensor, you will not get that

slim holly
mighty ledge
#

yes, that's correct. But if your states update, the template will not react to the update

#

ignore the 'reloading' bit

slim holly
#

Ahh, ok is there a better way instead of states?

mighty ledge
#

yes, states.light instead of states if state.entity_id.startswith('light.')

#
{% for state in states.light if device_id(state.entity_id) is not none %}
slim holly
#

Ok will try this. Thank you so much!

mighty ledge
#

np

floral shuttle
#

sorry wrong # ..

hollow summit
#

hello, do someone can help me with this cover template? it was working with an rf binary sensor, but now I change it to a zigbee binary sensor, with z2m

#

it always appear as unavailable

jagged obsidian
#

Your availability topic or payloads are incorrect

#

Also it's not a cover template, it's MQTT cover

hollow summit
#

My paylod is correct, as you say, I think it's my available topic, but I think I got from the Z2m website, maybe I need to double check it

hollow summit
# jagged obsidian Also it's not a cover template, it's MQTT cover

I already change the payload, as you say, it was wrong, but, it doesnt work, do you recommend a way to make my garage door card, with arrow up to open and down to close, and with the garage door icon to notice if is open or closed, my setup right now is a sonoff basic with tastmota to make a dry contact in the garage motor contact, and I want to set the status of the garage door with a zigbee door sensor working in zigbee2mqtt

half pendant
#

Is there a way to group radiators together in the same way you do with light groups?

mighty ledge
half pendant
#

climate

mighty ledge
#

you'd have to make a climate template entity

half pendant
mighty ledge
silent barnBOT
mighty ledge
#

use generic thermostat combined with template sensors

pastel moon
#

Hi guys, next challenge... I'm trying to create a template that evaluates to true if time(now() is 15 minutes before a set time. This is what I have so far, is there a better way? ```
"{{ ((now().strftime("%s") | int + (900)) | timestamp_custom("%H:%M", false)) > "17:36" }}"

tight wedge
#

hey guys, is there any1 who can help me to create a template for vapor pressure deficit? i have no ideae what i'm doing wrong after like 15 attemps of implementing someone else his template

jagged obsidian
#

It's usually beneficial to both parties to show what you want to get and what you tried instead of using vague terms

tight wedge
amber hull
#

I made a sensor base on information on the forum. Most of the time it gives the correct information on the Lovelace cards. Other times it shows the word "running"

silent barnBOT
finite swallow
#

Does anybody else's binary_sensor template get stuck? I'm using them for motion sensors but sometimes they just get stuck in a state. The only way to get them unstuck is to change their state manually to unavailable then change back.

inner mesa
#

no, that is not normal

finite swallow
mighty ledge
#

or

inner mesa
#

~share your template

silent barnBOT
jagged obsidian
mighty ledge
#
{{ now() - timedelta(minutes=15) > (now().date() ~ "T" ~"17:23:00") | as_datetime }}
#

or

{{ now() - timedelta(minutes=15) > now().replace(hour=17, minute=23, second=0) }}
#

I really think we need a new macro that takes a string 'HH:MM' or "HH:MM:SS" and makes a datetime out of it

#

something like

today("17:23")
jagged obsidian
#

That is an excellent idea

#

Would reduce the time template acrobatics

pastel moon
#

That would be awesome! And thanks @mighty ledge for the examples!

finite swallow
# inner mesa ~share your template

lamps_motion:
friendly_name: "Lamps Motion Sensor"
value_template: >
{{ is_state("binary_sensor.bedroom_motion_sensor", "on") }}
availability_template: >
{{ is_state('input_boolean.reset_all_motion_sensors', 'off') }}
delay_off:
minutes: 5

dense sleet
#

Hi guys, i hope you can help me with formatting the value of a sensor 🙂
I want to get the Uptime of a remote windows machine. Therefore im running a command with ssh and i am getting this value: "LastBootUpTime 20211002102605.500000+120"
Is it somehow possible to get this to the actuall uptime of the remote mashine? Im sorry im new to this 😄 Greetings

inner mesa
#

otherwise, it's just reflecting the state of the referenced sensors, so make sure they show the state you expect

dense sleet
#

could anybody please tell me how to format "LastBootUpTime 20211002102605.500000+120" to "2021-10-02T10:26:05" ? I would appreciate it .)

torpid reef
#

Hi guys,
How would you add the current time to a notification?

finite swallow
#

The Zigbee motion sensors are reporting as on when they see motion so it should be turning on this template sensor.

#

Another thing that happens sometimes is when turning on lights the home assistant shows the light on but the light in real life is not.

fossil venture
fossil venture
mighty ledge
dense sleet
mighty ledge
#

What does s return?

#

{{s}}

uneven blade
#

I'm having some issues with adding a new sensor template.... can someone assist? I'm guessing it's something to do with the YAML formatting, but for the life of me i'm not seeing it.

#
    current_channel_1:
      friendly_name: Shed Panel Sensor 1 Current
      unique_id: current_channel_1
      unit_of_measurement: "A"
      value_template: "{{ (states('sensor.shellyem_e459d4_channel_1_power') | float / states('sensor.shellyem_e459d4_channel_1_voltage') | float) | round(2) }}"
    current_channel_2:
      unique_id: current_channel_2
      friendly_name: Shed Panel Sensor 2 Current
      unit_of_measurement: "A"
      value_template: "{{ (states('sensor.shellyem_e459d4_channel_2_power') | float / states('sensor.shellyem_e459d4_channel_2_voltage') | float) | round(2) }}"
#

i get configuration invalid: Invalid config for [sensor.template]: expected dictionary for dictionary value @ data['sensors']. Got None. (See ?, line ?).

dense sleet
# mighty ledge What does s return?

{{s}} returns
LastBootUpTime
20211002102605.500000+120

I guess the string "LastBootUpTime" is the problem, but i dont know how to filter it :/

mighty ledge
#

Don’t filter it, add it to the format

#

Put it in front of the strptime format in the quotes

#

I’m on mobile so you’ll have to figure it out

#

Unless someone like @inner mesa can paste it quick

dense sleet
mighty ledge
#

Ya

dense sleet
# mighty ledge Ya

its not working :/ what am i doing wrong?
EDIT: i got it, thank you verymuch !

mighty ledge
#

Nice

uneven blade
#

can anyone offer a suggestion on my issue?

mighty ledge
uneven blade
#

i have sensors above that snippet that work.... here's the full thing....

silent barnBOT
uneven blade
#

i'm a doofus

#

ignore me

#

user error

mighty ledge
#

😬

uneven blade
#

i had started typing it elsewhere in the file, then put it in the right place, forgot to take out what i had started elsewhere

dense sleet
# mighty ledge Nice

do you have an idea to get the difference between the sensor time and the time sensor at this moment ? To get the actual uptime and not the time it was booting? 😄

mighty ledge
#

Just put the sensor on an entities page with device class set to timestamp

#

Clarify: device_class: timestamp goes on the configuration of the template sensor

dense sleet
mighty ledge
#

Right, I understand and what I said will give you that as a result in the ui

dense sleet
mighty ledge
#

You have to place it in an entities card

#

Or look at the entity state after it’s translated

#

Looking in the states page will return the under the hood value

dense sleet
mighty ledge
#

Entities

#

Not entity

#

For some reason, timestamp sensors haven’t been implemented on the entity card yet

dense sleet
agile storm
#

Is there anyway of sending one telegram message with inline_keyboard entries depending on the state of each switch

whole marsh
fossil venture
whole marsh
#

yes that's what that template uses. but i want to get warnings before it expires

#

just in case my cert renewal stuff fails

fossil venture
#

You are comparing strings, which is fair enough, but the first value in your first if statement is not typed as a string.

whole marsh
#

yeah strings was the best way i could figure out how to do it. open to alternative suggestions as well

fossil venture
#

{% if as_timestamp(states('sensor.ssl_cert_fuzzymistborn')) | timestamp_custom('%Y-%m-%d') > (now().date() + timedelta(days=14)) | string %} needs to be {% if as_timestamp(states('sensor.ssl_cert_fuzzymistborn')) | timestamp_custom('%Y-%m-%d') | string > (now().date() + timedelta(days=14)) | string %}

jade inlet
#

Hi All, first look at templates.. what i am trying to achieve is. 1. Find out what switched a light ON/OFF, Local light switch connected to zigbee device, User via GUI or an Automation 2. If light turned on by local switch or user via GUI disable associated automation being able to turn lights off 3. If light turned off by local or GUI, re-enable automation. I have just read some of the documentation on Templates, however have not really grasped it as yet. Dont suppose anyone has done this already or could throw some lines together that might at least steer me in the right direction?

thorny snow
#

how to create a switch with 2 URLS ? url 1 activate url2 deactivate?

thorny snow
#

o thank you

thorny snow
#

question: given the following configuration, is there a reason that none of my sensors show up in HA?
https://pastebin.com/DMMSP4Jt
If I use the old way of setting up template sensors they do work, but with the new structure none of them seem to work

#

I'm on the latest 2021.9 so it should at least do something

ivory lily
#

Try the following formula:
´´´

  • platform: template
    sensors:
    sensor.power_consumption:
    friendly_name: "Power consumption"
    value_template: {{ ( states('sensor.power_consumption') | float - states('sensor.power_pr>
    unit_of_measurement: "kWh"
    ´´´
    Indentations are probably wrong, and there is something missing on the value_template line. I just copied one of your sensors...
thorny snow
#

the part missing is just my console cutting off. the line is complete

#

which is the thing I'm trying to get away from

#

I want to use the new format

marble jackal
#

remove the - before sensor:

#

als you are importing it as a list, it will be added automatically

thorny snow
#

ah thanks man, good to know 🙂

#

hmm no change when I remove the list marker

marble jackal
#

wait a sec, upon second review. You use a command to include a dir, but you provide a file

#

This is my include:

template: !include_dir_list /config/include/template/
#

For a file you should use:

thorny snow
#

hmmmno I'm providing a directory

marble jackal
#

sorry, my second review was not correct

thorny snow
#

that's fine. I just didn't add the final / at the end

marble jackal
#

does it work now?

thorny snow
#

hmm nope

marble jackal
#

I also use this new template format, but I have separate files per sensor, and they all start with sensor:

thorny snow
#

nope even with all sensors removed and just the most basic one nothing shows

#

I wanted to separate them out like that based on function but that didn't work

#

so I separated them by type instead

marble jackal
#

I have the include like provided above, then in that dir I have a dir per type (sensor/trigger/binary_sensor)

thorny snow
#
➜  ~ grep template config/configuration.yaml 
template: !include_dir_merge_list input_templates
➜  ~ ls -l config/input_templates 
total 8
-rw-r--r--    1 root     root           166 Oct  7 16:01 binary_sensor.yaml
-rw-r--r--    1 root     root          1120 Oct  7 16:03 sensor.yaml
#

I have this

marble jackal
#

And then I provide my sensors like this:

sensor:
  unique_id: sensor_nightstate
  name: Nightstate
  state: >-
    {% if is_state('sun.sun', 'below_horizon') %}
      1
    {% else %}
      0
    {% endif %}
thorny snow
#

it works for other assorted things but just not for templates

marble jackal
#

This works for me 🙂

thorny snow
#
sensor:
  - name: "net_power_flow"
    unit_of_measurement: "kWh"
    state: >
      {{ ( states('sensor.power_consumption') | float - states('sensor.power_production') | float ) }}
marble jackal
#

looks fine

thorny snow
#

right?

#

I'm confused why this doesn't show up at all while the legacy version works just fine

marble jackal
#

if you put that in eg net_power_flow.yaml

#

it should work

thorny snow
#

maybe but I wanted to use include_dir_merge_list precisely so that I don't have to mess around with precise filenames and such 😦

marble jackal
#

doesn't matter, you can also put it in dit_is_een_leuke_naam.yaml

silent barnBOT
marble jackal
#

but this is more a topic for #integrations-archived since it concerns the template integration, and not the template itself 🙂

thorny snow
#

really? seems more like a base template problem to me?

jagged obsidian
#

It's not a template problem

thorny snow
#

as in, I either don't understand them or there's some weird quirk I'm not getting

marble jackal
#

Your actual template is fine, but you have an issue with the template integration 🙂

jagged obsidian
#

Why are you using sensor: if it's a dir merge list?

thorny snow
#

because some of the things I want templated are regular sensors and some are binary sensors

marble jackal
#

That's the issue, it is a list, not a dictionary

thorny snow
#

and according to the docs you need to specify that in the template

marble jackal
#

you need !include_dir_list instead of !include_dir_merge_list

thorny snow
#

example from the docs

#
template:
  - sensor:
      - name: "Average temperature"
        unit_of_measurement: "°C"
        state: >
          {% set bedroom = states('sensor.bedroom_temperature') | float %}
          {% set kitchen = states('sensor.kitchen_temperature') | float %}

          {{ ((bedroom + kitchen) / 2) | round(1) }}
#

I just split this out over the 2 files

#

template itself in configuration and the rest in my file

marble jackal
#

No wait, I'm confusing everything now

thorny snow
#

nope I really do think it should be merge_list

marble jackal
#

With dir_merge_list you do need the - in front, but I think you need to provide - sensor: for every sensor

thorny snow
#

see but that's weird... why do we put a list in sensor and the only allow a single item?

#

I'll try it

marble jackal
#

so:

- sensor:
  - name: "net_power_flow"
    unit_of_measurement: "kWh"
    state: >
      {{ ( states('sensor.power_consumption') | float - states('sensor.power_pr>
- sensor: #add sensor here
  - name: "Forecast Minimum Temperature (3d) new"
    unit_of_measurement: "°C"
    state: >
#

but then with the right indentation

thorny snow
#
sensor:
  - name: "net_power_flow"
    unit_of_measurement: "kWh"
    state: >
      {{ ( states('sensor.p
#

to me this makes no sense: we have a sensor: object with a list inside. but we cannot actually use the list as a list?

marble jackal
#

It looks weird indeed, but does it work?

thorny snow
#

I forgot to put the hyphens back so I'm checking again 🤦‍♀️

marble jackal
#

You know you can reload template entities without rebooting right?

thorny snow
#

yes. with the hyphens and multiple sensors in the list it does work

#

yes

#

I do that 🙂

#

I think it's a bit strange that we have to redefine sensor each time but it makes sense if you see each sensor entry itself as a list item defining the type

#

the error in my throught process was therefore that you cannot define the sensor TYPE once and then have multiple sensor instances (of that type) listed below it

#

each individual entry must be individually typed

#

okay

#

well that's fixed then

marble jackal
#

👍

thorny snow
#

thanks @marble jackal . see ya on the forums 😉

dense oak
#

I don't really get how templates work, but how would I be able to implement this?

when status of input_number.a changes:
if(input_number.a != input_number.b)
if(input_number.a > number.b)
(b-a)/10 * script.x
if(input_number.a < number.b)
(a-b)/10 * script.y

#

@inner mesa could you maybe help?

inner mesa
#

the first "if" statement shouldn't be required because input_number only has a state that will change, and the automation will only trigger if the state changes

#

I don't know what (b-a)/10 * script.x means. Call the script a bunch of times?

dense oak
#

yeah, the min would be 1 the max would be 9

inner mesa
#

oh, I missed that you're comparing input_number.a and input_number.b

#

anyway, you should read this page, particular the parts on choose and repeat:

#

and you don't need the initial "if" clause because neither of the next two will match

dense oak
#

okay, will look into it!

amber hull
#

I'm trying to clean up my template errors before Dec and I am not understand the messages. Hopefully someone can give me some insight? Template warning: 'float' got invalid input '2021-10-07T15:31:35.939654-04:00' when rendering template '

inner mesa
#

That’s not a float

#

I’d complain, too 🙂

amber hull
#

There is a lot more in the error message

#

I believe it is coming from my uptime sensor that has been working for several years.

#

set hours = (states('sensor.uptime') | float - states('sensor.uptime') | int) * 24 %}

inner mesa
#

Well somewhere you’re sending a date into |float

amber hull
#

I'm sure I am. I did not have enough knowledge when I first copied the sensor a long time ago. I am now starting to read about what is and isn't allowed in the code.

inner mesa
#

You’ve been saved by the quirk that if float doesn’t understand the input, it just passes the input straight through

#

Same with int

amber hull
#

I would have rather had it not working when I first entered it. That way I would have remember why?

inner mesa
#

You need to use | as_datetime instead

amber hull
#

Does it make sense that the error is what I typed above?

inner mesa
#

Yes

amber hull
#

So I am replacing the float?

inner mesa
#

Yes

amber hull
#

Is this in the Jinja docs?

inner mesa
#

You’ll probably need to play with the time section there, yes

amber hull
#

And you also say that int is wrong?

inner mesa
#

Same problem

#

Maybe you were hoping for a timestamp

amber hull
#

It was a template that I copied a long time ago that calculated the uptime of the system

inner mesa
#

Ok

amber hull
#

It takes from the system monitor sensor uptime and calculates the days, hours and minutes that the system is up.

inner mesa
#

Ok

#

You’ll need to experiment in devtools -> Templates

amber hull
#

I did, and I get ha_uptime:
friendly_name: HA Uptime
value_template: >

#

Not much help to me.

inner mesa
#

I guess you didn’t paste the whole template.

dense oak
# inner mesa <https://www.home-assistant.io/docs/scripts/>

I tried my best. I came up with this but nothing happens
- trigger: platform: state entity_id: input_number.ledstrip_brightness action: - choose: conditions: "{{input_number.ledstrip_brightness > input_number.ledstrip_brightness_old}}" sequence: script.led_light_on repeat: sequence: - script.bri_plus - input_number.ledstrip_brightness - 10.0 until: "{{input_number.ledstrip_brightness == input_number.ledstrip_brightness_old}}"

inner mesa
#

That’s not how you subtract a number from an input_number

amber hull
#

The only thing I didn't paste was platform: template
sensors:

inner mesa
#

Ok

amber hull
#

I now pasted the entire cmd sensors and it shows no errors and 3 days, 10 hrs and 41 mins

#

Which is correct.

#

Not sure why HA has a problem in the logs but not in the developers tools

silent barnBOT
dense oak
#

I removed the trigger, cause I can only share 15 lines max
I tried this, but no I have an error at the second sequence

#

action: - choose: conditions: "{{input_number.ledstrip_brightness > input_number.ledstrip_brightness_old}}" sequence: - service: input_number.set_value target: entity-id: input_number.ledstrip_brightness_counter data: value: "{{input_number.ledstrip_brightness}}" sequence: script.led_light_on #error on this line repeat: sequence: - script.bri_plus - value_template: "{{states('input_number.ledstrip_brightness_counter') | float -10.0}}" until: "{{input_number.ledstrip_brightness_counter == input_number.ledstrip_brightness_old}}"

outer socket
#

Ok, so - I don't quite know what I'm actually googling for - but I want to toggle a sensor/state. Where, if it's pressed it's because some one is in the room.

Like a light-switch, except it doesn't really control lights it just sets the state of the room to occupied. I was thinking a Binary_sensor which would be toggled by a switch-press.

My issue: My stairwell lighting is also used as room-lighting in the upstairs-room. So, motion-sensing on/off lights for the stairwell is all good, except for when someone is upstairs at which point it should stay on - and if everyone has left upstairs it should turn off when motion on the stairwell is off. Hence why I want to toggle the state of the room occupied/unoccupied - but what template/sensor/object/entity would I keep this information in?

inner mesa
#

Anyone can help, no need to tag me

dense oak
#

This doesn't work either.
- trigger: platform: state entity_id: input_number.ledstrip_brightness action: - choose: conditions: "{{input_number.ledstrip_brightness > input_number.ledstrip_brightness_old}}" sequence: script.led_light_on repeat: count: "{{(input_number.ledstrip_brightness_old|float - input_number.ledstrip_brightness|float) / 10.0}}" sequence: - script.bri_plus

#

sorry, was on accident

fossil venture
#

You are not accessing the entity states correctly, try this format for your conditions and count: ```
conditions: "{{ states('input_number.ledstrip_brightness')|int > states('input_number.ledstrip_brightness_old')|int }}"

count: "{{ ( ( states('input_number.ledstrip_brightness_old')|int - states('input_number.ledstrip_brightness')|int ) / 10.0 )|int }}"

haughty kite
#

hey guys, I have a small problem that I am not able to solve. I have a sensor that saves a float with a comma instead of a point. so lets say the value is "1,36". within a value_template I want to use that number and calculate with it. thats not possible cause the template sees that value as a list "[
1,
36
]" - any idea how I can convert that within my value_template into "1.36" float so that I can calculate with it?

fossil venture
#

|replace(',','.')

stable wagon
#

The template seems to be find but can you help me? Lovelace won't accept it:
`entities:

  • entity: sensor.ics_restmuell_deutsch
    icon: mdi:delete
    value_template: >
    {% if is_state_attr('sensor.ics_10', 'remaining', 0 ) %}
    HEUTE
    {% else %}
    {{states('sensor.ics_restmuell_deutsch')}}
    {% endif %}`
fossil venture
dense oak
#

most of this code works, but input_number.ledstrip_brightness_old doesn't get changed to the same values as input_number_brightness ledstrip_brightness: sequence: - service: script.led_light_on - repeat: count: "{{ (states('input_number.ledstrip_brightness') | float - states('input_number.ledstrip_brightness_old') | int) / 10}}" sequence: - service: script.bri_plus - service: input_number.set_value target: entity_id: input_number.ledstrip_brightness_old data: value: "{{ 'input_number.ledstrip_brightness' }}" can anyone help?

stable wagon
mighty ledge
dense oak
#

is the ' ' ? does it need to look like this? value: "{{input_number.ledstrip_brightness}}"?

marble jackal
#

hint: count: "{{ (states('input_number.ledstrip_brightness') | float - states('input_number.ledstrip_brightness_old') | int) / 10}}"

dense oak
#

yeah

#

I got it

#

thanks!😅

primal snow
#

Just updated and saw this message "Template warning: 'float' got invalid input 'unavailable' when rendering template". It appears that, I will have to review my templates before 2021.12. The question is what is the best practice for it? I mean if a float or timestamp variable of a template is "unavailable", how to best reflect to the template evaluation. Using is_number or using float(default='unavailable') or something else?

inner mesa
#

Give it a default

#

Or maybe you don’t need the filter at all if the template was working with unexpected input

primal snow
primal snow
inner mesa
#

My point is that some people may have filters that never do anything

#

That’s for you to decide. Your template

primal snow
#

let me be a little more clear
imagine a template like this
set a = states('sensor.x') | float
set b = states('sensor.y') | float
set total = a + b
{{total}}

inner mesa
#

And what do you want it to do?

primal snow
#

if you give default='unavailable'

#

one of them gets a default and the other gets a float which creates an error

inner mesa
#

Unavailable is not a useful default

primal snow
#

yeah exactly

inner mesa
#

0 is

#

54321 is

primal snow
#

what would be the best practice

inner mesa
#

What do you want it to do?

primal snow
inner mesa
#

It’s your data

primal snow
#

well if a variable is an unexpected value I want the template to render as unavailable or some error

inner mesa
#

There is no best

primal snow
#

I see

inner mesa
#

You could use ‘undefined’ and then catch that in the last line in either variable and return ‘undefined’

#

But if you’re expecting a number elsewhere, you need to deal with that too

inner mesa
#

You probably don’t want to return ‘undefined’ + ‘undefined’

primal snow
#

in that case I better use is_number and check all the variables before rendering the template

#

the question is how will 2021.12 behave? is it going to be mandatory to use | float(default) or we can still use | float but with consequences?

#

I am guessing that the template will fail to render then the state will be unavailable

#

with errors on the logs

silent barnBOT
primal snow
#

Just checking again but apparently, the state template rendered first then the availability template will be rendered later for template sensors. I should not get any errors since the availability template will override the state template. But I got this error anyway "Template warning: 'float' got invalid input 'unavailable' when rendering template". Is my logic wrong or this is a minor bug? See below simple sensors.

primal snow
grand brook
#

Ive got a bunch of sensor data on MQTT in a single message, and Im struggling to get that into HA since Im exceeding the size limit for the state topic. Does anyone have any examples of a set of sensors coming from a single MQTT topic where I can fake the state (so I dont hit the limit) yet still extract the data I need (which is a dictionary of arrays, keyed by a name)

mighty ledge
grand brook
#

Yes - the message is several KB

mighty ledge
#

ok, then pull 1 item for the state and put the rest into attributes, there are many examples of this

grand brook
#

could you point me to one please - how do I stop the state blowing up?

mighty ledge
#

but you need to know the shape of the json that's in the state topic in order to properly pull the info you want

grand brook
#

Im setting the JSON in the MQTT topic externally

grand brook
#

I read something earelier where states were being faked by setting it to "OK"

mighty ledge
#

pretty much every mqtt example has this in some way shape or form

#

they'll all be different based on the content of the state

#

that link shows you a small content set, and how to extract it

grand brook
#

even a single attribute is > 254 bytes

#

so I cant put that in the state topic

mighty ledge
#

ok

#

still doesn't change anything

#

it's all accessed the same way

#

attributes do not have a 254 limit either

#

only the state does

grand brook
#

but I only have 1 topic - and its got everything in it. The state_topic is a required field

mighty ledge
#

yes, that's fine

#

did you look at the example?

#

or are you not looking at the example and just making assumptions

grand brook
#

Yeh - Ive been on this page countless times in the last few hours 🙂

mighty ledge
#

the first example has 2 sensors all using the same topic

#

it actdually has 2 sensors each with an attribute, where all of them feed off the same topic

mighty ledge
grand brook
#

{"updateTime":"2021-10-08T20:43:47+00:00","temperature":[[1633705200000,18.3],[1633708800000,20.6],[1633712400000,21.7]],"other":[ array of 2 element arrays ] }

mighty ledge
#

ok, to get updateTime...

grand brook
#

this is graph data - x/y coords for weather info

mighty ledge
#
{{ value_json.updateTime }}
grand brook
#

and do I make that a separate attribute?

#

(or rather, should I)

mighty ledge
#

you can make it whatever you want

grand brook
#

so In my mind, this is 1 sensor, with 9 attributes. Is that the wrong way to think about this?

mighty ledge
#

no, it's whatever you want

#

typically, the standard MO for HA is 1 value to 1 sensor

#

some poeple like having 1 sensor with 9 attributes

grand brook
#

but what about when Ive got a series of values?

#

as is the case for each of the values here

#

does that not matter?

#

I get a light switch has a state, and it has a single value

mighty ledge
#

nope, but you'll have an easier time if they are a single sensor

#

single*

grand brook
#

so I should make separate sensors off the same topic?

mighty ledge
#

if that's what you want, yes

#

do you want easier automations?

grand brook
#

and how do I group all these sensors under a single device?

mighty ledge
#

then yes

#

you can't

#

MQTT doesn't have the concept of device

grand brook
#

ok, no matter on the device then. Ill just create a series of sensors that follow a consistent name

mighty ledge
#

yep

grand brook
#

so the template you pasted earlier - is that a json_attribute_template or a value_template?

mighty ledge
#

value_template will result in a state

#

json_attribute_template will result in attributes

grand brook
#

and if I dont specify a value_template, then my sensor has an undefined state, but has attributes (assuming I specify json_attribute_template )?

mighty ledge
#

yep

#

but value_template may be required

grand brook
#

and HA is ok with a sensor without a state?

mighty ledge
#

the docs will say if a field is required or not

grand brook
#

ok, let me take another crack at this. Thanks

mighty ledge
#

np

grand brook
#

so for the json stuff, I set the attributes_topic to the same value as the state topic?

mighty ledge
#

it's a dictionary, so you can just set it as "{{ value_json }}" and it will plop everything

#

if it's a list, you won't be able to do that

#

but, your's looks like a dictionary assuming you pasted it properly.

#

dictionary -> { }

#

list -> [ ]

#

use this post as a guide to figure out how to access your items

#

value_json is what your state topic returns

grand brook
#

Am I correct in my assumption that there is no quick way to reload MQTT sensors - I have to do a server restart?

mighty ledge
#

that is correct

grand brook
#

oh, saying that I just noticed a new reload button for "manually configured mqtt entities" appear

mighty ledge
#

ah, ok, I don't have any manually configured ones

#

so, use that

grand brook
#

Ok, I see my updateTime sensor now in the dev tools, but not my temperature one

mighty ledge
#

check your log for errors

#

make sure you don't have multiple sections that are identical

grand brook
#

Im back to the state length problem

mighty ledge
#

post your full json

grand brook
#

its huge

mighty ledge
#

use hastebin

silent barnBOT
mighty ledge
#

3rd link

grand brook
mighty ledge
#

ok first

#

do yourself a favor and format it

grand brook
#

so Ive got the updateTime sensor working, but if I dont specify a value_template for the next sensor (temperature) it overruns the state limit. Setting updateTIme as the value_template for that 2nd sensor just results in a duplicate of the first (just with a different name - I dont see the attribute in the dev window).
Ive got an IDE - it was formatted 🙂

mighty ledge
#

your result will look like this

#

much easier to read and figure out your path

grand brook
mighty ledge
#

ok, so if you want the first temperature

grand brook
#

I want the array of temps as temperature

mighty ledge
#

what does the array represent?

#

timestamps and a temperature?

grand brook
#

X/Y values for a graph - millis since epoch and then temp as C

mighty ledge
#

ok, yeah, you should't do that

#

just output the last temperature

grand brook
#

these are forecast values

#

not historical

mighty ledge
#

ok

#

do you want the timestamp?

#

like, what's the goal

grand brook
#

well, the forecast isnt much use without the timestamps - need to know the time of the forecast

#

Im graphing weather data from a variety of sources

mighty ledge
#

you won't be able to use home assistants graphs for this btw

grand brook
#

then hoping to feed it into the ApexCharts card

#

Ive got some reasonable graphs with that so far (granted, all historical)

mighty ledge
#

yeah, that won't be possible unless the apexcharts accepts a chunk of historical data at once

grand brook
#

Ill cross that bridge if I get to it 🙂 So can I set an array of values as an attribute?

mighty ledge
#

I would do that

#

yes

grand brook
#

so how do I extract the temperature array into a 2nd sensor?

mighty ledge
#

post what your configuration is right now

grand brook
#
  • platform: mqtt
    name: "Forecast Temperature"
    state_topic: "weather/forecast"
    value_template: "{{ value_json.updateTime }}"
    json_attributes_topic: "weather/forecast"
    json_attributes_template: "{{ value_json.temperature | tojson }}"`
#

If I omit the value_template, it blows up

mighty ledge
#
  - platform: mqtt
    name: "Forecast Temperature"
    state_topic: "weather/forecast"
    value_template: "{{ value_json.updateTime }}"
    json_attributes_topic: "weather/forecast"
    json_attributes_template: "{{ value }}"
grand brook
#

what is "value" doing there?

mighty ledge
#

just outputing the whole topic

#

so, you'll get 2 attributes, updateTime and temperature

grand brook
#

ok, so I have a state of the updateTime, and then all the attributes - can I filter for just temperature?

#

value.temperature ?

mighty ledge
#

you can access it via state_attr through a template, and i would assume the apex card would allow you to pull from attributes

grand brook
#

I can change the msg format

mighty ledge
#

if you want, but there's really no point, it would just remove the updateTime attribute

#

juice isn't worth the squeeze if you catch my drift

plain patio
#

Hello, how would I use the information from the Developer Tools from a device to create a button or card to trigger a certain response ?

mighty ledge
#

that doesn't really make sense

plain patio
#

Make sense in how ?

mighty ledge
#

What behavior are you expecting? Creating a template that dynamically makes frontend cards ?

plain patio
#

It's a Diffuser and has 2 options. Fan and colour. I would like to somehow be able to control fan/colour with a template ? At the the moment it's setup with Local Tuya.

mighty ledge
#

Sounds like you just need an automation

#

Input select -> changes and runs service to change fan

#

Input number -> changes color number

plain patio
#

'speed_list:

  • 'off'
  • low
  • medium
  • high
    preset_modes: []
    speed: low
    percentage: 33
    percentage_step: 33.333333333333336
    preset_mode: null
    friendly_name: Diffuser
    supported_features: 1`
#

'effect_list:

  • Night
  • Read
  • Meeting
  • Leasure
  • Scenario 1
  • Scenario 2
  • Scenario 3
  • Scenario 4
    supported_color_modes:
  • hs
    friendly_name: Diffuser LED
    supported_features: 21'
#

These are the 2 options for the device I can see changing in Dev Tools.

#

Is it possible to make a template to set device to low/high and set as a certain colour. Sorry for my noobness.

mighty ledge
#

Yep, you can create and input select and use that in the ui and use the result to use on each of those

#

You can create a template select that does the same as well

plain patio
#

A template select ? I don't see that in the Helpers menu.

mighty ledge
#

It’s a template entity

plain patio
#

Any chance you could point me to maybe an example I can play with? Oh, and thanks for helping. I wanted to be able to control the fan speed and colour. At the moment it's working; but unable to control the speed. I thought I could set the values to "x" into button somehow. I'll have a look at the link you sent. Wish me luck and thanks again.

mighty ledge
#

I don’t have a good example sorry

plain patio
#

Yeah me too; but still trying. It's funny though; I have a card which updates when I change speeds with the Tuya App instantly on my dashboard.

plain patio
#

Checked your link for template select; tried a few things but no go.

plain patio
#

Nope. Must be doing something wrong.

visual falcon
#

I've got a for loop and I'm trying to append a string in order to call the notify service once with a string of multiple entity id's.

I understand everything is immutable. I've tried set var = var + entity + ', ' to no avail. Is there a link to best practices?

inner mesa
#

the easiest solution is usually to create a list via namespace and use |join(', ')

#

but the "best practice" depends on how you're generating the list of entity_ids. There may be a better way to do it through a set of filters

dense oak
#

Hi guys, I pieced together this bit of code and even tested it in developer Tools. it all works, but then I get a Template rendered invalid error for the automation and script. How do I fix this?

    platform: state
    entity_id: input_number.ledstrip_brightness
  action:
    - service: >  
        {%- if states('input_number.ledstrip_brightness') > states('input_number.ledstrip_brightness_old') %}
          service: script.ledstrip_brightness_plus
        {%- elif states('input_number.ledstrip_brightness') < states('input_number.ledstrip_brightness_old') %}
          service: script.ledstrip_brightness_min
        {%- endif %}```
#

but I want it to trigger on the state and than if one value is bigger then the other excecute that script

#

no?

nocturne chasm
#

Yea, sorry, read your post too quick

dense oak
#

oh, okay

nocturne chasm
#

But you are doing the template wrong

#

You are asking if your entity has a state

#

What does it produce

#

In the template editor

dense oak
#

really? because I thought that code will trigger when the state of input_number.ledstrip_brightness changes

nocturne chasm
#

What does your template produce

dense oak
#
    - platform: template
      value_template:
          service: script.ledstrip_brightness_plus``` This
nocturne chasm
#

No, your template.

#

Your trigger was fine, that’s my bad

dense oak
#
    - platform: template
      value_template:
          service: script.ledstrip_brightness_min``` and this when the other value is higher
#

that's what I thought as well, but i'm still getting errors

nocturne chasm
#

What’s the error

silent barnBOT
#

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.

nocturne chasm
#

And add the whole automation to that also

dense oak
#

Logger: homeassistant.components.automation.automation_19
Source: helpers/script.py:1344
Integration: Automation (documentation, issues)
First occurred: 1:09:49 PM (1 occurrences)
Last logged: 1:09:49 PM

automation 19: Error executing script. Error for call_service at pos 1: Template rendered invalid service: service: script.ledstrip_brightness_plus

#

Logger: homeassistant.config
Source: config.py:464
First occurred: 1:16:39 PM (1 occurrences)
Last logged: 1:16:39 PM

Invalid config for [automation]: [entity_id] is an invalid option for [automation]. Check: automation->entity_id. (See /config/configuration.yaml, line 9).

#

these two errors

nocturne chasm
#

I need to check but I think your service is script.turn_on

#

And then the template defines which script

dense oak
#

isn't scrip.turn_on for every device?

nocturne chasm
#

Yes, that’s what I was checking.

#

I would try it though

#

You can call scripts directly

dense oak
#

that's not what i'm doing?

#

cause I want to do that

nocturne chasm
#

Yes, that is what you are doing, I was just confirming you can

dense oak
#

oh okay

nocturne chasm
#

Auh, think I found it

#
action:
  - service: >  
      {%- if states('input_number.ledstrip_brightness') > states('input_number.ledstrip_brightness_old') %}
        script.ledstrip_brightness_plus
      {%- elif states('input_number.ledstrip_brightness') < states('input_number.ledstrip_brightness_old') %}
        script.ledstrip_brightness_min
      {%- endif %}
#

Take the service: out

inner mesa
#

Also: |float

dense oak
#

that worked!!!

dense oak
nocturne chasm
#

But took waaaaaaay to long for me to see it

dense oak
#

well i'm glad you did, thanks a lot!

nocturne chasm
#

Morning ……. Coffee….🤣

dense oak
#

😂

dense oak
#

how would I perform two scripts under one if/elif?

fast mason
#

Is it meant to be
states('sensor.entity_id')|default(0)|float or
states('sensor.entity_id')|float|default(0)

dense oak
#

If I'm not mistaken the second one

marble jackal
#

Isn't | float(0.0) the default setting? So combining | float() with | default(0) seems redundant to me

pastel moon
#

When googling for ways to work around global variables in HA, helpers are often recommended. Though I use some of them, would it somehow be possible to configure any of them to return the outcome of a template? I have calculations I use throughout many scripts and automations, would be so great to have it at one place

native relic
#

Hope this is the right channel. I´m doing water monitoring by reading a reed contact from my water meter which works fine. Now i want to synchronize the value the physical water meter shows to home assistant. I´ts just to set an offset that increases by the reading values. I´ve seen something similar a few days ago maybe on an gas sensor integration but i can´t find it. Do you know how to do this?

inner mesa
cobalt iron
#

Hey all. Finally took the time to do a deep dive and learn how to do template syntax properly. But now I'm wondering what is now accepted best practice in terms of where one places individual custom sensors? I'm assuming it is not in configuration.yaml?

inner mesa
#

Everything starts with configuration.yaml. Whether you include files from there is up to you

cobalt iron
#

Thanks @inner mesa - any tips on where to get a good overview on switching to includes? My configuration.yaml is starting to get unwieldy and wondering if this might be time to take the plunge...

inner mesa
cobalt iron
#

That's the ticket. Many thanks @inner mesa

bronze horizon
#

So I wanted to split a string into an array and grab the last value. Easy; {{ value.split() | last() }}. My problem is the split() function isn't mentioned on either the Jinja or HomeAssistant-Template doco. I found it on the forums this time, but I was wondering what other functions I'm not aware of and whether these are documented anywhere?

inner mesa
#

Jinja uses Python objects, so you can use Python object methods

#

I think that’s mentioned in the Jinja docs

bronze horizon
#

Thanks! Tbh I had just been Ctrl+F-ing for the split function, I see the the section on Python methods... Although if I hadn't just been told by you, "You can also use any of the methods defined on a variable’s type." probably wouldn't have made the penny drop 😅

pastel moon
# inner mesa of course, you can set the value of a helper to a template

Well, indeed. But I intended to ask if I could do the reverse (by some hidden magic perhaps), so that the helper instead held the result of a template. I guess a helper could be defined with yaml, and thus perhaps this be possible to mimic with a time-pattern-trigged automation... On to some testing... 🙂

bright plaza
#

can I convert json_attributes from a rest sensor to integers easily? I have an attribute that is a count but suspect it's coming through as a string which is causing the coloured bars for each different number. I want to convert the attribute to an integer which hopefully will correctly show history as a line graph

pastel moon
bright plaza
#

I'll give that a go - wasn't sure if you could do transformations on json_attributes

#

this is what I have now:

#

json_attributes_path: 'data'
json_attributes:
- time
- lastSeen
- activeCount | int

#

but getting one of these for a history graph:

#

ah can't upload images here for some reason

#

bit it's basically the horizontal bar graph thing with different coloured segments for different numbers

#

it seems the | int hasn't fixed it. I've been throuugh the states table with a SQL plugin and deleted state entries which had Unknown and null for some reason

#

I suspepct I'll have to put a unit_of_measurement on it - that's how I usually fix it, but I don't know what one to use just for a count/number

#

fixed it with a customisation for that sensor with unit_of_measurement: 'Count'

#

(didn't know that count existed for unit_of_measurement until now)

steep gate
#

I have an entity which stores a monetary value that resets each day. How can I get the last value of this entity before it resets and add it to a cumulative value?

pastel moon
#

I have a script in which I define a variable by assigning the output of a number helper, but does not seem to be the correct way? Error below definition is from DevTools ```
variables:
lux_actual: "{{ input_number.lux_actual }}"

"Stopped because of unknown reason "null" at October 10, 2021, 13:59:23 (runtime: 0.00 seconds)"```

mighty ledge
#

You’ve been here enough to know about the states method

dusky flicker
#

I receive non-printable binary data(little-endian uint16) via MQTT and have no idea how to convert it to a number using templates. value doesn't seem to be an array. {{ value }} seems to pass through the raw data to the browser while {{ value | pprint }} seems to work like Pythons print on a binary string but without the b prefix. Any hints?

mighty ledge
#

value_json will get you an accessible object if the object is json. Otherwise you need to parse value if it's a string

dusky flicker
#

well it's neither json nor a string. it's binary data. I'm not sure how I can get the bytes by index so I can shift and or them into an integer. value[0] and value[1] don't seem to work

mighty ledge
#

value is always a string

#

value_json is always a json object if values string can be converted to json

dusky flicker
#

so how does the mqtt component convert the binary data into a string and how can I reinterpret it as bytes? because the mqtt protocol definitely supports binary data and that's what my publisher is sending.

mighty ledge
#

what does the topic say when you access it via a mqtt explorer or the like?

#

home assitant pulls every topic as a string

#

how about you post what "{{ value }}" returns as the state of your entity

dusky flicker
#

well mosquitto_sub -F '%x' just gives me the hex value (e.g. 0100). lovelaces mqtt listener just seems to put that data into the string printing unprintable characters: V

mighty ledge
#

what does the state show in the dev tools -> states page

dusky flicker
#

'C\x02'

#

looks like pythons binary string formatting

mighty ledge
#

no that doesn't

#

that would be 0xFF or in your case 0x02

#

What does the C represent?

#

if that's the first byte and \x02 is the second, then you should parse the string based on what it's expecting

dusky flicker
#

it does

>>> print(b'\x64\x02')
b'd\x02'
#

(sry used d instead of C)

#

a C would represent 0x43

#

to me it looks like I'd have to extract single characters and then convert them to numbers somehow

dreamy sinew
#

i don't believe there are any filters in jinja to convert this data. Would need to be dealt with elsewhere

mighty ledge
#

You'll have to regex it and separate them into groups that match a single letter or \x##. Then apply int('', 16) on each character found

#

oh and replace \x with 0x

#

for int with a base of 16 to work

#

you'd also need to be on v2021.10 at a minimum to do this because the regex method you need was added that version.

#

findall_match or match_findall, returns a list of found regex stuff

dusky flicker
#

the \x## isn't actually part of the string. it's just caused byte homeassistants)or lovelaces?) output formatting.
this template: {{ '0:' ~ (value[0] | pprint) ~ ', 1:' ~ (value[1] | pprint) }}
results in this output: 0:'7', 1:'\x02'

meaning the indexing does actually work. now I have to try to convert those non-printable characters to integers somehow.

mighty ledge
#

regex match....

dusky flicker
#

on the pprint output?

mighty ledge
#

on the value

#

inside your template

#

here, i'll do it for you

#
{% set bytes = value | replace('\\x','0x') %}
{% set byte1, byte2 = bytes | regex_findall(find='(0x[0-9a-f]{2}|[0-9a-f])', ignorecase=False) %}
{{ byte1 | int('', 16) }} {{ byte2 | int('', 16) }}
dusky flicker
#

again, the string does not conotain \x this is a mere representation of pprint. In jinja it seems to be legal for strings to contain non-printable characters.

Your suggestion would probably work on the pprint output though as ugly as that might be

mighty ledge
#

I asked you 3 times to show me what "{{ value }}" placed in your sensor

dusky flicker
#

And I did that

mighty ledge
#

you gave me an example

#

Then this will work off your example

#

because that's what I used

#

proof in the pudding

#

it would work with C as well, but you might have to adjust the ignore case

#

i'm not just blowing smoke up your ass, i know what i'm doing.

#

value is a string

#

it's always a string

#

you can test it out using your sensor that uses {{ value }} in the template tester area. Just replace value with states('sensor.your_entity')

dusky flicker
#
  1. thx for your help. I'm not accusing you of anything. I'm trusting you and you have no reason to be offended.
  2. I've tried your code and it doesn't work. the regex has no matches. It works for you because your test string is different. you have a literal \x in it.
  3. yes it is always a string. I've shown that to you, but the string does contain unprintable characters. there's no \x in it. the string is of lengths 2 and in your example [0] returns d and [1] returns the unprintable character 0x02.
  4. the developer tools UI printing the state seems to do the exact same conversion as jinjas pprint. that's why it shows the quotes and the \x##
mighty ledge
#

the regex function I wrote searches for the unprintable characters

#

Please, tell me what your sensor is

#

the entity_id

#

the one using "{{ value }}" as the value_template: field

dusky flicker
#

If I understand it correctly, your regex searches for the string 0x, not for unprintable characters. The string does not contain 0x because the previos replace didn't find anything. That's because it does not contain \x.
I'm not using a sensor you can buy. I'm relaying raw bluetooth GATT data to a MQTT broker.
You could reproduce it this way:
echo -ne '\x64\x02' | mosquitto_pub -d -h IP -p 1883 -q 2 -t 'my/topic' -s

mighty ledge
#

dude, can you please for the love of god just answer the question. I'm trying to help by eseeing what you're getting and you keep saying the same thing over and over

#

im about to walk away

#

make a sensor that uses value in the value_template

#

and tell me the name of the entity

#

and i'll have you paste something so i can look at the output

#

jesus

dusky flicker
#

I did that already but here you go:
the important part in my configuraton.yaml:

sensor:
- platform: mqtt
  unique_id: "F9:83:B8:7D:BC:A8"
  state_topic: "bluetooth/F9:83:B8:7D:BC:A8/001b/state"
  unit_of_measurement: "ppm"
  value_template: "{{ value }}"
  device_class: "carbon_dioxide"

and a screenshot of the lovelace developer UI:

mighty ledge
#

ok, and what is the entity_id

#

FYI, developer tools is not what you're talking about

#

is it sensor.f983b87dbda8?

dusky flicker
#

I can't upload screenshots, but the entity id is sensor.mqtt_sensor

mighty ledge
#

ok

#

please, put this in developer tools -> template

#
{% set value = states('sensor.mqtt_sensor') %}
{{ value }}
#

you can post screenshots through imgur

#

or just post the results by copying them

#

they will appear on the right, where the template is on the left

dusky flicker
#

first off, my sensor is changing the value every few seconds, that's why I'm currently giving you examples with differrent values all the time. if that is a problem for you I'll hardcode it. anyway, here's the screenshot:
https://i.imgur.com/ylkgDXn.png

mighty ledge
#

can you copy/paste the result here

dusky flicker
#

E

mighty ledge
#

ok, for that you'll need a python script to parse the information

#
v = [ord(c) for c in 'E']
#

ord will convert it

#

we don't have acces to decode the string in jinja

#

you may even be able to take the state of that and pass it through esphome

dusky flicker
#

does homeassistant support python templates or would I have to relay it?
I'm not using esphome but I wrote the relay so I could in theory just publish it as a hex string directly

mighty ledge
#

I would just publish the hex directly. using a python script in home assistant will not give you a sensor. It acts like a script that is executed

#

hex is easy to convert

#

and jinja can do it

#

jinja cannot convert unicode characters

dusky flicker
#

ok. It would've been great to find an homeassistant solution instead of making the protocol worse but realistically homeassistant is the only subscriber on my broker so I don't care and can accept this as a solution

mighty ledge
#

well your other options is to make a custom integration

#

if you don't want to make the protocol worse

dusky flicker
#

which would be overkill given what I'm trying to achieve and that apparently everyone except me publishes strings or even json via mqtt

mighty ledge
#

json is the standard accross the board

#

personally, the only time i've ever bothered using bytes is at work when dealing with lasers that return millions of datapoints per minute.

#

even then, it needs to be converted into a usable unit like mm or inches

#

so, you might be going overkill by keeping it bytes

dusky flicker
#

well being an embedded C and rust developer binary data is pretty much standard given that is has no usability disadvantages.(in C it's even easier than json). 😛

#

keeping it bytes allowed me to not have to allocate any memory after having received data from BLE and passing generating an mqtt publish. But ofc that's a quick change

#

and typed json doesn't work here anyway since the software that relays data has no information of what it means(bluetooth is untyped raw data)

dusky flicker
#

FTR: {{ (value[2:4] | int('', 16) * 256) + (value[0:2] | int('', 16)) }}
this works with my u16le formatted as a 4 byte hex string.

thx a lot for your help and sry about the miscommunication when you asked for the entity_id.

mighty ledge
#

np, fyi apparently there are a few filters that could be useful with the unicode that you're dealing with

#

base64_encode, base64_decode but i'm not sure they'll give you what you're looking for.

#

and ord is a filter too

#

@dusky flicker @dreamy sinew

#

These must be new filters

dreamy sinew
#

hm, makes sense to have them. Probably added HA side

mighty ledge
#

yes

#

i'm adding a new filter now and I noticed them in the files I'm dealing with

#

so......... you could have kept the binary data

#

🤦‍♂️ well, at least we all know now

dusky flicker
#

nice. I'll try that later. yea it's even in the template doc

mighty ledge
#

@dusky flicker if you wanted to revert all your changes, your template would be :

{% set b2, b1 = value | map('ord') | list %}
{{ b2 * 256 + b1 }}
#

assuming it always has 2 bytes

dusky flicker
#

I just tested it and it works great thx 🙂
you did the * 256 on the wrong byte though 😉

mighty ledge
#

depends on the order you use, i was treating the bytes as left to right

#

er, right to left

#

higher, being on the left

dusky flicker
#

yeah that would be big endian. I'm using littleendian

visual falcon
inner mesa
#

it's more complicated that most, but should show the namespace() concept

visual falcon
#

I'm getting a comma after every character of the entity

#

looks like I forgot to enclose 'thinger' with []

#

Is that some jinja syntax thing?

#

nevermind - gonna find a different way to do this

inner mesa
#

it's not a Jinja thing, it's the fact that list addition requires both items to be lists

#

a string becomes a list of characters for that purpose, which isn't what you want

visual falcon
#

Yea I caught that afterwards. I'm just gonna do this in pyscript and get around immutable lists

visual charm
#

How to fix this warning:
Template warning: 'strptime' got invalid input '2021-10-11T05:24:55.028002+00:00' when rendering template '{{ (states('sensor.time') > "23:30") or states('sensor.time') < as_timestamp(strptime(state_attr('sun.sun', 'next_dawn'), '%Y-%m-%d %H:%M:%S')) | timestamp_custom('%H:%M') }}' but no default was specified. Currently 'strptime' will return '2021-10-11T05:24:55.028002+00:00', however this template will fail to render in Home Assistant core 2021.12

The code is:
{{ (states('sensor.time') > "23:30")
or states('sensor.time') < as_timestamp(strptime(state_attr('sun.sun', 'next_dawn'), '%Y-%m-%d %H:%M:%S')) | timestamp_custom('%H:%M') }}

inner mesa
#

Check the format of the string in that attribute with what you provided. It’s telling you that it can’t parse it

#

You can see the actual string in the error message

#

You should use the as_datetime filter instead, since that’s what it’s for

visual charm
#

Thanks for your response. How would it look with 'as_datetime'?

inner mesa
#

state_attr('sun.sun', 'next_dawn')|as_datetime

#

it looks like you don't even need as_datetime - as_timestamp() can take the attribute directly

visual charm
#

Can't get it to work in the full formula. You mean like this:
{{ (states('sensor.time') > "23:30")
or states('sensor.time') < as_timestamp(state_attr('sun.sun', 'next_dawn')) }} ?

inner mesa
#

was it working before? it's correct that you can't compare a timestamp and string

#

oh, nevermind. you got rid of the timestamp_custom() too

#

put that back

#
{{ (states('sensor.time') > "23:30")
           or states('sensor.time') < as_timestamp(state_attr('sun.sun', 'next_dawn'))|timestamp_custom('%H:%M') }}
visual charm
#

fixed:
{{ (states('sensor.time') > "23:30")
or states('sensor.time') < as_timestamp(state_attr('sun.sun', 'next_dawn')) | timestamp_custom('%H:%M') }}

thanks for your help!

young forge
#

i'm getting this random error since updating to 2021.10.1

Template warning: 'timestamp_custom' got invalid input '00:00' when compiling template '{{ '00:00' | timestamp_custom('%H:%M') }}' but no default was specified. Currently 'timestamp_custom' will return '00:00', however this template will fail to render in Home Assistant core 2021.12
#

the thing is, i don't have that template anywhere (or at least i can't find it)

#

how do i figure out what is throwing this warning so i can fix it?

nocturne chasm
#

do a search for timestamp_custom but you do have it somewhere in your config

young forge
#

i absolutely do not

#

i already grepped my config

#

it's not there

nocturne chasm
#

you absolutely do

young forge
#

so it's somewhere else but i have no idea where

nocturne chasm
#

it is prob in an automation

young forge
#
hass:~/hass-latest$ grep 'timestamp_custom' config/configuration.yaml 
hass:~/hass-latest$ 
#

ok, that's what i was asking

#

i don't know where to look

#

to try to find it in an automation somewhere

#

aside from looking at every single automation

nocturne chasm
#

could be in any file in your config folder

young forge
#

was hoping there was an easy way to just grep everything

#

but even grepping the config folder isn't finding anything

nocturne chasm
#

i use notepad++ to edit my files and it is easy to use their search function on each files

young forge
#

alright i'll keep digging

#

well that was easy, found it. it's in keymaster.

nocturne chasm
#

the fix is in the breaking changes of the release notes

young forge
#

i had to figure out what directory to grep

nocturne chasm
#

glad i saw this as i thought only float was an issue

young forge
#

looks like they already have a PR to fix it...nice

nocturne chasm
#

did it say something about the template not working after 2021.12

young forge
#

yup

nocturne chasm
#

crap

#

😆

young forge
#
Currently 'timestamp_custom' will return '00:00', however this template will fail to render in Home Assistant core 2021.12
nocturne chasm
#

so, the template section here:

#

has all the ones that need to be fixed

young forge
#

that's the only one i had that was throwing the warning...i just got confused when i looked in my config and didn't see it anywhere

#

didn't even think to check package automations

nocturne chasm
#

I have a lot of (as_timestamp(now()) that I am going to have to figure out how to fix

inner mesa
#

the vast majority of the stuff in my config is not in configuration.yaml

#

nothing escapes something like this:

#

find /config -name "*.yaml" -print0 | xargs -0 grep -i thing_to_find

nocturne chasm
#

so, whats the best way to do (as_timestamp(now()))? (as_timestamp(now()))|default(00.00)

#

or even something like this?
{{ (as_timestamp(now()) - as_timestamp(states.binary_sensor.back_yard_motion.last_changed)) > 900 }}

#

{{ (as_timestamp(now())|default(00.00) - as_timestamp(states.binary_sensor.back_yard_motion.last_changed))|default(00.00) > 900 }}

inner mesa
#

When does now() not have a value?

#

you only need to worry about situations where a template function/filter may not get a valid value

nocturne chasm
#

auh, so the only time something like that happens is when my zwave network is wonky at which point nothing is working anyway

#

but I understood the breaking change to mean it would never render

inner mesa
#

The point of the change is that if you pass garbage into some functions/filters, they just pass the garbage right out. You need to provide a default or otherwise filter the garbage if it could happen. If it will never happen, don't worry about it

#

that's why the error says "this template will return this nonsense now, but will just fail later"

nocturne chasm
#

I mean, if it does happen, there is a bigger problem and adding some useless default wont help matters so I guess I am just going to leave things as is

inner mesa
#

The following template filters and functions will now log a warning instead of silently returning the input if the input is invalid and no default value is specified:

#

it's usually when passing a state into a filter, and that entity may be unavailable or have an unexpected state

nocturne chasm
#

sure, but typically these things are used on the fly so knowing a good default is next to impossible

inner mesa
#

you probably only care about the default if you're using it as an input to something else, in which case you need to handle it there, or if you're graphing some value over time, in which case you want a default that doesn't mess up the data (like use the last value or something)

silent barnBOT
nocturne chasm
#

I misread the breaking change. I thought it would break the template permanently, not just when it couldnt render the results

#

@regal pawn , I already told you how

regal pawn
#

@nocturne chasm let me go back to the drawing board a little more then. im getting confused on the person1=on and person2=on notify person1

nocturne chasm
regal pawn
#

i had that and it wasnt working let me try your code real quick

nocturne chasm
#

but you are better off defining notify groups in your configuration.yaml and using them

#

make:

#

notify.mobile_app_iphone_12_pro_max_5 and notify.person_10 and notify.person_11

#

a notify.kids

#

and use that

regal pawn
#

i may have to do that. this was the error i got when trying to do 2 lines of services:

Message malformed: Service {% if (is_state("input_boolean.kristin_notify", "off") -%} notify.mobile_app_iphone_12_pro_max notify.mobile_app_kristin_iphone12 {% else %} notify.null {% endif %} does not match format <domain>.<name> for dictionary value @ data['action'][0]['service']
nocturne chasm
#

try notify.mobile_app_iphone_12_pro_max, notify.mobile_app_kristin_iphone12 on one line

#

and notify.null is prob your error

regal pawn
#

same error:

 - service: |-
      {% if (is_state("input_boolean.kristin_notify", "off") -%}
        notify.mobile_app_iphone_12_pro_max, notify.mobile_app_kristin_iphone12
      {% else %}
        notify.mobile_app_iphone_12_pro_max
      {% endif %}
#

i'll just use groups

#

thanks

nocturne chasm
#

try - service: >-

regal pawn
#

same thing :/

inner mesa
#

you need to use notify groups

#

you can't do what you're trying to do

regal pawn
#

yeah i guess i'll just create two groups to cover the different booleans for the different people

#

does notify: require reboot or just a reload?

nocturne chasm
#

never reboot

#

just restart

inner mesa
nocturne chasm
#

and notify is a reload

#

you beat me to it

regal pawn
#

Thanks for helping me through my brain farts of the day!

nocturne chasm
#

its all good. Once you understand templates they are very powerful

#

and I truly only know the basics when it comes to templates

inner mesa
#

you can also try stuff like this in devtools -> Services without the template to make sure that the syntax would be correct when the template is evaluated:

#
service: notify.device_one, notify.device_two
data:
  message: foo
#

that fails

nocturne chasm
#

auh, good point, never thought of using services

regal pawn
#

awesome thanks

tender prawn
#

anyone know how I can fix this to use a default if the entity is unavailable?

{{ as_timestamp(states('sensor.kariong_uv_start_time_0')) | timestamp_custom(' %I:%M%p') | lower | replace(" 0", "") }}
pastel moon
mighty ledge
north locust
#

got a question about my alarm_clock template:
it displays who's alarm will go off first , displays hours/minutes left
it will display the text_time_left in negative values when alarm dismissed , any workaround or did i miss something ?
text_time_left

mighty ledge
#

you do it again in minutes_left

#

basically all references to sensor.next_alarm need to be replaced with the calculation that you use in value_template.

marble jackal
#

I have an error in a template which used to be working, so I have no clue why it isn't working now..
The error is: TypeError: 'NoneType' object is not iterable
Template code is here: https://www.codepile.net/pile/GpWnELlQ

#

Ah, I already found it.

              {% 
                set all_ha_groups_playing = all_speaker_groups_playing 
                                                | replace('media_player', 'group')
              %}

This looked like it was still creating a list, since it returned [ 'group.boven_groep' ], but it was not a list. Eg all_ha_groups_playing[0] returned [
So I first had to do a join before doing the replace, and then a split

unreal merlin
#

howdy fellers 🙂

#

I've got a bunch of template sensors that seem to share quite some code with one another. Joining them would be awesome, but leads to some head scratching. Is there a way to use precomputed objects across multiple template sensors?

#

simple example: for a in expand(states|selectattr whatever -> do some computation & formatting, and build 5 sensors out of the data object this provides

#

that possible at all?

#

real world example: need all the temperature sensors from my ground floor that are not unavailable, and get an average value for the floor. I display what sensors have been used for compute the data in an attribute. But obviously I've got to share the same filter for those two, just display different portion of that data.

manic onyx
#

hi everyone. Simple one - how do I match partial string?
This is what I have:

value_template: "{{ '1AFF4C00021555B561A9E94C40A9925F992F6940852400640001AC' in states.sensor.blegateway.attributes.values() }}"

I want to match this long string using just a portion of it - 555B561A9E94C40A9925F992F69408524

rugged laurel
#

then change 1AFF4C00021555B561A9E94C40A9925F992F6940852400640001ACto 555B561A9E94C40A9925F992F69408524

manic onyx
#

I tried - did not match

#

if I use the full string - works fine

inner mesa
#

Right, it’s going to look for that exact string in the attribute values

manic onyx
#

@inner mesa - how do I match just a partial one? The last few characters are changing

inner mesa
#

{{ states.alarm_control_panel.aarlo_base_station.attributes.values()|select('search', 'Data')|list }}

#

the select() part is the key

manic onyx
#

so instead of using "in", use select after?

inner mesa
#

follow my example

#

and test in devtools -> Templates

manic onyx
#

just trying to understand what "list" does

inner mesa
#

turns a generator into a list

#

if your goal is simply to return true or false if it's found, you want this:

#

value_template: "{{ states.sensor.blegateway.attributes.values()|select('search', '555B561A9E94C40A9925F992F69408524')|list|length > 0 }}"

manic onyx
#

@inner mesa - legend! 🙂

inner mesa
#

Now play with it in devtools -> Templates if you don’t fully understand how it works

thorny snow
#

hey, I have a simple python script run via command line template. The python script does give following output to the sensor FanState(Humidity=62.48, Temp=23.5, Light=7, RPM=2044, Mode='Light ventilation')

#

I

#

I have tried to find ways to get RPM shown as a value (as a sensor attribute), but it keeps on failing

#

any ideas? right now all these are shown as one single entity state

brisk temple
#

have your python script export in json is what I would start with

faint crest
#

HI!
Short question, i have the tankerkönig-integration. There i have 5 fuel station sensors with Name and Price. From this I have the min/max-template to get the minimal price. From that i have a sensor Template to have that minimal price in the Dashboards.

How do I get the Name of the sensor with minimal price?

dreamy sinew
#

.share your template

silent barnBOT
faint crest
#

Tried it to get it into the friendly name

thorny snow
brisk temple
#

@faint crest {{ state_attr('sensor.tankstellen', 'friendly_name') }}

faint crest
#

does this work also for min_entity_id? (From Dev-Tools)

count_sensors: 5
max_value: 1.579
max_entity_id: sensor.tankerkoenig_aral_tankstelle_diesel
mean: 1.57
median: 1.57
min_value: 1.559
min_entity_id: sensor.tankerkoenig_avia_tankstelle_diesel
last: 1.559
last_entity_id: sensor.tankerkoenig_shell_#####_diesel
unit_of_measurement: €
friendly_name: Tankstellen
icon: mdi:calculator
#

nvm

#

Found it by myself

#

Thanks! @brisk temple

brisk temple
#

sorry @thorny snow I don't know python to help you there

mighty ledge
tawdry arrow
#

I'm trying to set up a universal media player with a state_template, and the template works in the developer tools 100% of the time, but the entity state is not reflecting the template. I'd be really grateful for pointers. (Re-asking here because I think I asked in the wrong place a few moments ago.)

    attributes:
      state_template: >
          {% if is_state_attr('media_player.receiver', 'source', 'strm-box') -%}
            on
          {%- else -%}
            off
          {%- endif %}

Basically, HA thinks the media player is on regardless of the selected source.

brisk temple
#

this might have been fixed, but last i remember attributes only updated on state change

mighty ledge
brisk temple
#

👍

mighty ledge
tawdry arrow
mighty ledge
#

yeah, use the state field

faint crest
#

Hi! Second question: How can I set the Name of a template sensor to the name of a specific sensor (min_entity_id of a min_max sensor)?

mighty ledge
#

not a random attribute under the attributes

tawdry arrow
#

I was trying to follow the docs, but I couldn't find relevant examples to draw from, and it's a bit confusing. Thanks

mighty ledge
#

every example uses state though for the new style

#

not sure where you got the idea to use state_template, i don't even think thats mentioned in the docs

mighty ledge
#

that's for universal media player

tawdry arrow
#

that's what I'm using

mighty ledge
#

that doesn't support templates

tawdry arrow
#

wut

mighty ledge
#

well, i guess it does now. state_template must be new

#

anyways, that goes at the root level, not inside attributes

#

i.e:

media_player:
- platform: universal
  name: blah
  state_template: "{{ }}"
  attributes:
  ...
  commands:
  ...
tawdry arrow
#

good catch

#

thanks

mighty ledge
#

np

mighty ledge
faint crest
#

thanks!
Had some problems with it, but now it works fine!

tawdry arrow
#

@mighty ledge I'm all sorted out now, thanks again

#

I hate touching these media configs

#

"Let's add one input, how bad could it be?" ... 4 hours later:

 configuration.yaml | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++
 scripts.yaml       | 33 +++++++++++++++++++++++++++++++++
 2 files changed, 84 insertions(+)
dreamy sinew
#

lol

faint crest
#

Hi,
after reboot this doesn't work. I can't find the entity via the unique_id

  - platform: template
    sensors:
      tanken_min:
        unique_id: tankstelle_min_price
        value_template: "{{ state_attr('sensor.tankstellen', 'min_value') }}"
        friendly_name_template: "{{ state_attr(state_attr('sensor.tankstellen', 'min_entity_id') , 'brand') }}"```
#

when looking in dev -> template and entering state_attr(state_attr('sensor.tankstellen', 'min_entity_id') , 'brand') it works. also with {{ state_attr('sensor.tankstellen', 'min_value') }}

#

but the sensor template doen't seem to get loaded/work

atomic python
#

hey guys

#

any idea what this means?
```Template warning: 'float' got invalid input 'unavailable' when rendering template '{{ states('sensor.shellyem_5e26f6_channel_2_power')|float + states('sensor.shelly1pm_e09806aa06ba_power')|float }}' but no default was specified. Currently 'float' will return '0', however this template will fail to render in Home Assistant core 2021.12````

#

only started happening after updating

#

or should I say, what is the fix?

inner mesa
#

the Breaking Changes section of the release notes explain the change

atomic python
#

got it, must have missed when I skimmed over it earlier

#

I assume float(default=0) is the fix

#

instead of just float

dreamy sinew
#

that will continue with the existing behavior. Assuming that is what you want it to do

marble jackal
faint crest
#

ah, okay, but the whole entity is now in state: unknown and attributes {}

keen abyss
#

Hey, how would I figure out if my trigger data is a number or not? I have a template battery sensor based on a webhook and sometimes it gives weird non-number values so the sensor becomes unknown, I want to avoid that by testing if the variable is an int or not

#

I tried this in the template editor but it's telling me I'm misssing a colon {% if {{ my_test_json.temperature }}|int != 0 -%}

#

ah got it, it's {% if my_test_json.temperature is number -%}

weary drift
#

I have a sensor (CalDav integration) that shows the message of the calendar booking. The message looks like message: VAB: Name
I then split that message with a template
value_template: "{{ state_attr('calendar.barnen_vab', 'message').split(' ')[1] }}"
Works great. But not when the calendar is empty. I get a lot of errors in the log saying Template variable error: 'None' has no attribute 'split' when rendering .
Can i some how set the default value to blank or temp or whatever?

#

Just to clarify. When there's nothing in the calendar. The entry "message:" doesn't exist in the sensor.

#

So maybe just do the templating if the state of the sensor is on? Is that doable?

dreamy sinew
#

need to handle it being None

#
{{ message.split(' ')|first if message else 'some default result' }}```
weary drift
#

I tried looking at the templateing. Could i do like
"{{ state_attr('ccalendar.barnen_vab', 'message').split(' ')[1] if is_state('calendar.barnen_vab', 'on') }}"

#

Ooh, thanks! I'll try.

dreamy sinew
#

yours might work too

#

but this only needs one states check

weary drift
#

Ah yeah, that's better then.

dreamy sinew
#

if you think that is_state check would be more reliable you can definitely do it