#templates-archived

1 messages Β· Page 7 of 1

waxen lynx
#

Tried the same ..bit round(3) shows like 0.123

fossil venture
#

?

#

I thought you wanted two decimals?

waxen lynx
#

Yeah i wanted two...it works now...i just tried 3 to see if it works

waxen lynx
thorny sparrow
#

It gives a default value 0

fossil venture
waxen lynx
fossil venture
#

Then 2 or 1 will be substituted if the float filter can't convert the value to a number. You can use anything you want. e.g. one of mine that ensures a known result in case of missing values: {% if states('sensor.lounge_room_temperature')|float(25) <= states('input_number.upstairs_ac_temp_set_heat')|float(21) - 2 %}

waxen lynx
fossil venture
#

Correct

waxen lynx
rancid pelican
#

hi

rancid pelican
#

can i have a timeout action inside a step of sequence?

fossil venture
rare linden
#

I gave you a rough idea of what the maths should be, i reccomend going to google and using google calculator to figure out the final equasion, once you have a number like 0.23594538 then you can apply a round to it

waxen lynx
limber haven
#

Are there any decent guides on how templates work, I've gone over the HA docs and Im not really getting it. Maybe something with smaller words and sock-puppets perhaps?

rare linden
#

come to think of it this might do the trick ((1.0 - 0.2) * (brightness / 255 + 0.2)) | round(1)

limber haven
#

Or a moralizing robot side-kick who talks about recycling or something πŸ˜›

rare linden
limber haven
#

Yeah im looking but its never great when most of them are like "Yeah you do this for some reason I dont understand".. good for specific examples of what they are doing but rather lacking in 'well I want to do something a little different' πŸ˜„

rare linden
#

yeah sadly i dont think most of the HA video makers are programmers so they don't explain things half the time

limber haven
#

Yeah, Im at the stage of "Eitehr copy and paste this automation 14 times.. or learn templating" and Im rather torn which is the lesser hell πŸ˜‰

rare linden
#

come to think of it you may want to look into jinja2 thats what templates use, but home assistant adds it's own functions and filters on top of that

silent seal
#

What are you trying to do?

#

Instead of looking for a guide try building the thing you need, or at least explaining it.

mighty ledge
#

If you don't have a mind for programming, jinja isn't going to help your problems

#

it's code, no way around it

thorny snow
#

Motion Sensor last action: Need some code to find the last action of the motion sensors. Sometimes my zigbee devices need to be repaired and it would be good to know this as soon as possible. No action longer than 12h i have to check. It happens about 8-12 weeks one.

limber haven
# silent seal Instead of looking for a guide try building the thing you need, or at least expl...

TBH what I need is to setup some automations to be 'general' in that for each remote/light in my home I can use the same codeblock again and again.. So for example this code block.. - alias: "Zigbee2MQTT Lights - Hold On to Full Brightness" trigger: - platform: state entity_id: - sensor.office_switch_action to: "on_hold" action: - service: light.turn_on data_template: entity_id: light.office_light brightness: 254 transition: 1 That ideally I could change it so entity_id works for anything called 'sensor.roomname_switch.action' and convert that into a trigger for 'light.roomname;

#

I did have something like this working with Deconz, but z2m is different enough that breaks beyond my ability to fix it

#

(So I dont need to make 9+ copies of this same automation for every single room /light combo in my home)

#

(I need an automation for every 'interaction' for the light, so 1 swithc is actually about 8 automations per room, so its going to really grow arms and legs)

#

for reference.. this is what I made/kinda lifted from the internet for Deconz πŸ˜„ ```## Turn a light On and set it to 100% if On is long-pressed

  • alias: "Hue Light Remote: Long Press On"
    trigger:
    • platform: event
      event_type: deconz_event
      event_data:
      event: 1001
      action:
    • service: light.turn_on
      data_template:
      entity_id: "light.{{ trigger.event.data.id | regex_replace(find='_switch.*', replace='', ignorecase=False) }}"
      brightness: 254
      transition: 1
    • service: input_boolean.turn_on
      data:
      entity_id: "input_boolean.{{ trigger.event.data.id | regex_replace(find='_switch.*', replace='_light_override', ignorecase=False) }}"
earnest cosmos
#

This seems easy, but I cannot find a way:
My Espressomachine needs to be switched on 30 minutes before my alarm goes off in the morning to make it preheat. How can I set the trigger for the Espresso switch to power on 30 minutes before the alarm (set by input_datetime.alarm)?

#

Was hoping this would work ...

trigger:
  - platform: time
    at:
      entity_id: input_datetime.alarm
      offset: -00:30:00

But it seems I need a template trigger. Can anyone help with an example of such a template

inner mesa
#

I don't see an input_datetime.alarm service. Assuming that your input_datetime only has a time, you can use this:
{{ today_at(states('input_datetime.date_test')) - timedelta(minutes=30) }}

marble jackal
#

For a trigger you'll need to compare that with now()

inner mesa
#

I had that in there, but I would probably just set the input_datetime each day in an automation

#

in any case, OP vanished

marble jackal
limber haven
#

If you have any opinons on my question, Im still here? πŸ˜„

mighty ledge
#

otherwise, you'd need to get in deep with templating

#

@limber haven if you post all your sensors and all your lights that you're doing using a share site, i'll take a look and see how feasible it is

#

.share @limber haven

#

apparently the bot is dead

limber haven
#

Mm, I managed to do it for Deconz wsithout too much trouble. Basically using a set naming scheme and using string replacements to format it in a way that HA would like

mighty ledge
#

#botspam message

#

that message points to the share sites

limber haven
#

Ah, well Im still porting all the lights / switches over, but they should be all "light.roomname" and "sensor.roomname_switch_action" πŸ˜„

mighty ledge
#

if it's that simple, then...

marble jackal
#

Here comes the magic

#

πŸͺ„

mighty ledge
#
- alias: "Zigbee2MQTT Lights - Hold On to Full Brightness"
  trigger:
    - platform: state
      entity_id:
        - sensor.office_switch_action
        - list
        - sensors
        - here
      to: "on_hold"
  action:
    - service: light.turn_on
      data_template:
        entity_id: light.{{ trigger.to_state.object_id.split('_')[0] }}_light
        brightness: 254
        transition: 1
#

and if your room names have multiple underscores in them, then the template would be this instead

#
- alias: "Zigbee2MQTT Lights - Hold On to Full Brightness"
  trigger:
    - platform: state
      entity_id:
        - sensor.office_switch_action
        - list
        - sensors
        - here
      to: "on_hold"
  action:
    - service: light.turn_on
      data_template:
        entity_id: light.{{ trigger.to_state.object_id.split('_')[:-2] | join('_') }}_light
        brightness: 254
        transition: 1
#

remove the _light if you don't have that on your entity_id

#

anyways, that should get you started

limber haven
#

So that is taking the trigger.. in this case the Entity_id for the switch (Which I'll have to list, I guess I cant do something similar for 'find anything that is sensor.*...

mighty ledge
#

you could, but it's more work

#

you'd need a second automation that makes a group list. But triggers are limited

#

so it's not worth the effort IMO

limber haven
#

Is there a way in HA to.. test.. what the results are for some of these templates? Like have it run it through in a simulation to give me the end result of what light.{{ trigger.to_state.object_id.split('')[:-2] | join('') }}_light does?

mighty ledge
#

in the template editor

#

you can use this

{% set trigger = {'to_state':{'object_id': 'office_switch_action'}} %}
marble jackal
#

Should have known I would be too slow on mobile

mighty ledge
#
{% set trigger = {'to_state':{'object_id': 'office_switch_action'}} %}
        entity_id: light.{{ trigger.to_state.object_id.split('_')[:-2] | join('_') }}_light
mighty ledge
#

⚑

limber haven
#

Great! OK, let me fuzt around with this and see what I can make it do.. having a easy way to test what its actually doing will make this a bit easier πŸ˜„

mighty ledge
#

returns

entity_id: light.office_room_slyboots_this_will_work_regarless_of_the_amount_of_underscores_light
marble jackal
#

Would be a silly room name though

mighty ledge
#

haha yes

#

just wanted to make sure it catches dining_room and crap like that

#

rompus_room

marble jackal
#

You could also just do | replace('_switch_action', '_light')

mighty ledge
#

yah that oo

#

many ways to skin this cat

#

not sure which one is more efficient

#

probably | replace

#

1 iteration vs potentially 3

limber haven
#

okay I see. So the split_ splits the entity_id into an array and the [x] is what calls what part of the result to use.. Neat. although once the trigger in this case be called 'sensor.... whatever?, so the result would be.. light.sensor.office_light ? Although if can do | regex_replace(find='sensor.*', replace='', ignorecase=False) I suppose?

#

Or just replace

marble jackal
#

It takes the object_id, which is the part after the .

limber haven
#

Ahh, okay.. Makes sense πŸ™‚

rare linden
#

why not do it based on the area of the entity? you can get the area of the trigger and apply that to the entity you want to set i basically do that in my automations

limber haven
#

Now the next tricky bit is for the MQTT publishes πŸ˜„

limber haven
#

Getting MQTT wasnt that bad but.. funny problem, the 'trigger' name is all lowercase, but the topic requires it to be Sentence case.. πŸ˜„ So "/light/office/set" to MQTT is differnt to /light/Office/set" still.. might be able to figure this one out πŸ˜„

#

Thank you for your help Petro, and for going that extra step to help me understand it as well πŸ™‚

rare linden
#

expand(states) | selectattr('domain', 'eq', 'light') <-- is that the correct syntax to get all lights ?

inner mesa
#

states.light

rare linden
#

assuming that replaces the whole lot?

also if I wanted to use the selectattr domain eq light i assume i can just use states and then apply selectattr as a filter? using it to create a debugging sensor to see the end results

inner mesa
#

What I suggested results in the same thing without a ton of extra processing time and memory

#

using expand() on states doesn't do anything useful, anyway

rare linden
# inner mesa What I suggested results in the same thing without a ton of extra processing tim...

the reason for the debugging sensor is i'm trying to see where this goes wrong ```

  • name: Light Living Room
    unique_id: light_living_room
    state: >-
    {% set current_values = expand(area_entities('living_room')) | selectattr('domain', 'eq', 'light') | map(attribute='attributes.brightness') | map('int') | list %}
    {% if current_values | count > 0 %}
    {{ current_values | average | int }}
    {% else %}
    {{ this.state|int(0) }}
    {% endif %}
#

so creating a debug sensor that mimiks that expand on the area entities and one that just gets all lights in the house which i wont bother with expand on

inner mesa
#

ok

rare linden
#

the above is on a template number:

inner mesa
#

I guess

rare linden
#

the above was suggested to me by petro, unless there's a better way to achieve that

#

well the expand(area_entities('kitchen')) | selectattr('state', 'eq', 'on') | map(attribute='attributes.brightness') | map('int') | list | average | int bit was

inner mesa
#

that's okay as long as they're all lights

rare linden
#

I added selectattr('domain', 'eq', 'light') to account for that but for some reason kitchen returns unknown value, i get a value for living room fine, but when the entities are reloaded it defaults to 127 so i can only assume it's getting a 0 value and a 255 value and averaging them

inner mesa
#

you'll need to debug that in devtools -> Templates

rare linden
#

Thanks, I've never noticed the really noticed template tab before, I always wondered if there was something similar to that, in the past I just created a sensor to see what the values were outputting.

inner mesa
#

it's invaluable

rare linden
#

Any idea why this doesnt work? area_entities('living_room') | map('regex_search', '^light\.') the result of area_entities does return light.living_room

#

managed to achieve desired result with | select('match', 'light.') it seems

#

and since that appears to be regex i replaced with '^light.'

