#templates-archived

1 messages ยท Page 49 of 1

wintry night
#

it may be easier to write a PR to the integration itself to fire events, or provide a catch-all device for these orphaned entities

inner mesa
#

they just added somethign like that

#

there's a config_entry_changed event, or something like that

#

again, requires a config entry

wintry night
#

my automation is triggered by entity_registry_updated -- i didn't think the integration was in the event data, but let me tripple check thanks for the reminder

#
    event_type: entity_registry_updated
    data:
      action: create
      entity_id: switch.cloud_alexa
    origin: LOCAL
    time_fired: '2023-07-28T15:46:02.152994+00:00'
    context:
      id: 01H6EJV9S8H3246CPWYM9MK519
      parent_id: null
      user_id: null
#

i'm not sure what the context is... but the data dict doesn't have what i need

inner mesa
#

oh, yeah, that ๐Ÿ™‚

wintry night
#

so.. that'd also be a sweet solution - if the event just had a bit more info

#

oh man, here's the solution:

{% set entity_id = "device_tracker.pihole" %}
{% set integration_name = "unifi" %}
{{ entity_id in integration_entities(integration_name) }}
#

thanks for your help and encouragement @inner mesa

inner mesa
#

yes, if you already know the integration

#

I was looking for a more general solution, rather than solving your problem ๐Ÿ™‚

wintry night
#

yeah, maybe i didn't give enough context! i just want to know if new entities are coming from a specific integration

inner mesa
#

given an entity_id, what integration did it come from?

grim flicker
#

Thanks this will help

undone jungle
#

Hi all,

Could someone please assist in understanding why a template sensor becomes NaN after many hours of normal performance. This is coupled with the fact that when I restart templates while they are NaN state, they come back up as normal

plain magnetBOT
undone jungle
#

`Ventilation power recovery
10 hours ago
Unavailable

Ventilation energy efficiency
11 hours ago
Unavailable
`

mighty ledge
#

the value is NaN or the entity is unavailable

undone jungle
#

NotANumber

mighty ledge
#

yes I know that

#

but NaN can only be produced by python when the math fails to calculate

#

so, is the actual state NaN or is it unavailable?

undone jungle
#

Sorry - Entity is currenly unavailable,

#

It sometimes showed up as entity is not a numerical output (or something to this effect).

mighty ledge
#

Then you need to revaluate your availability template

undone jungle
#

The problem is that as per template tester, I don't.

mighty ledge
#

The only way you can get a non real number w/ those templates is if it falls into the else case, which you don't have

undone jungle
#

I agree, but what is strange is that the template tester is working just fine while at the same time the entity is unavailable

mighty ledge
#

I.e. is_state('binary_sensor.ventilation_bypass', 'on') and is_state('binary_sensor.fan_operational', 'off')

undone jungle
#

All the availability criterions are met

mighty ledge
#

once it goes unavaialbe, it won't come back with that error

#

so fix your else statements

#

that error will also cause the entity to go unavailable

#

so, it's either your avail template or that missing else clause

#

and you're saying that the availibility is correct, so it's your else clause

#

that will also remove the errors in your logs

undone jungle
#

Would you mind having a look at it. I don't think I am missing a combination of conditions.

mighty ledge
#

you are, i just explained what you're mssing

#

if this case happens is_state('binary_sensor.ventilation_bypass', 'on') and is_state('binary_sensor.fan_operational', 'off')

#

you will supply the template sensor with no value

#

that's just 1 that I found

#

I'm sure there's others

#

just put an else statement with a default output for those cases

undone jungle
#

But that combination is impossible. It can't have an open bypass while the unit is off.

#

The bypass would not have the power to open, so it must be getting some false states then.

mighty ledge
#

HA is async, and templates resolve quickly, A momentary state change could be happening

#

that's why you always CYA

undone jungle
#

The else goes inside the endif statement chain or beyond it??

mighty ledge
#

Yep that looks correct

#

You can probably get rid of all those other elifs because they all just output 0

undone jungle
#

I'll consider it, but I also like seeing the logic as I read through the templates

#

Even if its a bit cluttered.

#

Thank for help @mighty ledge, but that unfortunately is not it. With else the entities are still unavailable in HA, even after template entity restart, but the template is returned correct values in the tester.

mighty ledge
#

Can you post your actual config and not an image of it please

mighty ledge
#

I want it with your changes

undone jungle
#

Aaa..sorry. Just added the else. Give me a sec

plain magnetBOT
mighty ledge
#

Also, how are you including those

plain magnetBOT
undone jungle
#

Not sure I understand?

#

They are in the configuration under sensor:

inner mesa
#

this part isn't going to help:
and states('sensor.incoming_air_temperature')

#

it's probably always true

mighty ledge
#

Theyโ€™re in the wrong section if they are in sensor

inner mesa
#

and yeah, they're templates

undone jungle
#

I just did a test and changed one of the is_state statements from (name of the sensor, on) to the same without a space in front of on and the sensors returned

#

template:
sensor:
- etc.

undone jungle
undone jungle
#

I don't get it. I've done this now three days in a row, where I think I see a small typo, which is an additional space, or something, and that is why these two sensors stop working. I change it and the sensors are back. 10 hour later they are unavailable again, and persist as unavailable, even though they work in the template tester just fine.

#

I did absolutely nothing to make it become unavailable, but it does and then doesn't recover. If I make mostly any small change, save the file and restart templates, it's back up again.

#

It happens only for these two templates.

mighty ledge
#

The only things that would cause that is source sensors going unavailable or you populating the state with an empty value by not having an esle clause

#

nothing else

undone jungle
#

They are all present.

mighty ledge
#

then it's the else clause

undone jungle
#

I've added the else state now and let's see tomorrow.

#

Could you please confirm the else is where it should be in both sensors?

mighty ledge
#

yep, looks good

#

personally, I think your templates need to be reworked

#

the way you code makes it hard to read

#

also, i'm not sure why you have this in your availability template is_state('binary_sensor.fan_operational', 'on')

undone jungle
#

I am very much selftaught and without any formal training, so whatever I pick up as bits and pieces I incorporate... kind of like Orc Whaaa! ๐Ÿ˜‰

undone jungle
mighty ledge
#

ok, then what's the point of checking it in your state template

#

that's what I mean by "the way you code"

#

you're making it unecessarily complicated

#

it makes it harder to read and harder to follow

#

your code should only highlight the paths you care about

#

e.g.

{% set strumienN = states('sensor.air_supply_flow') | float %}
{% set tcz = states('sensor.incoming_air_temperature') | float %}
{% set tn = states('sensor.room_supply_temperature') | float %}
{% if is_state('binary_sensor.ventilation_bypass', 'off') and is_state('switch.open_windows', 'off') %}
  {% if tcz < tn %}
     {{ (((tn - tcz) * strumienN * 1200) / 3600) | round(2) }}
  {% else %}
     {{ ((((tn - tcz) * strumienN * 1200) / 3600) * -1) | round(2) }}
  {% endif %}
{% else %}
  0
{% endif %}
#

much easier to read and understand what's happening

undone jungle
#

Fair point, I won't lie, this looks much simpler. Won't removing all the additional information (such as the fact temperature comes as float,etc.) make it much less robust?

marble jackal
#

Can't you just use | abs instead of the nested if?

#
{% set strumienN = states('sensor.air_supply_flow') | float %}
{% set tcz = states('sensor.incoming_air_temperature') | float %}
{% set tn = states('sensor.room_supply_temperature') | float %}
{% if is_state('binary_sensor.ventilation_bypass', 'off') and is_state('switch.open_windows', 'off') %}
  {{ (((tn - tcz) * strumienN * 1200) / 3600) | abs | round(2) }}
{% else %}
  0
{% endif %}
mighty ledge
mighty ledge
undone jungle
undone jungle
# marble jackal Can't you just use `| abs` instead of the nested if?

Need to look this over when in front of a monitor but indeed sound like this could be further simplifying things. If the outside temperature differential is the only determinant which later gets converted to a positive output., then using an absolute number should be enough

rare linden
#

the switch isnt showing up in entities

rare linden
#

I've looked at that but the templating seems to be slightly different when included

same with the other stuff that's included in the other files doesn't match that type they show in the configuration example but the other stuff works

marsh cairn
#

It needs to be in switch with platform template, not in template

rare linden
#

ah, so if i wanted to include it would basically be?
switch:

  • platform: template
    switches: !incldue blah;

will give that a try, thanks

#

bah discord messed up the syntax

#

yeah that got the dev tools seeing it when i did check config, thanks

floral shuttle
#

Template loop detected while processing event: <Event state_changed[L].. that is new to me: {% set period = states('input_number.lightning_strikes_period')|float %} {% set ns = namespace(count=0) %} {% from 'lightning.jinja' import strikes %} {%- for s in strikes().split(',')|reject('eq','') if states[s].last_updated > now() - timedelta(hours=period) -%} {% set ns.count = ns.count + 1 %} {%- endfor %} {{ns.count}}

#

and when entered in dev tools template does not tjhrow an error

#

unless its the attribute to coin the phrase: {% set period = states('input_number.lightning_strikes_period')|float %} {% if this.state|int(default=0) != 0 %} {% from 'lightning.jinja' import strikes %} {%- for s in strikes().split(',')|reject('eq','') if states[s].last_updated > now() - timedelta(hours=period) -%} {{'Inslagen om: ' if loop.first}} {{-as_local(states[s].last_updated).strftime('%H:%M')}}{{', ' if not loop.last}} {%- endfor %} {% else %} Geen inslagen de afgelopen {{period}} uur {% endif %}

#

but that shows a correct list of times too, so I am at a loss really what to check for that Warning to go away

silver rose
#

So 'return' isn't valid here. Is there a way that doesn't involve fetching from states() 6 times?
value_template: >
{%
set aqi = states('sensor.air_quality_index')|float(0)
if (aqi >= 300) return "darkred"
if (aqi > 200) return "purple"
if (aqi > 150) return "red"
if (aqi > 100) return "orange"
if (aqi > 50) return "yellow"
return "green"
%}

#

