#templates-archived

1 messages Β· Page 58 of 1

tardy stirrup
#

what got rid of the config issue was adding "template" into the platofrm line, which I didn't have before

lofty mason
#

do you get a value if you put this into developer-tools/template?

{{ state_attr('air_quality.laseregg_air_quality', 'Carbon_dioxide') }}
#

that's a good first step

tardy stirrup
#

omg, got it, i capitolized "C" in Carbon_dioxide because that is what it read on the attributes panel

#

lower case "c" worked

inner mesa
#

devtools -> States tells you what it really is

tardy stirrup
#

can someone briefly explain why i needed to add "template" after the - platform line?

#

the original recommendation from Github convo was:

in Sensors.yaml

sensors:
sensedge_co2:
value_template: "{{ state_attr('air_quality.sensedge_air_quality', 'carbon_dioxide') }}"
device_class: carbon_dioxide
unit_of_measurement: ppm```
#

but that did not work for me

#

I just don't understand the difference in approach and how I got it to work

#

I'm trying to actually learn, not just make things work... which is new to me πŸ™‚

languid pendant
#

which?, learning, or not just mking things work?

tardy stirrup
#

learning... i usually am just satisfied making things work, following other people's content - but i'd like to understand what i'm actually doing here

languid pendant
#

I can dig it.

#

I think the answer to your question might be right in front of your nose, though - (YOU are the one creating the (templated) sensor, not loading the sensor from an integration/addon)

lofty mason
#

please use triple backticks when posting code for formatting

tardy stirrup
#

sorry, still trying to figure that out

lofty mason
#

no problem

#

Better to try to go to the official documentation than old forum posts

tardy stirrup
#

will discord not apply the triple backticks after the fact

#

in edit

#

or am i just doing it wrong

lofty mason
#

you can edit it

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.

lofty mason
#

Looks like you confused single quote for backtick, wrong character.

tardy stirrup
#

yep, thanks. got it

#

finally

#

so the format that I'm using that works, is old, and no longer recommended

#
    sensors:
      sensedge_co2:
        value_template: "{{ state_attr('air_quality.laseregg_air_quality', 'carbon_dioxide') }}"
        device_class: carbon_dioxide
        unit_of_measurement: ppm```
clear mist
#

hey guys, not sure if this is the right place but i want to make a script that takes some input data (2 numbers, a string and a bool) and then sets the value of input_numbers/input_string/input_bool to those values - how would i do that, and how would i call that in automation?

#

i just can't get my head around how to give something an external value and then have the script read that value

inner mesa
#

Shows you how to write the script, use a variable, and how to call it

river coral
#

Do templates have access to all entity properties or only what's exposed through the "state" property?

inner mesa
#

What is an entity property?

river coral
#

I don't know what they're called in the UI, I just mean "property" in the Python sense

inner mesa
#

You cannot access them

river coral
#

interesting. So how do cards like the todo list card show them? Do they have special access beyond what templates provide?

lofty mason
#

there is a core websocket API that can give todo list items

clear mist
acoustic urchin
#

How can I count a decrease of a sensor to one meter and an increase to another meter?

sacred sparrow
#

lights color_temp never used to be defined when the light was off - did the new update change this? all my lights now show up in the list when I do: {{ states.light|selectattr('attributes.color_temp', 'defined')|map(attribute='entity_id')|list }}

quick prairie
#

Hi all, does anyone know the problem that on the energy dashboard every day the whole value is written to the statistic every day at around 8pm and 6am?
I already postet this question in #energy-archived but they think it is a templating issue. Maybe somethink is wrong with it. Here my template that I use to calculate the entity

  - sensor:         
      - name: pv_production_total
        unique_id: "PVProductionTotal(kwh)"
        state_class: 'total_increasing'
        unit_of_measurement: 'kWh'
        device_class: 'energy'
        state: >
          {% set l1 = states('sensor.victron_pvinverter_l1_energy_forward_total_20') | float %}
          {% set l2 = states('sensor.victron_pvinverter_l2_energy_forward_total_20') | float %}
          {% set l3 = states('sensor.victron_pvinverter_l3_energy_forward_total_20') | float %}
          {{ (l1 + l2 + l3) | round(1, default=0) }}

Here is the ticket I opened but I think it is not a integration issue https://github.com/sfstar/hass-victron/issues/136

flat grail
#

is there a way to convert days to Year, months, days

I have a sensor that returns a value in days (example, 800 days)
Is there a way of converting that to 2 years, 2 months, 9 days ?

marble jackal
#

yes, I created a macro for that

#

you'll need to convert the days to seconds though

flat grail
#

its already converting to get days, I will adjust to make it seconds

marble jackal
#
{% set days  = 800 %}
{% set seconds = 800 * 24 * 60 * 60 %}
{% from 'relative_time_plus.jinja' import relative_time_plus %}
{{ relative_time_plus(seconds, parts=3, compare_date=0, week=false) }}
flat grail
#

I will play with that in the template tool

#

thanks

marble jackal
#

This will give 2 years, 2 months and 10 days

#

seems to be a day difference with yours πŸ™‚

#

that's probaly because I compare it with first of January 1970

flat grail
#

how do I add it via HACS?, Searching doesnt find it

marble jackal
#

no conversion to seconds needed

{% set days  = 800 %}
{% from 'relative_time_plus.jinja' import relative_time_plus %}
{{ relative_time_plus(now() - timedelta(days=days), parts=3, week=false, time=false) }} # 800 days ago
result: 2 years, 2 months and 9 days
{{ relative_time_plus(now() + timedelta(days=days), parts=3, week=false, time=false) }} # 800 days from now
result: 2 years, 2 months and 7 days
#

you need to have experimental mode enabled in the HACS settings

plain magnetBOT
compact rune
# quick prairie Hi all, does anyone know the problem that on the energy dashboard every day the ...

@quick prairie probably the value of your template is dropping to 0 at those times, then jumping back up to the accumulated/summed value. If you use the availability to instead make the sensor unavailable when that happens it will probably correct the issue. It could be that you're getting unusual values when some of your source sensors are returning data and others aren't, or they might be returning nothing overnight, or something like that; you'll need to look at the history of your sensors to see what's going on

quick prairie
#

@compact rune Thanks a lot for the help. I will try this option. Hopefully tomorrow the will be no more issues with it πŸ™‚

marble jackal
#

@flat grail FYI, I just updated the macro, and made the instructions for HACS more clear

analog mulch
#

I'm setting up a trigger-based sensor with a trigger with variables defined. Does this exist when the trigger is triggered, so that I can use it in the templates under the variables key? Or is it only available once we are evaluating the state? I've noticed that my trigger has stopped triggering and the only difference between my old version and this one is the use of "this"

marble jackal
#

this in a trigger based template sensor works the same as in an automation. It is created on trigger, and doesn't change anymore during the whole process of calculating the values in the sensor (both state and attributes)

#

just check the logs for issues

analog mulch
#

my bad -- I used states.this

mighty ledge
#

well that's your problem

#

this.state

#

this is a state object (or at least it emulates one)

analog mulch
#

yeah -- evidently I'm not so great at this debugging business πŸ™‚

mighty ledge
#

always check the logs, it's going to be your goto for issues

mild mica
#

i used the UI to build a template sensor yesterday, but now its showing as unavailable
not sure what happened or how to fix it

mighty ledge
#

check your log for errors and then fix the errors

mild mica
#

why can't i delete it?

#

i haven't changed the template

mild mica
#

i forced the template to have good data. still can't delete it

{% if 4 <= 700000 %}
  0.021086
{% else %}
  0.011943
{% endif %}
analog mulch
#

Hmm, it seems that this still gives me trouble: I get the following in the log: Template variable error: 'this' is undefined when rendering '{% set temp_hist_store = this.attributes.get('temp_history',{})%}
this is called by the template: temp_hist: >- {% set temp_hist_store = this.attributes.get('temp_history',{})%} {% if hour_solar in [7,14,21]%} {% set temp_prev = temp_hist_store.get('last_'~hour_solar,13.6)%} {% set temp_hist_store = dict(temp_hist_store,**{'previous_'~hour_solar: temp_prev,'last_'~hour_solar: T_curr})%} {% endif %} {{temp_hist_store}}

#

Is it supposed to be this.state.attributes?

mild mica
#

yeah the template UI editor is busted. how does one force delete one of those templateS? where is HA shoving them?

marble jackal
#

put it in the action section

#
- trigger:
    - platform: template
      value_template: >-
        {% set midnight = as_local(as_datetime(state_attr('sun.sun','next_midnight')))%}
        {% set mins = ( now().minute == max([5,midnight.minute+1]) )%}
        {% set new_day = (today_at('00:00:10') <= now() < today_at('00:01:00'))%}
        {{mins or new_day}}
  action:
    - variables:
        hour_local: ...
  sensor:
    - name: ...
violet kite
#

any good ways to subtract two entites from each other?

sensor.solarpowertotal - sensor.home_energy_meter_electric_consumption_w

both are in watt units

"{{ ( states('sensor.solarpowertotal') | float | round(1)) - ( states('sensor.home_energy_meter_electric_consumption_w ') | float | round(1)) }}"

is what i've made so far but i'm getting an unknown when rendering template

mighty ledge
#
{{ (states('sensor.solarpowertotal') | float - states('sensor.home_energy_meter_electric_consumption_w') | float) | round(1) }}
violet kite
#

hm it seems to just be displaying the first value not the subtraction

#

first value being the solar power total

mighty ledge
#

that means your second value is 0

violet kite
#

ah it was cuz my second value was set to KW not W

thankyou!

spiral imp
#

I have a vibration sensor to indicate if my garage door is opening or closing. It takes 4 secs to go from fully open to fully closed. Is there a way to create a template to distinguish between opening and closing?

violet kite
#

probably a toggle entity and have it triggered by the vibration sensor

only down side is that it could go out of sync if someone bumps the garage door hard enough

vibration detected -> toggle entity "on" "open"
vibration detected - > toggle entity "off" "closed"

again - i come along and bump your garage, now that sensor is screwed up

i would suggest a door sensor vs. vibration

spiral imp
#

I have both. I have a tilt sensor that indicates open or closed. I am trying to solve for opening and closing because there is a short time when the tilt becomes horizontal (on / open) but the door is still vibrating and same with closing

mighty ledge
sly adder
#

Hi all! Does anyone know of a way to display "days until the next week day (e.g., Saturday)"?

mighty ledge
#
{{ 5 - now().weekday() }}
#

or if you want it to work on sunday

{% set w = now().weekday() %}
{{ 5 - w if w <= 5 else 12 - w }}
sly adder
#

Oh awesome, thanks!

mighty ledge
#

the eq will change for every day

sly adder
#

Never knew about weekday()

mighty ledge
#

0 is monday btw

#

6 is sunday

terse walrus
spiral imp
#

the vibration lasts 4 secs if that is useful

analog mulch
marble jackal
analog mulch
#

At least only a month behind! πŸ˜‰

spiral imp
#

Can I set the state of a sensor when a different sensor state changes and have that be conditional on a third sensor?

mighty ledge
#

just make a template sensor

#

adjusting an entities state is not suggested

analog mulch
spiral imp
#

this goes back to my garage door, I was thinking that I could create a template sensor that for example, get set to "opening" if the tilt sensor is "off" and the vibration sensor changes from "off" to "on" but not from "on" to "off". Is that possible?

marble jackal
#

It's not VSCode which is complaining, it's the HA extension, in which this is not added yet

mighty ledge
#

95% sure I already said that

spiral imp
#

you did, i am just confused on how to accomplish that

mighty ledge
#

with a trigger based template sensor

#

the logic may be hard, but post what you've tried when you try something

spiral imp
#

will do, thanks

spiral imp
quick prairie
#

@compact rune I change the template