#

found the select match in a random ha forum post, the jinja2 template reference was useless for that

inner mesa
#

map() applies a function or extracts a value, it doesn't filter the results

#

It's from the second link in the channel topic

rare linden
#

Can anyone see anything wrong with this? https://pastebin.com/0xAFzMeu i tested the values in state: and they were working fine, but it's showing as unavailable in developer tools

#

looks like it's the use of expand as a filter

inner mesa
#

Oh, that's a bug

#

It won't pass validation

#

I have a PR open to fix it

rare linden
#

Yep, it was that validation error, though annoyingly - name: Light Living Room unique_id: light_living_room state: > {% set light_values = expand(area_entities('living_room') | select('match', '^light\.')) | map(attribute='attributes.brightness') | map('int') | list %} {% if light_values | count < 1 %}{{ value|int(0) }}{% else %}{{ light_values | average | int }}{% endif %} still resets to 127 when the entities are reloaded rather than the current value of the living room light

rare linden
#

Think i found another bug if you do
set light_values = expand(area_entities(area_id(this.entity_id)) | select('match', '^light.'))
then do something like if light_values | list | count < 1 and try to use the value of light_values it acts as if it's been converted to a list, rather than the state it was at when it was set, also happens if you echo the value out with {{ light_values | list }} in the dev tools for example then try and use it again

i've managed to get around it, but it's annoying

inner mesa
#

The seiect() part isn't good. You should do selectattr('domain', 'eq', 'light')

#

What you have will work, it's just not optimal

marble jackal
#

Isn't the problem that lights which are off don't have the attribute brightness?

inner mesa
marble jackal
#

Switch > light lights also don't have brightness when on (and maybe other types). Wouldn't it be better to check on brightness being defined first?

fierce turret
#

Morning all. I have a question regarding yaml files. My template sensors file is growing and I’d like to split it up into multiple files if possible. I have the include line in the config file for my sensors.yaml file but when I try to create a new file and include it, it tells me sensors is a duplicate. How do i create multiple files and include them? Example:

cost_sensors.yaml
count_sensors.yaml
power_sensors.yaml

And include them all in the config.yaml?

marble jackal
#

Put them all in the folder sensor and use:
sensor: !include_dir_merge_list sensor

fierce turret
#

I'll give it a try. Thanks

fierce turret
marble jackal
#

Yes

#

If you create a folder sensor in the folder custom_files

fierce turret
silent seal
#

Did you make sure all the entries in each file are in a list?

fierce turret
#

yes, i think so

#
#=== Get Daily Cost of Tumble Dryer
#==============================
- platform: template
  sensors:
    tumble_dryer_daily_cost_total:
      unique_id: tumble_dryer_daily_cost_total
      friendly_name: "Tumble Dryer Daily Cost"
      device_class: monetary
      icon_template: mdi:currency-gbp
      unit_of_measurement: GBP
      value_template: >-
        {% set state = states('sensor.tumble_dryer_daily_energy_usage') %}
        {{ (state | float * 0.2706) | round(2) if is_number(state)}}

#==============================
#=== Get Last Month Cost of Tumble Dryer
#==============================
- platform: template
  sensors:
    tumble_dryer_last_month_cost_total:
      unique_id: tumble_dryer_last_month_cost_total
      friendly_name: "Tumble Dryer Last Month Cost"
      device_class: monetary
      icon_template: mdi:currency-gbp
      unit_of_measurement: GBP
      value_template: >-
        {% set state = state_attr('sensor.tumble_dryer_monthly_energy_usage', 'last_period') %}
        {{ (state | float * 0.2706) | round(2) if is_number(state)}}```
elder moon
#

Hi. Recently i got some awesome advice here with declaring a list of switches in a variable. I wanted to add additional functionality to that automation and i was wondering what is the best way to check if any of the switches declared in a variable are on

silent seal
#

~check

elder moon
#

a couple of days ago i've been recommended a very elegant template solution, so i would prefer to keep it tempalate only

silent seal
#

A template can easily expand a group

#

And it would save you re-declaring the same list twice in the example you linked

#

Please don't use Pastebin, since it can randomly add spaces to the main view. πŸ™‚

marble jackal
fierce turret
# marble jackal Looks okay, where did you place these files, and how did you do the include?

Location: custom_files/sensor
Include: sensor: !include_dir_merge_list custom_files/sensor
Example inside cost_sensors.yaml inside the custom_files/sensor folder:

#=== Get Daily Cost of Tumble Dryer
#==============================
- platform: template
  sensors:
    tumble_dryer_daily_cost_total:
      unique_id: tumble_dryer_daily_cost_total
      friendly_name: "Tumble Dryer Daily Cost"
      device_class: monetary
      icon_template: mdi:currency-gbp
      unit_of_measurement: GBP
      value_template: >-
        {% set state = states('sensor.tumble_dryer_daily_energy_usage') %}
        {{ (state | float * 0.2706) | round(2) if is_number(state)}}

#==============================
#=== Get Last Month Cost of Tumble Dryer
#==============================
- platform: template
  sensors:
    tumble_dryer_last_month_cost_total:
      unique_id: tumble_dryer_last_month_cost_total
      friendly_name: "Tumble Dryer Last Month Cost"
      device_class: monetary
      icon_template: mdi:currency-gbp
      unit_of_measurement: GBP
      value_template: >-
        {% set state = state_attr('sensor.tumble_dryer_monthly_energy_usage', 'last_period') %}
        {{ (state | float * 0.2706) | round(2) if is_number(state)}}```
marble jackal
#

And custom_files is in the same folder as where you configuration.yaml is?

marble jackal
#

Anything in the log? And did you reload template entities?

fierce turret
#

I dont see anything in the log. Yes, I reloaded the templates.

elder moon
#

im trying to do something like that but it doesnt work:
{{ switches | selectattr('state', 'eq', 'off') | list | count == 0 }}"

#

also tried replacing switches with expand(switches)

silent seal
#

Well that's a domain, not a group

elder moon
#

no, a variable

marble jackal
#

What's in the variable? You might need to expand it first

elder moon
#

the thing is that the list of switches will be modified in the future, if i will also create a group out of it - i will need to modify three different lists every time i add or remove a switch just for one automation

silent seal
#

You can use automations to set groups πŸ˜‰

fierce turret
marble jackal
#

No, that should not be an issue

elder moon
#

but this is that automation youve been helping me with a couple of days ago - only one switch can be on at a time

silent seal
#

How does using a group prevent that?

fierce turret
elder moon
#

ok i will try to move the list to a group

fierce turret
marble jackal
elder moon
#

so now ive created a group. With this automation, can i just replace the variable name with group name for this to work?

marble jackal
#

Well, you do need to make some changes, you'll need other templates

#

Can you share the current automation again?

elder moon
marble jackal
#

Okay, I will come back to this when I finished doing the groceries

elder moon
#

no worries, i will try to crack on with this until then

#

hmmm i think i can make it work, except i have change the trigger to the group and now the automation doesnt know which switch has actually been switched so wont get a correct trigger.entity_id for this bit:
entity_id: '{{ switches | reject(''eq'', trigger.entity_id) | list }}'

#

would it be possible to use a template trigger to expand a group and then get a trigger.entity_id later on in the action field?

earnest cosmos
elder moon
#

I got to something like this:
{% set x = expand('switch.private_office_consoles') | selectattr('state', 'eq', 'on') | sort(attribute='last_changed', reverse=true) | list %} {{ expand('switch.private_office_consoles') | reject('eq', x[0].entity_id) | list }}
but reject doesnt want to work

silent seal
#