And am I the only one who has Studio Code Server get stuck in some mode where it thinks hitting enter means 'find next' instead of insert newline? I wind up having to switch to something else in sidebar and back to get out of it.

#

Can't get it to accept this either.
value_template: >
{{
set aqi = states('sensor.air_quality_index')|float(0)
"darkred" if (aqi >= 300) else
"purple" if (aqi > 200) else
"red" if (aqi > 150) else
"orange" if (aqi > 100) else
"yellow" if (aqi > 50) else
"green"
}}

inner mesa
#

You need to write valid Jinja

haughty breach
#
value_template: >
  {% set aqi = states('sensor.air_quality_index')|float(0) %}
  {% if (aqi >= 300)%} darkred
  {% elif (aqi > 200) %} purple
....
silver rose
#

I read that it was not possible to set a variable inside a block and have it show up outside the block.

haughty breach
#

That's the same block...

silver rose
#

The first %} doesn't end the block introduced by the first {% ?

haughty breach
#

No, the next YAML key would start a new "block"

silver rose
#

Oh. Wasn't clear from what I read exactly what a block was so I made a wrong assumption.

grand quarry
mighty ledge
marble jackal
#

Also, devtools doesn't show warnings, there is probably a warning in the log though

fast mason
#

Hello template gods, does anyone have an automation based on their sensor.mobile_app_next_alarm entity? My template for it recently started getting triggered everytime I plug in my phone to charge

#

Keep getting startled everytime I go to bed from the music ๐Ÿ˜‚

plain magnetBOT
#

Sadly we're not mind readers (any more anyway, not after the last time we tried). Please share the YAML and any errors so we can see what you've done.

marble jackal
#

๐Ÿ˜œ

fast mason
#

I was writing the yaml! You're too fast

#
{{now().strftime('%a %h %d %H:%M %Z %Y') == (((state_attr('sensor.thanasis_next_alarm', 'Time in Milliseconds') | int / 1000) ) | timestamp_custom('%a %h %d %H:%M %Z %Y'))}}
#

took this from somewhere obviously. I'n not good enough with (time) templates

marble jackal
#

I'm waiting for my barber appointment btw, so if I stop responding it was my turn

#

I don't see an obvious reason why this would trigger when you start charging your phone

fast mason
#

Also somehow my entity in HA and my actuall alarm has a 1h difference ๐Ÿ˜ฅ

#

see just plugged it now

marble jackal
#

That's because of timezones, one is probably in UTC

slate flame
#

Hi is there any solution to iterate through the whole media_player domain without creating a group by hand?

marble jackal
#

Is your next alarm at that time?

#

Is that a template sensor, or just the sensor provided by the companion app

inner mesa
fast mason
#

now that is the time I plugged the phone in, and every time I plug in the phone it changes to the now time

#

and now it changes back

#

only that my alarm is at 7:15 instead

#

๐Ÿ™ƒ

#

try explaining that hahaha

#

but template looks OK right? so the problem is with the mobile app integration, not a template issue

marble jackal
#

So the companion app sensor changes to the current time when you start charging and then changes back

#

Or file a bug report

#

Template does what it should do

floral shuttle
slate flame
floral shuttle
#

In fact it it happened once.

slate flame
# inner mesa What do you want to list?

got it ๐Ÿ˜„ {% for item in states.media_player %}
{% if item.state | lower == 'playing'%}
{% if 'Emby' in item.attributes.friendly_name %}
{{item.attributes.friendly_name}}
{% endif %}
{% endif %}
{% endfor %}

#

thank you ๐Ÿ˜„

mighty ledge
mighty ledge
floral shuttle
haughty breach
mighty ledge
marble jackal
slate flame
#

if have now {% for item in states.media_player %}
{% if item.state | lower == 'playing'%}
{% if 'Emby' in item.attributes.friendly_name %}
{{item.attributes.media_title}} auf {{item.attributes.friendly_name}}
{% endif %}
{% endif %}
{% endfor %}

marble jackal
#

No, then you need to use a loop

#

Btw, there is no need for the lower filter

fast mason
#

Thanks for the hint

#

Still need to workout the issue with the time changing when I plug the phone though. SO weird! Aha! Package: com.miui.securitycenter

slate flame
undone jungle
#

First it was non-numerical and a minute later unavailable

#

If I make any change in the syntax, save the file and reboot templates, it will be back up.

#

Even if this change is completely inconsequential and changed back will work just fine as well

mighty ledge
#

can you post the errors from the logs

#

non-numerical means it will never come back

#

also post the history of all input devices at that moment in time

undone jungle
#

There isn't anything in the logs concerning this entity, nor can I find anything related to templates

mighty ledge
#

... that's impossible if you're saying 'non-numerical'

#

so you aren't telling the truth about one thing or the other

undone jungle
#

There is a modbus error, and these are mostly values from modbus (i.e. HVAC unit via modbus):
Logger: homeassistant.components.modbus.base_platform
Source: components/modbus/base_platform.py:350
Integration: Modbus (documentation, issues)
First occurred: 21:14:51 (147 occurrences)
Last logged: 21:22:03

Unexpected response from modbus device slave 11 register 4224, got 0x a

mighty ledge
#

where are you getting this 'non numerical' crap from?

#

that's what I want to see

#

I don't want to see your version of that message, I want to see the message

undone jungle
mighty ledge
#

my man

#

don't look at the UI for states

#

use history

#

that's a message from that particular gauge

#

Do me a favor, go to your history, throttle the time to 10 minutes before and 10 minutes after the event

#

select all 5 entities that make up the template sensor and the entity itself

#

and post that image

undone jungle
#

Both gaps are HA reboots

#

After the second there is a brief lack of response from the 'operation' binary sensor, but this should be captured by else, I suppose.

mighty ledge
#

I only see 2 values? Didn't the template have 3?

undone jungle
#

Efficiency is the output, two temperatures are inputs. There may be a flow as well, let me see

mighty ledge
#

can you post which template we are talking about right now

#

with your current config

plain magnetBOT
undone jungle
#

I'll correct the graph with the additional variable, just a sec

mighty ledge
#

thanks

undone jungle
#

That is all of them

#

After the unit boots up, the values are streaming but the template doesn't come back up.

#

This started on 2023.07, or at least never happened before very recently

#

It looks like as if the 'fan.operation' sensor being off or unavailable as the unit boots up brings the template down and it never recovers.

mighty ledge
#

well, like i said before, I don't know why you have that in unavailable

#

personally, I'd just have 0 when the fan was off

#

and I wouldn't care about the state of the ventialtion bypass either

#

all that matters is that you have numbers for your values, the template can cover the rest.

#

you also don't really have a safety net in your code

#

if t1 and t3 are the same value, you'll divide by zero

#

that will cause an error

#

this is what I would use

#
      - name: Ventilation energy efficiency
        unique_id: recu_energy_efficiency
        icon: mdi:percent
        device_class: percent
        unit_of_measurement: %
        state: >
          {% set t1 = states('sensor.incoming_air_temperature') | float %}
          {% set t2 = states('sensor.room_supply_temperature') | float %}
          {% set t3 = states('sensor.room_exhaust_temperature') | float %}
          {% if is_state('binary_sensor.ventilation_bypass', 'off') and is_state('binary_sensor.fan_operational', 'on') and is_state('switch.open_windows', 'off') and t1 != t3 %}
            {% set output = (t2 - t1) / (t3 - t1) * 100 %}
            {{ ([ 0, output, 100] | sort)[1] | round(2) }}
          {% else %}
            0
          {% endif %}
        availability: >
          {{ [
                'sensor.incoming_air_temperature',
                'sensor.room_supply_temperature',
                'sensor.room_exhaust_temperature'
             ] | map('states') | select('is_number') | list | length == 3 }}
#

there should be no risk of failures with that.

undone jungle
mighty ledge
#

and you could simplify the first 3 lines to

#
          {% set t1, t2, t3 = [ 'sensor.incoming_air_temperature', 'sensor.room_supply_temperature', 'sensor.room_exhaust_temperature' ] | map('states') | map('float') | list %}
undone jungle
#
  1. Won't the above go to zero every time the t1 = t3 which is bound to happen as the night/day cycle progresses? This will result in some efficiency and a zero in between, with the same being true for the other template for power.
mighty ledge
#

yes

#

but it's simple math man

#

that makes your denomiator 0

#

you can't divide by 0

#

that's a math rule

#

can't get around that

undone jungle
#

I know that right now there would be a divide by zero error, technically, but it doesn't show up in the date, for some reason. Hence, even though through ignorance, that is preferable

mighty ledge
#

no it's not preferable

#

dividing by zero will make that error

#

see the red error?

#

that means your entity would not come back

#

if you want a rock solid template, you account for everything, you don't ingore things because you like them a certain way

undone jungle
#

I am not disagreeing with you, but this specific failure mode just doesn't happen for some reason. Either they never synch perfectly and jump over an identical temp somehow or IDK.

mighty ledge
#

well, you should account for it regardless

undone jungle
#

I'll try it out, though if accounting for it means having additional zeros messing up other calculations, I'll have to look for another way. I am very sorry if it sounds as if I don't appreciate your input. That is not the case - just trying to be pragmatic about down the line information storage.

mighty ledge
#

I think you're over thinking it

undone jungle
#

That's just the way I am... lol

mighty ledge
#

you're having problems, but you're not willing to account for them and you're making your templates extremely hard to manage and read

marble jackal
#

I think you're thinking he's overthinking it

mighty ledge
#

too much thinking going on

undone jungle
#

I believe there isn't device_class: percent. It's giving an error

#

I've found fixed the other which is % must be in parentheses.

plain magnetBOT
plain magnetBOT
undone jungle
#

I've also added device_class: power here after I posted, for the long term statistics

#

Let's see what happens over the next 24h

#

๐Ÿคž

#

There is one last issue I'll have to resolve which is what happens when the unit is turned off via the software switch.

#

This means the temperatures will still be reported, but this will be stale air that will produce nonsense values for both power and efficiency.

#

I'll probably modify the availability to include it somehow, though it's risky once again, that it will get confused when HA is rebooting and modbus is not yet up....

