#templates-archived

1 messages Β· Page 56 of 1

mighty ledge
#

Ok so when I put this into a template sensor in the helper section

#

the helper section is only in the UI

#

so, what did you mean by that

jagged rivet
#

I forgot to update you on what I did. I deleted my first attempt, the one with the error, and recreated it. It is still a template sensor with the same ui then when I created it when I open the helper up again.

mighty ledge
#

you aren't understanding

jagged rivet
#

I am not, you are right

mighty ledge
#

Are you using the UI to create this entity? Yes or No?

jagged rivet
#

Yes

mighty ledge
#

Ok, then you cannot make a trigger based template sesnor via the UI

#

So, the behavior of your template sensor will be different

jagged rivet
#

I can not find good examples online to create this kind of template sensor that are in the new style of script. It really trips me up attempting anything remotely advanced in yaml atm :/

#

I see

mighty ledge
#

Also, because you're creating a new sensor that has a different unique_id, it** will not replace your existing entity.** That means you're old entity will remain and will have an unavailable state. Your new sensor will have a new name and entity_id.

#

so theres 2 things your doing wrong

#
  1. Looking at the wrong entity
  2. expecting the behavior to be the same
jagged rivet
#

Yes it is called the same. You said what was wrong. What do you propose I do to make this work? Do this in yaml editor?

mighty ledge
#

why are you recreating it, just keep your old one

jagged rivet
#

I don't know petro. I am experimenting and trying things that might work to create experience.

#

I am working with limited knowledge here. I am learning πŸ˜…

#

When I pasted and changed TheFresses example in my sensor yamls, I got a ton of errors. I disregarded the idea that TheFes made mistakes and assumed I was using it in the wrong spot.

marble jackal
#

it should not be in sensor.yaml

jagged rivet
#

Alright that's what I thought. But also not in helpers?

marble jackal
#

the first line is template, not sensor

#

you can put template: !include templates.yaml in your configuration.yaml and put it in templates.yaml (remove the first line with template: though)

jagged rivet
#

I see my mistake now. Thank you

#

I do have that

marble jackal
#

okay, that's where it should be then πŸ™‚

jagged rivet
#

Yes it feels right at home there

jagged rivet
#

It's purring along as a test and I am now trying to make a statistics graph from it but it's not letting me check any stat type

#

I want to show one card that displays the number of liters pumped up live when it is pumping and reset every day and I want do display a bar graph of pumped amount per day.

marble jackal
#

you need to add at least a unit_of_measurement but I would also add state_class: total_increasing

jagged rivet
#

I do have unit of measurement, device class and now state class

#

What is it called again; to drop the numbers after the comma? I want to add that too

#

Fantastic! State class did the trick! I can now show changed state on a daily basis with bars

neon bolt
#

Hi, could someone help me on how I can make a condition that check if the value into my nest thermostat target_temp_high and compare it with a numeric field?

cursive berry
#

what is the correct syntax to check for a string inside a calendar event title in an automation with a calendar event trigger? I know I have access to the trigger.calendar_event.summary variable but cant figure out what the function is to check for the required string.

inner mesa
#

{{ 'foo' in trigger.calendar_event.summary }} @cursive berry

vestal reef
#

Could You please help me on esphome. My homeassistant has been installed on raspberry pi 4. I have a temperature sensor that connected to esp32 via SPI and that esp32 connects to Homeassistant. I have a another esp32 in aanother location. I want to read that temperature and out put that value on esp32 uart for experiment. I may attache a large seven segment later. I tried to do this with esphome assistant custom cocomponent so i could write arduino code in as seperate include file. But didnt work. It says temperature sensor id is not in this scope . Couldn't you Please tell me the proper way to do this. Thank you.

odd marsh
#

Hello πŸ™‚

#

I need a little bit of assistance with a template πŸ™‚

#

User input malformed: invalid template (TemplateSyntaxError: expected token 'end of statement block', got 'float') for dictionary value @ data['state']

fossil venture
#

Are you going to share your template?

odd marsh
#

{% set energy =
states('sensor.kwh_24_hours')
%}

{% set house =
states('sensor.heat_pump')
%}

{{ ((energy - house)) }}

fossil venture
#

{{ states('sensor.kwh_24_hours')|float(0) - states('sensor.heat_pump')|float(0) }}

#

States are strings. You have to convert them to numbers before doing math with them.

odd marsh
#

Ahhh okay πŸ™‚

#

let me try that

fossil venture
#

You should use an availability template as well if you are going to use this with the energy dashboard.

#

availability: "{{ has_value('sensor.kwh_24_hours') and has_value('sensor.heat_pump') }}"

odd marsh
#

It works πŸ™‚ What does the availability do?

#

No, I am not very happy with the energy dashboard so I am working on making my own

marble jackal
#

But that error didn't came from that template, there is no float in that template, so it can't be that one.
That template would have given TypeError: unsupported operand type(s) for -: 'str' and 'str'

wraith shell
#

Hi guys

#

how can I know the amount of active persistent notifications? I used to have this template but for some reason it stopped working after updating

#

{{states.persistent_notification | length }}

#

I don't see persistent notifications as entities either...

marble jackal
#

that's right, those have been removed a couple of months ago already

#

I know @floral shuttle had issues because of this as well, he might created a work around for it

odd marsh
#

Thanks for the template πŸ™‚ It works perfectly just the way I need it

floral shuttle
#

this consists of a trigger template which you can use to show the notifcations in let's say a markdown, and count them. Next to the counter, I also made a binary sensor for any alarm on existing notifications in the UI, and lastly, I built a system where a boolean is toggled per notification (as stated in the yaml you need to create those manually) and then can show individual card with alarms on those. Or, dismiss the notifications by means of those booleans

floral shuttle
#

changed my expand templates to use state_attr() and see startup errors on these {%- for s in state_attr('binary_sensor.active_devices','entity_id') if states(s) == 'on' %} {%- if states[s].last_changed.day == now().day %} {%- set stamp ='%H:%M' %} {%- else %} {% set stamp = '%d/%m - %H:%M' %} {%- endif %} {%- if loop.first %} {% else %}, {% endif -%} {{states[s].name}} ({{as_local(states[s].last_changed).strftime(stamp)}}) {%- endfor %}

#

bottomline:homeassistant.exceptions.TemplateError: TypeError: 'NoneType' object is not iterable

#

do I have an obvious mistake here?

#

same goes for bject of type 'NoneType' has no len()') while processing template 'Template<template=({{state_attr('switch.critical_switches','entity_id')|count}}) renders=4>' for attribute 'aantal' in entity 'sensor.kritieke_schakelaars_samenvatting'

#

so even though these templates check a core ha helper group, they are not available on startup? after startup they populate correctly

mighty ledge
#

No obvious mistake but there's no reason to change that from expand.

#

you're accessing the state object in the first one, that should remain expand

#

the second one you can use {{(state_attr('switch.critical_switches','entity_id') or [])|count}}

floral shuttle
#

originally I had {%- for s in expand('binary_sensor.active_devices') if s.state == 'on' %} {%- if s.last_changed.day == now().day %} {%- set stamp ='%H:%M' %} {%- else %} {% set stamp = '%d/%m - %H:%M' %} {%- endif %} {%- if loop.first %} {% else %}, {% endif -%} {{s.name}} ({{as_local(s.last_changed).strftime(stamp)}}) {%- endfor %}

#

and that never threw errors. However, TheFes figured why expand to the full state object, not required, so this would be faster/more efficient?

#

my counters were also simpler:{{expand('binary_sensor.active_devices')|count}}

#

but again there, why use the full object if not perse required, causing more memory usage?

mighty ledge
#

the only way you'd make it faster is if you actually make use out of generators

#

which you aren't doing, so it doesn't matter

floral shuttle
#

for testing purposes I added that same or [] to the other templates, and all startup errors are gone.

mighty ledge
#

just keep in mind that only works when state_attr returns None

floral shuttle
#

ok noted. as was the case here.

cursive berry
wraith shell
#

I love HA. It's got the greatest ability to break the simplest things and make you nuts in order to fix them.

#

It's easier to just turn on/off the lights manually than keeping HA updated lol

#

thanks you all

#

I'm selling everything

heavy crown
wary yew
#

I have a binary sensor created manually that I want to disable at times. I have been told the only way is templating it into another sensor. Can someone advise how to do that?

- platform: ping
  host: 192.168.1.159
  name: LG TV Online
thorny snow
#

hey

#

can someone help me on this
Hey can someone help me to create a sensor? Basically i have 2 sensors. One that tells me it the energy is reverser or forward and another that tells me the energy What i need is if the sensor.direction == reverse the energy value should be negative if it is forward should be positive. I try so many things but i cannot make it work. and somethimes other sensors stop work :/

mighty ledge
#

if yes, you have to use the spook integration

#

it's custom

wary yew
#

yeah. But tbh I just found that I won't need it.

wary yew
mighty ledge
#

the alternative is manual enabling/disabling

wary yew
#

can't be done for yaml sensors, that's the thing.

plain magnetBOT
#

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

mighty ledge
#

then your only option is spook

mighty ledge
marble jackal
hybrid merlin
#

Is there a way to pull out the next event time (or time until next event) for a specifically named recurring event on a Local Calendar?

For example, if I have a calendar with "Event A" recurring twice a week and "Event B" twice a month, is there a template I can use to create template sensors to tell me when the next "Event A" and when the next "Event B" is? Or do I need to use separate Calendars for that?

wary yew
marble jackal
#

Using an availability template

mighty ledge
#

that can only be done by disabling the entity

#

manually or with spook

marble jackal
#

yeah okay, you could create a template binary sensor out of it, and make that one unavailable. But to disable it you need to use spook or do it manually

paper hazel
#

Is it possible to use this while creating a list in a template```
states.light | << other selectattr >> |
selectattr('last_changed', 'lt', '10') |
map(attribute='entity_id') | list }}

inner mesa
#

last_changed is a datetime, so comparing it to 10 doesn't make sense

paper hazel
#

Thx - Did a crude work around, still to be tested... fingers crossed. My aim is to create a list of lights that turned off in the last x amount of seconds that I can then pass to a service as the entity_id target

inner mesa
#

then you want something like selectattr('last_changed', 'lt', now() - timedelta(seconds=10))

#

or maybe selectattr('last_changed', 'gt', utcnow() - timedelta(seconds=10)), since I think it's in UTC

paper hazel
#

Thank you! Much cleaner as the solution I currently have πŸ™

inner mesa
#

you want gt if you want the lights turned off in the last 10 seconds. I changed it

paper hazel
#

Appreciated... My brain is fried now - Will finish up tomorrow, also discovered that my automation bombs on the conditions. The error in the log says: In 'template' condition: UndefinedError: 'list object' has no attribute 'startswith' In```
- condition: template
value_template: >-
{{ not trigger.event.data.service_data.entity_id.startswith('light.browser') }}
- condition: template
value_template: >-
{{ not trigger.event.data.service_data.entity_id.endswith('doorbell_flash') }}
- condition: template
value_template: >-
{{ not trigger.event.data.service_data.entity_id.endswith('control_screen') }}
- condition: template
value_template: >-
{{ not trigger.event.data.service_data.entity_id.endswith('control_screen') }}
- condition: template
value_template: >-
{{ not trigger.event.data.service_data.entity_id.startswith('light.swimming') }}

#

The triggers do seems okay in the trace```
trigger:
id: '0'
idx: '0'
alias: null
platform: event
event:
event_type: call_service
data:
domain: light
service: turn_off
service_data:
entity_id:
- light.master_bedroom
- light.master_bedroom_led

#

Its most likely because it is a list and not a single entity

#

Will perhaps move the conditions to the actions in a repeat or something similiar

#

My starting point will be TheFes's suggestion of using this:```
variables:
trigger_entities: >
{% set e = trigger.event.data.service_data.entity_id %}

{% if e is not string %}
{{ e }}
{% else %}
{{ [e] }}
{% endif %}

