#templates-archived

1 messages Β· Page 54 of 1

rose scroll
#

That Jinja looks syntactically correct. What does value_json return?

fierce hawk
#

currently reported value is 129

rose scroll
#

value_json returns 129 directly? Then you don't need .svalue1.

#

Does it return 129 as a number or string?

fierce hawk
#

yes directly, i supposed it's a string

#

how can I double check in mqtt explorer?

rose scroll
#

Also, 129 is not one of the numbers defined in your if statements.

fierce hawk
rose scroll
#

If you remove .svalue do you still get an error?

plain magnetBOT
#

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

rose scroll
#

It says there that you have to provide command_topic: before it will parse the yaml validly.

#

It is required for an MQTT select, as per the docs.

fierce hawk
#

aaaaaah

#

ok thanks I will try to do that after lunch

mighty ledge
#

FYI value_json will not resolve if it just returns a number. You'll have to use value. Also, if value_json does resolve and it has keys like svalue, you'll have to make sure to check the value type when making if statements. 129 is not the same as "129". You can see this directly in the JSON for the topic. No quotes means you check without quotes.

plain magnetBOT
#

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

marsh cairn
#

There are missing % in front of each many }

fierce hawk
#

thanks a lot

fierce hawk
#

Ok so now it parses the value Level1, Level2 or Level3 instead of 129, 130 and 131 when I select the dropdown.
I assume this is because we need now a command_template

I've tried this:

      command_template: >
        {% if value == Level1 %} 129
        {% elif value == Level2 %} 130
        {% elif value == Level3 %} 131
        {% endif %}