- sensor:         
      - name: pv_production_total
        unique_id: "PVProductionTotal(kwh)"
        state_class: 'total_increasing'
        unit_of_measurement: 'kWh'
        device_class: 'energy'
        availability: 'yes'
        state: >
          {% set l1 = states('sensor.victron_pvinverter_l1_energy_forward_total_20') | float %}
          {% set l2 = states('sensor.victron_pvinverter_l2_energy_forward_total_20') | float %}
          {% set l3 = states('sensor.victron_pvinverter_l3_energy_forward_total_20') | float %}
          {{ (l1 + l2 + l3) | round(1, default=0) }}```                      
but I still get the same error. Do I used it the wrong way? Any ideas
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.

compact rune
#

You need the availability template to actually do something, it's not a yes/no thing

#

You need to figure out what states of the underlying sensors create the problem and then make the template sensor unavailable when there would be an issue

paper hazel
#

Any help will be much appreciated - I'm stuck on a brain teaser and not even sure if it is possible. Also, unsure which channel to post this, but figuring this could be done in the microcontroller or using a template sensor, I decided to start here, but I belive it will probably best to implement on the microcontroller itself (ESPHome). I need to recognise patterns to determine different states. The for main patterns I'm prioritising to recognise is:```

The digital input drives HIGH following a status LED on a motor controller.

Gate Closed: LED OFF, Input Pulled low --> Easy, and done.
Gate Open: LED ON, Input Pulled High --> Easy, and done.
Now, this is where I get stuck,
Gate Opening: LED Flashing at an interval of 0,5s
Gate Closing: LED Flashing at an interval of 0,2s
Gate Loss of Mains: 2 Flashes per second, off for 1 second. Then repeat.

lucid thicket
# paper hazel Any help will be much appreciated - I'm stuck on a brain teaser and not even sur...

ESPHome has a discord, I would recommend going there. I think you’ll have to measure the time between the input transitioning from low to high (rising edge trigger), and progress through a decision tree. E.g if it saw two edges in 0.2s then gate is closing. If it saw two edges in 0.5s then it’s either opening or loss of mains so you need to wait for two more edges and make a decision. If it’s been longer than 1s since the last edge, then check if the state is currently high or low and set it as open or closed, respectively. After the state of the sensor is set, the next rising edge would start the logic from the top of the decision tree.

north locust
#

trying to setup a notification automation to notify if WAN ip changes , but this notify does not give my IP address :

service: notify.mobile_phone
data_template:
  title: Your External IP address has changed
  message: Your new IP address is {{ states.sensor.router_extern_ip }}

outputs "Your new IP address is )>" ? something wrong with the template ?

compact rune
#

I'd try states('sensor.router_extern_ip') instead of states.sensor.router_extern_ip as a first step. What you have is probably getting a state object rather than a string of the state.

analog mulch
#

Hi. Is it possible to pass a state object inside a variables statement? I am doing this in a trigger-based sensor action statement: - variables: temps: "{{states.sensor.inpo_praha_temperature_today_average_test}}"
and then trying to use it as {% set temp_hist_store = temps.attributes.get('temp_history',{})%}
which gives me an error ```
Template variable error: 'str object' has no attribute 'attributes' when rendering '{% set temps_hist_store = temps.attributes.get('temp_history',{})%

#

The sensor.inpo_praha_t... in the variables is actually the sensor I am calculating itself. I tried using "this" originally, but "this" doesn't seem to get defined until the main sensor part - -it's not defined in the trigger or the action parts

marble jackal
#

you seem to be right, this is not available in the action part as well

robust prism
#

Hey all, I got a (guess) simple question, but not sure where to start. I have setup a template trigger sensor to get my daily calendar events for birthdays. Now that all works, and I get a new sensor with the amount of birthdays + the ones in there. It is possible that there are more celebrating on that day, so I get 1 or more records back from my 'scheduled_events' attribute. My goal is to show a template mushroom card with the names that are in the title of the calendar event.

How can I loop over those events, and get a certain attribute of it? My attributes I get from the sensor:
`scheduled_events:

  • start: '2023-11-03'
    end: '2023-11-04'
    summary: Linde jarig
  • start: '2023-11-03'
    end: '2023-11-04'
    summary: Nardy jarig . Linde jarig`
#

I just want to loop through the events and take the summaries and put them together

#

So the output in the example above must be: Linde jarig, Nardy jarig . Linde jarig

mighty ledge
#
{% for event in state_attr('sensor.xyz', 'scheduled_events') %}
  {{ event.summary }}
{% endfor %}
robust prism
#

@mighty ledge How simple can it be... Thanks a lot for your time

spiral imp
atomic pasture
#

Hi how can i change this to show information "This is your week" To display this for 7 days and then start counting again. this is based on calendar events that repeats every 35 days.
The idea is to show remaining time and once it is my time to throw bins i can see for a week that is my turn
At this moment its only counting down and once the day hit its reseting and counting again for next turn

Your bin week in:  {{ ((state_attr('calendar.michal', 'start_time') | as_timestamp - today_at('00:00') | as_timestamp) / 86400) | int }} Days
inner mesa
#

So just 'if that believes less than 7, display "this is the week"'?

#

It's just an if/then

atomic pasture
#

sorry not sure how to do that ;/ i have done this from yt tutorial but wanted to edit this a little bit

inner mesa
#

there are great docs in the channel topic, but here:

#
{% set days = ((state_attr('calendar.michal', 'start_time') | as_timestamp - today_at('00:00') | as_timestamp) / 86400) | int %}
{{ iif(days > 7, 'Your bin week in: ' ~ days ~ ' Days', 'This is the week') }}
atomic pasture
#

Thank you very much!

#

I would never write that πŸ˜„

silent vector
#

Is there an easy way without a loop to take 2 keys and add their values together from a list of dictionaries.

- name: 'santa'
  place: 'mars'
- name: 'elf'
  place: 'moon'
#

Output

- santa/mars
- elf/moon
mighty ledge
#

not possible

silent vector
#

I figured was worth asking lol

#

Loop it is

inner mesa
#

Everyone knows that Santa lives on the moon. No idea about elves, maybe a big tree

lusty viper
#

I’m trying to make a template trigger for an automation that fires off 5 minutes before an input_datetime. This is what I have currently but isn’t working:

{{ now() == today_at(states('input_datetime.work_mode_time')) - timedelta(minutes=5) }}

#

Is there a syntax error or will I need another component, like a sensor to calculate the offset, and use that value to trigger the automation when the current time matches?

marble jackal
lusty viper
marble jackal
#

That will work

plain magnetBOT
#

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

marble jackal
#

If that resets twice a day, it is because your source sensors reset as well

quick prairie
#

But there must be some way to prevent this that the total value is not written into the entity. @compact rune said the availability option would be the right way to go but I don’t know how to write that.

mighty ledge
#

well, he was wrong

#

that just makes the sensor go unavailable or not

#

your template already has the correct availability

quick prairie
#

So there is no way how to fix with HA functionality? So maybe the developer of the integration has to be fixing something?

mighty ledge
#

no, if your state_class is set properly, then the resetting shouldn't matter

#

and your energy panel will output the correct info

#

i.e. in your case you probably want a state_class of total, and then you have to calculate last_reset based on when your sensors reset.

#

if you go w/ total_increasing it may also work as long as your sensor drops to 0

#

more than likely, you don't even need the template sensor, you just need to add all your sensors to the energy panel.

still thistle
#

is it possible to translate state in a jinja template? i've seen some work about this by @craggy parrot but it's not yet merged. does it mean I need to do some | replace() to get weather state translated?

marble jackal
#

@still thistle Create a mapping with the translations

#
{% set translation =
  { 
    'cloudy': 'foo',
    'sunny: 'bar'
  }
%}
{{ translation[states('weather.home')] | default('unknown') }}
granite pilot
#

Is there a way to get the todo items out of a todo in templating? I want to create some custom UI foir it using templating?

mighty ledge
#

ah, I see thefes show'd you the chore

mighty ledge
#

coming soom ℒ️

still thistle
#

thank you @marble jackal i think it's cleaner than my replace

plain magnetBOT
#

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

jolly crest
#

How can I list up the two lowest values from these 4?

{% set plat1tid = 3 %}
{% set plat1tid2 = 34 %}
{% set plat3tid = 12 %}
{% set plat3tid2 = 30 %}
{{name of the lowest value}}
{{name of the 2nd lowest value}}

inner mesa
#
{% set plat1tid = 3 %}
{% set plat1tid2 = 34 %}
{% set plat3tid = 12 %}
{% set plat3tid2 = 30 %}
{% set items = [plat1tid, plat1tid2, plat3tid, plat3tid2]|sort %}
{{ items[0] }}
{{ items[1] }}
jolly crest
#

Thanks! Not sure if im doing this right tho. I have a name for each value. How can I get the two lowest values including their names?
{% set plat1tid = 3 %}
{% set plat1tidNAME = name1 %}
{% set plat1tid2 = 34 %}
{% set plat1tid2NAME = name2 %}
{% set plat3tid = 12 %}
{% set plat3tidNAME = name3 %}
{% set plat3tid2 = 30 %}
{% set plat3tid2NAME = name4 %}
{{lowest value + its name}}
{{second lowest value + its name}}

#

Finished editing the post now btw

marble jackal
#

You need to create a mapping/dictionary to be able to do that. Or a list with mappings.

mighty ledge
#

list w/ mappings

marble jackal
#

So either

{
  'name1': 3,
  'name2': 34,
  'name3': 12,
  'name4': 30
}

or

[
  { 'name': 'name1', 'value': 3 },
  { 'name': 'name2', 'value': 34 },
  { 'name': 'name3', 'value': 12 },
  { 'name': 'name4', 'value': 30 }
]
#

I agree the second will be best, but the first can work too

clever forum
#

I'm writing a template to translate wattage from a sensor into a percentage value, and it's not working. Did I screw up the syntax? It just shows up as "unavailable"

{{ ((states('sensor.sonoff_blahblahblah_power')) * (100 / 27))-548 | round(1, default=0) }}

marble jackal
#

You need to convert the state to a number, as all states are strings

clever forum
#

OK, so add "| float"?

#

(after states)

marble jackal
#

Oh, and you are only rounding 548 right now

marble jackal
clever forum
#

boom, fixed and extra parenthesis fixed the rounding. Brilliant. Thanks, @marble jackal !

primal holly
#

Why is this not appearing in home assistant? I saved it and restarted the configuration and there were no errors

template:
  - sensor:
    - name: "thermpwr_hourly"
      unit_of_measurement: "kWh"
      state: >
        {{ [state_attr('climate.neviweb130_climate_kidroom1', 'hourly_kwh_count'), state_attr('climate.neviweb130_climate_basement', 'hourly_kwh_count'), state_attr('climate.neviweb130_climate_kidroom2', 'hourly_kwh_count'), state_attr('climate.neviweb130_climate_dining_room', 'hourly_kwh_count'), state_attr('climate.neviweb130_climate_living_room', 'hourly_kwh_count'), state_attr('climate.neviweb130_climate_parents_bedroom', 'hourly_kwh_count')] | map('float') | sum }}
#

Scam

#

@real fog please ban this user

obtuse zephyr
#

<@&330946878646517761> ^

primal holly
obtuse zephyr
#

Yup

#

Then it gets cleaned up πŸ™‚

charred dagger
#

That's the right thing to do with spammers.

sterile finch
#

Yep πŸ™‚

visual abyss
#

hi there πŸ‘‹

I have a 3d printer, that runs klipper/moonraker. There is an integration that expose a bunch of stuff to HA and is really cool

One of the things that are passed along is the raw value of a pin on the microcontroller in the device, it happens to be connected to a bunch of LED strips.

It is shown as a number entity, that takes a (float) value between 0 and 100, but effectively, it's a dimmable light

#

I am trying to create a template that exposes as such, but I have difficulty reading the value and/or level of the actual number entity

plain magnetBOT
#

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

visual abyss
#

For now it works one way only, I can set the value of the light, but if I change the value of the underlying number it does not update the state of the light

#

I guess I am not sucessfully reading the number in level_template

#

playing with the template thing in the dev tools

state_attr('number.voron2_output_pin_caselight', 'value') is None somehow

#

Oh

#

I think I got it

inner mesa
#

Does that entity have such an attribute?

visual abyss
#

{{ states('number.voron2_output_pin_caselight') | float / 100 * 255}}

inner mesa
#

Yes

visual abyss
# inner mesa Yes

it's actually my first time writing one of those for myself... Looking at the docs and using the tab in the dev tools is actually useful... πŸ™‚

inner mesa
#

You'd be surprised how few people do those things

visual abyss
#

This machine is a giant box full of lights enclosed in acrylic, so it actually act a a lamp in the room... Hence why I want to be able to control it via HA too πŸ˜‚

#

what the proper thing to put in a unqiue_id? a uuid as a string?

#

Yup, that works, I can now set stuff about it in the GUI

#

If anybody's curious, here's what I got working

plain magnetBOT
#

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

inner mesa
#

This bit isn't doing what you think: value: "{{ brightness / 255 * 100 | int }}"

#

It's turning 100 into an int & truncating it, which it already is

visual abyss
#

Ah

#

parenthesis around the whole expression would do?

inner mesa
#

Yes

visual abyss
#

make sense

#

Ah yes, it was still putting hte output values with a bunch of decimal points

#

Alright, I think I got it as good as I could, thanks @inner mesa !

#

Aaaaand now I can set it via HomeKit thanks to HomeBridge, perfect

#

that was the goal

crimson lichen
#

Hi,
With Release 2023.11.1 - November 4
Template trigger.to_state.state don't working.

marble jackal
mighty ledge
#

to_state definitely works, it's an issue w/ the template

#

I'd wager that it's a template that grabs an attribute and the attribute is now None. That's breaking many things ATM

crimson lichen
visual abyss
wintry night
#

i have a blueprint that takes multiple light entities. i then alias the !input other_lights as other_lights . then i try to get their maximum brightness. this used to work, but in a recent HA upgrade it stopped working:

    {{ expand(other_lights) | map(attribute="attributes.brightness", default =
    0)  | max  > 30 }}``` 