inner mesa
#

that would do it

analog mulch
#

What’s the right way to store a data table in HA? I want to set up some template sensors to calculate eg temperature anomalies versus a long term average which I have as say a table of floats with a row for each of the weeks of the year.

plain magnetBOT
#

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

ember otter
#

uh ok lol, don't think that was necessary but sure

#

will further note: i've already reloaded config, restarted HA, checked FAQs and documentation, etc... about all I can say is that I'm probably glancing over the obvious answer like an idiot lol

marble jackal
#

Where did you place this?

ember otter
#

in the configuration.yaml. is that not where they are supposed to go?

#

okay so I finally got something to show up as an entity but it didn't show as available at first - turns out something was being misunderstood with the availability template? so I just replaced it with
{% if is_state('binary_sensor.garage_available', 'on') %} yes {% else %} no {% endif %}

#

of course I have yet to test if the template cover works...

#

yep it works!*

* -it clearly still has a problem with not differentiating between the door being stopped & the door closing/opening, but that's a problem for tomorrow morning, it's 1AM and I can't be bothered rn lol, I achieved my goal of making an entity that triggers the button & displays the current status of the garage so I'm satisfied for now

marble jackal
#

That will return true or false which is what it expects

ember otter
#

i think that's what I did first, but it then caused the template cover to forever be stuck unavailable, even though the entity was not in that state

thorny snow
marble jackal
#

Should work fine

marble jackal
thorny snow
plain magnetBOT
#

To format your text as code, enter three backticks on the first line, press Shift+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
#

If it's energy I would expect kWh

thorny snow
#

i will try

plain magnetBOT
#

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

thorny snow
#

do you feel it is ok ? πŸ˜„

#

when i add this new sensor every sensor into this template stop work

marble jackal
#

Compare the first one with the second one

#

You are using state in the first one, and value_template in the 2nd

thorny snow
#

what is the diference between them ?

#

i cannot mix them into a template ?

marble jackal
#

value_template is used in the legacy format, which you are not using

thorny snow
#

Hey there,

#

I got a hommatic hm-es-tx-wm to track my electricty statusmeter (consumption and returning to grid). Unfortunately I only get the overall values in kWh and the current values in W. So my energy dashboard displayes a daily consumption of e.g. 25000 kWh... How can I get the difference from yesterday to now to display the todays consumption in the energy dashboard?

thorny snow
#

The historic data is persisted. So If I open the sensors details I can see past values.

marble jackal
#

In basic a lifetime sensor is best for the Energy Dashboard

thorny snow
#

I thought that the energy dashboard displays the daily values.

#

But I will move this there. Thanks

quiet kite
#

stipid question... Why i dont see this sensors in my ha after reload and restart:

[core-ssh config]$ grep sensors configuration.yaml 
sensor split: !include_dir_merge_list includes/sensors/
[core-ssh config]$ cat includes/sensors/energy_sensors.yaml 
# sensor:
- platform: template
  sensors:
    tuya-zmywarka_voltage:
      value_template: >-
        {{ states.switch.zmywarka.attributes.voltage }}
      unit_of_measurement: "V"
#

... invalid slug tuya-zmywarka_voltage (try tuya_zmywarka_voltage)

#

how can i do this Developers Tools > Check config from CLI or VSS code extensions?

inner mesa
#

it tells you what the problem is

#

and what to do about it

quiet kite
#

yes, i resolve my problem with - in name... but how can i execute check config from CLI? ha os check dotn show this errors

plain magnetBOT
gusty pulsar
#

Evening All, I've got an automation that triggers based on any update to an entity but I need to ensure the automation doesnt run if the previous state was unavailable / unknown.

Can I use a template condition with {{ trigger.from_state.state not in ['unknown', 'unavailable'] }} for this?

marble jackal
#

Or just add this to the state trigger

not_from:
  - unavailable
  - unknown
#

But your solution would also work

gusty pulsar
#

Would that go in the yaml of the trigger?

marble jackal
#

Yes

#

If you are using a state trigger

gusty pulsar
#

Thank you πŸ™‚

ruby vault
#

hi, can I use the 'this' (described here) object in a condition of an automation? If so, hwo is it refernced? 'this.state.attributes' or something else?

marble jackal
#

this in and automation will refer to the automation itself, if you need the attributes you will need to use this.attributes

sly adder
#
sensor:
  - platform: rest
    resource: https://api.nasa.gov/planetary/apod?api_key=API_KEY
    name: "NASA Astronomy Picture of the Day"
    scan_interval: 3600
    value_template: "{{ value_json.hdurl }}"

Hi all, I keep getting a "'value_json' is undefined" error when trying to get the picture of the day from NASA's API. I can access the URL just fine with curl. What is the issue here?

heavy crown
sly adder
#

Hm without the interval I still get "unknown"

#

and in the template editor I get the JSON eror.

heavy crown
#

error when you use the json ?

sly adder
#

I mean when I put this code in the Template Editor of the Developer Tools section

heavy crown
#

and if you are blocked, removing the interval will not help

#

which code? the one with the url? that will not work of course as template editor will not get the json

sly adder
#

ah so I cannot test it there?

#

can I test it anywhere else before putting it in my YAML files

#

without having to restart HA each time

heavy crown
#

you donot need to restart... in devtools/yaml you can reload the rest but again, above works fine for me so I think you have another problem, maybe too often, maybe your HA server has a hick-up on this address?

#

you can put logging to debug for rest, restart HA and then see if more is shown

#

other wise you can use the url in browse, copy the json in the template editor and setitng it simialr as the one that is shown by default...then add your sensor from above and see what happens...again, from my pov it is not the sensor

sly adder
#

Thanks πŸ˜„

#

ah it works now!

#

but still, just reloading YAML made the sensor disappear

#

when I fully restarted again, it suddenly showed up with the correct information

full crescent
#

I am finding that where this works fine:

condition:
  condition: template
  value_template: |-
    {% from 'logic_chekr.jinja' import true_all %}
    {{- true_all( ['binary_sensor.dark_outside'] ) | bool -}}

This does not. This renders a true and the execution stops with the shortcut syntax.

condition: |-
  {% from 'logic_chekr.jinja' import true_all %}
  {{- true_all( ['binary_sensor.dark_outside'] ) | bool -}}
#

Can anyone else verify that the custom templates cannot do the shortcut notation, or did I mess that up syntax wise.
No HA errors I do not believe.
Update... Check that, there was an error...

while parsing a block mapping in "/config/./automation2/Outside_A2.yaml", line 5, column 5 expected <block end>, but found '<scalar>' in "/config/./automation2/Outside_A2.yaml"
granite bear
#

Hello, could someone help me with some Jinja? Is this the place?

full crescent
#

right place

granite bear
#

I have this codnition that does somethign when a condition is met

#

{{is_state_attr('sensor.octopus_energy_electricity_xx_xx_current_rate', 'current_day_min_rate', states('sensor.octopus_energy_electricity_xx_xx_current_rate')|float)}}

#

How do I trigger something if it is not true?

marble jackal
thorn harness
#

Hello together. @marble jackal helped to modify a blueprint, thanks for that. I want to extend it, but i am not sure, if this is the right way. What do i want to achieve: We have a lot of danfoss ally room thermostats, which could be updated in "covered" or "uncovered" mode. For both situations, it is needed to update the temperature from time to time. For the covered mode, which i prefer, it is needed to update the time -> minimum 5 minutes AND more then 0.1 degree temperature change OR when the timer is finished if there is no temperature change. with the first blueprint, only min timer works. The same is for uncovered mode, but with different times cycles. I think there is something wrong with the timer at my try, which seems not to be defined and not restarts, if fired from event. May someone take a look at it? πŸ™‚

original one: https://dpaste.org/tOVPt
modified one: https://dpaste.org/UeqQP

marble jackal
#

@full crescent This would work

condition: 
  - >
      {% from 'logic_chekr.jinja' import true_all %}
      {{- true_all( ['binary_sensor.dark_outside'] ) | bool -}}
marble jackal
distant plover
languid pendant
#

g'mornin yall. I have an auto-entities card that I'd like to list all entities with regex; "/^media_player(.).*_mrp_active/" doesnt seem to work - can someone point out what I have wrong?

#

I spoke too soon - I dont know what it was doing

junior jasper
#

how come my template which i saved as a template itself is working and giving me a percentage output, but my automation does not react to it?

marble jackal
#

@full crescent I think my indentation was wrong before, I changed it above

thorn harness
#

Hmm.. Maybe someone has an idea why i get this error? From my understanding, max update timer is defined!?

Executed: 16. Oktober 2023 um 14:56:42
Error: In 'template' condition: UndefinedError: 'max_update_timer_id' is undefined

marble jackal
#

is this about the modified blueprint above?

thorn harness
marble jackal
#

The error is a bit strange, as it is one of the input selectors

thorn harness
#

well, it does not work πŸ˜… i am also not sure, if the modifications i made, make sense how i did them.
If temperate difference is above 0.1 degree AND timer is above 5 minutes, then make action. OR maximum timer time reached if no temp difference is happening , also fire the action, which should set a new time and gives a timer loop.

Step detaills shows me:
Executed: 16. Oktober 2023 um 15:13:42
Error: In 'or' (item 2 of 2): In 'template' condition: UndefinedError: 'max_update_timer_id' is undefined
conditions/0
Executed: 16. Oktober 2023 um 15:13:42
Result:
result: false
conditions/0/conditions/0
Executed: 16. Oktober 2023 um 15:13:42
Result:
result: false
entities:

  • sensor.average_temperature_badezimmer
  • number.tcv_badezimmer_external_measured_room_sensor
    conditions/1
    Executed: 16. Oktober 2023 um 15:13:42
    Error: In 'template' condition: UndefinedError: 'max_update_timer_id' is undefined
thorn harness
#

at the template editor i also get this error!?
'timer' is undefined

{{ states((timer.timer_badezimmer), 'last_triggered') }}

obtuse zephyr
#

quote the entity id

#

you've got extra parens, too

thorn harness
#

{{ states(("timer.timer_badezimmer"), 'last_triggered') }} ?

Thanks @obtuse zephyr it found the timer now! Will reboot HA and hope that it works now πŸ˜„

marble jackal
#

still extra parenthesis

thorn harness
#

Hmm.. Now i git this error:
Error: In 'template' condition: TypeError: unsupported operand type(s) for -: 'datetime.datetime' and 'str'

state_attr fixed it.

thorn harness
#

:\ Whatever i do - now the timer is always "true" - it doesnt matter if the time is running or running out. i tried two things:

    value_template: >
      {{ as_timestamp(now()) - as_timestamp(state_attr("max_update_timer_id",'last_triggered'),0) < 60 * "max_update_minutes" }}

    value_template: >
      {% set last_trigger = states((max_update_timer_id), 'last_triggered') %} {{
      last_trigger is none or now() - last_trigger >
      timedelta(minutes=max_update_minutes) }}
plain magnetBOT
#

To format your text as code, enter three backticks on the first line, press Shift+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
#

the quotes around max_update_timer_id in the first one are wrong, that makes it a string, and not a variable

#

your are still using double paranthesis in the second one

#

and I just tested with a timer of myself, it doesn't have a last_triggered attribute

#

oh wait, you are using states() not state_attr()

#

what are you trying to achieve with that last_triggered part?

#

you are using state_attr() in the first one and states() in the second one

#

@thorn harness can you explain in words what your goal is with this template

thorn harness
#

I would like to do:

If temperate difference is above 0.1 degree AND timer is above 5 minutes from timer, then make action. OR maximum timer time 30 minutes is reached if no temp difference is happening , also fire the action, which should set a new time and gives a timer loop.

marble jackal
#

there is no attribute in the timer which stores when it was last finished

#

you can see if the timer is idle

thorn harness
#

so only chance is, to compare time

marble jackal
#

Sorry, I have to go now

thorn harness
#

Np πŸ™‚ Thanks for help!