You probably need rejectattr('state'.

elder moon
marble jackal
# elder moon https://pastebin.com/aj8AsE6i

I don't understand what you are doing with that if. The goal was to have only one of the group members on, so the others will always be off and the condition there will always be false

#

Anyway, hoe is your group called?

elder moon
#

switch.private_office_consoles

marble jackal
#

I would use this as a template trigger: {{ expand('switch.private_office_consoles') | selectattr('state', 'eq', 'on') | list | count > 1 }}

elder moon
#

so this automation should do the following:

  1. make sure that maximum one of the group members is on - if another device is switched on, switch off previous one
  2. If a particular group member is turned on - send an IR command
    those two were working in a previous version (without a group), what i wanted to add to it is:
  3. if any of the group members is on - also switch on a monitor
marble jackal
#

Okay, still not sure what you are doing with the template in the if on line 21, that will only be true if all switches are on

elder moon
#

ahh, thats the functionality i was trying to add (3) - that line may be wrong, didnt get to a point where i can test it

marble jackal
#

I assumed that, but now it checks for 0 switches being off, meaning all are on

#

Anyway, you can combine it all in one automation, but I would suggest to do it in 3 separate ones

#

Makes it all a lot easier

  1. use the trigger I suggested above, I will come back on how to determine which ones to turn off
  2. trigger on that specific member turning on
  3. trigger on the group itself turning on
#

To determine which switches to turn on for 1) you can use
{{ (expand('switch.private_office_consoles') | sort(attribute='last_changed) | map(attribute='entity_id') | list)[:-1] }}`

elder moon
#

ok, we can try that if i can use a single group to store the consoles

#

ok many thanks, i have slightly modified this:
{{ (expand('switch.private_office_consoles') | selectattr('state', 'eq','on') | sort(attribute='last_changed',reverse=true) | map(attribute='entity_id') | list)[:-1] }}
but now it works flawlessly

#

but how can i check if any member grouip is on/a particular member group is on

marble jackal
#

I already mentioned that, but to check in the particular member, just use a state trigger on that specific entity

#

And the group will be on if any member is on, so for that use a state trigger on the group turning on

#

Either use 3 separate automations or use 3 triggers in one statistics automation, add trigger ids and use choose to determine the action based on the trigger id

elder moon
#

aaaahhh right

#

one last thing, what trigger should i use for this template?
currently i made a simple
- platform: state entity_id: switch.private_office_consoles
but it only seems to trigger when the group changes its state, not when members do

marble jackal
#

Why would you want that?

marble jackal
earnest cosmos
#

What is wrong here? My automation never triggers, even though I would think the timestamp comparison would be correct.

trigger:
  - platform: template
    value_template: >-
      {% set espresso_on = today_at(states('input_datetime.alarmtid')) - timedelta(minutes=30) %}
            {{as_timestamp(now()) == as_timestamp(espresso_on) }} 
#

Here is my output

AS TIMESTAMP ESPRESSO ON: 1662290700.0
AS TIMESTAMP NOW:         1662291592.743583
```
mighty ledge
#

input_datetime.alarmtid needs to be a time only datetime

earnest cosmos
#

how?

mighty ledge
#

it's part of the configuration

elder moon
mighty ledge
#

for the datetime

#

there's 3 options, date, time or date and time

earnest cosmos
#

so converting to timestamp will not help?

mighty ledge
#

secondly, you can just use >= without the timestamps

earnest cosmos
#

I want it to triggar "at" the time set

mighty ledge
#

no, converting it to a timestamp is going to make it into those long numbers

earnest cosmos
#

and I thought it was more accurate..

mighty ledge
#

no

#

assuming it's a time only datetime, you can remove the as_timestamps

#

{{ now() == espresso_on }}

#

and if that doesn't work, because of the microseconds...

#

{{ today_at(now().time() | string) == espresso_on }}

earnest cosmos
# mighty ledge no

This is what I get:

ALARM:        2022-09-04 13:55:00+02:00
ESPRESSO_ON:  2022-09-04 13:25:00+02:00
NOW:          2022-09-04 13:43:32.857665+02:0
mighty ledge
#

right, but now() in a template resolves at the minute

#

now() in the editor resolves when you hit enter and on the minute

earnest cosmos
#

Right! I was concerned it would matter but did not fully understand it

#

Thank you @mighty ledge IΒ΄ll investigate this further using your suggestions. πŸ™‚

marble jackal
earnest cosmos
mighty ledge
#

Then don’t use that and use >= with just now()

#

You just need it to resolve from false to true

#

So you’ll only get 1 trigger with >= not multiple

earnest cosmos
#

meaning...?

#

using >= and now() evaluated OK

mighty ledge
#

Meaning you want it to trigger on the minute right? >= will do that

earnest cosmos
#

ah! got it. Testing in the automation, now.

mighty ledge
#

Aight I gotta go for a run

earnest cosmos
#

Sure thanx for helping me furhter

earnest cosmos
rare linden
#

Can you not template triggers? for example: ```trigger:

  • platform: state
    entity_id: "{{ trigger_lights + trigger_booleans + trigger_blinds + [ 'input_text.current_presence' ] }}"``` where each variable is a list of entity_ids? i get an error Message malformed: Entity {{ trigger_lights + trigger_booleans + trigger_blinds + [ 'input_text.current_presence' ] }} is neither a valid entity ID nor a valid UUID for dictionary value @ data['entity_id']
marble jackal
#

Nope, you can't use templates for the entity_id in a state trigger

rare linden
#

what about a template trigger loop through all of them and check if state has changed within the last n seconds?

marble jackal
#

You could do that

#

No need for a loop

#

{{ expand( trigger_lights + trigger_booleans + trigger_blinds + [ 'input_text.current_presence' ] ) | selectattr('last_changed', '>', now() - timedelta(seconds=10)) | list | count > 0 }}

rare linden
#

alright, thanks

#

doesn't seem to trigger

marble jackal
#

@rare linden Where are those variables defined?

rare linden
marble jackal
#

Those are limited to limited templates though

analog mulch
#

Is there an add on or something like that that would let me define a template and evaluate it on a historical state recorded in the HA database β€” to see whether my definition of a trigger works as if is supposed to etc? A sort of history tab with a function of entities instead of entity

tidal meteor
#

Hi have a question on calculation with times.

I have a couple of helpers (times) that i want to subtract from a time i set in the lovelace interface, also a helper (time)
How do i do that because i cant get input_datetime to work in templates.
I have the following helpers, the input is set to time for all the helpers

  • input_datetime.time_work_start
  • input_datetime.travel_time_work
  • input_datetime.travel_time_manual
  • input_datetime.prep_time_home

I want to do the calculation: input_datetime.time_work_start - input_datetime.travel_time_work - input_datetime.travel_time_manual - input_datetime.prep_time_home
to get my wake-up time.
I have daly different wake-up times depending on the start time and start location for work
The wake-up time will be the base for other events that precedes the actually wake-up

marble jackal
#

I assume work start is like 9:00, and the others are more like 0:45, 0:30 etc?

#

So work start is an actual time, and the others are more like time durations

mental violet
#

Is it possible to say in a way:
For i in range(0,variable_1 | length)
{% set my_array[i] = [variable_1[i], [variable_2[i] %}
End if

Everytime when I write [i] after my_array I get an error.

inner mesa
#

No, you can't change array contents like that

#

You can just build the list with mylist = mylist + [...]

#

But then you also need to use a namespace

mental violet
#

But the list variable_1 and variable_2 could be very long or very short :/

inner mesa
#

Does that matter?

#

It's exactly the same

marble jackal
# tidal meteor you assume correctly
{% set w = today_at(states('input_datetime.time_work_start')) %}
{% set tw =  states('input_datetime.travel_time_work').split(':')
{% set tm = states('input_datetime.travel_time_manual').split(':') %}
{% set pt = states('input_datetime.prep_time_home').split(':') %}
{% set h = tw[0] | int + tm[0] | int + pt[0] | int %}
{% set m = tw[1] | int + tm[1] | int + pt[1] | int %}
{{ w - timedelta(hours=h, minutes=m) }}
mental violet
inner mesa
#

but that part doesn't change

mental violet
#

But I skipped that part. Is there a away to ask:
Is this_string in my_string?

Like:
Is 'test' in 'hello this is a test'
Answer: yes
Is 'hello 'in ' hello this is a test'
Answer: yes
Is 'tree' in 'hello this is a test'
Answer: no

inner mesa
#

I'm just addressing your issue, which was that you're trying to modify an array/list based on indicies. You can't do that

#

what you wanted to assign to each list item is exactly the same

#

what is your actual question?

inner mesa
#

{{ "foo" in "foobar" }} -> true

tidal meteor
mental violet
#

I have 2 lists that each have elemnts in it. These elements are touples. They belong to each other. It is a name and a value.
So name_list[1] should be related to value_list[1] and so on.
So I wanted an array that put those 2 lists in 1 list with touples

mental violet
inner mesa
#

sounds like you really want a dict

#

this creates a dict that I think does something like what you want:

{% set list1 = ['foo', 'bar', 'blah'] %}
{% set list2 = [1, 2, 3] %}
{% set ns = namespace(mylist={}) %}
{% for i in range(0, list1|length) %}
  {% set ns.mylist = dict(ns.mylist.items(), **{list1[i]: list2[i]}) %}
{% endfor %}
{{ ns.mylist }}

->

{
  "foo": 1,
  "bar": 2,
  "blah": 3
}
#

if you really want a list of lists:

{% set list1 = ['foo', 'bar', 'blah'] %}
{% set list2 = [1, 2, 3] %}
{% set ns = namespace(mylist=[]) %}
{% for i in range(0, list1|length) %}
  {% set ns.mylist = ns.mylist + [(list1[i], list2[i])] %}
{% endfor %}
{{ ns.mylist }}
mental violet
#

I have now a problem with my Marksdown Card. I want a table (all numbers are now working)
But with that many lines of code I destroyed the table layout.
I tryed now all possibilities of {%- and -%}
I do not really know what they do the minusses for and after the {%

inner mesa
#

They remove whitespace

elder moon
#

@marble jackal seems to work perfectly. Thank you very much for your help and patience!

#

at the end of the day i have done two automations, one for switching and ir blast - managed to do both with one trigger and the other one for the monitor

marble jackal
#

πŸ‘πŸΌ

mental violet
#
{% set this_month_tally = [1,2,3] %}  
{% set this_month_tally_name = ['test1', 'test2', 'test3'] %} 
{%- if this_month_tally|length == this_month_tally_name|length -%}
{%- set endvalue = 0  -%}
|Ausgabe| &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; | EUR  |
|:--------------------|---|:-:|
{%- for i in range(0,this_month_tally|length) -%}
{%- set name = this_month_tally_name[i].replace(' GmbH','').replace(' Ltd','').replace(' Germany','').replace(' & Co.','').replace('.com','').replace('.de','').replace('B.V.','').replace('Payments','') -%}
{%- set filtername = states('input_text.legro_ausgaben_einnahmen_name_filter') -%}
{%- if filtername == '' -%}
  {%- set value = this_month_tally[i] -%}
  {%- if value >= 0 -%}
    |{{ name }}| |{{ value }}|
  {%- else -%}
    |{{ name }}| |{{ value }}|
  {%- endif -%}
{%- else -%}
  {%- if filtername in name -%}
    {%- set value = this_month_tally[i] -%}
    {%- if value >= 0 -%}
    |{{ name }}| |{{ value }}|
  {%- else -%}
    |{{ name }}| |{{ value }}|
  {%- endif -%}
  {%- endif -%}
{%- endif -%}
{%- endfor -%}
{%- else -%}
FEHLER!
{%- endif -%}

I cannot figure out, that there is no completed table. I know possibly it is a hideous work, but can someone pls help me?

mighty ledge
mental violet
rare linden
#

is there a way to get a list of all areas?

mighty ledge
#

also, you're using -%} in 4 spots that shouldn't have it

#

before each |{{ name }}| | {{ value }}|

#

each |{{ name }}| {{ value }}| shouldn't have an indentation in front of it either.

#

if you make those changes, you should have a markdown table

mental violet
mental violet
mighty ledge
#

yeah, you can, but when not empty it outputs nothing

#

either way, if you just ignore the filtername crap I said and make the other changes, it will probably work the way you want

mental violet
#

can I just if claused it? like if states('input_text.legro_ausgaben_einnahmen_name_filter') is string then {%- set filtername = states('input_text.legro_ausgaben_einnahmen_name_filter') -%} ??

mental violet
mighty ledge
#

you want the carriage return, but not the spaces πŸ˜‰

#

@mental violet fyi this does the same thing

#
{% set data = [
  dict(name='test1', tally=1),
  dict(name='test2', tally=2),
  dict(name='test3', tally=3),
] %}
{%- if data %}
  {%- set filter = states('input_text.legro_ausgaben_einnahmen_name_filter') %}
|Ausgabe| &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; | EUR  |
|:--------------------|---|:-:|
  {%- if filter %}
    {%- set data = data | rejectattr('name','!=', filter) | list %}
  {%- endif %}
  {%- for item in data %}
|{{ item.name }}| |{{ item.tally }}|
  {%- endfor %}
{%- else %}
FEHLER!
{%- endif %}
mental violet
#

can I set the data with a for loop?

mighty ledge
#

no

#

where is the data coming from?

mental violet
#

name and tally are: {%- set this_month_tally = state_attr('sensor.legro_spending_list',('monthly_tally_'+ (now().month)|string)) -%} {%- set this_month_tally_name = state_attr('sensor.legro_spending_list_name',('monthly_tally_'+(now().month) |string)) -%}

mighty ledge
#

ok, change that to

#

hold on, trying to think of the best way to handle this

#

where are tallies and names coming from?

#

what's the integration that's making those sensors?

#
{%- set attr = 'monthly_tally_' ~ now().month %}
{%- set tallies = state_attr('sensor.legro_spending_list', attr ) %}
{%- set names = state_attr('sensor.legro_spending_list_name', attr) %}
{%- set filter = states('input_text.legro_ausgaben_einnahmen_name_filter') %}
{%- set ns = namespace(data=[]) %}
{%- for i in range(tallies) %}
  {% set ns.data = ns.data + [ dict(name=names[i], tally=tallies[i]) ] %}
{%- endfor %}
{%- if ns.data %}
|Ausgabe| &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; | EUR  |
|:--------------------|---|:-:|
  {%- if filter %}
    {%- set ns.data = ns.data | rejectattr('name','!=', filter) | list %}
  {%- endif %}
  {%- for item in ns.data %}
|{{ item.name }}| |{{ item.tally }}|
  {%- endfor %}
{%- else %}
FEHLER!
{%- endif %}
#

that would work as is, but it's not optimal

#

it'll be fine on any system, there just might be better ways if you can change sensor.legro_spending_list and sensor.legro_spending_list_name

mighty ledge
mental violet
mental violet
mighty ledge
#

change it to selectattr('name', 'search', filter)

mental violet
#

thank you

dusky ore
#

Having a weird issue with a pretty basic script:

  - if:
      - condition: state
        entity_id: '{{states(''sensor.music_leader'')}}'
        state: 'paused'```

is throwing the error `Message malformed: Entity {{states('sensor.music_leader')}} is neither a valid entity ID nor a valid UUID for dictionary value @ data['sequence'][0]['if'][0]['entity_id']`. The template state is the name of a media_player entity and it works fine later in the script. Also resolves correctly in the template dev tool. The script works fine if I plug in a media_player entity too.
mighty ledge
#

you can't template entity_id

dusky ore
#

Ah

#

But it works later in the script?

mighty ledge
#

it's probably not a state condition entity_id

dusky ore
#

It's not

#

Got it, thank you!

mighty ledge
#

that would be why

#

general rule of thumb

#

target, and anything in data for a service call can be templated

#

everything else, you have to read the docs

dusky ore
#

Understood, that's super helpful

mighty ledge
#

yeah, in the docs it'll say next to the field if it can be templated or not

#

i think it's just template

#

next to the field name

mental violet
#

Is there a filter for a list which only includes the last 30 entrys?

inner mesa
#

I'm a bit perplexed by regex capture. This works fine to extract "upstairs" in the template editor, but results in \x01 if I use exactly the same thing in an automation:
{{ 'sensor.kit_keypad_upstairs_lights_scene'|regex_replace('sensor.*_keypad_(.*)_lights_scene', '\\1') }}

#

it fails to parse with only a single \

inner mesa
#

seems to work fine in the Python implementation of regex_replace, but I get the same bad result with a single \:

>>> import re
>>> p=re.compile('sensor.*_keypad_(.*)_lights_scene')
>>> p.sub('\1', 'sensor.kit_keypad_upstairs_lights_scene')
'\x01'
>>> p.sub('\\1', 'sensor.kit_keypad_upstairs_lights_scene')
'upstairs'
inner mesa
#

Okay, so it works if you use it in a multiline template, but not a single-line template

inner mesa
#

This works:

        floor: >-
          {{ trigger.event.data.entity_id|regex_replace('sensor.*_keypad_(.*)_lights_scene', '\\1') }}

This doesn't (results in '\0x01'):

        floor: "{{ trigger.event.data.entity_id|regex_replace('sensor.*_keypad_(.*)_lights_scene', '\\1') }}"
floral steeple
#

hi, trying to create a trigger based on my proximity sensor when it equals to 1 km.

#

trigger:

  • platform: template
    value_template: "'{{(states.proximity.my_name.state) == 1}}'"
#

the above does not seem to fire the automation

sick ice
inner mesa
#

And...states are strings

floral steeple
floral steeple
inner mesa
#

Neither address my comment

#

You just added parentheses

#

First, you should use states() as shown in the second link in the channel topic. Second, you need to add |float to convert a string to a number

floral steeple
inner mesa
#

Yes. But the earlier comment about using a > or < rather than an absolute number is also advisable. Or between two values

floral steeple
inner mesa
#

That's not right

#

{{ 0.8 < states('proximity.my_name') | float(0) < 1.2 }}

floral steeple
#

oh geeze, I was searching the documentation, could not find that!

#

for my own, could you link the documentation for this?

#

thank you!

inner mesa
#

it's typical Python syntax, I'm not sure if it's explicitly called out for Jinja

floral steeple
#

ok, got it! Hope you have a very good night, @inner mesa

#

and @sick ice

stuck dock
#

is there any online template testing tool/ demo Homeassitant?

marble jackal
#

devtools > templates

stuck dock
#

I don't have access to a working HA right now

marble jackal
#

What would be the use of that? You won't have access to your entities, so it will also no be a proper test.
I would suggest to either set up a VPN connection to your HA, or arrange remote access in another way.

stuck dock
#

power was down and I wanted to try out ```
{% set days = [ 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday' ] %} {{ days[now().weekday()] }}

marble jackal
#

Well, I can tell you that that is going to work

#

{{ now().strftime('%A') }} will have the same result though

#

I would only use your approach for other languages besides English

stuck dock
#
# Time check
sensor time:
  - platform: time_date
    display_options:
      - 'time'
      - 'date'
      - 'date_time'
      - 'date_time_utc'
      - 'date_time_iso'
      - 'time_date'
      - 'time_utc'
      - 'beat'
      - {{ now().strftime('%A') }}
#

this is how I I should setup?

marble jackal
#

Huh? No

stuck dock
#
Configuration invalid!

Error loading /config/configuration.yaml: invalid key: "OrderedDict([("now().strftime('%A')", None)])"
in "/config/configuration.yaml", line 176, column 0
marble jackal
#

I have no idea what you are trying to do now?

stuck dock
#

I am trying to create a weekday sensor

marble jackal
#

Then create a template sensor with that template for the state

stuck dock
#

unfinished business

marble jackal
#

you can not simply add options to the time_date sensor

#
template:
  - sensor:
      - name: Weekday
        state: "{{ now().strftime('%A') }}"
stuck dock
#
template:
  - sensor:
      - name: Weekday
        state: "{{ now().strftime('%A') }}"
#

output is ```yaml
template:

  • sensor:
    • name: Weekday
      state: "Monday"
marble jackal
#

Isn't that what you want?

#

It will be Tuesday tomorrow

#

if you add that to your configuration it will create a sensor.weekday with the current weekday as it's state

stuck dock
#

yes

#
sensor.weekday
Weekday
Monday    friendly_name: Weekday
#

Thanks for the assist

rose cosmos
#

Hey All. Could anyone help me with debugging a REST sensor template? I can't seem to find any useful info as to where this is going wrong. debugging rest only logs the http response which is fine but the sensors don't seem to be getting updated.

#

EDIT: Nevermind. It seems to have started working. πŸ€·β€β™‚οΈ

marble jackal
tepid onyx
#

πŸ’©

warm saddle
#

With templating is there a way I can get context on how a light was turned off?. For context I have one or more automations to turn a light on and usually one to turn them off (decouples and really simplifies the logic). Problem I'm trying to solve is I have motion based automation that constantly turns the light on and I basically want to ignore turning on if the light was manually turned off... Was hoping to find basically the state info that is shown in the log history of what turned it off and use that in an automation.

#

{{states.light.office.context}} wondering how how I can serialize that to json so I can see all the properties...

#

doesn't like to_json

warm saddle
#

looking more into the context it doesn't seem to be consistent across the light group

#

especially for parent id

#

kinda shocked context doesn't persist trigger_id

fossil venture
warm saddle
#

I see that table and I'm not seeing that in real life

#

the context is not in sync

#

I have 4 zwave switches using switch as light.. I then have a light group triggered by motion. I'd expect all of the light context to be somewhat in the same state.

#

Which is very very od the context ids/reference are different

marble jackal
#

This doesn't say much without knowing what caused the lights to change. bar and main have a user_id in the context, so they are changed by something a user did, not by an automation

warm saddle
#

I told alexa to turn them all off.

#

then walked in the room triggering them all on by a single automation (granted cabinet shouldn't have came on, expect that one to have different context as it only comes on before sunset).

marble jackal
#

adding last_updated might also give some more insight as you can see if they are changed at about the same time (so also by the same action).

#

it could be that other automations also affected the lights, no way for us to know whay you have set up

#

or maybe both last_changed and last_updated

warm saddle
#

I get that 100%, just nothing else in the log book and like I said I have one automation to turn on the lights and one automation to turn off the lights after no motion for 15 minutes

#

I may need to dig into this deeper and get reproduction steps and possibly log a bug

#

seems like there might be an issue with switch as

#

Kitchen Main turned on triggered by service light.turn_on
7:08:18 AM - 1 minute ago - Blake
Kitchen Sink turned on
7:09:13 AM - 1 minute ago

Turned them all on via ha ui and one of the switch as and the light group helpers (turned on all lights of the group) are missing the user_id on the context.

#

yeah, just got it into a good state and it's not syncing properly, there's two different context ids and the update times are all different all going through light.turn_on:light.kitchen (light group helper).

So if I did get this working, still seems like it would be nice for templating to provide some more helpers (to easier detect physical press instead of checking three different states) and maybe even flow through trigger_id.

mighty ledge
#

I.e. you can't use the template editor to test context

tidal meteor
#

I am hitting a wall in converting a string into a datetime object.
I have a dropdown with various times and i want to store the selected dropdown item from 'input_select.start_work_time' in a second helper 'input_datetime.time_work_start
if i dont select a pre programmed start_work_time then i have to manual fill in the start_work_time into the 'input_datetime.time_work_start'
In this way the start_work_time is always a datetime object which makes further processing of the start_work_time easier.

i have this in my automation:
service: input_datetime.set_datetime
data:
time: "{{ as_local(today_at( states('input_select.start_work_time')+':00' )) }}"
target:
entity_id: input_datetime.time_work_start

But it gives the error:
Invalid time specified: 2022-09-05 05:30:00+02:00 for dictionary value @ data['time']

nocturne chasm
#

if this {{ expand('group.zwavejs_fw_updates') | selectattr('state', 'eq', 'unavailable') | map(attribute='entity_id') | list |join(', ') | default(none)}} produces update.kitchen_light_firmare. What do I need to do to get just kitchen light? unfortunately, map(attribute='name') does not produce the desired results so I need to use replace but I cant figure it out

mighty ledge
#

What’s it producing

mighty ledge
nocturne chasm
#

I know and I asked in zwave, maybe it is just a bug but the friendly name is Firmware

mighty ledge
#

Then rename it

#

Name is user or integration set

nocturne chasm
#

I wish I understood your comment but i dont

warm saddle
mighty ledge
nocturne chasm
#

in customize.yaml? yes, but the name is right when the entity is available. it is only when it is unavailable that the friendly name is not respected

mighty ledge
warm saddle
nocturne chasm
#

when it is available the friendly name is Kitchen Light Firmware

mighty ledge
nocturne chasm
#

it is not worth all that. If there is no way to fix it in a template I will just move on

warm saddle
#

I’ve been trying to figure that out, see my original post above for context

#

Only want to turn on lights if it they were manually turned off for at least x minutes

marble jackal
#

but only if all the sensors following the same entity_id structure

mighty ledge
nocturne chasm
marble jackal
#

well, as you are creating a string already, you can als just do | replace('_firmware', '')

#

{{ expand('group.zwavejs_fw_updates') | selectattr('state', 'eq', 'unavailable') | map(attribute='object_id') | join(', ') | replace('_firmware', '') | default(none)}}

warm saddle
#

This really should be easier todo… like I see this asked quite a bit on forums.

nocturne chasm
marble jackal
#

you indeed need to do the replace after the join, because as of then it is a string πŸ™‚

mighty ledge
warm saddle
#

What does that even mean

mighty ledge
#

Context will only tel you what automation fired it or what user fired it

#

It will not tell you who or what pressed the physical switch

warm saddle
#

Yeah I get that via automation triggers context

mighty ledge
#

Right, so you need to come up with a way to cancel your automation when the context is empty

warm saddle
#

Seems like a big hole is missing because your trigger context might not contain light state but motion state.

mighty ledge
#

You can filter that with trigger ids

warm saddle
#

And it seems like entity context changes on any entity state attr changes

nocturne chasm
warm saddle
#

But still would be useless because I trigger on an entirely different device/entity

mighty ledge
#

It’s possible, you have to build the logic

#

I do it, but without context

warm saddle
#

Thanks for bouncing ideas off. Feels like if I see something in the logbook, I should be able to drive automations or templates from the last log book entries values

mighty ledge
#

You can, the context is what builds the logbook

warm saddle
#

Yeah via sql queries?

#

Do you have an example anywhere?

mighty ledge
#

No, context is only alive during automations

#

I don’t know how else to explain it

#

What you see in the state machine is not your current context

#

So it looks random

mighty ledge
#

If you use states.xxx.xxx.context, you’re getting the wrong context

nocturne chasm
marble jackal
#

you can use | map('title') before the join

#

{{ expand('group.zwavejs_fw_updates') | selectattr('state', 'eq', 'unavailable') | map(attribute='object_id') | join(', ') | replace('_firmware', '') | replace('_', ' ') | title }}
This probably can be done more efficient though

nocturne chasm
#

ehh, its just a markdown and I am happy with working over efficient. thanks again and just | title worked

warm saddle
mighty ledge
#

You have to capture it when it occurs

marble jackal
warm saddle
#

And store it where? I don’t want to maintain it, I have literally hundred switches

nocturne chasm
#
Z-Wave JS Firmware Status
Total:          45
Update Needed:  0
Up-To-Date:     44
Dead:           1
Dead Devices:   Kitchen Light
marble jackal
#

RIP Kitchen Light 😒

mighty ledge
nocturne chasm
#

RIP Kitchen Light Firmware status πŸ˜‰

warm saddle
marble jackal
mighty ledge
#

Just make a template trigger entity that produces the current context. I’m on mobile so I’m not going to write any yaml

warm saddle
mighty ledge
#

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

#

Through a trigger it is

warm saddle
#

Ok

#

Thanks for your time

tidal meteor
mighty ledge
#

Pretty sure 00:00 also works

pseudo vector
#

Hi guys, I was wondering if templates are the way to go for creating a virtual light entity which maps to an existing light. I want to map the new entity's brightness 0-100% to the existing light 0-70%.

marble jackal
#

A template light would be the way to go

thorny snow
#

Hi, I'm trying to map a text output to a sensor value coming from ESPhome. This is nearly the same as what is discussed on the forum link below but in my case I somehow need to read the sensor value and convert it to an integer before I can map it. https://community.home-assistant.io/t/wanting-to-map-sensor-number-value-to-words/40663/15

I tried the YAML config below but it gives met the "else" clause output while it should be the "0" output so I'm gessing the value isn't coverted to an integer. Could somebody please assist as I'm not familiar with these templates...

`sensor:

  • platform: template
    sensors:
    hc1_mode_text:
    friendly_name: "Werkingsmodus HC1"
    entity_id: sensor.hc1_mode_text
    value_template: >-
    {% set mapper = {
    '0' : 'Standby',
    '1' : 'Only DHW',
    '2' : 'Heating + DHW',
    '3' : 'Constantly reduced',
    '4' : 'Constantly standard' } %}
    {% set state = states('sensor.ketel_sens_hc1_mod_operation') | int %}
    {{ mapper[state] if state in mapper else 'Foutief' }}`
inner mesa
#

your "mapper" is using characters, not integers

#

you need to choose one or the other and be consistent

#

'0' is not the same as 0

thorny snow
#

Thanks a lot!

jagged obsidian
#

the better question is why don't you send number values from esphome in the first place?

inner mesa
#

they're still going to end up as strings

jagged obsidian
#

meh, esphome disappoints again

inner mesa
#

it's just because all HA states are strings

zealous flame
#

how would I go about creating a single automation that monitors all my leak sensors and sends a notification reporting which one had a state change?

#

what's a keyword there to google?

silent seal
zealous flame
#

thanks

silent seal
zealous flame
#

got it thanks

orchid vessel
#

Hello, I'm a shite coder and would appreciate some assistance.

{% set T = ((states('sensor.tent_temperature') | float)) %}

This is what I currently have. It is working. I would like to add a second sensor and divide it by two to get the average of both. How would I do that?

#

{% set T = ((states('sensor.tent_temperature') | float + states('sensor.second_tent_temperature') )) /2 %}

#

is this correct?

inner mesa
#

No. You converted the first to a float, but not the second?

orchid vessel
#

{% set T = ((states('sensor.tent_temperature') | float + states('sensor.second_tent_temperature') | float )) /2 %}

orchid vessel
#

*understanding.

inner mesa
#

This would be a good time to walk through it. It's quite simple

orchid vessel
#

interesting so float is the conversion to a real number

inner mesa
#

A floating point number

#

Because all states are strings

orchid vessel
#

right so float is more accurate at the expense of processing time?

inner mesa
#

Compared to what? You cannot do math by adding strings

orchid vessel
#

Ah right. Sorry again, I have some learning difficulties so I apologize if I'm being slow.

orchid vessel
#

I got it working. Thank you for your help.

flat shell
#

Hi, I have power plug that is added automatically by local tuya and unlike the previous ones that I added using yaml this one has no separate sensors for current consumption but instead it's added as attribute of switch itself. I tried adding sensor as template but I'm doing something wrong. Here is What I have tried:
"sensor: gas_heater_current_consumption: friendly_name: "Gas Heater Power Consumption" device_class: power state: >- {% if {{state_attr('switch.plug2', 'current_consumption')}} %} {{state_attr('switch.plug2', 'current_consumption')}} {% else %} '0' {% endif %}"
but I'm getting error "Invalid config for [template]: [gas_heater_current_consumption] is an invalid option for [template]. Check: template->sensor->0->gas_heater_current_consumption."

analog mulch
marble jackal
flat shell
#

I may be stupid but I'm trying right now all possible combinations and still getting nowhere 😦

#

....well obviously not all...

marble jackal
#

@flat shell you have this in template.yaml now? Or at least under the template integration?

#
sensor:
  - unique_id: sensor_gas_heater_power_consumption
    name: Gas Heater Power Consumption
    device_class: power
    state_class: measurement
    state: "{{ state_attr('switch.plug2', 'current_consumption') | default(0, true) }}"
#

the entity_id will be sensor.gas_heater_power_consumption, you can change that by editing the entity_id in the GUI (only if a unique_id is provided)

flat shell
#

yes it's in my template.yaml I just tried it and it's not working. Maybe because I already have some binary sensors?

#

this is my complete template.yaml:

dusty grailBOT
marble jackal
#

you need to add - for each sensor type. template: expects a list

#
template:
  - sensor:
      - name: sensor 1
        state: "{{ some template }}"
      - name: sensor 2
        state: "{{ some other template }}"
  - binary_sensor:
      - name: binary sensor 1
        state: "{{ yet another template }}"
#

That was not an issue when you had only binary_sensor, because with one item it will be treated as a list, but after you added sensor as well, that caused errors

flat shell
#

ok, ill try and fix it

marble jackal
#

your binary sensors are also wrong btw, and using the same mix of new and legacy format

#

and your indentation is off

flat shell
#

I know now... I'm trying right now to rewrite it to new format

marble jackal
#

@flat shell you're welcome

flat shell
#

It's working! Thank you very much!!!

silent vector
#

Is there a way in my dictionary set_color_temp to use at 8pm and after9pm 400 and 370. Check if it's not equal to either 400 or 370. I'm not sure with selectattr if 'not in' can be used

Seems dpaste is down?
https://pastebin.com/si6N8ST8

marble jackal
#

use rejectattr(attribute, 'in', value) for that

silent vector
#

How would I do that? As I only want to check for 2 temperatures on those 2

#

The rest are single numbers.

marble jackal
#

rejectattr('attributes.color_temp', 'in' , [400, 370])

silent vector
#

I assume that goes here

{{ states.light | selectattr('entity_id', 'in', area_entities(area)) |
        selectattr('attributes.color_temp', 'defined') |
        selectattr('attributes.color_temp', 'ne', set_color_temp[script_type]) | rejectattr('attributes.color_temp', 'in' , [400, 370]) |
        list | count == number_of_lights  }}
marble jackal
#

you can simplify that:
{{ states.light | selectattr('entity_id', 'in', area_entities(area)) | selectattr('attributes.color_temp', 'defined') | rejectattr('attributes.color_temp', 'in', [ set_color_temp[script_type], 400, 370 ]) | list | count == number_of_lights }}

#

forgot to remove one pipe

silent vector
#

And this would allow it to still work if it's 222? The goal is to accept if any of the lights are 400 or 370 when the dictionary is 370 or 400. Essentially don't accept 370 if it should be 222

marble jackal
#

if what is 222

silent vector
#

set_color_temp[script_type]

marble jackal
#

you first selected all lights with the color_temp not equal to that variable, and then rejected all with color_temp equal to 370 and 400

#

I combined those in one rejectattr

silent vector
#

I see. So if it is false at 222 because the lights are at 370 then it won't become true because the lights are 370 at the rejectattr. It would use rejectattr if the first select attr is false when the lights are 370 or 400? Then it will reject both and count the lights? I'm sure I probably confused you. I'm trying to wrap my head around trying explain this.

#

I just want to make sure if it's Day and the lights are 370 when they should be 222 that it will be false not true. Only true when it should be 370 and it's not equal because the lights are 400 for example so then it becomes true.

marble jackal
#

number_of_lights seems to be all the lights in a particular area which are on

#

What are you trying to do with that condition then?

#

that condition will be always be false if one of those lights which are on doesn't support color_temp

#

For that condition to be true, all the lights in the area need to support color_temp and the color_temp should be set to anything besides set_color_temp[script_type], 400 and 370

#

that's what your current, updated, condition does

silent vector
#

Yes not equal to set_color_temp[script_type] and if the set_color_temp[script_type] is 370 then all lights in the area must not equal 370 or 400

marble jackal
#

ah, so when it's 222 you only want to check for 222, but when it is 370 you also want to check for 400

#
{{ states.light | selectattr('entity_id', 'in', area_entities(area)) | selectattr('attributes.color_temp', 'defined') | rejectattr('attributes.color_temp', 'in', iif(set_color_temp[script_type] == 370, [370, 400],[set_color_temp[script_type]])) | list | count == number_of_lights  }}
#

small correction applied

silent vector
#

Yes I didn't know this could be done.

#

Thank you.

#

Missed another ) at the rejectattr but I found and fixed that, by learning from the best at Jinja (you,Petro, a few others).

marble jackal
azure drum
#

Hello there, I am relatively new in ha. I learned to crawl and do some stuff I wanted to do. But now I can't find the answer to the question how to set a default value within a template, if the e.g. sensor.xyz is not yet having data. How can I set an initial value to a sensor within a template? Maybe a link to an example will be enough... I could not find one...

marble jackal
#

can you give some more details on what you actually want to do

azure drum
#

I simply add different sensor data into a new one. And as long as not all haver received a value (after restart of ha) the visualisation gives an error, that the data is not available. So I thought just give an initial default to make it work.

marble jackal
#

.share your current template

dusty grailBOT
#

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

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

azure drum
#

Can I paste the four lines?

marble jackal
#

4 lines is okay

#

.format it as code though

dusty grailBOT
#

To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks. Here's an example

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

For over 15 lines you must use a code share site such as https://dpaste.org/ (pick YAML for the language), https://www.codepile.net/ (pick YAML for the language), or https://paste.debian.net/ (pick YAML for the language).

azure drum
#
  • name: "Solare Leistung Summe"
    unique_id: "solar_power_sum"
    unit_of_measurement: 'W'
    state: '{{ (states("sensor.wr1_powerdc_1k") | int + states("sensor.wr1_powerdc_2k") | int + states("sensor.wr2_powerdc_1k") | int + states("sensor.wr2_powerdc_2k") | int + states("sensor.wr2_powerdc_3k") | int) }}'
    device_class: power
inner mesa
#

please see the bot message

marble jackal
#

And you and add defaults to your int filters to avoid the errors are startup

#

int(0)

rare linden
#

is there nice simply way to sort a list of states by last changed? timestamp

#

such as a filter instead of having to loop through it

inner mesa
#

{{ expand(["switch.fr_table_lamp", "switch.fr_reading_lamp"])|sort(attribute="last_changed")|map(attribute='entity_id')|list }}

#

like that?

rare linden
#

yeah i think that will do the trick, thanks

rare linden
#

Just posting this for anyone looking to do the same in future, code to create a sensor to get the last motion sensor detected with an on state else fall back to the last sensor that changed- name: "[Motion] Last Active Sensor" state: "{{ (states.binary_sensor | selectattr('entity_id', 'match', '^binary_sensor\\.motion_') | sort(attribute='last_changed', reverse = True) | sort(attribute='state', reverse = True)| map(attribute='entity_id') | list)[0] }}" icon: mdi:motion-sensor and you can create another sensor to display the name or area "{{ states[states.sensor.motion_last_active_sensor.state].name | regex_replace('^\\s*\\[.*?\\]\\s*', '') }}" and "{{ area_name(states.sensor.motion_last_active_sensor.state) }}" , may require a tweak to the '^binary_sensor\\.motion_' based on your naming convention, my sensors don't show under motion domain so i target them using my own naming convention. the regex for the name is to strip out any prefixes contained within square brackets aka [Motion Sensor] Computer Desk and leave just Computer Desk

azure drum
# marble jackal `int(0)`

yes, that's what I would like to do. But how, I found no documentation of the syntax, nor an example. So one example would help, that what I am searching. Can you post one example of how it would look like? Thanks!

marble jackal
#

There is a link to a post about defaults in the pinned posts in this channel

azure drum
#

Thanks!!!!! That is what I didn't find....

obtuse zephyr
#

For template sensors, what's the best way to handle when the source sensor is unknown/unavailable? Should everything be wrapped w/ an if chain to check and pass through that status or is there a better way? I'd rather not default it to a value since that'd technically be reporting an incorrect state for the template sensor

Ex. {{ states('sensor.garage_door_y_axis') | int > -720 }}, where that sensor is unavailable for a few during start up, the template sensor should report unavailable as well, but as is since there's no default (and shouldn't be one), it'll error.

fossil venture
#

Best practice is to supply a default value, e.g. {{ states('sensor.garage_door_y_axis') | int(0) > -720 }} if you want it to show unavailable as well then use the template integration rather than the template sensor platform ("new" style templates) for which you can supply an availability template like this: availability: "{{ states('sensor.garage_door_y_axis')|is_number }}"

obtuse zephyr
#

Ahh, interesting. So if I apply that availability attribute, even though the actual template may be returning inaccurate data, the sensor won't report that and instead will report as unavailable?

fossil venture
#

If the availability: template returns false the state becomes unknown, no matter what the state template resolves to. The state template can still generate errors in the log though, which is why the default for the int filter is required.

obtuse zephyr
#

I gotcha, that makes sense. Thanks for that @fossil venture

marble jackal
#

There's also availability_template in the legacy format

fossil venture
#

It's quite a while since I've used it.

dusty grailBOT
rare linden
#

is there a delay_on as well as the delay_off for sensors?

#

Looks like there is

mighty ledge
#

Only binary_sensors

plain sigil
inner mesa
#

that's a good thought, but you'd need state: "{{ states('binary_sensor.original_sensor') }}"

plain sigil
#

Oops. Simple mistake to make when writing stuff without testing it

heady fox
#

I have a working example of sorting the hourly energy price and comparing if the actual hour is the cheapest or not. However I only want to sort the coming 7 hours, not the entire day of 24 hours. How do I solve it?

#
{%- set sorted_prices = state_attr('sensor.nordpool_kwh_se3_sek_3_095_025','today')|sort %}
          {{ states('sensor.nordpool_kwh_se3_sek_3_095_025')|float <= sorted_prices[0]|float }}
mighty ledge
mighty ledge
mighty ledge
#

you also could just get the min or max out of it

#

instead of sorting

#
{{ states('sensor.nordpool_kwh_se3_sek_3_095_025')|float <= state_attr('sensor.nordpool_kwh_se3_sek_3_095_025','today')[:7] | min }}
heady fox
#

Thanks a lot! Will try that out.

sullen wyvern
#

noob question: how do you do a simple string compare in a template if condition?

i wanna do
{{user}} == Hypnopunch

mighty ledge
#

user is only available in the front end and multiple people can be logged in at the same time

sullen wyvern
#

πŸ™ i have a button and wanna add to an input counter if i press the button on my app and a different counter if my wife presses it on her app

mighty ledge
#

That is possible to do, but it's advanced templating. YOu'd need to explain what you expect to happen if the user is not one of the ones in question

#

The users have to be people though.

sullen wyvern
#

then it can be disregarded

#

yes they're people

mighty ledge
#

what's triggering the button press

#

show your automation

dusty grailBOT
#

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

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

sullen wyvern
#

it's a simple button card. when pressed it calls a script

mighty ledge
#

can you post the script please

sullen wyvern
#

ye 1 sec

#

its just playing a thing on the speaker for now, but i'll eventually do other stuff

mighty ledge
#

yeah but that's not the full script

#

thats just 1 service call

sullen wyvern
mighty ledge
#

right, but I need to see the full counter script

#

what you posted is only a single action in your full script

sullen wyvern
#

oh, i hadnt done that part yet

#

gimme a min ill do it and post

#

here it is

mighty ledge
#

ok

#

so

#

Remove the quotes around "No Person", mistake on my part

sullen wyvern
#

hmm

#

its not hitting the if condition

mighty ledge
#

post the trace variables

#

click on the trace, then click on the step variables tab and paste the contents

sullen wyvern
#

will do, but noticed something. if i change to visual editor and click Test on the template condition i get this
Error occurred while testing condition template value should be a string for dictionary value @ data['value_template']. Got None

mighty ledge
#

did you copy exactly what I pasted or did you alter it?

sullen wyvern
#

i altered just my name and the quotes around No Person

mighty ledge
#

did you alter the quotes around the name == 'husband'?

#

theres interior quotes and exterior quotes, both are needed.

sullen wyvern
#

they are there

      - condition: template
        value_template: "{{ user == 'Husband' }}"
    then:```
mighty ledge
#

I don't know how you can be getting that error as that's the only value_template

#

are you sure you're looking at the correct trace and not an old one?

sullen wyvern
#

so.. i dont see a step variables tab. i clicked debug script -> clicked on the branch button on the left -> Step Config tab

mighty ledge
#

step variables are at the bottom of the page

#

and what you see there is fine

#

changed variables, sorry

#

if you don't get changed variables, then you didn't add the variable

#

see my paste dump again and look at the top of the script, you'll see a variables section

sullen wyvern
#

oh yeah i see that

#

user_id isn't sensitive information is it?

mighty ledge
#

na, give me a sec tho

#

sorry, mistake in a line

#

``

#
  {% set person = states.person | selectattr('attributes.user_id', 'eq', context.user_id) | first | default %}
#

replace that line with what I just posted

sullen wyvern
#

same result

mighty ledge
#

post trace

sullen wyvern
mighty ledge
#

post what you have for the user variable

violet flare
#

I've got a binary_sensor for a Dahua camera that goes to on when a human is detected. I'd like to populate the last time that sensor went to on. Getting the last_changed attribute will only get me the last state change. My thought was to make a helper variable that populates when the switch goes to on, but is there a way of doing this strictly within a template?

sullen wyvern
#
variables:
  user: >
    {% if context is defined and context.user_id is defined and context.user_id
    %} {% set person = states.person | selectattr('attributes.user_id', 'eq',
    context.user_id) | first | default %}
      {{ person.name }}
    {% else %}
      No Person
    {% endif %}
sequence:```
mighty ledge
#

should be working

#

change it to

{{ states.person | selectattr('attributes.user_id', 'eq', context.user_id) | map(attribute='name') | first | default }}
sullen wyvern
#

didn't work either

mighty ledge
#

when it doesn't work, just jump straight to the trace

#

are you pressing test or pressing the button

#

and are you 100% sure your user is a person

sullen wyvern
#

ive tried pressing the button, running script directly from the script

mighty ledge
#

it should work from the button only

#

anyways, I need to see the output of the template, i.e. the trace variables

sullen wyvern
#

would this work in Dev tools -> template?

#

just the setting user variable part

mighty ledge
#

no

#

it should take 2 seconds to get this info

#

update -> press button -> go to trace,

sullen wyvern
mighty ledge
#

you didn't change the template

sullen wyvern
#

im pretending to work at the same time sorry

mighty ledge
#

it's still outputting No Person and what I posted above will not do that

#

replace the whole user template with

{{ states.person | selectattr('attributes.user_id', 'eq', context.user_id) | map(attribute='name') | first | default }}
sullen wyvern
#

i see

#

failed to call service script/1662586451099. UndefinedError: 'context' is undefined

mighty ledge
#

are you using the button or the test script button

sullen wyvern
#

button

mighty ledge
#

that makes no sense

#

unless the button doesn't transfer context

#

does the button press show up in logbook?

sullen wyvern
#

yeah

#

not exactly the button but it triggers the script

mighty ledge
#

... what do you mean

sullen wyvern
#

counterscript started triggered by service script.1662586451099

#

thats what i get in logbook

mighty ledge
#

the trace shows that context exists.

sullen wyvern
#

i hadnt replaced the entire thing when i sent the last trace

#

after replacing it it doesnt work
Stopped because of unknown reason "null" at September 7, 2022 at 3:53:02 PM (runtime: 0.01 seconds) i get that in Trace Timeline

#

i gotta hop off, got a meeting in 3 mins
really appreciate your help. enjoy the coffee πŸ™‚

mighty ledge
#

thanks, giove me a moment to set this up on my end

#

ok, it's a stupid bug

#

change your button to

#
  - type: button
    entity: script.counterscript
    tap_action:
      action: call-service
      service: script.turn_on
      data:
        entity_id: script.counterscript
#

in the UI

#

instead of using script.counterscript as the service, use script.turn_on

#

and send entity_id in the data

fresh vortex
#

I have been trying to get a MQTT sensor issue resolved that has objects that are not always in the published topic:

#

{"windDir": "326.66798419", "rain24_in": "0.0", "hourRain_in": "0.0", "txBatteryStatus": "0.0", "windSpeed_mph": "4.0", "outTempBatteryStatus": "4.0",
"rainRate_inch_per_hour": "0.0", "dateTime": "1662591804.0", "dayRain_in": "0.0", "usUnits": "1.0"}

{"windDir": "326.66798419", "rain24_in": "0.0", "hourRain_in": "0.0", "txBatteryStatus": "0.0", "windSpeed_mph": "1.0", "outTempBatteryStatus": "1.0",
"rainRate_inch_per_hour": "0.0", "dateTime": "1662591850.0", "dayRain_in": "0.0", "outTemp_F": "75.30", "windchill_F": "75.3", "usUnits": "1.0"}

mighty ledge
#

value_json.windchill_f | default(none)

fresh vortex
#

that will stop the values bouncing from zero?

mighty ledge
#

it will be unavailable when it doesn't get the attribute

fresh vortex
#

thank you

mighty ledge
#

np

fresh vortex
#

I tried value_template: "{{ value_json.windchill_F | default(none) }}" but instead of zero I am getting none.

#

i would like to have previous value remain.

sullen wyvern
#

@mighty ledge i was able to get it working like this. i got my user_id from the trace and entered it there

  user: >
    {% set person =  states.person|selectattr("attributes.user_id", "==",
    "7b6ad9dsgfsdgdsdsg9c36")|map(attribute="attributes.friendly_name")|first 
    %}
      {{ person }}```
mighty ledge
#

No, don’t do that

#

That hard codes it

#

Just change your button config

sullen wyvern
#

yeah

#

i tried the button thing you posted with no luck

mighty ledge
#

Add this. Before the conext.user_id

#

In the selectattr

#

In combo with the button config change

sullen wyvern
#

what exactly does selectattr do?

fresh vortex
#

@mighty ledge is there a way of retaining the previous value if that object is not present?

dusty grailBOT
summer iron
#

Damnit.. i intended to do a code block. But... Ah well.. My entire message is in the one above.

#

If anyone could point me at where i would do what i wish.. i would be a very happy camper.

marble jackal
#

if it is your first template sensor, you can place it in configuration.yaml

#
template:
  - sensor:
      - the code you posted
#

As soon as you create more, you'll probably want to put them in a separate template.yaml

summer iron
#

YEah, Got some help on that by a friend who knows the structure of HA a lot more.

#

Set myself up some .yaml files and includes in preperation for all the stuff i intend to do πŸ™‚

#

Thanks a lot for the reply tho.

sullen wyvern
#

in the condition of an automation how do i check if trigger.event.data.file contains the string abc123 using a template condition

marble jackal
#

{{ 'abc123' in trigger.event.data.file }}

sullen wyvern
#

@marble jackal thank you!

#

looks like my syntax was wrong

mighty ledge
mental violet
#

Hi,
when I do this:
{%- set gesamttally = gesamttally + item.tally |float %}
in a for loop and declare before like this:
{%- set gesamttally = 0 %}
after the for loop, it is still 0. 😦 why?

mighty ledge
#

jinja's doesn't have access to information in the loop. It's scope is 1 dimensional. Meaning, things that happen in the loop can only be accessed in the loop.

#

if you want a counter, you have to use namespace

#

i.e. the code I provided days ago does that πŸ˜‰

#

@mental violet ^

mental violet
#

i think I have done it, thank you πŸ˜„

abstract river
#

Is the formatting for templates different in the automation editor? I see there is an asterisk but i cannot see what that means

#

I copied in a template that worked fine in YAML, but it adds ' where there should be and puts it on two lines.

mighty ledge
#

post what you're talking about

abstract river
#

My template is:
{{ states('input_select.home_away') != 'away' and now().month >= 5 and now().month <= 9 }}

mighty ledge
#

when you save that in the UI, you'll get double '' for every '

#

that's expected

#

it will also cut it up into multiple lines

abstract river
#

Is that a bug or is that how it is supposed to be? And is there documentation somewhere how I am supposed to write them? I searched but I could not really find anything very detailed for the automation editor

mighty ledge
#

as for "how to write them", you can write them however you want as long as it gets the result you want

#

the documentation covers methods and filters you can use, it doesn't really cover the 'best practices'

abstract river
#

Can you just not write templates in the automation editor then?

mighty ledge
#

you can

#

they still work

#

see pin 1 about the test button, as I have a feeling that's why you're asking these questions

abstract river
#

They will still work even with the double ' and it being on two lines?

mighty ledge
#

yes

abstract river
#

It fails in vs code and in the template editor under developer tools with the format that the automation editor uses

mighty ledge
#

yep, it will

#

as for vscode, why are you looking at that if you're using the automation editor?

abstract river
#

Well originally because the test button wasn't working with the templates

patent ruin
#

hi guys, I had this automation working for my sprinkler to irrigate only if precipitation forecast is > 0 but since weeks the test goes wrong with this error "template value should be a string for dictionary value @ data['value_template']. Got None"

{{ state_attr('weather.rome', 'forecast')[0].precipitation > 0.1 }}

anybody knows if anything changed in HA?
thank you

inner mesa
#

you'll need to look at that entity in devtools -> States

#

it's a pretty straightforward template

patent ruin
#

I get "true" instead a number. i suppo se this might be the problem. the strange part is that it ahs been working for months

mighty ledge
#

so what you're saying is that you're not really the task master yet

patent ruin
patent ruin
mighty ledge
#

if it's true/false just remove the > 0.1

patent ruin
mighty ledge
#

but you said it was true before

patent ruin
# mighty ledge this

thst's what i suppose because while testing model in developer tools I get string result. But I expected to get the number value as presented in states

mighty ledge
#

any numerical comparision is going to give you a true or false

#

that's what > or < does

#

is 4 greater than 5? -> false

#

is 4 greater than 3? -> true

#

so when you use the > or < or <= or >= or == or !=, you're going to get a True/False

patent ruin
#

perfect that could be enought but if i test the condition inside automation this template provides an error (while I get true in the model test)

mighty ledge
#

did you put quotes around your template?

#

"{{ ' ' }}"

#

outside quotes = ", inside quotes = '

#

if you're using the automation editor, quotes don't matter but see pin 1, as the test condition button doesn't work

patent ruin
patent ruin
mighty ledge
#

yes, that's why we have pins

#

because 90394802938409283409820348024 people ask this a day πŸ˜‰

#

πŸ“Œ

patent ruin
#

oh the pin is that thing on the top right? great i should have a discord tutorial first in this case πŸ™‚ anyway thank you, I'll take a look at those pins right now (my next task)

waxen lynx
#

hi...I want to merge two entities and create one myself ? is it possible ...
reason : for android tv one entity provides some informations and other entity provides some more which aren't available in other entity ...soo if I could merge them together by adding as a custom sensor ..I can get attributs of both together ...is it possible ?

inner mesa
#

you can build a template sensor

paper pumice
#

Hi guys, i'm setting up a dashboard to control my pool/spa pumps and heaters. I'm using a mushroom template card for this. Basically for the secondary info on the card I want it to Display "On / 80Β°F" where the temp is the current_temperature attribute of climate.pentair_pool_heat

{{ states('switch.pentair_pool') | title }} / {{ state_attr("climate.pentair_pool_heat", "current_temperature")}}Β°F

This works as expected, but how would I make it only show the / 80Β°F part if the attribute is available? I don't want it to display / UnavailableΒ°F basically. Any help appreciated

waxen lynx
waxen lynx
inner mesa
#

the docs indicates what's required. an entity without a state doesn't make sense

waxen lynx
#

yeah....just realised

fierce turret
#

What is the meaning behind these when assigning icons etc?
|
|-

inner mesa
waxen lynx
# inner mesa the docs indicates what's required. an entity without a state doesn't make sens...

what am i doing wrong here?
it shows unavailable? and it shows as sensor.mitv...instead i want it to show as media_player.mitv
here is the code can yu please help?
`template:

  • sensor:
    • name: mitv
      state: "{{ media_player.android_tv }}"
      attributes:
      media_title: >
      {% if is_state('media_player.android_tv', 'playing') %}
      {{state_attr('media_player.android_tv','media_title')}}
      {% endif %} `
inner mesa
#

first, you haven't provided an alternative if your if statement evaluates to false

#

second, this is the right syntax:

#

state: "{{ media_player.android_tv }}"

#

third:

dusty grailBOT
#

To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks. Here's an example

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

For over 15 lines you must use a code share site such as https://dpaste.org/ (pick YAML for the language), http://pastie.org/ (pick YAML for the language), or https://paste.debian.net/ (pick YAML for the language).

inner mesa
#

fourth, you're creating a sensor, not a media_player entity

waxen lynx
# inner mesa perhaps you really wanted this? <https://www.home-assistant.io/integrations/univ...

ha....sorry for being nobbie..and guess this is want i needed ..thanks
but just as i trying to learn is this ryt way of making a sensor? i want the state of that entity to reflect in this custom sensor state

        state: >
          {{states('media_player.android_tv')}}
        attributes:
          media_title: >
           {% if is_state('media_player.android_tv', 'playing') %}
             {{state_attr('media_player.android_tv','media_title')}}
           {% else %}  
             unavailable
           {% endif %}```
inner mesa
#

Please read the bot message

#

Looks okay to me

waxen lynx
inner mesa
sullen wyvern
#

Hi, i'm using mini graph cards

im trying to set a secondary entity but it shows up as NaN in the card

if i do this, it works correctly

state_map:
  - value: "steady"
    label: steady
  - value: "falling slightly"
    label: falling slightly

and so on...

how would i do this without hardcoding? theres more than 20 states

waxen lynx
# inner mesa Please read the bot message

hi i tried and these are the results
when i use children it does not overwrite or create any new attribute
and when i try the below code..it shows the state but cant find none of the below attributes.

  platform: universal
  name: mitv
  attributes:
    state: media_player.android_tv
    media_title: media_player.android_tv|media_title
    entity_picture: media_player.android_tv_192_168_0_137|entity_picture
    app_name: media_player.android_tv_192_168_0_137|app_name```
im not actually getting things right..i guess only limited attributes can be used may be.
what i really wanted is to have is a media player with all the attributes of this media player `media_player.android_tv_192_168_0_137` and also add extra attributes from other media player...like media_title
rustic raft
#

Inside of an automation blueprint I'm creating, am I able to use templating to call expand on a group of entities in a single input, e.g. !input target_lights so I can iterate over them?
Assuming target_lights is defined in the top of the blueprint as:

      name: Lights
      description: The lights to keep in sync.
      selector:
        target:
          entity:
            domain: light```
mighty ledge
#
variables:
  my_target: !include target_lights
  my_iterating_crap: >
    {% for t in my_target.entity_id %}
      ...
    {% endfor %}
honest horizon
#

Hello, is it possible to query a sensor value at a past timestamp? Best regards

marble jackal
#

you need to get that out of the database using an sql sensor

fossil venture
#

Here's one I prepared earlier: ```
SELECT state FROM states WHERE entity_id = 'sensor.total_cost_today' AND HOUR(TIMEDIFF(UTC_TIMESTAMP(), last_updated))>=24 ORDER BY last_updated DESC LIMIT 1

#

This gives me the total cost 24 hours ago.

valid hatch
#

I have a Z-wave lock that reports events, like so:
https://imgur.com/a/iHTyul8
Is there any way to make a template sensor that indicates what the most recent event was?

trail estuary
#

Someone once helped me with a template, of which this is a part:

        {% set end = 'light_energy' %}
        {% set ns = namespace(states=[]) %}
        {% for s in states.sensor %}
          {% if s.object_id.endswith(end) %}

It checks for sensors whose entity_id ends with light_energy. I was wondering if there is a function that can check if a sensor contains a certain string instead of if it ends with this string?

inner mesa
#

yes, 'in'

#

as in {% if end in s.object_id %}

trail estuary
#

Nice! Thanks! πŸ™‚

#

Was it you maybe that helped me to begin with? πŸ˜‰

inner mesa
#

I don't remember writing that, but 🀷

little forge
#

hey guys I'm trying to build an automation that sets a guest mode until a certain time (guesttimer_end) is reached. I need to calculate the time between now and the end time and delay that much. But I'm stuck a bit, any pointers would be appreciated:

{{ today_at(states('input_datetime.guestmode_end')) - now() }}```
#

I know I still need to convert the delta back to military time format so that the delay works

#

i'm on a mission to see if I can have all of my NR flows as HA automations, but this is one of the more tricky ones πŸ™‚

marble jackal
#

delay also works with seconds, do you can use (today_at(states('input_datetime.guestmode_end')) - now()).total_seconds()

little forge
#

tx. still struggling tho. this one stays in NR for a bit πŸ™‚

marble jackal
#

If you would save date and time in your input_datetime instead of time only, it would be easier

lapis quarry
#

Good morning guys πŸ™‚ Could I get some help with some templates? I have been getting these errors in a bunch of templates and been trying to fix them for a long time. Il share the simplest one to start with

In 'condition':
  In 'template' condition: UndefinedError: 'None' has no attribute 'object_id'```
#

would like to figure out how I can protect the template from triggering if the entity trigering has no entity_id or object_id or if the device is not available

#

I cant seem to find any solution online on how to fix this error when using this as a trigger

    - platform: event
      event_type: state_changed```
marble jackal
#

This automation will probably trigger multiple times per second if you have a lot of entities

#

You can create a template sensor which has as state a count of all battery sensors you consider as low

#

And as an attribute the list of the sensors which are low

#

Trigger on a state change, check in the condition if it increased and compare the attribute in the to_state and for_state to see which entity causes the increase

lapis quarry
#

Yes, I have hundreds of sensors so it does trigger very often. but its been working fine for years.

Main thing I wanted to achieve templating like this is the template needs to be flexible, meaning if i add or remove a new sensor as long as i name it right it should be transparent to the template and not have to modify any code for it to work

#

Im not sure im following your sugestion and if that can be implemented to achieve the above

static orchid
#

I created this:
/config/configuration.yaml

template:
  - binary_sensor:
    - name: "Washer Status"
      state: >
        {% if state_attr('sensor.washer_current_power', 'W')|float >= 5 %}
            on
        {% else %}
            off
        {% endif %}

I tried to add it to the dashboard, but I cant find it. How do i do this

#

Nevermind, i forgot to restart HA after i coded it

marble jackal
lapis quarry
#

I need to wrap my head around what you are sugesting, I think i kind of get but not sure how to implement it

#

i need to think about it maybe do some tests, so i create a new template sensor using a for loop to filter out only the sensors im interested in

#

and then use that info in the state change condition to trigger this template?

#

its kind of what im understanding

marble jackal
marble jackal
#

The template above will give you a count of all binary_sensors for which the entity_id ends with batt and which are on

lapis quarry
#

ok..

marble jackal
#

Use that as the state of the template sensor

#

For the attribute you can use

{{ states.binary_sensor | selectattr('entity_id', 'match', '.*batt`) | selectattr('state', 'eq', 'on') | map(attribute='entity_id') | list }}
#