edgy flume
#

Template friends - can I get a sanity check? Traces gives me the following error: Choose: Option 2 executed

Stopped because an error was encountered at July 29, 2023 at 6:11:11 PM (runtime: 0.03 seconds)

not a valid value for dictionary value @ data['entity_id']

plain magnetBOT
cerulean cipher
#

posting the template in question would help

#

ahhh there it goes

edgy flume
#

Sorry - slow in copy-pasting

cerulean cipher
#

which must be really slow because my internet is provided by pigeons

#

๐Ÿคช

edgy flume
#

let me know if you'd like to see the script too - but the script is working fine (I get its notifications without issues)

inner mesa
#

media_player doesn't appear to be defined

edgy flume
inner mesa
#
      playing_media_players: >-
        {{ expand('media_player') | selectattr('state', 'eq', 'playing') |
        rejectattr('entity_id', 'eq', 'media_player.office') |
        map(attribute='entity_id') | list }}
#

That

edgy flume
#

You're right. Ah - okay now I'm all confused - I wonder if it was supposed to expand the speaker groups I created under helpers for the script.

inner mesa
#

Did you write that?

edgy flume
#

No, I'm getting help from the unthinkable.

#

I did write the script though, with help from here.

inner mesa
#

Good luck

edgy flume
#

Thanks.

cerulean cipher
#

RobC

dry narwhal
#

Good morning everyone
any chance of modifying my template to show me the device name instead of id?

{{ integration_entities('tasmota') | map('device_id') | unique | list }}
#

I was thinking of wrapping device_attr around it but it does not seem to work for a list)

{{ device_attr(integration_entities('tasmota') | map('device_id') | unique | list,  name_by_user) }}
inner mesa
#

{{ integration_entities('insteon')|map('device_attr', 'name')|list }}

dry narwhal
#

So simple! Thank you ๐Ÿ™‚

dry narwhal
#

I am trying to only list those devices that are available and played with has_value. Cannot seem to get it right though.

{% if has_value(integration_entities('tasmota')) %}
{{ integration_entities('tasmota') | map('device_attr', 'name') | unique | list | count }}
{% endif %}

Returns AttributeError: 'list' object has no attribute 'lower'

Of course a one-line would be nicer, but I couldn't get that to work ({{ has_value(integration_entities('tasmota')... either ๐Ÿ˜ฆ

dry narwhal
#

Also no luck with
{{ integration_entities('tasmota') | rejectattr('state', 'in', ['unavailable', 'unknown']) | map('device_attr', 'name') | unique | list | count }}
UndefinedError: 'str object' has no attribute 'state'

#

Nope

{% set devices = integration_entities('tasmota') | map('device_attr', 'name') | unique %}
{{ devices | rejectattr('state', 'in', ['unknown', 'unavailable']) | list }}
willow wing
#

{{ is_state_attr('sensor.dwd_weather_warnings_stadt_xxxxxx_current_warning_level', 'warning_1_parameters')['gusts'] | replace('<', '') | replace('[km/h]', '') > 59 }}

why this template are not working, someone can help?

lyric comet
#

You are comparing a number to a string

willow wing
#

can you assit me? dont know how i can change these

#

i need it as a trigger in an automatisation

marble jackal
#

You need to look at what to use where, you are mixing filters to be used on state objects with filters to be used on entity_ids

dry narwhal
marble jackal
#

integration_entities() returns entity ids, not state objects

spark vortex
spark vortex
#

yeah, I tried that but get this error: Invalid config for [template]: [sensor] is an invalid option for [template]. Check: template->sensor.

#

sensor is under id at same level of platform

marble jackal
#

There is no platform in the template integration

#

share the whole thing

spark vortex
#

what I pasted is the content of templates.yaml that I include with template: !include templates.yaml

#

without "sensor" it works, or better I dont get any arror, if I add sensor after each id: , I start to get that error

marble jackal
#

sensor is under id at same level of platform

There is no sensor, nor platform in that code you shared

spark vortex
#

let me paste it with sensor

marble jackal
#

template expects a list, you're providing a dictionary. You should start with a hyphen.
That will also allow you to put sensor on the and level as trigger, where it belongs

spark vortex
#

nut if I put on the same level of "trigger" how can I create multiple sensor per platform?

#

I need onw per each patform

inner mesa
#

there's an example in teh docs

spark vortex
#

yes, but the example is with one entry under trigger, if I have more and I need a sensor for each?

#

how the indention would be?

marble jackal
#
template:
  - trigger:
      - platform: event
    sensor:
      - name: trigger based sensor 1
      - name: trigger based sensor 2
  - trigger:
      - platform: event
    sensor:
      - name: trigger based sensor 3
  - sensor:
      - name: state based sensor 1
inner mesa
#

like the example

spark vortex
#

yes, this is a sensor for the same event, I have multipl events under the same trigger

#

so I need to create a sensor per event

#

not multiple sensor for the same event

#

ah, I can have multiple trigger

inner mesa
#

then use the ids you created

spark vortex
#

ok, makes sense, thanks

marble jackal
#

Yes, because it is a list

spark vortex
#

right

#

and how can I print out somewhere the content of this? trigger.event_data.args[0] , I don't know what it contains so I can't be sure that I am assigning the right value to the sensor

#

can I print it in dev tool somewhat

marble jackal
#

Listen to the event in devtools > events

spark vortex
#

yes, I see the raw event in yaml

#

but how can I get the parsed one in the trigger?

inner mesa
#
  1. Just make it the state
  2. Make an automation that uses persistent_notification.create
spark vortex
inner mesa
#

but if you simply look at the event in devtools -> Events, you get the whole structure

spark vortex
#

yes, I get the whole structure before the trigger parsing

#

I need it after

inner mesa
#

ok

spark vortex
#

in the trigger I filtered out a lot of not needed things

inner mesa
#

then do one of the things I suggested

spark vortex
#

how?

marble jackal
#

trigger.event gives the whole event

spark vortex
#

(sorry if I ask too much, I am not expert yet ๐Ÿ™‚ )

#

yes, how can I print it?

marble jackal
#
  - platform: event
    event_type: dahua_event_received
    event_data:
      name: Dahua
      Code: CrossLineDetection
      action: Start
      data:
        Object:
          ObjectType: Human

This will most likely not trigger from my experience. Best to do the test in the state template

spark vortex
#

uhm, how if the sensor/entity is not created yet?

mighty ledge
#

events don't requires entities

spark vortex
#

in the state templace I can print out the content of a sensor/entity, but how can I print the content of my trigger.event_data

#

what I built here https://pastebin.com/WUTpNuM6 is a selection of what I need from a raw event that I see in the event dev tool, so now I have my filtered data in trigger.event_data.args[0], correct?

#

how can I show it?

mighty ledge
#

sorry, i just jumped in here

#

If your dahua creates events, then you have to listen to the events and build your triggers off them

spark vortex
#

this is what I am trying to do

mighty ledge
#

ok, well, you've yet to post your event

#

you've only posted what you think it looks like

spark vortex
#

ah, you need the raw event generated?

#

let me do it

mighty ledge
#

... yes

#

you can't make an event trigger without knowing what the event looks like

spark vortex
#

this is an example

#

I just need to create a sensor/entity out of these kind of events

#

the vent structure is the same, they change just a couple of fields

mighty ledge
#

well, from what I can tell your triggers are wrong

#

unless you have a camera named dahua

#

but you have name: dahua in all of those, but the name is garage.

#

seems like your indentations are correct, so if you have a dahua camera then it would work

spark vortex
#

yes, it is

#

well, the name is not dahua, but in this event is "garage"

#

and I have others too, but the strucutre is the same

#

so, the name in my trigger probably is wrong, I have to create it for each cameras, with the right name?

#

that is fine, I can do it, but now, from what I have, how can I add the sensor creation there?

mighty ledge
#

you can just omit values

#

you don't need to have it rigidly find the event data

#

you can have it trigger off any event and then you perform actions using the event data in your messages

spark vortex
#

yes, but I need to create a sensor per camera

mighty ledge
#

then you have to make sure your data matches

#

i.e. dahua is not correct

#

garage is

spark vortex
#

yes, so changing the name it should

#

yes, correct

#

first thing now: how can I test that my trigger is correct?

#

second how can I build a sensor out of it?

mighty ledge
mighty ledge
#

robc already linked the docs for making the trigger based sensors

spark vortex
mighty ledge
#

why do you need to know that

#

make an automation if you want to see it happen live with a gui

spark vortex
#

to know if my trigger is parsing the data correctly

mighty ledge
#

looking back these suggestions were already given to you

spark vortex
#

I will check that, and what about the content of trigger.event_data.args[0], can I print it somewhere?

mighty ledge
#

so, either listen to the events, or make an automation that shows the 'trigger'

mighty ledge
spark vortex
#

what I dont unerstand is where can I get it, is there a "trigger console"? ๐Ÿ™‚

mighty ledge
#

Sorry, rob said it, not thefes

#

there is no trigger console

#

anyways, rob detailed what to do

spark vortex
#

ok, I will re-read all the msg carefully and try it, thanks all anyway

marble jackal
#

Automations are more easy to debug, you can create an automation with the same trigger and maybe just delay: 0 as the action and see the whole event in the trace

spark vortex
#

yep, I will try this method

marble jackal
#

Or send it in a notification as Rob proposed

spark vortex
#

thanks

dense patio
#

I've got a template sensor that calculates distance between two entities and it only shows the history bar, not a statistic graph

#

how can I change the type of the sensor?

inner mesa
#

Add a unit_of_measurement

dense patio
#

Ah, that was probably obvious

#

thank you

inner mesa
#

Documented, but not necessarily obvious

spark vortex
#

hi again, so I followed your suggestion, so I created the automation with action persistent_notification.create, but probably the trigger is not correct and the notification never happen, so now I am trying to debug the trigger itself, but I don't see any log about that to throubleshouting

#

even the sensor has been created, but of course it never been updated, probably for the same reason

marble jackal
#

So what's your trigger

spark vortex
#

(the raw event contains name: Garage, but I also have name: Giardino)

