#templates-archived

1 messages · Page 132 of 1

inner mesa
#

the point is that you want to do a comparison and it's important to know what the attribute looks like and its type to know what and how to compare it

#

right now, you have no comparison at all

mighty ledge
#

Are you going to share the value?

silent barnBOT
#
:8ball: 8Ball prdiction:

Question: Will Zyankali provide the mystery value?
Answer: No

ivory delta
#

Well, that's pretty definitive.

dreamy sinew
#

Lol

hybrid tide
#

Been working a loop using a chunk of code provided by Mono. However, I can't figure out how to deal with a default condition:

{% if trigger.event.context.user_id == '0c3242344a8ef4c5eb0668feaeecf2332' %}Locked by Google
{% else -%}
{% for person in states.person -%} 
  {% if trigger.event.context.user_id == person.attributes.user_id %} App Lock - {{ person.name }}
{%- endif -%} 
{%- endfor -%} 
{%- endif -%}
#

If the user_id isn't the first option, and it isn't in the person.attributes.user_id, I'd like to it be "unknown". But I feel like I've painted myself into a corner here...

#

Sorry...wrong attribution, Tinkerer provided the loop.

inner mesa
#

Seems like that could be done by a set of filters and assigned to a variable. Then you can make a decision on whether it found something

#

But I’d have to play with it and I need to eat. I’ll come back if someone hasn’t figured it out

dreamy sinew
#

(states.person|selectattr('attributes.user_id', 'eq', trigger.event.context.user_id)|first).name

hybrid tide
#

Yeah. That's the one that mono gave me last night, but if the user_id doesn't exist in the person list, it blows up because you get an empty result.

#

Trying to get it to check the person list, if it exist in there output the name. If not, check my hardcoded options. Finally if nothing can be found output "unknown"

inner mesa
#

So grab the result right after the selectattr, check it, then decide whether to move forward

inner mesa
#
{% set person = states.person|selectattr('attributes.user_id', 'eq', trigger.event.context.user_id)|list %}
{{ (person|first).name if person|length > 0 else "unknown" }}
hybrid tide
#

oh. piping to length will catch "empty" responses?

inner mesa
#

sorta - that's how to determine if the search found something

#

I don't think this is a great way to handle it, though. Why would you get an event with a user_id that doesn't correlate to a person?

hybrid tide
#

there's a user called "cloud_user" which isn't in the user table

inner mesa
#

If it's just null or 0 or user_id doesn't exist at all, then that's easier to check for explicitly

#

then you can just check for that

hybrid tide
#

not sure if there are others

inner mesa
#

anyway, I think what I have up there should help

hybrid tide
#

Thank you

mortal sundial
#

`## Some one home

  • platform: template
    sensors:
    someone_home:
    friendly_name: Someone Home
    device_class: presence
    value_template: >-
    {{ is_state('person.xxx', 'home')
    or is_state('person.gggg', 'home') }}`

Is it possible to have this sensor act by the domain person and not individuals?

inland stag
#

Hi everyone, why is my template energy sensor sometimes dropping to 0 when it is just a sum of three other sensors?

dreamy sinew
mortal sundial
#

thanks

inland stag
dreamy sinew
#

.share your template

silent barnBOT
#

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

inland stag
#
  - sensor:
      - name: "Total Energy"
        state: >
          {% set phase1 = states('sensor.energy_phase_1') | float / 1000.0 %}
          {% set phase2 = states('sensor.energy_phase_2') | float / 1000.0 %}
          {% set phase3 = states('sensor.energy_phase_3') | float / 1000.0 %}
          {{ (float(phase1) + float(phase2) + float(phase3)) | round(3) }}
        device_class: energy
        unit_of_measurement: "kWh"
        state_class: measurement
        attributes:
          last_reset: '1970-01-01T00:00:00+00:00'
dreamy sinew
#

if any of those are ever unavailable they'll eval to 0.0

mighty ledge
#

could just add an availability template to it

inland stag
#

ok, so I can leave state like it is and add availability_template to set it to unavailable when one of the phases is unavailable?

inland stag
#

thank you very much guys!

cold mica
#

@dreamy sinew @ivory delta Yesterday i tried and then went to sleep . Where can i find the value , iam a bit lost what i need to share is it this? supported_color_modes: hs color_mode: hs brightness: 255 hs_color: 0, 100 rgb_color: 255, 0, 0 xy_color: 0.701, 0.299 friendly_name: Canvas FA77 supported_features: 17

ivory delta
#

Use the template I asked you to use.

cold mica
#

which template you mean?

cold mica
#

other question, i got this work now how i want ```template:

  • sensor:

    • name: "canv"

      state: >
      "{% if state_attr('light.canvas_fa77', 'brightness') | int >= 220 %} bright
      {% elif state_attr('light.canvas_fa77', 'brightness') | int >= 200 %} bright2
      {% elif is_state('light.canvas_fa77', 'on') %} on
      {% else %} off
      {% endif %}"``` how can i use this entity in Picture Elements Card ? When i use the Sensor.canv it dont Work anymore with changing Pictures

ivory delta
patent sparrow
inner mesa
#

First, data_template: was deprecated over a year ago - use data:

ivory delta
#

Second, if you let the UI interfere, you can expect to see it formatting your code in odd ways

#

They appear functionally equivalent to me, so what's the problem?

inner mesa
#

I don’t think the spacing is particularly important there

ivory delta
#

Second one is 'better', just because the opening tags are all on their own line. The UI knows better in this case.

#

You shouldn't have to read halfway along a line to see where something new starts.

patent sparrow
ivory delta
#

Aha, I clicked the links in the wrong order 😂

#

If you're doing something advanced enough to need multiline templates, you're probably better off using a real editor.

patent sparrow
#

is there a way i can not have the UI "interfere" ? other than move the whole automation into raw yaml ?

ivory delta
#

Nope. You use the UI or don't. It's not customisable.

patent sparrow
#

ahhh okay

ivory delta
#

If you're comfortable with YAML and Jinja, I'd recommend switching to YAML mode and just SSHing in with something like VS Code.

#

You get a lot more control over how your config is organised too if you start splitting the files out.

edgy umbra
#

I want to change the color if both speakers are playing, works fine for one speaker but the template below seems not working Anyone know whats wrong on this? Thx