Then you have all you need for the trigger and to determine which entity caused it

static orchid
#

Ok It turns out it still doesnt work

template:
  - binary_sensor:
    - name: "Washer Status"
      state: >
        {%- if states('sensor.washer_current_power') >= 5 -%}
            on
        {% else %}
            off
        {% endif %}

https://paste.debian.net/hidden/90ea33de to see the other two sensors that I experimented with to show that the above should work
"Washer Watts" and "Jinja Test" both work, but "Washer Status" doesn't work. Why?

marble jackal
#

And states are strings, so you need to convert that to a number using the float filter

static orchid
#

thank you

marble jackal
#

This returns true or false which is what the binary sensor template expects

lapis quarry
#

ok i need to go out 30 min, when i get back will test your code and take it from there, I would like to avoid modifing my templates to much, i have a few other templates a lot more complex and convoluted that are constructed in the same fashion that throw a lot more of these errors (this is the simplest template of all so i thought i would start here)

marble jackal
#

You need quotes around the template

#
  - platform: template
    sensors:
      Low_battery_count:
        friendly_name: Low Battery count template
        value_template: "{{ states.binary_sensor | selectattr('entity_id', 'match', '.*batt') | selectattr('state', 'eq', 'on') | list | count }}"
        attribute_templates:
          entities: "{{ states.binary_sensor | selectattr('entity_id', 'match', '.*batt') | selectattr('state', 'eq', 'on') | map(attribute='entity_id') | list }}"