#

it seems that the trigger is not catching the event, but no logs to confirm this

marble jackal
#

It won't work like this, you can't provide partial information of a key from the event_data in the trigger

#

You need to provide the whole value

#

So it's better to check on it in a condition (in case of an automation) or in the state template in case of a template sensor

spark vortex
#

what do you mean with the whole value? I added the fields that I need to filter, the rest of data in the whole event is not important for me

#

I probably dont even need all of them, just the name, the ObjectType and the action, for filtering what I need

marble jackal
#

Your trigger will now fire when data exactly matches:

Object:
   ObjectType: Human
#

It will never do that as the data key contains a lot more information

#

So you need to check on the ObjectType after the trigger, not in the trigger

spark vortex
#

can you please provide an example? I dont get it, I need the trigger when ObjectType is "Human", this field can also contain different values yes, but I just need when it is = 'Human'

marble jackal
#
trigger: 
   - platform: event
     event_type: dahua_event_received
     event_data:
       name: Giardino
       Code: CrossLineDetection
       action: Start
     id: giardino_human
  condition:
    - "{{ trigger.event.data.data.Object.ObjectType == 'Human' }}"
  action:
    service: persistent_notification.create
      data:
      message: "my giardino human test"
      title: "dahua human giardino"
spark vortex
#

this is odd, I was not aware that I need to filter for ALL the possible fields under data to make it works, I was thinking that it is possible to filter also for only the fields that I want

#

@marble jackal no notifications, no errors, nothing is happening

mighty ledge
#

Check your trace to see if it triggered

spark vortex
#

where?

#

one of the sensor that is generated by the dahua integration triggered, so the event happened

mighty ledge
#

In the automation trace section.

spark vortex
#

ah ok, let migrate it to the UI editable one

mighty ledge
#

you don't need to, just add id: alkdjflaksjdflkjlskjfd

spark vortex
#

no trace found, it means that the trigger is not catching the event?

mighty ledge
#

That would be correct

#

keep in mind, Ive never seen your events have the name that matches your trigger

#

your events are all Garage

spark vortex
#

let me get one with the exact name

mighty ledge
#

Also, you have CrossLineDetection or CrossRegionDetection

#

The only thing that seems correct is Start

spark vortex
#

just triggered one

mighty ledge
#

Your trigger is CrossLineDetection and your event was CrossRegionDetection

#

it's gotta match exactly.

#

if you want both, it needs to be in the condition.

#

or you have to duplicate your trigger.

spark vortex
#

ah, let me fix that

#

how can I have both in the same trigger?

mighty ledge
#

you can't

spark vortex
#

so I have to create another trigger for it?

mighty ledge
spark vortex
#

what I meant how can I check something like: Code: CrossRegionDetection | CrossLineDetection ?

mighty ledge
#

my guy

#

I really think you don't read my responses

#

let me copy and paste what I wrote again that answers that question

spark vortex
#

ah in the condition, ok

#

ok, it is triggering now

mighty ledge
#

If you want to create your template sensors with the object detection & logic applied to all cameras, I suggest an automation with a custom event.

spark vortex
#

uhm, I was thinking to use something like this in the state: under template sensor {{ trigger.event.data.data.Object.ObjectType == 'Human' and trigger.event.data.data.action == 'Start' }}

#

but the logic will be more complex if I need to check for 'Stop' too

#

can you please provide an example of an automation with custom event?

mighty ledge
#
  alias: Dahua Camera Event Translator
  id: Dahua_Camera_Event_Translator
  mode: parallel
  max: 25
  trigger: 
   - platform: event
     event_type: dahua_event_received
  action:
  - event: dahua_translated_event
    data:
      name: "{{ trigger.event.data.name }}"
      detection: "{{ trigger.event.data.Code in ['CrossLineDetection', 'CrossRegionDetection'] }}"
      type: "{{ trigger.event.data.data.Object.ObjectType }}"
      action: "{{ trigger.event.data.action }}"
#

That will create a custom event that just has the data you care about.

#

then your triggers will be

spark vortex
mighty ledge
#

hold on a sec

#

then your trigger will be:

- platform: event
  event_type: dahua_translated_event
  data:
    name: ...
    detection: True
    type: ...
    action: ...
#

That automation will work for all cameras and all events

spark vortex
#

and the new sensors?

mighty ledge
#

and the new sensors will use the translated event as the trigger

#

you just have to fill the sensor triggers out with the information you want to capture

spark vortex
#

ah ok, in the template for platfrom event that I created

#

[homeassistant.components.automation] Automation with alias 'Dahua Camera Event Translator' could not be validated and has been disabled: extra keys not allowed @ data['action'][0]['data']. Got {'name': '{{ trigger.event.data.name }}', 'detection': "{{ trigger.event.data.Code in ['CrossLineDetection', 'CrossRegionDetection'] }}", 'type': '{{ trigger.event.data.data.Object.ObjectType }}', 'action': '{{ trigger.event.data.action }}'}

marble jackal
#

data needs to be event_data

spark vortex
marble jackal
spark vortex
#

ah under action?

#

yes, it works now!

mighty ledge
#

oops, my b

spark vortex
#

thanks

inland peak
#

Hello, I need some help writing a template condition that compares two attributes from the same sensor

#

basically, I have a "climate.bedroom_TRV" entity that lists the TRV's operating modes if called directly and "set_temperature" and "current_temperature" as attributes and I don't know how to tell the template to use the attributes instead of just the direct value

inner mesa
#

With state_attr

#

There's a whole section in the templating docs

inland peak
#

I have zero knowledge of templating or yaml and I'm trying to use what I can find online

#

this is a template I have that seems like it should do what I need, but I have no idea how to add "state_attr" in it

#

{{ states('climate.bedroom_trv') | float < states('climate.bedroom_trv') | float + 1 }}

inner mesa
#

You're already using states()

#

Use state_attr instead

inland peak
#

ok, so where do I go from there?

#

ah

inner mesa
#

I suggest reading that section in the docs

inland peak
#

so, whould this be correct then?
{{ state_attr('climate.bedroom_trv', 'current_temperature') | float < state_attr('climate.bedroom_trv', 'temperature') | float + 1 }}

#

I need it to compare "current_temperature" with "temperature" and only act if the difference between the two is larger than 1 degree

pastel moon
#

Can an area somehow be used as an entity? I want to add an area's lights to a history card. Or must I rework that somehow?

inner mesa
inner mesa
inland peak
#

"current_temperature" can list values along the lines of 25.1 degrees, so I figured that adding the |float should help with the decimals

inner mesa
#

it doesn't do anything with that

#

it's only needed if you want to turn a string into a float

pastel moon
inland peak
#

so the info I found was wrong. Can you please link me to the correct documentation?

inner mesa
#

not sure what you're looking for

#

that's just the way it is - if you have a string that represents a numeric value and you want a float, use |float, preferably with a default like |float(0)

#

If you already have a float, you don't need it. Since attributes can retain their native type (unlike states, which will always be strings), numeric values in attributes are probably already the proper type

inland peak
#

I see. Thank you for the explanation.

#

Final question then, how can I eliminate the decimal point from the value?

inner mesa
#

use |int to just truncate/chop it off or |round(x), wehre x is the number of decimal places to round to

inland peak
#

Thank you very much.

#

The template seems to be working as intended now.

pastel moon
#

Something like this? {{ expand(area_entities('kitchen')) | selectattr('domain', 'eq', 'light')|map(attribute='entity_id')|list }}

#

or can it be done more efficient?

inner mesa
#

that's a lot of work for just {{ area_entities('kitchen') }} ๐Ÿ™‚

pastel moon
#

Agreed

inner mesa
#

ah, you just want lights

pastel moon
#

Yes, there is a bit of filtering, so not total waste I hope

inner mesa
#

{{ area_entities('kitchen')|select('match', 'light.')|list }}

pastel moon
#

Oh, much neater, thanks ๐Ÿ™‚

#

So to create a globing group, would I list my areas ans then loop them through this line to get the entities?

inner mesa
#

that already provides a list

pastel moon
#

True, but for one area only. I'd like to end up with one large group with all area's lights

inner mesa
#

is that different from all lights?

pastel moon
#

Hm. Shouldn't be, youre right. Then I can just filter on state to see which is on or not

inner mesa
#

๐Ÿคท

#

{{ areas()|map('area_entities')|list }}

#

you really want this:
{{ areas()|map('area_entities')|sum(start=[])|select('match', 'light.')|list }}

pastel moon
#

Very nice, thanks! ๐Ÿ™‚

heavy island
#

what is the jinja solution for checking that a value is not 'undefined' before passing it to float? For instance:
{% set total = states('sensor.that_is_sometimes_unavailable') | float %} gets errors when that sensor isn't available, and I'd like to handle that to prevent the errors

inner mesa
#

if you want to ensure that total has a value, use |float(0), or whatever default you want

#

it really depends on the behavior you want if it's not available

heavy island
#

oh, ok

#

thanks

silent flicker
#

if i have {{ states('binary_sensor.windows_11_aaron_p600s') }} , is there a way to get the value of its previous state?

inner mesa
#

No, templates only have access to the current state

silent flicker
inner mesa
#

It does matter, as long as it's a state trigger

silent flicker
#

i was trying to update a Helper when the state changes because the last changed time of the state changing obviously resets when i reboot and i wanted to not show that

royal rampart
#

Soooo...

I have sensor.home_general_forecast which has a array (forecasts) of dictionary structure under it {start_time, end_time, per_kwh}

I kinda need to do this (not real code)

state_attr('sensor.home_general_forecast', 'forecasts') | filter(start_time > today@15:00 && end_time < tomorrow@7:00) | min(per_kwh)

any tips? ๐Ÿ˜„

fervent island
#

Does anyone has experience how to create a "virtual" device in HA that you can assign some "real" enities to? Here is the use case: I have several plugs that I would like to aggregate under one main device

tawny zephyr
#

You add them to a group

fervent island
#

Sounds good - How do I create a group then?

tawny zephyr
#

Settings > Devices > Helpers > Add group

mighty ledge
#

so if they are sensors, then you'd make a sensor group... etc

