#templates-archived

1 messages · Page 79 of 1

frail dagger
#

That is sexy!

haughty breach
#

I don't know why... but it makes me a little queasy. 🤢

mighty ledge
#

and you make the same dict twice

#

definitely some jinja get-around-limitations-fuckery

remote perch
#

Jinja has been an adjustment after years of Python, it's like it's mostly python but with the fuckery 😛

mighty ledge
#

yep, if you know python, you can get around some of the jinja issues

#

but jinja is restricted

remote perch
#

I stick my foot in it a lot trying to python a jinja yaml only to realize jinja doesn't like my python because, reasons. Then I walk away and design a dash for a while 😄

mighty ledge
#

Just learn filters!

#

The rest is python basically

remote perch
#

Filters are quite often how I do it. Trial and error and picking up tricks on the forums

lime olive
#

Can someone please help me, I'm trying to play random mp3 files from a folder. I've already set the folder integration and added a sensor for that folder. It can see all my files

For some reason I can't get the media path right. The folder is located in /config/www/media/toilet - yest the MP3s are of funny comments when someone flashes the toilet 🙂

#

I've tried many variations of the path using this in "services" tab but no dice

service: media_player.play_media
target:
  entity_id: media_player.office_gh
data:
  media_content_type: music
  media_content_id: "/media/toilet{{ state_attr('sensor.toilet', 'file_list')|random }}"
mighty ledge
#

"/local/media/toilet/{{ state_attr('sensor.toilet', 'file_list')|random }}"

frail dagger
#

TIL people play MP3s for the toilet flushing... 🤣

lime olive
mighty ledge
#

what's your filelist contain?

lime olive
#

MP3 files

#

Ahh, can't update screenshots

#

yes I've tried the path within the sensor but still didn't work
"/config/www/media/toilet/"

mighty ledge
#

your media list already has the path in it

#

so you're adding the path twice

lime olive
#

I've tried playing a single file from that folder and it works
media_content_id: /local/media/toilet/Ahh great, now we can't use the bathroom for at least an hour!.mp3

lime olive
mighty ledge
#

right because your path is wrong in your list

#

/config/www is wrong

#

that's what's in your list

#

so just that won't work

#

then when you combine it with the other path, you're adding 2x the path

#

and then use "/local/media/toilet/{{ state_attr('sensor.toilet', 'file_list')|random }}"

lime olive
#

Ahh, ok interesting. Well that gets auto generated by the sensor. It's in the attributes

#

This is what I put into the sensor

- platform: folder
  folder: "/config/www/media/toilet/"
mighty ledge
#

well, just change that to /local/

#

if that doesn't work, then you need to remplace after the random

lime olive
#

So "/local/www/media/toilet/"?

mighty ledge
#
media_content_id: "{{ state_attr('sensor.toilet', 'file_list')|random|replace('config/www', 'local')}}"
lime olive
#
- platform: folder
  folder: "/local/media/toilet/"

Integration couldn't be setup error

mighty ledge
lime olive
#

getting the following
Failed to call service media_player.play_media. template value should be a string for dictionary value @ data['sequence'][0]['data']. Got {'media_content_type': 'audio/mp3', 'media_content_id': "{{ state_attr('sensor.toilet', 'file_list')|random|replace('config/www', 'local'}}"}

lime olive
mighty ledge
#

try this in the template editor {{ state_attr('sensor.toilet', 'file_list')|random|replace('config/www', 'local')}}

lime olive
mighty ledge
#

alright, then try that template

#

in your script

lime olive
# mighty ledge alright, then try that template

That worked!!!

service: media_player.play_media
target:
  entity_id: media_player.office_gh
data:
  media_content_type: audio/mp3
  media_content_id: "{{ state_attr('sensor.toilet', 'file_list')|random|replace('config/www', 'local')}}"

Much appreciated Petro! I was pulling my hair out for a few hours

lucid thicket
#

This is nice! Maybe a little gross but still nice. I wanted to do something with more than two elements in each list or tuple though, so unless you can enlighten me i think this hack is only relevant to two-element tuples?

latent flax
#

I am editing my llama3 configuration and it is returning 'exposed_entities' is undefined for the line {%- for entity in exposed_entities: %}. Is there any way to add the exposed_entities list?

frail dagger
latent flax
remote perch
# latent flax Ah, I dont want to type my entities manually, is there any way to get a list of ...

Yes, what is the criteria of your entities for exposed_entities? You can create a list using filters, such as:

{% set exposed_entities = 
  states.binary_sensor |
  selectattr('attributes.device_class', 'defined') |
  selectattr('attributes.device_class', 'eq', 'vibration') |
  rejectattr('name', 'search', 'dryer', ignorecase=True) |
  rejectattr('state', 'in', ['unavailable', 'unknown', 'off']) 
%}
boreal siren
#

Is there a way to set a sensor state to the current system time so I can show the last time that a webhook was triggered? Or is there a better way to do this?

#

Ideally, I'd also be able to perform an action with the time, like if more than an hour has elapsed since the last update, notify me

haughty breach
#

state: "{{ now() }}"

lofty mason
boreal siren
#

Ok, thanks!

boreal siren
lofty mason
#

states of entities are always strings.

#

but an input datetime has a timestamp you can use in an attribute to make formatting slightly easier

boreal siren
#

I get the always strings bit, I don't get the second bit

#

I do see last updated as a secondary information on all these sensor values, so i can definitely see when they were last updated

#

I don't know how to do anything with that value, but i'll google some more

quiet creek
#

I have a number sensor, and I want to display the change since the last update, Ex: "-5" or "+5". How can I achieve this?

quiet creek
#

Also, how do I convert a string to a number? I have this as an action in my automation for when my string changes, but it's not working. service: input_number.set_value data: entity_id: input_number.value_number value: >- {% set value = states('sensor.value_string') %} {{ value.split(' ')[1] | float }}

marble jackal
marble jackal
quiet creek
#

I need it to convert the string to a number and set it to the input number helper

marble jackal
#

Test the template in developer tools > templates

#

What is the state of sensor.value_string

quiet creek
#

209

quiet creek
marble jackal
#

There are no spaces in that, so no 2nd element

#

Counting starts at 0

marble jackal
#

{{ '209'.split(' ')[0] | float }} will return 209 instead of that error you mentioned

#

But does the sensor also have states including a space to split on?

quiet creek
lime olive
#

With the "random" play of audio clips. Is there a way I can set it to play random but not play anything that's already been played until every clip has been played once, and then restart the process again?

I understand this could be very complicated, but very interested to see if there's a way

marble jackal
#

Store the clips played in an attribute of a trigger based template sensor using an event trigger, and reject those from your selection. Reset the attribute when the last clip is selected

lost locust
#

if I'm getting a timestamp from an API ("startTimestamp" : "2024-09-17T16:20"), how can I convert that to a sensor with a timestamp device_class with the correct timezone? I've tried {{ value_json.startTimestamp }}-05:00 but that didn't work and said timezone was missing :/ (and also doesn't account for daylight saving time)

adding -05:00 threw an error that timezone was missing
adding -0500 "worked" but was in UTC
{{ value_json.startTimestamp }} is in UTC

lucid thicket
lost locust
lime olive
#

Guys I have a sub-folder in the media directory, I can't seem to get this template to work as I'm trying to play the files in that folder randomly

    media-source://media_source{{ state_attr('sensor.Test', 'file_list')|random |replace('/media/','/local/Test/')}}```

However, specifying the file within that folder does work
```media_content_id: "media-source://media_source/local/Test/Test.mp3"```

I'm probably going blind, and am sleep deprived 🙂
inner mesa
#

what does {{ state_attr('sensor.Test', 'file_list') }} return in devtools -> Templates?

#

first, sensor.Test isn't an actual entity_id - they're all lowercase

#

but it may fix that for you automatically

lime olive
inner mesa
#

that's not a list

#

it just looks like a string

lime olive
inner mesa
#

you gotta provide all the data

#

hard to help otherwise

#

what does media-source://media_source{{ state_attr('sensor.Test', 'file_list')|random |replace('/media/','/local/Test/')}} show there?

lime olive
inner mesa
#

there ya go

lime olive
inner mesa
#

something doesn't add up

#

I suspect you just have the wrong entity_id there

#

in other words, it's not what you're actually testing

#

you're editing stuff to be different from what you're really doing

lime olive
#

Sorry, Just fixed it.

media_content_id: "media-source://media_source{{ state_attr('sensor.test', 'file_list')|random |replace('/media/','/local/')}}"

Can't for the life of me figure out what was wrong, I could swear I've tried this before lol

Thanks anyway Rob for your time mate

thorny snow
#

Hey there,
I did not find it (I guess I was blind).
I got an energy counter for consumption. I multiplied it with an entity helper to calculate the total costs. Tomorrow the price changes, so I want to make a cut, create a new helper which contains the current costs and calculate the new costs by mutiplyng the new price with the consumption beginning tomorrow and add the costs until today.
Like
current price 30ct
current consumption 2000kWh
so I got 600€
Tomorrow i have a price of 40ct
Now I want to save 600€ as a helper and calculate everything from 2000kWh with 40ct and add the helper
so when I reach 3000kWh it should display a total cost of 1000€.

mighty ledge
#

no idea what you're even asking, post an equation and we can help

thorny snow
#

Hehe

#

Like

#

I got energy consumption * energy price from 1.1. Until today. This product shall now be added to energy consumption beginning tomorrow multiplied with the new energy price.

hardy garden
#

Hey all - posted on the HA Community Forums about this too but is there any way to get a list of exposed entities that can be used in template? I'm looking for a way to iterate over the list of entities that are exposed to Voice Assist

hardy garden
frail dagger
hardy garden
#

I can change the path to /homeassistant/.storage/core.entity_registry and that also works

#

but it does not work when run as shell_command as this gets executed out of the container scope

inner mesa
#

Looks like you didn't try /config/...

#

You can shell into the container and see what's in there and what's mounted where

frail dagger
hardy garden
#

I'm running a supervised install - shell commands get executed in the host environment

frail dagger
#

There is zero question about that.

inner mesa
#

Looks like you didn't try /config/...

#

I say again

hardy garden
#

I sure have

inner mesa
#

That's the path

#

You can confirm yourself

hardy garden
#
stderr: >-
  /bin/sh: jq '[.data.entities[] | select(.options.conversation.should_expose ==
  true) | {entity_id}]' /config/.storage/core.entity_registry: not found
returncode: 127
#

Thats the response from the shell_command call

frail dagger
#

And it's the same error with just ./.storage/core.entity_registry?

hardy garden
#

Yes

frail dagger
#

If you docker exec into the core container and just run the command, what does it return?

inner mesa
#

Do that

frail dagger
#

Even on a supervised install, it still executes in the Core container.

#

This is when I am bash'd into my container:

iot-server:/config# find . -name core.entity_registry
./.storage/core.entity_registry
iot-server:/config#
hardy garden
#

It works when i run the command from within the ha container

frail dagger
#