lapis quarry
#
Invalid config for [sensor.template]: extra keys not allowed @ data['attribute_templates']. Got OrderedDict([('entities', "{{ states.binary_sensor | selectattr('entity_id', 'match', '.*batt`) | selectattr('state', 'eq', 'on') | map(attribute='entity_id') | list }}")])
invalid slug Low_battery_count (try low_battery_count) for dictionary value @ data['sensors']. Got OrderedDict([('Low_battery_count', OrderedDict([('friendly_name', 'Low Battery count template'), ('value_template', "{{ states.binary_sensor | selectattr('entity_id', 'match', '.*batt`) | selectattr('state', 'eq', 'on') | list | count }}")]))]). (See ?, line ?).```
marble jackal
#

Oh sorry, indentation

#

Fixed

lapis quarry
#

still same error πŸ€”

marble jackal
#

Fixed it a second time

lapis quarry
#

yes i noticed πŸ™‚

#

but still same error argg

#

fixed the capital letter and now i get the above

marble jackal
#

Got a backticks instead of a quote there

lapis quarry
#

after batt?

marble jackal
#

Yes

#

Fixed it in mine

lapis quarry
#

that did it πŸ‘

#

ok so just checked and this works now and counts the low batteries that are ON

marble jackal
#

Yes, that was the intention, and those entities should be listed in the attribute

lapis quarry
#

and shows the entities that they are also in the attributes

#

yes

#

now how do i trigger my template based on this sensor?

marble jackal
#

Just a simple state trigger

#

On the attribute if you want

lapis quarry
marble jackal
#

No, you'll have to rebuild it

#

But it will be a lot more resource friendly

lapis quarry
#

I´m not programmer, it took me hundreds of hours to come up with these templates, i have a bunch or more complex ones using the same method, I cant aford to rebuild them all 😭

#

Bear with me, im proud of them personaly, put a lot of effort making them, but also ashamed to share them.. lol IΒ΄m sure a programmer with good knowledge of HA might trow his hands up in the air because I screwed up a lot and maybe overcomplicated things, buy hey they work and do excatly what i want:

https://hastebin.com/rifidaxame.kotlin
https://hastebin.com/netaloqaxa.http

#

and back in the day everyone advised me to go the state_change route for what i wanted to do

#

(I just wanna get rid of the warning in the logs)

marble jackal
#

Check for is not none instead of != 'none'

#

none is not a string

lapis quarry
#

you mean here and new_state.status != 'unknown' and new_state.status != 'unavailable' and new_state.status != 'none' and new_state.entity_id != 'none' and new_state.object_id != 'none'

marble jackal
#

Yes

lapis quarry
#

will that change avoid the template becoming true which is what i have been trying in this section? precisely to avoid these errors

marble jackal
#

I think so, I'm on mobile so it's a bit cumbersome to review the entire thing

lapis quarry
#

LOL you guys dont stop amazing me, writing code on your phones, I need a few screens to make sense of anything 🀣

mighty ledge
#
               and new_state.status != 'unknown' and new_state.status != 'unavailable' and new_state.status is not none
               and new_state.entity_id is not none and new_state.object_id is not none
#

but entity_id and object_id will always be populated, so not sure why you have to check for those

marble jackal
#

The errors he posted indicated that

lapis quarry
#

just trying things out of desperation tbh

marble jackal
#

Which I found strange as well though

lapis quarry
#

but yeas as TheFes said i guided my self by the errors in the logs

mighty ledge
#

well it is coming from a state changed event, so many that event has some oddness to it

lapis quarry
mighty ledge
#

!= is 'does not equal'

#

is not none, is checking something different

lapis quarry
#

what should i use where?

mighty ledge
#

exactly what I wrote πŸ˜‰

lapis quarry
#

ok ill try πŸ™‚

lapis quarry
#

added your suggestion to all my state_change based templates, rebooted fine, i guess i just need to let it run a few days and see if errors have gone away

#

unless you know how i could test the change now with the developer tools and try to force these warnings

#

they have been happening randomly so I dont know how i can force them to happen

dusty grailBOT
#

To test an automation there's three stages you can follow. Testing the action, the condition and action, and the whole automation:

  1. Use Configuration -> Automations to find the automation and then push Run Actions. If this fails your problem is in the action: section, and details should be found in your log file
  2. Use Developer tools -> Services and call automation.trigger on the automation with skip_condition: false. If the first passes but this fails then the problem is in your condition: block
  3. Use Developer tools -> States to find the trigger entity, click the name, then change the state (at the top) to something that'll trigger the automation before pushing Set State. If this fails then the problem is with your trigger: section, or the automation is turned off (you can check that in Developer tools -> States).

You can also see this section in the docs and with HA 2021.4 onwards debug automations.

marble jackal
#

You could try 3)

#

But I'm not sure if that will cause a state changed event

#

Or create a trigger based template binary sensor which matches your filter criteria and use an input boolean as the trigger

lapis quarry
#

that is what i was playing around for a while cant seem to trigger it, i will just let ir run a few days and see πŸ˜‰

#

one more question, im upgrading an old install 2021 to current release and having this problem, i know i need tro set a default value if sensor not available but not sure how exactly:

marble jackal
#

You should use states() to get the state.

#

For the defaults there is an explanation in the pinned posts in this channel

#

But I would advice to use availability_template to check if your source sensors are providing a numeric value

lapis quarry
marble jackal
#

The availability_template should return true or false

#

And it's availability_template: not just availability:

#

availability_template: "{{ states('sensor.airconlr01a_current_power_usage') | is_number }}"

#

And you are not using states() everywhere. You only changed it in the if statement

#

If wait, you were already using it there

lapis quarry
#

like this?

#
value_template: "{% if states('sensor.airconlr01a_current_power_usage') | int(0) > 10 %} {{ states('sensor.airconlr01a_current_power_usage.state')| float*7) | round(2) }} {% else %} {{ states('sensor.airconlr01a_current_power_usage.state') | round(2) }} {%endif %}"
        availability_template: "{{ states('sensor.airconlr01a_current_power_usage') | is_number }}"
        unit_of_measurement: W```