It doesn't work but I don't think I am too far; I tried to re[p;ace value by state but doesn't work either

mighty ledge
#

can you post the values in your topics please?

#

@fierce hawk ^

haughty breach
#

You need quotes around your strings i.e. {% if value == "Level1" %} 129

mighty ledge
#

that won't necessarily work

#

yes it will correct the problem on that template, but we still need to see the values in the topics

fierce hawk
#

Im trying to send an image in discord but seems I dont have the option?

mighty ledge
#

just copy/paste the value

fierce hawk
#

the value are just
129
130
131

mighty ledge
#

images are discuraged because we don't want pictures of text, we want the text

mighty ledge
fierce hawk
#

yes

mighty ledge
#

then value_template and commadn_template will be opposite

plain magnetBOT
#

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

mighty ledge
#
command_template: >
  {% if value == 'Level1' %}129
  {% elif value == 'Level2' %}130
  {% elif value == 'Level3' %}131
  {% else %}?????
  {% endif %}
#

You need a command for the off selection

#

assuming it's zero

#
  {% if value == 'Level1' %}129
  {% elif value == 'Level2' %}130
  {% elif value == 'Level3' %}131
  {% else %}0
  {% endif %}
#

then reverse it for the value_template

  {% if value == '129' %}Level1
  {% elif value == '130' %}Level2
  {% elif value == '131' %}Level3
  {% else %}Off
  {% endif %}
fierce hawk
#

ok, should it be ' or " ?

mighty ledge
#

doesn't matter

fierce hawk
#

it works πŸ™‚
one thing I noticed is that the state is "unknown" under the dev tools/state
select.ccei_pump_speed -> unkown

I'd expect to be the reported value??

mighty ledge
#

that's why I've been asking for you to copy/paste the values from your topics here

#

because right now, I have no idea if what you're saying is correct

fierce hawk
#

what is the best way to share this? the way I checked the values are on MQTT explorer
topic: anteavs_C049EFEC7950/u8_w/filt_speed/info/reported

value history
129
130
...

mighty ledge
#

if that's the case, it should just work on startup if the topic has one of those values in it

fringe sail
#

Hey guys. I'm at a loss on template fans. Can somebody explain to me what I'm missing in this setup? I can run a script that cycles through a set of scenes, where each scene controls a speed of a 3 speed fan. So, I have scene.dining_room_fan_all_off, all the way to scene.dining_room_fan_high_on. If I cycle through the scenes, everything works as expected. I want to make a template fan that comes on, when any of the fan speeds come on. I also want the template fan to show 4 presets or speeds, off all the way to high. I've set this example of a template fan up, but it doesn't work as expected. What am I missing?

https://pastebin.com/g5dDfQbk

mighty ledge
#

scripts don't have states

#

so your preset mode template isn't correct

#

and your set_preset_mode service doesn't do anything

#

that should be calling the scenes, assuming that's what you want to run

fringe sail
#

Am I allowed to have more than 1 entity in the set pre set mode?

mighty ledge
#

set_preset_mode is just an action section, exactly like the automation action section

fringe sail
#

So, I should be turning on the scenes that correspond to the fan speeds?

mighty ledge
#

but you aren't using the preset_mode variable

mighty ledge
#

or scene

fringe sail
#

Do I need a script for every scene/speed or can 1 script that cycles through the scenes/speeds work?

mighty ledge
#

you can do whatever you want it to do

#

that's the beauty, if you can dream it up, you can do it

#

it's a full action section

#

that means you can write multiple actions

fringe sail
#

What about the preset mode template, am I describing it correctly, or if not how would I?

#

This template does cylce throught the speeds fine, but I can't pick a set speed. I can only cycle.

fringe sail
#

You said scripts don't have states, but when I put {{ states('script.dining_room_fan_control') }} into the developer tool template, I get whatever the scene the script is on at the time. I thought that I could then describe the preset mode template, as each different scene of the script as a preset.

#

I'm sure templates are easy for guys like you, but I can't understand things like this, unless I get specific questions answered, or have directly similar examples.

inner mesa
#

Scripts are either off or on, and the latter only if they're currently running and waiting for something. At no time is the state of a script a scene

wicked kiln
#

I have a ... aesthetical problem right now: This is my morning routine template: https://www.pastiebin.com/650c29e60ed40 and this the current output: https://www.pastiebin.com/650c2a2878563 today there is nothing on Google Calender and thus is does not show any appointment. My problem is that there are double spaces between a few of the outputs and these ugly newlines are not needed, too. What did I do wrong here?

jagged obsidian
#

you have spaces outside of the templated values

wicked kiln
#

I do? I tried to get rid of any trailing and leading spaces. What for example do you mean?

jagged obsidian
#

von {{ states('sensor.openweathermap_forecast_precipitation_probability') }} Pr has a space before the value and a space after the value, if the value is empty you get 1+1 spaces

mighty ledge
#

if you're referring to the whitespace, i.e. carriage returns. add -'s to your template. See pin #2

wicked kiln
#

that is true, but the values are not empty by normal circumstances.

#

For example line 4. This line is passed nicely and then the output has two spaces instead of one before it continues with the line 7 rainy condition output. And the line 31 part seems to create newlines even.

jagged obsidian
#

petro answered the newlines issue

wicked kiln
#

He did? I just fixed the second whitespace thx to him now, that for sure.

mighty ledge
#

Yes I did, read the 2nd pin in discord

wicked kiln
#

I mean I know why it's there I guess, but if I remove the spaces from for example line 7 it starts to tell me in File Editor that I am doing bad things. Template Editor is happy though.

marble jackal
#

that indentation is because you have it indented in the template editor

mighty ledge
marble jackal
#

@wicked kiln you can remove a lot of repetition in the weather part if you do it more like this: https://dpaste.org/eXfr7

mighty ledge
#

πŸ”₯

#

proper use of the -'s

wicked parrot
#

Any way to have state_arr check for multiple values?

buoyant pine
#
{{ state_attr('deez.nuts', 'attr') in ['foo', 'bar'] }}
wicked parrot
#

Yesss, @buoyant pine thank you.

wicked kiln
haughty breach
#

IMAP Content Template sensor

junior star
#

I'm having an issue with this template. I've discovered the nature of the issue...I'm just too new at templates to know how to fix it.
"val":{{- state_attr({{ light_entity }}, 'brightness') -}}

#

{{light_entity}} is defined elsewhere and works in all other calls within the script, but the 2 sets of {{ }} are throwing an exception

inner mesa
#

Right, you should remove the inner pair

#

It's a variable, just use it

junior star
#

I was getting confused because other places I needed to use quotes around the double braced variable, but because this is a function it just needs the variable (not the value contained in the variable) ...right?

slate fossil
#

I'm confused as to why this works in Dev Tools but not when I create a binary template sensor helper with a Motion device class. Entity's state doesn't change even though the template returns properly in Dev Tools. Ideas?

{% set motion = 'binary_sensor.bathroom_motion_detector_on_off' %}
{% set occupancy = 'binary_sensor.bathroom_motion_detector_occupancy' %}
{% if is_state(motion, 'on') or is_state(occupancy, 'on') %}
Detected
{% else %}
Clear
{% endif %}```
lofty mason
slate fossil
#

so the device class handles the Detected/Clear, right?

lofty mason
#

Yes, it's just a frontend translation.

The sensor is on if the template evaluates as True, yes, on, enable or a positive number. Any other value will render it as off. The actual appearance in the frontend (Open/Closed, Detected/Clear etc) depends on the sensor’s device_class value
https://www.home-assistant.io/integrations/template/#state

slate fossil
#

changing to on/off is literally all it took to work. πŸ€¦β€β™‚οΈ

rose scroll
slate fossil
fierce hawk
#

Hi there,
I have a question regarding the brightness_scale on mqtt light.
I currently have a light where you can change the brighness but its on 3 levels instead of %

  • 0 = 25%
  • 1 = 50%
  • 2 = 75%
  • 3 = 100%

I have done the code below but doesn't seems to work: or maybe I should use a different slider?

  light:
    - name: "CCEI WEX30 PoolLight"
      device:
        identifiers: "C4DEE2D4C3B0"
        manufacturer: "CCEI"
        name: "Tild"
        model: "V1"
        hw_version: "1"
        sw_version: "2.80"
      unique_id: CCEI_WEX30_Light
      state_topic: "tild_C4DEE2D4C3B0/u8_w/light_state/info/reported"
      command_topic: "tild_C4DEE2D4C3B0/u8_w/light_state/info/desired"
#      brightness: true
      brightness_scale: 3
      brightness_state_topic: "tild_C4DEE2D4C3B0/u8_w/light_bright/info/reported"
      brightness_value_template: >
        {% if value ==  0 %} 0%
        {% elif value == 1 %} 25%
        {% elif value == 2 %} 50%
        {% elif value == 3 %} 100%
        {% endif %}
      brightness_command_topic: "tild_C4DEE2D4C3B0/u8_w/light_bright/info/desired"
      brightness_command_template: >
        {% if value ==  "0%" %} 0
        {% elif value == "25%" %} 1
        {% elif value == "50%" %} 2
        {% elif value == "100%" %} 3
        {% endif %}
      payload_on: "1"
      payload_off: "0"
marble jackal
#

brightness_value_template should return a number, you are now returning a string

#

besides that, you've set the brightness_scale to 3, so 3 is now your maximum brightness value

#

I must admit I don't have a lot of experience with mqtt lights, but to me it looks like you don't need the brightness_value_template at all

#

for the brightness_command_template you might need to round the value, don't know if it will send a floating point number

fierce hawk
#

it works πŸ™‚ thanks

silent vector
#

What's the difference between from_keys in home assistant and fromkeys in native python when working with tuples ?

#

from_keys in home assistant works with tuples while native fromkeys does not.

thorn harness
#

Hello alltogether. May someone help me to get an automation working?

#

What i want to achieve: i have 11 room thermostats. every room has its own external thermostat. if 3 of the actual set temperatures are below 1 degree of the actual measured room sensors, i want to set the heater to on, because then i need enough thermal energy

mighty ledge
marble jackal
thorn harness
#
  • platform: state
    entity_id:
    - climate.tcv_badezimmer
    attribute: current_temperature
silent vector
thorn harness
#

trigger:

  • platform: state
    entity_id:
    • sensor.average_temperature_badezimmer
    • sensor.average_temperature_buro
    • sensor.average_temperature_dusche
    • sensor.average_temperature_flur_anbau
    • sensor.average_temperature_kinderzimmer_1_west
    • sensor.average_temperature_kinderzimmer_2
    • sensor.average_temperature_kuche
    • sensor.average_temperature_schlafzimmer
    • sensor.average_temperature_wohnzimmer
  • platform: state
    entity_id:
    • climate.tcv_badezimmer
    • climate.tcv_buero
    • climate.tcv_dusche
    • climate.tcv_flur_anbau
    • climate.tcv_kinderzimmer_1_west
    • climate.tcv_kinderzimmer_2
    • climate.tcv_kueche
    • climate.tcv_schlafzimmer_ost
    • climate.tcv_schlafzimmer_west
    • climate.tcv_wohnzimmer_nord
    • climate.tcv_wohnzimmer_sued
      attribute: temperature
#

This should do it i think?

#

because average sensor is already a temperature which changes states

#

value_template: "{{ state_attr('climate.tcv_badezimmer','temperature') }}"

#

this should do it

#

Well, is this right here? "{{ state_attr('climate.tcv_badezimmer','temperature') }} <=1 {{ states('sensor.average_temperature_badezimmer','temperature') }}

#

"19.0 <=1 20.8

marble jackal
#

you are still creating 2 different templates with a string in between

thorn harness
#

i just want to compare 😦

#

if sensor 1 is 1 degree lower then average

marble jackal
#

test you templates in developer tools > templates, but I guess you want something like:
{{ state_attr('climate.tcv_badezimmer','temperature') <= states('sensor.average_temperature_badezimmer') | float }}

thorn harness
#

i did

#

Thank you, it gives me true outout

marble jackal
#

it should output true or false. Not something like 19.0 <=1 20.8

thorn harness
#

but how do i tell it,compare 1`?

marble jackal
#

{{ state_attr('climate.tcv_badezimmer','temperature') - states('sensor.average_temperature_badezimmer') | float <= 1 }}

#

something like that

#

subtract them, and compare the result with 1

#

or move stuff around {{ state_attr() + 1 <= states() | float }}

thorn harness
#

Thank you πŸ™‚

rose scroll
#

And if you want to test whether at least 3 of your thermostats pass that test, you can simply do {{ (state_attr('climate.xxx', 'temperature') - states('sensor.aaa') | float <= 1) + (state_attr('climate.yyy', 'temperature') - states('sensor.aaa') | float <= 1) + ... + (state_attr('climate.zzz', 'temperature') - states('sensor.aaa') | float <= 1) >= 3 }}

#

Because {{ true + true }} yields 2 πŸ˜‰

thorn harness
#

Thanks πŸ™‚

#

I will try now, change from true to false worked by changing target temperature πŸ™‚

#

I just want to save unneccesary gas at winter

#

πŸ™‚

#

boiler should heat, if heat is needed, not the whole day

silent vector
thorn harness
#

it seems to work πŸ˜„

#

{{ state_attr('climate.tcv_badezimmer','temperature') + 1 <= states('sensor.average_temperature_badezimmer') | float +
state_attr('climate.tcv_buero','temperature') + 1 <= states('sensor.average_temperature_buro') | float +
state_attr('climate.tcv_dusche','temperature') + 1 <= states('sensor.average_temperature_dusche') | float +
state_attr('climate.tcv_flur_anbau','temperature') + 1 <= states('sensor.average_temperature_flur_anbau') | float +
state_attr('climate.tcv_kinderzimmer_1_west','temperature') + 1 <= states('sensor.average_temperature_kinderzimmer_1_ost') | float +
state_attr('climate.tcv_kinderzimmer_2','temperature') + 1 <= states('sensor.average_temperature_kinderzimmer_2') | float +
state_attr('climate.tcv_kueche','temperature') + 1 <= states('sensor.average_temperature_kuche') | float +
state_attr('climate.tcv_schlafzimmer_ost','temperature') + 1 <= states('sensor.average_temperature_schlafzimmer') | float +
state_attr('climate.tcv_schlafzimmer_west','temperature') + 1 <= states('sensor.average_temperature_schlafzimmer') | float +
state_attr('climate.tcv_wohnzimmer_nord','temperature') + 1 <= states('sensor.average_temperature_wohnzimmer') | float +
state_attr('climate.tcv_wohnzimmer_sued','temperature') + 1 <= states('sensor.average_temperature_wohnzimmer') >= 3 }}

delicate dune
#

Anyone can help me out with the FAN template to control my type-D ventilation? I have a smart plug to turn then vent on and of, and a "shelly 2PM" to set the fan to MID and HI

Off : smart plug turned OFF
low : smart plug ON, S1 & S2 shelly OFF.
mid: smart plug ON, S1 ON& S2 shelly OFF.
hi: smart plug ON, S1 & S2 shelly ON.

Or Node-red, also good,I have read some posts, but still not really clear to me.

mighty ledge
#

FYI that can be drastically simplified if you just shared the automation like I asked πŸ˜‰

#

well, apparently you did, but it didn't ping me?? wtf

#

fucking discord

thorn harness
#

Well, i just didnt know how to do, it was work in progress πŸ™‚

mighty ledge
#

give me a moment

mighty ledge
#

might require you to check for -1 to -3

#

instead of 1 to 3

thorn harness
#

thank you πŸ™‚

#

Thanks all for the support πŸ™‚

mighty ledge
#

your template makes no sense

#

fyi

#

you're adding the value "True" which is equivalent to 1 to all your temperature differences then evaluating that against the number 2

thorn harness
#

i dont understand that i think ^

#

do you mean the triggers?

mighty ledge
#

what do you think it's doing?

thorn harness
#

I thought it is looking for every thermostat and its temperature sensor if the difference is higher then 1 degree. if 3 or more of these pairs are with that difference, then my heater will be set on

mighty ledge
#

no it is not doing that

thorn harness
#

but it shows me true and false

mighty ledge
#

yeah, that doesn't mean it's correct

thorn harness
#

hm :\

mighty ledge
#

I pasted a working automation that literally does what you want

#

it didn't have the other trigger though

#

but you don't really need the other trigger

thorn harness
#

i try yours πŸ™‚

mighty ledge
#

you want heat_cool mode, so you'll have to alter that service call

#

and as I said, if the temperature is below the average, then you'd want to account for that instead of what I had

thorn harness
#

@mighty ledge your automation does not trigger

#

i changed the service call to the right one

#

i have set 4 thermostats to 23 degrees, room temps are aroun 20 degrees, automation was not triggered

mighty ledge
thorn harness
#

yeah, but thats the thing: if room temperature is 19 degree, room temp thermostat is set to 19 degree. someone changes thermostat to 20 degree, then it should be count as 1. if some other rooms are also set higher, then that should also count and if 3 thermostats are set 1 degree higher, or temp in 3 rooms falls below 1 degree, heater should start heating πŸ™‚

#

that was what i meant with compare

#

πŸ™‚

mighty ledge
#

so you have all these climate devices that don't run thermostats? They just give you a temperature?

thorn harness
#

no. i have actually 11 rooms thermostats. every rooms has its own, external room sensor. each thermostat will be actualzed every 15 minutes for the external temp. i have a gas boiler which only should heat, when enough heat is needed

#

these are danfoss ally thermostats. but if u measure the temperature directly at the heat, you will get extremely inaccurate room temperatues

#

at the radiator i mean not heat

#

these thermostats support external sensors. they measure the room temp at the middle of the room, far away from the radiator.

#

thats why i meaned that we need to compare the actual set temp of the room thermostat and the room sensor, then it works

#

that was why this -> {{ state_attr('climate.tcv_badezimmer','temperature') + 1 <= states('sensor.average_temperature_badezimmer') | float

#

the average sensor is middled by a custom sensor of the external room sensor by 5 minutes. if a door gets opened or a window, the thermostat should not immediately react to that

mighty ledge
silent vector
#

Any idea where I can find the from_keys python docs?

thorn harness
#

@petro thank you very much πŸ™‚ it seems to work πŸ™‚

inner mesa
#

I think it's almost the same as the Jinja from_keys method

silent vector
abstract folio
#

Is it possible to have a sensor of device_class duration to only show days in the front end?

lofty mason
#

Don't believe this is customizable with any of the default cards.
You could do it with a template in Markdown card if that works for you

radiant spindle
#

Hey, I'm trying to make a custom weather template, is there a field for the full week forecast?

#

because this forecast_daily_template: "{{ state_attr('weather.my_region', 'forecast') }}"does not work, I'm not sure what the template is expecting

#

(weather.my_region) is an entity coming from accuweather

marsh cairn
#

The forecast attribute is depreciated and not used anymore by some weather integrations. You have to get the forecast by a service call

plain magnetBOT
marble jackal
radiant spindle
#

yes, but it returns a list

marble jackal
#

Because if it does, it should work for the template weather

#

That's expected, a list with one forecast per item

marble jackal
radiant spindle
#

Invalid config for [weather.template]: [forecast_daily_template] is an invalid option for [weather.template]. Check: weather.template->forecast_daily_template. (See ?, line ?).

marble jackal
#

Are you on HA 2023.9?

radiant spindle
#

maybe it's deprecated as Jorg said

#

I'm on 2023.3.1

inner mesa
#

Ancient

marble jackal
#

That specific key is added in 2023.9

radiant spindle
#

oh well

#

sorry then

marble jackal
#

forecast_template should work

radiant spindle
#

it works indeed, thanks for the help

plain magnetBOT
lucid thicket
#

{% set LEDOn = states('input_datetime.light_s_on') | as_datetime %}
        {% set Length = states('input_number.light_schedule') | float %}

        {{ ( LEDOn + timedelta(minutes=Length) ) | as_timestamp | timestamp_custom("%H:%M:%S", True) }}

#

Or another way:

#
{% set LEDOn = states('input_datetime.light_s_on') | as_timestamp %}
{% set Length = states('input_number.light_schedule') | float * 60 %}

{{ ( LEDOn + Length ) | timestamp_custom("%H:%M:%S", True) }}
brave vine
lucid thicket
#

Sure. The template editor is extremely useful when trying to get this stuff correct. Just start small and as you get each line correct you can add more lines of code.

plain magnetBOT
#

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

lucid thicket
marble jackal
#

alternative

start: >
  {% set t = today_at('18:00') %}
  {% set d = 0 if now() > t else 1 %}
  {{ t - timedelta(days=d) }}
#

Same result πŸ™‚

brave vine
# lucid thicket ```jinja {% set LEDOn = states('input_datetime.light_s_on') | as_timestamp %} {%...

Just gave these two a try and neither seem to work either.

First one comes back with error "TypeError: unsupported operand type(s) for +: 'NoneType' and 'datetime.timedelta'"

Second comes back with error "ValueError: Template error: as_timestamp got invalid input '01:00:00' when rendering template '{% set LEDOn = states('input_datetime.light_s_on') | as_timestamp %} {% set Length = states('input_number.light_schedule') | float * 60 %} {{ ( LEDOn + Length ) | timestamp_custom("%H:%M:%S", True) }}' but no default was specified"

Gave it another go myself but just cant figre it out at all.. this is such a pain 🀣

#

It doesnt seem to be using the input_datetime as needed

inner mesa
#

your datetime only has a time

#

replace the first line with {% set LEDOn = today_at(states('input_datetime.light_s_on')) | as_timestamp %}

brave vine
#

Thank you @inner mesa, although still having an issue with this, it has improved for sure, but the time is now 1 hour behind (ive taken away the + 18 hour input nunber), but the input_datetime is not showing as 00:00 if I set it to 1:00, any ideas ?

inner mesa
#

I'm not following

brave vine
#

so ive got an input_datetime to select when the lights will turn on and a input_number for how long the lights are on for, essentially im trying to figure out the time the lights will turn off (if that makes sense?)

inner mesa
#

you should use the first bit of code provided by mekaneck that uses a datetime object

#

I don't understand the problem that you described above

#

but the input_datetime is not showing as 00:00 if I set it to 1:00

brave vine
#

using the below;
{% set LEDOn = today_at(states('input_datetime.light_s_on')) | as_timestamp %}

input_datetime is set to 1:00 but the code shows 00:00, so its an hour behind

inner mesa
#

okay, I think you said the opposite above

brave vine
#

sorry.. im confusing myself here too lol... but yes, the code pulls back a value which is an hour behind

inner mesa
#

what is the input_number set to?

brave vine
#

input_number is currently set to 18

#

{% set LEDOn = today_at(states('input_datetime.light_s_on')) | as_timestamp %}
{% set Length = states('input_number.light_schedule') | float * 60 %}

{{ ( LEDOn + Length ) | timestamp_custom('%H:%M', False) }}

returns 03:18, which, working correctly should be 18:00

inner mesa
#

why did you add False?

brave vine
#

Hmm, didnt see that one, thats now been changed πŸ˜„

silent vector
#

Is there a way with a rest sensor to just pass the entire response into the attributes field? I tried

json_attributes:
  -  "{{ value_json }}"

GitHubs API spits out an array with no Json keys to go off of.

inner mesa
#

if you specify hours

marble jackal
brave vine
silent vector
#

Dang. Not sure how else to get this into the attributes field when it's just a giant list response.

#

It's that. Can see the example response is just a list

lucid thicket
silent vector
#

I think the issue is just wether or not it's possible to dump the rest API response into an attribute. When there's no keys to go off of?

lucid thicket
#

Attributes support lists and dicts. I don’t see why that entire output couldn’t be stored in an attribute, at least with multiscrape. I don’t know the limitations of the rest sensor.

silent vector
#

I'll look into it thank you

languid pendant
#

quick though to y'all smart peeps... when templating an entity_id for a target in a script, if the template returns more than one entity, how do I write the jinja so it doesnt error with invalid entity_ids?

target:
entity_id: >-
{%for entity in (state_attr('media_player.mrp_helper','entity_id'))%}
{%if is_state(('input_boolean.' ~ entity.split('.')[1]),'on')%}
{{entity}}{%endif%}{%endfor%}
[3:19 PM]
above checks if correlating input boolean is on, then returns the id
[3:19 PM]
works in templater, doesnt work in script
[3:20 PM]
thoughts?

#

oop sorry about the timestamps, I am asking in automations as well

inner mesa
#

Please do not cross post

languid pendant
#

fair. i figured i would check here as I didnt get any kind of response in the other chan; sorry

inner mesa
#

This was the correct channel

#

The answer is that you need to output a list

languid pendant
#

ahh .. on the for line

#

correct?

#

or with the entity

#

wait .. i think I remember reading something somewhere about join?

marble jackal
#

You can either use a namespace and put the entity_ids in a list and output that.
Or use the group members and create a separate list to check on the input boolean states out of that list

#

With the second option you don't even need a for loop

languid pendant
#

Fes, I'll be honest; I'm not that familiar with Jinja. I'm coming from google and VB from about 15 years ago

#

It's new, and for a dude my age, painful to learn and keep up... but I'm tryin

#

I'll see what I can do, but I appreciate the pointers from you both

#

unless you can example me up faster than google, and I can take a gander (I'm good at dissecting, not creating from scratch)

marble jackal
#
target:
      entity_id: >-
        {% set ns = namespace(list=[]) %}
        {% for entity in (state_attr('media_player.mrp_helper','entity_id')) %}
          {% if is_state(('input_boolean.' ~ entity.split('.')[1]),'on') %}
            {% set ns.list = ns.list + [entity] %}
          {% endif %}
        {% endfor %}
        {{ ns.list }}

That's option 1

languid pendant
#

ok ... so defining ns as a list and then adding them. then return the ns

#

that, I understand

marble jackal
#

Correct

#

You need to define a namespace to get the data out of the loop

languid pendant
#

(namespaces are new. Ill have to google up on them)

#

i wasnt aware you could define them as lists

marble jackal
#
{% set mp = state_attr('media_player.mrp_helper','entity_id') %}
{% set bool_on = mp | map('replace', 'media_player.', 'input_boolean.') | select('is_state', 'on') | map('replace', 'input_boolean.', 'media_player.') | list %}
{{ mp | select('in', bool_on) | list }}
#

That should also work

languid pendant
#

literally just choked on my coffee. holy cow

#

ahh ok I see what its doing, though

#

remapping the domain to and from input_boolean

#

selecting the ones in the list that are on, then exporting as list

#

dang

#

I dont think I would have found the 2nd option very easily with google

#

thanks, Fes. 6 of one, half dozen of the other... I can dig it

heavy minnow
wheat junco
#

Hello. How could I combine two sensors for the same period of time but 24 hours apart? I have a sensor counting how long my AC ran during the previous day (using History Stats), and I have a different sensor counting how long the AC has run today so far. If it’s only 3PM so far today, I want to compare today’s usage with yesterday’s usage up until only 3PM, so I can figure out if I’m using more or less by the same time of the current day. I’m not sure if this would end up needing to be an elaborate template sensor, or if something exists built-in like a helper or integration that I may have missed trying. I’m looking for any suggestions or a direction to go. Thank you.

haughty breach
languid pendant
#

alright ... one more for ya, Rob or Fes;

  entity_id: >-
    {% set ib = trigger.entity_id %}
    {% set mp = ib | map('replace', 'input_boolean.', 'media_player.') | list %}
    {{ mp | list }}

this would, from what I think I understand would replace the 'input_boolean.' with 'media_player.' and then output as a list.

but, it splits the whole thing into seperates:
valid entity IDs: ['i', 'n', 'p', 'u', 't', '_', 'b', 'o', 'o', 'l', 'e', 'a', 'n', ...]

#

what am I missing, here?

inner mesa
#

You're making it a list...twice

#

It is iterating over the strings, as requested

languid pendant
#

so i've also tried this:

{{ trigger.entity_id | map('replace', 'input_boolean.', 'media_player.') | list }}

same result

inner mesa
#

Oh, you're iterating over the entity_id from the start...

#

Why do you want a list of one item?

languid pendant
#

media player

inner mesa
#

if you just want to replace the domain, {{ trigger.entity_id|replace('input_boolean', 'media_player') }}

languid pendant
#

long story short, its for an automation that will only involve one entity at a time

inner mesa
#

alright, if you say so

#

{{ [trigger.entity_id|replace('input_boolean', 'media_player')] }}

languid pendant
#

ahh ... brackets

#

(confused) that works?

inner mesa
#

that's what makes a list

#

identical results:

{{ ['foo']|replace('foo', 'bar') }}
{{ ['foo'|replace('foo', 'bar')] }}
#

['bar']

languid pendant
#

remember how i said that learning new languages is painful??

#

so jinja basically allows you to turn a string into an array just by adding brackets.

#

yep. makes sense to me!

#

smh

inner mesa
#

it's not turning a string into an array, it's creating a list with the only item being that string

languid pendant
#

well, true,

inner mesa
#

the string is unchanged, aside from the replace

#

there are really only two types of data structures in Jinja - lists and dicts. lists are [xxxx, yyyy] and dicts are {'foo': 'bar'}. That's pretty much it

languid pendant
#

well that would explain it then

#

devil magic.

#

got it.

wheat junco
lucid thicket
plain magnetBOT
#

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

plain magnetBOT
#

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

rose scroll
torpid mural
#

@static dune Instead of including explicit entity_id's in the template as Daniel suggest, you could create a lights group with all lights you want excluded in it, then exclude all members of that group in the template by adding |rejectattr('entity_id', 'in', expand('light.ledstrips')). Advantage is you wouldn't have to edit the template if something in your setup changes.

halcyon kindle
#

Hi All, have a question about templates being new to HA. I have a number of climate entities which I want to create a sensor entities for each. I've played in the Dev tools template part of HA and was able to return something I wanted but now curious how do I create it as an entity I can use? Is it in the configuration yaml?
This is the code I used in the template area in Developer Tools:

      friendly_name: Master Bedroom Temperature
      unit_of_measurement: 'Β°C'
      value_template: "{{ state_attr('climate.master_bedroom', 'current_temperature') }}"

guest_king_temperature:
      friendly_name: Guest King Temperature
      unit_of_measurement: 'Β°C'
      value_template: "{{ state_attr('climate.guest_king', 'current_temperature') }}"```
torpid mural
halcyon kindle
#

Thanks @torpid mural I prefer the separation route so will create a sensor.yaml!

torpid mural
halcyon kindle
#

Does this look right for the include yaml @torpid mural ?:

master_bedroom_temperature:
      friendly_name: Master Bedroom Temperature
      unit_of_measurement: 'Β°C'
      value_template: "{{ state_attr('climate.master_bedroom', 'current_temperature') }}"

platform: template
guest_king_temperature:
      friendly_name: Guest King Temperature
      unit_of_measurement: 'Β°C'
      value_template: "{{ state_attr('climate.guest_king', 'current_temperature') }}"```
torpid mural
# halcyon kindle Does this look right for the include yaml <@955115730368598026> ?: ```platform: ...

Almost. Do mind the 2 leading spaces. It behaves like you copy-pasted the contents of the sensor.yaml into the configuration.yaml at the position of the include ! statement. i.e. it would need to be indented to be under the sensor: heading. Plus, you never repeat the - platform: template, you just specify more sensors after teh sensors: heading.```

  • platform: template
    sensors:
    master_bedroom_temperature:
    friendly_name: Master Bedroom Temperature
    unit_of_measurement: 'Β°C'
    value_template: "{{ state_attr('climate.master_bedroom', 'current_temperature') }}"

    guest_king_temperature:
    friendly_name: Guest King Temperature
    unit_of_measurement: 'Β°C'
    value_template: "{{ state_attr('climate.guest_king', 'current_temperature') }}"```

#

One more tip, if you want to be able to view, edit, or show history for your new template entities from your front-end, do add a unique_id: attribute to your entities.

#

@halcyon kindle Good luck, have to go offline now.

marble jackal
torpid mural
marble jackal
torpid mural
#

Is there a way to make state_attr('light.ledstrips', 'entity_id') return an empty list when light.ledstrips doesn't exist? i.e. make the statement filter out nothing when the group doesn't exist instead of giving an error message?

#

|rejectattr('entity_id', 'in', state_attr('light.ledstrips', 'entity_id') or []) would this be a correct way of achieving it? (It works when I test it, but does it have any unwanted side effects or something like that?)

wheat junco
torpid mural
rose scroll
#

What's the formula to calculate the hypothetical compensation?

torpid mural
#

it's the sum of all compensations over time I would have received had I returned all energy generated by my solar installation into the grid. i.e. it's the running total of all price/kWh * number of kWh generated. I put the names of my sensors in the message that was turned into a text.

rose scroll
#

Is price/kWh a constant?

torpid mural
#

To mimic how the energy dashboard records costs and compensations. I would do the same for the total of hypothetical costs of my usage.

#

It is an input_number at the moment, so it may change over time.

rose scroll
#

I don't use any energy dashboard stuff in my setup, but it sounds like you want to find an integral. Have you looked into the Riemann Sum Integral integration?

torpid mural
#

Yes, I know about the Integration integration. This works only if the price is a constant a.f.a.i.k.. What I think I need is however a repetitive calculation of price * usage at time t added to any previous results. This is how the energy dashboard stores the costs and compensations for the actual energy returned to and taken from the grid. If I can get the same information for the total energy produced and total energy consumed, I can calculate the difference between those costs and compensations and it'll show me exactly when I break even plus what the gain/loss is.

torpid mural
rose scroll
#

At any point in time, you can use a template sensor to calculate price * usage, then integrate over the value of that template sensor?

#

Though again, I don't have experience with this application.

torpid mural
#

I'll have an another look. Any further suggestions are still welcome though πŸ˜‰

marble jackal
lucid thicket
#
  - platform: history_stats
    name: Yesterday AC run duration at this time
    unique_id: 0a50bbea-73f2-401a-a260-7e9576812e0a
    entity_id: binary_sensor.ac_state
    state: "on"
    type: time
    start: "{{ today_at('00:00') - timedelta(days=1) }}"
    end: "{{ now() - timedelta(days=1) }}"
mighty ledge
#

if you want yesterdays info, you'd want

    start: "{{ today_at('00:00') - timedelta(days=1) }}"
    end: "{{ today_at('00:00') }}"
lucid thicket
#

They are looking to compare the on-time of yesterday up to the current time, to today at the current time.

#

If it is 3 pm, how much longer has the AC been on today compared to the amount it was on yesterday up until 3pm yesterday

#

So that example was the yesterday sensor, but it can’t be the whole day

wheat junco
# lucid thicket They are looking to compare the on-time of yesterday up to the current time, to ...

The goal would be to look at the "final sensor" at 3PM to see if I'm using more or less cooling than the previous day for the current time. And then again at 4PM let's say or some other time period (like a 3 hour block) if each time period needs to be calculated individually. In a perfect world the sensor would show + or - the number of hours different (since the history stat sensors are in hours) between yesterday and today.

lucid thicket
#

The example I pasted would be the AC on-time from yesterday at midnight until this time yesterday.

wheat junco
#

The sensor might look like this over time if I was using more AC than the previous day:

12PM value: -0.12h
1PM value:  -0.05h
2PM value:   0.11h
3PM value:   0.23h
lucid thicket
#

Yes, you just need a history stats sensor to calculate the usage today, and then a template sensor to subtract the two. It should do exactly as you want, it will continuously calculate the difference

wheat junco
lucid thicket
#

Let’s say it is 10:15am right now. The example I pasted will give you a sensor that shows the AC on time from 0:00 yesterday until 10:15 yesterday. And 15 minutes from now, that same sensor will show the AC usage from 0:00 yesterday until 10:30 yesterday

wheat junco
#

Okay, I now see what you did there. Let me create that and play with it. Thanks for your time and help with this.

torpid mural
mighty ledge
#

because it's easier to read

torpid mural
#

ok.

thorn harness
#

@mighty ledge Thanks again for your automation. It seems to work good. I tried to update to set gas boiler on and off with two automations now. For some reason, they will be triggered, even if they should not. May you take a look at them?

#

from my understanding, i have made the condition AND and OR - it should not execute now

thorn harness
#

hm. something seems to be wrong with the changes iΒ΄ve made πŸ˜„ But i think iΒ΄ve got it. I had to multiply by -1.

#

{% if average is not none and temperature is not none and (average - temperature) * -1 >= 2 %} - that does it

inner mesa
#

you probably want abs(average - temperature) >= 2 instead

thorn harness
#

ah okay, that returns also a positive ?

#

Thank you πŸ™‚

#

but technically its same i think? just better to read?

inner mesa
#

no, yours won't work if average is larger than temperature

thorn harness
#

does that matter?

inner mesa
#

you've heard of "absolute value"?

#

do you want it to work?

thorn harness
#

because is just want to check just in one direction

inner mesa
#

ok

#

then you could have flipped the order of the subtraction

thorn harness
#

with abs it would check then in both directions for >=2 ?

#

because that i dont want

inner mesa
#

ok

#

then just flip the order of your subtraction and get rid of the * -1

thorn harness
#

ok πŸ™‚

hot dew
#

How do I reference a template I specified? I have:

  - platform: template
    sensors:
      all_lights_count:
        friendly_name: 'all_lights_count'
        icon_template: mdi:lightbulb-group
        value_template: "{{ expand('light.all_lights') | selectattr('state','eq','on') | list | count }}"

I defined the group all_lights in groups.yaml. How can I reference this template, specifically to get the count of all lights that are on?

inner mesa
#

if you defined all_lights in groups.yaml, it won't be called light.all_lights

#

it would be group.all_lights

#

what do you mean by "reference"?

#

are you asking where to put that block of text?

slate fossil
#

if you want to create a light group, you'll have to use something like light: !include lights.yaml in configuration.yaml and put your group in that yaml. Instead, you can create a Helper > Group > Light group and accomplish the same thing, but it could be more convenient when adding/removing lights from the group since you can do it through the UI instead of yaml.

inner mesa
#

or that

hot dew
#

Yeah, sorry I noticed the group.all_lights but i'm looking to then add them to a card to display the lights currently on. Specifically I'm looking to add the card:

type: custom:mushroom-chips-card
chips:
  - type: weather
    entity: weather.forecast_home
    show_conditions: true
    show_temperature: true
  - type: entity
    entity: lock.lock_frontdoor
  - type: entity
    entity: lights.all_lights
alignment: center
slate fossil
#

The group should still work though, right? It just won't have the added "light capabilities".

#

Provided your template works properly, you should now have a sensor called sensor.all_lights_count. Put that as the entity.

#

And, technically, you don't need the template sensor (unless you plan on using it for other automation purposes), but you can use a template card as the chip. I have some stuff that I can show you, but it looks like your question is more for #frontend-archived.

fringe sail
#

Hey guys. I've been trying for several days to get something going. Can somebody give me a hand? I've got some old mechanical ceiling fans. They changed speeds with the old pull chain. The only way that I could figure out how to make them smart was to use a 3 relay switch, to set relay 1 and 2 to be low, set relay 2 and 3 to be medium and all 3 relays to be high. I had to set it up like this, because this is the way the capacitors are wired to the fan motor. That all works like clockwork in my UI. The problem comes with voice control. I only have fan speeds, but not a fan as a whole. I made a fan group of the speeds, but I never figured out how to make it behave as a single fan with different speeds. If somebody could explain how to create a fan out of the speeds, maybe I could get an understanding of how to make a template fan with all of the speeds. When I try to make a template fan with presets, I don't know how to use the correct format to turn it on and off, or how to set the presets.

rose scroll
#

Something like:

variables:
  fan.fan1:
    0:
      switch.relay1: off
      switch.relay2: off
      switch.relay3: off
    1:
      switch.relay1: on
      switch relay2: on
      switch.relay3: off
    ...
rose scroll
#

The script would call switch.turn_on or switch.turn_off based on the combination of entity_id's of the fan, switch and speed. Then in the automation, you would call the script and pass it the appropriate fan, switch and speed values.

torpid socket
obtuse zephyr
#

If you share what you've tried, it'll be easier to guide you in the right direction, though

plain magnetBOT
#

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

mighty ledge
fierce hawk
#

Hi there! hope you all had a good weekend.
I am having a lamp where you can change the color. To change the color, its a MQTT message where you send a code (between 0 and 15).
I'd like to have a card to select the desired color.
I found custom:rgb-light-card completly serves purposes, and in that card you can call a service/script.

I am able to create a script to call a particular color, but instead of creating 16 scripts I'd like to create 1 script and just parses the payload value in the entity yaml?
Do you know if this is feasible?

Example, instead of having a script.blue and script.white I'd like to have a script.light and when clicking on blue i'd like to send payload '1' and clicking on white sending payload '2'

mighty ledge
fierce hawk
#

That's the color/pattern and payload code
Warm = 0
Cold = 1
Blue = 2
Lagoon = 3
Cyan = 4
Purple = 5
Magenta = 6
Pink = 7
Red = 8
Orange = 9
Green = 10
Pop = 11
Rainbow = 12
Modern = 13
Techno = 14
Horizon= 15

mighty ledge
#

and what service do you use to change the color?

fierce hawk
#

service: script.ccei_light_color
and in there I am publishing to this topic : tild_C4DEE2D4C3B0/u8_w/light_code/info/desired

mighty ledge
plain magnetBOT
#

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

mighty ledge
#
service: script.change_mqtt_color
data:
  color: green
#

it will also work via the UI

marble jackal
#

maybe just to make it a bit more fool proof, use:

#
    selected: >
      {{ colors.get(color | lower, 0) }}
#

oh, and I think the paload should be {{ selected }}, not {{ color }}

mighty ledge
#

yah, there's ways to make it better, the goal was to just have it work with a selector

#

I edited the paste, if it didn't take via the link then I'll have to post the link again

#

looks like it didn't take

marble jackal
#

that looks better!

mighty ledge
#

odd, my old link which is still open in a tab didn't push the changes trhough when I edited it an hour ago

#

oh, it does, but apparently it changes the link

#

wtf is the point of editing then....

#

-1 point for dpaste

marble jackal
#

not much, it shows the change history

mighty ledge
#

effectively making edit pointless

marble jackal
#

that other site, which changed to being paid, was better in that respect. It even had a party mode you could enable and then everybody with the link could edit it

#

but I already forgot the url

mighty ledge
#

probably one of the ad driven ones

fringe sail
fringe sail
fringe sail
#

I've created my input number with 4 settings, 0 to 3. I'm now making a script that has triggers of the input number changing to specific numbers. I gave each trigger an id, but when I try to make a choose action for the trigger id's, HA says that no triggers have id's set. I saved the script after setting the id's. Is this a bug, or is there something else I'm not doing?

fringe sail
#

I was able to do the triggered by in yaml.

mighty ledge
#

trigger id's like that can only be used in the automation that created them

#

also, you don't need input helpers, that's why I was offering to help you with the template

fringe sail
tender summit
#
  - sensor:
    - name: "Battery Charge Only"
      unique_id: "battery_charge_only"
      unit_of_measurement: "W"
      device_class: power
      state_class: measurement
      state: >-
        {% set batterypower = states('sensor.battery_charge_discharge_power') | float %}
        {% if batterypower > (0)}
          {{ batterypower * 1 }}
        {% else %}
          {{ 0 }}
        {% endif %}
#

why does my template sensor not work?

#

i want sensor.battery_charge_only to have the positive values from sensor.battery_charge_discharge_power

buoyant pine
#
{% if batterypower > (0)}

You're missing the closing % in this line

inner mesa
#

some unnecessary math in there, too πŸ™‚

buoyant pine
#

Also you should set a default for the float

#

Oh yeah I thought that was a + πŸ˜‚

mighty ledge
#

but if the value goes negative, the if isn't unnecessary

inner mesa
#

you could replace that whole block with this:

{{ [0, states('sensor.battery_charge_discharge_power')|float(0)]|max }}
tender summit
#

what do you mean with set a default for float?

inner mesa
#

like I just added

mighty ledge
#

can be reduced 1 character if...

{{ max(0, states('sensor.battery_charge_discharge_power')|float(0)) }}
thorn harness
#

Hello Petro, i actualized the automations for heater on and off. I also added some negated checks at the heater off section. All work, i cant find a problem. Bute may you take a look at it? I am not really sure, if negation (is not) is the right thing at that place.

mighty ledge
#

@buoyant pine I thought you'd laugh at that 🀣

tender summit
#

oh wow you guys are amazing. why does this work? like max(0, sensor.... does only count values until the max is reached?

mighty ledge
#

if it's negative, then 0 is higher than the negative value

tender summit
#

ah it is "take the higher value"

#

so this clears up why min also works πŸ˜›

#

i am amazed. really

#

where is this written down? is there a sheet with all "*math"

buoyant pine
#

There are some links in the channel topic

thorn harness
tender summit
#

wow also learned where the channel topic is. nice

buoyant pine
mighty ledge
thorn harness
#

You helped me with the automation for heater on πŸ™‚ i added now 3 checks - 2, 3 or 5 sensors below specified temperature. i made a second automation if 7 sensors are above specified temperature. to avoid some misleading behaviour, i copied the 3 "heater on" checks negated to heater off automation. if one of these 3 heater on are still used, then automation off should not be fired.

torpid mural
#

How can I create a list of floats out of a list of TemplateState objects so I can sum the values?

      | rejectattr('attributes.device_class', 'undefined') 
      | selectattr('attributes.device_class', 'eq', 'power') 
      | rejectattr('attributes.unit_of_measurement', 'undefined') 
      | selectattr('attributes.unit_of_measurement', 'in', ['W', 'kW'])
      | map(attribute='state')
      | list()
%}
{{ watts|sum }}```
results in "TypeError: unsupported operand type(s) for +: 'int' and 'str'" because state is of type str, but I can't find how to make it into floats...
inner mesa
#

add map('float')

#

after the existing map()

fringe sail
torpid mural
# inner mesa after the existing `map()`

Great! thank you. One final follow up question: can I conditionally divide the float value by 1000 if unit_of_measurement eq 'kW'?

      | rejectattr('attributes.device_class', 'undefined') 
      | selectattr('attributes.device_class', 'eq', 'power') 
      | rejectattr('attributes.unit_of_measurement', 'undefined') 
      | selectattr('attributes.unit_of_measurement', 'in', ['W', 'kW'])
      | rejectattr('entity_id', 'in', area_entities('energie'))
      | rejectattr('state', 'in', ['unknown', 'unavailable'])
      | map(attribute='state')
      | map('float')
      | list()
%}{{ "%.2f"|format(watts|sum) }}```
inner mesa
#

not that I can think of. I would split it up into two sets and unconditionally divide the ones in kWh

torpid mural
#

OK Thank you

inner mesa
#

you can collect the everything up to taht check in a variable to avoid repeating yourself

#

or make a macro

plain magnetBOT
#

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

inner mesa
#

you could further break some of that out to reduce repetition, but meh

rose scroll
gritty wagon
#

Trying to round to nearest 0.5 using round(1, "half", default). but automation will not safe and highlight it red in service: climate.set_temperature data: temperature: "{{ (state_attr('climate.hallway','temperature'))|float|round(1, "half", default)) }}" target: entity_id: climate.hallway

inner mesa
#

you have an extra )

gritty wagon
#

this also won't save "{{ state_attr('climate.hallway','temperature')|float|round(1, "half", default) }}" it will pass in dev tools.

inner mesa
#

you have " both inside and out

gritty wagon
#

Sorry what do you mean?

inner mesa
#

I haven't reviewed the arguments for round, but try round(1, 'half', default)

#

that

#

you can't surround the template in " and also use it inside

gritty wagon
inner mesa
#

that only has the function call. You have to consider the context in which you're using it

gritty wagon
#

Right. That make sense.

mighty ledge
wispy lodge
#

Good morning everybody.
I'm now receiving this warning several times, what's wrong?
Thanks

twin compass
#

"this warning"

wispy lodge
#
Template variable warning: 'homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'last_reset' when rendering '{{ ( as_timestamp( now() ) - as_timestamp( states.sensor.energy_tostadeira_monthly_total.attributes.last_reset ) ) | timestamp_custom("%d") }}'
#
 - platform: template
    sensors:

## Dias
      monthly_energy_cicle_days_tostadeira:
        friendly_name: 'Dias em consumo'
        unit_of_measurement: "dias"
        value_template: >-
          {{ ( as_timestamp( now() ) - as_timestamp( states.sensor.energy_tostadeira_monthly_total.attributes.last_reset ) ) | timestamp_custom("%d") }}
marsh cairn
#

Your template does not work, because there is no attribute last_reset present

wispy lodge
#

And how can I remove the warning? Because the correct value appears in HA

marble jackal
#

Most probably this occurs after a restart when the sensor is not available

marsh cairn
#

My guess would be, that this attribute is created after the first render attempts. I'd try an availability template.

 - platform: template
    sensors:

## Dias
      monthly_energy_cicle_days_tostadeira:
        friendly_name: 'Dias em consumo'
        unit_of_measurement: "dias"`
        availability_template: "{{ state_attr('sensor.energy_tostadeira_monthly_total', 'last_reset') != none }}"
        value_template: >-
          {{ ( as_timestamp( now() ) - as_timestamp(state_attr('sensor.energy_tostadeira_monthly_total', 'last_reset')) ) | timestamp_custom("%d") }}```
edit: see below
marble jackal
#

I would use state_attr()in the value template as well πŸ™‚

wispy lodge
#

I'll try it and let you know if it works.
It may be when it restarts, but sometimes it still takes a while to appear.

spark vortex
#

I have a template that creates a binary_sensor like this:
- trigger: - platform: state entity_id: binary_sensor.alarm_sensordi0006 to: "on" id: "on" - platform: state entity_id: binary_sensor.alarm_sensordi0003 to: "on" id: "on" binary_sensor: - name: bla_bla state: "{{ trigger.id }}"
instead of repeat all the platrom multiple times, can I add more entity_id in the same platform?

mighty ledge
#

You can use yaml anchors

spark vortex
#

how?

mighty ledge
#

well, if you're trying to repeat code for different sensors, then you'd use anchors

#

if you just want mutliple entity_ids in the same trigger going to that single bla_bla sensor, then you'd just list out the sensors in 1 trigger

spark vortex
#

they are already in one trigger, but in multiple "platform"

mighty ledge
#

they are in 2 separate triggers

#

in your example

spark vortex
#

in this example I have only 2, but in others I have 4/5, so I want to avoid to retrite platform 4/5 times

mighty ledge
#

right, so just list out the entities

spark vortex
#

ah, you mean the sensor that can trigger, yes then

#

list how? under entity_id: comma separated?

#

or can I add multiple entity_id in the same trigger?

marble jackal
#

what is your actual goal here

mighty ledge
marble jackal
#

you can add multiple entities in one trigger

mighty ledge
#
- platform: state
  entity_id:
  - ...1
  - ...2
marble jackal
#
- trigger:
    - platform: state
      entity_id:
        - binary_sensor.alarm_sensordi0006
        - binary_sensor.alarm_sensordi0003
      to: "on"
      id: "on"
  binary_sensor:
    - name: bla_bla
      state: "{{ trigger.id }}"
spark vortex
#

ah ok, thanks

acoustic arch
#

how can i stringify the actual entity so i can use a regex pipe on it?

spark vortex
#

they are by default in OR?

marble jackal
#

triggers are always OR

acoustic arch
#

i can use friendly_name but that regex is more hard for me to obtain hehe

mighty ledge
#

what do you mean 'stringify' the actual entity?

#

what's the goal

acoustic arch
#

print the sensor.blabla@xxx@bla so i can regex xxx

marble jackal
#

from what? you have to give more context here

acoustic arch
#

sensor.tgtg_backwerk_amersfoort_verrassingspakket

marble jackal
#

yes, that's an entity_id

mighty ledge
#

ok, that is a string πŸ˜‰

marble jackal
#

and that's already a string

acoustic arch
#

i would like to TTS the shop

#

ok brb. kids calling

mighty ledge
#

which part of it is "the shop"

marble jackal
#

as it is Dutch, my guess is he want's to have backwerk

dense swan
#

I have two set of keys and want to use a BLE tracker for each set but if one set goes away I want it to be reflected under a single entity I can use with user presence. Today I have my iPhone with the iOS companion but the ble keys are a fall back if the app stops working. Could I use a template to create a single entity to be used in the user's devices page for my user?

marble jackal
#

tgtg_{shop}_{city)_{box type}

mighty ledge
dense swan
#

Can I create a device_tracker entity using templates?

mighty ledge
#

what's a suprise package 🀣

marble jackal
#

well, shops can make boxes with stuff they can't sell otherwise, and then sell it as a surprise package
like bakery which will put 3 breads, 6 donuts, and a package of cookies in a bag and then sell it for 10 euros as a surprise package

mighty ledge
marble jackal
#

backwerk is actually a bakery

mighty ledge
#

I would assume it does create one from scratch

dense swan
#

Hmm. ok. let me try that.

mighty ledge
#

I don't know why we don't have a template device_tracker integration

#

I'd wager that this service does it?

dense swan
#

I was hoping you did but the service would create the device_tracker entity but does it "live" across restarts?

mighty ledge
#

as a sidebar, worse case you can create a template sensor that has lat/lon attributes that essentialy works like a device_tracker when paired with a person

marble jackal
#

@acoustic arch
Guess this should work {{ 'sensor.tgtg_{shop}_{city)_{box type}'.split('_')[1] }}

acoustic arch
#

im back. You can buy for a couple of euros a suprise bag worth around 15euros of stuff almost over date

dense swan
#

I am just trying to determine if at least one set of keys is gone so it triggers the automation I have of home = 0

mighty ledge
#

just plop the sensor on a person in the person UI area

acoustic arch
#

backwerk is the shop yes

acoustic arch
dense swan
#

@mighty ledge that works but if one set is home and one is gone it sets the user home. I was tired of swapping BLE track across keys so got a second one.

acoustic arch
#

example:
{{ "sensor.tgtg_boni_amersfoort_magic_box" | regex_findall_index('(?<=\_)(.*?)(?=\_)') }}

#

but the first part would be the trigger_entity name? havent looked at it yet

marble jackal
#

yes, if you trigger on that sensor changing state, you can get that from the trigger variables

acoustic arch
#

thats great to hear. a lead to the solution

#

im farming the forum, regex sites and you guys atm lol

marble jackal
#

But your regex thing returns the same as my split solution

mighty ledge
#

not sure why you need regex at all tbh

#

split and remove what you don't want and then combine using spaces

#

it'll be faster than regex

acoustic arch
#

thats where my lack of coding kicks in....

#

but you guys are great help

marble jackal
#

Well, I provided something, which you dismissed as mmmm. not sure how this works.

#

but it splits the entity_id on the _ and then takes the 2nd part

acoustic arch
#

because im not sure how to proceed with that solution in an automation

marble jackal
#

the same as with your regex solution

mighty ledge
#

post the automation...

acoustic arch
#

it doesnt exist yet

marble jackal
#

take the entity_id from the trigger

#

{{ trigger.entity_id.split('_')[1] }}

acoustic arch
#

i only have the non TTS version going. But once home i want the TTS version. Saves me picking up the phone because it makes a sound πŸ˜‰

marble jackal
#

it does become a bit more complicated if the shop has more than one word though

mighty ledge
#

or if the trigger doesn't have the entity_id key

marble jackal
#

like bakery on the corner

mighty ledge
#

bakkerij op de hoek

acoustic arch
#

friendly_name: TGTG Bakkerij Groenendijk - Euterpeplein, Amersfoort (Verrassingspakket)

#

like this one

#

remove TGTG, select until -

mighty ledge
#

that would be easier to regex.

#

do they all start with TGTG?

acoustic arch
#

yes

marble jackal
#

It's the name of the app (Too Good To Go)

acoustic arch
#

TooGoodToGo

mighty ledge
#

if you use the friendly name regex_findall("TGTG ([a-zA-Z ]+) - ")

#

or

#

regex_findall("TGTG (.*) - ")

marble jackal
#

both seem to work (I have the same integration installed)

mighty ledge
#

Yeah, the .* is like a "greedy find everything"

#

so it's saying find everything between TGTG and -

#

the [a-zA-Z ] will only find letters and spaces, so it might not work if you have those fancy letters in your names of things

#

the result of the findall will be the name

#
{{ "TGTG Bakkerij Groenendijk - Euterpeplein, Amersfoort (Verrassingspakket)" | regex_findall("TGTG (.*) - ") | first | default }}
marble jackal
#

So assuming you are using a state trigger @acoustic arch you can use trigger.to_state.attributes.friendly_name | regex_findall("TGTG (.*) - ")

#

maybe even trigger.to_state.name | regex_findall("TGTG (.*) - ")

mighty ledge
#

yeah for sure

#

well, you'd want the | first | default

#

findall returns a list

acoustic arch
#

{{state_attr('sensor.tgtg_bakkerij_groenendijk_euterpeplein_amersfoort_brood_box', 'friendly_name') | regex_findall("TGTG (.*) - ")}}
this gives me ['Bakkerij Groenendijk']

#

and {{ state_attr('sensor.tgtg_bakkerij_groenendijk_euterpeplein_amersfoort_brood_box', 'friendly_name') | regex_findall("TGTG (.*) - ") | first | default }} gives me Bakkerij Groenendijk

#

so without ['']

#

which for TTS is what i want

acoustic arch
#

i think i have all the pieces to make this TTS automation work

#

thanks a lot. you guys are gold

#

im gonna try building the TTS automation

plain magnetBOT
#

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

mighty ledge
#

@sudden wraith @marble jackal created a macro that does those calculations for you if you're interested.

marble jackal
#

It can do a lot more than just return the cheapest hour. If your dishwasher has a 3 hour program for example, it can find the cheapest consecutive block of 3 hours.
And if you have a power sensor, you can even find the best start time based on the power usage of a previous run.

sudden wraith
#

Oh, that's exactly the thing I wanted.

marble jackal
sudden wraith
#

I was just experimenting with cheapest hour first because I don't know jinja at all.

#

Sounds like we think alike, because next step for me was to measure power draw to see when it makes the most sense. πŸ˜„

#

You just made my life a lot easier πŸ˜„

winged hare
#

Anyone have the template for 'tomorrow' ? eg 2023-09-27

mighty ledge
#

(now() + timedelta(days=1)).date()

winged hare
#

thanks πŸ™‚

karmic sapphire
#

im having a hard time implimenting a conditional statement to this template sensor, what am I missing?

plain magnetBOT
#

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

inner mesa
#

conditions aren't supported there

haughty breach
#

That's not a thing... add the condition to the template

      attributes:
        changes: >
          {% set current = this.attributes.get('changes', {}) %}
          {% if is_states('input_boolean.server_boot_complete'. 'on') %}
          {% set new = {trigger.entity_id: trigger.to_state.last_changed.isoformat()} %}
          {{ dict(current, **new) }}
          {% else %}{{ current }}{% endif %}
inner mesa
#

I've had a feature request open for that for quite a while

karmic sapphire
#

ah thank you!

mighty ledge
#

No clue if it stops the state from updating, been on my list to look at

#

I woudl assume it does

inner mesa
#

not supported there, where they had it

mighty ledge
#

ya ya ya, but it's supported in action

#

"supported"

inner mesa
#

and this part is a critical piece:

No clue if it stops the state from updating, been on my list to look at

mighty ledge
#

Yes it is

inner mesa
#

I wouldn't expect a condition failing in the action to stop the state from being updated, just to stop execution of further steps in the action

mighty ledge
#

πŸ€·β€β™‚οΈ I think of it in terms of returned data from service calls

#

no returned data, it wouldn't update

inner mesa
#

depends on the intention of the OP for that condition

mighty ledge
#

alanporter would know better, he made the change

inner mesa
#

the way the docs read, it sounds like you're just providing data that you can use in the state, but it doesn't have any direct effect on the state

#

action list (optional)
Define actions to be executed when the trigger fires. Optional. Variables set by the action script are available when evaluating entity templates. This can be used to interact with anything via services, in particular services with response data. See action documentation.

mighty ledge
#

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

haughty breach
#

I think TheFes tested conditons in the action block during beta, but they had no effect on the sensor update...

mighty ledge
#

@marble jackal ^?

#

You could grab the state from the current sensor without it being a circular reference.

#

and essentially treat it like "no update"

haughty breach
thorn harness
#

good evening. i have a shot question for which i didnt find an answer: if i have a numeric state at an automation set to below 17. what will happen if outside temperature goes to -1?

#
  • condition: numeric_state
    entity_id: sensor.outdoor_temperature
    below: 17
#

or does this better work?

#
  • condition: numeric_state
    entity_id: sensor.outdoor_temperature
    above: -20
    below: 17
haughty breach
thorn harness
#

ok πŸ™‚

marble jackal
#

@haughty breach @mighty ledge the condition in that example had an effect on the state, as I was setting a variable used in the state template after the condition. But the state template was rendered on each trigger

mighty ledge
#

Oh you just posted that 🀣

#

I just got back from a meeting and though you posted that an hour ago

marble jackal
#

No, I didn't notice your ping before

#

Was translating some intents to Dutch πŸ™‚

#

But I also tested if variables from the action part could be used in the availability template during the beta

#

That wasn't the case then, but it was changed somewhere after my tests

buoyant pine
marsh cairn
#

No, Dutch

marble jackal
silent grove
#

Hello

#

I'm struggling a little bit with a template from a multiscrape output.

#

Any chance of getting some help?

#

I'm managed to get the data and to truncate it, but now the value I want is at the end of my string....and the quesiton is how do I extract that.....?

#

Long story short - I get a blob from a multiscrape fetch....and then I do this to it:

#

value_template: '{{ value.split(","conditions":")[0]}}'

#

Which gives me this:

#

What I want is the "14478" off the end.....but...this can be any number so it is not fixed length....I must basically take everything from the right up to, but not including the ":"

#

This seems like a simple problem but I am a little stumped.

#

😦

inner mesa
#

it looks like you're trying to manually parse JSON πŸ™‚

silent grove
#

Indeed I think so....

#

But probably doing it badly

inner mesa
#

I don't know what the %7D and %7B are there, but you should try {{ value_json.brightness }}

#

oh, I see - that's { }

#

what a mess.

silent grove
#

That seems simple.....

inner mesa
#

it looks like it's URL-encoded JSON

silent grove
#

How do I formnat that into value_template: ?

inner mesa
#

like I showed you

inner mesa
#

ok, that's a giant block of JSON

silent grove
#

value_template: '{{ value_json.brightness }}'

inner mesa
#

I'll need to get back to it

#

or perhaps you can figure it out with that guidance

silent grove
#

Yes...it is mega ugly.....

inner mesa
#

you just need to pretty-print the JSON (any online formatter can do it) and it will be more clear

silent grove
#

So if I do it simple as above, the log gives me:

#

Template variable error: 'value_json' is undefined when rendering '{{ value_json.brightness }}'

jagged obsidian
#

You need to set value_json with your JSON at the beginning of template

silent grove
#

OK...conceptually yes - tell it you have json, then tell it to parse and extract the tag value i want

#

This is my multipscrape yaml:

#
- name: Tempest Scraper
  resource: https://swd.weatherflow.com/swd/rest/better_forecast?callback=jQuery22409170868888429933_1695760092404&api_key=a8f5dbda-af0a-4b57-99b9-f10baa88f27b&build=76&lat=-41.17002&lon=174.83538&station_id=34978&units_temp=c&units_wind=kph&units_pressure=hpa&units_distance=km&units_precip=mm&units_other=metric&units_direction=kph&_=1695760092405
  scan_interval: 120
  log_response: true
  timeout: 20
  sensor:
    - unique_id: public_light_level
      name: 'Public Light Level (lux)'
      #state_class: measurement
      value_template: "{{ value_json.brightness }}"
      #unit_of_measurement: 'lux'
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.

jagged obsidian
#

Maybe that custom component doesn't accept value_json but just value

silent grove
#

Maybe....using value on it's own doesn't work (Template variable warning: 'str object' has no attribute 'brightness' when rendering '{{ value.brightness }}')

#

Hmmm....maybe harder.....

#

They seem to have a multiscrape section and then some sort of extra sensor section...thought it is unclear to me how these releate to each other....

#

It's not proper json.....I can't even prettify it....it's actually multiple bits smushed together.....

#

So on that basis a simnple json_value will not work.....so back to text extracttion.....

#

So sad....

rose scroll
#

Why not split the string again on : then index the last item [-1]?

silent grove
#
value_template: '{{ value.split(",\"conditions\":")[0].split(":")[-1]}}'
#

That worked!

#

I'm so excited I just about wet myself!

rose scroll
#

Sometimes string manipulation is just simpler πŸ˜‰

silent grove
#

Yes!

#

I'm so stoked! At least I can stop my lights from going bananas now.....

#

Now I need to find a few more data sources, and then aggregate them somehow...but that's a separate problem!

rose scroll
#

Just be aware that if for some reason the format of your result doesn't remain consistent (eg. If ,"conditions": somehow appears before :14478 sometimes), the above would not work.

compact rune
#

that callback is for jsonp (https://en.wikipedia.org/wiki/JSONP) which luckily isn't used much anymore but some stuff still supports it. Luckily, that API supports not using it, which should make your life easier πŸ™‚

lucid thicket
#
  - name: Tempest Scraper
    resource: https://swd.weatherflow.com/swd/rest/better_forecast?api_key=a8f5dbda-af0a-4b57-99b9-f10baa88f27b&build=76&lat=-41.17002&lon=174.83538&station_id=34978&units_temp=c&units_wind=kph&units_pressure=hpa&units_distance=km&units_precip=mm&units_other=metric&units_direction=kph&_=1695760092405
    scan_interval: 120
    log_response: true
    timeout: 20
    sensor:
      - unique_id: public_light_level
        name: 'Public Light Level (lux)'
        state_class: measurement
        value_template: "{{ value_json.current_conditions.brightness }}"
        unit_of_measurement: 'lux'
rose scroll
silent grove
#

Thsanks for your help everyone - much appreciated!

compact rune
fringe sail
lofty mason
fringe sail
#

it's supposed to be that. Did you notice the 2nd template?

pearl bough
fringe sail
#

Oh damn! I must be really tired!

#

I looked at that for several minutes and didn't see it...smh

cyan saffron
#

Hi all... I have an MQTT binary sensor that needs to get its state from two different MQTT topics, is this possible? Thanks πŸ™‚

mighty ledge
#

make a template sensor from 2 mqtt sensors

cyan saffron
#

thanks for the reply... so the template sensor can get its state from multiple MQTT binary sensors?

mighty ledge
#

yes

#

you can even make a binary_sensor group

#

without needing a template binary_sensor

cyan saffron
#

ah, ok... I did see something about binary_sensor group when I was searching for an answer, I will check into that, thanks

tribal drift
#

Hi folks, I see we can now do templates in UI and I was wondering if to set an attributed for a sensor using templates in UI is done with Jinja2 ?
I'm looking to move this:

template:
  - sensor:
    - name: yellow_bin_days
      state: >-
        {{ min(((state_attr('calendar.recycling_collection','start_time') | as_timestamp - today_at('00:00') | as_timestamp) /86400) | int,2) }}
      attributes:
        days: >-
          {{ ((state_attr('calendar.recycling_collection','start_time') | as_timestamp - today_at('00:00') | as_timestamp) /86400) | int}}
haughty breach
#

No, attributes cannot be set up using the UI.

tribal drift
#

I just read the changelog. My bad, should have read the fking manual properly πŸ˜„

Other more advanced fields, like attributes, are unavailable from the UI. You will still have to set those up in YAML.

sacred sparrow
#

I can't seem to get the attribute to work:

    - platform: state
      entity_id: sensor.home_switch_action
      not_from:
        - unavailable
        - unknown
        - none
        - ""
  sensor:
    - name: Home Switch
      icon: hue:button
      state: >
        {% set action = states('sensor.home_switch_action') %}
        {{ trigger.from_state.state if action == "" else action  }}
      attributes:
        last_triggered: '{{ trigger.event.time_fired }}'```
#

is there a way to show the last triggered as the last time the state changed but not_from: unavailable, unknown, none and ""

#

as there is no 'time_fired' for the sensor sensor.home_switch_action

lofty mason
#

is last_triggered: '{{ now() }}' what you're looking for?

sacred sparrow
#

I think it is! thank you πŸ™‚

unborn minnow
#

I'm trying to build a url_path for a tap_action on a config-template-card, but seem to be running into a wall. The syntax

http://example.com:9925/recipe/{{ states('sensor.mealie_todays_meal').lower()|replace(' ','-') }}

is working for me in a markdown card, but when I try to move it over to the url_path in the config-template-card it chokes and rather than going to the intended site, it opens the same dashboard in HA with that URL appended and without resolving the value of sensor.mealie_todays_meal.

Can anybody point me in the right direction? I've been beating my head against this for a day or so and just haven't had any luck.

rose scroll
unborn minnow
#

Thanks @rose scroll XD

rose scroll
#

Haha...but you're not far from making it work! Just need some translating to JS.

unborn minnow
#

lol that's easier said than done for me, but at least I have a basis for google-fu

rose scroll
#

Or if you like Jinja, just set up a template sensor that takes that template as it's state and then reference that template sensor's state in your custom template card.

#

That'll allow you to render the url in Jinja and use minimal JS.

north locust
#

hmm trying to convert bytes to Gb

{{ ((float(states('sensor.routerdevice_b_received')) / 1000000000) | round(2)) }}

gives a very low value of 0.09 while it should be more near 4 GB ?

whole pecan
#

Hello everyone, i'm veeery new to HA, i'm using AirCon extension to control an air conditioner, and some of the AC commands are not available in the HA UI, like "quiet mode", the extension and HA are using MQTT, how can I customise the HA UI to integrate additional functions ? i tried adding a custom climate section to the configuration.yaml with the same name as the device but it creates a second device...hiiints ? TY

jagged obsidian
#

what is the AirCon extension?

whole pecan
#

deiger/aircon on github

jagged obsidian
#

since quiet mode isn't part of the mqtt climate entity its best to incorporate it as an additional switch under the same device

whole pecan
#

Can you please point me to some yaml doing something similar ? I can code but I’m very unfamiliar with this environment

mighty ledge
whole pecan
#

i looked at the py that "talks" with the AC, i know which mqtt message it expects

bold stirrup
#

Hi all. I have a problem since the last update 2023.9.3 in one of my template. I have the follwing error "state_attr is not defined". Do you have the same problem ? Below the code which was working before :
let input = states[variables.retain] === undefined || states[variables.retain].state === 'unavailable' ? time(Date.now() - Date.parse(state_attr[script.set_values_when_chlrore_pressed].last_triggered)) : time(Date.now() - Date.parse(states[variables.retain].state)), unit = ' '; return circle(state, input, unit);

mighty ledge
#

t_fan_mute

#

I think it's up to you to figure out what topic it goes to as the docs don't cover it

#

oh nm, they are listed shittily in those docs

#

{mqtt_topic}/{property_name}/command

#

{mqtt_topic}/{property_name}/status

#

So you should be able to make an MQTT switch out of that

jagged obsidian
#

weird that it doesnt get discovered already since its supported by the script

mighty ledge
#

I didn't look but I would expect it to be automatically made into a switch, so yeah it is weird

north locust
#

how do i add a series of input numbers, have a piece of yaml 5 input number fields

mighty ledge
#

it's basically an on/off toggle

north locust
#

can i add it in yaml

mighty ledge
#

what custom card is that?

bold stirrup
bold stirrup
#

So I will get the value before the JS template

mighty ledge
#

custom button card has never had state_attr

#

unless that's something new in the 4.0 version

#

attributes are accessed states['entity_id'].attributes.<attribute>

bold stirrup
#

well in the custom button card I check the attribute of an input select

#

- type: custom:button-card entity: input_select.chlore_state name: Chlore triggers_update: input_select.chlore_state template: - base_task - icon_pool - circle

mighty ledge
#

tehre's alot of other issues i'm noticing with that template as well

#

Are you sure the script just alwasy did the 'else' statement in that?

#

JS will not resolve code in if statements if it doesn't go that path

#

meaning you can have syntax errors and it won't know until it runs that 'limb'

bold stirrup
#

I see. Ok I will use a different method to input the correct value in my JS template

mighty ledge
#
                let input = states[variables.retain] === undefined || states[variables.retain].state === 'unavailable'
                        ? time(Date.now() - Date.parse(states['script.set_values_when_chlrore_pressed'].attributes.last_triggered))
                        : time(Date.now() - Date.parse(states[variables.retain].state)),
                    unit = ' ';
                return circle(state, input, unit);
bold stirrup
#

It works. Thx a lot

north locust
#

no got it, wanted to add a few input_numbers , can be done in configuration.yaml ty

#

copy / paste πŸ˜›

north locust
#

kib/sec to gb = / 1000000000

arctic field
#

I'm trying to save a video as part of an automation. If I check my logs I get a "Can't write motion_detect_video/garage1.mp4, no access to path!" error. Any ideas? Doing a google there seems to be some very old information about whitelisting directories but I can't see where to put this in the configuration.yaml file.

arctic field
mighty ledge
marble cave
#

Hello, is there any way to create a log list of who closed or opened the garage door and when? I currently have a template created in homeassistant that turns on the relay in half a second to open the gate. Unfortunately, when I enter the gate entity created in the template, it does not show me who opened or closed it. And I write that the gate was opened by state 1...

autumn inlet
#

Hello, I was wondering it is possible to have a template that if the Value is above 1.00 for 5 min, then it becomes True? below what I have so far
{{ states('sensor.pressure_1')|float > 1.00 or states('sensor.pressure_2')|float > 1.00 }}

inner mesa
#

<was about to say...>

#

I would create a trigger-based template binary_sensor for each with a numeric_state state trigger and a for: "00:05:00 block

#

then use the states of those template binary_sensors

autumn inlet
#

Thanks @inner mesa I will give it a go

inner mesa
#

even easier:

#
template:
  - binary_sensor:
      - name: "Pressure 1 High"
        state: "{{ states('sensor.pressure_1')|float > 1.00 }}"
        delay_on: "00:05:00"
      - name: "Pressure 2 High"
        state: "{{ states('sensor.pressure_2')|float > 1.00 }}"
        delay_on: "00:05"00"
lucid thicket
#

is there a preferred way to set a template sensor as "unknown" ?

jagged obsidian
#

via a template preferably

lucid thicket
#

yes I meant what do I set it to

marsh cairn
#

Do you really mean unknown or unavailable?

lucid thicket
#

I specifically want unknown rather than unavailable

jagged obsidian
#

You can set it to whatever you want to if the sensor class allows

lucid thicket
#

this would be for a temperature device class

jagged obsidian
#

then no

#

you can only render none

lucid thicket
#

perfect, that works. I set it to render to none and dev tools > states is now showing it as unknown

#

thank you

autumn inlet
# inner mesa ``` template: - binary_sensor: - name: "Pressure 1 High" state: ...

I only just saw this ( Thanks RobC), in the mean time I came up with this as I wanted in one Sensor overall
{{ states('sensor.pressure_1')|float > 1.00 delay_on: "00:02:00" }} or {{ states('sensor.pressure_2')|float > 1.00 delay_on: "00:02:00" }}

Getting >> TemplateSyntaxError: expected token 'end of print statement', got 'delay_on'

might just have to stick with what you come up with @inner mesa

inner mesa
#

yeah, that's quite the mishmash of stuff

lucid thicket
winged hare
#

When 2023.9 dropped, I created a Template binary sensor - It works but I don't seem to be able to find a way to actually view the template I used. Any ideas ?

jagged obsidian
#

created it in the UI?

winged hare
#

yes

jagged obsidian
winged hare
#

yes. thats where I created it but how do I view the template I created it with ?

jagged obsidian
#

you want to change/view the template you used for that sensor?

winged hare
#

yes, just view at this point

winged hare
#

perfect, thats what I was looking for - thanks

jagged obsidian
#

you can also click the cog icon and go to template options

winged hare
#

ah yeah, i see it now. I think my initial problem was that the helper I first looked at wasn't actually based on a template πŸ˜‚ user error !

jagged obsidian
#

That would make things difficult

winged hare
#

In my defence <grin> I'd created an automation (which did include a template) which toggled a binary sensor (and that's the helper I was trying to understand)

silent vector
#

Any idea what's happening here. I'm getting this API response which means somehow the template is in the rest string this worked until now with a different end point but same template
{'message': 'Invalid stack identifier route variable', 'details': 'strconv.Atoi: parsing "{{ states.sensor.portainer_stack_list.attributes[\'data\'] | select(\'search\',\'zwave\') | map(attribute=\'id\') | first }}": invalid syntax'}

rest sensor resource

https://192.168.4.46:9443/api/stacks/{{ states.sensor.portainer_stack_list.attributes['data'] | select('search','zwave') | map(attribute='id') | first }}/images_status"
#

I guess somehow I have been using resource with a template but I actually should have been using resource_template. Fixed my issue.

plain magnetBOT
mighty ledge
#

@solemn ore expand "expands" groups into their grouped entities.

solemn ore
marble jackal
#

You can avoid using expand
{{ area_entities('your area') | select('is_state', 'on') | select('search', '^light.') | list }}
That should include the group as well

solemn ore
plain magnetBOT
#

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

sacred sparrow
#

this sensor used to work but the last 2 days it has been showing 'unknown'

rose scroll
#

What is making sensor.outside_home_feels_like_temperature go to unknown?

sacred sparrow
#

no idea - it hasn't gone unknown - it just went to that when restarting HA

#

its it because states('sensor.outside_min_temp') | is_number isnt a number?

languid pendant
#

@sacred sparrow -- is not a number is a float?

plain magnetBOT
#

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

obtuse zephyr
languid pendant
#

I dont think need to define a default; it should pass the variable regardless

languid pendant
#

even with the variable declared and a default given, the error is still the same

obtuse zephyr
languid pendant
#

I dont think I worded it correctly; the variable, 'ac_alarm' needs to be sent to the script with data: variables: ac_alarm: 'this is the variable' ... then the script uses that ac_alarm variable content ... the problem is that the script reports that the variable has not been defined, when it is.

#

specific err is : Template variable warning: 'ac_alarm' is undefined when rendering '{{ ['media_player.'~ac_alarm~'_kodi_mini'] }}

#

so the script isnt accepting the variable, even though it was presented

obtuse zephyr
#

I'm saying that it should be called like this

service: script.ac_on
data:
  ac_alarm: room
languid pendant
#

hrm

#

strange. it works, but im not sure i understand why. I have another script that works, that I put variables: xxx: yyy in and it still works

#

but this one is not

#

inconsistent... head scratcher

#

thanks though

lucid thicket
languid pendant
#

strangely enough, I dont, which is why I was having a hard time

lucid thicket
#

If it is inside the script, you define variables with the variables: block. If you call a script via a service, you pass variables into that script with the data: block

analog mulch
#

hi. what's the right way to test if the sun is below the horizon and it's at some point between the sunset and 3 am, i.e. I want the template to reject the morning times of darkness. Is there an easy way to achieve this?

marble jackal
#

There is no easy way to retrieve the previous sunset, but you could check if the sun is below the horizon and if it's like between 15:00 and 03:00

#

Which can be done with two separate conditions without the need for templates

analog mulch
#

My real trigger is more complicated so I'd rather have a template if poss -- my problem right now that if I test now()<today_at("3:00") it doesn't do the evening

marble jackal
#

With a template it would be something like
{{ is_state('sun.sun', 'below_horizon') and not today_at('03:00') < now() < today_at('15:00') }}

analog mulch
#

aha negating -- that's smart instead of going crazy with ors

marble jackal
#

Not so crazy

#

{{ is_state('sun.sun', 'below_horizon') and (now() < today_at('03:00') or now() > today_at('15:00')) }}

silent vector
#

Is there a more efficient way of getting the friendly name of a bunch of sensors than this

{{ expand(states.sensor) | select('search','stack_image_status')  | selectattr('state','eq','outdated') | list }}

Also from that how would I get the friendly name when the template output is this
https://dpaste.org/tYAWy

summer salmon
#

having some trouble ...trying to do this simple equation (| x - y |) / ((x - y) / 2)) * 100
where x is sensor.x and y is sensor.y
any help is appreciated

inner mesa
#

what did you try?

summer salmon
#

im getting nothing πŸ˜‚ i think the ( ) is making me confused

inner mesa
#

tried nothing?

summer salmon
#

yes ive tried just putting the sensor data there but im not sure if using int or float is the way to go? im far from an expert at this πŸ₯Ί

autumn flower
#

What is that supposed to do, exactly? Because to me it looks like that's going to result in

  • divide-by-zero error if x==y
  • -200 if x<y
  • 200 if x>y
summer salmon
#

trying to do % difference between sensor.x and sensor.y

autumn flower
#

And - looking at the || which I assume you're shorthanding abs() as - you don't care which is higher?

marble jackal
marble jackal
upper mulch
#

Hi πŸ‘‹! Is there a bitwise right shift or some equivalent to struct.pack available in Jinja?

rose scroll
#

I've never heard of a bitwise right shift operation before...interesting concept. What are you using it for?

compact rune
upper mulch
#

Thanks! @rose scroll I want to deconstruct an integer to have a list of bytes (integers 0-255 in this case). So eg. [(num & 0xffff) >> 8, num & 0xff]

merry furnace
#

Goodmorning, I'm struggling with adding a template in the service part of an automation.
In the first part of the automation I write entries into an input_text with a template, which works well.
Then I try to call a service input_boolean.turn_on, but only when the input_text is filled.

        {% if is_state('input_text.battery_notification_text', '') %}
          input_boolean.turn_off
            target:
              entity_id: input_boolean.battery_notification
        {% else %}
          input_boolean.turn_on
            target:
              entity_id: input_boolean.battery_notification
        {% endif %}```
I tried different spacings but to no avail yet. 
Is this use within this service not allowed perhaps?
-- edit -- just changed it to service_template, but still an error stating Template rendered invalid service
marble jackal
#

You should only template the service call itself, not the service data

merry furnace
#

Ha. Thanks for answering, I was just going to try that.

marble jackal
#

And service_template has been depreciated for years now, you can just use service

merry furnace
#
        {% if is_state('input_text.battery_notification_text', '') %}
          input_boolean.turn_off
        {% else %}
          input_boolean.turn_on
        {% endif %}
          target:
            entity_id: input_boolean.battery_notification```
merry furnace
marble jackal
#

Indentation looks off, target: should be indented the same as service:

merry furnace
#

Yes that works! Thanks a lot. Have been struggling for a few hours now.

slate fossil
#

Is it possible to create a timer entity that sets its duration based on the state of an input_number?

#

The docs say:yaml timer: test: duration: "00:00:30" so I'm wondering if something like this will work: yaml timer: test: duration: '{{states.input_number.test.state | int }}'

#

The goal is to be able to adjust the duration of the timer via the frontend but be able to use a slider.

languid pendant
#

alternatively, you can

duration: >
  {{states(input_number.test) | int }}
haughty breach
slate fossil
#

Unfortunately, duration wants to be in "HH:MM" or "HH:MM:SS" format. Trying this but not working yaml {{ "'00:" + states("input_number.test_timer_duration") + "'" }}

lofty mason
#

I don't think that is templatable at all.

haughty breach
#

Currently, you can alter duration via script with a templated value after the entity is set up.

languid pendant
#

@haughty breach you can also specify a digit. It does not 'have' to be in that format. 00:01:00 -or- 60

haughty breach
#

Yes, I said above you can use an integer...

#

for seconds

#

IIRC the configured duration will set the max for what you can set it to via script

slate fossil
languid pendant
#

@slate fossil -- youre not templating that correctly. use

{{ states('input_number.test_timer_duration')|int }}
lofty mason
#

That is a valid form of template

languid pendant
#

single quotes.

lofty mason
#

states.foo.state gives you the same as states("foo") , with some subtle differences. the latter is encouraged, but the former is not incorrect.

slate fossil
languid pendant
#

@slate fossil

  duration:
    minutes: >-
      {{ states(trigger.entity_id | replace('input_boolean.','input_number.'))|int }}

this is taken directly from one of my automations.

slate fossil
#

That's an automation. I'm trying to make an entity.

#

Probably safe to say duration is not templatable for the entity. This yaml timer: test_timer: duration: > {{'00:01'}} name: "Test Timer" icon: mdi:timer restore: truereturns Invalid config for [timer]: offset {{ '00:01' }} should be format 'HH:MM', 'HH:MM:SS' or 'HH:MM:SS.F' for dictionary value @ data['timer']['test_timer']['duration']. Got "{{'00:01'}}\n".

languid pendant
#

oh. youre putting it in a config? yeah I dont think you can template config yaml at all

slate fossil
#

perhaps not as a timer:, but I wonder if I can put it in template: with a trigger / platform: state πŸ€”

languid pendant
#

which, to be honest -- is unfortunate. I'd love to be able to template my configs for my alarm clock package. have it dynamically create the entities based on helper memberships

slate fossil
#

Yeah. That's kind of what I'm trying to go for.

languid pendant
#

I get it. I've searched high and low. The only way I found a way to get it that way is to make a 'template' and put it in the templater in dev tools to make it spit out the yaml

#

if you can figure out the template: idea, please share. I'd buy you a beer for that one lol

lofty mason
#

that's not gonna work at all

lusty moat
slate fossil
#

I created a template: that stores the last_changed values of certain entities and it survives restarting.

marble jackal
#

You need to set the timer using a service call

slate fossil
marble jackal
#

Then you can use your template

slate fossil
#

Added duration: to timer.start in my automation. yaml service: timer.start data: duration: "{{ states.input_number.test_timer_duration.state | int(0) * 60 }}" target: entity_id: timer.automation_auto_office_lightsNow, I can use a slider to adjust the duration. The time remaining appears on the custom:button-card on my dashboard and actually counts down in real-time.#frontend-archived message

lofty mason
#

FYI I think there's some plan to eventually remove duration from timer.start

#

I don't quite understand what state that's in but it seemed contentious

slate fossil
#

I'm confused. How would the duration of a timer end up being set?

languid pendant
languid pendant
#

duration will accept seconds, minutes, hours

slate fossil
#

Yeah. I was just thinking about that figuring it would work but, I believe the default is in seconds so I just let the template do some math and save a line.

languid pendant
#

touche. yes, default is seconds. It'll even accept milliseconds. I have to use that for my announcements script

#

ope. maybe. I might be wrong. I am using -delay in the script

lofty mason
languid pendant
#

that'd be a pain IMO ... just adds more lines to stuff

slate fossil
#

Do you mean they're talking about removing the duration from the timer.start service call, and not the actual entity?

lofty mason
#

Yes, no duration in timer.start service.

languid pendant
#

I sure hope that someone has some sense and 'votes that off the island' Good Idea Fairies'... I tell ya.

languid pendant
#

ugh. this is an awful idea.

lofty mason
#

actually I can't tell. that might have been walked back or partially walked back, I can't find the thread

slate fossil
lofty mason
#

so maybe don't worry about it for now.

languid pendant
#

+1 @slate fossil ... but I'm hopin I shouldnt have to worry about it ever

#

Even still, I'd imagine a change that drastic would take years to actually come to fruition so that users would have time to accommodate

lofty mason
#

6 months is the deprecation time.

slate fossil
#

Kind of makes me wonder what would be next. Removing, for example, color_temp from light.turn_on and have to rely on a light.change service?

languid pendant
sudden wraith
#

I'm trying to wrap my head around your cheapest-energy-hours macro @marble jackal, but I'm not entirely sure how to use it. What I want is, when event happens, I want to pick the cheapest three hours before 14:00 the next day, and then have it start my device then. Are there any examples that could help with that?

marble jackal
#

That was supposed to be part of 2023.8, but has been completely reversed

lofty mason
#

Temporarily, or permanently?

marble jackal
#

Permanently

lofty mason
#

cool, thanks for the update.

languid pendant
#

Shew.