I now get an error saying:
```Error: TypeError: '>' not supported between instances of 'NoneType' and 'int'```
wintry night
inner mesa
#

The problem is that as of 2023.11, attributes they don't apply are now set to None if they don't apply rather being removed

wintry night
#

so the default=0 is doing nothing because it's passing through a value of None

inner mesa
#

I don't know if map() can take a parameter that makes it also apply the default to None like default() does

#

Could be another option

#

But it's at least not documented

wintry night
#

thanks so much for the referral. this saved me a ton of time. i was trying all sorts of stuff.

#

where do you find documentation for select selectattr etc?

inner mesa
#

See the links in the channel topic

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

wintry night
#

thanks again, RobC.

inner mesa
#

First one

regal wraith
#

hi guys hopefuly very easy question how could i divide this binary sensor value by half? using templates but its not working for me yet:
`sensor:

  • platform: statistics
    name: "blabla"
    entity_id: binary_sensor.c
    state_characteristic: count
    max_age:
    hours: 24`
inner mesa
#

What did you try?

regal wraith
#

"{{ count | multiply(0.5) | round(2) }}"

#

not sure where to put it

inner mesa
#

You can't do it in the definition you provided. You need to make another template sensor

regal wraith
#

oh

#

i will try thanks

#

like put that sensor inside template?

inner mesa
#

Like make a template sensor

#

That references the sensor you defined above

regal wraith
#

looking there right now thanks

thorny snow
#

Hi all, is there any way to write a script to turn off all entities that contain a specific word within a certain domain? For example, I am trying to turn off all automations that contain the word "*heat" when I switch to summer mode:

sequence:
  - service: automation.turn_off
    data_template:
      entity_id: >
        {% for state in states.automation if 'heat' in state.name|lower %}
          {{ state.entity_id }},
        {% endfor %}

My code is wrong but I don't know what is wrong exactly? Any help?
Thank you!

plain magnetBOT
#

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

uneven lark
#

New to this... any idea why I am getting this (trying to add bandwidth monitors per: https://community.home-assistant.io/t/snmp-bandwidth-monitor-using-statistics/96684/76)

  - platform: template
    sensors:
      internet_in_mbps:
        value_template: "{{ (state_attr('sensor.FGT_wan_in_stats_mean','change_rate')|float*8*(state_attr('sensor.FGT_wan_in_stats_mean', 'sampling_size')-1)/1000000)|round(2) }}"
        unit_of_measurement: "MBps"
        entity_id: sensor.FGT_wan_in_stats_mean //PROPERTY ENTITY_ID IS NOT ALLOWED
      internet_out_mbps:
        value_template: "{{ (state_attr('sensor.FGT_wan_out_stats_mean','change_rate')|float*8*(state_attr('sensor.UDMP_wan_out_stats_mean', 'sampling_size')-1)/1000000)|round(2) }}"
        unit_of_measurement: "MBps"
        entity_id: sensor.FGT_wan_out_stats_mean //PROPERTY ENTITY_ID IS NOT ALLOWED
#

specifically the /PROPERTY ENTITY_ID IS NOT ALLOWED

haughty breach
#

Just remove those two lines.

marble jackal
#

I've seen it before, it's a legacy thing of the legacy format. Should not give errors, but it does nothing. However, this entity_id is faulty, as it includes capitals.

#

You should still remove the entire line though, as it doesn't do a thing

marble jackal
#

If you really want to turn them off, use the code below

sequence:
  - service: automation.turn_off
    data_template:
      entity_id: >
        {{
          states.automation
            | map(attribute='entity_id')
            | select ('search', 'heat')
            | list
        }}
plain magnetBOT
#

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

covert moss
#

Platform: sql. - Not displaying sensor

lucid thicket
#

@final parcel you need to create a list like ['item1','item2']

#
Time: >
  {{ [ states('sensor.date') ~ 'T00:00:00+01:00', 
    today_at().isoformat()] }}
#

Play around with the template in developer tools until you get what you want

final parcel
#

Thanks, what I am trying to do is a template sensor for apex card. I need to get today date - hours of a day and also tomorrow date plus hours of a day. πŸ™‚

lucid thicket
#

You can add or subtract from datetimes with timedelta(hours=2)

final parcel
#

thank you!

lucid thicket
#

A string containing the ISO format of Yesterday at 21:00 for example:

{{ (today_at() - timedelta(hours=3)).isoformat }}
final parcel
#

if I add 24 then I will have tomorrow. Great!

#

hmm but I am still getting error

  - binary_sensor :
    - name: "test"
      state: yes
      attributes: 
        datum: >-
          {% set values = [states('sensor.date') ~ T00:00:00+01:00, states('sensor.date') ~ T01:00:00+01:00, states('sensor.date') ~ T02:00:00+01:00] %}
          {{ values }}
#

Ok, maybe I shall try without template

lucid thicket
#

You need quotes around the T00… stuff

#

To make it a string

final parcel
#

ah!

lucid thicket
#

But you should be trying that template in the dev tools template editor first, it’s much easier to debug there

final parcel
#

you are right... but I am still not getting the list with the dashes... I am getting one row of: 5. listopadu 2023 v 00:00:00, 5. listopadu 2023 v 01:00:00, 5. listopadu 2023 v 02:00:00

lucid thicket
#

In the template editor or that is what the sensor attributes returns?

#

If you delete everything in the template editor and only put in your template, the template editor will tell you result type: list

final parcel
#

I did and the output is

[
  "2023-11-05T00:00:00+01:00",
  "2023-11-05T01:00:00+01:00",
  "2023-11-05T02:00:00+01:00"
]
lucid thicket
#

Yes that is a list

final parcel
#

But if I go to the dev tools > states and look for the sensor it shows: datum: 2023-11-05T00:00:00+01:00, 2023-11-05T01:00:00+01:00, 2023-11-05T02:00:00+01:00 friendly_name: test

#

Which is not the list...

#

I would expect dashes between

lucid thicket
#

Is this a template binary sensor?

final parcel
#

yep

#

I will try to use sensor

#

.. same

lucid thicket
#

I’m not sure why it isn’t showing correct. try {{ values | list }}

#

Also take the dash out so it is datum: >

final parcel
#

I took out the dash and nothing changed...

#

with list it is still the same also 😦

lucid thicket
#

I’m trying to find an example of another sensor that only has a list as an attribute. This might be how the frontend displays it.

#

If it is a list inside a dict it will show with the dashes:
{{ dict(vals=values)}}

final parcel
#

I wish I could translate that to the regular language, I am not programmer 😦 just hobby

#

so how should put it into the config pls? πŸ™‚

#

just put {{ dict(vals=values)}} instead of {{ values }}?

#

Can I post you a screenshot to the message so you know how it displays now? It with dashes but on the top of the dates there si vals=

lucid thicket
#

Yes

#

And yes to your second question

#

You can also do a list of dictionaries too, if you like that display better:


{% set values = [{'date':states('sensor.date') ~ 'T00:00:00+01:00'}, {'date':states('sensor.date') ~ 'T01:00:00+01:00'}, {'date':states('sensor.date') ~ 'T02:00:00+01:00'}] %}
{{ values}}
#

I can’t display screenshots in this channel

final parcel
#

I post you a private message

lucid thicket
#

Yes that is showing like it should, that is a dictionary with one key and a value that is a list

final parcel
#

Thanks! I am getting closer....

lucid thicket
#

It seems that the front end just shows a simple list as comma separated values, and there’s nothing you can do about it. If you embed the list into a dictionary, or if each item in your list is a dictionary, then it shows with dashes

final parcel
#

but I think I am gonna sleep and let it for future... because now I have name of dictionary and also name of that attribute

#

I.. πŸ™‚

#

I have it almost!!! πŸ™‚

thorny snow
plain magnetBOT
#

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

final parcel
lucid thicket
# final parcel I have it almost!!! πŸ™‚

if all you want is to create a sensor with a list of values, you've already accomplished that. You don't need to worry about how the frontend displays the list. If you want to confirm it's a list, you can go into the template editor and write `{{ state_attr('binary_sensor.test','datum')[0] }} and it will show you the 1st (technically 0th) element of the list

lucid thicket
final parcel
#

hmmm but I will look at that tomorrow really πŸ™‚ And many thanks! Its to late here πŸ™‚

lucid thicket
#

if you really want to do it that way, you'd have to use {{ (as_datetime(states('sensor.date')) + timedelta(hours=24)).date() ~ "T00:00:00+01:00" }}

final parcel
#

thanks!! Very much

#

Maybe I will find out using "for" how to write that more easy than specifying 48 hours per hour from current day midnight :). And thanks for helo. Much appreciated

lucid thicket
#

play around with this tomorrow: {{ (today_at() + timedelta(hours=24)).isoformat() }}

final parcel
#

A need really 24 hours of current day and 24 of tomorrow so I need to use probably date at first

#

Or I can do maybe for cycle just for changing the second numbers in that format πŸ™‚

lucid thicket
#

sure. I may come up with something and post it for you to look at tomorrow.

final parcel
#

So I need to list of each hour for current and tomorrow hours and per each hour a need to assign the price of the tarrif

#

Good night

lucid thicket
small wasp
#

anyone have any ideas?

small wasp
#

nvm, just wrote out a monster of a template to accomplish this

plain magnetBOT
small wasp
#

then can easily work with the produced list of entities

final parcel
marble jackal
#

it's creating a range going from 0 to 47, and then takes last midnight and adds hour * number in range

#

and adds those in a list

marble jackal
mighty ledge
# small wasp then can easily work with the produced list of entities
entities: >
  {%- set ns = namespace(ret=[]) %}
  {%- for key in ['device_id', 'area_id', 'entity_id'] %}
    {%- set items = lights.get(key, [])  %}
    {%- if items %}
      {%- set items = [ items ] if items is string else items %}
      {%- set filt = key.split('_') | first %}
      {%- set items = items if filt == 'entity' else items | map(filt ~ '_entities') | sum(start=[]) %}
      {%- set ns.ret = ns.ret + [ items ] %}
    {%- endif %}
  {%- endfor %}
  {{ ns.ret | sum(start=[]) }}