fervent island
#

But beside groups I guess there is no actual way of creating a "virtual device" right? I just thougt it would be nice to click on a device to see all plugs assigned to it and then switch them seperately (now itยดs just on and off for all)

mighty ledge
#

but it doesn't have the name 'virutal device'

fervent island
#

Well it doesnยดt show up in devices ...

mighty ledge
#

it's an entity

fervent island
obtuse zephyr
#

Instead of navigating device pages, why not make a dashboard with the layout you want to see?

#

You can make an entities card w/ all the switches grouped together that you'd like

fervent island
#

Yes, that would be an option - anyway, not quite the same as an virtual device but I guess the group will do then

#

Itยดs a little sad that when using the "Remote Home Assistant" integration, only single entities are getting synched but not the actual device#

frigid iron
#

Hello everyone

I'm trying to find out how to setup a fan template, so I've got a IR fan and it generates 4 scenes on home assistant (Fan_off, Fan_1, Fan_2, Fan_3)

Anyone has a template to help setup so that those 4 scenes works as a single fan template?

Thanks so much for the help

mighty ledge
#

scenes? are you sure about that?

frigid iron
#

yeah, the IR blaster that i have at the moment creates the ir comands like scenes instead of buttons or something else.

cosmic hamlet
#

How do i get the selected option of an input_select in a template

#

it shows unknown if i use states

inner mesa
#

it's the state

cosmic hamlet
#

oh the input select must be recreated. sigh

floral steeple
#

I have a feeling I need to use the responce variable somewhere, but not sure where

floral steeple
#

maybe it should be

      message: >-
        {% if ('quote.response.response_type == action_done') %}
          Your Quote of the day is {{ quote.response.speech.plain.speech }}
        {% else %}  
          No quote today. 
        {% endif %}
rigid jasper
#

Hello! I am new to HomeAssistant and I just made the Cast to my Google Nest Hub working but I have a problem when casting the dashboard to the nest hub. I have a custom card and it have some value_template with some functions to process the time value, but on the casting display, the functions seems to not work. Any ideea how I can fix this?

untold solar
#

Does anyone know if i can filter a list of entities by domain (eg. light), this template seems to pick up everything in the area:

{% set lights_on = expand(area_entities('office')) %} 
{{ lights_on | selectattr('state', 'eq', 'on') | list | count > 0 }}
untold solar
mighty ledge
untold solar
floral steeple
#

ok, this seems to be working

    data:
      agent_id: [redacted]
      text: quote of the day
    response_variable: quote
  - service: tts.speak
    data:
      cache: false
      media_player_entity_id: media_player.
      message: |-
        {% if ('quote.response.response_type == action_done') %}
          Here is your AI quote of the day {{quote.response.speech.plain.speech | trim | replace('\"','')}}
        {% else %}  
          No quote today. 
        {% endif %} ```
#

i found I had to add the | trim | replace('\"','') not sure what that means

mighty ledge
#

You'll never get no quote today with that code

#

if you check your automation, you'll be able to see the response data and then you can fix this {% if ('quote.response.response_type == action_done') %}

#

but that part is wrong, you're basically saying if True, which is always true. because it's a populated string

floral steeple
#

oh, ok, that whole "if" part was to take care of the case where there is an error, and that would be reflect by this:
response_type: error
but is the response if successful, it would be this:
response_type: action_done

#

so, it will not recognize if the response_type: error as written?

weary jolt
#

Hey guys I used to have a template working, however I had to restart my home assistant from a backup and the template no longer works

#

{{ now() - state_attr('automation.roborock_clean_if_tv_turns_off', 'last_triggered') > timedelta(hours=12) }}

#

Testing to see if an automation hasn't run for last 12 hours or more

#

I get this error "In 'template' condition: TypeError: unsupported operand type(s) for -: 'datetime.datetime' and 'NoneType'"

mighty ledge
#

'quote.response.response_type == action_done' -> quote.response.response_type == 'action_done'

floral steeple
#

thank you!

marble jackal
mighty ledge
#

line 1, position 39, d -> s

#

๐Ÿ˜‰

#

I put it in our language

marble jackal
#

Hehe

#
{% set last_trigger = state_attr('automation.roborock_clean_if_tv_turns_off', 'last_triggered') %}
{{ last_trigger is none or (now() - last_trigger > timedelta(hours=12)) }}
mighty ledge
#

you could do

marble jackal
#

If you are using this in automation.roborock_clean_if_tv_turns_off you can use this.attributes.last_triggered

mighty ledge
#
{{ now() - (last_trigger or now()) > timedelta(hours=12) }}
marble jackal
#

Could that possibly give a negative timedelta of a few milliseconds?

mighty ledge
#

probably

marble jackal
#

It will still not exceed 12 hours

mighty ledge
#

Maybe I'll add another macro called this_minute()

#

which will be exactly on the minute

#

and a this_second()

#

or something like that

#

this_hour()

#

or today_at('now')

#

๐Ÿคทโ€โ™‚๏ธ

#

time needs to be easier

weary jolt
#

Thanks both of you!

fluid radish
#

I have some Zigbee bulbs that are 2700K-6500K, but claim over Zigbee to be 2000K to 6536K. So when Adaptive Lighting tries to control them, the colors come out all wrong.
Does anyone know how to make a template that remaps them? The doc just says how to set the min and max, but my interpretation of that is if I set the limit to 2700, it will cap the value HA asks for to 2700K, resulting in a mystery actual color temperature, rather than remapping it.
https://www.home-assistant.io/integrations/light.template/

mighty ledge
#

Y=mx + b

marble jackal
mighty ledge
#

Ah

#

Last trigger or now() - 13

marble jackal
#

Yes, something like that will work

fluid radish
#

Also, the light template seems to have a way to set what the value is read as, but not what it's written as.

fluid radish
#

There's also this, but is this saying that you need to make not only a template, but also an input_number entity, to use the template?
https://www.home-assistant.io/integrations/light.template/

        set_temperature:
          service: input_number.set_value
          data:
            value: "{{ color_temp }}"
            entity_id: input_number.temperature_input
lofty mason
#

The input number is optional, it's just showing that you can do anything you want when something calls the set_temperature service on the template light

#

So if adaptive lighting calls set_temperature on your template light, you can turn around and then call set temperature on your real light, but you can use some transform function to send a different temperature.

fluid radish
#

The wiki could really use a more useful remapping (say, brightness or color temperature) example. That huge example just gives errors when I paste it in the dev tool, even if I chop out a bunch.

ValueError: Template error: int got invalid input 'on' when rendering template 'ceiling_light_adj:
  friendly_name: "Ceiling Light"
  temperature_template: "{{states('light.ceiling_light_1', 'color_temperature') | int}}"
  set_temperature:
    service: input_number.set_value
    data:
      value: "{{ color_temp }}"' but no default was specified
#

"Umm, what?" is all I can get out of that.

lofty mason
#

{{states('light.ceiling_light_1', 'color_temperature') | int}} <- this isn't a valid template

#

should be state_attr(), not states()

fluid radish
#

also, ctrl-space or whatever gives no suggestions in the template tool.

#

state_attr('light.ceiling_light_1', what do I do here?)

#

Maybe I should file a bug about having a built-in feature to fix up lights that lie. I have three different Zigbee light things that all have the same problem, from two brands.

inner mesa
#

provide the attribute

fluid radish
#

And one of them isn't even a strip controller where it makes sense for them not to know what LEDs you connect to it.

#

Okay, what attribute? I don't know what the attribute is called.

inner mesa
#

you mentioned "color_temperature" before

#

is that what you wanted?

fluid radish
#

That was just a wild guess.

inner mesa
#

alright

fluid radish
#

If I look at the light in HA, the only attributes it shows are "off with transition" and "off brightness". And a color and-or color temperature picker, but that's not an attribute.

plain magnetBOT
fluid radish
#

Huh, if I use the attribute name color_temp instead of color_temperature, the error changes: UndefinedError: 'color_temp' is undefined

inner mesa
#

are you looking in devtools -> States?

plain magnetBOT
fluid radish
#

Thanks, I thought that data used to be directly on the light's details.

#

This seems to work for reading the scale:
temperature_template: "{{(370-153)/(500-15) * (state_attr('light.ceiling_light_1', 'color_temp') | int - 500) + 370 }}"

#

Is there a way to generalize and reuse a template for more than one light without copying and pasting a bunch?

#

Or maybe there's a way to make a ZHA quirk instead to avoid having to template it.

inner mesa
#

you can make a macro, but the code to import and use it would probably be just as wordy as copying and pasting

fluid radish
#

If I want to use "the requested color temperature" as the input for this, how would I do it?

        set_temperature:
          service: input_number.set_value
          data:
            value: "{{ color_temp }}"
            entity_id: input_number.temperature_input
fluid radish
#

I see, the template debug tool can't handle template light format.

#

It would be helpful for the wiki to have an example that just straight passes through every attribute, rather than confusingly doing stuff with random scripts and named entities.

#

I think I'm getting it, though.

#

Do you have to specify to pass through things like brightness, if you're directly calling another light.turn_on from the turn_on section?

#

ValueError: Template error: int got invalid input 'None' when rendering template '{{(370-153)/(500-153) * (state_attr('light.ceiling_light_1', 'color_temp') | int - 500) + 370 }}' but no default was specified

inner mesa
#

it sounds like you tried to get the color temperature of a light that's off

#

and didn't provide a default

fluid radish
#

What would even be reasonable as a default?

#

And actually, the base light is currently on.

plain magnetBOT
fluid radish
#

That's a few revisions later, still trying to get it working.

#
Template variable warning: 'transition' is undefined when rendering '{{ transition }}'```
fluid radish
#

I got toggling and color temperature to work, but not yet the level.

royal rampart
#

is there a way to copy all the attributes from an entity to the templated entity? I'm changing the state to add an invisible whitespace so the trailing 0 doesn't get eaten in the UI

graceful widget
#

Yes these sensors from HA app i know. I have assigned assignable names to my sensors. Additionally I have device_tracker over ping

#