marble jackal
#

Indentation seems off, but besides that it looks fine

#

Well, I would use the multi line yaml format for that state template

dull burrow
# lapis quarry ```yaml value_template: "{% if states('sensor.airconlr01a_current_power_usage') ...

if you type "yaml" then go to next sentence after the first three ` code block start then your code gets colored and easier to read like this: yaml value_template: "{% if states('sensor.airconlr01a_current_power_usage') | int(0) > 10 %} {{ states('sensor.airconlr01a_current_power_usage.state')| float*7) | round(2) }} {% else %} {{ states('sensor.airconlr01a_current_power_usage.state') | round(2) }} {%endif %}" availability_template: "{{ states('sensor.airconlr01a_current_power_usage') | is_number }}" unit_of_measurement: W

marble jackal
#
value_template: >
  {% if states('sensor.airconlr01a_current_power_usage') | int(0) > 10 %}
    {{ states('sensor.airconlr01a_current_power_usage.state')| float*7) | round(2) }}
  {% else %}
    {{ states('sensor.airconlr01a_current_power_usage.state') | round(2) }}
  {%endif %}
availability_template: "{{ states('sensor.airconlr01a_current_power_usage') | is_number }}"
unit_of_measurement: W
#

Took me a couple of times to get that right on mobile

lapis quarry
dull burrow
#

Shit

#

It ate my ` after each three lol