Can you post what you have in your shell_command?

hardy garden
#

It's weird cause I set up a dummy shell_command to ls -al and it shows the container filesystem

frail dagger
#

Yup. That's my point. shell_command always executes in the Core container, regardless of installation type.

hardy garden
#

I'm an idiot - I had:

  exposed_entities: >-
    "jq '[.data.entities[] | select(.options.conversation.should_expose == true) | {entity_id}]' /config/.storage/core.entity_registry"

instead of:

  exposed_entities: >-
    jq '[.data.entities[] | select(.options.conversation.should_expose == true) | {entity_id}]' /config/.storage/core.entity_registry
#

works now

frail dagger
#

lol ablobbouncefast yay!

hardy garden
#

fookin quotes

inner mesa
#

That will do it

crimson wadi
#

I have an entity camera.workshop but entity_id.name in my automation returns None even though the interface shows Workshop how do I get that value? If I edit the entity, the name field is indeed blank so where is Workshop coming from?

inner mesa
#

The name and entity_id are separate

#

The entity_id is initially derived from the name, which has a default assigned by the integration

#

If you want the name in a template, you would do {{ states.camera.workshop.name }}

#

@crimson wadi ☝️

crimson wadi
#

Hmm, though if I'm targetting multiple cameras, how can I get the name in a generic way?

#

{{ states[entity_id.entity_id].name }} ?

inner mesa
#

That's one way

#

{{ ['xxx', 'yyy']|expand|map(attribute='name')|list }}

thorny snow
# mighty ledge no idea what you're even asking, post an equation and we can help

okay, the best I can giver you is this:

{{ ((float(states('sensor.hm_es_tx_wm_iec_energy_counter_ch2')) - 2 ) * float(states('input_number.energyprice'))) | round(2) }}

this gives me the energy costs based on a helper entity and the energycounter from hm-es . Now I have a changing energy price. So I would like to have the costs until yesterday, and add it to the energy counter multiplied with th enew energyprice

oldCosts + hm_es_sensor_beginning_from_30th_of_june * new_energy_price

how do I get the energy counter starting from 30th of june?

mighty ledge
#

You can't do that in template entities

#

calculations that span periods are performed by statistics integrations, utility meter, or other similiar integrations.

#

SQL lets you perform a query and a calculation as well.

thorny snow
#

Okay, Unfortunately I have no time right now to learn about that. I think I will create new helper entities holding the necessary values and simply substract / add them like

oldCosts_from_helper + {{ ((float(states('sensor.hm_es_tx_wm_iec_energy_counter_ch2')) - 2 - old_energy_count_from_helper ) * float(states('input_number.energyprice'))) | round(2) }}
mighty ledge
#

just use the built in integrations that do this

#

in some cases, if you just want this in the UI, ou don't even need to make entities

plain magnetBOT
#

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

stoic bison
#

It appears I could be using rejectattr(, , ) in the template, but I do not know how to implement it correctly to make something like rejectattr('datetime', <, now().strftime)

silent seal
#

I don't know that the rejectattr can compare dates like that as strings to be honest. You might be better off using foreach to iterate over them or similar.

inner mesa
#

It can as long as both arguments are a datetime

silent seal
#

That's handy to know!

inner mesa
#

like:
{{ states.alarm_control_panel|selectattr('last_changed', '>', now() - timedelta(hours=2))|map(attribute='entity_id')|list }}

silent seal
#

The last line might end up looking something like this then:

{{ today_forecast | rejectattr('datetime', '<', now().strftime('%Y-%m-%dT%h:%M')) | sort(attribute='electricity_price', reverse=True) | first }}
inner mesa
#

you shouldn't need the strftime() call as long as datetime is a datetime

#

that's just converting it to a string

silent seal
#

Excellent, I don't have anything like that integration on my install so it's hard to test.

inner mesa
#

I don't know what it is either, just speculating

#

it depends on the integration, as these datetime attributes are actually strings (boo!!!):

#

you can't convert during a comparison without losing the state object, so that requires a loop

silent seal
#

Huh, I thought the MET office integration died for a while 🤔

mighty ledge
#

you can compare strings though

#

isoformatted strings

#

just make sure you remove microseconds

#

and keep the value in UTC

inner mesa
#

True

orchid oxide
#
entity_id:
  - sensor.night_end
value_template: "{{(as_timestamp(now())-as_timestamp(state.state))/3600}}"
above: 14
id: Awake time```
is there something wrong with this trigger? its not working. its for a timestamp
#

i used this elsewhere and it works fine

#

but for this it seems to not trigger, but if i manually set the date of the timestamp outside of the condition and then back into the condition, it triggers

marble jackal
#

it only triggers when the state of sensor.night_end changes

#

it doesn't check the template every minute

orchid oxide
#

oh

marble jackal
#

if you want that, use a template trigger

orchid oxide
#

oops, that makes more sense

marble jackal
#
platform: template
value_template: "{{ (as_timestamp(now()) -as_timestamp(states('sensor.night_end'))) / 3600 > 14 }}"
id: Awake time
orchid oxide
#

awesome, ty

marble jackal
#

oh wait

#

should have mentioned the entity_id now, changed

outer oyster
#

Good morning! I am getting this error, Error: TypeError: object of type 'bool' has no len(), and I think it has to do with this variable I am setting in a script. I think it might be because notify_always or notify_if_home, both multiple entities, are not set. At least one should be set. Is there a better way to join these arrays together when one may be blank?

variables:
  entities_to_notify: >
    {{ notify_always | expand | map(attribute='entity_id') | list +
    notify_if_home | expand | selectattr('state', 'eq', 'home') |
    map(attribute='entity_id') | list }}
mighty ledge
#

notify_always or notify_if_home is a boolean

#

that's what the error is telling you

#

if they are lists of entity_id's, then you're doing a ton of extra work for nothing

#
{{ notify_always + notify_if_home | select('is_state', 'home') | list }}
#

again, both have to be lists

plain magnetBOT
#

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

mighty ledge
#

notify_always is a string

#

it's not a list

#

    notify_if_home: []
    notify_always: group.parents
outer oyster
#

ah good call, thank you petro, I'll run that down

#

Appreciate the quick assist

mighty ledge
#

you'll still need expand though if you're planning on using groups

outer oyster
#

Cool, thank you!

mighty ledge
#

and you should format the value coming in from your service call

#

i.e. if it's a single entity that's a string, turn it into a list of entities

#

also, if the list is empty, make sure to stop execution or account for that.

outer oyster
#

Good point, thanks for all the input

stoic bison
#

@silent seal @inner mesa @mighty ledge I now implemented this

{% set forecast = state_attr('sensor.zonneplan_current_electricity_tariff', 'forecast') %}
{{ forecast | selectattr('datetime', '>', now().strftime('%Y-%m-%dT%h:%M')) | sort(attribute='electricity_price', reverse=false) | list }}

which generates a list sorted on electricity price. The selectattr filter however only seems to care about the days. So I get a list based on tomorrow, excluding the remaining hours of today. (Which is 50% of what I want)
I tried this, but it again only generated a list based on the hours of tomorrow

{{ forecast | selectattr('datetime', '>', now().strftime('%Y-%m-%dT%h:%M')) | rejectattr('datetime', '<', now().strftime('%Y-%m-%dT%h:%M')) | sort(attribute='electricity_price', reverse=false) | list }}

Do you have any suggestions?

mighty ledge
#

that format is wrong

#

You need to match the timezone that's in your forcast datetime attribute and you need to remove microseconds

#

it's aslo a bit redundant

#

you select things greater than now, but reject things less than now

#

which is 2 ways to do the same thing

#

@stoic bison ^

stoic bison
# mighty ledge you select things greater than now, but reject things less than now

Thanks for the response @mighty ledge!
Well if I have a list containing all hours of today and tomorrow and I want the remaining hours of today in a variable I should exclude the passed hours and all hours of tomorrow, that is what I try to achieve. I will look into matching the timezones. Is this related to the now().strftime() method?

mighty ledge
#

just post the output of {% set forecast = state_attr('sensor.zonneplan_current_electricity_tariff', 'forecast') %}

#

well, seeing that you haven't, I'm assuming they output in this format 2024-07-01T00:00:00.000000Z

#

so you need to figure out if Z means your tz or if it means utc

#

if it's your timezone...

{% set midnight = today_at() + timedelta(days=1) %}
{% set fmat = '%Y-%m-%dT%H:%M:%S.%fZ' %}
{{ forecast | selectattr('datetime', '>', now().strftime(fmat)) | selectattr('datetime', '<', midnight.strftime(fmat)) | sort(attribute='electricity_price', reverse=false) | list }}
#

if it's utc you should do a for-loop

stoic bison
#

It is like a list of dictionaries with each list entry is a new hour

mighty ledge
#

Yes use what I posted

abstract maple
#

Hey all, I hear there is a way to use templates and context to determine if the last state change in an input_boolean was triggered by a certain automation. How would I do that?

for a bit of context, I have an input_boolean and a sensor, and two automations to keep them in sync. One updates the input_boolean if the sensor state changes, the other calls a service (which amounts to updating the sensor value) when the input_boolean changes

Right now, that causes a chain reaction if the sensor is updated from outside HA. I'm looking to prevent that. (And yes, I am entirely open to completely different alternative solutions=

mighty ledge
abstract maple
#

@petro by instead you mean instead of an input_boolean?

mighty ledge
#

correct

abstract maple
#

Ok, I'll look into that.

mighty ledge
#

post your atuomation and I can help you build it @abstract maple

abstract maple
#

@petro I'll do that as soon as I can, but I have to figure out why my server seems to have crashed first.

#

I swear I'll rip this failing drive out bodily if the bloody system doesn't get on with migrating it to a hotspare...

abstract maple
#

Well, it looks like my nas has a major problem, so it may not be until later or tomorrow that I can get back to you

cinder pendant
#

I'm trying to create a template fan. As shown in the docs, I'm using attrs like value_template: "{{ states('input_boolean.state') }}" but that results in a fan state that is never updated and log warnings like: [homeassistant.helpers.service] Referenced entities input_boolean.state are missing or not currently available

Have I configured something incorrectly or are these placeholders in the docs that need to be replaced with newly created helper entities? The docs aren't clear on this point.

frail dagger
cinder pendant
#

OK. That's how I've done it for templates in the past but I was hoping that there was some cleaner way to do it for these "internal" helpers where the entity is solely to be used as an attr for a templated entity.

frail dagger
languid pendant
#

listens to crickets

plain magnetBOT
#

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

plain magnetBOT
#

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

inner mesa
#

right, this is nonsense: states.hvac_mode

#

that's not an entity_id, or how you would retrieve the state or an attribute from an entity. Where did that come from?

minor halo
inner mesa
#

based on the documentation there, yes

#

it's a variable that's made available in that section

#

data_template was deprecated many, many years ago in favor of data

minor halo
inner mesa
#

no, data_template still works

#

and you're surrounding the variable with quotes, which turns it into a string, and you're treating the hvac_mode as an entity_id, which it isn't

#

there's just a bunch of stuf weird there

#

hvac_mode is a variable, and you should just evaluate it as one

#

value: "{{ iif(hvac_mode == 'heat', 1, 0) }}"

#

if you need a list, then value: "{{ [iif(hvac_mode == 'heat', 1, 0)] }}"

minor halo
real girder
#

Hey 👋

I have a weird issue with expand() in notification messages. Below example only spits out Device unavailable! through an automation, but when manually checking the template in the Template section of Developer tools, it spits out Device bedroom window unavailable! correctly. Note: state=on only used for testing.

`id: critical_device_unavailable
alias: Send notification if a critical device goes unavailable
trigger:

  • platform: state
    entity_id:
    • binary_sensor.critical_devices
      to: unavailable
      action:
  • service: notify.persistent_notification
    data:
    message: Device {{ expand('binary_sensor.critical_devices') | selectattr('state', 'eq', 'on') | map(attribute='name') | list | join(', ') | lower }} is unavailable!`

What am I missing?

mighty ledge
#

How are you testing this?

plain magnetBOT
#

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

silent seal
#

The jinja isn't formatted as a string

      value_template: >-
        {{
            states("sensor.meterkast_groep_1_vermogen")| float(0) +
            states("sensor.meterkast_groep_2_vermogen")| float(0) +
            states("sensor.meterkast_groep_3_vermogen")| float(0) }}
wicked galleon
#

Hi guys,
I working on template...
My idea is that I will end up with a sensor "one each for north, east, south and west," comination of day and azimuth (value beteen) which will give me true or false for the current day (now).

Example:
Wednesday July 4rd 4:30pm azimuth for south is between 51 and 207 = true

Something I already have...

#

{% set start = now().replace(day=1, month=7).date() %}
{% set end = now().replace(day=15, month=7).date() %}
{% set low, high = [start, end] | min, [start, end] | max %}
{% set current = low <= now().date() <= high %}
{{ not current if start > end else current }}

{{ states('sensor.sonne_solar_azimuth')|float >= 202 and states('sensor.sonne_solar_azimuth') | float < 308 }}

#

is there anyone here who can help me with this matter

#

I have also already created a list of azimuth for the whole year at intervals of 2 weeks

#

This looks like this,

#

from day to day north nort-east/east east-south south-west/west
16. Dez 01. Jan -no shading- -no shading- 126-207 202-232
17. Jun 01. Jul 55-106 51-128 51-207 202-308

heavy minnow
#

Hello, I'm making a script with fields, I want the action of the script depend on the provided filed (i.e if color is provided do X, if color temp is provided do Y) but I'm struggling to understand what to write in the condition template {{ color is not none }} wouldn't work, also tried

{% if '{{color}}' == '' %}
  False
{% endif %}```
I tried '', 'none', 'null' 