I have only one AP on every etage. For me, it would be more important to know if everyone in the household is home.

#

And the AP can change then yes, so no special AP

#

I have tried this with the ping variant. But when the users are asleep in flight mode, the presence is no longer guaranteed

mighty ledge
#

Typically, you have to store brightness and transition in a helper entity and use those values.

#

or you omit them from that service

plain magnetBOT
mighty ledge
#

@fallen linden you have to share your full xml, otherwise we can't help. Both of those examples appear to only show a section of the XML.

fallen linden
#

how do I upload it as a file? It says the length is too long

#

i put it up at Pastebin in the link above

mighty ledge
#

value_json.status.outlets.outlet[0].state

#

if AOF is off and AON is on...

#

value_json.status.outlets.outlet[0].state == 'AON'

fallen linden
#

That will give me either AON or AOF how do i change that into a booleon value

#

So if i read the whole XML into HA with

sensor:

how do create a sensor that will read value_json.status.outlets.outlet[0].state and give me a True or False or 0 or 1 or on or off or what ever?

mighty ledge
#

exactly what I just wrote

fallen linden
#

I am sorry i am not understanding...

mighty ledge
#

your value template... just copy/paste what I wrote

fallen linden
#

i thought value_json.status.outlets.outlet[0].state will just give me AON or AOF... not a booleon value

mighty ledge
#

dude

#

you completely didn't read my last code

#

let me poitn to it

mighty ledge
#

it's that simple

fallen linden
#

so in my yaml i just put

platform: http
name: Raw XML Data
resource: http://10.11.1.195/cgi-bin/status.xml
method: GET
content_type: 'text/xml'
value_template: '{{ value }}'
value_json.status.outlets.outlet[0].state == 'AON'

mighty ledge
#

no... dude, where did you put your template before?

#

in your working sensor

#

hint, check pin 1 2

fallen linden
#

i dont have a template for this... i dont know how to make the template

#

i was thinking something like this but it does not work...
platform: template
sensors:
aquarium_freshwater_mid:
friendly_name: "Aquarium Freshwater Mid"
value_template: >-
{% set ns = {'ns': 'http://www.w3.org/2005/Atom'} %}
{% set xml = state_attr('sensor.raw_xml_data', 'value')|parse_xml %}
{% set value = xml.xpath('//ns:status/ns:outlets/ns:outlet[66]/ns:state/text()', namespaces=ns) %}
{% if value[0] == 'AON' %}
on
{% else %}
off
{% endif %}s

mighty ledge
#

Ok, so you're saying this template did you didn't create?

#

So, if that works and is correct

#

and I told you your new template is value_json.status.outlets.outlet[0].state == 'AON', where do you think it should go in your new sensor?

fallen linden
#

it does not work

mighty ledge
#

did you try the template I wrote, are you grabbing the correct outlet?

#

the template I wrote looks at outlet 1

#

you have liek 40 outlets there

#

the 0 in the template means outlet 1

#

so, you have to count to what outlet you want and put the number there

#

well, the number minus 1

#

so outlet 40 would be 39

fallen linden
#

SO something like

This would give me AOF or AON?

mighty ledge
#

yes

#

but you want true/false so you need the == 'AON'

fallen linden
#

oh ok... so that just changes it to Bool??? i did not know that... i thought i would have to do a if statement or somthing

#

let me try it

mighty ledge
#

that's a normal if statement

#

or test

#

{% if (statement) %}
do something
{% else %}
do other
{% endif %}

#

statement just needs to resolve true/false, so in this case we don't need the if

#

because x == y will return true or false

#

same with x > y or x < y or x != y etc

fallen linden
#

iam restarting HA

#

Thanks you so much! and sorry i was not understandingg

floral shuttle
#

would it be safe to replace {{expand('group.lights_outside_total_device_power') |selectattr('state','is_number') |map(attribute='state') |map('float')|sum}} with {{expand('group.lights_outside_total_device_power') |map(attribute='state') |select('is_number') |map('float')|sum}} consider both output and efficiency?

#

changing the order of selects

mighty ledge
#

I don't think it matters

floral shuttle
#

thx. my eyes have a preference for the shorter version, but I wasnt sure if selecting the numbers 1 step later would impact the evaluation

mighty ledge
#

they are generators so it's almost the same

#

if not exactly the same

#

the resulting output is only provided if the information is chosen

#

for each generator

#

it's a hard concept to grasp but, if something is being filtered out, the order really doesn't matter because it's not resolving that item during the process and the number of loops is still the same

#

with things like sort and unique, it will matter because they return lists, not generators

floral shuttle
#

yes, I think I can understand that... very clear explanation btw thx

mighty ledge
#

the only thing in your template that outputs a list is expand

floral shuttle
#

have another one, triggered by TheFes's changing his version template with some new possibilities in the version template. - unique_id: ha_dev_update_available_not_skipped state: > {{states('binary_sensor.ha_dev_update_available') == 'on' and 'dev' in state_attr('update.home_assistant_core_update','latest_version') and state_attr('update.home_assistant_core_update','latest_version') != state_attr('update.home_assistant_core_update','skipped_version')}} seems a bit complex with those different integrations (supervisor en Version), but I can find a way to use only those update entities

#

idea: ignore a dev update and still be notified for the next update

mighty ledge
#

Sorry, I haven't dove into understanding how the version function works

floral shuttle
#

no worries, this works, maybe if Martijn returns he can have a look

marble jackal
#

While sharing the link I now understand why ludeeus is promoting it ๐Ÿ™‚

mighty ledge
#

but is it really awesome????

mighty ledge
#

Maybe I'll deploy awesome version on my production lines here for version control

#

it's on pypi

floral shuttle
#

thats external to HA? or used in the version integration? trying to find a way to check the Version services and its entities, and link that to update entities (whishing those 2 were integrated somehow)

mighty ledge
#

Yes, it's external to HA

#

but it's built into HA

#

i.e. any application can use it if they choose

floral shuttle
#

btw there's a very confusing ux on that because clicking any of those 4 services brings on to a huge overview, and the selected service. which was the reason for my template in the first place

graceful widget
#

Hello, how can I create a sensor which will show me the minand max outdoor temperature of the day from 0-24?
So exactly for one day of the week

mighty ledge
#

use history stats or the statistics integration, not templates

graceful widget
#

But of course, that would be even better. Do you have an example for me from which I can learn?

plain magnetBOT
peak juniper
#

I'm having some issues with a restful sensor - it worked a dream before but seems to have stopped pulling data. Is this thread the best place to post it?

inner mesa
#

Doesn't seem related to a template

mighty ledge
#

well, if the data shape changed, it would be a template change

#

I had a few rest endpoints do that on me

#

pissed me off to say the least

inner mesa
#

Hard to say from 'some issues' and 'stopped pulling data'

#

There should be logs

peak juniper
#

where would I find these logs?

mighty ledge
#

settings sytem logs

peak juniper
#

ah yeah ok, nothing in there that indicates they're not working

#

they show a value, but it's a few days old

#

tried restarting, but the values don't seem to refresh and i've looked at the page it's pulling data from and all still seems to be there

mighty ledge
#

go directly to the endpoint and see if the data is the same

peak juniper
#

no, the data is different

#
  - platform: rest
    name: "Vanguard: US Equity"
    resource: https://www.vanguardinvestor.co.uk/api/funds/vanguard-us-equity-index-fund-gbp-acc
    value_template: >-
        {{ value_json.navPrice.value }}
mighty ledge
#

then verify that your endpoint is correct in your configuration. Also, something like that would have an error associated with it

peak juniper
#

hmmm ok, i'll keep looking then, no errors in the logs

mighty ledge
#

Your template still works based on that endpoint, so it's not the template

graceful widget
# plain magnet

Thanks. I have already been to this page. I just wonder how I can capture the day period. Because this value, shows me yes always 24 hours back and not a day of the week?

    max_age:
      hours: 24
mighty ledge
#

You can't with that integration, you can with the SQL integration, but you'll need to come up with the query.

graceful widget
#

There is no other option?

mighty ledge
#

no

fluid radish
mighty ledge
#

because it may recieve them

#

that doesn't mean it exists at all times

#

if you call a light.turn_on service without defining those, ti does not have them

haughty breach
graceful widget
#

Is Minimum value only this

            {{ [source, current] | min }}
pastel moon
#

@inner mesa Would this look like a start? ```

  • platform: template
    sensors:
    fade_duration_left:
    friendly_name: Fade Duration Left
    value_template: "{{ now() - states('input_datetime.fade_start') }}"```
plain magnetBOT
#

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

pastel moon
#

didn't I? I always do, will fix

marble jackal
#

I'm not Rob, but some comments

  1. all states are strings, you need to convert it to a datetime
  2. that datetime needs to be timezone aware, so use as_local on it
  3. the result will be a timedelta, I would suggest to convert it to seconds and use state_class: duration in combination with unit_of_measurement: s
pastel moon
#

Oh. there's even a class for it! Thanks for the suggestions, will try to update accordingly

inner mesa
#

I'm not Rob
Few are ๐Ÿ™‚

pastel moon
#

Ok, so broke it down to this; {% set duration = (now()|as_local) - (states('input_datetime.fade_transition_time_start')|as_datetime|as_local) %} {{ duration.seconds }}

#

it counts up though... ๐Ÿ˜„

mighty ledge
#

yah, no that won't work

#

you need to know the duration before the calc

#

so if you set the duration to 600 seconds, it would be....

pastel moon
#

Oh gosh, I'm sorry. I wrongly tagged RobC before...

marble jackal
#

Ah, I'll give it back to Petro, as he seems to know the background

mighty ledge
#
{% set duration = 600 %}
{% set calc = now() - states('input_datetime.fade_transition_time_start')|as_datetime|as_local %}
{{ (duration - calc.total_seconds()) / duration * 100 }}
mighty ledge
marble jackal
#

Ah, a completion percentage so it seems

mighty ledge
#

that is correct

marble jackal
#

Ah, I actually scrolled back, but the question was in another channel ๐Ÿ˜…

pastel moon
#

True... It evolved into a template more than anything...

pastel moon
#