languid pendant
#

having a blonde moment; what's the right way to get a state attribute in JS? using it on a custom button card -- I keep getting [object Object]

#

... smh

#

i got it

languid pendant
#

Just want to make sure I am right, but markdown card titles are not templatable, right?

lofty mason
#

yeah doesn't look like they are. only the content.

languid pendant
#

hey @lofty mason, have you ever used the config-template-card?

lofty mason
#

no

languid pendant
#

it looks cool as hell, but Im not sure I can get it to do what I want

#

was hoping someone had some experience with using it

lofty mason
languid pendant
#

that might be better -- it's kindof a mix with templates too and I usually get good advice here. (just like now)

full crescent
real magnet
languid pendant
#

lol actually it was .alerts -- was creating a nws card for active noaa alerts in the area

#

since then, I've literally given myself a headache trying to figure out how to pull apart something interesting I found with creating dynamic cards to go into a swipe card for the alerts that come up

#

has pretty much been an all-day escapade, and I just now got it to make 2 buttons. lol

languid pendant
#

basically going to take the nws alerts and create a single card per page on the swipe card with the alert info

#

if my head doesn't explode first

sick junco
#

Hi everyone, I want to find out if my gas heating is currently running or not. I already have set up a counter for the gas consumption and get this properly. Based on that I also calculate the kWh consumed. Now I want to have a status display if the heating is currently on or not. My idea was to do this with a derivation helper variable on the gas consumption counter (based on 1 min). If this derivation helper is greater than zero than I could set a binary template sensor to "on", otherwise it is off. However, I am a total newbie on Yaml and Homeassistant still. Could anyone let me know where I product the error in the template?

#
  • binary_sensor:
    - name: "Status Gasheizung"
    unique_id: status_gasheizung
    state: >
    {% set ableitung_gasverbrauch = states('sensor.ableitung_gasverbrauch') | float %}

        {% if ableitung_gasverbrauch > 0 %}
          {{'on'}}
        {% elif ableitung_gasverbrauch = 0 %}
          {{'off'}}
        {% endif %}
    
inner mesa
#

you used ">", but didn't actually provide a multiline template

sick junco
#

And that was the error in the log:

#

Invalid config for [template]: invalid template (TemplateSyntaxError: expected token 'end of statement block', got '=') for dictionary value @ data['binary_sensor'][0]['state']. Got "{% set ableitung_gasverbrauch = states('sensor.ableitung_gasverbrauch') | float %}\n{% if ableitung_gasverbrauch > 0 %}\n {{'on'}}\n{% elif ableitung_gasverbrauch = 0 %}\n {{'off'}}\n{% endif %}\n". (See /config/configuration.yaml, line 164).

sick junco
inner mesa
#

you also need == to test for equals

#

and it helps to format your code properly

plain magnetBOT
#

To format your text as code, enter three backticks on the first line, press Shift+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.

sick junco
#
  - binary_sensor:
      - name: "Status Gasheizung"
        unique_id: status_gasheizung
        state: >
          {% set ableitung_gasverbrauch = states('sensor.ableitung_gasverbrauch') | float %}
          
          {% if ableitung_gasverbrauch > 0 %}
            {{'on'}}
          {% elif ableitung_gasverbrauch = 0 %}
            {{'off'}}
          {% endif %}
#

Thanks for the hint ...

inner mesa
#
template:
  - binary_sensor:
      - name: "Status Gasheizung"
        unique_id: status_gasheizung
        state: >-
          {% set ableitung_gasverbrauch = states('sensor.ableitung_gasverbrauch') | float %}
          {% if ableitung_gasverbrauch > 0 %}
            on
          {% elif ableitung_gasverbrauch == 0 %}
            off
          {% endif %}
#

you didn't provide a case for when it's negative, but if it can't be negative, it's even easier

#
template:
  - binary_sensor:
      - name: "Status Gasheizung"
        unique_id: status_gasheizung
        state: >-
          {% set ableitung_gasverbrauch = states('sensor.ableitung_gasverbrauch') | float %}
          {{ ableitung_gasverbrauch > 0 }}
sick junco
#

Thank you RobC. Will give this a try....

#

It works! Thank you very much. Now I just need to do the display on the GUI based on that! Thanks a bunch!

#

the == was missing in my part ... and yours is a lot leaner!

languid pendant
#

Hey Rob, trying to combine 2 working templates - the first one creates my swipe card, and the other is the a for loop that lists all the nws alerts. I've removed the pagination and extra stuff to make this fit on here, but Im curious how I can get the foor loop where cards: is supposed to go

{%- set ns = namespace(results = [{
  "type": "custom:swipe-card",
  "cards": ""
}])
-%}
{{ns.results}}
thorn harness
#

Finally i got the danfoss ally automation to work. πŸ™‚ Thanks all for your help. πŸ™‚ Is it somehow possible, to add a condition, that the automation will not fire when temp sensor is 0? I use some average sensors for those thermostats, after home assistant run, they will be 0 for a few seconds. Something like if temp sensor is zero or not availabe? https://dpaste.org/7cNL7

sick junco
#

As I am new to HomeAssistant I sometimes do not know on how to best solve a problem. I want a simple display if my gas heater is running or not. The gas consumption in kWh is working reliably. However, my approach to do a derivation helper on the last minute to check if it is running or not is not working properly. The derivation does not go back to zero if energy consumption (total increasing) remains constant. How could I simply check if the value of my total energy consumption now vs. 1 min ago did not change and then set the status accordingly?

plain magnetBOT
#

@thorn harness To format your text as code, enter three backticks on the first line, press Shift+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.

#

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

inner mesa
#

you don't have a template there, so it doesn't belong under template:

#

not everything is a template πŸ™‚

mellow sigil
#

erm OK, then how can I write the equivalent of the derivate helper in yaml?

#

can i get the code for an existing on which works?

plain magnetBOT
#
The topic of this channel is:

Become a real Jinja2 Ninja! Don't worry my Genin, we are here to help! You can find general Jinja docs at https://jinja.palletsprojects.com/en/3.1.x/templates/, Home Assistant extensions at https://www.home-assistant.io/docs/configuration/templating/, and trigger variables at https://www.home-assistant.io/docs/automation/templating/

This channel is for support with Jinja templates. Some custom Lovelace cards support other types of templates, such as those written in JavaScript, and #frontend-archived is the right channel for that.

Please use http://pastie.org/, https://dpaste.org/, or https://paste.debian.net/ to share code or logs

inner mesa
#

that describes what a template is

#

you second example looks fine

#

what do you mean by

but I've no way to see this "sensor" like creating a Card showing it's value.

#

it should create a sensor entity, and you can display that

mellow sigil
#

no I can't "see" it anywhere.
Of course I know I've to reload the configuration and did.

plain magnetBOT
mellow sigil
#

I checked it, green.

inner mesa
#

and you "see" it in devtools -> States, and in the entity picker of whatever card you're using (if it provides one)

#

reloading YAML won't be enough if you didn't already have sensor: in your configuration.yaml

#

you would need to restart HA

mellow sigil
#

I already have, yes

#

ohhhhhhhhhh - let me try

#

it's restarting... while this, is there a way NOT to reload for every sensor I'll create?

inner mesa
#

yes, via devtools -> YAML

#

and you don't need to use YAML at all if you just create helpers in the UI

#

then you don't need to reload anything

mellow sigil
#

I wish a specific one, like for the format displayed etc - this test above is just a basic one, but I'd wish something more personnalized than the UI

#

I don't understand yes via YAML, you mean, you can YAML an UI created derivative? let me check...

inner mesa
#

I didn't follow that

mellow sigil
#

Thank you - cnfirmed, it's now showing in States or for creating a Card, it works! thanks!

#

I mean, now I wish to make other sensors, should I restart every time??? Is there another way, or file, to put them?

inner mesa
#

yes, via devtools -> YAML

#

look there, reload whatever you want, or everything

mellow sigil
#

? YAML? but this is in configuraion.yaml

#

I don't get it

inner mesa
#

what part?

mellow sigil
#
  • platform: derivative
    name: TestCurrentPower
    source: sensor.lixee_current_summ_delivered
    round: 3
    unit_time: h
    unit: kW
    time_window: "00:01:00"
inner mesa
#

I don't know what you're asking

#

you asked if you need to restart HA every time you add a new sensor, and I said no

#

and what to do instead of restarting

#

is there still confusion?

mellow sigil
#

ok, but then why did I had to restart HA a few minutes ago (and it worked, thank you again, a million!)

inner mesa
#

because you added sensor: for the first time, so it wasn't loaded at all

mellow sigil
#

ah no, I already had a sensor:, this was my second

inner mesa
#

ok

mellow sigil
#

this is what's in configuration

#

sensor:

  • platform: group
    name: GroupMeasuredEnergy
    (etc)

  • platform: derivative
    name: TestCurrentPower
    source: sensor.lixee_current_summ_delivered
    round: 3
    unit_time: h
    unit: kW
    time_window: "00:01:00"

languid pendant
#

any time you add a new sensor:, paramecie, you'll need to reload the yaml that goes with it

inner mesa
#

please stop posting unformatted code

mellow sigil
#

ohhh sorry

plain magnetBOT
#

To format your text as code, enter three backticks on the first line, press Shift+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.

inner mesa
#

anyway, doesn't matter. you can reload YAML via the method I mentioned

languid pendant
#

what RobC is saying is that once the sensor is created, you can reload the templated sensors without reloading all of HomeAssistant

mellow sigil
#

I did it, ten times trying many things - no way to see the sensor, only after the restart of HA it worked

languid pendant
#

right. because you have to initialize the sensor: with a restart of HomeAssistant

#

every time you add a new sensor

mellow sigil
#

sorry but no, it's my second sensor, the first works since yesterday

languid pendant
#

if you modify an existing one, then reloading the templated entities will only apply to the sensor: 's already loaded

#

right. the second one is new

#

so you had to reload HA

mellow sigil
#

ohhhh you mean for every NEW (only) sensor, you've to restart HA?
otherwise only YAML reload?

languid pendant
#

correct

mellow sigil
#

wow

#

and of course no way to escape this (apart using existing helpers for ex)?

languid pendant
#

no

mellow sigil
#

so, I'm not sure I would have found this written somewhere, especially not knowing what the problem was πŸ˜‰
A MILLION thanks both. Please have a nice one!

languid pendant
#

You're welcome. (and I still owe you a couple, RobC)

#

lol

#

esp. after my debacle of a template

mellow sigil
#

BTW... I've a few sensors in templates.yaml with work very well, no problem.

Why for this derivative it can't be a template?

What's in short the difference in between a sensor in template (that I can show in a Card) and a sensor in configuration.yaml sensor: (that I can show also). This is a bit puzzling.

inner mesa
#

there's simply no template there

#

if you want a template sensor, you need to create a template sensor

mellow sigil
#

no, all I want is basically sensors, but put some in template

inner mesa
#

then make a template sensor that references the other sensor

#

you can't just add a template to some other sensor. you can create a template sensor that derives its state from some other sensor

#

I'm not even sure what you're trying to do. Why do you want a template?

#

I mean, they're cool, but why?

mellow sigil
#

still don't get it... this is a sensor? I put it in templates.yaml:

- sensor:
    - name: TempoToday
      state: >-
        {% set tempo = states('sensor.lixee_active_register_tier_delivered')%}
        {% if tempo == 'HPJB' or tempo == 'HCJB' %} BLEU
        {% elif tempo == 'HPJW' or tempo == 'HCJW' %} BLANC
        {% elif tempo =='HPJR' or tempo == 'HCJR' %} ROUGE
        {% else %} Error
        {% endif %}
inner mesa
#

presumably that's under template: and is a template sensor

mellow sigil
#

arf - I still don't understand what's a template vs what's a sensor

inner mesa
#

they aren't mutually exclusive

#

that is a template sensor

#

template sensors derive their state from a template, as you just showed

#