also, is there a way to see what the filed returns?
inner mesa
#

You're nesting templates

heavy minnow
#

I tried color without {{}}

inner mesa
#

And then turning it into a string

#

Remove both {{}} and the quotes

heavy minnow
#

so whats is the correct condition? '' or 'none'

haughty breach
#

{{ color is defined }}

inner mesa
#

Probably {{ color is defined }}

#

Or that

haughty breach
#

Dangit... stupid, slow internet.

inner mesa
#

Whichever you want

haughty breach
wicked galleon
haughty breach
#

I'm just a bit inexperienced here, so I'

bronze prawn
#

I'm looking to set a calendar event by voice and curious if someone can tell me how I might get a date if the user uses somethink like "create a calendar event called breakfast on Wednesday at 8am" Is there an easy way to convert Wednesday to a calendar date using a template or otherwise?

plain magnetBOT
#

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

eternal stag
#

I literally don't see how that's any better ^

mighty ledge
#

You have to template the entire field

eternal stag
#

nvm, I figured it out:

  - service: scene.create
    data:
      scene_id: before_lighting
      snapshot_entities: >
        {% set switches = states.switch | rejectattr('state', 'eq', 'unavailable') | map(attribute='entity_id') | list %}
        {% set lights = states.light | rejectattr('state', 'eq', 'unavailable') | map(attribute='entity_id') | list %}
        {{ switches + lights }}
inner mesa
#

Hard to imagine that does what you want

#

If you change states.switch + states.light to states.switch, it should

eternal stag
#

i am just trying to save all switch and light states in the house

#

then later i will restore it

#

errr, i see what you mean, yeah that's not actually what i have in my file, sorry i'll update

#

I was trying to combine the domains before going through the function pipe, but it didn't like concatenating domains and this is good enough for me

short thicket
#

Good morning, I've just started using ha, so please be patient 🙂
I've a esp32, that is reading some values from my inverter. I would like to add these readings to ha.
Therefore I've created a rest sensor:

sensor:
  # RESTful Sensor to get the JSON data
  - platform: rest
    resource: http://esp32-943cc637b4d8.local/data
    scan_interval: 5
    name: inverter_data
    value_template: "{{ value_json.gridFrequency }}" # Dummy value, required but not used
    json_attributes:
      - gridFrequency

Then I've added a template sensor:

template:
  - sensor:
      name: "Grid Frequency"
      state: "{{ state_attr('sensor.inverter_data', 'gridFrequency') }}"
      state_class: "measurement"
      unit_of_measurement: "Hz"

I know, that the json is returned from the rest endpoint. I've added a temp command to dobule check.
The returning json looks like

{
   "gridFrequency": 50
}

But the state of the template sensor is always "unkown". Can someone please give me a hint, what's wrong?

marble jackal
#

so does the rest sensor give the right vaule in it's gridFrequency attribute?

#

I also don't really understand why you are using a rest sensor, which will have this 50 value as it's state (and in an attribute as well) and then you create another template sensor which will have the same state of 50

half pendant
#

I have an automation that checks whenever a specific TV switches channel it sets the source to a matching source in a list. When the TV turns of i'd like it to set it to Off (which isn't a channel) or if there is not a match in the list i'd like to set it to a default. How can i achieve this? This is how i set the input right now.

target:
  entity_id: input_select.lg_inputs
data:
  option: "{{state_attr('media_player.lg_c2', 'source')}}"```
marble jackal
#

option: "{{ 'Off' if is_state('media_player.lg_c2', 'off') else state_attr('media_player.lg_c2', 'source')}}"

#

something like that?

half pendant
#

Thx.

#

Is there a way to do a default value as well?

short thicket
marble jackal
#
option: >
  {% if is_state('media_player.lg_c2', 'off') %}
    Off
  {% elif state_attr('media_player.lg_c2', 'source') in state_attr('input_select.lg_inputs', 'options' %}
    {{ state_attr('media_player.lg_c2', 'source') }}
  {% else %}
    Unknown source
  {% endif %}
marble jackal
half pendant
#
  {% if state_attr('media_player.lg_c2', 'source') in state_attr('input_select.lg_inputs', 'options' %}
    {{ state_attr('media_player.lg_c2', 'source') }}
  {% else %}
    Off
  {% endif %}```
short thicket
marble jackal
#

you can see the current state in developer tools > states

plain magnetBOT
abstract maple
#

A question about template switches, just so I know if I understood correctly: The switch will update to whatever value_template evaluates to, whenever what that refers to changes, but it will NOT execute whatever is configured in turn_on or turn_off unless it is switched by interacting with the template switch directly, right?

short thicket
# plain magnet

there is only the sensor.grid_frequency. No entity with inverter_data

marble jackal
marble jackal
#

check your log for issues

plain magnetBOT
#

show your Home Assistant logs

short thicket
# marble jackal then your rest sensor isn't working, which would fit with the state of the templ...

ah ok.
In the logs, there is not too much to see.

2024-07-05 11:16:48.408 INFO (MainThread) [homeassistant.components.sensor] Setting up rest.sensor
2024-07-05 11:16:48.410 DEBUG (MainThread) [homeassistant.components.rest.data] Updating from http://esp32-943cc637b4d8.local/data

I've set log level to

logger:
  default: info
  logs:
    homeassistant.components.rest: debug
    homeassistant.components.sensor.rest: debug
marble jackal
short thicket
plain magnetBOT
#

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

marble jackal
#

well, again, you should have a sensor.inverter_data based on that config

short thicket
marble jackal
#

yes, that is using the rest integration, you are using the sensor integration

#

both work

plain magnetBOT
#

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

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

#

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

#

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

marble jackal
#

@short thicket you don't have a sensor.jsontest in developer tools > states now?

short thicket
marble jackal
#

okay, well, it should work the same for your inverter

short thicket
#

hmm true 🙂 don't really understand why my rest sensor is not working the same. when firing the request with postman, it is responding like expected

#

actually, the hostname was a problem. using the ip now, and it is getting the values.. thanks for your help 🙂

marble jackal
#

anyway, it should have 50.00009 or something like that as it's state, which makes teh template sensor a bit redundant

#

and if you want to create multiple sensors from that resource, you can better use the rest integration, which allows you to create multiple sensors based on one rest call

short thicket
#

understood. i removed the template sensor. From my understanding based on the documentation I was thinking the restful sensor is used for multiple sensors?

#

so i need one sensor for each value in the json response, right?

#

I've now one sensor inverter_data with ~50 values. is that best practice or would you recommend using the rest integration and create one sensor for each of these values?

short thicket
#

I am now trying to add the energy-solar-graph card to the dashboard. but I am not sure how the data is linked to the cards?

marble jackal
plain magnetBOT
#

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

marble jackal
#

you can store it in a template sensor (or in attribute if you expect this will go over 255 characters)

mighty ledge
#

ah, i see that I was tricked by discord cache again

#

and the fes already helped you

mighty ledge
tardy nimbus
marble jackal
#

share what you have now

tardy nimbus
#
  - trigger:
      - platform: time_pattern
        seconds: /10
    action:
      - service: calendar.list_events
        target:
          entity_id: calendar.tommeplan
        data:
          duration:
            days: 14
        response_variable: trash_pickups
    sensor:
      - name: Food Waste Collection Events
        state: |
          {{ trash_pickups['calendar.tommeplan']['events'] }}
#

If I just do {{ trash_pickups }} it gives the message Invalid state with length 348. State max length is 255 characters., so it seems there is indeed something inside that variable

marble jackal
#

put it in an attribute instead

#
template:
  - trigger:
      - platform: time_pattern
        seconds: /10
    action:
      - service: calendar.list_events
        target:
          entity_id: calendar.tommeplan
        data:
          duration:
            days: 14
        response_variable: trash_pickups
    sensor:
      - name: Food Waste Collection Events
        state: "OK"
        attributes:
          events: "{{ trash_pickups['calendar.tommeplan']['events'] }}"
tardy nimbus
#

how can I see those attributes?

#

and should the UI show them? or do I need to define these variables in the config files? (and does that mean I need to restart for every change?) Trying to learn how to use this stuff

lean jetty
#

Hi, I'm making template binary sensor that is true when any alert in alert domain state is on. Why is this template does not work?