what would the difference be between .total_seconds() and .seconds? Its the latter rounding? Answer was: Yes. ๐Ÿ™‚

mighty ledge
#

Total seconds gives you the total seconds. Seconds only give you the seconds for under 24 hours

marble jackal
#

And (less important) seconds gives an integer, total_seconds() a floating point number

pastel moon
#

Thanks! Yes, I noticed they were in fact int and float at least... ๐Ÿ™‚ Thanks for the help for now, will continue on this later!

wooden aurora
#

I have a template sensor that I have created for my washing machine based on the power state. One this i want to do is add a "delay" between state changes. Before going off or standby I would like a certain amount of time to pass. Is there a way to do that?
Here is my code: https://pastebin.com/NWbFsM3y

marble jackal
#

Convert it to the new format and make it trigger based

#

Then you can use numeric state triggers and hold the state

wooden aurora
#

could you point me to an example? this was my first attempt at a template

plain magnetBOT
marble jackal
#

There are examples in the docs. In your case I would use 3 numeric state triggers, add a trigger id which represents the intended state and just refer to the trigger id in your template

#

Well maybe a state trigger for the off trigger

#
template:
  - trigger:
      - platform: state
        entity_id: sensor.washing_machine_power
        to: "0"
        for:
          minutes: 3
        id: "off"
    sensor:
      - unique_id: sensor_washing_machine_status
        name: Washing Machine Status
        state: "{{ trigger.id }}"
#

This is the gist of it, you need to add the other 2 triggers

wooden aurora
#

Thanks I will give this a try

cerulean cipher
haughty breach
#

You'll need a namespace to get previous_tier_limit and total_cost out of the loop.

cerulean cipher
#

ok I'll need to read some more then, it works in python so just trying to copy it over best I can

cerulean cipher
#

shit I made an error in that one, but it's just a rate error

fluid radish
mighty ledge
#

You can use a choose statement to see if the the variable is defined and perform the action (using it) if it is

fluid radish
#

What would that look like? Currently, it looks like this:

#
        set_level:
            service: light.turn_on
            target: 
                entity_id: light.ceiling_light_1
            data:
                brightness: "{{ brightness | int }}"
                transition: "{{ transition | float }}"
mighty ledge
#

You can put a whole script in the set_level key. So everything that automation actions can do (multiple actions) can go under that field.

cerulean cipher
#

that's a helluva lot cleaner than my bullish attempt

cerulean cipher
#

now that I think about it, it's been about 3 years since I did any templating

orchid oxide
#