dusty grailBOT
#

To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks. Here's an example

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

For over 15 lines you must use a code share site such as https://dpaste.org/ (pick YAML for the language), http://pastie.org/ (pick YAML for the language), or https://paste.debian.net/ (pick YAML for the language).

marble jackal
#

Just add yaml directly after the backticks to format it as YAML

lapis quarry
#

got it thanks πŸ™

#
Invalid config for [sensor.template]: invalid template (TemplateSyntaxError: unexpected ')') for dictionary value @ data['sensors']['airconlr01a_current_corrected_power_usage']['value_template']. Got "{% if states('sensor.airconlr01a_current_power_usage') | int(0) > 10 %}\n {{ states('sensor.airconlr01a_current_power_usage.state')| float*7) | round(2) }}\n{% else %}\n {{ states('sensor.airconlr01a_current_power_usage.state') | round(2) }}\n{%endif %}\n". (See ?, line ?).```
marble jackal
#

That's not valid YAML 😜

lapis quarry
#

jaja yeah just testing your sugestion

marble jackal
#

What's your complete code for the sensor now?

lapis quarry
#

your last post

marble jackal
#

That's not the complete code

lapis quarry
#
  - platform: template
    sensors:
    
      airconlr01a_current_corrected_power_usage:
        friendly_name: AirConLr01a Current Corrected Power Usage
        value_template: >
          {% if states('sensor.airconlr01a_current_power_usage') | int > 10 %}
            {{ states('sensor.airconlr01a_current_power_usage')| float*7) | round(2) }}
          {% else %}
            {{ states('sensor.airconlr01a_current_power_usage') | round(2) }}
          {%endif %}
        availability_template: "{{ states('sensor.airconlr01a_current_power_usage') | is_number }}"
        unit_of_measurement: W```
marble jackal
#

You should remove .state after every entity_id