{% set is_any_alert_on = false %}
{% for alert in states.alert %}
  {% if alert.state == 'on' %}
    {% set is_any_alert_on = true %}
    {% break %}
  {% endif %}
{% endfor %}
{% if is_any_alert_on %}
  true
{% else %}
  false
{% endif %}
silent seal
#

Try this instead:

{{ states.alert | selectattr('state', 'eq', 'on') | list | count > 0 }}
mighty ledge
#

you'd have to use namespace to get past that

#

however, what rosemary posted is the way you should go

lean jetty
#

Thank you

marble jackal
# tardy nimbus how can I see those attributes?

you can see those attributes in developer tools > states
you can use them in templates.
You can also use the output of the calandar service call to create separate sensors for each trash type

tardy nimbus
marble jackal
#

did you reload template enitites after making the change?

#

check your log for issues

tardy nimbus
#

HA log or LogBook in GUI?

#

Should the whole thing be pasted in State template* in the GUI? Including template:?

marble jackal
#

ah

#

you are creating a template in the GUI under helpers

tardy nimbus
#

Yeah, trying, but if it's not supported, I can add it to config file instead

marble jackal
#

that doesn't work for trigger based template sensors, they need to be created in YAML in you configuration.yaml

tardy nimbus
#

Aha, thanks, let me try that and see!

plain magnetBOT
#

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

abstract maple
#

Why is it claiming it doesn't have any unique id?

mighty ledge
#

did you restart?

#

if you reloaded, that will create a second entity and the first will remain unchanged

#

whenever you add a unique_id, you should restart

#

otherwise you just shot yourself in the foot

abstract maple
#

Shot in the foot? how so?

mighty ledge
#

because if the entity exists without a unique_id and you add it, then reload, a second entity will be created with the config entry

#

which means your only recourse is to restart HA, delete the original sensor from the UI if it exists. If it doesn't exist, just rename the entity_id to remove the _2 from the end of it

marble jackal
#

what are you trying to achieve with this template switch

abstract maple
#

@petro: reloading sorta fixed it

marble jackal
#

because those actions won't be performed when the switch changes because of the device tracker state change

abstract maple
#

Don't know anything about the condition of my feet yet.

#

@marble jackal That is actually exactly the issue I'm trying to address. I want the actions to be triggered when the switch is actively thrown, but not when the state of the binary sensor changes, because that would cause an endless loop.

mighty ledge
#

as long as you're aware that you need to press the switch for the script to be ran

abstract maple
#

that set_pet_location service sets the state of the thing represented by that binary sensor

#

the idea is to keep the state of the switch in sync if the state of the external thing is changed outside ha, but call a service to update it if the switch is changed inside ha.

mighty ledge
#

when you say "changed inside ha", you mean when a user (like yourself) clicks 'turn on' for the switch in the HA UI?

abstract maple
#

pretty much, yes.

marble jackal
#

what does that binary_sensor indicate?

abstract maple
#

where my cat is.

marble jackal
#

is it on when it's inside?

abstract maple
#

the plan is to export that switch to alexa and throw it with a routine.

#

@marble jackal I've tested it in the dev tools and that seems to be how it is.

#

actually the state is internally represented by 1 and 2 apparently, but the integration exports it as true and false.

#

with all I know about the system of the company that built that appliance, if I was in charge there, I'd have a thing or two to say about it.

marble jackal
#

okay, so if the binary sensor indicates that the cat is inside (binary_sensor state is on) the switch will be on as well.
Which means the action you can perform is to switch it off

#

as you can't turn on a switch which is already on

abstract maple
#

makes sense. What are you getting at? Did I do it the wrong way round or something?

marble jackal
#

no, I wanted to make sure you were aware of that

abstract maple
#

No that's fine. If the system already reflects the cat being inside and I for whatever reason updated it to be inside, nothing would happen anyways.

#

except a log entry saying the state was updated.

#

Good. That was the easy part. Now comes the hard part of enabling Alexa to speak the status of the cat. I can get the status by state_translated, but getting Alexa to speak it fluently might be a whole different kettle of fish.

mighty ledge
#

make a routine

abstract maple
#

@petro that is what I'm planning. But since Alexa has no conditionals, I'll have to somehow trigger the reply in HA, and that's where the problems start.

mighty ledge
#

make 2 separate binary sensors, one for inside, one for outside, use that as the triggers

abstract maple
#

You're not quite understanding what I want to do. An announcement when the cat comes in would be easy. What I want to do is actively ask Alexa "Where's the cat at?" and that's HARD to do right.

#

I'm seriously contemplating a custom skill

#

But I'm probably going to replace my echos with esphome devices instead, because Alexa's ruffling my feathers anyways.

inner mesa
#

I don't think it's that hard. Use a routine (speech trigger of 'where is the cat?') to execute a script and have the script speak whatever you want via Alexa Media Player

plain magnetBOT
#

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

small elk
#

Hmm, should I start a thread for this if the message is too long?

abstract maple
#

@RobC the problem is, whenever you trigger a script, Alexa says "OK" before the script runs, which can't be suppressed by any means I know of so it would work, but it would never feel right. Also alexa_media_last_called has been REALLY unreliable for me

inner mesa
mighty ledge
#

the whole alexa media player integration is unreliable

inner mesa
#

I never had an issue with doing tts through them, but I transitioned off of it a few releases ago

#

That was all I used it for, and I just moved to my Onju devices

#

I changed my Alexa acknowledgement to a tone years ago, but I don't know if it's possible to eliminate it entirely

mighty ledge
#

mine is just a tone

small elk
mighty ledge
#

just use all ands

#

no parenthesis

inner mesa
#

Right. I don't know what the stray { } are doing there

mighty ledge
#

has_value() and has_value and x <y and a < b

abstract maple
#

@inner mesa {{ expand(integration_entities('alexa_media') | select('search', 'media_player')) | selectattr('attributes.last_called','eq',True ) | map(attribute='entity_id')|first }} That's kinda important if you want to simlulate a question/ response thing with alexa media player. It updates eventually, but definitely not in time to route a reply to the right device.

inner mesa
#

Ok

small elk
# mighty ledge just use all ands

Ah I see, so this would be correct?

{{ has_value(states('sensor.p1s_nozzle_temperature')) and has_value(states('sensor.p1s_bed_temperature')) and
      (states('sensor.p1s_nozzle_temperature')|float(100)) < 50 and (states('sensor.p1s_bed_temperature')|float(100)) < 50 }}
mighty ledge
#

no, you don't need states method for has_value

small elk
#

Ok, thanks

mighty ledge
#

you also most likely don't need to supply defaults to floats if you use has_value before hand because it doesn't execute the functions later on in the syntax if it fails early

small elk
#

Yeah that's what I was thinking, was just wanting to play it safe as I wasn't sure

#

I'll remove those

abstract maple
#

@inner mesa The problem is really that amazon apparently doesn't see alexa as a marketable product they want to promote but as sort of an internal thing they don't want to share, a bit like apple does. They have tons of APIs, but you have to jump through a million hoops to be allowed to use them, and the system really isn't designed with flexibility and expandablity in mind. I honestly have no idea what they were trying to achieve with it or where they want to take it. It's been suggested that the main purpose was to gather data to train their stt engine. If that's the case they have failed miserably, because that sucks too

dark rain
#

I know I can use a senro template to display the status of a switch in the UI, but not sure how

small elk
plain magnetBOT
#

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

inner mesa
#

What does that template evaluate to?

#

You can see this yourself

small elk
#

Currently it evalutes to true in the devtools template tab, but the old one used to give an error when evaluating during the "blackout" period, and then true afterwards, so I'm expecting it's probably the same thing happening for this one where it doesn't catch the error even with checking has_value first

#

I can upload a trace if that would help with debugging?

inner mesa
#

No

#

Just monitor it in dev tools

small elk
# inner mesa Just monitor it in dev tools

Ok so I did this and the template remained false until both variables were < 50 and then turned true (although I had to copy and paste the same template to get it to update to true on the dev tools page), but the automation didn't turn off the light like it should

inner mesa
#

Then review the trace

small elk
#

The same automation works if I add a 15 sec delay to before the wait_template, so I'm pretty sure it's the template not handling the error or something

inner mesa
#

And do basic testing of the action

small elk
#

The light turn off action does work, for example if I run the exact same automation now it turns off the light immediately because both values are already < 50

small elk
# inner mesa Then review the trace

The trace says the template completed with 3599.89 secs remaining out of the 1 hour timeout, so it completed in 0.1 secs which shouldn't happen because it takes around 7+ mins for the printer to cool down and for the 2 values to go below 50C

inner mesa
#

Then it was already true

small elk
#

But if it was already true then why didn't it run the action to turn off the light?

inner mesa
#

The trace would tell you that

small elk
#

I'm not sure how to interpret it exactly or which of the tabs within the trace to pay attention to

#

I've never really used the HA trace before now

#

The main difference I can see is that the original trace does not have a logbook entry for P1S Chamber light turned off triggered by automation Turn off P1S light at end of print triggered, whereas the new trace for the time I ran it manually just now does have that entry.

#

So does that imply the light turn off action didn't run for the first trace, or that it did run but for some reason failed to turn off the light?

inner mesa
#

The trace shows you what parts executed

small elk
#

I can see it's possible if the printer was just running the last bits of its code just after the "print finished" event fired for example, then maybe it overrode HA's command to turn off the light, and instead kept it on

inner mesa
#

You can test all this

#

Manually set the state of the temp sensors to whatever you want, trigger the automation action manually

small elk
#

Can confirm that adding a 4 second delay action before the wait_template fixed the issue.
It seems that it was like what I was suspecting, which is that the printer briefly sends a very low incorrect sensor temperature value up to about 4 seconds after the print finished event has fired.
Therefore, even though the template would complete as true too early and execute the light turn off service, the light wouldn't actually turn off because the printer wouldn't accept any instructions to do so in the brief period after the print finished event.
This is probably because it was still executing the last bits of the gcode or other code 4 second after the event fired.

quaint hinge
#

Hi all, I got redirected here. I'm transferring from homey which has a room activity. Basically add sensors to a room, motion or door contact and it will mark a room as active when a sensor is triggered. Instead of linking to individual sensors id simply check if a room is active or not for my flows. I'd like to achieve a similar thing with home assistant. Could anyone assist?

frail dagger
quaint hinge
#

Just motion sensors and door sensors, sorry, I tried some approaches already and I'm not sure what's the best or even possible way 🙂

#

If by any means I could retrieve the room a device is in by tracking events that would be ideal, I could then log a timestamp to a helper

frail dagger
#

Honestly, just trigger off the entities. That is the easiest approach.

frail dagger
onyx kiln
#

Hi guys. I think this is where my question should be asked, but I'm not sure. Please slap me if not.

I am using multiscrape to scrape a webpage that is made by adruino. the webpage is as follows:

23.69<br>37.85<br>967.22<br>789.32<br>143.07<br>Girls 2023-04-27 Giraffe CalTemp:-0.74 CalHum:0.00