other types of sensors derive their state from something else, like the derivative sensor that you showed earlier

#

they are both sensors

mellow sigil
#

ohhh I thought template as in "template of a sensor" something like a model you can apply to a sensor, multiple sensors

inner mesa
#

no, it's not that kind of template

plain magnetBOT
#
The topic of this channel is:

Become a real Jinja2 Ninja! Don't worry my Genin, we are here to help! You can find general Jinja docs at https://jinja.palletsprojects.com/en/3.1.x/templates/, Home Assistant extensions at https://www.home-assistant.io/docs/configuration/templating/, and trigger variables at https://www.home-assistant.io/docs/automation/templating/

This channel is for support with Jinja templates. Some custom Lovelace cards support other types of templates, such as those written in JavaScript, and #frontend-archived is the right channel for that.

Please use http://pastie.org/, https://dpaste.org/, or https://paste.debian.net/ to share code or logs

mellow sigil
#

ohhhhhhhhhh

languid pendant
#

I think he got it, just backwards

mellow sigil
#

yep πŸ˜„

languid pendant
#

you apply the template to the sensor

inner mesa
#

"template" is Jinja terminology

languid pendant
#

not the sensor to the template

mellow sigil
#

you're champs people, thanks - but I've been disturbed by the "template" wording

fathom jetty
#

How do I use a "or" condition in jinja? Iam confused, that I cant find a answer with Google ^^'

inner mesa
#

literally "or"

lunar crater
#

is there a good way to have a sum helper not become unavailable when one or more of the child entities be unavailable but return a default value instead?

inner mesa
#

if you want to continue to use your sum helper, then you can create a template sensor to assign a default

#

{{ states('sensor.sum_sensor')|float(0) }}

lunar crater
#

i see thanks!

mellow sigil
#

@inner mesa @languid pendant Very sorry people, but following the above conversation, and about templates (was confused) and the fact I've to restart HA when I create a new sensor in configuration (yaml)....

My problem is, I tried to change an existing (same as above) sensor either source: or unit:, but even reloading YAML twice, or "quick rebooting" reloading the yaml, the changes aren't effective.

I tested, I have to restart HA for any change to an existing sensor in configuration 😦

Is this normal? It's pure pain, sincerely, especially with sensors like derivative as the numbers are crazy for some time after the restart...