#
  ha-card {
    --primary-text-color:
    {% if is_state('media_player.sonos_keuken', 'playing') and (states('media_player.badkamer', 'playing') %}
     #EBEBEB
    {% endif %} ;```
ivory delta
#

states('media_player.badkamer', 'playing') isn't valid, and you have too many opening parentheses in your template.

edgy umbra
#

Got it fixed in the meanwhile, thanks anyway for the help mono. 😉

#

This is the working version.

#
  ha-card {
    --primary-text-color:
    {% if is_state('media_player.sonos_keuken', 'playing') and is_state('media_player.badkamer', 'playing') %}
     #FFA229
    {% endif %}
      ;```
proper holly
#

Coming over from automations. I need a template sensor that turns "on" when message attribute of calendar.district_calendar CONTAINS "No School" they put all sorts of other information like "No School - Teacher Workday" or No School - Teacher Training", but they all contain "No School" as a string. Help!

inner mesa
#

{{ "No School" in "No School for frogs" }}

#

or for your actual use case: {{ 'No School' in state_attr('calendar.district_calendar', 'message') }}

#

@proper holly

proper holly
#

Wow, so easy. Will put into testing! Thanks!

inner mesa
#

you can test in devtools -> Templates and change the attribute to whatever you want in devtools -> States

proper holly
#

Worked perfectly. Thanks for the help!

#

Thanks @inner mesa

#

One more question, they have a few that are "NO School" with a capital "O" in "NO". Can I make it non-case sensitive?

#

@inner mesa

inner mesa
#

you can use filters to force a case on both sides

#

something like {{ "No School"|lower in "No School for frogs"|lower }}

proper holly
#

Ah fantastic. Whole new world!

pliant dagger
#

Hello there template masters.

#

I"m trying to figure out why this is throwing an error

  sensors:
    living_room_window_sensor:
      value_template: {% if 'states.binary_sensor.living_room_window' %}
        {% if states.binary_sensor.living_room_window.state == "off" %}
          open
        {% else %}
          closed
        {% endif %}
        {% else %}
          n/a
        {% endif %}
      friendly_name: 'Living Room Window Sensor'```
#

I get the following error message when I lint it ```(<unknown>): found character that cannot start any token while scanning for the next token at line 4 column 24

#

I don't understand what the issue is. I've tried with quotes without

#

this was working

jagged obsidian
#

either put it in a single line under quotes or open a multiline with >

pliant dagger
#

I don't fully understand. Sorry my yaml skills are lacking but they're getting better

jagged obsidian
ivory delta
#

If you want to put a template on multiple lines, you must write value_template:> and not wrap your template in quotes.

pliant dagger
#

oh

#

ok thank you

wintry moon
#

is there anything like relative_time to count "age" of kids? I'd like to create 2 sensors for kids - older one getting value "x years, y months" and younger: "xx weeks"

#

or even "x weeks, y days"

mighty ledge
mighty ledge
#

and once you get to months, it becomes ballpark numbers.

#

years and weeks are easy to calculate. Months are not because calculations require a static number of days and as you know months alternate between 28, 30 and 31 days

marble jackal
# pliant dagger I"m trying to figure out why this is throwing an error ```- platform: template ...

I reformatted it a bit, your first if statement doesn't seem to be an if statement..

      value_template: >
        {% if 'states.binary_sensor.living_room_window' %} {# if what?! #}
          {% if states.binary_sensor.living_room_window.state == "off" %} {# better use if is_state('binary_sensor.living_room_window', 'off') #}
            open
          {% else %}
            closed
          {% endif %}
        {% else %}
          n/a
        {% endif %}
      friendly_name: 'Living Room Window Sensor'
dreamy sinew
#

should use is_state which would handle that entity existing properly

#
{{ map.get(states('binary_sensor.living_room_window'), 'n/a') }}```
#

@pliant dagger ^ simplified lookup

mighty ledge
dreamy sinew
#

probably

mighty ledge
#

I wish we could expunge these old templates when device_classes and translations didn't exist

dreamy sinew
#

lol

mighty ledge
#

even from my head 🤣

runic viper
#

hi everyone, Im trying to use the value of a script field on wait_for_trigger template and it errors saying that the variable is undefined, is that expected? this is the block (time_away is the field that I defined on the script :

- wait_for_trigger:
      - platform: template
        value_template: '{{is_state(motion_sensor_entity_id, ''off'')}}'
        for:
          minutes: '{{ time_away|int }}'
dreamy sinew
#

need to share the full thing

runic viper
dreamy sinew
#

seems fine. have you tried tracing the run with the new debugging tools?

runic viper
#

yeah, execution wise looks fine, but the logs say Error rendering 'My Script' for template: UndefinedError: 'time_away' is undefined is like the fields defined on the script are not passed downstream, like they're not available on the for: section

#

btw, I tried creating a variable as well, and it's the same...

#

by new debugging tools you mean the diagram of the execution, right?

mighty ledge
#

i.e. clicking 'run'

#

the examples do not auto populate the data, so you have to provide it yourself or give defaults to the variables

pliant dagger
#

thank you @mighty ledge so are you guys saying that we don't really need the value templates to convert on/off to open/closed anymore? Except in the case of my living room window where its backwards, which is the result of using an external sensor. Took me some time to figure out how to monitor a dual slide window but that did the trick

mighty ledge
pliant dagger
#

ah gotcha, thank you for educating me. A lot of this stuff was stuff I setup years ago

#

but I'll gladly go through and clean it up. Will require changes to my automations to monitor a different device and the state of said device from being open/closed to on/off

mighty ledge
#

yah they are like 3 years old now tho

pliant dagger
#

mainly my alarm code in appdaemon I'll just have to add an 'or' statement in there

mighty ledge
#

I made that change at some point, so it was only a matter of time

#

ya

#

I ditched appdeamon too

#

kicked that pile o mess to the door. You can do most things in native automations now

pliant dagger
#

Yeah me and yaml aren't the best of friends lol

mighty ledge
#

pyscript then

pliant dagger
#

probably

mighty ledge
#

appdaemon is so bloated now

pliant dagger
#

I'll have to look into that

#

I like the ability to reuse one script multiple times

#

which I'm sure there is a way to do that natively as well

mighty ledge
#

Most of my appdaemon apps were 100s of lines, on conversion most of them are shorter with yaml.

pliant dagger
#

thats always a bonus

#

I'll have to research that and see where I can convert things

mighty ledge
#

There were 2 that I didn't want to convert and I just made custom integrations

#

which were shorter than the appdeamon apps

#

and easier to understand

pliant dagger
#

I also use NodeRed for things but I keep that to a minimum

#

flows get so big and messy

mighty ledge
#

I never bothered with NR, I don't think like that

pliant dagger
#

I thought it would be something neat initially

#

and it was

#

but the flows can get complicated and it was easier just to write a few lines of python to do the same thing

mighty ledge
#

ya

#

the api for integrations now is super duper simple

#

and you can fake out configurations by passing a True back from the config validator if you want to bypass all the voluptous

pliant dagger
#

oh dang

#

ok so how does one set the device class?

#

aww can't paste pics in here

#

but I'm looking at a binary sensor for a door

mighty ledge
pliant dagger
#

Thanks @mighty ledge

sonic oracle
#
template:
  - sensor:
      - name: "energy_current_hour_watts"
        unit_of_measurement: "W"
        state: "{{ (states('sensor.energy_current_hour') * 1000) | float }}"

What did i do wrong?

inner mesa
#

You didn’t add |float

#

States are strings

#

Just move the one you have to after states()

sonic oracle
#

thanks that removed the errors although the sensor still doesn't show up in the dev tools

inner mesa
#

did you reload template entities or restart HA?

sonic oracle
#

both actually

inner mesa
#

not sure what to say

#

logs?

sonic oracle
#
Package templates setup failed. Component template cannot be merged. Expected a dict.
inner mesa
#

ok then

#

you can't do that from within a package

sonic oracle
#

is there a way around that?

inner mesa
#

put it in configuration.yaml

sonic oracle
#

thanks alot 👍 i don't really understand though how that made a difference 🤔 i mean if i do: template: !include template.yaml it works aswell

runic viper
inner mesa
eternal saddle
#

just starting out and I'm looking for advice on setting color_temp via left-right button on tradfri. I'd like to adjust the color_temp up or down similar to the automation brightness step. Wondering if I need to do this in a script, or a template in the automation?

mortal sundial
#

Hi Guys,

I would like to turn on a switch when my last active sensor changes state.
The sensor is changing every time it detects mouse movement on my computer.

I don't want the trigger to fire all the time when I use the mouse.

I tried to do a template trigger but it can't get it working.

Something in this direction:
{{ now() - states.sensor.last_active_sensor.last_updated > "5 minutes" }}

Is this even possible?

ivory delta
#

Is this for an automation?

#

If so, just set the run mode to single and put a 5 minute delay as the last action.

inner mesa
#

{{ now() > states.sensor.last_active_sensor.last_updated + timedelta(minutes=5) }} 🤷

lost wyvern
#

So can Jinja just support full python expressions? Or are these custom filters and tags specifically for HA

inner mesa
inner mesa
#

{{ "foo:bar:blah".split(':') }}, for instance

#

and Python data structures, like dicts, lists, datetime, etc.

mortal sundial
#

{{ (states('sensor.office_desk_peripherals_power')|float > 30.0) and ((as_timestamp(now()) - as_timestamp( states.sensor.last_active_sensor.last_changed))|float < 10) }}
`

Entering the above code into the developer template tools:

This template updates at the start of each minute. <<<<---- How would i reduce this interval?

warm ibex
#

Can somebody help me. I have some states for each user where it records the time and date of when the user unlocks the door. Everything behind this works. Including the states which change there time and dates when that user unlocks the door. I have this sensor (unlocked_by) which is what the conditional Lovelace cards use to determine who was the last to unlock the door. However, both David and Vicky work but if I add anymore such as spare card or another user it doesn’t work. Could somebody help me? I’m completely stuck

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

Sorry if I’ve posted this wrong. I’m a little new. Any help is appreciated.

I basically need the sensor to determine which state is the latest time and date and then update with the corresponding users name

ivory delta
#

🤦‍♂️

#

I did just say to use a code sharing tool, right?

#

Delete your post, do it properly.

warm ibex
fossil venture
#

@warm ibex See if this works. If it does you can add as may cards to the list and elif statements as you want https://paste.ubuntu.com/p/DHwN7shPBq/ if it does not work the input datetimes need to be converted to timestamps first. EDIT: I just tested it. It works.

warm ibex
fossil venture
#

The if statements should use the comparison operator == not =. Sorry.

#

Only the set statement should use =.

warm ibex
dull dune
#

Hey guys, I'm trying to add two additianal sensor for smarter status reporting of a poolcover. Can I simply just add the bottom two sensors to the template sensor here? There are comments in the paste that should explain what I'm trying to do/understand

inner mesa
mortal sundial
#

i'm using it with a template sensor

inner mesa
#

Great, then follow the docs to add a trigger

worn kraken
#

Can a template reference itself or does that result in a loop as the templates own value would change? For instance.. - sensor:
- name: "DTE Daily Energy"
state: >
{% set minuteKwhUse = states('sensor.dte_summation_minute') | float / 1000 / 60 %}
{{ (float(minuteKwhUse) + states('sensor.dte_daily_energy') | float) | round(3) }}
unit_of_measurement: kWh
device_class: energy
state_class: measurement

ivory delta
#

Why would you want to do that? 🤔

#

Just use two sensors.

worn kraken
#

In that case, wouldn't you need two sensors and an automation?

ivory delta
#

No...? Make a template sensor that exposes the value you want for minuteKwhUse, then create another template sensor that uses the result and performs the next step.

#

No circular references 🎉

copper quail
#

Does anyone know of a way to force decimal places?

When using round(2) – if I have a float with a value of 13.4004, it'll round to 13.4 instead of 13.40

dreamy sinew
#

but if the value is 13.405 it would round to 13.41

ivory delta
#

'{0:.2f}'.format(your_number_here)

#

You'll still want to round first so you're not just truncating the extra digits.

dreamy sinew
#

though the template tester will still chop it for reasons

ivory delta
#

It doesn't here...

dreamy sinew
ivory delta
#

Ah, my example with pi isn't useful 😄

#

Will it return correctly in a template sensor?

dreamy sinew
#

but $%0.2f works

ivory delta
#

This is returning 1.20 for me:
{{ '{0:.2f}'.format(1.20000) }}

dreamy sinew
#

force it into a string

ivory delta
#

Is it that thing where the Dev Tools works differently if you only have a single template in there?

dreamy sinew
#

probably

ivory delta
#

Yup

dreamy sinew
#

its getting natively converted to a number

ivory delta
#

Just got rid of the rest, can confirm.

dreamy sinew
#

so ymmv

#

probably a device class thing

copper quail
#

gotcha. It's NBD.

worn kraken
#

templates

dreamy sinew
#

cold starting a thread is a good way to be ignored

worn kraken
ivory delta
#

Please stop tagging me.

silent barnBOT
#

When using Discord's new Reply feature it defaults to pinging the person you reply to, which can get frustrating for the target. Click @ ON to @ OFF to stop this - on the right side of the compose bar.

worn kraken
#

For my template, I am still getting a circular reference when split. it looks like it still complains of circular references

  • name: "DTE Daily Energy"
    state: >
    {{ ( states('sensor.dte_minute_energy') | float + states('sensor.dte_daily_energy') | float ) | round(3) }}
    unit_of_measurement: kWh
    device_class: energy
    state_class: measurement
dreamy sinew
#

you are still referencing the sensor within itself

ivory delta
#

Are you just trying to keep a running total?

worn kraken
#

agreed, doesn't seem like templates can update themselves. I am trying to run a total in a template

ivory delta
#

And if this is for use with the new energy dashboard, #energy-archived can help more.

worn kraken
#

ok. I will try there. I need to convert from minute based kwh usage to hourly in order to use utility_meter

#

for totals in general, it doesn't appear that templates are appropriate

ivory delta
#

Templates are a calculation of known values, not a tracker of any form of history.

#

And I think you misunderstand power/energy. If you have something that can report power, the rest is easy... but still #energy-archived

silent barnBOT
ivory delta
#

🤦‍♂️

silent barnBOT
#

@grave cargo Rule #6: Spam will not be tolerated, including but not limited to: self-promotion, flooding, text walls (longer than 15 lines) and unapproved bots.

Please take the time now to review all of the rules and references in #rules.

For sharing code or logs use https://paste.ubuntu.com/.

ivory delta
#

44 lines of text across two posts. Nice.

#

Energy questions go in #energy-archived. Share a short description of your issue there and include the rest in a paste from a tool like the one in the bot message.

thorny snow
#

Thanks and sorry for trying to explain my issue with to much text 🤣

stone marsh
#

Is it possible to use customize_glob to add a friendly name that truncates the suffix? All of my energy sensors end in "_energy" and I would like to strip energy off and make the friendly name the rest of the entity id

ivory delta
#

You're describing a RegEx replacement.

#

Not quite the same as a glob but similar idea.

stone marsh
#

Can that be done through customize_glob so I can bulk hit all of my entities?

ivory delta
#

Nope.

stone marsh
#

Could the template update the friendly name?

ivory delta
#

Nope.

stone marsh
#

ahh dang

#

guess I'll just have to manually update each of them

ivory delta
#

Templates just are. They're calculators. They don't impact other things.

hot swift
#

Hello, is it possible to somehow get the last_changed or last_updated attribute on a template sensor? I have a template sensor that just tracks the position of a cover. I would like to make a sensor to track if it's moving or not, and i thought sensors had last_changed attribute?

dreamy sinew
#

they do

#

just checked against one of mine

#

states.domain.entity.last_updated

hot swift
#

Okay, it's just under developer tools and attributes there is not anything like that. Is it because it's a hidden attribute and can just be used in automations?

ivory delta
#

In templates, but yes.

#

It's not an attribute in the sense of entities having attributes. It's just a property of that state object.

hot swift
#

Yeah in templates. Okay I will try playing around some more with it.

#

I just don't really get any results when I try it out in template. This is the templates. And the output is blank for the first two, and None for the last.

#
{{ states["sensor.cover_position_livingroom_1"].attributes.last_updated }}
{{ states["sensor.cover_position_livingroom_1"].attributes.last_changed }}
{{ state_attr('sensor.cover_position_livingroom_1', 'last_updated') }}
{{ state_attr('sensor.cover_position_livingroom_1', 'last_changed') }}
waxen rune
#

@hot swift I checked a couple of mine. They seem to behave a bit differently.
Normal sensor:
{{ state_attr('sensor.tellstick_id_22_temperature', 'lastUpdated') | timestamp_local }} = 2021-08-13 23:49:50
{{ states.sensor.tellstick_id_22_temperature.last_updated | timestamp_local }}= 2021-08-13 21:50:38.842806+00:00
Template sensor:
{{ state_attr('binary_sensor.balkongdorr_sovrum_tmpl', 'lastUpdated') | timestamp_local }} = None
{{ states.binary_sensor.balkongdorr_sovrum_tmpl.last_updated | timestamp_local }}= 2021-08-11 09:36:08.678170+00:00

Also note "lastUpdated" vs ".last_updated".

Based on this, does {{ states.sensor.cover_position_livingroom_1.last_updated | timestamp_local }} give you anything useful?

ivory delta
#

Based on this, does {{ states.sensor.cover_position_livingroom_1.last_updated | timestamp_local }} give you anything useful?
this

#

Which is... what phnx said 🤯

waxen rune
#

Yes. But for some, me included, it is easier to see an actual example. Anyway, i hope AnthonMS got what they needed.

placid pilot
#

I'm having conceptual difficulties. I am looking at KASA HS110 power adapters, and I'm trying to figure out where in the HA UI I can see the attributes of the device (so I can create templates etc.) I have seen example templates with entries such as: washing_machine_pump_volts: friendly_name_template: "{{ state_attr('switch.washing_machine_pump','friendly_name') }} Voltage" value_template: "{{ state_attr('switch.washing_machine_pump','voltage') | float }}" unit_of_measurement: "V"

#

But I don't see where I can find the relevant information ie: voltage? How do I 'list' the attributes of a device, so I can create the relevant sensors for my setup?

fossil venture
#

Developer Tools devtools / States

placid pilot
#

Hmm, in my case, that doesn't give me any more information. If I look at the switch.washing_machine_pump entity. I don't see any attributes other than friendly_name.

ivory delta
#

The attributes available depend on the integration you use.

wet vault
placid pilot
#

@wet vault 👍 thank you

dire shadow
#

i have a command_line sensor that outputs a huge float in celsius. using the example template from the docs seems to throw off the conversion to fahrenheit. without the template the conversion is correct. is there something else i need to do to trim the sensor output? e.g from 119.72000133989536 °F to 119.7 °F

- platform: command_line
  name: Core Switch Temperature
  command: "ssh -o StrictHostKeyChecking=no -o GlobalKnownHostsFile=/dev/null -o UserKnownHostsFile=/dev/null homeassistant@10.0.2.2 -i /ssh/id_ed25519 \"show system environment temperature | json\" | jq '.tempSensors[] | select(.name==\"TempSensor1\").currentTemperature'"
  unit_of_measurement: "°C"
  # value_template: "{{ value | multiply(0.001) | round(1) }}"
inner mesa
#

I'm not following. You have value_template there that should effect the rounding, but you've commented it out. What exactly is the problem?

dire shadow
#

yes, when it's uncommented it rounds but the conversion to fahrenheit is incorrect, 32.0 °F

hot swift
# waxen rune <@223052069525913601> I checked a couple of mine. They seem to behave a bit diff...

Thank you for this reply, it helped a lot! I have briefly tested it out with these two templates:

{{ state_attr('sensor.cover_position_livingroom_1', 'lastUpdated') | timestamp_local }}
{{ states.sensor.cover_position_livingroom_1.last_updated | timestamp_local }}

The first returns None, but the second returns "2021-08-14 18:07:54.015289+00:00", so now I think I can make my binary_sensor that checks if it's currently changing/moving.

Thanks again

dire shadow
mighty ledge
#

So you can just remove the | timestamp_local

nocturne nexus
#

I've been working on this for weeks and feel so close, yet so far away... Hoping someone here can help me. All I want to do is take my automation that I'll post, but make it trigger off of ANY moisture sensor in my HA setup without having to list each one out. I THINK I need to do this with a template, but I can't figure out how to format it. Am I on the right track?

inner mesa
#

You could certainly do it with a template, but that might work

#

Did the UI build that?

#

I suspect that platform: device is wrong

nocturne nexus
#

Most of it. Whoops. I was playing with the trigger. Here it is how it works.

inner mesa
#

You want entities with device_type: moisture

nocturne nexus
#

Rob, you gave me a sample code a few weeks back, but when I use it, it take like a minute before it actually triggers.

#

{{ states|selectattr("attributes.device_class", "==", "moisture")|selectattr("state", "==", "on")|list|length > 0}}

inner mesa
#

Yeah, that

#

I don’t think that’s a problem with the trigger

nocturne nexus
#

Do you see any reason why it would take so long to trigger when using this vs. watching the state change on a single sensor?

inner mesa
#

No

nocturne nexus
#

Hmm. I've rebooted my RaspPi since trying that last. Let me put that template as the trigger again and try now.

inner mesa
#

Test it in dev tools

nocturne nexus
#

I did, and it still took a long time to change to true.

inner mesa
#

Try states.binary_sensor instead of states

nocturne nexus
#

Just that by itself of inserted into that original template somewhere?

inner mesa
#

Replace one with the other

nocturne nexus
#

{{ states.binary_sensor|selectattr("attributes.device_class", "==", "moisture")|selectattr("state", "==", "on")|list|length > 0}}

#

Like that?

#

Sorry for my ignorance...

inner mesa
#

Yes

nocturne nexus
#

Oh, wow. That triggers in like 2 seconds now instead of 30+

inner mesa
#

Are you on a pizero?

nocturne nexus
#

No. Pi4

#

Oh, I am so thrilled!!!

inner mesa
#

Weird

nocturne nexus
#

When using the first template, it was also listing a motion sensor in my alerts in the actions section. When I just changed it to this new one, it accurately uses the name of the triggering water sensor!

inner mesa
#

Hmmm

#

That doesn’t make sense

nocturne nexus
#

Is there some way I can buy you a beer?

inner mesa
#

No, just happy it’s working

nocturne nexus
#

Well thanks sir. Now I can move on to the next thing. That was the biggest thing bugging me that I couldn't recreate since moving away from SmartThings.

inner mesa
#

All I did was further restrict the entities under consideration to binary_sensor

nocturne nexus
#

So made it only look at binary sensors vs every sensor out there?

inner mesa
#

Vs every entity

nocturne nexus
#

Got it.

#

Well thank you again! Can't say how much I appreciate it!

inner mesa
#

Np

low blaze
#

I’m trying to write a template that has 2 If statements and an else but I’m not getting it correct

#

If a, then x ; if not a, but b, then y, Else z

#

I keep getting a return of z on the second and third evaluation

#

So I can get x, but never y when I should

#

I did it this way ; if a then x else if b then y else z

#

And then endif twice. I’m thinking my issue is placement of the endif and else

inner mesa
#

can you show the actual code?

#

it sounds like you just want elif for the middle one

low blaze
#

Yea gimme a sec will retype, it’s just going into iOS as a watch complication

#

(So I didn’t save a draft)

#

Else if or us elif something else?

inner mesa
#

?

#

elif

low blaze
#

‘’’{% if states("sensor.held_lvpd") == "True" %}
VPD
{%else%}
{% if states("sensor.herbybig4_true") == "True" %}
HLD
{%else%}
!!!
{%endif%}
{%endif%}’’’

#

Sorry on iOS. Not sure if there is a back tick

inner mesa
#

there is

low blaze
#

‘ is apostrophe I assume.

inner mesa
#

hold it down

#

anyway, it's a pain in the ass

low blaze
#

Aaah

#

Still helpful for pasting code

inner mesa
#

so like I said, elif

low blaze
#

that it?

#

Yup

inner mesa
#
{% if states("sensor.held_lvpd") == "True" %}
VPD
{% elif states("sensor.herbybig4_true") == "True" %}
HLD
{%else%}
!!!
{%endif%}
low blaze
#

Just looked up elif makes sense never seen that syntax thanks

#

Thank you kindly Rob

#

Hmm doesn’t seem to work

#

Maybe I have a typo somewhere let me double check

inner mesa
#

it's better written like this, assuming that the sensors and values are correct:

#
{% if is_state("sensor.held_lvpd", "True") %}
VPD
{% elif is_state("sensor.herbybig4_true", "True") %}
HLD
{% else %}
!!!
{% endif %}
floral shuttle
#

can we template the used unique_id's of our entities somehow? Ive just found an identical unique_id used in my template: sensor and binary_sensor doesn't hurt, but Id like to prevent that nonetheless. Having an easy check for unique_id's would be nice for that

mighty ledge
floral shuttle
ivory delta
#

Generate a UUID, use that. The chances of generating the same UUID twice are... beyond astronomical.

#

You'll start seeing collisions in about 2^50 ie. about 10^15 keys. Your chances of seeing a collision if you've populated your database with just 1000 billion keys are still negligible.

floral shuttle
ivory delta
#

Or if you have a Linux machine, literally type uuidgen on the command line.

floral shuttle
#

ok, will do that next time I need a manual uuid... (although I like the UID to be related to the entity...) still, Id like to know if/how one can list all used unique_id's. We should be able to do so, as they are attributes of the entities?

ivory delta
#

They're not attributes, they're just ID's in the registries. You know where to raise feature requests if you want them surfaced.

open coral
#

hello everyone. I am trying to get my HA to read XML data from my pool manager.

I have the following in my configuration.yaml:
https://pastebin.ubuntu.com/p/2WTC4TkdtD/

if I put the address in my browser I get:
<pm5>
<item type="34" id="4033" label="T1" unit="°C" value="27.5"/>
</pm5>

My goal is to "extract". the value (27.5) so that HA can interact with it... but I am struggling with how to get HA to read just the " value" component.

I saw someone on the forms use grep after the address (https://community.home-assistant.io/t/use-xml-result-from-rest-api/6195/9?u=aziwa), but im not sure if thats the right path, if it is i would need help to right the grep.

any help really appreciated 🙂

fossil venture
open coral
#

thanks @fossil venture , i get the following error with that:

unknown escape sequence at line 39, column 62:
... |regex_findall_index('value="(\d*.?\d*)') }}""
^

fossil venture
#

Try it like this ```
value_template: >
{{ value|regex_findall_index("value="(\d+.?\d*)") }}

open coral
#

saves ok, and I am able to reproduce what you did in the template developer tools, this is the logs:

#

line 39 is the value_template

fossil venture
open coral
#

you good sir @fossil venture are a genious!! its working perfectly!!!

#

2 days iv been trying, thanks so much for your help!!!

open coral
#

hi again @fossil venture , I saw your post on the forum, looks great,

im getting "unknown" however with that code you posted. any ideas? (i assume the ' after value should have been " ?)

#

ue_template: '{{ value["pm5"]["item"]["value**"**] }}'

fossil venture
#

Try it without the pm5 value_template: '{{ value["item"]["value"] }}'

#

And yes that single quote should have been a double.

open coral
#

nope, still unknown

#

nothing in the logs

#

or if i did it correctly

#

but it says " UndefinedError: 'value' is undefined

inner mesa
#

you can't do that

#

it's intended to parse the result of that REST call

open coral
#

ok?

#

do you mean I cannot just add it in the "templates" in dev tools? or the parsing? sorry im easily confused 🙂

inner mesa
#

I mean pasting that in devtools -> Templates isn't useful because it's not actually going to make that REST request

open coral
#

oh i see

#

ok thanks

inner mesa
#

the template must be evaluated in the context of that REST sensor

open coral
#

ok

fossil venture
#

Yeah you actually have to create the sensor and restart.

inner mesa
#

you could use curl or similar from the command line, capture the output, and seed a variable with that to test the template, if you want

fossil venture
#

thats where we started. Restful avoids nasty xml searches with regex as it converts xml to json.

#

Oh sorry, you mean to test. Yeah it works.

open coral
fossil venture
#

Nope. The template editor is not going to do xml -> json. Only the rest sensor will do that. You have to actually create the sensor.

open coral
#

ok let me try

#

so basically I would create it with this?

  - resource: http://10.1.1.42/cgi-bin/webgui.fcgi?xmlitem=34.4033
    scan_interval: 60
    sensor:
      - name: "PoolTempRest"```
fossil venture
open coral
#

oh sorry, i thought i was just creating the rest sensor in order to test the value_template line

#

when i add the value_template: '{{ value["pm5"]["item"]["value"] }}' with or without the ["pm5"] it doenst work

#

i get "unknown" in the state of the sensor after a reboot

hard pond
#

I'm in need of some guidance... I am trying to create a binary sensor for my OpenSprinkler set up that will tell HA if any of the zones are running. I have 6 entities that i have to account for and the docs just look confusing to me. any help would be appreciated...

fossil venture
open coral
#

will do. thanks for the help today!

fossil venture
#

Oh crap. I see why, we should be using value_template: '{{ value_json["pm5"]["item"]["value"] }}' try it if you can be bothered.

open coral
#

trying 🙂

#

nope, still unknown with:

rest:
  - resource: http://10.1.1.42/cgi-bin/webgui.fcgi?xmlitem=34.4033
    scan_interval: 60
    sensor:
      - name: "PoolTemprest"
        value_template: '{{ value_json["pm5"]["item"]["value"] }}'
fossil venture
#

What do you get if you just use: value_template: '{{ value_json }}'?

#

You might have to look in developer tools / states to see the whole value.

open coral
#

trying that now.

in the meantime, if it helps, i used a xml -> json converter online for the xml that the poolmanager outputs and get this:

{
"item": {
"@type": "34",
"@id": "4033",
"@label": "T1",
"@unit": "°C",
"@value": "28.0"
}
}

fossil venture
#

Yeah I did a few too. I remember that silly one that prefixes attributes with @

open coral
#

arg now having other issues, cant find the sensor. got to go anyway but will try and pick this up later, thanks again for your help!!

silent barnBOT
hard pond
#

Nevermind, I just ended up adding 6 triggers to the automation...

slim cliff
#

Looking for a little help with a template here
I use an integration (twente mileu) which retruns 3 seperate sensors, all three sensors return a date (next garbage pickup date for that specific garbage type)
For a dashboard I would need a template / sensor which returns only the first upcoming date and garbage type of the three sensors
I was thinking a value template to check which date comes first and use the value of this sensor as the value for the template output, and a friendly_name_template which takes the name of the date that comes first, but to be honest I hardly know where to start

Anyone with a similar example or something to move forward?

inner mesa
#

Share an example of the state of one of the sensors

slim cliff
#

2021-08-20

dreamy sinew
#

{{ [states('sensor.sensor1'), states('sensor.sensor2')]|min }}

slim cliff
#

Ahhh

dreamy sinew
#

Oh that would just get the date

inner mesa
#

I would create a dict of the state and name

#

Then do that for the dict and index for the name

slim cliff
#

I have no idea how the dictionairy and index work :P
But, the idea from phnx works great, and I suspect I can figure the rest out from there =D

inner mesa
#

for fun:

#
{% set date1=states.input_text.test %}
{% set date2=states.input_text.test2 %}
{% set mapping={date1.state:date1.name, date2.state:date2.name} %}
{{ mapping[[date1.state, date2.state]|min] }}
slim cliff
#

Interesting, thanks, I'll try that!

#
      afval_next_up:
        value_template: >
          {{ [states('sensor.non_recyclable_waste_pickup'), states('sensor.organic_waste_pickup'),states('sensor.plastic_waste_pickup')]|min }}
        friendly_name_template: >
          {% set pickup = states('sensor.afval_next_up') %}
          {% if pickup == states('sensor.non_recyclable_waste_pickup') %}
            Rest
          {% elif pickup == states('sensor.organic_waste_pickup') %}
            GFT
          {% elif pickup == states('sensor.plastic_waste_pickup') %}
            Verpakkingen
          {% endif %}

It's not elegant, but it works :P

inner mesa
#

I don't recommend a self-referential template

#

but that's essentially what I had in my example, but with a bunch of if/elif instead of a dict

#

it's a shame that template sensors don't have a common variables section

slim cliff
#

Would help a bunch

#

Thanks for your help! I'm happy with my sensor! now to make a nice button card for it :)

dreamy sinew
#

Oh, min() accepts an attribute parameter

#
{{ '{}: {}'.format(sensor.name, sensor.state) }}```
#

@slim cliff

#

And @inner mesa too I guess

somber radish
#

My entity state stays in 'unavailable' anyone can point me to what i am doing wrong ? ```template:

  • binary_sensor:
    • name: "shellymotion01 Brightness"
      unique_id: shellymotion01_brightness
      state: >
      {% if is_state('sensor.shellymotion01_luminosity')|int > 1700 %}
      bright
      {% else %}
      dark
      {% endif %}
      icon: >
      {% if is_state('sensor.shellymotion01_luminosity')|int > 1700 %}
      mdi:brightness-5
      {% else %}
      mdi:brightness-4
      {% endif %}```
#

sensor.shellymotion01_luminosity has a value of 1989 according to developer tools

ivory delta
#

Your templates are invalid. Try them in Dev Tools > Templates.

somber radish
ivory delta
#

The config check in the UI is very basic and won't know if your templates work. It only looks for YAML syntax.

#

To check properly:

silent barnBOT
#

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

somber radish
#

That should actually be a note in the UI itself ...

ivory delta
#

There's not space to describe everything in the UI... but if you feel it should be changed, you can suggest a feature request.

somber radish
#
            bright
          {% else %}
            dark
          {% endif %}``` fixed it
somber radish
open coral
#

hi @fossil venture (and others) - im trying again with the rest function you helped me with yesterday.

with the following code:

rest:
  - resource: http://10.1.1.42/cgi-bin/webgui.fcgi?xmlitem=34.4033
    scan_interval: 60
    sensor:
      - name: "PoolTemprest"
        value_template: '{{ value_json }}'

I get this from the states in dev tools when i call up the status of PoolTemprest:

{'pm5': {'item': {'@type': '34', '@id': '4033', '@label': 'T1', '@unit': '°C', '@value': '27.3'}}}

just need to filter out all the rest exept 27.3 🙂 any ideas? we are so close!

fossil venture
#

Huh. Well there you go. It does the silly @ thing too. Try value_template: '{{ value_json.pm5.item["@value"] }}'

open coral
#

it worked! well done!! thanks again! 🥳 🙏

fossil venture
open coral
#

good catch! will do

#

is it possible to create a new line in the configuration.yaml file?

i am creating a combined sensor with multiple (6) states combined, making it difficult to eddit and work on:

value_template: '{{ "on" if (is_state("switch.status_light_on_annex", "on") and is_state("switch.status_light_on_covered_terrace", "on") and is_state("switch.status_light_on_covered_terrace", "on")) else "off" }}'

I would like to be able to have a line break between each item to make it easier to work with, is there a way?

silent barnBOT
charred dagger
#

You could make a script that you call from the frontend which does this.

wintry garden
#

Hi! I'm having trouble making a simple service call with templates in my lovelace-ui file. Here is a simple representation of my dashboard: https://paste.ubuntu.com/p/fsBqX2HxpH/
Currently making service call in the UI logs "{{ states('input_select.broadlink_remote') }}" as a string instead of the state. I also tried without the outer " " and get the following error:
invalid key: "OrderedDict([("states('input_select.broadlink_remote')", None)])" in "/config/racelandDashboard.yaml", line 29, column 0

#

I was under the impression that I could use templates in the UI

open coral
#

thanks @charred dagger - helpful

wintry garden
#

(I already checked if the template is correct using the template tab in dev tools)

wintry garden
#

got it, I'll find a workaround

silent barnBOT
tepid apex
#

im trying to create a sensor to display the correct year/month/days that a person is old, but cannot get it to work. If this person did not have a birthday this year it will display for example -2

#

if the person had his birthday, the value is correct

#

how can i change this in a way to calculate the exact amount of months the person is old for this year?

#

state_attr("sensor.anniversary_verjaardag_caroline", "date") is for example '1990-09-27', this returns -2 now 🤣

dreamy sinew
#

that kind of date handling gets pretty dumb in a hurry. What is the intended purpose of this sensor?

ivory delta
#

the exact amount of months the person is old for this year
Full months? Partial months? Julian, Gregorian, lunar?

inner mesa
#

it's a crime that all months aren't exactly the same length

dreamy sinew
#

we need a metric calendar and time scale

inner mesa
#

I was just going to say that 🙂 But it would guarantee that the US wouldn't use it

dreamy sinew
#

eh, as long as all the computers use it i won't care

#

i already use day-month-year and 24h notation so meh

ivory delta
slim cliff
dreamy sinew
#

i had an example directly below of a full template you could use

#

typed out on mobile even 😉

slim cliff
#

Sorry I might have quoted the wrong message than :P
I was actually talking about the code you posted
The {% set sensor .... code, this is a value template?

dreamy sinew
#

the whole thing is a template together

#

you can drop that as is into the devtools > template page, just swap out for your sensors

slim cliff
#

Sorry to ask, but,, how would I use it..
Something like the followign?

  {% set sensor = [states.sensor.non_recyclable_waste_pickup, states.sensor.organic_waste_pickup, states.sensor.plastic_waste_pickup]|min(attribute='state') %}
  {{ '{}: {}'.format(sensor.name, sensor.state) }} ```
dreamy sinew
#

yep

#

and that should give you name: date

slim cliff
#

Oh wow, That's way cleaner... I had no idea that was an option XD

#

Let me give this a go

dreamy sinew
#

i had a suspicion that it was possible but had to look it up

slim cliff
#

Getting an error after swapping out for my sensors, TypeError: 'attribute' is an invalid keyword argument for min()

dreamy sinew
#

that's odd

slim cliff
#

checking my sensors, but I think I swapped the correct values..

dreamy sinew
#

but i just tested it and get the same error

slim cliff
#

Ahh that's reassuring :P

dreamy sinew
#

lame, guess i sent you down a rabbit hole

#

sorry about that

slim cliff
#

No not at all!

#

Thank you for helping me, thank you for teaching me things about this genius application!

ivory delta
#

| sort(attribute='block_total') | first should still work, right?

#

Update the first line to be this, Giblet:
{% set sensor = [states.sensor.non_recyclable_waste_pickup, states.sensor.organic_waste_pickup, states.sensor.plastic_waste_pickup] | sort(attribute='state') | first %}

slim cliff
#

That totally works!

ivory delta
#

Slightly more verbose, does the same thing.

slim cliff
#

The combined brainpower in here is staggering XD

ivory delta
#

phnx contributes way more toward that total than I do.

#

Most of what I know about the 'clever' stuff with templates, I've picked up from phnx and petro.

slim cliff
#

Still, the combined know-how and willingness to help is what makes this an awesome community

hollow girder
#

hello, is there a easy way to remove one month to a date? I think there was a recent update to that, but I can't find any reference to that

inner mesa
#

Rephrase?

hollow girder
#

a easy way do do now() - 1 month?!

ivory delta
#

That'd be a timedelta.

#

Plenty of examples in the chat history if you'd like to search for that term.

hollow girder
#

thats it... tks

inner mesa
hollow girder
#

😆

past wigeon
#

I'd like to create a sensor that is the absolute value of another sensor. So templates seems to be the way to go about it.

#

But I can't figure out how to use mathemtical operator with template.

inner mesa
#

{{ -5|abs }}

#

-> 5

#

That’s how filters work

past wigeon
#

so something like:

#

value_template: "{{ state('sensor.iotawatt_input_solar2_wh')|abs }}" ?

inner mesa
#

Not quite. States are strings, so you need to convert it to a float first

#

value_template: "{{ state('sensor.iotawatt_input_solar2_wh')|float|abs }}"

past wigeon
#

ah

#

I don't even know if that will fix the issue I'm seeing with the energy bit, I get no data showing for my solar. My only guess is that I'm reading an negative value

inner mesa
past wigeon
#

it's showing as "unavailable" in the developer tools

#
  sensors:
    solar1_wh:
      friendly_name: "Solar11"
      unit_of_measurement: Wh
      device_class: energy
      value_template: "{{ state('sensor.iotawatt_input_solar1_wh')|float|abs }}"
inner mesa
#

states

past wigeon
#

in the developer tools, sensor.iotawatt_input_solar1_wh is :

inner mesa
#

Not state

past wigeon
#

-1202752

#

ah.

#

it says "state" in the dev tools

#

I just assumed

inner mesa
#

Where?

past wigeon
#

in "Developer Tools"

inner mesa
#

Yes, but where?

past wigeon
#

where I can see the value of entities

#

Entity:

#

State:

#

state attributes...

inner mesa
#

Ok, that’s unrelated to templates

#

That’s just a table. The data structure is called states

past wigeon
#

that it's plural is a bit confusing 🙂

inner mesa
#

I’ve felt that way as well

#

Consider that it’s a data structure of all states and you’re grabbing one out of it

past wigeon
#

perfect, working now

#

well, my sensor is of the right value

inner mesa
past wigeon
#

hmm, my sensor while showing in the "developer tools" with what I'm hoping is the right unit and type, isn't showing in energy

tepid apex
ivory delta
#

That should be pretty easy then. Work out full years first (difference between the two, rounded down, multiplied by 12), then work out the remaining full months (similar logic, no multiplying).

lofty hound
#

well hello there everyone 😄 i'm trying to setup a template that add's together the 3 current hour estimated solar production to make one value and its throwing a "Error loading /config/configuration.yaml: while parsing a block mapping
in "/config/configuration.yaml", line 73, column 13" and a "expected <block end>, but found '<scalar>'
in "/config/configuration.yaml", line 75, column 34"

here's my code, any help would be greatly appreciated 🙂 thank you!
sensor:

  • platform: template
    sensors:
    estimated_total_hourly_energy:
    friendly_name: "total estimated hourly energy" #(line:73)
    value_template: "{{ (states('sensor.energy_current_hour')|float + states('sensor.energy_current_hour_2')|float + states('sensor.energy_current_hour_3')|float) }}
    unit_of_measurment: "kWh"
inner mesa
#

could you please format it properly?

silent barnBOT
#

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. Here's an example

Don't forget you can edit your post rather than repeatedly posting the same thing.

For over 15 lines you must use a code share site such as https://paste.ubuntu.com/.

inner mesa
#

offhand, it looks like you're missing a closing "

lofty hound
#
  - platform: template
    sensors:
        estimated_total_hourly_energy:
            friendly_name: "total estimated hourly energy"
            value_template: "{{ (states('sensor.energy_current_hour')|float + states('sensor.energy_current_hour_2')|float + states('sensor.energy_current_hour_3')|float) }}"
            unit_of_measurement: "kWh"
inner mesa
#

first, 2 spaces per indentation level

lofty hound
#

quote added. good catch, changed error to

Error loading /config/configuration.yaml: while parsing a block mapping
in "/config/configuration.yaml", line 1, column 1
expected <block end>, but found '<block mapping start>'
in "/config/configuration.yaml", line 77, column 2

inner mesa
#

second, the outer set of parens are unnecessary in the template

lofty hound
#

the {{'s?

ivory delta
#

() = parentheses

#

{} = curly braces

lofty hound
#

the one around the states? gotcha

inner mesa
#

I suspect that the problem is indentation

#

you're just inconsistent across the definition

lofty hound
#

well. that's how all my other things on config are indented.... why's it only messing up on this one?

#

infact i went to change the other's to only two spaces and it broke those uhh.. integrations

inner mesa
#

you need to be consistent everywhere

lofty hound
#

i am, 3 spaces for each "tab" notepad++ is nice like that

inner mesa
#

looks like 4 to me

lofty hound
#

well its 3, one before the - the - and one after the - for example

#

#icantcount nvm your right

#

its still consistent across the board

inner mesa
#

I don't see anything else wrong with it other than the indentation, and indentation is important and meaningful in YAML

lofty hound
#

i've noticed lol.

inner mesa
#

not sure what to tell you, then

lofty hound
#

so when i do binary_sensor: - platform for example should the - line up under the binary_sensor ?

inner mesa
#

it's a list under binary_sensor:, so...

#
binary_sensor:
  - platform: template
    sensors:
      foo:
        value_template: "{{ xxx }}"
lofty hound
#

i ask because right now they're all bumped in two spaces. has the - and then another space. as you just exampled to me, so sensors: in that case is also 4 spaced in, correct?

inner mesa
#

it's all relative to the parts around it

#

in any case, I just added what you posted above. fixed the spacing, and it checks fine for me

#
- platform: template
  sensors:
    estimated_total_hourly_energy:
      friendly_name: "total estimated hourly energy"
      value_template: "{{ (states('sensor.energy_current_hour')|float + states('sensor.energy_current_hour_2')|float + states('sensor.energy_current_hour_3')|float) }}"
      unit_of_measurement: "kWh"
lofty hound
#

i adjusted to

  - platform: template
    sensors:
      estimated_total_hourly_energy:
        friendly_name: "total estimated hourly energy"
        value_template: "{{ states('sensor.energy_current_hour')|float + states('sensor.energy_current_hour_2')|float + states('sensor.energy_current_hour_3')|float }}
        unit_of_measurment: "kWh"

with no luck, i'll copy your code in and hope it fixes it

inner mesa
#

you're still missing a closing "

#

it seems to come and go when you paste here

lofty hound
#

oh dang it, i prolly ctrl+z'd too far and didn't check. good eyes

#

well i copied your code in and it works fine now 😄 thanks for your help and expanding my understanding of this powerful platform! 😄

dreamy sinew
#
        value_template: "{{ [states('sensor.energy_current_hour'), states('sensor.energy_current_hour_2'), states('sensor.energy_current_hour_3')]|map('float')|sum }}"
spice crow
#

Hey!
I am pretty new to templating, but i have manage to do some stuff. Now i am stuck.. I am trying to translate this to swedish, since it shows if my cat is inside/outside, and since when. The code takes status from another sensor, and then translate it's to "Inside sedan 18:02" etc.. "Sedan" means "Since", the thing is i can't manage to make it from "Inside/Outside" to instead show "Hemma" or "Ute" Witch is the translate i wan't. I can't really understand how i knows to translate "where" to inside, since "where" from the sensor is 1 or 0, depending on my cats status. Hope someone can help, thanks!

ivory delta
#

Something like {{ 'Hemma' if is_state_attr('binary_sensor.pet_doris_2', 'where', 'inside') else 'Ute' }} should do it

inner mesa
#

cat_tracker:

spice crow
spice crow
granite wharf
#

Anyone have any suggestions where I should list a webpage that generates template elements? I made a template-generator to track profit and loss on crypto purchases. Just saving myself some coding hassle, but I think it would be useful to others who are speculating in crypto and tracking via HA.

ivory delta
#

You could share it on the forums, then it's easy to search for.

silent barnBOT
mighty ledge
silent barnBOT
mighty ledge
#

It doesn’t get automatically assigned. Integration just performs a mathematical integration on the data coming from a sensor. It doesn’t assume it’s a power device_class.

charred dagger
#

But avoid double posting, @wheat cargo.

wheat cargo
#

sorry, I posted it here and then thought #energy-archived would be a better place

#

thanks for the commit fixing it

charred dagger
#

No worries... and I guess you can't delete a message after the bot has had it's way with it...

mighty ledge
charred dagger
#

Definitely

spice crow
dreamy sinew
#

have to share what you chagned

neon pivot
#

Hey, I have an LED strip controller where 50% brightness is actually 100%, and setting anything higher than 50 overheats/bricks the device. Does anyone know of a way to limit or rescale the dimmer so that 100% on the bar sends 50% to the controller? Most important thing to me is that it should not be able to be set higher than 50

marble jackal
#

Is thera a device_entities() equivalent for area's? I want to somehow get the entities associated to an area.

marble jackal
#

Thanks.. I've been informed by Frenck in the Dutch HA discord that template support for areas is in the pipeline

silent barnBOT
broken urchin
#

Hey, could anyone with knowledge of „Create sensor with attribute of entity using templates“ look at this? I really dont know what else I could try to get this sensor working…

silent barnBOT
#

Rule #6: Please do not post codewalls (text longer than 15 lines) - use sites such as https://paste.ubuntu.com/ (just not Pastebin).

Please take the time now to review all of the rules and references in #rules.

broken urchin
#

(sorry for the codewall ._.)

inner mesa
#

What is wrong?

#

I do note this, which can’t have a space in it:
aussentemperatur city:

charred dagger
#

And there's sensor: three times.

inner mesa
#

You’ve only said ‘none of them seem to work’

#

That too

#

But there are several different formats there, so no sure what’s going on

broken urchin
#

Still, If I search the entity (newly created sensor) in the developer tools sektion of HA, it wont show up

#

*section

inner mesa
#

After restarting HA? All that would go in configuration.yaml, BTW

valid hatch
#

Not sure if this is the right channel for this. I have a group, group.people, which includes some person entities. I also made a template sensor which counts the number of people at home:

template:
  - sensor:
    - name: Number of people at home
      unique_id: 'number_of_home_people'
      state: "{{ states | selectattr('entity_id', 'in', 
        state_attr('group.people','entity_id')) | 
        selectattr('state','eq','home') | list | count }}"

There is a delay of about a minute between a person being detected as away, and the sensor updating to reflect this new reality. Why is that? Also, if there is a way to improve this template sensor, would love to hear it. I feel like there should be a way to start at expand('group.people') but I couldn't figure it out.

inner mesa
#

If HA doesn’t know what entity state changes to track, it updates every minute

#

You can add a state trigger to your template sensor listing the entities it should monitor

valid hatch
#

ah, cool

#

Anyway to have it monitor all entities within a group?

inner mesa
#

Yes, use the group in the state trigger

#

Well, that won’t monitor the individuals

valid hatch
#

Right—I imagine that would only update when the group overall is home/away

ivory delta
#

Why don't you just expand the group?

#

{{ expand('group.people') | selectattr('state','eq','home') | list | count }}

inner mesa
#

I was thinking that, but I think you can just use the same state template in the trugger

ivory delta
#

Any time the group changes, the template will be re-evaluated.

broken urchin
# inner mesa After restarting HA? All that would go in configuration.yaml, BTW

Yes. I had a look into the logs:

Logger: homeassistant.config
Source: config.py:437
First occurred: 18:07:12 (1 occurrences)
Last logged: 18:07:12

Invalid config for [template]: required key not provided @ data['trigger']. Got None. (See /config/configuration.yaml, line 30).

I dont understand why I need a trigger, according to this info state-based template sensors are formatted like I did
( https://www.home-assistant.io/integrations/template/#state-based-template-sensors )

ivory delta
#

Which line is line 30 of your configuration.yaml?

valid hatch
#

I think mono's solution is correct!

#

It simplifies the expression, and the template dev tool tells me it will monitor for the group as well as each entity in the group

#

Thanks, @ivory delta

ivory delta
#

Your approach would make more sense if you were looking for something dynamically... but then you could still use select or selectattr filters.

broken urchin
ivory delta
#

That's 3 lines. Which is line 30?

broken urchin
ivory delta
#

Great. Now stop pinging me.

silent barnBOT
#

When using Discord's new Reply feature it defaults to pinging the person you reply to, which can get frustrating for the target. Click @ ON to @ OFF to stop this - on the right side of the compose bar.

inner mesa
#

Where did you put that?

ivory delta
#

It sounds like you have something nested where it shouldn't be.

broken urchin
#

sorry mono

inner mesa
#

It goes in configuration.yaml, not in sensor.yaml

broken urchin
#

I already moved the code to the configuration.yaml file

ivory delta
#

.share the whole file, hide any secrets

silent barnBOT
#

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

inner mesa
#

if I paste exactly your definition into my configuration.yaml, it checks fine

broken urchin
#

When I „check configuration“ do, everything is fine too. But when rebooting I still get the error :

„Invalid config for [template]: required key not provided @ data['trigger']. Got None. (See /config/configuration.yaml, line 30).“

Here the stuff thats above the code in my configuration.yaml file:
https://paste.ubuntu.com/p/by4Q7S63Bp/

inner mesa
#

what version of HA are you using?

#

something from a stone tablet?

#

please don't say something like 2021.2

broken urchin
#

Version core-2021.4.6
Installationstyp Home Assistant Container
Entwicklung false
Supervisor false
Docker true
Virtuelle Umgebung false
Python-Version 3.8.7
Betriebssystemfamilie Linux
Betriebssystem-Version 5.10.17-v7+
CPU-Architektur armv7l

inner mesa
#

keep updating

#

you're 4 releases behidn

#

I suspect that's before the new template sensor format was supported

#

it's August, and that's from April

broken urchin
#

ok.. will try it. Started backup process..

ivory harbor
#

hey yall, I'm trying to wrap my head around templates and for some reason this feels like PhD level math to me right now....

#

my goal is to use a sensor on my mailbox to create a virtual switch where the state of the switch corresponds to if we've gotten mail

ivory delta
#

What information does the sensor give you?

ivory harbor
#

open / closed

#

so do I want something like value_template: "{{ is_state('switch.source', 'open') }}" ?

ivory delta
#

How do you plan to know if you've had mail and if you've checked the mail?

inner mesa
#

Then you really need to latch that with an input_boolean

ivory harbor
#

(funny enough we literally just got mail 10 seconds ago and I got the notification 😂😂)

ivory delta
#

So you don't need a 'virtual switch'. Just use the automation.

inner mesa
#

Right, if all you care about is the moment when the door is opened

ivory harbor
#

what if I want to be able to use the state of 'mail' in other places?

ivory delta
#

Use the boolean 🤷‍♂️

ivory harbor
#

not to sound dense... but what do you mean? I understand what a boolean is generally, but not in HA.

silent barnBOT
ivory delta
#

Maybe that's what you meant by a virtual switch. It's a helper that tracks a boolean state.

ivory harbor
#

🤯

ivory delta
#

A word of warning with your suggested approach...

If switch is on, and opened again, set it to off.
If you get two mail drops in one day, you'll think you've had none.

inner mesa
ivory delta
#

If you have no reliable way to know you've checked the mail, maybe stick with clearing the boolean at midnight.

ivory harbor
#

@ivory delta yeah, it's imperfect. If I were to also go check it manually before mail has arrived, it'd think I have mail

ivory delta
#

No need to check before it arrives if you know when it's been opened by someone else 😉

ivory harbor
#

I mean... I could also do image recognition of our mailman with our doorbell camera 🙂

inner mesa
#

Maybe you’ll find that it’s a trained bear

ivory harbor
#

where I live, that actually happens 😂😂

ivory delta
#

I have a similar setup but with two sensors. Input boolean gets turned on when someone rings the doorbell. Input boolean gets turned off when I open the door. If it's on, that means someone has rung the bell and the door hasn't yet been answered.

#

I have flashy lights and stuff that continue for as long as the boolean is on. It's my 'go answer the door, you lazy swine' notifier.

ivory harbor
#

measuring the delta between ring and open would give me so much social anxiety for the person waiting 😅

ivory delta
#

So don't measure it 😉

inner mesa
#

If it’s important, they’ll ring again

ivory delta
#

For me, it's so I know if my wife beat me to the door. If she's closer and answers it first, the light stops flashing.

ivory harbor
#

thanks yall, this info on the booleans is super helpful and, in reading the documentation, obvious

#

@ivory delta I'm just joking, I see the utility in it for sure

nocturne trout
#

I'm not sure if this is the right place, or if #integrations-archived would be more appropriate, but.....
I use a lot of custom: button-cards and would like to change the properties of them (name, color, etc) based on values/states of OTHER sensors/entities. Unlike templates in HomeAssistant, they use Javascript formatting and I'm struggling to learn it. Can anyone point me to a good resource where I can try and gain some knowledge about the commands/syntax required? Thanks!!

ivory delta
#

You'd want to ask in #frontend-archived about frontend stuff (including JavaScript 'templates')

fossil venture
#

When using default to guard against a variable not always being defined like this {{ my_variable | default }} what does it actually default to?

tardy jolt
#

is there a minimum time until a sensor define via a template makes it to the list?

ivory delta
ivory delta
fossil venture
tardy jolt
#

the ones with unit of measure %

#

but the ones without or kg or other

#

do not appear

#

here is the full

#

as a note I see them in the normal graph so the entities exist

wicked smelt
#

So I got one question! I've been using a lot of time on templates and trying to figure out why my template is not working still I got a True result in developer tools. What I actual found out, I think that actual there is a difference between "True" and "true". Can someone explain this to me? Is it a string and a boolean, if so I think it should be handled as the same.

Here are two examples when using wait_template,
This will allow the automation to go on,

{% if states('light.dimmer_stue') == 'on' %}
    true
  {% else %}
    false
  {%endif%}

Neither one of there are working. Result for both of these are True

{{ states('light.dimmer_stue') == 'on' }}
{{ is_state('light.dimmer_stue', 'on') }}

fossil venture
#

true is a boolean True is a string. Home Assistant is case sensitive, as it is built with Python, which is case sensitive.

#

For what you want to do. Just do this: {{ is_state('light.dimmer_stue', 'on') }}

#

This will return true/false

#

However Lovelace and other parts of the frontend (like the template editor) will display the state as True/False.

#

Confusing but pretty.

wicked smelt
#

will states('') also do the same? Also, I cant trust the template editor as it will state True/False, even if its true? I need to recheck my script

fossil venture
#

Actually I got that wrong. The template editor will display true/false. It's only Lovelace that capitalises the states.

wicked smelt
#

ah, okey, thanks will try again

bronze horizon
#

I've got some hard drive stats being reported on MQTT, but I'm having a hard time setting up the value template because the payload contains objects named "C:", "D:" etc so can't figure out how to escape or deal with the colon, e.g. value_json."C:".use value_json.C:.use etc all give yaml errors.

frigid marsh
#

I have a question! I have a scenario where a user can do without a couple of cards, to remove complexity from a common view. Can we check against a currently logged-in user? Is there such thing as a "user template"?

sonic slate
#

I'm changing a bunch of things in an older configuration section that contains template sensors in the old format, and guess would want to update that. See for instance in this example in the docs, each sensor has some sort of ID (e.g. solar_angle and sunrise), are these the unique IDs in the new format?

mighty ledge
#

I’m the old config, those made up the object_id. Now the unique_id or name derives the object_id

broken urchin
edgy umbra
#

Hi, can anyone help to show two labels below each other in a custom button card. I have the template below but if i add another state it show behind the first state...

#
            [[[
              if (states['media_player.telenettvbox'].state == "off") return 'Uitgeschakeld';
              else return states['media_player.telenettvbox'].attributes.media_title;
            ]]]```
ivory delta
#

Add a line break. Share your attempt at having multiple lines.

edgy umbra
#

After allot of attempts i now have a two custom button cards below each other using a stack in card but it's partly working with to many space between the names and the card itself is a mess. 🙂

#

Tinkerer, any change to explain how i can add a line break. 🙂

ivory delta
#

If that doesn't work, \n is the new line character.

edgy umbra
#

Found it using "<br>".

silent barnBOT
thorny snow
#

I'm getting the following error in log:

2021-08-21 19:22:12 ERROR (MainThread) [homeassistant.helpers.template] Template variable error: 'person' is undefined when rendering '{{ is_state(person.michael, 'home') }}'

ivory delta
#

You're missing the quotes.

thorny snow
#

ahh 🙂

keen nacelle
#

Stupid question I can't find the ansswer to: How do you get the length of an array? I've got a rest sensor pulling in some JS. I simply want the length of an array.

autumn matrix
#

Just asked the question in #automations-archived but i'm looking for a way to determin what user triggered the switch so that I can decide which speaker should turn on. When my wife stars playing music her spotify account should be used. When I hit the same button in the interface my spotify account should be used. I was told this can be done with templates but I don't see how this should be done in a script. Any hints on were to start?\

keen nacelle
past wigeon
#

Question: I have a iotawatt that is being read every 30s, I retrieve the cumulative value of the amount of energy produced by my solar panels. The value returned is negative. I have a template that will calculated the absolute value as the energy screen requires a positive value.

#

This is done using a template:

#
      friendly_name: "Solar Total Energy Output"
      unit_of_measurement: Wh
      device_class: energy
      value_template: "{{ states('sensor.iotawatt_output_total_solar_wh')|float|abs }}"
      attribute_templates:
        last_reset: "{{ state_attr('sensor.iotawatt_output_total_solar_wh', 'last_reset') }}"
        state_class: "{{ state_attr('sensor.iotawatt_output_total_solar_wh', 'state_class') }}"
#

the problem is that when I restart HA, where the original sensor just has no value (the graph of the history will show a gap)

#

the problem is that during that time, that template sensor will be set to a value of 0.

#

This totally mess up the energy screen or the energy_meter which if the reset happened at midnight, will see say a value of 3.5MWh , followed by 0, and then again 3.5MWh . So my daily meter now has a value of 7MWh

#

how can I define the template so that it doesn't return 0 during the time the entity sensor.iotawatt_output_total_solar_wh has no value?

fossil venture
#

Use an availability template.

#

availability_template: "{{ states('sensor.iotawatt_output_total_solar_wh') not in ['unavailable', 'unknown', 'none' ] }}"

past wigeon
fossil venture
#

What is a "normal template"? Just add it as an extra option to your template sensor.

past wigeon
fossil venture
#

That's the one.

silent barnBOT
autumn matrix
#

Could someone help me out with this. I wanna trigger an action based on who pushes a button in the home automation interface

          {{ (expand(states.person) | selectattr('attributes.user_id', 'eq',
          trigger.to_state.context.user_id) | first).name == 'Ronald' }}
   

However, this does not seem to work and i'm struggling to find the attributes to use

valid hatch
#

Is there a way to convert color_name to RGB values in a template? There is a homeassistant.util.color.color_name_to_rgb function that does what I want.

ivory delta
#

You don't have access to that within templates. You could look at the code for that and try to reproduce it though.

autumn matrix
#

@ivory delta is that in response to @valid hatch or to me?

ivory delta
#

Nice, double tagging...

#

I answered the most recent question. If I want to reply to an earlier one, I'll use the reply function to make it obvious

ivory delta
autumn matrix
#

Yesterday I asked it myself but replied with it that I found the solution. However when I tried to use the solution it didnt work so finding the answer continues

ivory delta
#

Ok. What doesn't work?

autumn matrix
#

Well I thought this would work in a script because it gave True when using it in the template developertools

#

{{ ((expand(states.person) | selectattr('attributes.user_id') | first).name) == 'Ronald' }}

#

However when I log in with another user it also returns true as a boolean

ivory delta
#

What do you mean when you log in? What's the trigger?

autumn matrix
#

The trigger is a button in the interface/app.

#

In this particular case; when my wife clicks the button it should use her spotify account, when I clicks the same button in the interface it should select my spotify account. For this I need to determin the user that clicks the button

ivory delta
#

Use a sharing tool for long posts. Don't edit extra in to fool the bot.

#

You'd have to debug the automation to see what details you get in the trigger object.

stone briar
ivory delta
#

No... the first follows a filter.

#

Oh, yes...

#

But that's a mistake in their second paste. Original is okay.

stone briar
#

I don't see anything in that conditional that's comparing against "user who triggered this".

autumn matrix
#

Yeah I suspect the same indeed. Trying to understand trace function but this doesnt give me the information I need

ivory delta
#

selectattr('attributes.user_id', 'eq', trigger.to_state.context.user_id)

stone briar
#

wow..how the hell did I miss that? sigh

autumn matrix
#

Yes tried that one as well but in the template tester I got UndefinedError: 'trigger' is undefined

ivory delta
#

Yes, because you're outside of an automation...

stone briar
#

won't work there.

ivory delta
stone briar
#

Can't just "Run automation" either.

#

Create a button or something to trigger.

ivory delta
#

They have the button. The issue is knowing what's in the trigger.

autumn matrix
#

So I should ask what information is in the trigger of a button?

fossil venture
ivory delta
boreal siren
#

is there a guide explaining the {{ }} and {% %} syntax?

fossil venture
karmic prism
#

Afternoon all , first time here i need to sum up some sensors

#

well derive some from existing sensors

#

i can create mysensor and set the state with '{{ states('sensor.existing') | float }}'

#

where i fail is with '{{ ( states('sensor.existing') | float / states('sensor.sensor2' | float )}}' it should give a numerical value but i get '0.0'

ivory delta
#

What are the values of the two sensors?

karmic prism
#

also i have around 12 energy monitoring plugs and i need to add each watts together to get a total is there a straightforward way to do this they are named energy01 to energy12

#

well typically something like 320 and 0.95

ivory delta
#

Not typically. What is it now when you say your other template gives 0?

#

Also... you have a mistake in the second half. Look closely and compare it with the first half.

karmic prism
#

well 267 and 9.725 and the result is 0.0 everytime

ivory delta
fossil venture
karmic prism
#

maybe I should start at the beginning 🙂

#

I have a current cost meter which delivers a watts value every 6 seconds via a serial port this works in the new energy tab as is but its wrong

#

first issue is that really its not watts its VA and the Vis assumed to be 240 where the nominal V is 230V but it drifts due to grid load

#

so my first attempt is VA * (gridactual volts / 240)

#

I have a smartplug on a lightly loaded ring near the breaker box which gives me a reasonable reference voltage.

#

So thats the first correction the next one is that va and watts are not the samething unless the load is resistive. so for example i might be drawing 75 watts with a VA of 125

#

However my unmeasured loads e.g shower , cooker immersion heater are primarily resistive and the powerfactor is close to one.

#

so what i want to do is correct for my knownloads and leave the unknown loads with a power factor of 1

#

It won't be quite right as i cant really get a read of the led lights but since there are 10 at 90 watts total its not a problem if they actually register a bit high.

ivory delta
#

So what are you actually asking for help with?

karmic prism
#

ok part one correcting the VA measured with assumed 240V to a VA with the realtime voltage

#

i've created a sensor which takes real volts and divides by 240 giving around 0.93 to 0.97 that works but when i create a sensor using VA x (my power factor) it results in 0.0

#

i know that state is recorded as a string but i thought | float would cast it to a float

#

actually using / in the first place was a lucky error as the templating tool says i'm trying to divide by zero

karmic prism
#

so that means i must be getting a float that equates to zero

ivory delta
#

No. It means your template is wrong.

#

Read your template.

Good:
states('sensor.existing') | float
Bad:
states('sensor.sensor2' | float

karmic prism
#

ok can i paste a few lines

ivory delta
#

No

#

Read what you've already been told.

karmic prism
#

yes i missed a closing ) but even with it corrected it still gets a result of '0.0'

ivory delta
karmic prism
#

the adding of sensor values ?

ivory delta
#

What are the values?

#

{{ 267 / 9.725 }}
This definitely doesn't give 0.0.

karmic prism
#

which is where i'm messed up since thats what it gives as a result

ivory delta
#

Go to the Dev Tools, experiment until it gives a value,.

#

You said you fixed the parentheses, so this will work:
{{ ( states('sensor.existing') | float / states('sensor.sensor2') | float ) }}

karmic prism
#

i have '{{ ( states('sensor.vawatts') | float * states('sensor.mypf') | float )}}' and it results in '0.0'

ivory delta
#

Then one of your values is 0...

#

0 * anything = 0

karmic prism
#

hmm {{ states('sensor.vawatts') }} = 292

#

{{ states('sensor.mypf') }} = '0.971'

#

{{ states('sensor.mypf') | float }} = 0.0

ivory delta
#

Yeah, no...

#

{{ '0.971' | float }} gives... 0.971

#

What you're describing makes no sense.

karmic prism
#

yes but seems to be the case in practice your string converted fine

#

i don't know why the string held in states('sensor.mypf') isn't converting but thats what is happening

karmic prism
#

ok i think mypf sensor is bogus

#

i replaced it with a helper numeric object and it works

#

so maybe i need to give it an entityid

ivory delta
#

sensor.mypf is an entity ID.

karmic prism
#

ok so its not that

#

my definition is

#
  • sensor:
    name: "mypf"
    unit_of_measurement: 'W'
    state_class: measurement
    device_class: power
    state: >
    '{{ (states("sensor.energy03_energy_voltage") | float / 240.0) | round(3) }}'
burnt wigeon
#

I'm working on a sensor template for a zooz_multirelay(which defaults to the type outlet). I'm using an input to read a reed switch for my garage door. I'd like to change the color if the door is open in the lovelace dashboard.

#

is there a template item for icon color?

inner mesa
#

no

#

the docs show what's available

#

you'd need to use card_mod or a card that explicitly allows you specify the color, like custom button card

burnt wigeon
#

well that's annoying, seems like the most basic thing, but I'm guessing that topic has been overly beaten.

ivory delta
#

HA is an open source project. You're welcome to add that functionality.

inner mesa
#

It has been discussed often, and there are a number of options to do it. I mentioned two

#

but i prefer to use something like custom button card, which is very flexible at changing color, icon, etc.

mighty ledge
karmic prism
#

Thanks for the assistance, finally stomped my bugs 🙂

iron rose
#

Hey, trying to get some data out of makers api (hubitat) but cant get the template or rest working

#

this is what the api responds with: [{"capabilities":["Refresh","EnergyMeter",{"attributes":[{"name":"energy","currentValue":"6.49","dataType":"NUMBER","values":null}]},"ReleasableButton",{"attributes":[{"name":"released","currentValue":null,"dataType":"NUMBER","values":null}]},"Switch",{"attributes":[{"name":"switch","currentValue":"off","dataType":"ENUM","values":["on","off"]}]},"PushableButton",{"attributes":[{"name":"numberOfButtons","currentValue":"3","dataType":"NUMBER","values":null},{"name":"pushed","currentValue":"1","dataType":"NUMBER","values":null}]},"HealthCheck",{"attributes":[{"name":"checkInterval","currentValue":"3720","dataType":"NUMBER","values":null}]},"Configuration","Actuator","PowerMeter",{"attributes":[{"name":"power","currentValue":"0","dataType":"NUMBER","values":null}]},"HoldableButton",{"attributes":[{"name":"held","currentValue":null,"dataType":"NUMBER","values":null}]},"SwitchLevel",{"attributes":[{"name":"level","currentValue":"99","dataType":"NUMBER","values":null}]},"Sensor","DoubleTapableButton",{"attributes":[{"name":"doubleTapped","currentValue":null,"dataType":"NUMBER","values":null}]}]}]

#

and i want this part as a energy template: {"name":"energy","currentValue":"6.49"

#

any suggestions?

ivory delta
#

There are lots of bits that look like that. Which one?

iron rose
#

Tried with a rest but cant get it to display

#

value_template: "{{value_json.attributes}}"

#

json_attributes:
- currentValue

#

but i might be off?

ivory delta
#

Yeah, a little 😂

#

It'll be something like... value_json[0].capabilities[2].attributes[0] to get to the object you want.

#

That's nasty... arrays could change order, so it'll break if it does.

formal ember
#

hey all, I am trying to work out the best way to show on a little graph card or something the real time energy being consumed on some devices. I have power monitoring smart plugs on these devices and some template and statistic sensors which I will post below. The statistic sensor works, but the template sensor of realtime_power returns a state of unknown. Any ideas what I have done wrong here?

- platform: statistics
  name: power_per_minute
  entity_id: sensor.kitchen_fridge_smartplug_energy_total
  sampling_size: 60 # This is assuming you are getting 1 sample a second.  Adjust otherwise.    

- platform: template
  sensors:
    realtime_power:
      friendly_name: Realtime Power
      value_template: "{{ state_attr('sensor.kitchen_fridge_smartplug_energy_total', 'total') / (1000 * 60) }}"
mighty ledge
formal ember
mighty ledge
#

You screwing with me?

#

Look at what entity is getting created from your statistics configuration…

rare sage
#

Hi Guys, I am trying to show a sensor's negative value only but as positive. Does anyone know how i can do this?

#
  • name: "Battery Discharge"
    unit_of_measurement: "W"
    device_class: energy
    state: >
    {% set batter_cons = states('sensor.battery_watts') | int %}
    {% if batter_cons < 0 %}
    {{ -batter_cons | int }}
    {% else %}
    0
    {% endif %}
marble jackal
#

use | abs to return the absolute value or multiply with -1

#

{{ batter_cons | abs }} or {{ batter_cons * -1 }}
as you already defined batter_cons as an integer, there is no need to use the int filter again in your template

rare sage
#

OKay but i have no idea what i am doing

#

Could you edit the one above?

marble jackal
#

use one of the two suggestions instead of {{ -batter_cons | int }}

rare sage
#

Let me see if i can figure it out

#

Very noob with templates still new for me

#

Woohoo

#

That seems to work.. Thanks

formal ember
edgy umbra
#

Anyone know how i can use this in a custom: button-card?

#
{% for light in state_attr('light.all_lights', 'entity_id') if is_state(light, 'on') %}
{% set ns.res = ns.res + 1 %}
{%endfor%}
{{ ns.res }}```
inner mesa
#

You could make a template sensor from that Jinja code and reference it

#

It looks overly complicated

#

or maybe you have to do it that way for a light.group

edgy umbra
#

I want to count the lights that are on and use it as a label in a custom: button card.

inner mesa
#

yes, I understand. I was thinking that something like {{ expand('light.all_lights')|selectattr('state', '==', 'on')|list|count }} would do it, but I don't know if that would work for a light.group

#

in any case, the answer to your question is to create a template sensor with whatever template you want and then just refer to to it in your custom button card definition

edgy umbra
#

Seems that your template works fine, now figuring out how to add that to a custom: button-card...

inner mesa
#

ok, I've said twice to put it in a template sensor

edgy umbra
#

Yes going to do that, thanks Rob.

inner mesa
#

ok, just checking 🙂

reef onyx
#

I'm tryting to make a working value_template for a rest sensor
Config: https://www.hastebin.com/pevegohevu.yaml
That request gives me this data: https://codebeautify.org/jsonviewer/cb52ffad

What i'm trying to do is getting the points, points_this_week and time_this_week for the students. Right now i get error messages like this:
homeassistant.exceptions.InvalidStateError: Invalid state encountered for entity ID: sensor.irene_duolingo_xp_stats. State max length is 255 characters.

reef onyx
#

Not really sure what i'm doing. Just some copy paste configuration 🙂

ivory delta
#

The state is limited to 255 characters. You're able to store more in attributes, so just move your data around a bit, vacum.

reef onyx
#

but the data i want is just a couple of bytes

ivory delta
#

That's not what the error message says. The value of your template is resolving to something longer than 255 chars or it wouldn't complain.

#

Stick your JSON into Dev Tools > Templates and then use your template to see which parts it grabs.

reef onyx
#

i have tried to make a sensor like this:
sensor:
- name: "Irene Duolingo XP points"
value_template: "{{ value_json.students.0.xp.points[0] }}"
but i get this as a result

#

oh. it looks like i can't attach an image here

silent barnBOT
#

Please use imgur or other image sharing web sites, and share the link here.

Image posting is blocked in most channels to discourage people from sharing text as images.

ivory delta
#

But text is better 😉

reef onyx
#

as you can see. that template isn't doing much

ivory delta
#

Test it in Dev Tools > Templates.

reef onyx
#

the old template did to much 🙂

mighty ledge
#
{{ value_json.students[0].xp.points }}
reef onyx
#

i will try that @mighty ledge

#

@ivory delta How do i add all the data to test?

#

ah. i see it now at the demo template

#

It looks like {{ my_test_json.students[1].xp.points }} worked

#

0 works too for the other student

#

But it doesn't work in the config

#

the only difference is value_json in the config instead of my_test_json in the tempalate dev tool

ivory delta
reef onyx
#

That's what i have in the config now

ivory delta
#

You said it doesn't work. That could mean anything.

reef onyx
#

no log file errors
the state is unknown

fringe temple
#

Wondering how to build my own entity from my media player(s) to reflect a log of the content played. I see the attributes I want to use and can access via template with state_attr('media_palyer.chromecast', 'media_title') and similar properties but how do I build a custom sensor with each of these for use in a lovelace logbook card? Any suggestions?

#

Thinking this may have been done by folks getting parental controls or similar visibility into media

dreamy sinew
#

a normal template sensor can do that

fringe temple
#

@dreamy sinew is there any trick to only logging state changes when new content is played? i.e. next song, or next episode is played and no logged state for when the player is not in use?

dreamy sinew
#

probably not. it'll update to whatever that attribute value is

fringe temple
#

ok maybe the logbook card can be customized to ignore certain sensor states... I'll toy around with this

floral blaze
#

Can someone help me with this, im kinda stuck, i want to make a binary sensor out of an attribute. With the template function in Dev. Tools i came up with this;

binary_sensor:

  • platform: template
    sensors:
    toon_current_temperature:
    friendly_name: "toon current temperature"
    device_class: sensors
    value_template: >-
    {{ state_attr('climate.thermostat', 'current_temperature')}}
dreamy sinew
#

binary sensors are on/off only

inner mesa
#

And your indentation looks incorrect

floral blaze
#

how would one go about, making a sensor out of an attribute?

dreamy sinew
#

use a template sensor

#

not a template binary sensor

waxen rune
#

Like phnx and RobC pointed out, mind the type, sensornot binary_sensor and the indentation.
Probably something like this.

sensor:
- platform: template
  sensors:
    toon_current_temperature:
      friendly_name: "toon current temperature"
      value_template: >-
      {{ state_attr('climate.thermostat', 'current_temperature')}}
floral blaze
#

hmm

#

i was going to come back with this;

  • platform: template
    sensors:
    thermostat_current_temperature:
    friendly_name: "Current Temperature"
    unit_of_measurement: '°C'
    value_template: "{{ state_attr('climate.thermostat', 'current_temperature') }}"
#

which seems workable (sorry for not using code format), but it doesnt show up

#

ill try yours @waxen rune

inner mesa
#

please format code:

silent barnBOT
#

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. Here's an example

Don't forget you can edit your post rather than repeatedly posting the same thing.

For over 15 lines you must use a code share site such as https://paste.ubuntu.com/.

dreamy sinew
#

if you were still under the binary_sensor key it would still be wrong

floral blaze
#

got everything working, thanks for your input guys!

reef onyx
#

There must be something basic that I miss in my config. With my untrained eyes everything looks OK

#

And there are no errors in the log related to what I try to do

inner mesa
#

how do you know that that's what you're getting back from the REST call?

reef onyx
#

Curl

#

But it’s a good question. Is it positive to verify the response somehow? It is a quite large response and I guess it is to be stored as a state

#

If I take that config and add -H for each header line and add \ for line breaks curl get that data

inner mesa
#

you could set it as an attribute

reef onyx
#

Oh. How?

inner mesa
#

json_attributes_path and json_attributes

#

I haven't used it myself, but it looks like you could use $ for the path and students for the attributes