Of course, the numbers change. It's an environment sensor. Here's my code for the sensor:

  • resource: http://192.168.1.31
    scan_interval: 5
    sensor:
    • unique_id: bme680_girlsroom_temperature
      name: bme680 girlsroom temperature
      select: ""
      value_template: "{{ value }}"

I do not know what to put in select to get each number. Or the value template for that matter. Can you help?

slate plover
#

Am I able to attach a calculated value from a template to the device itself so it has everything? like a temperature and humidty sensor having a real feel added to it so I can see all 3

mighty ledge
#

you can if you create a template entity from the UI

lone knoll
#

can someone explain bereifly but surly what are remplates are for? begginer here

silent seal
lone knoll
#

When it tells me I need a basic understanding of things I don't know anything aobut I'm starting to get scared

silent seal
#

But underneath that paragraph it tells you what templates do.

lone knoll
#

Thanks !

bronze prawn
#
[{'name': 'Living Room', 'type': 'area', 'id': '5c5d54b7c86f4223ae8f6acf614d2c45'}, {'name': 'LR Lamps', 'type': 'entity', 'id': 'light.monoprice_z_wave_on_off_plugin'}, {'name': 'LR Standing Lamp', 'type': 'entity', 'id': 'light.sonoff_awp04l_1'}]

I'm getting rusty. How can I pull id for all elements in this list?

bronze prawn
#

Thanks so much!

tired berry
#

I have a triggered template sensor and would like to turn it to unavailable based on certain inputs. How can I do so? True unavailable, not a string "unavailable" ... Is it possible?

#

Ah. availability template in the definition of the sensor.

silent seal
#

You need to set the availability:

availability template (optional, default: true)
Defines a template to get the available state of the entity. If the template either fails to render or returns True, "1", "true", "yes", "on", "enable", or a non-zero number, the entity will be available. If the template returns any other value, the entity will be unavailable. If not configured, the entity will always be available. Note that the string comparison is not case sensitive; "TrUe" and "yEs" are allowed.

https://www.home-assistant.io/integrations/template/#configuration-variables

marble jackal
#
template:
  - binary_sensor:
      - unique_id: template_bs_livingroom_activity
        name: Living Room activity
        state: "{{ area_entities('living_room') | select('match', 'binary_sensor.') | select('is_state_attr', 'device_class', 'opening') | select('is_state', 'on') | list | count > 0 }}"
        delay_off:
          minutes: 5
plain magnetBOT
#

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

quaint hinge
marble jackal
#

I wouldn't say that matters, in both cases your room/area will count as active right?

#

as long as one of them is on, the area is active

#

@lusty ridge this is not related to #templates-archived, this channel is for jinja templates. Not sure what the right channel should be though

quaint hinge
#

yes, but the last active time would be the time of the window opening. The area would be marked as "inactive" regardless of the window still being open.

#

the timestamp is what marks the area as inactive, not the state of the sensors

#

eg: a door opening is an indication that something is active, but an open door isnt, it could be that someone forgot to close the door

#

actually, skip that, I can work with the time of the first sensor being tripped 🙂

marble jackal
#

ah okay, you want the last time it changed as the indicator that it is active

quaint hinge
#

ideally yes

#

Ideally I need both... an indicator for how long an area was in an active state and when it last detected activity. my motion sensors are still coupled to another system but both contact sensors and motion sensors would be used in an area to mark it as active

marble jackal
#
template:
  - binary_sensor:
      - unique_id: template_bs_livingroom_activity
        name: Living Room activity
        state: >
          {% set last_change = area_entities('living_room')
              | select('match', 'binary_sensor.')
              | select('is_state_attr', 'device_class', 'opening')
              | expand
              | map(attribute='last_changed')
              | last 
          %}
          {{ last_change > now() - timedelta(minutes=5) }}
#

that will create a binary sensor which is on when an opening sensor changes state, and turns off 5 minutes after the last cahnge

mighty ledge
#

5 minutes ± 1 minute

quaint hinge
#

the binary sensor created here, is only for within the template right? or is it an actual thing that I can access outside of the specific automation?

mighty ledge
#

that creates an entity that can be used anywhere

pearl grail
#

Hi guys,
I'm trying to create 2 template sensors for energy monitoring:

  • a template sensor for energy that will increment daily with 0.96 kWh each time a specific switch is on at 7AM or between 7AM and 8AM
    (use case: This will monitor my electric pump for sprinklers as I dont have a separate meter on it)
  • a template sensor for energy that will subtract daily from another energy sensor 0.425 kWh. I cannot subtract directly as I get a lot of negative values.
    (use case: This will subtract my daily average consumption (without air conditioning) from the total phase C energy consumption (air conditioning included), so the result would be AC energy consumption)
    Any ideas how can i use that?
    Thanks!
opaque sentinel
marble jackal
#

That, or create template sensors with a fixed power value (for the first case include an if statement making it 0 if the the switch is off) and integrate those to energy

pearl grail
#

That's what I thought, but I don't know how to write the if statement with time constraints.
Or I can make somehow the increment at 7:30AM only if the switch is on? 🤔

#

Where can I find some documentation about all possible if conditions?

bold vale
#

I have a Markdown Card with a text showing the total number of lights in my house, and the number of lights that are turned ;

`There are {{ states.light | selectattr('entity_id', 'in', label_entities('Light'))

            | list
            | count }} lights in the house,   {{ states.light | rejectattr('entity_id', 'in', label_entities('Lightgroup')) 
            | selectattr('state', 'eq', 'on')
            | list
            | count }} are turned on`

This results in it showing; There are 39 lights in the house, 1 are turned on
How do I change this to show; There are 39 lights in the house, 1 is turned on when there is only 1 light turned on?

opaque sentinel
#

I would probably assign the calculation to a variable (or template helper if thats your jam)

#

Then you could do {{ varName }} {{ varName == 1 and 'is' or 'are' }} turned on.

opaque sentinel
# bold vale I have a Markdown Card with a text showing the total number of lights in my hous...

So something like this I think would work (could probably be simplified 🙄):
{% set num_lights = states.light | selectattr('entity_id', 'in', label_entities('Light')) | list | count %} {% set lights_on = states.light | rejectattr('entity_id', 'in', label_entities('Lightgroup')) | selectattr('state', 'eq', 'on') | list | count %} There {{ num_lights != 1 and 'are' or 'is' }} {{ num_lights }} light{{ num_lights != 1 and 's' or '' }} in the house, {{ lights_on }} {{ lights_on == 1 and 'is' or 'are' }} turned on.

bold vale
#

that works, awesome, thank you 🙂

pearl grail
marble jackal
#

I'm not sure what you exaclty want here

#

why the time constraints?

pearl grail
#

Because if I see there is rain coming next day I deactivate the relay that supply the pump with energy at 22:00 or even if there's a storm during the night I might remember I left the relay on and turn it off

#

Then I turn it on anytime during the day

#

condition: state
entity_id: switch.releu20A
state: on

  • condition: time
    after: "7:00:00"
    before: "8:00:00"
marble jackal
#

But if you just use the state of the relay, you have your consumption right?

#

I assume it also consumes power if it's turned on at 6:00

pearl grail
#

No. The relay ON is just the power supply. For the actual sprinklers I have a programmable device that selects certain zones and open valves.

#

It's only mandatory for the relay to be on in the interval 7-8AM

marble jackal
#

well, anyway, you can't use these kind of conditions you posted in templates, you can compare times to the current time

#

have a look at the templating docs, they are linked to from this channel

plain magnetBOT
#
The topic of this channel is:

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

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

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

vale osprey
#

Hi guys, does anyone have any idea how to find the closes value using jinja?

#

I have a value from an entity, and then I have 3 values in helpers. I want to know which helper has the closest value to the entity

#

I think it's not gonna be an easy ride

opaque sentinel
#

Top of my head:
Set the initial value as a variable
Set two more variables: minimum difference (init it to something big) and closest helper (to empty value)

Loop through the three values and compare each value to the inital value
If the new value is smaller than the previous, assign it to the result variable

#

Something like that, hopefully that could point you in the right direction. 🙂

vale osprey
#

thanks 🙂

mighty ledge
vale osprey
#

float value

#

weight in Kgs

mighty ledge
#

can you describe what you're trying to do?

#

big picture, not what you want the jinja to do

vale osprey
#

Managed 🙂 got some assistance from chatGPT and made it work 😄

plain magnetBOT
#

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

vale osprey
#

Basically i'm using this for a scale... 3 people use the same scale. Each weighting a bit different than the other. So when you go on the scales the new value is checked against the current weight of the 3 people, the closes one is updated with the new value

mighty ledge
#
{% set target = states('sensor.a') | float(0) %}
{% set entities = ['sensor.b', 'sensor.c', 'sensor.d'] %}
{% set ns = namespace(items=[]) %}
{% for v in entities | select('has_value') %}
  {% set ns.items = ns.items + [{'e': v, 'd': target - v | float}] %}
{% endfor %}
{{ ns.items | sort(attribute='d') | reverse | first }}
#

that works with any number of sensors, not just 3

vale osprey
#

wow, thanks 🙂

marble jackal
#

to make it easier to maintain which entities to check, you could use labels

vale osprey
marble jackal
#

yes, or if you want to add or remove entities

vale osprey
#

I assume there is some function getEntityByLabel or something...

#

sorry for the questions but i'm not a developer... 🙂

marble jackal
#

label_entities('label_id')

plain magnetBOT
#
The topic of this channel is:

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

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

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

marble jackal
#

it's mentioned in the templating docs

vale osprey
#

much appreciated 🙂 thank you all

#

I think labels are being abused right now in all aspect. I think HA needs to split the concept in different properties

#

I would assume if labels are also being used in templates, the list of labels is huge on your end

frail dagger
marble jackal
#

it's up to the user how to use them 🙂

mighty ledge
#

abused is a harsh term

#

it's a great way to group items without needing a group entity

vale osprey
#

I love labels, don't get me wrong

mighty ledge
#

what makes it confusing?

#

it's a label

frail dagger
#

"a lot of different scenarios" Compared to what we had, labels should apply to a lot of different uses, imho.

vale osprey
#

exactly, and the name suits it well. As a label is quite generic and can be used for anything

#

but I feel that because of lack of certain other functionality for classification, etc, labels are being 'overused'

opaque sentinel
#

Areas, devices, helpers, entities, labels, categories, how much do you need?

frail dagger
#

I wouldn't say "overused". They're doing exactly what they are built for. Yes, you can overuse them in a sense I suppose, but I haven't hit that scenario at all. For instance, I have all my Zigbee router devices labelled with "Router". I can easily filter on all my routers and even break that down by areas if I choose to.

opaque sentinel
vale osprey
#

ye that is how i'm using them too, to group the device (router, socket, etc)

#

but then there are situations where I but a lable like 'Always On' , so when I switch off all the sockets for example, those with 'always on' are not switched off

#

which to me that sounds more like a 'tag' than a label

mighty ledge
#