#

does the same thing

#

just need to add lights: !input xyz before that variable

#

assuming you're coming from a target selector

#

aka no monster template needed

#

that get's all entities

#

you'll need to add | select( 'search' , '^light' ) | list to the end

karmic sapphire
#

How would I use a camera entity to link to a url like this when clicking on it? http://192.168.1.34:9000/recipe/{{states.sensor.mealie_todays_meal_id.state}}

mighty ledge
#

You need to use a card that supports templating in the tap action

karmic sapphire
#

got it, thanks

runic swan
#

how do I multiply an input (trigger variable) duration by a constant? I want to time my lights out in a blueprint, and I've successfully gotten a blueprint working where I can input the timeout duration, but sometimes the automation doesn't work for some reason or another (zigbee network overloaded, etc), so I want to retry a few times, e.g. after (!input timeout_duration) 3 minutes, 2 * 3 minutes, 3 * 3 minutes, etc. I'm fine with doing it a fixed number of times, but I don't know how to do the for: '{{3 * timeout_duration}}' part

When I try with the above or any similar variant with pipes to int/float/multiply, I get an error (after trying to create a new automation with the blueprint; current automations are just, confusingly, "unavailble" with no more information): Message malformed: offset None should be format 'HH:MM', 'HH:MM:SS' or 'HH:MM:SS.F' for dictionary value @ data['for']

Edit: nevermind, it was a silly typo on a previous line.

worldly tree
#

I’m trying to build a template to monitor all devices of a certain class with β€œ{{ states.binary_sensor | selectattr('attributes.device_class', '==', 'moisture') | map(attribute = 'entity_id') | select('is_state', 'on') | list | length }}” however it only triggers on first sensor that is triggered, I plan to use this template with blueprint so I cannot make template sensors for each class, any suggestions?

marble jackal
#

your only option is to select all relevant entities in a selector, without the help of a template sensor it is not possible to do this dynamically

plain magnetBOT
#

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

tardy stirrup
#

Hi, new to HA and programming in general. I'm trying to pull a buried attribute out of an integrated device. I created a sensor.yaml and have this code in there:

    friendly_name: 'sensedge_co2'
    value_template: "{{ state_attr('air_quality.laseregg_air_quality', 'carbon_dioxide') }}"
    device_class: carbon_dioxide
    unit_of_measurement: ppm```
I am getting the fallowing error: Invalid config for [sensor.template]: [friendly_name] is an invalid option for [sensor.template]. Check: sensor.template->friendly_name. (See ?, line ?).
#

I also have this code ahead of the template above, which may or may not be screwing something up?

    monitored_feeds:
      - type: five_minute
      - type: current_hour_average```
Thanks!
marble jackal
#

no, your yaml code is wrong for the template sensor

tardy stirrup
#

I also tried followign this format and it wouldn't work

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

Are you recommending I use the legacy format?

marble jackal
#

that's basically correct, but that falls under the template integration, so you can't place that in sensor.yaml

tardy stirrup
#

ah

marble jackal
#

no, I don't recommend you use that, but in your earlier posts you were using it, but it was not correct

tardy stirrup
#

right, it was working in my earlier post then stopped

#

so i'm tryign to update it

#

I'll need to read up on templating integration then, i'm not sure if that goes into config.yaml or gets its own

#

thanks!

marble jackal
#

This looks most like the legacy template sensor format, but it is wrong, and therefore not working. If it were correct it should be placed in sensor.yaml

  - platform: template
    friendly_name: 'sensedge_co2'
    value_template: "{{ state_attr('air_quality.laseregg_air_quality', 'carbon_dioxide') }}"
    device_class: carbon_dioxide
    unit_of_measurement: ppm

This is correct YAML, but can't be placed in sensor.yaml. The way you have it now it should be placed direclty in configuration.yaml. However the template you have there doesn't ouput anything, it just sets two variables

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

you could create a separate templates.yaml for the 2nd one if you want

tardy stirrup
#

Sorry, I feel like these questions are terrible. I created a template.yaml and in config.yaml i included
template: !include.template.yaml
But now getting error: Error loading /config/configuration.yaml: could not determine a constructor for the tag '!include.template.yaml'

#

This is what is in my template.yaml:

      - name: "sensedge_co2"
        unit_of_measurement: "ppm"
        state: >
          {{ state_attr('air_quality.laseregg_air_quality', 'carbon_dioxide') }}```
lucid thicket
tardy stirrup
#

ah, duh. thanks

#

my excuse: its dark and my eyes aren't working great right now (couldn't sleep)

#

thank you both!

rotund hazel
#

There is new switch configuration for command_line for 2023.12 update, but command_line does not support these settings(port and resource): - platform: telnet switches: zm_trigger_terasa: resource: 192.168.1.20 port: 6802 command_on: '2|on+30|2|External Motion|External Motion' command_off: '2|off|2|External Motion|External Motion'

#

What to do now for these breaking change?

mighty ledge
#

that's not a command line switch

#

i.e. there's nothing for you to change with that.

#

@rotund hazel ^

rotund hazel
#

thanks , because I got warning

mighty ledge
#

did you get a warning that said command_line?

#

if yes, then you need to find platform: command_line not the other platforms

rotund hazel
#

no, warning for switch

mighty ledge
#

post the warning because you're not providing the correct information

rotund hazel
#

Consult the documentation to move your YAML configuration to integration key and restart Home Assistant to fix this issue.```
mighty ledge
#

Right

#

notice how it says Command Line

#

therefor you need to search your switch configuration for platform: command_line

#

not platform: telnet which is not a command_line switch.

rotund hazel
#

thank you

ember saffron
mighty ledge
#

you can't mix and match platforms

#

you have to make a waste_collection_sechule and a separate template

ember saffron
#

its working right now as the docs states, but my intention was to move, if possible to the new format

#

that was the reason to ask

mighty ledge
#

what new format

#

the new format is only for templates

ember saffron
#

throught he template: and no more sensor: platform

#

I need to learn a bit more with the templates

mighty ledge
#

platform: template is different than platform: waste_collection_sechule

ember saffron
#

to get a better understanding

mighty ledge
#

platform: template is the template integration

#

platform: waste_collection_sechule is the waste collection integration

#

you can't mix and match

ember saffron
#

okay. but this is not possible I guess, but I would like to know it for sure ^^;

#

Which is the best approach when I would like to split this platform into a seperate yaml file? it works with the sensor: platform = sensor: !include template-sensor.yaml

mighty ledge
#

if you want to split them into separate files, you'd need to put them into a folder and your include would need to point to the folder. You'd used the merge list include.

marble jackal
#
sensor:
  - platform: template

those can be moved to the new template sensor platform

#
sensor:
  - platform: something_else

Those should be left where they are

ember saffron
#

I used different folder for now for template: with template/ and sensor: with sensor/

marble jackal
#

yes, that's how it should be

quiet creek
#

How can I make a template sensor for the chance of rain% and the humidity?

atomic blade
quiet creek
mighty ledge
quiet creek
# mighty ledge you don't need template entities, you can just template in your TTS automation
target:
  entity_id: media_player.bedroom_display
data:
  message: >
    Good Morning, It’s currently {{ states('sensor.weather_temperature') |
    round(0, default=0) }} degrees and {{ states('sensor.weather_condition') |
    default('N/A') }} in Salem today. Your bedroom is currently {{
    states('sensor.aidans_bedroom_temperature') | round(0, default=0) }}
    degrees. Today's high will be {{
    states('sensor.weather_daytime_high_temperature') | round(0, default=0) }}
    degrees with a low of {{ states('sensor.weather_overnight_low_temperature')
    | round(0, default=0) }} degrees. You can expect a {{
    states('sensor.weather_precipitation_probability') | round(0, default=0) }}%
    chance of rain today.``` This is what I have but the entities other than sensor.weather_temperature don't exist.
marble jackal
#

They are attributes of your weather entity

quiet creek
mighty ledge
#

they are visible in the UI if you use the weather card

#

or if you expand the weather attributes

#

regardless, to get an attribute from an entity, simply use state_attr

#

{{ state_attr('weather.home', 'humidity') }}

marble jackal
#

It looks like precipitation is only shown in the forecasts.

mighty ledge
#

you can figure that info out from developer tools -> states page

marble jackal
#

At least for the ones I have

mighty ledge
#

same for me

#

I know you're going to create it, so I'll sit back and relax πŸ™‚

marble jackal
#

Oh, I thought you were going to do it.
Anyway if there still is a forecast attribute @quiet creek will be able to take it from that (until March next year)

#

For a future proof solution a template sensor is needed

#

Unless there will be an alternative to get the forecast data in the time from now until March

plain magnetBOT
#

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

marble jackal
#

did you actually check in devtools > states?

#

if you look at the screenshot Petro posted, none of these values you are now trying to extract are attributes of the weather entity

quiet creek
#

It looks like I don't have these availble to me, what weather integration has these values?

marble jackal
#

probably no weather entity will have them as attribute

#

but the precipitation will be in the forecast attribute

#

but not all weather integrations include today in daily forecast

#

Accuweather does

#

and also has precipitation_probability in the forecast

mighty ledge
marble jackal
#

for the other two Accuweather provides temperature in the forecast for the highest temp of the day, and temp_low for the lowest

mighty ledge
#

accuweather set to daily

marble jackal
#

to get them out:
{{ state_attr('weather.accuweather_daily', 'forecast')[0].precipitation_probability }}

#

but again, this will not work after March 2024

#

So, for now you can use something like that directly in your TTS message, no template sensor needed

#

after that:

template:
  - trigger:
      - platform: state
        entity_id: weather.accuweather_daily
    action:
      - service: weather.get_forecast
        data:
          type: daily
        target:
          entity_id: "{{ trigger.entity_id }}"
        response_variable: forecast
        continue_on_error: true
      - variables:
          today: "{{ forecast.forecast[1] if forecast is defined else {} }}"
          precipitation_probability: "{{ today.get('templow', none) }}"
          temp_min: "{{ today.get('templow', none) }}"
          temperature: "{{ today.get('temperature', none) }}"
    sensor:
      - name: Temperature High
        unique_id: 858e8aa5-bed0-4920-a64d-0a659721887c
        device_class: temperature
        state_class: measurement
        unit_of_measurement: Β°F
        state: "{{ temp_min }}"
        availability: "{{ temp_min is not none }}"
      - name: Temperature Low
        unique_id: ca25703a-5d27-4bb2-a811-62c4637dfe26
        device_class: temperature
        state_class: measurement
        unit_of_measurement: Β°F
        state: "{{ temperature }}"
        availability: "{{ temperature is not none }}"
      - name: Chance of rain
        unique_id: c7f19a6e-7cfe-4c47-9eaa-f540861e2948
        state_class: measurement
        unit_of_measuremetn: "%"
        state: "{{ precipitation_probability }}"
        availability: "{{ precipitation_probability is not none }}"
#

You can use this trigger based template sensor to get the data out of your weather entity

quiet creek
obtuse zephyr
#

That is something for your config.yaml

worldly tree
quiet creek
inner mesa
#

ignore it

marble jackal
plucky depot
#

Can anyone tell me how to change this template so that I get the last know value instead of 0 ?

- name: Import power # power from grid: positive if importing, else zero
        unique_id: sg_import_power
        unit_of_measurement: W
        device_class: power
        state_class: measurement
        availability: "{{ not is_state('sensor.export_power_raw', 'unavailable') }}"
        state: >-
          {% if states('sensor.export_power_raw')|int < 0 %}
            {{ states('sensor.export_power_raw')|int *-1 }}
          {% else %}
            0
          {% endif %}
lucid thicket
#

{{ this.state }}

plucky depot
#

thanks

plain magnetBOT
small wasp
#

ugh

#

but yeah i was very happy to find out bitwise_and filter was a thing when & wasn't working

marble jackal
#

With the update to 2023.11 all lights which support brightness always have the attribute. So you could just check on that

small wasp
#

would there ever be any case where a light supports brightness but not transitions though?

marble jackal
#

Ah sure, in that case it will go to brightness 1 immediately

small wasp
marble jackal
#

My lights which don't support brightness simply don't have the attribute, whether they are on or off

small wasp
#

right, but state_attr returns null regardless of if the light simply does not support brightess, or if it does and it's just currently off

ember saffron
#

Hi, I would like to compare the state from 3 entities and the entitiy with the lowest value should be put as the value from the template sensor. Is this possible?

small wasp
#

for example this: {{ entities | expand | selectattr('attributes.brightness', 'defined') | map(attribute='entity_id') | list }}

#

will only list entities which support brightness

marble jackal
#

Yes, that's what I meant πŸ™‚

small wasp
#

yeah i just got confused because the string representation was the same when i was initially testing it out

shadow gorge
#

Hi, I wonder if anybody can help me with this sensor. I want the state to be TRUE after the media player being "paused" for 5 seconds. But in reality, it takes more or less 20 seconds for it to swicth. Is there something wrong in the template?

- name: Sonos Vardagsrum State
  state: >
    {{ (is_state('media_player.vardagsrum', 'paused')) and (now() > states.media_player.vardagsrum.last_changed + timedelta(seconds=5)) }}
```
fickle sand
#