What am I doing wrong? Is there an add-on (i've HACS) or sometheing that could help?

languid pendant
#

are you reloading all yaml configuration or template entities ?

#

specifically.

mellow sigil
#

ALL - the first choice

languid pendant
#

try template entities

mellow sigil
#

it's not in templates, it's in configuration.yaml - let me try anyway

languid pendant
#

it doesnt matter where theyre defined, theyre still templates.

mellow sigil
#

nope - I even CTRL+F5 the pages

#

I checked in both States and on my Card, it shows for example the previous unit: not the new one

languid pendant
#

if you have templates defined in configuration.yaml, or templates.yaml, you can reload the TEMPLATE with template entities

#

if you are attempting to change the core sensor data, you have to reload HA

mellow sigil
#

no, I've "sensor:" defined in configuration

languid pendant
#

ok,

mellow sigil
#

but then, if the problem is because it's not a template... can't I make this derivative a template?

languid pendant
#
sensor:
  - platform: weatheralerts
    state: AK
    zone: 827
    county: 290

^ this is a sensor. I have to reload HA when I change the data

marsh cairn
#

Is it

  - platform: template```
or
```template:
  - sensor:```
languid pendant
#
sensor:
  - platform: template
    sensors:
      wc_temperature:
        friendly_name: "weather-card temperature"
        value_template: |
        {{ state_attr("weather  .kged_daynight", "temperature") }}

^ this is a template

mellow sigil
#

it is (sorry, I don't have backticks on the keyboard):

#

sensor:

  • platform: group
    name: GroupMeasuredEnergy
    (etc)

  • platform: derivative
    name: TestCurrentPower
    (etc)

#

(etc) should be on a new line

marsh cairn
#

Those sensors need a HA restart

marsh cairn
mellow sigil
#

oh dear lord 😦
can't I make a derivative in template, or another way in some code, but not in UI?

languid pendant
#

@marsh cairn lol i know it's the first thing i could grab

mellow sigil
#

Not Frenckencode I hope πŸ˜‰

languid pendant
#

wait a min

#

i see what i did there

#

edited

marsh cairn
#

Hehe

languid pendant
#

good lookin out

marsh cairn
#

A legacy one

mellow sigil
#

Yep, seems obsolete to me, if you pardon me πŸ˜‰

#
  • platform: template
marsh cairn
#

Not obsolete - it still works. But the new format is recommended

languid pendant
#

still works; havent gotten around to updating those as theyre just for a weather card

mellow sigil
#

Yes, Visual Basic 6 still works you know?
πŸ˜‰
Sorry to tease you.
(and I'm still using it on a dedicated machine)
Anyway, the question: "can't I make a derivative in template, or another way in some code, but not in UI?"

languid pendant
#

HAHAHAHA ... hey now -- I used to work for a company who wrote (and still writes) an ERP in visual basic for their production

mellow sigil
#

That's exactly what we do πŸ™‚ Have new servers, node.js and such, but still old tools - still working like a charm

languid pendant
#

read, then re-read. then read again.

#

and really, what re you trying to template, exactly?

#

what data are you trying to pull from your derivative sensor

marsh cairn
mellow sigil
#

Already read!

A simple template or sensor of a derivative, the base being:

  - platform: derivative
    name: TestCurrentPower
    source: sensor.lixee_base
    round: 3
    unit_time: h
    unit: kW
    time_window: "00:01:00"
#

@marsh cairn because i wish to make some calculations and changes which aren't proposed in UI - thanks to help Jorg

#

I made this derivative in UI (another name) works fine. Same in YAML. But just the restart is pure pain.

atomic blade
#
{{ area_id('binary_sensor.living_room_motion')
| area_entities('bedroom')
| expand
| selectattr('attributes.device_class', 'eq', 'illuminance')
| map(attribute='state')
| map(int)
| average }}

Trying to get the average lux in a room but getting this error with the above template: TemplateRuntimeError: No filter named <function forgiving_int at 0x7f0682247240>.

inner mesa
#

map('int')

atomic blade
#

😐

#

thanks lol

mellow sigil
#

wow, gg Rob

marsh cairn
mellow sigil
#

agreed @marsh cairn - just the dev time is made longer and a bit painful

#

ok then, and again, thank you all Rob, Deadly, Jorg... ring me if you think at something πŸ˜‰ thank you

languid pendant
#

@inner mesa trying to add items to this list and reference it as such list later, but doesnt seem to work without being a namespace, is there no other way?

{% set ns2 = [] %}
{% for event in state_attr('sensor.st_lawrence_island','alerts') %}
{% set ns2 = ns2 + ['test'] %}
{% endfor %}
#

ns2 returns []

inner mesa
#

yes, it looks like you tried to use a namespace, but didn't actually do it

languid pendant
#

right. so when i use this:

{% set ns2 = namespace(cards=[]) %}

it works, but when I reference, i get this: [{'type': 'custom:swipe-card', 'parameters': {'pagination': {'type': 'bullets'}, 'spaceBetween': '8', 'effect': 'fade', 'fadeEffect': {'crossfade': 'true'}}, 'cards': <Namespace {'cards': ['test']}>}]

#

ooh. i have to use ns2.cards... maybe

#

i think

inner mesa
#

yes

languid pendant
#

got it.

#

thank you

knotty vessel
#

I'm trying to use a REST sensor to get info from an Arylic music amp. It returns strings as hex, eg "4920446F6E2774204B6E6F7720416E797468696E67". How do I convert from hex to ascii string in the value_template?

knotty vessel
#

It seems like there is no unhex function for templates

thorn harness
#

Good morning. I have a working automation with the following timer trigger. I would like to change to this to a more elegant solution, to survive reboots. Is it possible to use the last changed attribute with a timer? @marble jackal already told me, that there it is not possible this way. Maybe someone has a hint, what to look for?
(this.entity_id) is the entity of the automation.

this works:
value_template: >-
{% set last_trigger = state_attr(this.entity_id, 'last_triggered') %} {{ last_trigger is none or now() - last_trigger > timedelta(minutes=min_update_minutes) }}

this i tried ( gives me always true !?):
{% set last_changed = state_attr("timer.timer_buero", 'last_changed') %} {{ last_changed is none or now () - last_changed > timedelta(minutes=5) }}

marble jackal
#

to access the last_changed datetime, you need to use states.timer.timer_buero.last_changed

#

but as I already mentioned, it will reset after a restart

#

but I don't understand why you are so interested in the time the timer changed state?

#

it will either be idle and then it's not running anymore, or it is not, and then you can calculate the start time (if that's what you need)

thorn harness
#

Well, you are right. It would just be a cosmetic thing πŸ™‚ I let it how it is now. I published the working blueprint now for the community, it works good now how it is. πŸ™‚
Thanks again for your great help!

fallow gulch
#

hola

#

I have a dynamic feed-in tariff on my solar export, which is 16 cents per kWh for the first 15kWh per day, then drops to 5 cents per kWh for the rest of the day. I already have an input_number that I use for my exports in my energy dashboard, but I'm at a bit of a loss as to how I can automate this to change from 16c to 5c. The missing link (I think) is a sensor that's triggered at 15kWh of export, which resets daily.

sonic ember
marble jackal
#

do you have the daily export?

#
state: "{{ 0.16 if states('sensor.daily_export') | float <= 15 else 0.05 }}"
availability: "{{ has_value('sensor.daily_export') }}"
sonic ember
#

Def. simpler than my suggestion πŸ™‚

marble jackal
primal garden
marble jackal
#

which doesn't belong in sensor.yaml, but under it's own rest: integration\

primal garden
#

AH

#

Thank you so much, I was wavering which channel was best.

mellow sigil
#

Hi!

I know the total measure of energy spent according to the connected meter (Linky, french).
Some appliances have their own SmartPlugs on which I measure the consumption.
So, the difference between total - measured = not measured, the below template.
I could make the whole work yesterday/today, and getting some help from you (thanks!)

Problem is, while setting this NotMeasuredEnergy template in the Energy dashboard, first 2 hours where perfectly fine but now I I can see a (relatively big) negative value.
Which doesn't exist, of course - I'm not producing energy - I wish πŸ˜‰

Question is: see the template below, doesn't what I wrote supposed to avoid negative values?
Did I made a boo boo somewhere?

Thanks for your help!

#
- sensor:
    - name: NotMeasuredEnergy
      unit_of_measurement: kWh
      device_class: energy
      state_class: total
      state: >-
        {% set Tot = states('sensor.MeterTotalEnergy') | float %}
        {% set Measured = states('sensor.MeasuredEnergy') | float %}
        {% if Tot < Measured %}
          none
        {% elif (Tot - Measured) < 0 %}
          none
        {% else %}
          {{ Tot - Measured | round(3)}}
        {% endif %}
#

Also - I'm not sure if class of this template should be total or total_increasing... read about it, maybe tired, too old, or not my language (probably both), still not sure

modest pine
#

Trying to get an average of durations between a few dates, but not sure how to actually calculate the average of the time deltas.
Here is what I have so far and it gives me a list of everything, but I can't use the average() function on data.value.

{% set data = namespace(value=[]) %}
{% set pTime = namespace(value=0) %}
{% for row in state_attr('sensor.xxx','results') %}
  {% if count.value != 0 %}
    {% set data.value = data.value + [pTime.value - as_datetime(row.get('start'))] %}
  {% endif %}
  {% set pTime.value = as_datetime(row.get('end')) %}
  {% set count.value = count.value + 1 %}
{% endfor %}```
#

I've set up other templates similar to this where I used as_timestamp() instead of as_datetime() but that then doesn't account for differences in the dates and I need that in there.

mellow sigil
#

I don't know, but "set pTime = namespace(value=)0" seems to me bizarre (0 after the parenthesis)

modest pine
#

Oops, just a typo when transferring it over to Discord haha

lucid thicket
modest pine
#

Hmm maybe I need to take another look at it then tomorrow because I wasn't getting what I thought. Thanks for clarifying!

lucid thicket
#

That function gives you the number of seconds since Jan 1 1970 UTC

#

So if you subtract two timestamps you just get the number of seconds between them

modest pine
#

That's what I had thought but I wasn't getting the answer I was expecting. Might look at my data too and make sure it looks accurate

#

Actually, I just now realized what I was doing wrong πŸ€¦πŸΏβ€β™‚οΈ I copied the code from another sensor I had to get the time between events, and this one I want to average of events so I just need to subtract the end from the beginning of this row

slate fossil
#

I was looking at Petro's seasons.yaml template and I think I can adapt it for what I am trying to do. (Basically, return a holiday name if the date range matches or return none.)
A couple of questions come to mind:

  1. How often does a template update?
  2. Can it be forced to update at a specified interval?
  3. Is there are way for ensure a state change occurs? Even if the state goes to something else just for a moment (like, initializing) and then holiday/none.
inner mesa
#

When its entities update or once a minute if it includes now(), and with a trigger

slate fossil
#

The template does use now() but updating every minute is overkill for what I'm looking for (perhaps every hour or two). But, with that in mind, I'm thinking I can make an automation that runs hourly, sets the state of an input_helper to "initializing", waits a second or two, and then sets the state to the value of the template. That should give me the change that I need.

inner mesa
#

Sounds complicated when you can just add a trigger

slate fossil
#

Do you mean a trigger in an automation? I don't need the state change to actually trigger an automation. Instead, it is for something waaay different.
I'm actually looking to be able to use it with lovelace-animated-background. It reacts to state changes (example shows a weather sensor and then showing a background based on its state). But, I'm not trying to work with weather; I want holidays. But, an hourly state change would also change the background to a random default one (every day backgrounds).

inner mesa
#

I mean a trigger for the template sensor

#

time_pattern trigger, specifically

slate fossil
#

Okay. I think I see what you're saying. Basically, create a template sensor with a time_pattern trigger of hours: "/1" and then Petro's modified yaml in the sensor section.
I'm assuming this means that when now() updates, it won't update the entire sensor because the trigger has not fired.

inner mesa
#

Right

frank gale
#

We have two lists:

['Kitchen','TV Livingroom', 'Bed Bedroom', 'TV Bedroom']
['Livingroom', 'Bedroom']

Could we filter the first list to get the items that contain any of the elements of the second list without using for, just with the Jinja filters?

marble jackal
frank gale
#

You saved me again! Thanks!
What does the '|' means?

#

Is it just join them with the | separator or is it a special Charakter?

marble jackal
#

It's or in regex

frank gale
#

time to learn more about regex πŸ™‚

steel swift
#

I have made a template sensor and it is kinda working. The sensor gets its update from a attribute I get from Tibber with energy price information. It works fine for a couple of days, even maybee some more. The it get stuck in VERY_EXPNSIVE causing all my heat going into save mode instead of adjust the temp according to the price level. The attribute in the original sensor seems to update fine, and if I restart my RPi with HA on, then it works fine again for some days. Have I done anything wrong in my sensor? ```template:

  • sensor:
    • unique_id: energy_price_level
      name: "PrisnivΓ₯ StrΓΈm"
      state: >-
      {% set price_level = state_attr('sensor.electricity_price_hjemme', 'price_level') %}
      {{ price_level if price_level is defined else 'NORMAL' }}
marble jackal
#

Price level will always be defined, you are defining it yourself

#

If the attribute doesn't exist, price_level will be none, but it will be defined

#

{{ state_attr('sensor.electricity_price_hjemme', 'price_level') | default ('NORMAL', true) }}

#

That will do what you intended to do

steel swift
# marble jackal That will do what you intended to do

Makes sense, so like this then: ```template:

  • sensor:
    • unique_id: energy_price_level
      name: "PrisnivΓ₯ StrΓΈm"
      state: >-
      {{ state_attr('sensor.electricity_price_hjemme', 'price_level') | default('NORMAL') }}````
marble jackal
steel swift
plain magnetBOT
#

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

marble jackal
#

@steel swift that would work as well, but remove the unit_of_measurement
With that included only numeric states are accepted.
And either add defaults for your float filters, or add an availability template

steel swift
plain magnetBOT
#

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

mellow sigil
marble jackal
#

what you see there is not because the template sensor had negative values

#

they just were lower than the previous value

#

you are not looking at the state, you are looking at the delta between the states

mellow sigil
#

oh, but then, why do I get negative energy ???

marble jackal
#

because of what I just said.

#

you are useing a sensor with state_class: total

#

which means that if the state is eg 20 at one point, and then changes to 15 it will see that as a energy return of 5

mellow sigil
#

ohhh so what should I use to see the difference between total energy (meter) and measured one (smartplugs) ? state_class: measure or something like this?

marble jackal
#

BTW your whole if statement in the state template is not needed, they can never be below 0 as you already account for that in the availablity

mellow sigil
#

^ I know, but it wasn't working, so I doubled the tests

marble jackal
#

your problem is that they will update on a different timing

#

so if the measured one will update first, before the total one does, then your value will decrease

#

furthermore, your total one probably comes from your meter, which will be accurate, the measured one will never be

mellow sigil
#

accuracy I don't care, yes the total is the meter (Linky), if that makes -0.01 kwh difference I don't care
but you're right on the timing... you mean fixing this would give correct results?
I don't have to change the state_class?

marble jackal
#

well the inaccurate results will cause issues like this

#

it's nice to have a sensor to measure the unmeasured energy, but the long term statistics will be crappy, and so will the display on the Energy dashboard

mellow sigil
#

oh - wrong topic, sorry... how would you fix the timing, with a "timer" event every minute where all 3 totals are calculated (almost) at the same time?

#

OK I'll post in energy channel - million thanks @marble jackal

mellow sigil
#

Stupid question...
When I play in dev tools/Model with a template of sensor setting a State to this sensor, does it NOT actually modify the sensor's real State?
I mean, I hope...

inner mesa
#

no

mellow sigil
#

ooof thank you!

inner mesa
#

what you're describing would probably just be a syntax error

mellow sigil
#

I meant I hope it doesn't really update the real sensor State.

inner mesa
#

I understand, but it's just broken syntax and wouldn't do anything at all

#

as in, this is nonsense and just results in a syntax error: {{ set states('sensor.aarlo_battery_level_family_room') = 5 }}

mellow sigil
#

ok thanks Rob - please have a good one!

plain magnetBOT
#

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

torpid crag
#

Ive got a weird thing. I have a template sensor i was mucking around with via the UI helpers area, now for some reason its showing a warning, and there is no way to delete it.... any ideas? https://imgur.com/a/z5acSXJ

marble jackal
misty basalt
#

Hey all, any ideas why this Utility Meter sensor is updating every 5minutes - I am trying to get it to record every 30minutes hence the cron

  30minconsumption_no_defined:
    source: sensor.consumed_today_watts_nodef
    cron: "*/30 * * * *"
    periodically_resetting: true```
But it is giving results every 5minutes? 
https://snipboard.io/qFI6kG.jpg

`last_reset: 2023-10-19T08:00:00.007476+00:00` does show every 30minutes, rather than 5. Have I misunderstood something of how it works?
marble jackal
misty basalt
deep marsh
#

Hello everybody,
Is there a way to remove all non-numeric characters from a string?

heavy crown
#

something like this {{ 'test123asd'|select('in','.-0123456789')|join }}

deep marsh
frank gale
#

Is there any way to filter for a spefic device model without a for?
Get from the state.sensor all the entities (or device_ids) that have a device model 'SYMFONISK Sound Controller'.

heavy crown
#

ah..sorry... WITHOUT a for...no clue, sorry for that

frank gale
#

I'm sorry that you had to type all that without helping πŸ™‚

heavy crown
#

deadly tired indeed πŸ˜“

marble jackal
#

that won't work anyway, as the device model is an attribute of the device, not of the sensor itself. Or am I misunderstanding that?

#

But I don't think that's possible without a for loop, als is_device_attr is not available as a test like is_state_attr is

mighty ledge
#

I’ll put a pr for that when I get back from vaca

marble jackal
#

Enjoy your vacation

untold galleon
#

Hello! Can we get access to some random input_datetime objects from template? For example {{ input_datetime.light_facade_turn_on_time }} gives an error "UndefinedError: 'input_datetime' is undefined" (both in template editor and in 'variables' section in automation). Feels like it's out of scope...

inner mesa
#

You're just not using the right syntax

#

See the links in the channel topic

marble jackal
#

The state of some random input_datetime? Voila! 😜
{{ (states.input_datetime | list| random).state }}

untold galleon
#

Okay, not so random πŸ˜„

#

I got it worked with help of @inner mesa 's link, {{ states('input_datetime.light_facade_turn_on_time') }} {{ states.input_datetime.light_facade_turn_on_time.state }} but still not fully understand the syntax. In first option states('entity') returns array of all entity states, if it has more than one state? In second option, what does .state in the end mean?

inner mesa
#

There's only one state

#

There is a box on that page that explains why the first is preferred

untold galleon
#

oh, then the function name 'states' instead of 'state' sounds a bit confusing(

inner mesa
#

Yes, it is

karmic sapphire
#

does mushroom template not regard this type of code for changing the icon color?

#
        {% if index > 300 %}
          Red
        {% elif index > 200 %}
          Orange
        {% elif index > 150 %}
          Yellow
        {% elif index > 100 %}
          Yellow
        {% elif index > 50 %}
          Blue
        {% elif index >= 0 %}
          Green
        {% else %}
          unknown
        {% endif %}```
marble jackal
#

Color names need to be lowercase

tawny sedge
karmic sapphire
marble jackal
#

Petro already mentioned above he will create a PR for that

marble jackal
karmic sapphire
#

I get all kinds of errors, I am trying to understand why it wont read any of my waqi sensors, I put them all in a group.waqi but it still doesnt work

tawny sedge
#

switches = states.sensor
| map(attribute='entity_id')
| select('is_device_attr', 'model', 'ZEN32')
| list

inner mesa
#

self.tests["is_device_attr"] = hassfunction(is_device_attr, pass_eval_context) mindblown

#

Petro is fast πŸ™‚

marble jackal
#

Oh, apparently it is a test

#

Then I did something wrong while testing it's a test

inner mesa
#

Keep testing the test

marble jackal
#

I tested my tests to test the test, and after some tests I can attest it does work as a test

marble jackal
#

Sorry for the confusion @tawny sedge

inner mesa
#

I think I had a PR open for that a while ago that I abandoned

untold galleon
#

Any way to get variable type in template? Something like 'typeof(some_strange_variable)' would be very helpful for debugging!

inner mesa
#

Not in that general sense, no

#

You can test directly for some types, but even that is incomplete and a pain the neck

#

That's why there are some custom tests that were added for HA, like is_number

untold galleon
#

Then if understand correctly, in the next two examples I get the time as 'string' and 'timestamp' objects. If the 'strings' comparison doesn't seem logical, that's okay. But how can I compare two 'timestamp' objects? I thought there was something like an overloaded operators '<' and '>' for 'timestamp', but all expressions always return 'false' ```{% set turn_on_time_string = state_attr('input_datetime.light_facade_turn_on_time', 'timestamp') | timestamp_custom('%H:%M', false) %}
{% set turn_off_time_string = state_attr('input_datetime.light_facade_turn_on_time', 'timestamp') | timestamp_custom('%H:%M', false) %}
{% set turn_off_time_timestamp = states('input_datetime.light_facade_turn_on_time') %}
{% set turn_on_time_timestamp = states('input_datetime.light_facade_turn_on_time') %}

{{turn_on_time_string < turn_off_time_string}}
{{turn_on_time_string > turn_off_time_string}}
{{turn_off_time_timestamp < turn_on_time_timestamp}}
{{turn_off_time_timestamp > turn_on_time_timestamp}}```

#

probably i should use some function for comparision?

#

ah

#

nevermind

#

it was wrong input_datetimes. Assigned "input_datetime.turn_on" values for both "turn_on_time" and "turn_off_time" variables πŸ˜„

marble jackal
#

There is an open PR for additional tests for the other types like list or datetime

hybrid tide
#

I'm really struggling with the round() function. I'd like it to just round to a whole number. Can anyone help?:

Kelvin: {{ test | round(0) }}
Farenheit: {{ test | float(0) * 9 / 5  - 459.67  | round(0)}}```
Output ends up as:
```Kelvin: 289
Farenheit: 60.84800000000007```
#

I'd just expect Farenheit to result in 61

lofty mason
#

Farenheit: {{ (test | float(0) * 9 / 5 - 459.67) | round(0)}} = 61

#

order of operations matters

hybrid tide
#

Hrm. OK. I assumed left to right would be the default I guess?

marble jackal
#

Filters are applied first (from left to right if there are multiple)

hybrid tide
#

Thank you! Result is as I'd hoped.

#

Oh...Filters, THEN math?

marble jackal
#

So you were only rounding 459.68

languid pendant
#

{{ state_attr('') }} is the jinja equiv to [[[ states[''].attributes]]], right?

#

or is it states.attributes['']

marble jackal
languid pendant
#

drawing a blank and I cant google it atm

hybrid tide
#

That makes sense. Thank you!

marble jackal
languid pendant
#

thanks Fes -- am in a meeting and jotting things down -- trying to do something like [[[ return (integer variable) || 0; ]]] <-- that will return the variable, unless it cant, then instead return 0, if I remember right, yes?

#

no, I think thats backwards, isnt it

#

is that doable with jinja?

#

i would think its an if else, right?

#

(I am working on a scene for my livingroom to dim the lights to 1%, turn the back ones off, and then brighten the fronts to ~20% red)

#

since my lights dont support the transition property, I have to do it via scripts and templates

languid pendant
#
{{ (state_attr('light.light', 'rgb_color')[0] | float + increment_x)) if (state_attr('light.light', 'rgb_color')[0] | float + increment_x)) >= 0 else 0 }}

keeps giving me message malformed -- is it the parens?

plain magnetBOT
#

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

mellow sigil
#

On this graph the meter is stating -89 kWH for 1 minute or so πŸ˜‰

Sorry, always forgot the 15 lines limit, apologizes.

languid pendant
#

@marble jackal have you ever had any issues with this kicking out after just a few iterations? The script you sent is only adjusting a couple times, then ending as complete.

languid pendant
#

I got 3 iterations and then it just stops

#

super wierd

marble jackal
#

what is your input for the script

languid pendant
#

was a 2-member light group

#

it only seems to happen when transitioning color

#

i think I fixed it -- change the abs value to something higher and have been testing

marble jackal
#

If it should be fixed in the script, can you issue a PR for it so I can check it and correct it for myself πŸ™‚

#

Or create an issue

languid pendant
#

I'll be honest with you - I dont know how ... is that push or pull?

#

i can do the issue πŸ˜‰

#

gotcha brother

marble jackal
#

Pull, but an issue is fine

languid pendant
#

πŸ‘

silent flicker
#

is it possible to get the volume_level of a mediaplayer? to check it

i tried {{ state_attr('media_player.aarons_room_display', 'volume') }} but it didnt give me anything useful

marble jackal
#

check developer tools > states for the attributes of the entity and you will notice the attribute is called volume_level

#

and possibly only available when the device is on

earnest cosmos
#

I am testing variables in an automation. I get no errors on this, but is the double quotes neccesary?

action:  
  - variables:
      sun_is_rising: "{{ is_state('sun.sun', 'rising') }}"
  - choose:
    - conditions:
        - "{{ states('sensor.daytime') in ['skumring2', 'skumring', 'dagtid'] }}"
        - "{{ sun_is_rising }}"
deft timber
#

Yes

earnest cosmos
#

Thanks. Which means...

#

the variables should evaluate as string?

deft timber
#

Another way of writing it without double quotes would be :

action:  
  - variables:
      sun_is_rising: > 
          {{ is_state('sun.sun', 'rising') }}
deft timber
earnest cosmos
#

Thank you for enlightening my knowledge.

#

BTW Chat GPT wrote this part of the script. Or optimized my old version πŸ™‚ Facinating πŸ™‚

earnest cosmos
# deft timber Yes

Forgot to point out if this also goes for the conditions:

- choose:
  - conditions:
      - "{{ states('sensor.daytime') in ['skumring2', 'skumring', 'dagtid'] }}"
      - "{{ sun_is_rising }}"

meaning; the double quotes must be there?

deft timber
#

yes

analog mulch
#

What's the efficient way to check in a template if we are between some two days in the year spanning New Year, e.g. 1 September and 1 March

fickle sand
silent vector
#

Can I use a macro in a while loop? Will it re-evaluate the macro with each loop?

fickle sand
#

You can use a macro like any other function within a for loop

marble jackal
#

{{ not as_local(as_datetime(now().year ~ '-03-01')) < now() < as_local(as_datetime(now().year ~ '-09-01')) }}

nova egret
#

I don't know if this is the correct place to ask this. I have two sensors, both numeric. Is there a way to create a new one that is the product of both? In the helpers there is only SUM, not PRODUCT.

strong forum
#

define product

#

you want to have the average over the 2?

nova egret
#

sensor1 * sensor 2. like 4*2 = 8

strong forum
#

uhm, use a helper?

inner mesa
#

You'd need to make a template sensor

strong forum
#

that's what I meant, with my noobish reply

obtuse zephyr
#

You can make a sensor group of type Product

strong forum
#

Helpers it is πŸ˜„

inner mesa
#

Whoa, indeed

nova egret
#

I didn't saw the Product available, before

inner mesa
#

It seems to overlap the 'combine multiple sensors' helper, which lacks that

nova egret
#

that's it

#

the "Group" name is a bit confusing

inner mesa
#

I don't know why there are two dissimilar ways to 'combine' sensors with that much overlap

nova egret
#

I have another question. On top of the product, I also need to divide by 100, for this I must create a static entity with value=100 right?

nova egret
# inner mesa

that was the one I saw before, where product isn't available

marble jackal
#

yes, I think that one was create first, and then the group one was created. I would say the combine one should be removed, but my guess is that it's tricky to do that in a non breaking way (copying them over to the group one automagically)

#

but hey, I'm still halfway my Python intermediate course and cancelled the Codecademy subscription before I had to start paying πŸ˜‰

inner mesa
#

I think that 'group' is a much less descriptive way to put it. It's hidden away where nobody will find it

nova egret
#

yes

#

i agree

nova egret
obtuse zephyr
#

I'd suggest just using a template sensor to keep things together if you're going to need additional logic.

marble jackal
#

Yes, you can create a template helper so you don't have to do the YAML

#

but it depends a bit on what you want to do if the source sensors are unavailable

nova egret
#

I managed to do what I wanted. I will use this a lot, it's great

#

thanks for the help

spark vortex
#

I have a templte value like this {% set duration = as_timestamp(now()) - as_timestamp(states.sensor.tv_letto_yearly_on_temp.last_changed) %} how can I show something like HH:mm:ss ? it is not 24h only, but in duration there is how much time my tv was on in the full year

marble jackal
#

{{ duration | timestamp_custom('%H:%M', false) }}

atomic blade
#

I have a template that uses now() causing it to update every minute. Is there a way to control how often it actually updates?

inner mesa
#

yes, with a trigger

#

I think the docs have a paragraph on that

atomic blade
# inner mesa yes, with a trigger

So I'd create a trigger sensor that updates every X mins and spits out the timestamp and then use that value instead of now(). Is that the idea?

inner mesa
#

no

#

add a trigger to the template sensor

atomic blade
#

Ah ok, I was on the trigger docs. Let me take a look, thanks

#

Ok so to make sure I understand, the trigger will be the only thing controlling when the template updates and nothing in the template

#

I think I was confused because I was still thinking things in the template would cause a trigger

#

So for instance if one of the sensors in the template updated, it wouldn't update the sensor, it's ONLY updating at the interval

#

I think the method I described would still keep the template updating when the other sensors in the template update. But depending on the use case that might not matter

inner mesa
#

add whatever you want to the trigger

atomic blade
#

For more context, I'm making a sensor that says the estimated timestamp when a battery will be drained. So I have a template that was using the battery level state and a derivative sensor

atomic blade
#

Could just manually add the sensors I'm using to the trigger

#

Just when I think I can use a sensor in the UI, the yaml pulls me back in lol

#

I wonder if it would be cleaner to do it my way though... Make a sensor that updates every X mins and spits out the timestamp. Then I can take my existing template and just replace now() with states('sensor.5_min_timestamp') or whatever

#

That would be reusable as well. Though kinda awkward to have a sensor for that.

inner mesa
#

Seems like a lot of work to avoid a YAML sensor

#

Use the right tool for the job

atomic blade
#

Yeah sorry, nothing against YAML, just considering alternatives

#

I think if I cared about it updating when the battery sensors updated my solution would be more attractive than it is

#

Because it does feel awkward to have to specify them manually as triggers

#

And if this is something I'd want to do a lot, I think the reusability of the sensor is desirable

languid pendant
#

Can anyone please help me with my automation https://pastebin.com/K8FwhfPe , I think the problem lies with the value_template: "{{ 'days' in trigger.calendar_event.summary }}" I just can't figure out how to write it??

atomic blade
spark vortex
#

what is wrong with the yearly template sensor counter? it always shows 00:00:00 while tv is on, and start to count when it is off
https://pastebin.com/v3Z1HEdd

languid pendant
#

the problem I'm having is with the calendar condition, I want it to fire with the calendar "on" and the summary

atomic blade
#

Have you tried using the trace feature for your automations?

#

Also have you tried using the template dev tools to validate your templates?

#

The trace tool will help show you what values are such as in the triggers and then you can use that to fill in values when using the template dev tools

languid pendant
#

I never used any of those, but so far never had an automation this complex, will give it a try

spark vortex
#

your so nested conditions are almost impossible to read

#

can you explain the logic?

languid pendant
#

it's the value_template that's not correct:
- condition: state
entity_id: calendar.menu
state: "on"
- condition: template
value_template: "{{ 'sunday' in trigger.calendar_event.summary }}"

marble jackal
spark vortex
spark vortex
marble jackal
spark vortex
spark vortex
honest ravine
#

How can I create a helper with attributes?
Example: I would like a light helper with binary state (on/off) and integer/float attributes for previous_color and previous_brightness.
These values would be set and read by several automations.

fast ice
#

Hi there,

We have a few window blinds that can be controlled (tilt and lift), however, the lift function should only allow a rango of 0% till 80% (when using more than 80% the ropes will jam as 80% is 100% in the physical space). Currenlty i have a few buttons that have preset values in them.

Now i want to add the entity to homekit, however, it gives the full control (over 80% lift). Is there a way to 'simulate' the entity where the lift will have a translated value, so that 100% is actually 80%?

marsh cairn
#

You can use a template cover and use a 0.8 multiplication in it

fast ice
#

Thanks, i'll take a look at that πŸ™‚

marsh cairn
#

I'm using one for my venetian blinds. I just want them to operate between 0 and 50% (50% is open and everything else would be closing the other direction)

#

I can share my code as an inspiration (you would have to modify everything to your needs)

fast ice
#

Awesome, that will help me out a lot ❀️

marsh cairn
#

You can't use that 1:1 for usual blinds. But with the documentation, you should be able to modify it

honest ravine
haughty breach
honest ravine
#

Thanks. I don't know why the search engine never found that.

spark vortex
#

how can I keep the data for an history_stat sensor for one year? utility meter is ok, but the original format is hh:mm:ss and it just keeps a number

sonic nimbus
#

https://pastebin.com/k0v3kMXM I ahev an issue with templating actions part. It says that extra keys are not allowed in section actions.
Do you have some hints on this?

obtuse zephyr
lucid thicket
# spark vortex how can I keep the data for an history_stat sensor for one year? utility meter i...

You’ll need to clarify if you want to save all the data or just the statistics data. Here’s a nice description I found on the forums:

https://community.home-assistant.io/t/long-term-statistics-what-is-the-retention-policy-and-how-can-it-be-changed/335050/9

If long-term statistics are sufficient then the post a few down from that has the requirements:

https://community.home-assistant.io/t/long-term-statistics-what-is-the-retention-policy-and-how-can-it-be-changed/335050/15

shadow hare
#

I have a z-wave magnetic binary_sensor on my garage door that has zome bounce when open/closing messing up my automations. Some searching looks like I want to use delay_on and delay_off to add some debounce to solve this, seems reasonable, but I'm not sure the intended way to do this. It seems I can't add these parameters to the door sensor itself, rather I create a template that wraps the existing sensor and creates a new one? Is this true? If anyone has an example I would be grateful as all of my attempts so far have failed.
This is what I have now:
`template:

  • binary_sensor:
    • name: Garage Door Debounced
      state: "{{is_state('binary_sensor.garage_door_window_door_is_open', 'opened')}}"
      delay_on:
      seconds: 1
      delay_off:
      seconds: 1`
inner mesa
#

a binary_sensor will never have a state of opened

#

it can be on, off, unavailable, or unknown

#

otherwise, there's nothing wrong with creating a template sensor to debounce, as you've done

shadow hare
slate fossil
#

@mighty ledge Can you help me understand something regarding your seasons.yaml ? In the events, you define yaml ('halloween', md(10,8) | as_datetime ), ('soft', md(10,31) | as_datetime ),where soft corresponds with scene.holiday_bulbs_soft_white.
Does this mean between October 8 - 30 the Halloween scene will be active but on October 31 the soft scene will be active? Shouldn't it have a + timedelta(days=1) to ensure your spooky scene is active on Halloween?

mighty ledge
slate fossil
#

was updated two weeks ago

mighty ledge
#

not sure why it's showing 10,31 for you?

#

showing 11,1 for me 🀣

#

All I changed in my last update was to have the lights for the full month of october

slate fossil
#

Gotcha. I just looked and do see that change made. You must have done it right after I started looking into it. Which is weird because I was asking about it a week ago. #templates-archived message
Maybe I had already copied the code into Dev Tools beforehand.

mighty ledge
#

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

heavy crown
#

On these 'seaonal' things, I have calendars as well covering those....could you maybe elaborate on the benefits that YOU see with the yaml one? I like HA for its flexibility but am sometimes getting 'nuts' on what to choose and thus need use cases πŸ™‚

slate fossil
#

I intend on using the yaml one to determine if there is a holiday season scheduled (per the events); if not, then it returns none, for example. (The equivalent to Petro's soft scene.) The entity will then be able to be used to change the animated-background on my tablet dashboards. A time_pattern trigger will be added so the sensor can be updated hourly, thus triggering a state change the animated-background can see.

#

I decided to go this route as it let's me define what holidays I want to incorporate into the backgrounds and does not include holidays that I don't. Additionally, one of the scheduling calendars I looked at would only do Federal holidays but not "lesser" holidays.

spark vortex
heavy crown
#

I do admit that I am not sure about VERY long term ... I use them to ttrack my sons gaming PC on and my daughters lights

spark vortex
heavy crown
#

Check... I did not know this until now...which makes the wording 'stats' a bit misleading vs the other stats...or maybe not...history is related to the rec-history...anyhow...not 100% transparent to mix the both (for me) πŸ™‚

spark vortex
#

yeah, history_stats is not statistics

lucid thicket
spark vortex
lucid thicket
#

From the second link in my first reply:

For long term statistics to be generated for a sensor… all it needs is a valid device_class a state_class of measurement and a unit_of_measurement

#

Do you see each of those things specified in your sensor config?

spark vortex
lucid thicket
#

Looks good to me πŸ‘

spark vortex
#

ok, so I have thsi data forever in statistics

lucid thicket
#

To verify it is there, add a statistics card to a dashboard to plot it out

spark vortex
#

yes, I did and I can see the data in the graph-statisitcs card

lucid thicket
#

To be clear, you have the statistics data forever. You don’t have every data point

spark vortex
#

yes, but I just need the hours count per year, I already have other sensor for aggregation per day/week/month

lucid thicket
sonic nimbus
#

how to store a bunch of playlists of a youtube, and to play it randomly?
for example:

leaden hatch
#

actions not allowed for some reason

inner mesa
#

does anyone see anything wrong with that simple example?

marble jackal
#

No, it doesn't

inner mesa
#

because you may need to grab data from the trigger?

marble jackal
#

And if it would, it would have the same issue as pressing RUN in the Automation GUI, there is no trigger, do everything relying on the trigger doesn't work

inner mesa
#

Yeah, I suppose so. Just seems like an unfortunately long and confusing error

#

The intended use case was to have a sensor updated periodically, but be able to force it sometimes. I guess you'd need an event or some other trigger for that, assuming that you weren't relying on the trigger data

marble jackal
#

But I know Marius asked about it a while ago, that's how I knew it didn't work πŸ˜…

inner mesa
#

I think I'd prefer to see it actually try and then fail to resolve some trigger data

#

the failure shouldn't be due to the service call

marble jackal
#

If you really want you can of course add a call_service event πŸ™‚

inner mesa
#

that's what happens with automations and "run", after all

#

this behaves differently, and kills a useful use case

marble jackal
#

Yeah, I only know that it doesn't work, never tried it myself. But indeed, it would make sense to allow it, and just log errors about the missing trigger variables

#

And make the state unknown

inner mesa
#

there's no sensor.trigger πŸ™‚

#

in any case, I added some verbiage to the issue and left it open

#

thanks for pointing that out

karmic sapphire
#

is there an easy way to get an entity id from a friendly name in a input dropdown list

obtuse zephyr
#

Sort of... friendly names aren't required to be unique though, so there is the potential for there to be multiple matches. The most naive way is to do this, but if you can filter it to a domain, that'd be better

{{ states | selectattr('attributes.friendly_name', 'eq', 'A Name') | map(attribute='entity_id') | first }}

karmic sapphire
#

I was trying to do something like this entity_id: "{{ states('input_select.speakers') }}"

#

for a target

obtuse zephyr
#

Sure, and that will only work if that's an entity id

So, if you wanted to use the above, it'd be something like
{{ states | selectattr('attributes.friendly_name', 'eq', states('input_select.speakers')) | map(attribute='entity_id') | first }}

karmic sapphire
#

Oh that works

#

Thank you so much

#

whats eq do

obtuse zephyr
#

equal

karmic sapphire
#

ah

karmic sapphire
#

thanks

obtuse zephyr
#

You're welcome

leaden hatch
#

quick question: how can i get calendar events only for the "current day". so in this case... everything from sunday, not monday. however at midnight, i want all from monday, not other days...

#

i call the service calendar.list_events... i was thinking of calling it once at midnight with a duration of 24h ... but that would mean during the day , the calendar can't update

#

i'm creating a template sensor for this now, that runs every hour

#

but then the duration doesn't work...

#

so i would need a "now" from 00:00:00 until "now" 23:59:59

#

wait... is it as simple as:

#
- service: calendar.list_events
      data:
        start_date_time: "{{ now().date() }}"
        duration:
          hours: 24
#

does it "default" the time to 00:00?

marble jackal
#

{{ today_at() }} will be midnight

leaden hatch
#

I have 2 questions: they both are on things that work, however, i think it could be "better" or at least "prettier" πŸ˜‰ how would i go about this?

#

do i start a thread for both? so i don't spam this one? or just ask here?

#

i get the feeling i'm missing ... concepts of it all. the whole templates,triggers, actions, sensors, variables, attributes are messed up in my head

marble jackal
#

now().date() just returns today's date. As there is no time info anymore, it will use midnight I guess

#

But to me it seems a bit of a hack

#

There are some links in the topic description to guide you

#

And also in the pinned posts

leaden hatch
#

i've done more hacky things in my life πŸ˜‰ but i want to do this "well" so i'm looking for guidance

#

there are many things on the website/forums... but no "best practices"

#

but i'll have a look

marble jackal
#

As always there are many ways to skin a cat. I will do things differently than others. But if you have specific questions I can tell how I'd tackle it

leaden hatch
#

i have to leave now, however... this evening, i will be back and if i find the courage, i'll ask πŸ˜‰

#

thanks ina dvance.

mighty ledge
#

Yep, it works, so it's usable. No PR needed.

marble jackal
#

Vacation over?

mighty ledge
#

ya

sonic nimbus
#

Hello Im getting an error for this variables:

{% set hallway_livingroom_main_light_last_changed = as_timestamp(states.light.hallway_livingroom_main_light.last_changed) %} 
{% set rotary_encoder_last_changed = as_timestamp(states.binary_sensor.hallway_actuator_button.last_changed) %} 

error:

ValueError: Template error: as_timestamp got invalid input '' when rendering template '{% set hallway_livingroom_main_light_last_changed = as_timestamp(states.light.hallway_livingroom_main_light.last_changed) %} {% set rotary_encoder_last_changed = as_timestamp(states.binary_sensor.hallway_actuator_button.last_changed) %}' but no default was specified

What does it mean bu default value?

#

'None' has no attribute 'last_changed' => when I just put {{states.binary_sensor.hallway_actuator_button.last_changed}}

sonic nimbus
sonic nimbus
marble jackal
#

@sonic nimbus You probably have a typo in the entity_id

#

That error indicates the entity_id doesn't exist

#

encoder vs actuator

spark vortex
#

how to translate a float(number_of_hours) in a readable time format?

marble jackal
#

(float(number_of_hours) * 3600) | timestamp_custom('%H:%M'), false)

spark vortex
#

even if the hours are more than 24?

obtuse zephyr
marble jackal
spark vortex
#

that is my problem, the number of hours that I have in the sensor is greater than 24

marble jackal
spark vortex
#

it counts the number of hours that a device is on in a year, so I can't predict

marble jackal
#

You can use %-j but then you need to subtract 1 from it

#

But how relevant is the number of hours if you are already counting days?

#

Do you really care if it's 12 days and 3 hours, or is 12 days enough?

spark vortex
#

for me is even good if I can have something like 12323:34:34 where the first number are the hours

#

I just need the hh:mm:ss doesn't matter if the hours are more than 24

marble jackal
#

So what does your sensor give? You just want to convert 5.5 to 5:30?

sharp plaza
haughty breach
#

Have you added the WebOS Smart TV integration to your Home Assistant instance?

sharp plaza
#

yes

sharp plaza
#

if you want i can screenshare for you and you can explain it to me in vc

plain magnetBOT
#

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

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

sharp plaza
#

like this is the code i want to implement. but where in the web interface do i put it?

#

@haughty breach

haughty breach
gleaming charm
#

I have a dumb templates question: I have 2 temp sensors that I want to reformat the output of. Do I have to do a replace template for each one?

#

That is, is there any way to say if device type = X, reformat output as Y

sharp plaza
gleaming charm
#

I have a working template to reformat the reported value for a sensor that is reporting a temperature, but I have 2 devices that need this reformatting. I don't see any way to duplicate the template, but it seems the only way to get the identical formatting applied to 2 different sensors is to create 2 templates with each one specifying the entity's value that is to be reformatted. Is there a way to create a template so it applies to multiple specified entities?

gleaming charm
#

Never mind, the answer is yes there is a way

plain magnetBOT
fast lotus
#

Hello Guys,
Newbie here, so I'm working with Mushroom to create a mobile Dashboard and I really like it but I have a question now. I want to create a Button where I click and I call a service and open my Lock of the House. So my Idea is the Icon Color is red (as the Lock is closed) when I now make my primary Action which is calling my Service to Open my Lock I want to change the Icon Color to Green then wait 5 Seconds and make it switch back to red. I hope you know what I mean. My Code at the moment is this: https://dpaste.org/8Bo4Z
Is something like this even possible to make with mushroom and what would be the way to go? Much thanks in advance for your help!

obtuse zephyr
fast lotus
#

Yeah but that doesn't work for me because its no lock what I can lock and unlock its just a service with open the door downstairs and for my flat I don't have a smartlock didn't get It working how I like it

stark sand
#

Hi Y'all, not sure if this is the right place to ask this question so please let me know if I'm in the wrong place.

I am trying to create a custom intent and intent script that has some basic logic to define the response. The log is as follows and works in the Template tester:

{% if float(states('sensor.soil_moisture_2')) > 30 %}
  {{'Fittonia is not thirsty!'}}
{% elif float(states('sensor.soil_moisture_2')) < 30 %}
  {{'Fittonia is thirsty!'}}
{% endif %}
inner mesa
#

Those tests are the same

stark sand
#

Yeah sorry, edited to fix it

inner mesa
#

You just need an 'else'

stark sand
#

I am trying to get this into my config.yaml in the intent script but I can't seem to figure out how to properly use the if statement with the intent_script. This is what I tried that didnt work:

intent_script:
  FittoniaThirsty:
    speech: >
      {% if float(states('sensor.soil_moisture_2')) > 30 %} 
        text: "Fittonia is not thirsty!
      {% elif float(states('sensor.soil_moisture_2')) < 30 %}
        text: "Fittonia is thirsty!"
      {% endif %}
inner mesa
#

You can't template keys like that

stark sand
#

Bummer

inner mesa
#

you don't need to

#

I have no experience with intents, but it's a simple change

#
intent_script:
  FittoniaThirsty:
    speech:
      text: "{{ iif(states('sensor.soil_moisture_2')|float > 30, 'Fittonia is not thirsty!', 'Fittonia is thirsty!') }}"
stark sand
#

Ahh I see

#

That makes more sense

#

Let me try that

inner mesa
#

I don't even know if you can put a template there...

stark sand
#

Looks like its working!

inner mesa
#

ok, looks like you can

stark sand
#

Oh bummer, can't post the screenshot of the assistant's resposne...so I guess trust me it worked?

inner mesa
#

no need, I'm sure it worked

stark sand
#

lol, thanks!!!!

stark spindle
#

Any template wizards about that might be able to assist me with something that's probably very simple?

{{ 'home' if is_state_attr('calendar.xander', 'message', 'Xander\'s Home') and is_state('person.sy', 'home') else 'not_home' }}

That's what I have now, and was working fine until a few weeks ago.
For some reason it fails to action now.
The main issue I have is it seems to change the state to home, at the beginning of the day, I'd prefer for the state to change to home at event start, upon reloading of HA if the event is still live and change to not_home at event end.

I've even tried the calendar events in automations to no avail.
I'm running out of hair to pull out...
Thanks for any assistance in advance

vale osprey
#

Hi, how can I add two time helpers together and store them in another time helper, as an action in an automation please?
I tried doing something like this:
`action:

  • service: input_datetime.set_datetime
    data:
    time: {{ (as_timestamp(state('helper.medicine_1_reminder_time')) + as_timestamp(state('helper.medicine_1_frequency'))) | timestamp_to_datetime }}
    target:
    entity_id: input_datetime.medicine_1_reminder_time`
    If i set the time to a fixed time example: "12:00:00", it works
    so i'm assuming im doing something wrong in the logic to add the helpers together
obtuse zephyr
mighty ledge
mighty ledge
vale osprey
mighty ledge
vale osprey
mighty ledge
#

Stop using bard πŸ˜‰

#

it's 100% wrong

#

find out your entity_id's, that's step 1

#

once you have those, we can help you with a template

#

but right now, your entity_id's are wrong for both of the helpers.

#

it even made up filters that don't exist

#

Stop using AI in general and learn this stuff yourself. AI for HA is typically wrong

vale osprey
weary frigate
#

Got an oil monitor sensor using the rtl_433 add-on reporting to mosquitto that is tracking the height between the top of the tank and the oil, which I'm then converting into the remaining oil via a simple template:

{% set currentDistanceToOil = states('sensor.' ~ states('input_text.oil_tank_sensor_name')) | float %}
{% set fuelDepthRemaining = states('input_number.oil_tank_height') | float + states('input_number.oil_sensor_offset_to_fill_level') | float - currentDistanceToOil | float %} 
{% set oilRemaining = (states('input_number.oil_tank_capacity') | float / states('input_number.oil_tank_height') | float) * fuelDepthRemaining | float %}
{{ '{:.2f}'.format(oilRemaining) }}

However I'm not sure how to handle the initial sensor states('sensor.' ~ states('input_text.oil_tank_sensor_name')) returning unavailable after a HA restart. I thought since mqtt was defaulting to persistance that setting the rtl433 to enable retain would be enough, but it appears that after a full HA restart (causes mosquitto and rtl433 addons to restart) reading the sensor doesn't work until it has transmitted. Looking around the only suggestion I've seeing is to add an automation to trigger on change to the original sensor to set an input number. Is that still the best way to handle persistence?

mighty ledge
vale osprey
mighty ledge
#

ok

#

gimme a sec

#
{{ states('input_datetime.medicine_1_next_reminder_time') | today_at + states('input_datetime.medicine_1_frequency') | as_timedelta }}
#

and

#

you need to change how you put that template into the service call...

#
 - service: input_datetime.set_datetime
   data:
     datetime: "{{ states('input_datetime.medicine_1_next_reminder_time') | today_at + states('input_datetime.medicine_1_frequency') | as_timedelta }}"
   target:
     entity_id: input_datetime.medicine_1_reminder_time
mighty ledge
#

in general, you can make that template better too

#

do you have an availability template that goes with that?

#

if yes, please post the entire sensor configuration.

#

Also, just looking at your template, it doesn't make sense IMO. The math that is.

#

it seems you're just using all input helpers for it too. Is this template 100% manual? How are these input entities being populated?

#

I'd wager there's a much better way to handle this, I can help you with the template.

#

@weary frigate ^

weary frigate
#

@mighty ledge are you suggesting the default for the float should be the current value? I had that and it resulted in various things thinking the tank was full for a period and messing up counters. The template is added via the UI, not seeing any way to add an availability template. However if I do use one, would that not result in any cards generated based on this being also unavailable or invalid until a suitable value is provided by the sensor?

#

I'm using input helpers as my initial numbers were estimates and I wanted to make it easier to update them. Essentially there is an distance between the oil monitor and the max fill point that needs to be accounted for, then after that a simple max oil vol * (depth of oil remaining / maximum depth of oil when full) to get the proportion of the max oil

#

Oil sensor is about 8cm higher than the max fill level, so any measurement it gives needs to be adjusted before calculating the proportion of the tank remaining

mighty ledge
marble jackal
#

It's made in the GUI (he mentioned that above) so it's not much more than the template

#

The template is added via the UI

mighty ledge
#

ah I missed that

#

Well your only option is to add a default for the float value.

#

otherwise, if you do this in yaml, you can make the sensor go unavailable when the text doesn't resolve to a real value

weary frigate
#

is the previous value of the template sensor available to use as a default after a restart? I just presumed not

mighty ledge
#

The input_text should be populated at startup with your last value, so the template sensor should never be unavailable. Unless you're doing something with an automation.

#

not sure why you're using an input_text anyways

#

as that's the root of your problems

#

you can use a input_select, that restores state as well

weary frigate
#

The input text is resolving fine, it's the sensor it references that is unavailable and I can see that when I look directly at it

marble jackal
#

probably the only one which can be unavailable is 'sensor.' ~ states('input_text.oil_tank_sensor_name')

mighty ledge
#

as thefes is pointing out

marble jackal
#

or after restart before the sensor is ready

mighty ledge
#

all input_helpers should restore state instantly, so it should work at startup

#

ah, I just noticed it's sensor.

#

so, the problem is with that sensor. and the only way to overcome it is w/ an availability template. Which can only be done in yaml.

weary frigate
#

The resulting sensor that resolves to is marked unavailable which is the problem. Until it reports in after a restart, I can't seem to paste an screenshot to show it. 'sensor.' ~ states('input_text.oil_tank_sensor_name') resolves to 'sensor.Oil-SonicSmart-145565457'

mighty ledge
#

well, that's an incorrect entity_id

#

regardless the states will sluggify it

#

however, the statements still stand

weary frigate
#

sorry, copy and pasted the wrong text, it's 'sensor.oil_sonicsmart_145565457_d'

mighty ledge
#

the only way to account for it is with an availability template

weary frigate
#

Which is not possible to define through the UI?

mighty ledge
#

no, as i've said 3 times now

weary frigate
#

Sorry, didn't spot the message

analog mulch
#

Hi! I want to have a trigger which will fire at a particular time offset form the next_midnight property of sun.sun, something like

now() > as_local(as_datetime(state_attr('sun.sun','next_midnight'))) - timedelta(hours=10)

I would like to make sure that it doesn't fire if I've missed the time because e,g. HA was offline. Is that guaranteed already here or do I need to have a slightly offset time on the other side of the now(), so that it doesn't resolve to true for more than e.g. a minute around my desired trigger?

marble jackal
#

you can do:

{% set mn = as_local(as_datetime(state_attr('sun.sun','next_midnight'))) %}
{{ mn - timedelta(minutes=1) > now() > mn }}
analog mulch
#

yeah -- I was wondering if that's necessary. I guess it is. πŸ™‚ Thanks!

vale osprey
mighty ledge
#

it's covered in the template documents

#

you can find all the resources in this channels pins

vale osprey
mighty ledge
silent vector
#

How would I get this to also account for days?

This is currently false because it's not looking at the date just the time.
{{ ((now() - '2023-10-22 08:20:56.702736-04:00' | as_datetime).seconds > 15 * 60) }}

obtuse zephyr
#

You can use the total_seconds() method as opposed to the seconds property to get the full duration

mighty ledge
#

you should pretty much only use total_seconds() if you want the full duration in seconds.

#

I personally never use any of the other attributes unless you're specifically going for the non-day ammount.

silent vector
#

How would I use it because I just got
TypeError: '>' not supported between instances of 'builtin_function_or_method' and 'int

obtuse zephyr
#

You're missing ()

silent vector
#

Awesome got it

analog mulch
#

Is there a fixed order in the evaluation of the template sensor's state vs atributes? e.g. For a trigger-based sensor, can I assume that the state will have evaluated prior to the evalution of attributes, so that if i use its value, it is the current one? At least in this.state

marble jackal
#

in a trigger based template sensor this will be created on the trigger, and will not change

#

so it's the same for the state and the attributes

#

for non trigger based template sensors it will update the state first, and after that this.state will be the new state in the attributes

analog mulch
#

so what happens if I have an attribute that uses this.state in its calculation?

#

trigger-based

marble jackal
#

then it will be the previous state (so at the time at the trigger, before the new state is rendered)

analog mulch
#

ok thanks!

hybrid merlin
#

Is there a way to pull out the next event time (or time until next event) for a specifically named recurring event on a Local Calendar?

For example, if I have a calendar with "Event A" recurring twice a week and "Event B" twice a month, is there a template I can use to create template sensors to tell me when the next "Event A" and when the next "Event B" is? Or do I need to use separate Calendars for that?

lofty mason
wanton sapphire
#

hi all, is there an easy way (probably not lol) to convert string 'five' to 5 or any other word number into its int?

mighty ledge
#

in the release it occured in

#

i'll have to find it

wanton sapphire
#

yes but that's not what I asked for. That's the actual opposite

inner mesa
#

Same idea

wanton sapphire
#

I need text to numeric, not numeric to text

marsh cairn
#

Only five or any number?

wanton sapphire
#

any