labels are tags

#

tags in home assistant are already used.. for actual physical tags

frail dagger
#

lol I was just typing that

vale osprey
#

🙂

#

yes, so what Im saying is that those two scenarios are both being handled by labels. I would assume most of you have huge lists of labels

mighty ledge
#

Nope, rather small

vale osprey
#

oh okay 🙂

#

maybe I'm over complicating it, but what if you are able to create a label with sub labels? 🙂

opaque sentinel
#

I actually haven't used them at all in any automations/scripting, most of my usecases for many entities are already on the same domian

mighty ledge
#

You can do that, you can add multiple labels to entities

vale osprey
#

but you cannot set a parent to a label, right?

marble jackal
#

I have 24 labels right now

mighty ledge
#

you don't need a parent label

#

just mark everything with one label, then filter your list to said lable, and add your second label

#

and if you want to filter... label_entities('x') | select('in', label_entities('y'))

#

or don't even bother with that, and just go for label_entities('y')

#

I definitely think you're over complicating things

mighty ledge
vale osprey
#

19, 24 are fine. quite controlled

#

I think one of my issues for example is organising helpers. But that would be sorted the moment the device linking is done for all helpers and not just template helpers.

marble jackal
#

It's already done for more

vale osprey
#

glad to hear 🙂

vale osprey
#

Is it possible from a template to update a value of another entity? I guess not right?

#

has to be done through automations I guess

mighty ledge
#

uh, you should avoid that type of logic

slender adder
#

is there a way to translate in templates?

#

got this

#

Goedemorgen, het weer voor vandaag is {{
states('weather.forecast_thuis')}}

#

but weather.forecast_thuis = english, and it doesnt "Work" in the TTS XD

#

it says "cloudy" and it should be "bewolkt"

haughty breach
marsh cairn
#

Or {{ state_translated('weather.forecast_thuis') }} - same thing, other format

compact pond
#

Hey all,

Is it possible to get history data from 24 hours back as an int to use ?

mighty ledge
#

Only the SQL integration can do that

compact pond
#

Any documentation on that?

mighty ledge
#

Yes, in the sql integration

plain magnetBOT
compact pond
#

Thanks ❤️

tame axle
#

Hi! I'm trying to create a binary sensor that will be on if my bedroom1 motion sensor has detected anything in the past 5 minutes. I think I'm close but can't wrap my head around the template anymore.
The current behavior is: sensor is always off, turns unavailable when bedroom1 motion detects, then back to off. Here's the YAML: https://dpaste.org/Gg6Nz

slender adder
marble jackal
tame axle
#
Invalid config for 'template' from integration 'sensor' at configuration.yaml, line 33: 'delay_off' is an invalid option for 'sensor.template', check: sensors->bedroom1_motion_recently_on->delay_off

think i tried this before too, i remember this warning

#

also, is there a new format? i only knew about this one

inner mesa
#

you need to switch to the new template format for that

marble jackal
#

it's mentioned under the legacy format as well

marsh cairn
inner mesa
#

indeed

#

wait, you pointed to the new format 🙂

marble jackal
#

no, I linked to the legacy binary sensor configuration format

inner mesa
#

where it's not listed

marble jackal
#

but the anchor for delay_off is the same for the modern format and the legacy format, if you click on the anchor it moves to the new format

#

it's listed in my docs

inner mesa
#

oops, was looking at the wrong one

marble jackal
#

for some reason my image upload is'nt working, but you seem to have found it 🙂

inner mesa
#

yeah, images in Discord have been broken for a couple of days

#

they don't have any trouble showing the poop emoji

marble jackal
#

then I tried imgur, which gave me an unsupported filetype message, are they using the same backend?

#

anyways @tame axle you could try if it works in the modern format

frail dagger
#

When templating a for: in an entity state trigger, can we template the entire for: or just the hours, minutes, seconds? The docs show the indivial properties, but nothing for the for: itself.

marble jackal
#
template:
  - sensor:
     - name: "Bedroom1 Motion Recently On"
       state: "{{ is_state('binary_sensor.bedroom1_module_bedroom1_motion', 'on') }}"
       delay_off:
        minutes: 5
marble jackal
frail dagger
#

Gotcha. Ok. That makes sense. I've been trying to do dynamic fors and it's fighting me. lol

slender adder
#

then i only need all the states it can give me XD

tame axle
#
Invalid config for 'template' at configuration.yaml, line 33: 'delay_off' is an invalid option for 'template', check: sensor->0->delay_off

seems to be the same error
here's a truncated version of the whole config yaml, tho i think i put it where i should: https://dpaste.org/dF7x3

frail dagger
#

You're missing a space before minutes: 5 (you only have 1 space there)

tame axle
#

oh, my bad. should have checked intendation

frail dagger
tame axle
#
Invalid config for 'template' at configuration.yaml, line 34: 'delay_off' is an invalid option for 'template', check: sensor->0->delay_off

i just don't think that's possible https://dpaste.org/KpNfa

#

think i'll make it work with some automations and timers

slender adder
#

ok found them
CLEAR_NIGHT
CLOUDY
FOG
LIGHTNING_RAINY
PARTLYCLOUDY
POURING
RAINY
SNOWY
SNOWY_RAINY
SUNNY

#

then ill do it like this

inner mesa
slender adder
#
{% if is_state('weather.forecast_thuis', 'SUNNY')}} %}
Zonnig
{% if is_state('weather.forecast_thuis', 'CLOUDY')}} %}
Bewolkt
slender adder
#

or should i take this diffrent?
do you have switch statements?

#
Switch(state('weather.forecast_thuis')){
  "Sunny" = "Zonnig"
  "Cloudy" = Bewolkt
}

Something like this?

frail dagger
#

There is no switch statement.

slender adder
#

ok what is the best practis in this case then ?

inner mesa
#

you can do something like that with a straightforward map/lookup

#
{% set map = {'foo': 'bar', 'blah': 'floop'} %}
{{ map['foo'] }}
slender adder
#
{% set map = {'weather.forecast_thuis'} %}
{{ map['sunny'] }}
{{ map['Cloudy'] }}
#

like this?

inner mesa
#

no

#

that's nothing like mine 🙂

#
  1. make a dict that maps values
  2. Index into it
slender adder
#

wait let me show you the whole concept