You will be better off with a trigger template sensor. The state change of your example is dependent on a state change in media_player.vardagsrumor now() which only forces an update every minute

shadow gorge
fickle sand
#

Yep to validate the extra 5 seconds the template relies on the update frequency of now() which is 1 minute to manage resources

shadow gorge
#

many thanks for explaining

ember saffron
#

How can I get the sensor entitiy ID which has the lowest from three different entities? (Is that even possible?) Rest = 3, Bio = 6, Wert = 9 In this case, "Rest" is the lowest and an icon should be set accordently to "Rest" to the new template sensor

mighty ledge
#

the throttle on states and states.<domain> were put in place to manage resources

mighty ledge
small wasp
#

could just use a "combine the state of multiple sensors" helper entity

mighty ledge
#
{% set ns = namespace(items=[]) %}
{% for e in ['sensor.a','sensor.b','sensor.c'] %}
   {% set ns.items = ns.items + [{'e': e, 's': states(e) | float(None)}] %}
{% endfor %}
{{ ns.items | rejectattr('s', 'none') | sort(attribute='s') | map(attribute='e') | first | default }}
small wasp
mighty ledge
#

That it does, TIL

ember saffron
mighty ledge
#

you don't need it, see what sebastian said

#

s and e are just labels I used to be lazy

ember saffron
#

ah okay, just asking because it provides me not the entity with lowest, but with the mid value

mighty ledge
#

you didn't create the group with the setting set to minimum

ember saffron
#

I was refering to your code snipped. With the helper, it returns the lowest value indeed, but not the entity which has the lowest value

small wasp
shadow gorge
#

Hi, I wonder if anybody can help me with

mighty ledge
#

it rejects sensors that do not have numerical results

plucky depot
#

Is it possible to create a template sensor that counts down to a specific date each month. And then starts over conting down to the same date next mont when it is reached ? I would like to know how many days are left until payday each month.

mighty ledge
#

Yes

#
{% set t = today_at() %}
{% set date = t.replace(day=20) %}
{% if date < t %}
  {% set next_month = date.month + 1 if date.month < 12 else 1 %}
  {% set next_year = date.year if date.month < 12 else date.year + 1 %}
  {% set date = date.replace(month=next_month, year=next_year) %}
{% endif %}
{{ (date - t).days }}
#

that's to the 20th of each month

#

@plucky depot ^

plucky depot
#

Thanks, would it be difficult do do the same thing to count down to a reaccuring event in the local calendar. And if that event is on an weekend it gives the countdown until the previous friday ?

My payday is the 25:th each month, but if the 25:th is on an saturday or sunday the payday is on the previos friday.

mighty ledge
#

That's all possible but the code would be different

#

you'd have to replace t = today_at() with your calendar start_event attribute

#

as for the previous friday, that's not an easy task.

inner mesa
#

as you say, friendly_name is an attribute, and you would use state_attr(entity, 'friendly_name') to get it

#

icon is (typically) not an attribute, but something built into the entity in some way

cosmic kraken
mighty ledge
#

find a different blog

#

shelly devices don't even need MQTT either, just use the shelly integration and avoid all the MQTT stuff

#

enable CoIoT, integrate, and you're done

cosmic kraken
mighty ledge
#

I don't think that should make a difference

#

unless you don't have access to the device remotely

cosmic kraken
#

well it is remote and I have access through the Shelly Cloud so I can make changes in settings

cosmic kraken
cosmic kraken
mighty ledge
#

I can help when I get home, I'm currently at work

#

~1.5 hours from now

cosmic kraken
mighty ledge
#

Just create a thread here

#

post your sensor

hard vale
#

i currently have a sensor that measures in kWatts, i would like to have this sensor in watts but i don't get it to work, tried this:
`sensor:

  • platform: template
    sensors:
    elektricity_meter_watts:
    friendly_name: "Huidig Verbruik In Watt"
    unit_of_measurement: "Watts"
    value_template: "{{ states('sensor.electricity_meter_energieverbruik') | float * 1000 }}"`
hard vale
#

i figured it out, did it like this:
- platform: template sensors: huidig_verbruik_in_watt: friendly_name: "Huidig verbruik in Watt" unit_of_measurement: 'W' value_template: >- {% set t = states('sensor.electricity_meter_energieverbruik') | float %} {{ t * 1000 }}

inner mesa
#

There's no meaningful difference between the two

#

Your unit of measurement was probably the problem

mighty ledge
#

works for me, added you as friend here,

marble jackal
#

The unit of measurement is different

inner mesa
#

Yeah, was looking at the template initially

hard vale
#

oh wow... didn't know HA has integrated list of units

sharp frigate
#

If I want to control the state of a switch based on comparison to some temperature values, would that be done with a template or something else?

#