did something change in how the template engine treats states that are formated as lists?
for the given state ('update.home_assistant_core_update', '2023.7.3', 'skip')
i used to be able to do {{states.input_text.ha_update_check.state.split('', '')[0]}}
to get the first entry
but now that returns ('update.home_assistant_core_update' so in order to get update.home_assistant_core_update, i have to do {{(states.input_text.ha_update_check.state|regex_replace('\(|\)|\s|\'','')).split(',')[0]}}

marble jackal
#

The quotes and parenthesis are part of the string

#

Furthermore, your state is not formatted as a list but as a tuple

fluid radish
marble jackal
#

To add to my comment above, if you would format it as a list (with [ and ]) and use double quotes around the items, you could use from_json to do what you want to do

undone jungle
#

It may be a convoluted question, so please bare with me.
The UPS integration (NUT) is outpuitting an incorrect parameter for one of the voltage sensors, since it's giving out a multiplier for the actual voltage and not the voltage itself. It's 2.25V when full, even though it should be 2.25 * 36V = 81V

#

Is there a way to customize the entity to give it the correct output, as opposed to using a template to create another entity with the correct voltage.

marble jackal
#

No, you can't change the output of the actual sensor. That has to be changed in the integration itself

undone jungle
#

The unfortunate part of it is that it's not even the integration. It's how the manufacturer did the firmware, so that ain't changing.

#

Their software probably knows it's a multiplier and not a voltage, while NUT is simply pulling the variable without contesting it.

mighty ledge
undone jungle
#

I've compared two drivers for the same device and one reports the value as incorrect number of cells with a V and the other driver multiplies this just fine.

#

So definitely a NUT issue, is what I am saying

#

Not HA related - though I am still more likely to fix it on HA end with a template, since NUT is a jungle of inefficiency and conflict..

icy jay
#

Hey,

id like to create a template sensor, that is on if theres any calendar event in the next 48h.

The calendar entity doesnt have any start attributes, they only appear when the event is right now

Some ideas?

lyric comet
#

You might need to use an automation to populate count.

icy jay
plain magnetBOT
tired sandal
#

(most likely the variables section) - all I have to go on is: " Error rendering variables: AttributeError: 'NoneType' object has no attribute 'tzinfo' " in the logs

#

scratch that - looks like my rest sensor is failing to grab the API data

#

Given an array of dictionaries that I want to filter, is there a reason to use selectattr('serviceImpacted', '==', true) vs selectattr('serviceImpacted', 'eq', true) ?

inner mesa
#

no, they're identical

#

from the Jinja docs:

jinja-tests.eq(a, b, /)
Same as a == b.

Aliases:
==, equalto

cerulean cipher
#

so if I'm trying to make a manual sensor, I just had a thought.... is there a way to make it record which month it's for using a template or would I have to do that from my input helper?

torpid crag
#

Hi Al, what am i doing wrong here? sensor.powershop_daily_charge = $1.03 and im trying to create a another sensor that is $1.03 / 1000. Im slowly getting there with the syntax, but i just need a bit of help with this one ๐Ÿ™‚

#
- sensor:
    - name: "Powershop Supply Charge NZD Wh"
      unit_of_measurement: "NZD"
      state: >-
        {{ states('sensor.powershop_daily_charge') * 1000 | float | round(3) }}
cerulean cipher
#

you said $1.03 / 1000 but in your sensor you have $1.03 * 1000

#

is that correct?

torpid crag
cerulean cipher
#
sensor:
  - platform: template
    sensors:
      powershop_supply_charge_nzd_wh:
        friendly_name: "Powershop Supply Charge NZD Wh"
        unit_of_measurement: "NZD"
        value_template: "{{ (states('sensor.powershop_daily_charge') | float * 1000) | round(3) }}"

should work

torpid crag
#

Yep - i got to the same place now as well. It does actually work, but i also get this error message: homeassistant.exceptions.TemplateError: ValueError: Template error: float got invalid input 'unavailable' when rendering template '{{ (states('sensor.powershop_daily_charge') | float * 1000) | round(3) }}' but no default was specified
2023-08-04 11:55:12.682 ERROR (MainThread) [homeassistant.helpers.template_entity] TemplateError('ValueError: Template error: float got invalid input 'unavailable' when rendering template '{{ (states('sensor.powershop_daily_charge') | float * 1000) | round(3) }}' but no default was specified') while processing template 'Template<template=({{ (states('sensor.powershop_daily_charge') | float * 1000) | round(3) }}) renders=4>' for attribute '_attr_native_value' in entity 'sensor.powershop_supply_charge_nzd_wh'

inner mesa
#

You should specify a default for your float filters

#

And ideally fix your sensors, which are apparently unavailable

torpid crag
winter pilot
#

Hey all. Looking for some help as my google skills have failed. Using the custom button card, trying to set the icon/card color based on the value of a binary sensor state. I read it couldn't be done using normal templating and trying "java" from what the page said. Any advice? I can paste the few lines if needed.

inner mesa
#

It's JavaScript

#

There are lots of examples in the docs

winter pilot
#

Just seeing some of that, went looking for something else. I'll read that and try and come back if i'm still stuck.

#

I copied and pasted from the docs the bit of code that applied, replaced with my binary sensor, changed the return values, and the code is accepted but does nothing.

#
    color: 
      - - - if (binary_sensor.ac = 'on') return "red"; else return "gray";```
#

sorry, I forgot how to paste code in here. been a bit.

inner mesa
#

I'm pretty sure that doesn't follow any of the examples in the docs

#

and

plain magnetBOT
#

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

winter pilot
#

HA reformatted it on me. It's not what I saved into it.

#

i'll redo it and share before I save this time

inner mesa
#

that's not the problem

#

first, I don't see where it says that the "color" supports templates

#

second, binary_sensor.ac isn't the way to test a state

winter pilot
#

well crap on the "first"

#

guess that's that lol

inner mesa
#

here's a more complicated example of mine:

                    - type: custom:button-card
                      entity: sensor.occupancy
                      state:
                        - value: "[[[ return states['automation.away_timer'].state === 'on'; ]]]"
                          operator: 'template'
                          name: "[[[ return parseInt(states['input_number.away'].state) + 's'; ]]]"
                          icon: "mdi:timer"
                          color: yellow
                        - value: "[[[ return parseInt(states['input_number.away'].state) === 0; ]]]"
                          operator: 'template'
                          name: "Away"
                          icon: "mdi:home-export-outline"
                          color: "red"
                        - operator: 'default'
                          color: green
                          name: "Home"
                          icon: "mdi:home"
                      tap_action:
                        action: call-service
                        service: script.home
#

the main point is that you should use the "state:" block

winter pilot
#

I do actually ... That was going to be in the new code I would have pasted after redoing it. Forgot to paste proper the first time.

inner mesa
#

or you can do it this way:

                    - type: custom:button-card
                      entity: sensor.mbath_water_temp
                      name: Water Temp
                      icon: mdi:water
                      show_state: true
                      show_units: true
                      template: badge_template_desktop
                      styles:
                        icon:
                        - color: >
                            [[[
                              if (states['input_boolean.heat_water'].state === 'on')
                                return 'red';
                              else
                                return 'green';
                            ]]]
                      tap_action:
                        action: call-service
                        service: homeassistant.toggle
winter pilot
#

Gonna try that now .... Would that work for the card color as well?

#

that does it! thank you!

wanton girder
#

what is wrong with this guys:

      - name: "ElliottsDoerSensor"
        state: >
          {{ states('binary_sensor.elliotts_vaerelse_dor_dorsensor_contact') | replace("on", "ร…ben",1) | replace("Unavaliable", "")) | replace("off", "Lukket", 1) }}
marble jackal
#

What does it return

limber haven
#

could use a little help solving a 'problem'.. Partner has bought an Electric car and we are looking for a way to easly collect a running total of how much electric we are using (using the actual cost) so we know how much of the electric bill is their share. We've hooked up a Zigbee plug that can generate a running total but there a few.. oddities with it we need to work around and we anrt sure how to turn that Kw usage count into a pound value for 'electric used'

#

So the issues are.. A) It already has a running total in it, and we cnat figure out how to reset it, B) every so often it seems to freak out and send (what we think) are its 'lifetime usage' totals as an actual usage amount to Zigbee which confuses the utter heck out of HA. Like reporting a device used 300Khw in a day. I dont know if there is a way to smooth out or.. filter results that would clearly be wrong (say if the previous total is.. 30kwh higher than the last one, thats almost certinally going to be impossibly wrong)

half pendant
#

Can someone help me fix this one, not sure what i've done wrong.

data:
  volume_level: {{ states('input_number.office_apple_tv_current_volume_level') | float + 0.1 }}
target:
  entity_id: media_player.kontor
marble jackal
#

What's the error?

half pendant
#

Error running action: expected float for dictionary value @ data['volume_level']. Got None

marble jackal
#

No quotes around the template

half pendant
#

great thank you!

wanton girder
mighty ledge
wanton girder
# mighty ledge there should be errors in your logs then

โ€™โ€™โ€™
Logger: homeassistant.config
Source: config.py:864
First occurred: 10:39:36 (2 occurrences)
Last logged: 10:39:36

Invalid config for [template]: invalid template (TemplateSyntaxError: unexpected ')') for dictionary value @ data['sensor'][6]['state']. Got '{{ states('binary_sensor.elliotts_vaerelse_dor_dorsensor_contact') | replace("on", "ร…ben",1) | replace("Unavaliable", "")) | replace("off", "Lukket", 1) }}\n'. (See /config/configuration.yaml, line 51).
Invalid config for [template]: [platform] is an invalid option for [template]. Check: template->platform. (See /config/configuration.yaml, line 85).
โ€™โ€™โ€™

mighty ledge
#

you'll have to post your config that you attempted

wanton girder
#
      - name: "ElliottsDoerSensor"
        state: >
          {{ states('binary_sensor.elliotts_vaerelse_dor_dorsensor_contact') | replace("on", "ร…ben",1) | replace("Unavaliable", "")) | replace("off", "Lukket", 1) }}
mighty ledge
#

That's fine

#

where you're placing it and how you're placing is not

#

meaning you have to post your entire config for it.

marble jackal
#

No it's not fine

wanton girder
#

I don't understand?

marble jackal
#

The is an ) too much in it

mighty ledge
marble jackal
#

In the replace for unavailable

mighty ledge
#

but the error is poitning at platform key

#

which means he's doing something wrong with his yaml

wanton girder
#

Ohhh ๐Ÿคญ

marble jackal
#

Well, there are two errors

#

The first one is for this template

mighty ledge
#

normally syntax errors will result in a "but got none"

wanton girder
marble jackal
#

The second one seems to be that you are using the legacy format under the template integration

wanton girder
#

In other words?

marble jackal
#

error 1

Invalid config for [template]: invalid template (TemplateSyntaxError: unexpected ')') for dictionary value @ data['sensor'][6]['state']. Got '{{ states(\'binary_sensor.elliotts_vaerelse_dor_dorsensor_contact\') | replace("on", "ร…ben",1) | replace("Unavaliable", "")) | replace("off", "Lukket", 1) }}\n'. (See /config/configuration.yaml, line 51).

error 2

Invalid config for [template]: [platform] is an invalid option for [template]. Check: template->platform. (See /config/configuration.yaml, line 85).
mighty ledge
#

mark, can you please just post your configuration

#

for the love of god

#

just post it, we will show you the errors

marble jackal
#

The second error is related to another sensor

mighty ledge
#

Yes, but that will cause the whole template integration to fail to load

wanton girder
#

I'm on the phone at the moment so ill post later...

#

Thanks alot so far ๐Ÿ™‚

cerulean cipher
#

Hurry up and wait

ancient island
#

Hoping someone can point me in the right direction here... I'm noticing that UI elements are rendering differently on different devices (https://i.imgur.com/dEQrOCR.jpg).

What can I change to help either eliminate or reduce this effect for a more consistent look across devices?

mighty ledge
simple tusk
#

Hello all,
I am in the process of implementing a small sensor to count my battery devices where the battery level is < X%.
The coding works in principle, but I would be interested if there is a cleaner or more elegant way to implement this?

  - name: count_battery_low
    unique_id: count_battery_low
    state: > 
      {% set devices = [
        states.sensor.shortcut_button_office_battery,
        states.sensor.shortcut_button_living_room_battery,  
      ] %}
      {{ devices | selectattr('state', '<', '51') | list | count }}
mighty ledge
#

well, your code doesn't actually work. It just appears to work

cerulean cipher
#

๐Ÿ™ˆ

mighty ledge
#

any battery devices in the single digits between 6 and 9 will not show up in that template

#

oh and devices with 100% battery will show up as low too

#
{% set ns = namespace(items=[]) %}
{% for device in [
        states.sensor.shortcut_button_office_battery,
        states.sensor.shortcut_button_living_room_battery,  
      ] if device.state | is_number %}
  {% if device.state | float < 51 %}
    {% set ns.items = ns.items + [ device ] %}
  {% endif %}
{% endfor %}
{{ ns.items | count }}
simple tusk
#

okay, i thougt it was not so bad
I would say.. many things to learn ๐Ÿ™‚

Thx petro - i will look into your code and try to understand it

icy jay
marble jackal
#

Example:

message: Sinterklaasavond
all_day: true
start_time: '2023-12-05 00:00:00'
end_time: '2023-12-06 00:00:00'
icy jay
marble jackal
#

Well, as you can see my event is 4 months from now, and I have a start time attribute

#

Did you check in developer tools > states

icy jay
#

Yep i did, this is the output:

offset_reached: false
friendly_name: Familie

#

@marble jackal if i call the service, i get 2 events on august 15th and 16th, but in dev tools the calendar has only these 2 attributes above

#

If i do the samr with a local calendar, i get start_time and the rest. But not with the icloud calendar. The attributes just show up if the event is right now

marble jackal
#

Okay, if the response of the service call does include them, then use that

icy jay
#

Yes thats it what i meant, i dont know how to do this :/
But still thanks for your response, ill find a way somehow

marble jackal
#

Well, I guess best might be to create an automation on a time pattern trigger, maybe once per hour

#

Then issue the service call and use the response to add the first start time to an input datetime

#

I would need to test that myself, and I'm on mobile so I can't do that now

icy jay
#

i think it would be enough if i count the given events and if theres just > 0 then turn a input bool on

#

but the count is the problem for me

wanton girder
#

I need help for some replacement thingy... I want to display a name and method of unlocking... but if a user with id 11 in the lock locks in i takes the text from user 1, twice..

    - name: "HoveddoerAabnet"
        state: >
          {{ states('sensor.hoveddor_last_unlock_user') 
            | replace("Unavaliable", "") 
            | replace('1', 'Mark - Pinkode') 
            | replace('0', 'Maria - Fingeraftryk') 
            | replace('11', 'Thea - Fingeraftryk') 
          }}
#

So if user 11 locks in the sensor value is Mark - PinkodeMark - Pinkode - but should be Thea - Fingeraftryk

marble jackal
#
{% set mapping = { '1': 'Mark', '0': 'Maria', '11': 'Thea' } %}
{{ mapping[states('sensor.your_sensor')] | default() }}
#

That's what I would do, you could also first do the replace for 11 before you do the replace for 1

wanton girder
#

Since there might be other things colliding, im gonna try yours ๐Ÿ™‚

silver pewter
#

Hi all ๐Ÿ™‚ Any1 know how to solve this?:
This one works.
{{ is_state_attr('input_datetime.maste_ut_kl', 'hour', 2 ) }}

But i want to show false/true of hour is above 8 or not. But i only get syntax error ๐Ÿ˜›
{{ is_state_attr('input_datetime.maste_ut_kl', 'hour', > 8 ) }}

inner mesa
#

Yeah, that's not right

#

{{ state_attr('input_datetime.maste_ut_kl', 'hour') > 8 }}

silver pewter
#

Yay! thank you Rob!

round oriole
#

Does anyone know if there is a way to include the word and during a joining of strings? Ie if it is two strings being joined it would just say 'word1 AND word2' but it its more than 2 being joined it would be 'word1, word2 AND word3'

#

trying to incorporate some natural language into a tts action

marble jackal
icy jay
#

Hi,

i want to create a template sensor that counts the events given by the following service, does somebody know how to do this?

data:
  duration:
    hours: 48
    minutes: 0
    seconds: 0
target:
  entity_id: calendar.familie ```
marble jackal
#

Try {{ response.events | count > 0 }}

plain magnetBOT
wanton girder
#

The id remains the same wether it is fingerprint or pincode

icy jay
marble jackal
#

You can't directly, because you need to issue the service call. That's why I proposed an automation on a time pattern

#

You can toggle an input boolean based on the template result

#

Or send an event in the automation and use that in a trigger based template sensor

icy jay
#

Okay, so call the service in a automation and then a template with {{ respone.events | count > 0 }}

but how do i toggle the bool on that result?

Sorry, im just not that into templating

#

I get this:

Error: Script requires 'response_variable' for response data for service call calendar.list_events

plain magnetBOT
floral shuttle
#

have this binary: {{is_state('person.me','home') or is_state('person.she','home')}} . figured id rewrite that to {{'person.me' or 'person.she' in state_attr('zone.home','persons')}} which has some unexpectd result.... it lists who is in that attribute, instead of true/false.

#

if I use only one, {{'person.me' in state_attr('zone.home','persons')}} it does true/false..

marble jackal
#

You need to do the check twice

#

x in y or z in y

icy jay
marble jackal
icy jay
#

the โ€žreapone_variable: responseโ€œ was the thing i didnt had, now its working

floral shuttle