#
service: tts.speak
metadata: {}
data:
  media_player_entity_id: media_player.sonos
  cache: false
  language: nl
  message: >-
    Goedemorgen, het weer voor vandaag is
    {{state_translated('weather.forecast_thuis')}}.   En de temperatuur is
    {{state_attr('weather.forecast_thuis','temperature') }} graden.  Vandaag
    moet je naar {{state_attr('calendar.werk','message') | replace ("Service
    Call:","") | replace(" B.V.","") }}.  Geschatte reistijd is
    {{state_attr("sensor.google_travel_time", "duration_in_traffic") |
    replace("mins","minuten")}}.
  entity_id: tts.google_en_com
#
{{state_translated('weather.forecast_thuis')}}. 

This part needs to be translated to dutch

#

but i dont wanna change my general to dutch

inner mesa
#
{% set map = {'Sunny': 'Zonnig', 'Cloudy': 'Bewolkt'} %}
{{ map[states('weather.forecast_thuis')] }}
slender adder
#

sick this works

#

thx allot @inner mesa

#

is it allowed like this

  {% set map = {'Sunny': 'Zonnig', 
                'Cloudy': 'Bewolkt', 
                'rainy': 'regenachtig'} %}
  {{ map[states('weather.forecast_thuis')] }}
inner mesa
#

try it?

slender adder
#

nice it works

inner mesa
#

?

#

that would have been easy, right? 🙂

slender adder
#

if some1 else wants it

      {% set map = {'Sunny': 'Zonnig', 
                    'Cloudy': 'Bewolkt', 
                    'rainy': 'regenachtig',
                    'Clear_Night': 'een heldere nacht',
                    'fog': 'Mistig',
                    'lightning_rain': 'Bliksem & regen',
                    'partlycloudy': 'Gedeeltelijk bewolkt',
                    'pouring': 'Zware regen',
                    'snowy': 'Sneeuwerig',
                    'snowy_rainy': 'Nattesneeuw'}%}
      {{ map[states('weather.forecast_thuis')] }}

Translated to dutch

inner mesa
#

it would be strange for the integration to reports states like "Sunny", "Cloud", "rainy", and "lightning_rain"

#

they are usually consistent in case and space handling

slender adder
#

also seen this 1

"clear-night": "Clear, night",
"cloudy": "Cloudy",
"exceptional": "Exceptional",
"fog": "Fog",
"hail": "Hail",
"lightning": "Lightning",
"lightning-rainy": "Lightning, rainy",
"partlycloudy": "Partly cloudy",
"pouring": "Pouring",
"rainy": "Rainy",
"snowy": "Snowy",
"snowy-rainy": "Snowy, rainy",
"sunny": "Sunny",
"windy": "Windy",
"windy-variant": "Windy"

inner mesa
#

"sunny" is not "Sunny"

slender adder
#

and then the right side is good

inner mesa
#

"cloudy" is not "Cloudy"

#

note that everything on the left side is lowercase

slender adder
#

yea but when i check my history i see it like thisa

inner mesa
#

that doesn't matter, it's not the real state

slender adder
#

you think the left side is the right 1 ?

inner mesa
#

looks better, but I'm also reading the thread there

marble jackal
#

What kind of weather is it when an integration states exceptional

slender adder
#

very good 😛

#

dunno

inner mesa
#

exceptional rain and thunder and hurricaney

slender adder
#
      {% set map = {'sunny': 'Zonnig', 
                    'cloudy': 'Bewolkt', 
                    'rainy': 'regenachtig',
                    'clear, night': 'een heldere nacht',
                    'fog': 'Mistig',
                    'lightning, rain': 'Bliksem & regen',
                    'partly cloudy': 'Gedeeltelijk bewolkt',
                    'pouring': 'Zware regen',
                    'snowy': 'Sneeuwerig',
                    'hail': 'Hagel',
                    'snowy, rainy': 'Nattesneeuw'}%}

This should be better then

marble jackal
#

clear, night is correct now

#

😅

slender adder
#

you say like this

marble jackal
#

Yeah, I started typing that, and then you corrected it. Now you made it wrong again

slender adder
#

its wrong now?

opaque sentinel
#

"Nattesneeuw" is a wonderful word

marble jackal
#

Yes

slender adder
#

how

marble jackal
#

clear-night is correct

inner mesa
inner mesa
#

"clear-night": "Clear, night",

slender adder
#

yea but i wanna have it translated

inner mesa
#

ahhhh

#

ok

#

I think you may be missing how this works

marble jackal
inner mesa
#

TheFes will help 🙂

slender adder
#

like this

'clear-night': 'een heldere nacht',

marble jackal
#

You did that while I was about to say it was wrong, and then I made it confusing by changing my message instead of just not sending it

slender adder
#
      {% set map = {'sunny': 'Zonnig', 
                    'cloudy': 'Bewolkt', 
                    'rainy': 'regenachtig',
                    'clear-night': 'een heldere nacht',
                    'fog': 'Mistig',
                    'lightning-rainy': 'Bliksem & regen',
                    'partlycloudy': 'Gedeeltelijk bewolkt',
                    'pouring': 'Zware regen',
                    'snowy': 'Sneeuwerig',
                    'hail': 'Hagel',
                    'snowy-rainy': 'Nattesneeuw'}%}
      {{ map[states('weather.forecast_thuis')] }}
marble jackal
#

There's also some inconstancy in the use of capital letters in your translations, but that's not an issue for the template itself

slender adder
#

you dont hear that in the TTS

inner mesa
#

just offends my OCD

slender adder
#

ah yea

#

i see now

#

when i change the state to snowy-rainy it says in the history snowy, rainy

#

good

#

cool the translate part also works now so this is all done 🙂

unique turret
#

How do I about creating a binary_sensor based on Mobile app connection type? so for example the if the mobile is connected to 'WiFi', they are shown as 'Home' and vice-versa, thanks

slender adder
frail dagger
slender adder
#

this way you can filter with SSID

unique turret
frail dagger
#

That's only available on Android. iOS doesn't have that.

slender adder
frail dagger
#

_connection_type is available on both

unique turret
slender adder
#

ah that sucks XD

#

i just installed it and pressed on my own allow location 🙂

#

they dont even know >:)

unique turret
#

Another wish of mine lol

slender adder
#

something else you can track them on on your SSID?

#

would go that route, when they connect with your wifi they are "Home"

#

unless you dont have that ofc

frail dagger
#

Ooohhhh and now you can also attach it to the mobile device itself! Love that new feature.

unique turret
#

I've just noticed this as well, awesome feature handgesture

slender adder
#

only for sensors or also for text helpers?

frail dagger
#

Only for sensors. I think it's going to come to the other helpers as well.

unique turret
#

Can the binary sensor be shown as a device_tracker, so I can replace the default one?

silent seal
frail dagger
#

You can also set the device class to Presence to simulate it as well. Either way should work.

unique turret
#

I've classed it as Presence and it works well, but HA doesn't detect it as a device_tracker even when linking the template. So, if I used the Person entity in frontend cards, it will only detect the default device tracker and not the template binary_sensor

unique turret
frail dagger
#

IIRC (it's been a few years since I've done this), you'd just create a device tracker in known_devices.yaml (if it doesn't exist, you can create it). It would look like:

wifi_device_tracker:
  name: Wifi Device Tracker
  icon: mdi:cellphone
  track: true

Then, you would need an automation to trigger (this is where you can use your binary template sensor) and call the device_tracker.see service.

unique turret
#

Ah good old known_devicse, I'll look in to it, thanks! 🙂

silent seal
#

That file is deprecated, so you may want to consider that it's going away 🙂

frail dagger
#

True... but I think it's been on the chopping block now for what, 2+ years? lol

arctic sorrel
#

I just create MQTT device trackers, HA can then publish to make them "move"

silent seal
arctic sorrel
#

Same same

unique turret
#

Interesting, thank you all

frail dagger
#

Since version 0.94 lol

silent seal
#

Sometimes you realise early on you made a mistake, but it's already really difficult to unpick

unique turret
#

How would I get it to appear on frontend?:
{{ state_translated(binary_sensor.person_presence) }}

mighty ledge
#

you're missing quotes

unique turret
#

oh my bad, thanks

plain magnetBOT
#

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

half pendant
#

I have a moving IKEA Desk that i want to build a sensor around if it's moving or not. I can see the current height but i'm unsure on how to build a template around if it's changing or not. I'm thinking i should be able to check when it was last change and if that's greater than a very small number then it's most probably moving (doesn't have to be bulletproof) still. I'm just not sure how to achieve that. Any ideas?

mighty ledge
#

Use a derivative sensor to get the rate of change. If the rate of change is > 0 it's moving.

half pendant
#

doesn't seem to work. THe height is reporter as number.megadesk_current_height and can't seem to be used in derivate sensor

mighty ledge
#

make a template sensor from the number

#

{{ states('number.megadesk_current_height') }}

half pendant
#

What settigns do i use for the derivative?

mighty ledge
#

You have to figure that out

half pendant
#

ok because i tried the standard one and it does not give me 0 when the desk i standing still

mighty ledge
#

it depends on how fast your sensor changes state and what the values are

half pendant
#

Hmm. I don't think it will work. When i use the buttons on the desk it does update the sensor in near real time but if i tell it to go to a postition nothing updates until it's done

mighty ledge
#

paul, go bakc to automations and click that link

lucid thicket
#

The derivative sensor will (usually) never go to zero because (most) sensors are prevented from reporting repeated values.

mighty ledge
#

That won't always be true because state reported was added to address that

plain magnetBOT
#

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

haughty breach
#

Templates are not supported in card actions in most card types. You need to move your service call to a script, then call the script from the card's action.

lucid thicket
mighty ledge
#

yes, but it was specifically added to address integration and derivative

lucid thicket
#

At least Riemann was updated to support a max sub-interval, which I think takes advantage of the last reported. Derivative has had no such update

mighty ledge
#

I think you're not understanding my original statement

#

It seems like you're aruging that derivative doesn't have it when I said that it will be changed in the future

#

that won't always be true

lucid thicket
#

I did misunderstand

#

I get what you were saying now 😂

livid pollen
#

Hello. I am trying to reuse a RESTful Sensor that is connected to a dashboard gauge. It currently displays water level for a pump, but I have two of them. For it to work as desired, I would need to pass it a different variable (device id). Is this possible at all?

#
  name: Water Level
  unique_id: water_level
  resource: http://api.ptdevices.com/token/v1/device/1234
  scan_interval: 900
  params:
    api_token: !secret api_token
  value_template: "{{ value_json['data']['device_data']['percent_level'] }}"
  unit_of_measurement: "%"```
frail dagger
#

You'll want to use two different names and unique_ids as well.

livid pollen
#

Can I pass the device ID as an input text from the gauge?

#

so I don't repeat that block of code

frail dagger
#

You could, but if you have 2 devices, wouldn't you want 2 sensors?

livid pollen
#

You're right

#

Sorry, last question. Is there a way to create 2 sensors based off the same code, but with different inputs?

#

I'm just trying not to repeat the code above twice, but maybe I'm overthinking it..

marsh cairn
#

Using the same api call?

livid pollen
#

No, each will have a different api call

#

basically 1234 (device id) would change

marsh cairn
#

If I understand your goal, you would have to set up a second one with the according template again

livid pollen
#

Ok. Thank you @frail dagger and @marsh cairn

maiden magnet
#

hi, can i mark a todo item as completed by only specifying the number of the array?
for example: todo.example[1] or something like that? i know i have to do it with the get service, but can i do this with the outputvariable?

inner mesa
#

The todo.update_item service takes the name of the item, so nothing there about taking an index in a list

#

You could get the name of the item by the list index and pass that

maiden magnet
#

how do you mean that?

#

how can i get the name of an item?

inner mesa
#

From the list you get back

maiden magnet
#

i can now get a list of all items, yes, but how do i output only the first item of the list?

wooden tusk
#

How to identify the device used when triggering a scene?

silent seal
wooden tusk
#

Can trigger data be used when running a scene too?

marsh cairn
#

What exactly are you trying to achieve?

wooden tusk
#

If a have a physical device in an area. I trigger a scene, I then depending on in what area the device is located turn of the lights in that area.

#

So I can have a generic scene that works for all areas.

#

Scene “turn of lights” triggered, what device triggered the scene, what area is that device located, turn of all lights in that area.

marsh cairn
#

That sounds like an automation

#

In those, you can use the trigger data, Rosemary suggested

torn ivy
#

best plugin for good lovelaces?

marsh cairn
#

Wrong channel?

torn ivy
#

and in which channel should i post it?

wooden tusk
#

Yes I can use trigger data, but what data locates the device triggered the automation?

silent seal
marsh cairn
vernal egret
#

Hi all. New to HASS and Jinja. Got a project where I am trying to calculate solar clipping using the forecast.solar API and a script. Even if I set the clipping threshold to a lower number than the current forecasted values I always get 0.0kWh result from the script. Here's the sensor and script config, and help would be awesome, the traces don't show any failures so I think it must be the logic in the script.

https://dpaste.org/FUSXO

lucid thicket
#

You can’t set or modify a variable inside a for loop and see the results outside that for loop

#

You need to use a namespace

wooden tusk
#

How to template using the current device used. Eg using a physical panel in an area and only displaying entities in that area were its assigned. Eg a For loop of entities in an area but only entities in the area were the physical device is located.

#

[{% set area_filter = states('device.room') %}
{%- for light in area_entities(area_filter) | select('search', '^light.') -%}

vernal egret
lucid thicket
#

I’m on my phone otherwise I’d type up an example for you

#

But that link has a good example for how to use namespace

vernal egret
# lucid thicket Scroll down to the heading titled “scoping behavior”: https://jinja.palletsproj...

Ah that makes sense. Unless I am mistaken, HASS seems to have a more limited implementation of Jinja?:

SCOPE OF VARIABLES
Variables have local scope. This means that if a variable is changed in a nested sequence block, that change will not be visible in an outer sequence block.
Inside the if sequence the variables action will only alter the people variable for that sequence.

https://www.home-assistant.io/docs/scripts/#variables

lucid thicket
#

No it is not a limited version. This should do what you want:

sequence:
  - variables:
      clipped_energy: >
        {% set ns = namespace(clipped_energy = 0) %}
        {% set interval_hours = 15 / 60 %}
        {% for timestamp, value in data.items() %}
          {% set value = value | float %}
          {% if value > threshold %}
            {% set ns.clipped_energy = ns.clipped_energy + ((value - threshold) * interval_hours) %}
          {% endif %}
        {% endfor %}
        {{ (ns.clipped_energy / 1000) | float }}
lucid thicket
vernal egret
frail dagger
abstract maple
#

Hey all, it seems everything in HA is a sensor or binary_sensor. I'm looking for ways to discern sensors by the type of device they belong to. Can that even be done?

#

as an example, I want all batteries that belong to switches as opposed to batteries that belong to temperature sensors etc. I also want to make sure if one device offers multiple functionalities, I only want to select it once.

frail dagger
# abstract maple Hey all, it seems everything in HA is a sensor or binary_sensor. I'm looking for...

Everything in HA is an entity. But, there are some different ways to do this. The easiest by far is with labels. It's a bit more time upfront (especially if you have over 2K entities), but allows for some really neat things. Especially since devices are defined by the integration they belong to and there really aren't many concrete standards in terms of how an integration exposes devices and entities.

#

You could also do some stuff with domains as well.

abstract maple
#

Hm. That sounds like a lot of work.

frail dagger
#

Upfront, sure. But it pays off in the end and allows for some interesting use cases.

abstract maple
#

true that.

#

Guess I'll just dig deeper into the various integrations and their attributes and see what I can come up with.

frail dagger
#

For instance, one thing that cannot be done via devices if using something like Zigbee2MQTT is to grab all my routing devices. With labels, all my routers are marked and I can just do a {{ label_entities('router') | list | count }} and get a count of all my Zigbee routers. Can't do that with device lookups.

lucid thicket
# vernal egret Nice! Thanks so much. Working now 👍

You can also skip the looping entirely. Something like this:

sequence:
  - variables:
      clipped_energy: >
        {% set interval_hours = 15 / 60 %}
        {{ data.values() | map('add', -threshold) | reject('lt', 0) | sum * interval_hours }}
vernal egret
hexed glacier
#

I am going slightly crazy. I am trying to dynamically change the image_entity in the Picture card. I have a text helper with the text of the image entity. I would like get that value in the field, but no matter how I try, I always get Entity is unavailable. This is all I am trying to do:

lofty mason
#

can't use templates there

#

@hexed glacier

hexed glacier
# lofty mason can't use templates there

Thanks. Is there any other way you can recommend achieving making that field dynamic? I do have an automation that saves a snapshot as latest.jpg and thats the image i can point to. I thought there could be a better way through the template.

lofty mason
#

default frontend in general just doesn't use templates at all. that's a backend thing.

hexed glacier
lofty mason
#

I'm not familiar with custom_templates

nocturne chasm
#

I keep getting Template variable warning: 'dict object' has no attribute 'events' when rendering '{{ birthdays.events }}'

mighty ledge
#

it's telling you that birthdays does not have events as a key inside it.

#

correct syntax is {{ birthdays['calendar.family_birthdays'].events }}

nocturne chasm
#

so in the actual state or state_attr?

mighty ledge
#

state or state_attr has nothing to do with it

#

the response from get_events is a dictionary with key value pairs in it. The key being entity_id and the value being a dictionary with the events key.

nocturne chasm
#

so this then?

      - variables:
          events: "{{ birthdays['calendar.family_birthdays'].events }}"
          descriptions: "{{ events | map(attribute='message') | join(', ') }}"
mighty ledge
#

Yes

nocturne chasm
#

I got all that from one of your old posts 😉 kinda

mighty ledge
#

no way I created those start/end templates

nocturne chasm
#

oh, no...I did that

mighty ledge
#

they can be reduced to 2 lines

nocturne chasm
#

I'll take if you are helping

#

i am a junior templater

mighty ledge
#
{% set days = states('sensor.family_birthdays_days') | int %}
{{ today_at() + timedelta(days=days) }}
#

oh and end would be

#
{% set days = states('sensor.family_birthdays_days') | int %}
{{ today_at() + timedelta(days=days + 1) }}
#

if you don't care about long lines...

nocturne chasm
mighty ledge
#
{{ today_at() + timedelta(days=states('sensor.family_birthdays_days') | int) }}
nocturne chasm
#

I am guessing message is wrong?

mighty ledge
#

message?

#

i'd have to see what the event structure is

nocturne chasm
#

it is local calendar

mighty ledge
#

it's most likely summary

nocturne chasm
#

thats what I thought

mighty ledge
nocturne chasm
#

still unavailable

nocturne chasm
mighty ledge
#

then message is the field

nocturne chasm
#

maybe it is unavailable because it hasn't triggered yet?

mighty ledge
#

are there errors in your logs?

#

it's unavailable because it didn't load

#

if it didn't trigger, that would be unknown

hexed glacier
nocturne chasm
#

nope, no errors

#

setting the state of sensor.family_birthdays_days in dev_tools states wont actually trigger the sensor will it

mighty ledge
#

that means the entity doesn't exist

#

are you sure ther'es no errros in the logs?

mighty ledge
#

There's a very good chance that you can solve your issue with template entities over whatever you're doing with that input_text and automations.

nocturne chasm
#

it created a entity_id_2

#

need to make some alterations

#

2024-07-12 00:00:00-04:00 will the -4:00 mess with the start and end date?

#

now I am getting errors:

Template variable warning: 'dict object' has no attribute 'events' when rendering '{{ birthdays.events }}'
Template variable warning: 'dict object' has no attribute 'message' when rendering '{{ events | map(attribute='message') | join(', ') }}'
mighty ledge
#

those are most likely old

#

if you use a unique_id, reloading templates won't create _2 entities.

nocturne chasm
#

yea, i changed the unique_id which was the problem

#

so now it reports a state of 2 but I want the actual calendsr event

mighty ledge
#

can you just post all the code

nocturne chasm
#

Test1 Birthday

#

yea, hold on...will do another link

#

what I am ultimately trying to do is send birthday notifications 3 days out. 2 days out, 1 day out and then other stuff with voice assistants on the actual day

mighty ledge
#

so, your template sensor will not contain birthdays on separate days

#

if you have 2 birthdays with 3 days of eachotehr this thing will not work

#

if that's not a problem... then what you're doing is fine

nocturne chasm
#

oooh, I think I got it

#
friendly_name: Today's Birthdays
birthday_events: 
- start: '2024-07-12'
  end: '2024-07-13'
  summary: Test1 Birthday
  description: ''
- start: '2024-07-12'
  end: '2024-07-13'
  summary: Test2 Birthday
  description: ''
- start: '2024-07-12'
  end: '2024-07-13'
  summary: Test3 Birthday
  description: ''
#

now to figure out how to say Happy Birthday to Test1, Test2, and Test3 😜

nocturne chasm
#

and I am still getting Template variable warning: 'dict object' has no attribute 'message' when rendering '{{ events | map(attribute='message') | join(', ') }}'

#

I think i need summary now

#

thank you for your help @mighty ledge

mighty ledge
#

and because HA is async, you never know which one you'll get

nocturne chasm
#

ha, no all on the same day

#

this one is just for immediate family

#

later I will only trigger on 0 for extended family

mighty ledge
#

I think you're missing my point though

hexed glacier
nocturne chasm
#

but all birthdays are more than 3 days apart

mighty ledge
#

ah ok

nocturne chasm
#

only 5 people 😜

mighty ledge
#

then use that

#

or a generic camera entity

#

and use that

#

no input_text or automation needed.

#

just point to the media file.

hexed glacier
#

My idea is I have 5 cameras and wanted to show the image of the of the one the one that triggered. I use frigate, so I could access it at image.camera_name. I made a helper to get the latest camera that showed the image and my plan was, to insert the image_entity of the camera entityid. The issue was, I couldn’t even get it to get the value from a text helper. So templates no allowed, made sense, I couldn’t use the helper or a custom template to do that I was trying to do.

mighty ledge
#

at most

#

fully post what you have and I can show you what I mean

hexed glacier
#

That was in the helper. and i was trying to get it to work getting the state of the helper

mighty ledge
#

what do you mean "without getting the state of the helper"

hexed glacier
#

trying to get it to work with the state. * image_entity: '{{states(sensor.getlatestperson)}}'. sensor.getlatestperson is the id for the helper

#

Thats all it was. The helper to store it and the picture card to show it.

mighty ledge
#

Yes, then all you need is a template image entity, nothing more.

hexed glacier
#

I have tried. I am just not getting it. Thanks anyway.

plain magnetBOT
#

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

rich temple
#

Someone pleae help me with this, im tryna to create a custom sensor for this because TAPO removed it 😄

fossil venture
#

The legacy template sensor platform does not support state_class and it will not be added. You need to use the new template integration.

rich temple
fossil venture
#

Yes

rich temple
#

okay, im gonna try it, thank you!

#

can i somehow set a Friendly Name after?

fossil venture
#
# configuration.yaml
template:
  - sensor:
      - name: Total Consumption
        state_class: total_increasing
        device_class: energy
        unit_of_measurement: "kWh"
        state: "{{ states('input_number.total_consumption') }}"```
rich temple
#

i have it now!

#

thank you!

fossil venture
#

Also confusingly this would have been better off in #integrations-archived as it is not actually a question about the template itself. But it's quite in here. Remember for next time.

rich temple
fossil venture
#

No probs.

rich temple
#

❤️

plain magnetBOT
#

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

thick matrix
#

Looking for some help on a template cover configuration. The resulting cover entity in HA and HK are not updating despite the LG washer (and sensor status) changing.

Goal: expose a sensor/switch/cover from HA to HomeKit which is toggled when the washing machine is finished (then configured to alert us via the native apple home activity notifications functionality).

Working integration from LG via the https://github.com/ollo69/ha-smartthinq-sensors HACS add-on.

Here's what's in my configuration.yaml:

plain magnetBOT
#

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

thick matrix
#

If everyone can see these file conversions I'm SO SORRY (and mortified) 😅

fossil venture
graceful whale
#

How do I get the response to weather.get_forecasts in a template to work with? Guessing there’s some function to call

#

The state function seems to only work with sensors, not services

#

Should I be looking for these functions in the Jinga docs, HA docs, or integration docs?

tepid citrus
#

I have zigbee innovelli blue lightswitches, and they have a number. innovellixxxxxx entity that sets the default indicator led color by hue. It is a 0-255 value, where zero is white and the hue rotates through for the other values. What I would like to do is define a template light to remap the 1-255 range to degrees, so that I can use a light entity in a card and have the hue coloring for the slider.

lucid thicket
mighty ledge
mighty ledge
tepid citrus
# mighty ledge make a template select, with the following template for the state: ``` {{ states...

Thanks for the example, I did not really know about select template. My understanding is that I'll need to make an actual template light if I want to use the colorize attribute hue on the slider in lovelace, or it won't apply that.
`type: entities
entities:

  • type: custom:slider-entity-row
    entity: number.inovelli_vzm31_sn_default_all_led_on_color
    name: LED Bar hue
    colorize: true
    attribute: hue`

Maybe I can instead set up a hue picker that works directly like a template select? The main thing I want is a visual colormap in the lovelace interface, not just the rescaling of the input.

mighty ledge
mighty ledge
graceful whale
#

I think I asked the wrong question. Is my understanding correct that a Service is something that is immediately executed and waits for a return value/ status (asynchronous function call) and a sensor is a value that is periodically updated, so it’s value can be read instantly? I know that I can get a value from a service call into a template by calling the service separately before getting to the template part. However, I see that I have something called an “entity” named “outside” and “weather.kw99_daynight”. That seems to already contain weather data, including all forecasts. Is this already accessible somehow in a template (and periodically updated without having to call the service constantly ), or is the entity-viewer just calling the service?

mighty ledge
#

what you're seeing is old information wherever you found it

#

weather entities used to have forecast attributes, but htat was removed to keep the large data out of the database

graceful whale
mighty ledge
#

is that a custom integration?

#

if yes, custom integrations... all bets are off, they can do whatever they like

graceful whale
#

“National Weather Service”. Not listed in HACS. Any other way to determine if it is “custom?”

frail dagger
#

If it's in the integrations page on the HA website, it's a native integration.

mighty ledge
#

NWS does not have the forecast attribute

mighty ledge
#

that's a special window.

#

go to developer tools -> states page to see the available attributes