I want to turn my radiator valves on and off when the set value (I guess I'll use some sort of helper to input that?) is the measured room temperature +/- 0.5 degrees or so

#

I basically want to replace the logic in my smart TRVs because they're detecting temperature at the radiator and it's rising too quickly compared to the room temperature so the radiators turn off too soon.

atomic blade
#

Yes that's something you can do with a template

sharp frigate
#

That I'll start taking a look tomorrow, bed time!

cyan star
#

hi guys, very quick question as I've already spent a while fighting this issue. How to create a template helper of boolean 'or' of group of binary sensors. Should it be {{ state.binary_sensor.sth1 or state.binary_sensor.sth2 }} or perhaps states('binary_sensor.sth1') or perhaps is_state('binary_sensor.sth1', 'on') OR ... ? I'm unable to solve that

fossil venture
#

is_state('binary_sensor.sth1', 'on') or is_state(...

#

You can also do, states('binary_sensor.sth1')|bool or states(...

cyan star
#

I'll try that, llama told me to try that:

sensor:
  - platform: template
    sensors:
      example_binary_sensor_or:
        friendly_name: "Example Binary Sensor OR"
        state: '{{ (states.binary_sensor1.state | boolean) | or(states.binary_sensor2.state | boolean) }}'

which looks similar to your second answer

fossil venture
#

No dont do that.

cyan star
#

sure

fossil venture
cyan star
#

thank you! it does work

sharp frigate
#

Is it possible to make a relative threshold helper? I want to use it for hysteresis in my temperature switch.

#

So I have an input number to set room temp, then a template sensor to get the value of the input into the threshold helper but that requires absolute values as far as I can tell.

odd flare
#

How do I limit a json response for weather where it’s only daytime is_daytime: true?

plain magnetBOT
odd flare
#

The one I currently have doesn’t differentiate between either true or false : {{ state_attr('weather.noaa_weather', 'forecast')[0]['temperature']}}

karmic sapphire
#

Why do I get an error when trying to do this?

{{ now() - (states('input_datetime.alarm_time') | as_datetime | as_local) }}

mighty ledge
sharp frigate
#

I'm using the UI, the threshold helper asks for a minimum and maximum value

sharp frigate
#

I ended up writing a template, it seems to be working fine; the PSU in my server just died now so my home is back to being dumb 😭

karmic sapphire
mighty ledge
haughty breach
#

Or it's time-only

karmic sapphire
#

it is time only

mighty ledge
#

true

karmic sapphire
#

im just trying to show time remaining on that time

mighty ledge
#

then use today_at()

#

FYI remaining time on that will only update once per minute

#

replace | as_datetime | as_local with | today_at

karmic sapphire
#

thats okay, ill try that

#
Alarm Time: 06:00:00
Time Remaining: 1:23:41.836484```
#

should be just 23ish hours

mighty ledge
#

if the alarm is tomorrow, then you need to account for that by adding a day

#

today_at returns todays date

#

secondly, you won't be subtracting it from now, now should be subtracted from it

#

if it's in the future

karmic sapphire
#

oh I see, thanks

haughty breach
# plucky depot Thanks, would it be difficult do do the same thing to count down to a reaccuring...

It seems to me that referring to the calendar would just make it more complicated than necessary...

{% set today = today_at() %}
{% set this_25 = (today.replace(day=25)).date() %}
{% set next_25 = (today + timedelta(days=(31-today.day))).replace(day=25).date() %}
{% set uncorrected = this_25 if today.day < 26 else next_25 %}
{% set wd = uncorrected.isoweekday() %}
{% set corrected = uncorrected if wd < 6 else uncorrected - timedelta(days= (wd-5)) %}
{{ (corrected - today.date()).days }}
odd flare
#

I need to select the temperature attribute but on when daytime = true

mighty ledge
#

selectattr is not state_attr

#

notice the entire difference in words

#

based on your response, I have a feeling you won't know how to use it

odd flare
#

I don’t but I will look

#

Happy for any pointer you have

mighty ledge
#

| selectattr('is_daytime', 'eq', True) | map(attribute='temperature') | first | default

karmic sapphire
#

what is the format of this timestamp 21:50:27.951358 and how do I get it into hours minutes

mighty ledge
#

You have to perform the math

#

timedeltas do not have a format function

#

if it's under 24 hours, you can use .seconds | timestamp_custom('%H:%M')

#

if it's over, you can still use timestamp_custom but you'll have to specify days

#

you'd use .total_seconds() | ... instead of seconds

karmic sapphire
#

I must be doing something wrong, here is the output

#
Time Remaining: 21:39:09.469205

Timeremain.seconds 14:39
timeremain.total_seconds 77949.469246```
#

code:

{%- set timeremain2 = timeremain.seconds | timestamp_custom('%H:%M') %}
{%- set timeremain3 = timeremain.total_seconds() %}


Time Remaining: {{ (states('input_datetime.alarm_time') | today_at) + timedelta(days=1) - now() }}

Timeremain.seconds {{timeremain2}}
timeremain.total_seconds {{timeremain3}}
mighty ledge
#

you probably need to provide false to the timestamp_custom to let it know it's local

karmic sapphire
#

that works, perfect! thank you so much

karmic sapphire
#

I am confused on one more thing, why cant the input_datetime display the value with AM/PM?

#

I also tried as_timestamp(states('input_datetime.alarm_time')) | timestamp_custom('%I:%M %p')

marble jackal
marble jackal
#

you can't convert a time only string to a datetime timestamp

mighty ledge
#

hah, was just going to say

karmic sapphire
#

that works!

#

{{ today_at(states('input_datetime.alarm_time')).strftime('%-I:%M %p') }} for true 12 hour time

marble jackal
#

@mighty ledge in my cheapest energy macro the user can input the number of hours, I now added a function wich basically copies the data and splits the hours in parts based on this number of hours (in case it is a float).
So if eg the input is 2.25 hours, I want it split in 4 parts, and if it is 2.8 hours in 5 pars.
I have now used this, but I wondered if there might be a more efficient way (h is the number of hours)

{%- set minutes = (h % 1 * 60) | round(0) -%}
{%- set minutes = [minutes, 60 - minutes] | max -%}
{%- set div_list = [60, 30, 20, 15, 12, 10] -%}
{%- set ns = namespace(d=60, wp=1) %}
{%- for div in div_list %}
  {%- if div <= minutes and minutes % div < ns.d -%}
    {%- set ns.d = minutes % div -%}
    {%- set ns.wp = (60 / div) | int -%}
  {%- endif -%}
{%- endfor -%}
{{ ns.wp }}
mighty ledge
#

So you're just finding the remainder and getting the lowest common increment?

#

.25 -> 4

#

.2 -> 5?

#

.4 -> 5?

#

for fractions basically

#

I use this to make fractions IIRC

#

but I don't think it's "better"

#
      {%- set fractions = {0.020833: '1/48', 0.041667: '1/24', 0.0625: '1/16', 0.083333: '1/12', 0.104167: '5/48', 0.125: '1/8', 0.145833: '7/48', 0.166667: '1/6', 0.1875: '3/16', 0.208333: '5/24', 0.229167: '11/48', 0.25: '1/4', 0.270833: '13/48', 0.291667: '7/24', 0.3125: '5/16', 0.333333: '1/3', 0.354167: '17/48', 0.375: '3/8', 0.395833: '19/48', 0.416667: '5/12', 0.4375: '7/16', 0.458333: '11/24', 0.479167: '23/48', 0.5: '1/2', 0.520833: '25/48', 0.541667: '13/24', 0.5625: '9/16', 0.583333: '7/12', 0.604167: '29/48', 0.625: '5/8', 0.645833: '31/48', 0.666667: '2/3', 0.6875: '11/16', 0.708333: '17/24', 0.729167: '35/48', 0.75: '3/4', 0.770833: '37/48', 0.791667: '19/24', 0.8125: '13/16', 0.833333: '5/6', 0.854167: '41/48', 0.875: '7/8', 0.895833: '43/48', 0.916667: '11/12', 0.9375: '15/16', 0.958333: '23/24', 0.979167: '47/48', 1.0: '1'} %}

      {%- macro fraction(value, count=0) %}
      {%- set out = fractions.get(value | round(6)) %}
      {%- if out is not none %}
      {{- out }}
      {%- elif count <= 1 %}
      {{- (value // 1) | int }}{{ ' & ' ~ fraction(value % 1, count + 1) if value % 1 else '' }}
      {% else %}
      {{- value }}
      {%- endif %}
      {%- endmacro %}
#

actually, I really need to update that cause it throws out shit on the regular

plain magnetBOT
mighty ledge
#

you have to build the list in jinja, you can't build the yaml

fathom yew
#

OK, so that is building the list and then outputing it using {{ listVariable }}?

#

But why is the template entirely removed during store & reload?

mighty ledge
#

because segments require a valid value and it removes the invalid things when you view it in the UI

#

if you keep it yaml mode, it iwll persist

fathom yew
#

The params are also just a Yaml field in the UI.

plain magnetBOT
fathom yew
#

Hmm, also not stored when I edit it in the YAML editor in the UI. πŸ€”

#

I'll edit the script on disk directly and see what it does …

#

OK, storing the script on disk makes it unable to be edited in the UI. I guess this is due to the usage of a template at all? At least, HA does not complain when reloading the scripts.yaml

mighty ledge
#
field: >
  {{ ....
#

you have

#
field: >
{{ 
fathom yew
#

@mighty ledge many thanks, that did the trick. I was fiddling for 2 days on this noob issue. πŸ™ˆ

#

OK, so now fighting again with actually returning a list from a template.

fathom yew
#

Awesome, needed some namespace() fiddling, but it works now. πŸ₯³

pulsar glacier
#

I'm trying to debug a template that isn't working... what's the best way to do the equivalent of a console.log or something in the Template editor?

#

nvm think i found it

mighty ledge
#

just do {{ }}

agile jungle
#

hello everyone. Is it possible to create template light with scenes? I have smart IR-RF remote which works with Tuya. I'm using official Tuya integration and IR-RF remote not supported by Tuya integration. I can only use this with scenes in Home Assistant.

mighty ledge
#

You should be able to use it with service calls.

#

So automatons scripts scenes and anything that has an action section.

agile jungle
#

This had never occurred to me before. I'm new at codes. Thanks a lot. I'll try it.

acoustic arch
#

do variables listen to eachother?

#

or are they only made independently?

mighty ledge
#

you aren't providing a default

#

it's the 3rd from the bottom pin

#

and to check for none, if xyz is not none

#

if you properly check for none then you don't need the default

acoustic arch
#

can you push me a liiiitle bit in the right direction? syntax wise?

mighty ledge
#

i literally gave it to you

mighty ledge
acoustic arch
#

is not is syntax?

mighty ledge
#

yes

acoustic arch
#

k ill try it

#

ugh....

#

trigger.to_state.attributes.pickup_start what does this renders when the attribute doesnt exist ? none? null? devtools says None

#

i just want to get it to run the {% else %} part lol. but now it jumps to the as_timestamp default of 0

mighty ledge
#

depends on what isn't rendering

#

post your triggers

marble cave
#

Can anyone boast about the template they created? I need some suggestions, I want to add a widget on the watch that will show some information in an interesting way than just text, and on the phone in the widget

sharp frigate
#

Is it possible to "template" a template sensor helper so I can reuse it with different entities in an automation?

#

I have a binary sensor template that does some calculations based on a few entities and I want to reuse it for different entities in different automations

solemn ivy
#

I have a string that I'm scraping with multiscrape in the format "[54m 0s]" where the minutes and seconds vary. I want to convert the string to a time in seconds that I can use for automations and statistics. I have had zero luck creating a value_template that gives me anything other than Unavailable. Any one know what I need to do? It seems like it should be very simple.

inner mesa
ocean hedge
#

Hi all,
I have a template sensor showing a cost, however when it is at 0.10 or 0.20 etc. it only shows 0.1 / 0.2 but I really need it show the 0 like 0.10. Hope that makes some sense and someone can help. Thanks

analog mulch
#

Hi. I'd like to set up a sensor which would store the highest value of another sensor during the past hour. I'd like it to update once on the hour every hour. What's the best approach here?

analog mulch
ocean hedge
analog mulch
#

OK! the reset interval had me confused. Thanks! Saves me doing some template/statistics frankenstein!

lofty mason
analog mulch
# ocean hedge Yes the integration calls it refresh interval and you choose that - see picture ...

Hmm it seems the daily sensor doesn't quite do what I want, but maybe I have misunderstood something. If I ask for max sensor with a refresh interval of 60 mins, then the value of the sensor will change only if the max in the last hour is larger than the max in the whole reset period, i.e. the day. I then thought I could get it to reset every 60 minutes manually, but in that case the sensor does not actually have a state until it updates and then immediately resets.

willow wing
#

Hey, is it possible to integrate a template string in the entities card? Someone can assist me with a example?

#

i trid these currentlly
type: entities
entities:

  • entity:
    data_template: state: {{ as_timestamp(state_attr('calendar.feiertage', 'next_date')) | timestamp_custom('%d.%m.%Y') }}
  • entity: sensor.schulferien_beginn_ende_indays
  • entity: switch.turoffner
    name: TΓΌrΓΆffner
    show_state: true
    ......
marble jackal
#

No, you can't use templates in an entity card

hard vale
#

someone who can help me out with following:
i have a siemens_logo plc where i configured some binary sensors which works fine now
now i would like to declare some sensor values holding uninsigned words (according to the holding registers help in logo siemens). i am getting some values like 8192 and 8183 or 0. Don't actually know what to try else. i have tried (u)int8, (u)int16, floats, now last i tried some custom:
sensors: - name: pomp_timer_seconds_auto # VW12 slave: 255 address: 11 data_type: custom structure: ">h" count: 1

zealous nebula
#

Anyone aware how to make a button for a denon receiver volume limit??

restive socket
#

When looking at media_player state, there is an entry called entity_picture.....but I cannot for the life of me figure out how to view/use it. IP:8123/api/path/and/token gives 404 not found - is there a trick to this

#

@zealous nebula what do you want to do - enable and disable a volume limit?

zealous nebula
#

Yeah ideally have three buttons one that sets it to -20 another -10 and lastly -5

restive socket
#

service: media_player.volume_set
data:
volume_level: .82
target:
entity_id: media_player.denon

sacred sparrow
#

is there a better way to do this: {{ ( as_timestamp(now()) - as_timestamp(state_attr('binary_sensor.pc_status', 'last_changed')) |int(0) ) <= 40 and states('binary_sensor.pc_status', 'on') }}

#

just want to make it true when the sensor has been ON for 40 seconds

#

(that code doesn't really work too well)

zealous nebula
#

Let me post the pic hang on

#

Actually cant but its on web ip of denon audio and volume limit

restive socket
#

I don't see a command for volume limit

#

I have an automation that checks the volume and if it is over 82 set it to 82 but that would only partially give you what you want

sacred sparrow
marble jackal
#

last_changed is not an attribute, so this won't work

#

You can have it in a wait template, but 40 seconds will not work, as the template will only update once per second

#
{{ now() - states.binary_sensor.pc_status.last_changed <= timedelta(seconds=40) }}
sacred sparrow
#

sorry I forgot to say it does have that attribute

#
    - name: "PC Status"
      icon: phu:laptop-windows
      availability: "{{ not is_state('sensor.pc_smartplug_watts', 'unavailable') }}"
      delay_off:
        seconds: 20
      state: "{{ states('sensor.pc_smartplug_watts')|float(0) > 6 }}"
      attributes:
        last_changed: '{{ now() }}'```
marble jackal
#

The first part of the comparison only increases though, so if it isn't true at the first time it's checked, it will only be true after a new state change

#

That attribute will just update every minute

sacred sparrow
#

oh I thought it updates every state change

marble jackal
#

No, attribute templates are not only rendered on time changes, but what's the use of adding data which is already available?

sacred sparrow
#

thats true - I didnt know it was

#

will {{ now() - states.binary_sensor.pc_status.last_changed <= timedelta(seconds=40) and states('binary_sensor.pc_status', 'on' }} work?

marble jackal
#

It will only be updated once per minute or on a state change of the binary sensor

#

But if your binary sensor was turned on like 2 minutes ago, this will only be true after it first turned off and then turns on again

sacred sparrow
#

hmm I see

#

I'll play around with it - thanks πŸ™‚

cerulean karma
#

Hi, I got a gas sensor that is "total_increasing" and representing the gasmeter in kWh. What template/helper could I use to calculate a current consumption (maby over the last 5 minues) based on this data.

surreal wasp
#
{% set test = "100" %}

{% if is_state(test, "100") %}
    True
  {% else %}
    False
  {% endif %}

Why does this template return "False" ?
To my understanding this code sets variable "test" to "100" and then checks if that variable is "100".
It should return "True" right ?!

cerulean karma
#
{% set test = 100 %}
{% if test == 100 %}
    True
  {% else %}
    False
  {% endif %}
#

I think a variable has no state, but a value

surreal wasp
marsh cairn
dry narwhal
#

Does anybody know if mediaquery can be used in templates?

marble jackal
#

Templates don't know frontend stuff

plain magnetBOT
remote finch
#

how can I get the id of the object (eg climate.kitchen) inside a template switch?

#

So I know which object called it

#

Basically I have a lots of generic_thermostats and they all call their own separate switch template to do turn the relavant TRV on, but it is not very DRY at the moment

#

So was trying to get the generic_thermostats to all call the same template switch and then evaluate within that or at least pass the id into a script

#

Thanks

obtuse zephyr
#

I'm thinking you probably can't do that from a single switch. But if you had multiple switches configured in the same way, you could use this.entity_id to identify that switches name and either use that directly or pass that to a script to differentiate

remote finch
#

Ha, actually that is not a bad idea at all, that would be better than what I have for sure - thank you!

outer sand
#

oh god I found why it wasnt working \\ inside "\\" becomes "\"

#

and in template tab it works because its not inside ""

remote finch
obtuse zephyr
#

the first

marble jackal
wanton girder
#

Can somebody help me to test whether a sensor state is a timestamp xx:xx - I have a sensor that return a time or "Error: Not enough data within current selection" I only wanna use the timestamp

grizzled grove
#

What would be the best approach to test a condition(ex: last_changed) at a certain time (ex: 17:00:00), to see if it's true or false?
{{(as_timestamp(now()))-(as_timestamp(states.binary_sensor.car_status.last_changed)) < 600}}
Should it be today_at(value)?

agile jungle
#

Hello. I'm trying to create "template light" with scenes and the on/off codes worked but I couldn't figure out how to set the brightness value. I have a Tuya smart remote and it is not supported by Home Assistant. So I can only use scenes.

#

Can anyone help me?

marble jackal
wanton girder
#

yes

marble jackal
#

The value_on_error setting is added for that

#

Let it return a datetime in the future if it errors

wanton girder
#

This is my snip so far

{% from 'cheapest_energy_hours.jinja' import cheapest_energy_hours %}  {% set s = cheapest_energy_hours('sensor.energi_data_service', hours=5, look_ahead=false, time_key='hour', value_key='price', time_format='time24', include_tomorrow=false) %}  {{ now().strftime('%H:%M') == s }}
glass jasper
#

whats wrong with this template trigger, it runs in automations, next alarm registers fine from my phone, yet it has never triggered

#

{{ states('sensor.pixel_8_pro_next_alarm') | as_timestamp > now().timestamp() + 3600 }}

marble jackal
#

Eg value_on_error=as_datetime('2999-12-31')

#

Wait, I misread your question

wanton girder
#

to fish - I feel stupid πŸ˜„

#

Im using it in an automation to charge my car...I want it to tell me the next cheap time..and not "error....."

marble jackal
#

Your snippet returns true or false, not a time, nor this error

#

Unless you shared the wrong template

wanton girder
#

Im using this:

  - sensor:
      - name: "Billigste 3 timer i dag"
        state: >
          {% from 'cheapest_energy_hours.jinja' import cheapest_energy_hours %}
          {{ cheapest_energy_hours('sensor.energi_data_service', hours=3, time_format='time24', look_ahead=true, time_key='hour', include_tomorrow=false, value_key='price') }}
marble jackal
#

So yeah, there aren't 3 hours left in the current day, what do you expect it to return?

wanton girder
#

Maybe "Ikke fΓΈr imorgen" (No until tomorrow)

marble jackal
#

Then use that for value_on_error

#

That's where that setting is for, to replace the errors the macro returns with something you want

wanton girder
#

Thanks πŸ™‚

#

value_on_error=Ikke fΓΈr imorgen ?

#
  • sensor:
    - name: "Billigste 3 timer i dag"
    state: >
    {% from 'cheapest_energy_hours.jinja' import cheapest_energy_hours %}
    {{ cheapest_energy_hours('sensor.energi_data_service', hours=3, time_format='time24', look_ahead=true, time_key='hour', include_tomorrow=false, value_on_error=Ikke fΓΈr imorgen ,value_key='price') }}
marble jackal
#

Quotes around your message

wanton girder
#
  • sensor:
    - name: "Billigste 3 timer i dag"
    state: >
    {% from 'cheapest_energy_hours.jinja' import cheapest_energy_hours %}
    {{ cheapest_energy_hours('sensor.energi_data_service', hours=3, time_format='time24', look_ahead=true, time_key='hour', include_tomorrow=false, value_on_error="Ikke fΓΈr imorgen", value_key='price') }}
marble jackal
#

That looks better

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
glass jasper
#

yes

#

but it doesn't tried multiple times, don't see the mistake

marble jackal
#

That's not what this is doing

Alarm at 10:00
Now is 9:15

10:00 > 10:15 == false

Now is 8:15

10:00 > 9:15 == true

#

So it will be true until one hour before your alarm

#

Basically you should use < instead of >

glass jasper
#

yeah, now I feel stupid, thx

marble jackal
#

But I would use
{{ states('sensor.pixel_8_pro_next_alarm') | as_datetime - now() < timedelta(hours=1) }}

glass jasper
#

sometimes you just don't see it

agile jungle
#

Hello. I'm trying to create Template Light. I created input.number for brightness and it works fine but I don't know how to enable scene based on brightness value. Can you help please? I can share my codes.

#
  - platform: template
    lights:
      dolap_isigi:
        friendly_name: "Dolap Işığı"
        level_template: "{{states('input_number.dolap_arkasi_isik_sensoru') | int}}"
        turn_on:
          scene: scene.lumina_osram_ac
        turn_off:
          scene: scene.lumina_osram_kapat
        set_level:
          service: input_number.set_value
          data:
            value: "{{ brightness }}"
            entity_id: input_number.dolap_arkasi_isik_sensoru```
marble jackal
#

You can use multiple actions

#
set_level:
  - action1
  - action2
agile jungle
#

I'm new to this. Can you write a little more clearly?

marble jackal
#

It can be a whole sequence of actions, exactly the same as an action sequence in an automation, include stuff like choose and if and scene.apply

agile jungle
#

Thank you very much.

restive socket
#

Does anyone know how to view or use entity_picture present in things like media_player

ember token
#

Hi , I'm using "<area name> <device name> ..." as my naming convention for all my device and entities.
It used to be, that the GUI would hide the <area name> part, if it is identical to the area the device is located in. Eg: "Keller Steckdose" would display as "Steckdose" in the area view. (The same way as Homekit does it btw)

However, this is not the case anymore. Everything ist show with the complete names everywhere.

I did not (knowingly) change anything, nor do I know if there is any setting for this behaviour. Any ideas?

marble jackal
ember token
#

Sorry, I tried to post to frontend and misclicked...reposted to #general-archived
thanks

rare furnace
#

Hello!

I am struggling a little bit.

I have an aqara mini switch which did not work as I expected. But I am trying to make a template to make it work like a push button where the signal stays 'true' as long as I hold the button.

I have found the states of action is hold and release. Hold is 'true' for some milliseconds when I hold the button and then is 'false' immidiatly after, and then the action state for release is 'true' for the same amount of time again after I release the button.

So I would like to make a template that changes the value of a binary sensor to 'true' when Hold == 'true' and only change the state of the binary sensor to 'false' when the release state is 'true' again.

#

I have tried with this:
{% if is_state('sensor.mini_switch_action', 'hold') %}
true
{% elif is_state('sensor.mini_switch_action', 'release') %}
false
{% else %}
false
{% endif %}

But it didnt work

#

It seems like it works, but since hold is immidiatly

#

'false' right after it doesnt work

#

Can I make the template ignore the 'false' values of my sensors?

rare furnace
#

In the logbook for the state action it changes to "hold" when holding the button, then changes to something like null or nothing, it just says nothing in the logbook. Then changes to release when I release the button, and then changes to nothing again. Not sure if its a nill value, null value or just "". Any ideas?

mighty ledge
#

just make a template sensor that filter's out those values

#

then apply your logic

rare furnace
#

Mini switch action
Mini switch action changed to release
Mini switch action
Mini switch action changed to hold

#

Oh, yeah I think thats what I need help for

#

Not sure how to filter out those

marble jackal
rare furnace
#

Yeah I figured that out

mighty ledge
#

make a trigger based template entity that only triggers on hold, release

rare furnace
#

I think thats what I am trying to do...

mighty ledge
#
template:
- trigger:
  - platform: state
    entity_id: sensor.mini_switch_action
    to:
    - hold
    - release
  sensor:
  - name: blah
    state: "{{ trigger.to_state.state }}"
#

if you want that as a binary sensor to skip your logic...

#
template:
- trigger:
  - id: "on"
    platform: state
    entity_id: sensor.mini_switch_action
    to:
    - hold

  - id: "off"
    platform: state
    entity_id: sensor.mini_switch_action
    to:
    - release
  binary_sensor:
  - name: blah
    state: "{{ trigger.id }}"
rare furnace
rare furnace
#

Okay, now I just need to also be able to toggle the lights with the same button, when I click the button the action is "single" - how can I manipulate the same binary sensor to go from off to on and back again using this action? And at the same time maintain the function with hold and release?

#

Seems weird that I have to program a button switch to work like a normal pushbutton

#

It seems it wont work since I allready filtered out the "null" value I didnt want, now I need it again

#

Not sure I should try another blueprint for this, but I am using "Single on/off/dim switch" blueprint which is based off a binary sensor.
So I got the hold/release to work, but not sure the blueprint works without a pulse of "On/Off" transition when just pressing the button. Now the pulse-signal is ignored and the sensor is only listening to the hold/release

mighty ledge
#
template:
- trigger:
  - id: "on"
    platform: state
    entity_id: sensor.mini_switch_action
    to:
    - hold
  - id: "on"
    platform: state
    entity_id: sensor.mini_switch_action
    to:
    - single
  - id: "off"
    platform: state
    entity_id: sensor.mini_switch_action
    from:
    - single
  - id: "off"
    platform: state
    entity_id: sensor.mini_switch_action
    to:
    - release
  binary_sensor:
  - name: blah
    state: "{{ trigger.id }}"
#

You're over thinking it

#

just look at your available triggers

rare furnace
#

yeah but the release state is not there when releasing a short press

#

then its just single, then nothing

#

So I can turn it on with single

#

but not off again

mighty ledge
#

right, that's why your 'off' trigger uses from instead of to.

#

see what I wrote πŸ˜‰

rare furnace
#

ahh okay

#

I will try it out

#

Damn, nice. Thanks alot ❀️

mighty ledge
#

np

rare furnace
#

Okay, more problems. But not a template problem this time... Not sure, but the blueprint automation seems to crash my zigbee network

mighty ledge
#

sounds like it should go in the trash then!

acoustic arch
#

i have an input_select with some brightness settings for a lamp (20 40 60 80 100) i can cycle through with a button on the wall. Now if i manually set it to say low, but the last setting of input_select was bright, and then i press the button, it jumps from low to bright.

How can i template something smart in the automation which first checks the current brightness, and then selects the first higher input_select?

#

i was thinking setting the input_select first to the lowest, then do an until loop where it checks the next_input select with the current brightess, until satisfied. Then continue with the automation of actually switching brightness

#

but that doesnt look 'smart'

acoustic arch
#

to follow up on my own question. I made something which works, but i feel im missing safety's, making the loop go beserk?

#

(input select has values 0 50 100 150 200 255)

lofty mason
#

what makes you feel it's going berserk?

acoustic arch
lofty mason
wise cliff
#

Hi everyone, I'm in desperate need of some guidance πŸ˜… I was sent here from #automations-archived but honestly have no clue where to start 😭

I'm trying to pre-heat my car based on driving time to my next calendar event.

I have my car connected
I have my calendar connect (google)
I have Waze Travel Time

I'm fairly new to this so excuse me if I'm saying anything that's fairly dumb haha.

What I'm trying to do is:
Get the location of the next calendar event (location attribute of calendar.kconsen_gmail_com)
Calculate the travel time through Waze using that location as destination and device_tracker.teslanl_location_tracker longitude and latitude attributes)
Get the start time of the next calendar event, subtract travel time from sensor.waze_travel_time and an extra 15 minutes
At the calculated time start - (travel+15) set climate.teslanl_hvac_climate_system to ON

opaque sentinel
#

The below template evaluates to "0.3", I'm expecting "0.30". I suppose Jinja2 removes the last zero by default, is there any way to force this to show? (round(3) evaulates to 0.297)

{% set fixed_tariff = states('select.energy_tariff_ex_moms') | float %}
{% set cost = hourly_usage * fixed_tariff %}
{{ cost | round(2) }}
### Evaluates to 0.3, expecting 0.30
lofty mason
#

you're generating a float, which has no concept of trailing zeros. 0.3 == 0.30 == 0.3000
If you want trailing zeros, you'll need to convert it to a string, and then do string manipulation to add extra zeros on the end.

mighty ledge
#

or use the UI to select your sig figs

#

just need a unique_id

#

on the template sensor

plain magnetBOT
#

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

forest ferry
#

this obviously works but am trying to replace the input_select by a variable (inputselect) defined in the button_card_templates

device: '[[[ return states[''input_select.ir_remote_ex''].state ]]]'
inner mesa
#

the correct syntax is the last one:
device: '[[[ return states[variable.inputselect].state ]]]'

forest ferry
#

thank you! it was indeed "[[[ return states[variables.inputselect].state ]]]"

inner mesa
#

Then there are several bad examples in the docs. BTW, this isn't JInja and belongs in #frontend-archived

forest ferry
#

ok thank you, still learning both HA and Discord .... the docs didn't have examples with nested variables within "return states" that's why I was struggling with syntax. Thanks again!

terse owl
#

Hello , can someone help me to create a value template please ? this is for this entity with the possible incoming values

entiteit : alarm_control_panel.mqtt_alarm ,
Values :
DISARMED disarmed
NIGHT_MODE armed_night
ARMED armed_away

#

mqtt:

  • alarm_control_panel:
    state_topic: "homeassistant/alarm_control_panel/state"
    command_topic: "home/alarm/set"
sacred sparrow
#

is there a way to put a template in a template? {{ is_state(states('input_text.tv_active_entity'), 'on') }} the input_text.tv_active_entity is media_player.living_room_tv_andriod_tv and the input text changes to what TV is active

#

I want to check the status of the TV

#

full condition code is from a repeat is currently:

  until:
    - condition: template
      value_template: >-
        {{ is_state('media_player.living_room_tv_kd_75x8500e', 'on') or
        repeat.index == 120 }}```
acoustic arch
#

i added 4 cores xeon to the HA VM

#

for this loop, must be sufficient LOL

cerulean karma
#

kWh Sensor -> kW Sensor

rare furnace
#

How can I check if my light brightness is over a certain value?

#

I cannot get this template to work

#

{{ is_state_attr('light.office_namron_dimmer', 'brightness', '249') }}

#

but this gives the value 250

#

{{ state_attr('light.office_namron_dimmer', 'brightness') }}

#

I got it, cant use '

#

But, it only checks if its the exact value

marsh cairn
#
{{state_attr('light.office_namron_dimmer','brightness')|int(0) > 249}}

This should be true if bigger than 249

acoustic wedge
#

Hi, long time ago, I used {{ currency }} in my templates and it appears that it's no more available. I cannot find how to access the currency set in global settings in my templates now. Any idea? Thanks in advance.

marsh cairn
#

You can set the device_class to monetary in a template sensor (and maybe set the unit_of_measurement, if it doesn't use the global settings currency - not 100% sure if it does by default)

acoustic wedge
#

I just wanted to know if this variable is still available somewhere as it used to be. If I understand well your response, it means that it's not the case anymore, right?

marsh cairn
#

At least I'm not aware of such variable - fwiw

acoustic wedge
#

Thanks a lot

cerulean karma
#

how can I get all properties of a sensor?

#

I want to see if there is a "last_changed" or "last_value" eg

marsh cairn
#

Go to the developer tools - states section

visual phoenix
marble jackal
#

it has javascript templates, which are not the topic of this channel

cerulean karma
#

Thanks Jorg

quaint grotto
#

hey...

i want to track the amount of time my boiler fires for hot water vs heating
i've a "boiler on" binary sensor - i'll call that binary_sensor.boiler_on, plus sensors for heating on (sensor.wiser_heating) + hot water on (sensor.wiser_hot_water).

So i want to track the time heating is on + boiler is firing as one history stat
And similarly, hot water on + boiler is firing as another history_stat.
And I can do that bit - binary sensor to combine the two being the key bit.

The bit i am stuck with - if hot water + heating are both on + boiler firing, I want to split the boiler firing time 50/50 between the hot water and heating history_stats ideally. But I can't see any way to do this....

Any suggestions ?

cerulean karma
#

If I have a sensor that is triggered by state change, I can access the old state via trigger.from_state.state. But if I have a second trigger that is time_pattern I can't get the old state. Is that right?

marble jackal
#

correct

#

there is no old state vs new state then

cerulean karma
#

and how would I solve this problem?

#

I want to calculate a difference

#

at least every 10minutes eg

marble jackal
#

what's the problem? If it triggers on the time patter there is only a current state

mighty ledge
#

there is no difference

marble jackal
#

you need to give more info here

mighty ledge
#

because there is no state change at your 10 minute period

cerulean karma
#

ok one moment I try to give some code

mighty ledge
#

the change would always be 0

cerulean karma
#
- trigger:
    - platform: state
      entity_id: sensor.gasverbrauch_in_kwh
      to: ~
  sensor:
  - name: Gas ZΓ€hlerstand Diff
    unique_id: gas_zahlerstand_diff
    unit_of_measurement: W
    state_class: measurement
    device_class: power
    state: >
      {% set diff_seconds = (now() - trigger.from_state.last_updated).total_seconds() %}
      {% set to_value_kWh = (float(trigger.to_state.state)) - (float(trigger.from_state.state)) %}
      {% set to_value = int(to_value_kWh*1000*(3600/diff_seconds)) %}
      {{ to_value if to_value }}
#

this one would never shot 0W if the state does not change any more

#

so I need to get back every 10minutes or so to look if there was a change

#

would it work to just check if it was a state change?

mighty ledge
#

right but what you aren't understanding is that if there is no state change, and you just get the state, then you're just getting the state.

#

there's no to-state, no from-state, only a current state

cerulean karma
#

I get you petro

#

so I just need to check if the trigger was by state or by time?

#

and if it was by time I return "0"

mighty ledge
#

right

cerulean karma
#

Can I check which trigger it was?

mighty ledge
#

trigger.platform == 'a'

cerulean karma
#

oh great

marble jackal
#

or by giving them a trigger id

mighty ledge
#

fyi to_value if to_value doesn't really make sense

cerulean karma
#

that is right, I simplified it while testing πŸ™‚

#
      {% if trigger.platform == "time_pattern" %}
      {{ 0 }}```
#

like this?

mighty ledge
#

that should work

#

but you need the endif

cerulean karma
#

yes sure

mighty ledge
#

assuming you left that out for brevity

cerulean karma
#

thanks to both of you....

mighty ledge
cerulean karma
#

I just try to get approx value (maby in percent) of how much the gasheater modulates

#

It can do 1kW-11kW and I want to see if I can visualize it with this sensor

#

I will see if this works πŸ™‚

mighty ledge
#

keep in mind that HA suppresses state changes if the state doesn't change

#

so if you get multiple zeros in a row, then your sensor will not have a 'new' last_changed

plain magnetBOT
cerulean karma
#

ahh ok

#

I did not know this

mighty ledge
#

all of HA does this

#

so any time a sensor updates w/ the same value, it does not produce a state change event

cerulean karma
#

So how to deal with that?

mighty ledge
#

you don't, you're stuck with how the system works

#

you can add a random value that's insignificant

#

also just to let you know, there's a derivative integration which does this math for you

cerulean karma
#

you say I could use a better/ready sensor instead if doing this?

mighty ledge
#

not sure what you're saying there, but there's an integration which gets you the rate of change of any sensor, it's called derivative

plain magnetBOT
cerulean karma
#

hmm ok

marble jackal
#

@mighty ledge my cheapest energy macro has a whitespace issue. Apparantly I have 330 %} but only 227 -%} so 3 of them are wrong

#

any chance you know how to find them using a regex search in VSCode?

#

So I want to have the %} without a hyphen (and they don't have a space before them, already searched for that)

#

found one, only 2 left

#

hmm, found the last 2, but still the same issue

cerulean karma
#

too late, but I think this would have helped: [^-]%}

marble jackal
#

tried that, but it no dice

cerulean karma
#

ok it is a VSC related problem...didnt get that

marble jackal
#

thanks anyway!

quaint grotto
mighty ledge
#

(?<!-)(%}|{%|{{|}})(?!-) for all

dense swan
#

I am trying to create an automation using some templates but not sure how to use nested variables in other variables properly in Home Assistant. I have a lock in Z2M and the payload into MQTT contains the "action_user" who generated the event and I need to get the PIN of that user from the payload and then run it against a list of users assigned to PIN to get me the "friendly name" of the user who unlocked the lock. Here is what I have but not sure how to get the nested variable done properly.

plain magnetBOT
dense swan
#

I was wondering if anyone had some examples to point me to.

mighty ledge
#

@dense swan
do you know the pin?

#

or is action_user the person who did the action?

dense swan
#

I know the MAPPING of PIN to user, I want to resolve that used pin to the "friendly name" of the user during the automation run

#

Yup

mighty ledge
#

ok, got it

#

give me a sec

dense swan
#

action_user = slot in lock

mighty ledge
#

So to clarify, we use the action_user to get the pin they used?

#

nevermind, i'll work with that

dense swan
#

action_user = slot the lock used so then get the PIN of that slot.

#

and then resolve that PIN against a hash to convert 1234 to User X

#

I didn't want to maintain a list of slots since it could differ on locks

mighty ledge
#
{% set user = payload_json.action_user | string %}
{% set used_pin = payload_json.users[user].pin_code %}
{{ pin_codes_to_names.items() | selectattr('0', 'eq', used_pin) | map(attribute='1') | first | default }}
dense swan
#

Hmm interesting

mighty ledge
#

if you made your pin to code names differently the code would be easier

#

e.g.

{% set pin_codes_to_names = [
  {'name': 'User X', 'code': "1234"},
  {'name': 'User Y', 'code': "5678"},
] %}
#

would be.

dense swan
#

Oh

#

I can do that

#

That is the only list i want to maintain by hand to be honest

mighty ledge
#
{% set user = payload_json.action_user | string %}
{% set used_pin = payload_json.users[user].pin_code %}
{{ pin_codes_to_names | selectattr('code', 'eq', used_pin) | map(attribute='name') | first | default }}
#

would be easier to read

#

not to mention, if this is in an automation variable section... you can just use yaml

#
pin_codes_to_names:
- name: A
  code: 1234
- name: B
  code: 5678
#

but you'd have to ensure the code is an int or enforce it as a string

#
pin_codes_to_names:
- name: A
  code: '1234'
- name: B
  code: '5678'
dense swan
#

Interesting.

dense swan
#

I see, thanks! Let me play with it.

mighty ledge
#

πŸ‘

marble jackal
#

New question, is there an easy way in Jinja to multiply the values of 2 lists of equal length with each other?
So [ 1, 5, 3] and [ 4, 2, 2 ] will result in [ 4, 10, 6 ]

#

I now use a for loop for that

mighty ledge
#

heh, no

#

numpy can do that really easily

#

so if you use pyscript you'll be able to do that

#

it'll just be np.array([ 1, 5, 3]) * np.array([ 4, 2, 2 ])

#

πŸŽ‰

marble jackal
#

Yeah, I found that

#

It's for the cheapest energy macro, you can assign a weight if you eg want to find the best time to turn on the dishwasher which uses most energy in the first hour

#

I'll stick to it loop then

mighty ledge
#

yeah, I'd just loop it w/ namespace

dense swan
#
variables:
  user: >
    {{ trigger.payload_json['action_user'] | string }}
  used_pin: >
    {{ trigger.payload_json[user].pin_code }}
  pin_codes_to_name:
  - name: A
    code: '1234'
  - name: B
    code: '5678'