#templates-archived

1 messages · Page 66 of 1

uneven cloud
#

Hey template folks. I've made a script, which will allow Alexa to tell me when my next bin (trash) collection is. However, the message is only static at the moment, like this.

#
sequence:
  - service: notify.alexa_media_kitchen
    metadata: {}
    data:
      message: Your next Recycling and Food Bin Collection is Wednesday
      title: Next waste collection
      target: media_player.kitchen
      data:
        type: tts
mode: single
icon: mdi:recycle```
thorny snow
#

if you put your code into either code blocks using like this, looks prettier

uneven cloud
#

I also have a sensor called 'Next Waste Collection' which downloads the correct info. How can I get the text generated by the sensor into the message?

thorny snow
#

two of these `

uneven cloud
#

Like so? 🙂

thorny snow
#

yup

#

i generally post to bpaste if it's over 3 lines

uneven cloud
#

Like that?

thorny snow
#

even better

uneven cloud
#

Now, onto my question 🤣

#

I thought (naively) amending the following to message: sensor.next_waste_collection would read out the string of that sensor. But alas, is just literally reads the line of text.

#

How can I make the message read out the line of text returned by the sensor I created?

#

Nevermind, I figured it out myself. It should read

    {{ states('sensor.next_waste_collection') }}```
plain magnetBOT
#

@wraith spade I converted your message into a file since it's above 15 lines :+1:

marble jackal
#

for that we would need to know what's in the blueprint

analog mulch
#

I would like to count how many persons who are in the group.smurf_drivers are home. This doesn't seem to work:

{{expand('group.smurf_drivers')|select('is_state','home')|count}}
marble jackal
#

if you expand the group, you will get the full state objects

#

either use:

{{ state_attr('group.smurf_drivers', 'entity_id') | select('is_state', 'home') | list | count }}

or:

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

Well, I could come up with some other variations on that which will also work, but I think those are the 2 most logical options

inner mesa
#

Do smurfs drive?

analog mulch
#

Smurf is our impossibly blue car

#

ok i see it -- groups have the list of entity_id's as an attribute

inner mesa
#

The main point was that the is_state test takes entity_id, not state objects

marble jackal
marble jackal
inner mesa
#

only during excessive complexity story time hour

marble jackal
#

too bad is_state isn't added as a filter, then you could do:

{{ state_attr('group.smurf_drivers', 'entity_id') | map('is_state', 'home') | sum }}
humble nova
#

Hi, I need help adding multiple lights to this code. This is used in a template card to change the icon color once the light entity which is specified for this card is on but I would like the icon to show when any light for that room is on. I’m using template cards for the card that’s seen on the dashboard but when you click the cards within that room are light cards. How do I tell this icon to also respond to the other light cards in that room? Thanks.

{% if is_state('light.office_hue_group_1, ‘light.office_hue_group_2','on') %}
orange
{% endif %}
inner mesa
#
{% if ['light.office_hue_group_1', ‘light.office_hue_group_2']|select('is_state', 'on')|list|length > 0 %}
orange
{% endif %}
humble nova
#

Oh great 😊 thank you Rob, I’ll try this

inner mesa
#

sorry, fixed

warm spoke
#

good morning, i created a few template helpers to grab attribute data from an entity. basically making the attributes their own entities so i can use the data in grafana

i seem to have an issue with the new helpers 'falling asleep' and not reporting data periodically. i'll look at my grafana dashboard and one or both of the template helper sensors are not reporting, when i goto the helper it looks like the last time it updated is hours ago, which leads me to believe it has some kind of timeout or lack of persistance

#

is this something that is common with template helpers? is there some way i can prevent the helper templates from 'falling asleep'?

humble nova
warm spoke
#

grafana is polling all entities every 5 minutes so there shouldn't be an issue from grafana side

inner mesa
#

it will return true if any of the lights is on

#

so, it will result in 'orange' if that's true

humble nova
#

It works if I have 1 entity like this…


{% if is_state('light.office_hue_group_1,'on') %}
orange
{% endif %}
inner mesa
#

You can verify that in HA

inner mesa
humble nova
#

Doesn’t change the icon at all using that code

inner mesa
#

it will do exactly what I described

#

any of those lights are on, it will evaluate to "orange"

#

you can debug in devtools -> Templates

humble nova
#

I’ll try that

inner mesa
#

oh, you need to add "if" to the first line

humble nova
#

Ohok

#

If is_state?

inner mesa
#

no

warm spoke
inner mesa
#
{% if ['light.back_door_infrared', 'light.back_porch']|select('is_state', 'on')|list|length > 0 %}
orange
{% endif %}
inner mesa
#

as I mentioned, they will update when the entities they reference update

#

you can confirm that in HA

#

the only exceptions are when your template starts with states, where it will only evaluate every minute or states.domain, where it updates every second

humble nova
#

TemplateSyntaxError: unexpected char '‘' at 35

warm spoke
#

{{ state_attr('sensor.servername_storage_c', 'UsedSpacePercentage') }}

#

that's the template sensor, does that mean it starts with states?

inner mesa
#

you'll need to debug it

humble nova
#

Ok

cerulean oyster
#

Is there a possibility to force the "secondary" attribute in a mushroom template card to show a blank value (space), such that the card is not vertically shortened?

inner mesa
still plank
#

evening. how do you (in effect) join lists of entities? for example, how do i template to get a list of all light entities which are not in the living room area?

marble jackal
#
{{ states.light | map(attribute='entity_id') | reject('in', area_entities('living_room')) | list }}
#

That would do that, without the need to join lists

still plank
#

nice thanks

last basin
#

hi, pulling my hair out here with a blueprint automation which uses template conditions. i've read through and i'm sure things are correct but clearly they are not. and because its using a template as condition its seemingly impossible to troubleshoot it using trace.

mighty ledge
#

the trace shows the result

last basin
#

yes and the result isnt what I want. i was hoping it would tell me which aspect is causing it

mighty ledge
#

post the blueprint

#

or break up the template into separate variables in the variable section

#

or test the template in the template editor

mighty ledge
#

there's multiple ways to test this

last basin
#

i tried to use the template editor but its not as simple as pasting it in there. i couldnt work it out

#

(couldnt work out how to declare the variables/inputs in there

mighty ledge
#

well, you're shooting yourself in the foot

#

you're creating variables with the name time_to

#

in the variable section, and then you're trying to overwrite that in the condition

#

can't do that.

#

variables set in variables are set in stone.

#

outside that, you're using a ton of strings to compare times instead of datetimes

#

do the input_datetime helpers actually exist? or are the intentions to pull the time input into the blueprint selector?

#

Yeah, based on what I see, I think you have a misconception on what the blueprint selectors are doing. You seem to have a helper conveniently named after each selector, which is not how selectors work.

last basin
#

current time is pulled in with now() the time_to and time_from are there are a part of the condition to determine whether to run or not

lux_entity: lux_value: and ilum_entity are all optional, so the value for these is possible to be undefined/blank.
what i need the conditions to trigger on are as follows:
if time_use: is ON then ONLY consider the time aspects to trigger the automation actions.
if time_use: is off, then consider the time and all other conditions too, but effectively only trigger if one of the other conditions are true AND it is within the time frame specified.
the other conditions are ilum_entity and lux_entity and sun elevation. which should be all considered (if they exist as defined values)
oh and if the time_to and time_from are default values 00:00:00 then dont bother caring about time at all.

it all made sense in my head and now i'm trying to explain it and i'm getting myself in a tizzy 😦

#

i've not done this before (templates) and its getting a bit overwhelming

mighty ledge
#

did you create this entity in the UI via the helper menu? input_datetime.time_to Yes or No.

#

or are you assuming that it's coming from this?

    time_to:
      name: 'Timeslot to'
      description: 'Automation only activates before this time'
      default: 
      selector:
        time:
last basin
#

no, i didnt 😦

#

the latter

mighty ledge
#

that's not how selectors work

last basin
#

ok

mighty ledge
#

selectors do not create entities

#

this is grabbing an entities state states('input_datetime.time_to')

#

which does not exist for you

last basin
#

hmm ok back to the drawing board then

mighty ledge
#

change your variable section to this

variables:
  target_brightness: !input 'target_brightness'
  target_color_temp: !input 'target_color_temp'
  time_from: !input time_from
  time_to: !input time_to
  use_time: !input use_time
  elevation_shift: !input elevation_shift
  lux_value: !input lux_value
#

that will get all the values from your selectors so you can use them

#

then your template will be

#

actually, you need to add variables for all selectors that you made

last basin
#

can't i just refer to the !inputs directly instead of creating the variable?

#

aren't they themselves variables

mighty ledge
#

No

#

they are not

last basin
#

ok

#

but the entity related inputs dont need to be variables?

mighty ledge
#

If you want to use them in a template, they do

last basin
#

right ok

mighty ledge
#

give me a moment

#

what is the light binary sensor doing

#

that doesn't make sense

#

it'll have a value of on or off

#

is that a flag to say "Use the lux entity?"

#

Yeah, I don't get that part at all, that doesn't make senes

#

You're trying to treat it like anumber. I'm going to remove it and just use the lux entity.

last basin
#

ok so i have a few light sensors... some which are normal ones which report the lux value , so those are to be used in the input for ilum_entity and value

#

and i have a few on esp devices which dont register the voltage/etc but they have a pot on them and will report on/off based on if a certain brightness is achieved (based on the pot adjustment)

#

so the automation allows for using one or the other and ignores the other in the conditions

#

does that make sense?

mighty ledge
#

yes

last basin
#

thank you thats really kind of you.

#

does that do what my orignal one was supposed to do? i can see you've very much simplified the conditions aspect. its just because with my weirdly specific list of conditions originally it seems that that condition wouldnt do all that? or is that all done elsewhere?

mighty ledge
#

Well your logic was all over the place, I cleaned up the intentions and the code

last basin
#

lol yeah the logic in the code was, yes. ok thanks let me give it a test

#

gah why does raw.github always take ages to refresh after you make changes 😐

#

doesnt appear to be working still trace doesnt give much info

#

Stopped because of unknown reason "null" at 30 January 2024 at 22:18:56 (runtime: 0.00 seconds)

mighty ledge
#

look in the logs, and check the outputs of each variable in the variable tab on the trace

last basin
#

fwiw the automation i'm testing it with has elevation shift set to -10 time from 01:00:00 , time to 23:00:00 .. tried with and without use_time on or off

mighty ledge
#

the homeassistant.log logs

#

Sorry, I'm not going to play guess work, typical HA debugging is to figure out exactly what's wrong by looking at the returned variables and logs

last basin
#

i'm looking

#

how would one find the returned variables if they're not in the trace page?...
looking through the logs and its a huge mess of stuff which is above my paygrade. things are all over the place and i can't tell whats relavent and what isnt

mighty ledge
#

just post the errors

last basin
#

raise ValueError(
ValueError: Sensor sensor.unavailable_entities has device class 'None', state class 'None' unit 'entities' and suggested precision 'None' thus indicating it has a numeric value; however, it has the non-numeric value: '' (<class 'str'>)
2024-01-30 22:11:09.461 ERROR (MainThread) [homeassistant.util.yaml.loader] while scanning a simple key
in "<unicode string>", line 62, column 1:... thing

^
could not find expected ':'
in "<unicode string>", line 63, column 17:
target_light:
^

#

is one... but its immediately preceeded by a traceback

mighty ledge
#

well the arrow is pointing to the underscore

#

unless that's not the full error, I can't tell because it looks like you truncated the full error

last basin
#

thats just one of the things which looks like it might be relavent... there are some stuff all over that mentions ValueError: could not convert string to float: ''

#

is the full error the traceback?

mighty ledge
#

yes

#

try to run the automation from a known point in your logs as well

#

don't just guess

#

look at your logs, note the time, run the automation, grab relevant lines that point to things in the automation

last basin
mighty ledge
#

man you gotta clean up your errors

#

I don't see anything related to the automation

last basin
#

ok

#

look, thanks for helping, I'm getting it in the ear from the wife now so i have to knock this on the head for now and i'll continue looking at it in the morning. really do appriciate the help and time

mighty ledge
#

unless lounge_motion_lights is one of the automations

last basin
#

yes

#

thats the automation in question

mighty ledge
#

ok, where is test_none coming from? That's not something I added

last basin
#

no idea. i've not done anything related to that either

#

what is it saying it is

mighty ledge
#

did you change anything in the blueprint?

last basin
#

nope

mighty ledge
#

if you did, post the blueprint here

last basin
#

just pasted it as it

#

is

#

check my link earlier for my github.. thats what its using, which is your code

#

unless its something mentioned in another blueprint i use ... is there a way of searching for it... is it an entity or something i've searched entities and dev states but nothing like tha

final trellis
#

hi, is this correct please?

#
{{ (monthly_total_usage / 24) | round(1) | replace("."," κόμμα ") }}
inner mesa
#

Looks like you're trying to treat a floating point number as a string

final trellis
#

yes, because Nabu Casa TTS for greek is crap

inner mesa
#

What does it say in devtools -> Templates?

final trellis
#

it does work indeed

inner mesa
#

Then

final trellis
#

I only asked for the parenthesis

inner mesa
#

You asked if it was correct

final trellis
#

yes

#

maybe it needs another parenthesis ?

#

because it is correct . i get what i need

#

after I divide with 24 I close this to a parenthesis and then round and then replace ? is it correct lke this ?

inner mesa
#

I wouldn't have expected replace() to work on a number, but 🤷. The parentheses are fine

final trellis
#

i use it very much with TTS

#

because Text to speech engine of nabu casa doesn't pronounce the comma correct.

#

so I always do a replace from 6.2. to 6 κόμμα 2
(it's greek)

so the tts engine read it properly

inner mesa
#

It's..uh..all Greek to me

humble nova
#

@inner mesa sorry can’t seem to get this to work, my other code works but not this


{% if ['light.office_hue_group_1', ‘light.office_hue_group_2']|select('is_state', 'on')|list|length > 0 %}
orange
{% endif %}
inner mesa
#

Put it in devtools -> Templates

humble nova
#

I did, if I remove the second group entity it works so it may be the separation between the 2?

#

Can’t seem to include the 2 entities without an error

inner mesa
#

what error?

#

you have a wrong quote before the second light.

humble nova
inner mesa
#

it doesnt have the broken quote

humble nova
#

Yes

inner mesa
#

it's fine

humble nova
#

Ok

inner mesa
#

not what you have above

humble nova
inner mesa
#

yes, that's broken

#

anyway, HA pointed to the broken quote

last basin
#

morning, I'm still trying to get this ruddy blueprint to work but i'm just seeing in my logs
2024-01-31 10:27:00.285 ERROR (MainThread) [homeassistant.components.automation.lounge_motion_lights] Error rendering variables: TypeError: test_none() takes 1 positional argument but 2 were given
(for every automation using this blueprint when it is triggered)

there is nothing in the blueprint or anywhere that I can see which mentions anything relating to test_none ... very very baffled
https://raw.githubusercontent.com/thefunkygibbon/homeassistant/main/motionlight.yaml <--- the blueprint

twin compass
#

Good morning guys all good? 🙂

#

Is there anyone who can help me build a "Your next meeting is in X minutes/hours" template?

#

This is what I have so far 😄
`{% set t =
strptime('states.calendar.ical_work_calendar.attributes.start_time', '%a %b
%d %H:%M:%S %Z%z %Y') %}

{{ t.hour }} {{ t.minute }}`

Although it is giving me an error

#

Error rendering data template: ValueError: Template error: strptime got invalid input 'states.calendar.ical_work_calendar.attributes.start_time' when rendering template '{% set t = strptime('states.calendar.ical_work_calendar.attributes.start_time', '%a %b %d %H:%M:%S %Z%z %Y') %} {{ t.hour }} {{ t.minute }}' but no default was specified

#

The start_time attribute is: start_time: 2024-01-31 13:00:00

lyric comet
#

Why not just install easy_time from HACS and use the macro in there?

twin compass
#

is that a thing??? 😮

#

ill try that 😄

#

thanks!

#

I can't find it

lyric comet
#

Yes. Should appear in a HACS, you might need to make sure HACS is in experimental mode to see templates, I can not remember.

#

BTW: It is recommended to use the state_attr() function to get attributes these days, I understand.

twin compass
#

thanks for that, i will keep it in mind

fickle sand
last basin
#

yeah i have just seen that, and i also just found what was causing the error, ( but it still doesnt explain test_none being mentioned ?!)

marble monolith
#

Good morning all, i would like to create a sensor that shows me Current W Usage, all i got is a sensor that is showing me my Total kWh usage with its value being 51545.0195, this value updates every 10s. My idea was to somehow store the previous value and do a calculation "new value - old value". Any idea how to achieve this?

last basin
#

there is something wrong with the formatting on my condition here... can anyone suggest what it could be?

    value_template: >
      {% if use_time %}  # If the use_time switch is on
        {{ within_time_use }}  # Only consider the time range
      {% else %}  # If the use_time switch is off
        {{ within_time_range and (time_range_not_set or ilum_check or lux_check or sun_elevation_below_shift) }}  # Consider all conditions
      {% endif %}
#

logs say Error handling message: while scanning for the next token found character '%' that cannot start any token in "<unicode string>" but i'm struggling to understand what it means as everywhere i read says i should have the % in there

fossil venture
#

Comments in templates must be enclosed like this {# comment here #}

last basin
#

ahhhh ok let me change that then 🙂

#

so like this ?
{% if use_time %} {# If the use_time switch is on #}

#

i guess i can just remove the comments tbh

twin compass
mighty ledge
mighty ledge
last basin
#

got ya 🙂

mighty ledge
#

that's why it's failling

#

you only copied the variables

#

I altered everything

#

the within_time variable covers the use of not using time or using time

#

{{ not use_time or time_from | today_at < now() < time_to | today_at }}

#

if use_time is false, then that statement will return true and it won't compare times

#

if use_time is true, then the portion before the or statement will return false, forcing that to check the second statement

#

so your changes to your value_template in the condtion and the addition of within_time_use is pointless

#

because it's handled by the within_time function

#

To debug, run an automation from this blueprint (give me a second) to see what the variables are.

#

@last basin ^

#

Post the variables on the variable page, then we can continue.

final trellis
#

have a look . you will remember it. It was you point me to keep the condition ...

marble jackal
final trellis
#

yes, you asked me to keep the original condition ...now you said to remove it again

marble jackal
final trellis
#

anyway, because the automation works flawlessly I will keep it as it is . I changed parallel to queued

marble jackal
#

After that your added the state to the trigger, based on my advice. That was not correct and my post you linked was an advice to go back to this
#templates-archived message

#

I don't think what you have now will work as flawlessly as you think it does, but you seem to have made many changes now, so I don't know what your current full automation is

#

You only share small bits every time, so that makes it hard to see the full picture

final trellis
#

here it is

fickle sand
#

That automation and its condition logic are not the same as talked about earlier, also the condition is still redundant as by definition of a state trigger; the from and to states are always different.

modest isle
#

@lofty mason I just wanted to thank you for all of your help last weekend!! I was able to set everything up and used 3 template sensors for the attributes, and everything works flawlessly!!

fickle sand
#

But I guess it will work with the mode queued with lesser precision though by ditching the confidence parameter

final trellis
#

@fickle sand are you talking to me ?

fickle sand
#

yes

final trellis
#

Bas honestly it is exactly the same as the first place.

#

I just enhanced it with a random function for each person (instead of saying the same thing)

#

the condition is intact and the trigger it's the same (i just added more faces - but they all end to FROM : frontdoor_camera2

marble jackal
#

You removed the whole condition checking on a match. It's completely different from the code I linked to above

final trellis
#

dont worry about it

#

You've forgot it

#

two messages bellow you said to me:
"I would say you should have kept your original trigger"

fickle sand
#

And after that, you expressed your concern about the changing confidence without a state change #templates-archived message so TheFes and I suggested to stick with Petro's trigger and condition so it wouldn't be more complex than it should be

final trellis
#

fair enough

#

thank you very much for your time!
I will stick with queued mode for now and get back to you with some feedback

lament dust
#

Cross postedish question from the #automations-archived channel, I am looking at making an automation that is generic so it can apply to multiple devices of the same exact type but have complex logic that is checking multiple entities on this single device? For instance, I have some of the 3rd reality smart night lights and I basically want to say for each night light, if motion is detected & the lux on the specific device motion was triggered on, then turn on the light for that specific device. What is the best way to get entities or properties of a device?

lament dust
#

Is there a more efficient way to do this for instance,

{{
states[device_entities(device_id(trigger.entity_id))
| select('search', 'light') | list | first].state == "on"
}}
#

I feel like I am doing this multiple times in an automation and would like to ideally avoid repeating it many times

lyric comet
#

If you have a trigger for each device you can pick up the entity and the device from the trigger data. Then use that to build the entity IDs in a variables section.

final trellis
#

@lament dust if you want to switch off lights that are ON, then you can try with expand. You just need to create a group of the lights
I've use it for years

lament dust
#

So basically the logic is as follows:

  1. If motion is detected on any of X night lights
  2. Check if the lux is low
  3. Turn on that specific light only
final trellis
#

ic

#

@lament dust how do you check lux ?

lament dust
#

check if the illuminance is 1 or not lol

final trellis
#

nope, i mean from the same sensor ? or another sensor just for lux ?

#

what am saying, is these night lights , got also motion sensor and lux ??

lament dust
#

Yes they are one device but 3 different entities

#

I think I got it mostly working now:

variables:
  occupancy_entity_id: trigger.entity_id
  light_entity_id: >-
    {{states[device_entities(device_id(trigger.entity_id)) | select('search',
    'light') | list | first].entity_id }}
  illuminance_entity_id: >-
    {{states[device_entities(device_id(trigger.entity_id)) | select('search',
    'illuminance') | list | first].entity_id }}
final trellis
#

ok

lyric comet
#

Out of interest I think you can simplfy the selects a little:

#
    {{device_entities(device_id(trigger.entity_id)) 
    | list | select('search', 'light') | first  }}
marble jackal
#

You even don't need the list filter

#

Oh, and you might want to use match instead of search to avoid finding an entity with light in the object_id instead of the domain

inner mesa
#

And/or use 'light.'

mighty ledge
#

or just do ^light

#

I always forget about match and just use search w/ leading/trailing indicators

#

^ = starts with $ = endswith

#

^light or light$

marble jackal
#

Yeah, I know. I normally do that myself

#

Just got reminded about match the other day, that's why I proposed it now 😅

lament dust
#

Cool thanks everyone just tweaked it further

warm spoke
warm spoke
inner mesa
#

They don't fall asleep

#

Like any entity: devtools -> States

warm spoke
#

well poor term then, but they aren't displaying in grafana again

inner mesa
#

Focus on HA first

marble jackal
#

You can see the last_changed and last_updated timestamps there

warm spoke
#

OK the entity referenced i clicked on it and it says
last changed yesterday
last updated 9 minutes ago

#

so the 'parent' entity seems to be updated..

#

oh there we go.. the attribute entity says:
last changed: 20 hours ago
last updated: 20 hours ago

marble jackal
#

last_changed means the state of the entity changed

#

last_updated means any of the attributes changed

warm spoke
#

ya i assume the last updated is the issue? that should be 'polling' or updating at a much more regular interval than almost a full day, no?

#

oh... given what you said there maybe not..

marble jackal
#

If there is no change, the timestamps don't change as well

#

So if the state of your source entity changes, but this doesn't render into a new state or attribute value, there is no update of these timestamps

warm spoke
#

hmm maybe its how im trying to pull the data into grafana then?

#

because its clearly there in HA, just seems to drop off at some point on my granafa dashboard

marble jackal
#

Possibly, I don't use Grafana, but this issue does ring a faint bell

#

I think I've seen something similar before

#

You could add an attribute in your template sensor with something like {{ range(1000000) | random }}

#

That should give you at least a last_updated timestamp everytime it renders the templates

#

Not sure if it would help for Grafana though

inner mesa
#

If your 'falling asleep' is that it doesn't continuously update for the same value, that's just how HA works

#

You can probably hack it as TheFes suggested

warm spoke
#

i think all of my grafana calls to HA are time series with a mean grouping, maybe because there isn't enough calls over a certain amount of time it just stops displaying the data because it doesn't have enough?

inner mesa
#

You would need to add a trigger, too

warm spoke
#

maybe that isn't explaining it properly... but i really don't understand it all myself which is why im asking for help... so ty in advance as well

#

SELECT mean("value") FROM "autogen"."%" WHERE ("entity_id"::tag = 'ParentEntity_AttributeEntity') AND $timeFilter GROUP BY time($__interval) fill(null)

#

ParentEntity_AttributeEntity are changed from what they actually are in HA

#

err. this may be the wrong chat for troubleshooting grafana query sorry

marble jackal
#

If it used a selection from the database that could indeed be the cause. If it doesn't change, nothing is written to the database

warm spoke
marble jackal
#

It should be an attribute of the sensor

warm spoke
marble jackal
marble monolith
warm spoke
#

i'll play around with that once i find the attribute code location

marble jackal
#

Unless you are using the legacy format, then you have to look at the bottom of that page

marble monolith
#

So my Electricity Meter does only deliver the Counter total kWh every 10s via a sensor. I would like to make a sensor that shows me current watt usage in my Home. I got an answer using the Derivative Helper but i cant figure out how to configure this to achieve my goal. It sounds so easy but yet i fail 😄

winter forge
pearl grail
#

Hello. I'm trying to calculate the average temperature for the next 24h.
The purpose of this is that I want to modify the temperature of my gas heater based on this avg temperature.
I tried this, but gives me the average for the next 24 days I guess. Or at least it's trying to.

{{ state_attr('weather.forecast_home', 'forecast')[:24]

  | map(attribute='temperature') | average | round(1) }}
#

I don't know how to access hourly instead of daily. Any ideas?

marble jackal
#

You need a weather integration which provides an hourly forecast

#

But using that attribute won't work on long term, it will be gone in two months

pearl grail
#

The default weather forecast have a hourly forecast. Can't I use that one?

pearl grail
marble jackal
#

Yes, use a trigger based template sensor and the weather.get_forecasts service call

#

There is an example in the docs

plain magnetBOT
marble monolith
#

TheFes, any tipps on my case?

pearl grail
#

Thanks!

marble jackal
plain magnetBOT
marble monolith
#

Alright, then ill try that. Thank you!

humble nova
#

I’m experiencing an issue with showing temperature from nspanels the way they are set in devices. In devices settings, I changed the default to showing 1 digit after the point (27.1 instead of 27.14621).
If I point to the temp entity using the mushroom chips card or sensor cards they show temp the way I want but when using the template cards (using the code), they display temperature the default way. How can I fix this? Is this an issue with the mushroom cards? This code pulls the temp the default way and not the way the entity shows. Puzzling thing is the code uses the entity id so not sure why this is happening.

{{ states('sensor.nspanel_livingroom_temperature') }}

I’m using the “secondary” field on my mushroom cards

marble jackal
#

The actual state still has the decimals, your setting is just applied in the GUI.
You can use

{{ states('sensor.nspanel_livingroom_temperature', rounded=True) }}
#

Or

{{ states('sensor.nspanel_livingroom_temperature', with_unit=True) }}

That will apply the rounding and add the unit of measurement

humble nova
#

@marble jackal thank you so much, helpful as always

slender laurel
#

I would like a binary switch to turn on when a value of a device is above 5, and turn off when the value of the device is below 1, but only when the binary switch is already on - these are power usages in W. Is a threshold helper a good way to accomplish this, or is this something I should do with a template.

mighty ledge
#

template binary sensor that uses those as triggers

slender laurel
mighty ledge
#
template:
- trigger:
  - id: 'on'
    platform: numeric_state
    entity_id: xxxxxxx
    above: 5
  - id: 'off'
    platform: numeric_state
    entity_id: xxxxxxx
    below: 1
  binary_sensor:
  - name: blah
    unique_id: 89124u32jlkjlfajoeijsef
    state: >
      {% if trigger.id == 'on' %}
        {{ trigger.id }}
      {% elif if trigger.id == 'off' and this.state == 'on' %}
        {{ trigger.id }}
      {% else %}
        {{ this.state }}
      {% endif %}
marble jackal
#

turn off when the value of the device is below 1, but only when the binary switch is already on
I don't get it, the alternative is that it is off. I don't see the harm in turning it off when it is already off

Especially when the trigger based template sensor like above is used, as that will restore the state, so it will not be unavailable

#

or am I missing something

slender laurel
marble jackal
#

but what would you like the binary sensor to be if the source sensor is unavailable?

slender laurel
marble jackal
#

okay, and is your actual goal to avoid getting notifications after a restart of HA?

slender laurel
marble jackal
#

use this in your automation:

trigger:
  - platform: numeric_state
    entity_id: xxxxxxx
    below: 1
    for:
      minutes: 1
condition:
  - condition: template
    value_template: "{{ trigger.from_state.state | is_number }}"
#

no need for that binary sensor

marble jackal
#

it will trigger as soon as your power value goes below 1 for 1 minute

#

and it will check if the previous value was a number

slender laurel
#

That's great, and clean!

floral shuttle
#

why would this state the wrong day {% set datum = states('sensor.afvalwijzer_next_date') %} {% from 'easy_time.jinja' import month, weekday %} {{weekday(datum) ~' '~ as_timestamp(datum)|timestamp_custom('%d') ~ ' '~ month(as_datetime(datum).month)}} 'donderdag' while tomorrow clearly is friday...

#

or a bit cleaner

#

this does work, but is so complex...```{% set next = 'sensor.afvalwijzer_next_date' %}
{% set dagnummer = as_datetime(states(next)).strftime('%w')%}
{% from 'easy_time.jinja' import weekday %}
{% set dag = weekday(dagnummer|int) %}

{{dag}}
{{weekday(states(next))}}```

floral shuttle
#

this should do it.... {% set datum = states('sensor.afvalwijzer_next_date') %} {% set stamp = datum|as_timestamp %} {% from 'easy_time.jinja' import month, weekday %} {% set dag =weekday(stamp|timestamp_custom('%w')|int) %} {% set datum = stamp|timestamp_custom('%-d') %} {% set maand = month(stamp|timestamp_custom('%m')) %} {{dag}} {{datum}} {{maand}}

floral shuttle
#

or {% set next = 'sensor.afvalwijzer_next_date' %} {% set date = as_datetime(states(next)) %} {% from 'easy_time.jinja' import month, weekday %} {% set dag = weekday(date.strftime('%w')|int) %} {% set datum = date.day %} {% set maand = month(date.month) %} {{dag}} {{datum}} {{maand}}. hmm more invlved than I would have hoped for

mighty ledge
#

check out the docs

#

for easy_time

mighty ledge
#

scratch that, wrong on that. But %w is 0 based, not 1 based.

#

so just add 1

floral shuttle
#

I had forgotten I needed to int that 0 number

mighty ledge
#

also, weekday from easytime only accepts numbers, not states from entities

floral shuttle
#

Didn’t I write a FR on that ?

mighty ledge
#

Yeah, but I haven't added it

floral shuttle
#

So much going on I forgot sorry

sonic sand
#

I moved to new house and now I'm getting an error when the call service of the telegram send photo should be sent to me with a snap of the aquarium camera, have no idea why it's happening..

service: telegram_bot.send_photo
data:
  authentication: digest
  file: /config/www/tmp/snapshot_aquarium_sub.jpg
  caption: "    {% if values.error %} 🐟 ❌ The fishes have not been fed at {{ values.timestamp }} ❌ {% else %} 🐟 The fishes have been fed {{ values.value }} portions at {{ values.timestamp }}. {% endif %}"

The error:

Error running action
Error rendering data template: UndefinedError: 'values' is undefined
inner mesa
#

where does "values" come from?

sonic sand
#

TheFes helped me a lot with those templates, it worked before I moved out here, now I'm getting an error on the telegram message part

mighty ledge
#

Nothing there is showing how values is created

#

Your template throwing he error is in the caption of your send_photo

sonic sand
mighty ledge
#

no it's not

sonic sand
#
    model: hfjh.fishbowl.v2
lan_ip: 10.0.0.142
entity_class: MiotSwitchEntity
miot_type: urn:miot-spec-v2:device:fish-tank:0000A0A2:hfjh-v2:2
fish_tank.on: true
fish_tank.water_pump: true
fish_tank.pump_flux: 100
function.ledboard_color: 0
state_updater: cloud
event.4.1: {"timestamp":1706808612,"value":[{"piid":16,"value":"2024,2,1,19,30,0,2"}]}
sub_entities: fish_tank-2.water_pump-2, function-4.ledboard_time_switch-8, function-4.feed_time_switch-11, function-4.key_switch-14, fish_tank-2.pump_flux-3, function-4.ledboard_color-5, function-4.ledboard_model-2, function-4.set_feed_single-1, fish_tank-2
device_class: switch
icon: mdi:fishbowl
friendly_name: Desgeo C series smart fish tank Fish Tank
supported_features: 0
mighty ledge
#

and if it is, we need to see it

sonic sand
#

inside event.4.1.

mighty ledge
#

right, but that's not being set anywhere

#

the template is getting values

#

it's not declared anywhere

marble jackal
#

Is that service call in an automation?

sonic sand
#

I can send the whole automation if needed

mighty ledge
#

it's needed

sonic sand
#

hold on

inner mesa
#

You're not setting values anywhere

#

It's a pretty clear error message

mighty ledge
#

it's in the variables section

sonic sand
#

so how did it worked before

inner mesa
#

Oh, at the bottom

#

That's why I write the YAML

mighty ledge
#

you'd have to view the trace, it seems that it's erroring and not creating the variable.

#

either way, the error seems impossible if the automation is actually running

#

because it is declared

#

are you copying and pasting that template into the service caller and testing it?

inner mesa
#

Probably just hit 'run'

sonic sand
#

I did hit run then this error shows up

inner mesa
#

Yep

mighty ledge
#

yeah, that's not going to work

#

it needs to run from a trigger

#

if you just want to test the actions separately, you should just make that a script.

sonic sand
#

wait i will send the traces

mighty ledge
#

no need

#

the issue is that you're clicking run

#

when you click run, it only runs the actions, nothing else

#

if you want to be able to click run, then you should make the variable section and the actions into a script. Then you can just click run on the script.

inner mesa
#

I also thought that it needed to be trigger_variables at that level

sonic sand
#

I clicked run after the automation failed just to make sure it wasn't the camera fault

mighty ledge
#

well the error you're pulling is only from the run

#

I'm not sure how much more I or rob can say this

#

if youre having a different problem, you need to post the different problem. The error you're getting is from you clicking run.

sonic sand
#

Triggered by the state of switch.hfjh_v2_eadb_fish_tank_2 at February 1, 2024 at 7:30:20 PM
Check if the switch didn't go from or to unavailable
Check if the values are correct
Call a service 'Camera: Take snapshot' on Aquarium Fluent
Stopped because an error was encountered at February 1, 2024 at 7:30:30 PM (runtime: 10.04 seconds)

That's the automation traces, before i clicked on Run

mighty ledge
#

well we need the error at February 1, 2024 at 7:30:30 PM

#

and if it's Error rendering data template: UndefinedError: 'values' is undefined then you're looking the wrong error

sonic sand
#

How can I get to this error via Traces?

mighty ledge
#

it's in your logs

#

whenever you see this Stopped because an error was encountered at February 1, 2024 at 7:30:30 PM (runtime: 10.04 seconds) that means there's an exception/error in your logs

sonic sand
#
Fish Fed Telegram Notification triggered by state of Last Fish Feed changed to February 1, 2024 at 7:30 PM
7:30:20 PM - 1 hour ago - Traces
Feeding is required changed to February 3, 2024 at 10:30 PM triggered by state of Last Fish Feed changed to February 1, 2024 at 7:30 PM
7:30:20 PM - 1 hour ago
Last Fish Feed changed to February 1, 2024 at 7:30 PM
7:30:20 PM - 1 hour ago

That's all I have on logs related to the fish tank today.

mighty ledge
#

ofir

#

please, look in your homeassistant.log file

#

you've been here long enough to know what the logs are

#

those are not the logs

sonic sand
#

thanks for helping me btw

mighty ledge
#

Your error is unrelated tot he template, the automation timed out creating the snapshot

sonic sand
#

What can cause that?

mighty ledge
#

an issue with the integration or an issue with the connection to the camera

sonic sand
#

ok, thanks!

terse nymph
#

Hi, i have a question regarding date and timestamp templating. When i use this piece of code the day (timestamp_custom("%A %d.%m.%Y") is displayed in english but my language settings are german. Any idea why the day is nevertheless displayed in english?

inner mesa
#

Templates aren't translated

warm spoke
#

only seems to update 'last updated' though, not 'last changed' which would make sense as teh value is relative static i don't expect it to change very much as it is % used on a backup drive

mighty ledge
mighty ledge
#

it just updates the entity in question

mighty ledge
terse nymph
#

german

mighty ledge
#

Yep, it's supported

warm spoke
#

i added all 4 entities to an update entity automation that runs every 30 minutes

#

the 'parent's both have 'last updated' update every 30 minutes

#

but the attribute do not update

#

im calling them parents because i don't know what else to call them

#

alias: "Refresh C: and D:"
description: ""
trigger:

  • platform: time_pattern
    minutes: "30"
    condition: []
    action:
  • service: homeassistant.update_entity
    target:
    entity_id:
    - sensor.parent1
    • sensor.parent2
      • sensor.attributetemplate1
      • sensor.attributetemplate2
        data: {}
        mode: single
mighty ledge
south scarab
#

Is there a way to make a templated rest_command that will take a number directly?

mighty ledge
#

Yes, the command itself can be a template

south scarab
#

How would I specify that?

mighty ledge
#

You can template the url or the payload

south scarab
#

so just "http://URL/{{ data }}" ?

mighty ledge
#

Yeah and you’d need to pass the data variable in the data section of your service call

#

You might want to use a different variable name so you don’t get confused

south scarab
#

would that go in the target?

mighty ledge
#

No, in data

south scarab
#

so If im making a button, I have a tap action:

tap_action:
  action: call-service
  service: rest_command.command
  target: {}

Where would I add my parameter?

mighty ledge
south scarab
#

Thank you, I got it to work now

bronze horizon
marble jackal
analog mulch
#

Hi. Maybe I am overthinking, but wanted to check. If I specify a datetime string with no timezone, will HA understand it as one in local time if I use "as_local". The dates are in the past, so in principle there could have been some change of DST with respect to the current time etc. If not, is there some way of taking care of this?

marble jackal
#

it will use the DST which applies to that date

dark rock
#

Hi! I'm making a sensor to represent the status of my standing desk and to use it as a input sensor for a history_stats sensor. The yaml seems to be working on developer tools, but then i don't know why is not showing on the entities page (I have saved and restarted HA VM). Code is:

      desk_standing_status:
        friendly_name: Desk sitting status
        value_template: >
          {% if states('sensor.desk_2995_height') | float < 0.9 %}
            Sitting
          {% elif states('sensor.desk_2995_height') | float > 0.9 and states('sensor.desk_2995_height') | float <= 1.15  %}
            Standing
          {% elif states('sensor.desk_2995_height') | float > 1.15 %}
            Walking 
          {% endif %}

(full yaml in https://pastebin.com/uU6Avw1C) Any clue what I'm doing wrong?

mighty ledge
dark rock
#

yes

mighty ledge
#

so you aren't using sensor: !include sensor.yaml?

dark rock
#

no I don't

mighty ledge
#

Ok then, the entity will appear in developer tools -> states page

dark rock
#

I should move it to there some day 🤣

mighty ledge
#

if you already have a sensor section, that would be the reason it's not showing up

marble jackal
#

unless you are declaring sensor: twice (another time below this one)

#

🐌

mighty ledge
#

TheSlowFes

dark rock
#

its showing up on there @mighty ledge

#

and also on the dashboard

#

I just had to wait 🤯

#

Thanks guys

uneven cloud
#

Hi all, QQ. I have a sensor for my car which is displaying the correct odometer reading, but the wrong units. (A bug in a depreciated integration). Can I use REPLACE on the sensor to change the text from km to mi?

#

This is all I have on my entity card at present

    name: Mileage ```
marble jackal
#

is the unit in the state itself, or in the unit_of_measurement attribute?

uneven cloud
#

It's in the state itself

marble jackal
#

if it's in the state you either need to use a custom card which allows you to overwrite the state in the card

#

or create a template sensor which does it in the state of the template sensor

#

but if it is indeed in the state itself, you can use replace to do that

uneven cloud
#

Great, thanks! How? 😂

#

I tried this, but don't know where to put it in the yaml
{{states('sensor.tmbbr8nxx_odometer') | replace("km", "mi")}}

marble jackal
#

create a template helper in Settings > Devices & Services > Helpers

plain magnetBOT
#

Open your Home Assistant instance and show your helper entities

marble jackal
#

and use that for the template

#

no YAML requred

#

that will create a new sensor

#

which you can use in your card

analog mulch
#

Is there some way I can load the weather.get_forecasts service's response variable into a variable I could then play with in the template editor?

inner mesa
#

there's no communication between the Services and Templates tabs, so you'd need to make the service call and then copy the response into the Templates tab when assigning to a variable

marble jackal
#

First convert it to json

quaint spoke
#

How would I set up a template helper that returns the amount of time since a certain entity switched from false to true?

silent vector
#

Is there a way in jinja from within a loop to increase the size of the loop itself?

#

As in add additional items to the loop

#

Or are you stuck with what ever is in your loop list at the time the loop starts.

{% for dolphin in ocean %}
{{ something something }}
{% endfor %}

In this example being stuck with whatever is in ocean at the start of the loop.

lucid thicket
#

Some front end cards will display this timestamp in a relative format that is easy to read (e.g. "two minutes ago"). If you want something more specific you can use a template card and format it however you desire

haughty breach
#

Just be careful you're not creating an infinite loop 🙃

silent vector
#

Interesting. Good to know.

cold geode
#

I dont know whats wrong with my template (im pretty new to ha)
as you can see in the screenshot the validation is just loading into eternity and never stops.
I also cant restart home assistant because of the following error:
" argument of type ‘NoneType’ is not iterable " .

This only takes place while i tried it with my custom template light i wanted to create. Can anyone tell me whats wrong with my template ligtht?
Here is the code: https://dpaste.org/D0cnu

If i remove the template there is no error at all and everything works fine.

haughty breach
#

Everything under treppenlicht: needs to be indented. Where did you add this i.e. which file?

cold geode
#

So should i just move it 2 spaces to the right?

cold geode
haughty breach
#

Then you need to remove the top light:.

cold geode
#

what exactly has to be indented?

haughty breach
cold geode
#

It worked thank you really much!

final trellis
#

I've setup local calendar and several automations that are triggered with some pir sensors.
When this happens, I get events with duration of 24 hours and then, if events > 0, I conditionally execute a TTS action which announce this events.

It's pretty simple and it covers me almost 100%.
But sometimes, with some very important events, if I don't trigger a PIR in time, I won't get an announcement.
And this might be a problem some times.

So I was wondering what is the best way to get a trigger before a calendar event occur ??
I've found a template that creates a sensor which gives the remaining minutes before an event occurs.

{{((state_attr('calendar.school', 'start_time') |as_timestamp|int - now()|as_timestamp|int)/60)|int}}

But is this the right thing to do? How to address it when you have multiple calendars?

marble jackal
#

Please don't crosspost

final trellis
#

am sorry TheFes, didn't mean it. I just did it because i didn't know where is the right to post it,

#

I just deleted it from automations

steep raven
#

not sure if i m in the right channel for this question but here i go: i have a sensor that gives out a kWh i want to create a new sensors out of this that resets every month to 0 but the original sensors sometimes goes to 0 for a short time and the nback to its original state. I do not need to have its value x2 then how can i do this? when i create a nutsmeter out if it that resets every month it adds up the value after what its at when it got to 0 for a short time....

marble jackal
#

@final trellis what is exactly your goal here. An announcement x minutes before a calendar event? You can use a calendar trigger for that

final trellis
lyric comet
#
platform: calendar
event: start
offset: "-1:30:0"
entity_id: calendar.work_days

Although I don't know why you could not have simply used the automation editor and done that yourself.

final trellis
#

Jane_t, I obviously read an old post which was saying that this was not possible.

final trellis
#

based on your recommendation I created the following automation which works
https://dpaste.org/ro0jK

thank you for that! My only problem is that if stataments inside message are not considered

#

would you please take a moment and have a look?

final trellis
#

is it because you can't put it on an IF statement ??

agenda['calendar.school'].events | count > 0
marble jackal
#

That template condition will always render true when the automation triggers

#

As it triggers one hour before the start of a calendar entry, there will always be a calendar which has an event

final trellis
#

I revise the code, but still doesn't work properly

#

it played only the school events. although there were events for calendar.makis, these events didn't TTS

marble jackal
#

Check your automation trace. Most probably they both worked, but are issues with microseconds after each other, so first one started, but got overridden by the second one

#

I would combine them in one TTS message

final trellis
#

i did but if statement is not working

#

see preious post

#

this is the reason I tried to change it

#

and also can the trigger combined to one?

trigger:
  - platform: calendar
    event: start
    offset: "-1:00:0"
    entity_id: calendar.school
  - platform: calendar
    event: start
    offset: "-1:00:0"
    entity_id: calendar.eleni
  - platform: calendar
    event: start
    offset: "-1:00:0"
    entity_id: calendar.makis
marble jackal
final trellis
#

TheFes, I said that this didn't work for me.
The if stamenets inside the TTS message was not consided

#

it played all three calendars, even though for calendar.eleni was no events

#

(but it anounced the name)

#

lines 42,49 and 59 didn't worked

#

can the if statement work like this ??

marble jackal
#

You might need to debug it a bit, I copied and pasted it on mobile

final trellis
#

I mean with agenda['calendar.school'].events

marble jackal
#

Use the service call in developer tools > service. Then convert the output to json using https://onlineyamltools.com/convert-yaml-to-json
Create a variable called agenda in devtools > templates using the json, and then test and tinker your TTS output message until you have what you want

final trellis
#

wow, dont know how to do this

#

i've got the json , but how to create a variable ?

marble jackal
#

{% set agenda = <json output> %}

final trellis
#

oh ok

#

this is great!! Today I knew something I didn't know

#

thank you for that +1

#

also my code is working as expected +1

#

so why TTS engine plays only the first part ???

#

I think it has to do with the trigger

#

they all triggered the same time and this confuse it

marble jackal
#

That template you now used was my proposal for the combined one right?

#

To have it all in one TTS message

marble jackal
#

Besides logging a warning that the automation didn't trigger because it was already running

final trellis
#

correct, but I still can't figure out why the template shows what is right and what I want and the TTS engige doesn't play it

marble jackal
#

Check the automation trace, it will tell you what it did

final trellis
#

found it!!

#

some extra spacing ...didn't let the code to be executed

#

thank you. about nabu casa cloud.say, does anyone know if there is a pause like alexa when you tts ??

marble jackal
final trellis
#

thanks

#

@marble jackal you got a coffee ....

marble jackal
#

I just saw the notification. Thanks, I will enjoy it ☕

final trellis
#

your welcome

bronze prawn
#

https://i.imgur.com/CawumtA.png

I could use some help. I'm trying to pull today's precipitation chance (see imgur image above) from weather.home . I have pulled attributes before but this one has a bunch of values listed each for the next five days. How can I pull just the value for today's percipitation chance using jinja (I will eventually need to do this in js but jinja call for now is fine).

marble jackal
#

@bronze prawn The forecast is a list, take the first item from the list and then the precipitation chance

#

state_attr('weather.home', 'forecast')[0].precipitation_probability

#

Do note that this attribute will be removed in a few months, you will have to use the service call to retrieve the data then

bronze prawn
#

Thanks for this. Oh yeah, I did see that as upcoming but until now, I had no need to think much of it. I'll take a look

ruby vault
#

how do I find out the integration name to use in auto-entities and integration_entities?

#

seems brute force guessing has worked today

marble jackal
plain magnetBOT
#

Open your Home Assistant instance and show your repairs

undone jungle
#

Hi all, probably a trivially simple question, how would go about calculating an average value of another sensor, though not taking into consideration values of the sensor when another binary sensor is switched ON.

#

More specifically, I'd like to calculate an hourly/monthly/yearly efficiency of my forced air ventilation system. My efficiency sensor goes to 0 however, when the bypass is switched on, so this would invalidate any sensible average.

#

I could probably indicate mathematically that the average should be non-zero average

#

But I was hoping to include a more mechanistic approach and use state of other sensors to inform the calculations of the average

#

This would be a super useful skill to have for me since I foresee using it in other templates as well.

#

Help will be greatly appreciated!

upper matrix
#

Hi I'm trying to write a template that lists all my plants that need watering.

I have the following so far

{% for plant in states.plant | selectattr('attributes.moisture_status', 'match', 'Low') %}
  {{- plant.name }} 💧{% if 'low' in plant.attributes.conductivity_status %}💩{% endif -%} {% if not loop.last %}, {% endif -%}
{% endfor %}

But how would I go about grouping by area?

marble jackal
undone jungle
#

I'll sit down to it and probably come back with questions. Thank you for the idea!

slate cobalt
#

How can I access the value of an attribute ? I tried this:
'{{ states("climate.thermostat_esstisch.attributes.temperature") }}'
but it returns always 'unknown'
I couldn't post pictures here (don't know why), here is a screenshot:
https://i.ibb.co/WBVF8Z7/Screenshot-2024-02-04-143409.png

lucid thicket
#

state_attr('device_tracker.paulus', 'battery') will return the value of the attribute or None if it doesn’t exist.

plain magnetBOT
#

@sharp night I converted your message into a file since it's above 15 lines :+1:

sharp night
#

Trying to setup a template for a weather station reporting it's battery status. I found this template sensor that seems to evaluate properly in the Template developer tools section, though it shows as "unknown". Upon further checking it looks like it's interpreting my battery voltage as a string:

ValueError: could not convert string to float: '# calculate percent from the voltage   # clamp the output to a 0-100% range 100'

The unit of measurement is mv for the source sensor in the template.

obtuse zephyr
#

Your "comments" aren't comments since they're outside the template

#

They are strings w/ the actual value 100 appended on the end

sharp night
inner mesa
#

Comments in Jinja must be surrounded by {# #}

sharp night
#

yeah, dumb mistake. i was just happy someone had already figured it out so i did the copypasta without even thinking about it. 🙂

distant abyss
upper matrix
distant abyss
upper matrix
distant abyss
#

If you get a working template let me know. What are you using instead of plants.yaml?

undone jungle
# marble jackal You could create a template sensor which uses your source sensor for the state, ...

Having looked into it, I know I am pedantic, though was wondering if there is a more elegant approach.
More specifically, I have the original ventilation efficiency, which is 0 when the bypass is open and 'something' then bypass is closed.
To use your approach, I need to first pull it's state and match it against the bypass being open of closed to draw 'non-zero' efficiency.
Then this would have another set of statistics platform sensors for the last hour/day/year created.

#

Is there really no way to use statistics platform-like sensor inside a template?

#
      - name: Effective ventilation energy efficiency 
        unique_id: recu_energy_efficiency
        icon: mdi:percent
        unit_of_measurement: "%"
        state: >
          {{ states('sensor.recu_energy_efficiency') | float }}
        availability: >
          {{ is_state('binary_sensor.ventilation_bypass', 'off') }}

Going from this into drawing an hourly/daily/yearly average:

usind something like:

    start: "{{ now().replace(hour=24).replace(minute=0).replace(second=0) }}"
    end: "{{ now() }}"
#

Am I overcomplicating it for the sake of having one entity vs. 2-3?

undone jungle
#

There is actually also a bit of an additional problem, which is that the statistics platform only allow max age so the monthly sensor would be the last 30 or so days and not a sensor for the month of march, june, etc.

marble monolith
#

So i im getting the total kWh value from my Power Box but i cant add it to my Energy tab, i Guess because i does not have the state energy class.

i tried adding this in my YAML but in it does not show my change in the developer tools. What did i do wrong?

homeassistant:
customize:
  sensor.tasmota_sml_total_in:
    unit_of_measurement: "kWh"    
    device_class: energy
    state_class: total_increasing
    last_reset: 1970-01-01T00:00:00+00:00
marble jackal
marble monolith
#

Could you point me in the right direction? Sorry i did not see any more fitting Channel

marble jackal
marble monolith
#

Thank you

undone jungle
grim geyser
#

Hello. How can I round this to the 1 decimal point? ```{% if is_state("climate.master_bedroom_ac", "cool") -%}
{{ states('sensor.master_bedroom_ac_9_1d') }} - kWh.
{%- else -%}

  • kWh.
    {%- endif %}```
inner mesa
#

Add |float|round(1)

grim geyser
#

thank you

plain magnetBOT
#

@undone jungle I converted your message into a file since it's above 15 lines :+1:

undone jungle
#

In other words, if left the way it is, the sensor will produce a result when the 'switch.hot_water` is on, but will produce a value of the main gas meter and not a separate meter that increases by only the delta of main gas meter value from the point the switch got activated.

#

I am sure there is a cool way of computing it, though I've not been succesful in finding it.

marble jackal
#

use a trigger based template sensor.
Might need some debugging though

- trigger:
    - platform: state
      entity_id: sensor.gas_meter_count
      from: null
  sensor:
    - name: Water heating gas energy consumption
      unique_id: water_heating_gas_energy_consumption
      icon: tc:dew-point-alternative
      unit_of_measurement: "kWh"
      device_class: energy
      state_class: total_increasing
      state: >
        {% set to = trigger.to_state.state %}
        {% set from = trigger.from_state.state %}
        {% if to | is_number and is_state('switch.shelly_hot_water', 'on') %}
          {% set previous = this.get('attributes', {}).get('previous', from | float) %}
          {{ this.state | float + to | float - previous }}
        {% else %}
          {{ this.state }}
        {% endif %}
      attributes:
        previous: >
          {% set from = trigger.from_state.state %}
          {{ from | float if from | is_number else this.attributes.previous }}
quasi frost
#

hey there, i need help using a template. I have no knowledge about template... 🙂
I want to make speak output on alexa device depending from the room where i am:
I already have the room tracking working. I write the actual room inside of a text helper: input_text.p_raumerkennung_input_sprachausgabe

Now i want to use the notify function to make speak output on alexa device. The alexa device is depending of the room.
How can i build that?

undone jungle
marble jackal
#

It should be placed under template:

marble jackal
#

don't start asking for responses within 10 minutes after placing your question

quasi frost
#

ok 🙂

marble jackal
#

what will be the state of that input_text?

#

you can probably do something like this:

{% set alexa_mapping = 
  {
    'room_1': 'media_player.alexa_room_1',
    'room_2': 'media_player.alexa_room_2',
    'room_3': 'media_player.alexa_room_3',
  }
%}
{{ alexa_mapping[states('input_text.p_raumerkennung_input_sprachausgabe')] }}
undone jungle
quasi frost
#

the state of input text will be variable. I want to use this input always if i want to make speak output on alexa device. Bit i have another state called "input_text.p_raumerkennung_aktiver_raum" this will be my trigger of the room

#

content of input_text.p_raumerkennung_aktiver_raum can be multiple rooms. For example Wohnzimmer, Flur, Schlafzimmer ect..

#

what i actually have as my tmeplate is:
trigger:
- platform: state
entity_id: input_text.p_raumerkennung_input_sprachausgabe
from:
to:
service: notify.alexa_media_schafzimmer
data:
message: {{ states('input_text.p_raumerkennung_input_sprachausgabe') }}

marble jackal
#

yes, so you need te define them all in that mapping

#

I guess you want to template the service call then, so notify.alexa_media_schafzimmer

quasi frost
#

i am right that this template already should trigger a speak output at the alex davice?

marble jackal
#

does the room always match the last part of the notify service?

quasi frost
#

no it doesnt

marble jackal
#

you won't have it there

#

unless you define it

#

like:

undone jungle
marble jackal
#
{% set trigger = dict(from_state=dict(state='100'), to_state=dict(state='110')) %}
quasi frost
#

i am not sure how to go on

undone jungle
marble jackal
#

you need to do the same thing there

marble jackal
quasi frost
#

yes

marble jackal
quasi frost
#

and it should right?

marble jackal
#
trigger:
    - platform: state
      entity_id: input_text.p_raumerkennung_input_sprachausgabe
      from: null
action:
  - variables:
      alexa_mapping:
        Schlafzimmer: notify.alexa_media_schafzimmer
        Flur: notify.alexa_media_1234qw45
        Wohnzimmer: notify.alexa_media_asdf556
  - repeat:
      for_each: "{{ states('input_text.p_raumerkennung_aktiver_raum').split(', ') }}"
      sequence:
        - service: "{{ alexa_mapping[repeat.item] }}"
          data:
            message: "{{ states('input_text.p_raumerkennung_input_sprachausgabe') }}"
#

sorry, had the wrong input_text

quasi frost
#

nice! Looks good, but the input eich de3vice should be make output is also a text helper. Its called "input_text.p_raumerkennung_aktiver_raum" Should this helper be used as "trigger" on wich room speka output will be make?

marble jackal
#

oh wait

#

multiple rooms

#

let me adjust it

#

adjusted

quasi frost
#

i got the output 'repeat' is undefined

marble jackal
#

how are you testing?

quasi frost
#

in the template editor

marble jackal
#

you can't test it there

quasi frost
#

on the upper right o got a red notification

marble jackal
#

run the automation by changing the input text

quasi frost
#

i did

#

still 'repeat' is undefined

marble jackal
#

where do you see that now?

quasi frost
#

screenshot

marble jackal
#

yes, I just explained you can't test this template in devtools > templates

#

you need to test the automation itself

#

and check the automation trace if ti worked

#

It relies on a variable created in the repeat loop

quasi frost
#

i am not sure if i understand you correct. There is actually no automation for the speak autput. Shouldnt the template do the output? I only have the input text helper and in your template example this helper is used correct?

marble jackal
#

in the step below, it splits the state of your active room input text into parts, based on the comma. So it will create a list of all the rooms in that input text

for_each: "{{ states('input_text.p_raumerkennung_aktiver_raum').split(', ') }}"
#

then it will do a notify service call for each of those rooms

#

meant to send out the notifications to the speakers when the input_text for the message changes

quasi frost
#

got that, but nothing happens

#

if i change the input. sprachausgabe

marble jackal
#

Did you change the data?

quasi frost
#

no

marble jackal
#

I provided gibberish notify services

#

you need to change it to the correct one per room, I have no clue what your notifcy services are

#

Also, everything is case sensitive, so the rooms have to be exactly like they are in your input_text

quasi frost
#

yes, i tested with the room Büro

marble jackal
#

What do you have now, as automation?

quasi frost
#

the value of input_text.p_raumerkennung_aktiver_raum isd actually Büro

#
trigger:
    - platform: state
      entity_id: input_text.p_raumerkennung_input_sprachausgabe
      from: null
action:
  - variables:
      alexa_mapping:
        Büro: notify.alexa_media_schafzimmer
        Flur: notify.alexa_media_1234qw45
        Wohnzimmer: notify.alexa_media_asdf556
  - repeat:
      for_each: "{{ states('input_text.p_raumerkennung_aktiver_raum').split(',  ') }}"
      sequence:
        - service: "{{ alexa_mapping[repeat.item] }}"
          data:
            message: "{{ states('input_text.p_raumerkennung_input_sprachausgabe') }}"
plain magnetBOT
#

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

marble jackal
#

please do that

#

if you have that, it should send a TTS message to notify.alexa_media_schafzimmer

#

which probably doesn't work, as I see there is an l missing

#

The whole idea of that alexa_mapping is to mach the rooms with the right notify service

quasi frost
#

git that

marble jackal
#

so you need to change that

#

you have this: Büro: notify.alexa_media_schafzimmer

#

is that correct?

quasi frost
#

so i removed the other "options"

#
trigger:
    - platform: state
      entity_id: input_text.p_raumerkennung_input_sprachausgabe
      from: null
action:
  - variables:
      alexa_mapping:
        Büro: notify.alexa_media_schafzimmer
  - repeat:
      for_each: "{{ states('input_text.p_raumerkennung_aktiver_raum').split(',  ') }}"
      sequence:
        - service: "{{ alexa_mapping[repeat.item] }}"
          data:
            message: "{{ states('input_text.p_raumerkennung_input_sprachausgabe') }}"
quasi frost
marble jackal
#

without the l?

quasi frost
#

yes, was a mistake while i setup the name

#

the device name

marble jackal
#

okay

quasi frost
#

but it is correct

marble jackal
#

so, you have this as an automation now

#

what happens when you change the input text? does the automatin get triggered?

quasi frost
#

where can i see if the autmation got triggered?

#

does the template generate a automation?

#

i am very nwe in HA, i used Iobrooker before..

marble jackal
#

The code above IS an automation

quasi frost
#

IS?

marble jackal
#

you should create an automation with that code

quasi frost
#

ahhh

#

thy for your patience... 😉
Yes, its triggering

#

i didnt know that i need to make a automation out of a template... 😉

#

now its working 🙂

marble jackal
#

A template on it's own doesn't do anything

#

you need to use it somewhere

quasi frost
#

i didnt know that 🙂

marble jackal
#

in an automation, or in a template sensor, or in a script

#

as you were providing a trigger and a service call, I assumed you were creating an automation

quasi frost
#

as i wrote, i came from the iobroker, and my thinking about automation is poisened 🙂

#

so looks good at all, i will know fill the alexa devices...

#

its working now, thank you very much! @marble jackal

undone jungle
#

Will see how it fares for my regular boiler kicking in.

#

Will report later today. Thank you again for the assistance!!

blazing axle
#

Hey y'all, anyone able to help me with a template binary sensor which so I can do the following: Can I set a time condition in an alert? So that the notification will happen only during certain times even though the boolean is turned on?

#

The alert itself is already setup, just not the part about in only sending the notification during certain times

marble jackal
#

go to Devices & Settings > Helpers and create a template helper with the type binary sensor.
Then paste this template in the respective field (adjust where needed)

{% set start = '09:00' %}
{% set end = '22:00' %}
{% set input_boolean = 'input_boolean.alert_washing_machine' %}
{{ is_state(input_boolean, 'on') and today_at(start) < now() < today_at(end) }}
blazing axle
#

Could you explain the logic behind this so I understand how it works? I'm sure it'll work, just trying to learn how exactly 😄

#

And the alert itself stays the same? As for the automation that turns the boolean on?

marble jackal
#

no, in the alert you use the newly created binary sensor instead of the input_boolean

#

in the automation you still turn the input boolean on

#

not sure what to explain about the template, the first 3 lines set some variables so it is more easy for you to know what to change

#

the last line outputs true or false, if it is true your binary sensor will be on, otherwise it will be off

coral garden
#

Hello

#

I have a sensor that I am turning into a template sensor to correct for inaccurate readings (it's a humidity sensor and I'm adding a constant as a calibration correction)

#

sometimes the sensor gives a 0 value and thus the template sensor returns just the calibration value which makes my graphs ugly

#

Is there a good way to filter out zero values of the sensor so that the template sensor is undefined or ignored or something so it doesn't show the incorrect value?

#

It seems that people haven't had success with trying to use the availability_template to ignore spurious values

mighty ledge
#

Post the template

#

@coral garden ^

coral garden
#
  - sensor:
      - name: "Livingroom Humidity C"
        unit_of_measurement: "%"
        state: "{{ (states('sensor.ble_sensor_livingroom_humidity') |float(0) + states('input_number.livingroom_humidity_correction')|float(0)) | round(2) }}"
      ```
#

can I use 'unknown'?

#

{{ 'unknown' if x == 0 else x|float(0) }}

mighty ledge
#
template:
  - sensor:
      - name: "Livingroom Humidity C"
        unit_of_measurement: "%"
        state: "{{ (states('sensor.ble_sensor_livingroom_humidity') |float + states('input_number.livingroom_humidity_correction')|float) | round(2) }}"
        availability: "{{ states('sensor.ble_sensor_livingroom_humidity') | is_number }}"
#

when sensor.ble_sensor_livingroom_humidity is not a number, it will go unavailable

coral garden
#

okay, so unavailable should prevent the value from being recorded? I read somewhere in the forums that availability wasn't preventing values from being recorded

#

it's an infrequent error so I'll have to test it for a while to see what happens

mighty ledge
#

but it won't affect your calculations

coral garden
#

great! thanks for the help

mighty ledge
#

np

plain magnetBOT
#

@rare schooner I converted your message into a file since it's above 15 lines :+1:

obtuse zephyr
#

Can't nest ' in ', just use " for the outer

mighty ledge
#

Also, you'd probably want float(None) there

#

Well, maybe not. nevermind

undone jungle
#

It seems like it's taking the original sensor state and not the delta

#

I've even tried setting the state to 0 assuming it was a momentary fluke, but it immediately returned to the state of the input sensor:
https://i.imgur.com/qmBNJaG.png

plain magnetBOT
#

@undone jungle I converted your message into a file since it's above 15 lines :+1:

undone jungle
#

Here is the sensor (inside a templates.yaml file).

#

Any assistance would be greatly appreciated!

blazing axle
marble jackal
#

ah, I know why that is, it already had a state from your old config

#

I also spotted a mistake on my end

undone jungle
marble jackal
#
- trigger:
  - platform: state
    entity_id: sensor.gas_meter_count
    from: null
  sensor:
    - name: Water heating gas energy consumption
      unique_id: water_heating_gas_energy_consumption_new_version
      icon: tc:dew-point-alternative
      unit_of_measurement: "kWh"
      device_class: energy
      state_class: total_increasing
      state: >
        {% set to = trigger.to_state.state %}
        {% set from = trigger.from_state.state %}
        {% if to | is_number and is_state('switch.shelly_hot_water', 'on') %}
          {% set previous = this.get('attributes', {}).get('previous', from | float) %}
          {% set delta = to | float(0) - previous %}
          {{ this.state | float + delta * 11.474 }}
        {% else %}
          {{ this.state }}
        {% endif %}
      attributes:
        previous: >
          {% set from = trigger.from_state.state %}
          {{ from | float if from | is_number else this.attributes.previous }}
#

make sure it has a new unique_id (I changed it above)

undone jungle
#

The gas meter count is in m3 and it must be converted by multiplication of 11.474

marble jackal
#

and the default in the float filter was missing

#

that really makes it a lot more complicated

undone jungle
#

That was my original way of going about it.

marble jackal
#

yeah, I was overthinking it

undone jungle
#

I'd have to produce the output in m3 and then feed this sensor into another for conversion.

undone jungle
marble jackal
#

okay, adjusted above

undone jungle
#

Shouldn't this be bracketed to have the addition before the multiplication?

#

{{ this.state | float(0) + delta * 11.474 }}

marble jackal
#

no

undone jungle
#

Won't this.state be still in m3 while delta won't.

marble jackal
#

no

#

the state is the state of your template sensor

undone jungle
#

OK, sorry, I may be missing the logical step somewhere.

marble jackal
#

that will start at 0 after creating, and will adding the deltas as soon as it starts working

#

so it will be a sum of deltas, which are all in kWh

undone jungle
#

I'd prefer having the unique_id the same - or at least this is how I had them until now

marble jackal
#

the unique id is just somehting in the backend

#

it can be a randomly generated uuid if you want

undone jungle
#

Sorry - OCD...

marble jackal
#

the name will determine the entity_id

undone jungle
#

But I will know... lol 🫣

marble jackal
#

delete the config

#

reboot

#

remove the entity entirely

#

reboot

#

create it again

#

that might work 🙂

undone jungle
#

OK, OCD cured by laziness....

mighty ledge
#

story of my life

undone jungle
#

Isn't it for all of us. It's just where we draw the line is what differentiates us....

undone jungle
# marble jackal ```yaml - trigger: - platform: state entity_id: sensor.gas_meter_count ...

Logger: homeassistant.config
Source: config.py:596
First occurred: 16:44:48 (2 occurrences)
Last logged: 16:45:16

Invalid config for 'template' at templates.yaml, line 108: invalid template (TemplateSyntaxError: expected token 'end of statement block', got 'integer') for dictionary value 'sensor->0->state', got "{% set to = trigger.to_state.state %} {% set from = trigger.from_state.state %} {% if to | is_number and is_state('switch.shelly_hot_water', 'on') %}\n {% set previous = this.get('attributes', {}).get('previous', from | float) %}\n {% set delta = to | float 0 previous %}\n {{ this.state | float(0) + delta * 11.474 }}\n{% else %}\n {{ this.state }}\n{% endif %}\n"

#

I can't seem to locate how I've messed it up.

mighty ledge
#

wrong syntax

#

post text next time

#

I'm assuming the 0 should be a minus

marble jackal
#

not sure what went wrong there

#

corrected it in my post above, should have been this:
{% set delta = to | float - previous %}

undone jungle
marble jackal
#

the default was not needed, as we already determined it was a number

#

you can round it if you want

undone jungle
#

I could round it with a float(0) to zero decimals / CORRECTED BELOW

marsh cairn
#

float(0) doesn't round. It uses the default 0, if the value isn't numerical

undone jungle
#

decimal(0)

mighty ledge
#

round(0) 😉

undone jungle
#

Not my day....

marsh cairn
inner mesa
#

How do I round a number? decimal(0)

undone jungle
#

Thank you all!

mighty ledge
undone jungle
# mighty ledge it's not a bad guess tbh
      state: >
        {% set to = trigger.to_state.state %}
        {% set from = trigger.from_state.state %}
        {% if to | is_number and is_state('switch.shelly_hot_water', 'on') %}
          {% set previous = this.get('attributes', {}).get('previous', from | float) %}
          {% set delta = to | float(0) - previous %}
          {{ this.state | float + delta * 11.474 | round(2) }}
        {% else %}
          {{ this.state | round(2) }}
        {% endif %}
      attributes:
        previous: >
          {% set from = trigger.from_state.state %}
          {{ from | float if from | is_number else this.attributes.previous }}

Why would it produce 4.474860000003757 ?

#

isn't the pipe after both the states enough to round it to 2 decimals?

#

I guess I am missing a parenthesis somewhere to make this work?

mighty ledge
#

You're only rounding the 11.474

#

(all your calc) | round(2)

#

pemdas

undone jungle
#

{{ (this.state | float + delta * 11.474) | round(2) }}

mighty ledge
#

parethesis, exponents, multiplication - division, addition - subtraction

undone jungle
#

I've tried it while you were typing and didn't work

mighty ledge
#

it works

undone jungle
#

OK, it must change state to take effect!

mighty ledge
#

gotta reload, make sure you didn't override your sig figs if you have a unique_id

undone jungle
#

I've reloaded the template_entities, but it didn't take effect until the state updated.

#

Once again, thank you for everyone's assistance!!

bronze tide
#

Hi folks! Is there any way to set an attribute of an entity? I know that state_attr(sensor.entity_id, 'current_temperature') is for reading an attribute. I could not find something for writing a value (in my case a float value) to an attribute.

inner mesa
#

You use service calls to actually do things

#

You can't modify the state or the attributes directly

#

Whatever is providing that entity should provide a way to change it, if it makes sense to do so

bronze tide
inner mesa
#

My point was that you use a service call. how you get there depends on your specific situation

bronze tide
#

ok

#

my problem is that I can create a namespace var and return it, but I cannot wrap my head around how the part of doing the service call with zero to a handful of records from the namespace is done.

inner mesa
#

I'm only getting bits and pieces of what you're actually doing, but if your goal with the template is to output a set of interesting entities, then you use that as a target for a service call

plain magnetBOT
#

@undone jungle I converted your message into a file since it's above 15 lines :+1:

inner mesa
#

there are a few issues in that code

#

as I think was pointed out, {{ this.state | float + delta * 11.474 | round(2) }} is rounding 11.474

#

and {{ this.state | round(2) }} is trying to round a string, which may work if they convert it to a float for you 🤷

marble jackal
#

round will actually do that

#

But the round filter is not needed there, the whole idea is that it will return the existing state, which should already be rounded to two decimals (if parenthesis would have been used)

heady trellis
#

Hello gang, a typical novice question.
I have filled an INPUT_DATETIME helper . I want to only print hours and minutes. How can this be done?

inner mesa
#

does it have a date or just a time?

heady trellis
#

It was set with the following JINJA2
{{ now().timestamp()|int + states('input_number.washing_expected_runtime')|int }}

inner mesa
#

Regardless, does it have a time or a date and time

#

You had to choose

heady trellis
#

Okee, in settings -> helpers it says Type: "date and/or time"

inner mesa
heady trellis
#

It was the 3rd option "Date and time"

inner mesa
#

then... {{ (states('input_datetime.whatever')|as_datetime|as_local).strftime('%H:%M') }}

heady trellis
#

Yes. This works. Thank you very much.

lament dust
#

Im not really sue if this falls into automations or templates, but I am trying to filter a sensor updates to an average .For conext, I have a distance sensor that updates ever 0.5 seconds and I want to take the average of the last say 5 seconds and use that as the actual distance

#

It seems the filter for average can only do this by minutes and hours though not seconds

summer salmon
#

hey, could use some guidance if anyone have any pointers it would be much appreciated.
i got this sensor that i want to shorten, its length and text varies
whats the best way to remove everything after the fourth "/"
/random/random/random/example/random/

lucid thicket
weak falcon
#

is there a way to take something that after a reset goes to 30% and then as it fills up goes to 100%, is there a way to make 30% be the new 0?

#

i can't do this on the device

#

and idc if i end up getting a different entity doing this

winter crescent
#

Hello everyone, I would like to finally bring my Luke Roberts lamp into HA The lamp can only be switched by rest without an app. I have the lamp so far that I can switch it on and off via restswitch, only with the brightness I stand on the spot what I have to enter behind Brightness: because a value is required. Ultimately, this should be a light template. Thank you very much. Here is the Rest_command code

    url: https://cloud.luke-roberts.com/api/v1/lamps/by_serial_number/1901ZH/command
    method: put
    headers:
      authorization: "Bearer XXX"
      accept: "application/json"
    payload: '{"brightness" : "??? "}'
    content_type: 'application/json' ```
obtuse zephyr
#

Are you asking what to use for ??? ? You can just use something like {{ brightness }} and then in the call to it, pass that value in as data

winter crescent
#

Yes, that was exactly my question, because I have the command with it for the time being in order to be able to process it in the template light. So does it have to work like this? Wow, I should have thought of that myself 😦
payload: `{{ brightness }}`

quasi frost
#

Hey there... I am trying to build a wokrtime counter. I want to Trigger a bolean Switch helper. If the helper is in the Templates should Count my working time. I found some example and configured IT to my conditions. I added this Code as a helper/Templates/binaray helper. But nothing Happen when try to Trigger.
'''
sensor:

  • platform: history_stats
    name: Living Room Main Light On Current Month
    entity_id: input_boolean.nebenjob_arbeiten_aktiv
    state: "on"
    type: time
    start: '{{ now().replace(day=1, hour=0, minute=0, second=0) }}'
    end: "{{ now() }}"
    '''
#

I also tryed state true, because its a bolean Switch helper i guessed the state should BE true instead of on. But both are Not working. Can someone Help me?

inner mesa
#

What are you hoping to get from that? I just copied exactly that definition into my config, changed the entity to a switch that I use regularly, and it created a sensor with a sane value

#
- platform: history_stats
  name: Living Room Main Light On Current Month
  entity_id: switch.office_desk_lamp
  state: "on"
  type: time
  start: '{{ now().replace(day=1, hour=0, minute=0, second=0) }}'
  end: "{{ now() }}"
quasi frost
#

The Sensor should Count the passed time between in and off

mighty ledge
#

that doesn't make sense

#

you're counting the duration the sensor is on, or the duration the sensor is off

#

over the given time frame

#

if you count both, it's just going to be whatever your time frame is

quasi frost
#

Of course IT should.only Count when the Switch is on. I dont need to Count my free time 🙂

mighty ledge
#

Ok, that's what Rob and your configuration will do

lyric comet
#

Also remember the history_stats do not update all the time, so you need to wait awhile to see them update.

mighty ledge
#

it has a polling rate

#

but the word trigger is sort of meaningless, are you talking about it changing state or triggering an automation?

quasi frost
#

I mean changing the state of the bolean Switch helper to on

mighty ledge
#

the history stats will only update once a minute

quasi frost
#

Should state "on" or "true" Trigger the Sensor?

Ok, so the Switch must be longer on then one Minute?

mighty ledge
#

the polling rate is once a minute

#

that means, it will only calculate once a minute

inner mesa
#

I note that it defaults to a unit_of_measurement of 'h', so maybe that's the problem?

quasi frost
#

Do you maybe know a better Option to Count working time?

mighty ledge
#

why do you need it to be better than once a minute?

#

it's work hours

quasi frost
#

I mean "better" in a easyer way f.e.

mighty ledge
#

after your work day, it'll show whatever you worked that day, it doesn't need to be instant. If you want instant feedback when you get to work, use the input_boolean

#

History stats is the easiest way to track time a sensor has been on

quasi frost
#

And IT would BE okay for me

#

Alright, so again the question about what should BE the correct Trigger state. "on" or "true"?

mighty ledge
#

"on"

quasi frost
#

Alright, i will Check it now again.

mighty ledge
#

exactly like rob and your configuration

quasi frost
#

I switched on more then 2 minutes before. But nothing Changes in the Template Details. Shouldnt IT be displayed?

mighty ledge
#

what do you mean "It be displayed"

#

the entity should instantly show up

#

if it's not showing up, you're not putting it in the correct spot

#

It will have a state directly after startup too. Then it will update once a minute.

#

So there's 2 things you could be doing wrong.

  1. You're assuming reload yaml will reload this integration. It will not if you just added it for the first time. Reload only works after you add an integration for the first time & restart.
  2. You're putting it in the wrong spot in configuration.yaml. Either you've duplicated the sensor section or you've put it outside the sensor section.
#

I'm guessing you sorted it out?

quasi frost
#

Correct 🙂

#

Do i need to add the Code to the yaml? I thought i Just need to make a new helper/Template?

mighty ledge
#

the code is yaml

#

it's the history stats integration

#

it has nothing to do with tempaltes other than it uses some templates in it's configuration

#

Did you paste that into the template helper in the UI? If yes, that's your problem. That's only for the template integration.

quasi frost
#

ah ok, i still struggeling to get in touch with the different meanings

#

i just went from iobroker to ha

#

so, sorry for that

mighty ledge
#

template integration uses jinja templates

#

this channel is for jinja templates

quasi frost
#

yes, but its very confusing to understand that fast

#

i added the code to the configurationyaml.
Now i get this information:
Platform error 'switch' from integration 'history_stats' - No module named 'homeassistant.components.history_stats.switch'

#

i am guessing the history data integration is missing? is that the problem?

mighty ledge
#

it needs to go in the sensor section, not switch section

#
sensor:

not

switch:
quasi frost
#

yes, i found it also

inner mesa
#

That's what you had originally

#

the "1000 cats on typewriters" method of debugging

quasi frost
#

🙂

#

looks like its working

#

now

#

is it possible to reset the counter?

mighty ledge
#

the reset occus based on the start time

plain magnetBOT
#

@lethal bison I converted your message into a file since it's above 15 lines :+1:

lethal bison
#

from my tests, looks like a no. HA removes the string after the variable. I think I need to move the quotation to after the string, at least

lyric comet
#

You also need to define your variables BEFORE you use them.

lethal bison
#

so for clarity, "before" means at a higher yaml level, not physicaly above?
I only mention this because the visual editor places the variables block at the bottom of the automation

#

This seems to work:

action:
  - service: script.utility_notification
    data:
      name: "{{ trigger.id }}"
      emojis: "{{ chosen_emojis }}"
variables:
  chosen_emojis: |
    {% if 'dryer' in trigger.id %} 👕👖♨️
    {% elif 'washingmachine' in trigger.id %} 👚👕
    {% elif 'dishwasher' in trigger.id %} 🍽🍳
    {% endif %}
inner mesa
#

With that, you're putting it at a higher/larger scope

#

Before, you were setting the variable at a later step in the action. They are processed in order

lethal bison
#

I get it, because the action: is processed as a list

marble jackal
#

the variables section is processed after the trigger, before the conditions are checked

#

you can already use them in conditions

plain magnetBOT
#

@worn dust I converted your message into a file since it's above 15 lines :+1:

lethal bison
#

possibly type conversion? What does traces show?

#

also, I don't have the data to back this up, but I've never liked using the hash values for device_id. Try using the entity_id for the thermostat instead (if you only have one, you could also use entity_id: all)

worn dust
winter crescent