#templates-archived

1 messages · Page 81 of 1

marsh cairn
#

That is what the template sensor I sent him does once an hour.

lucid thicket
#

Hah. Yes exactly that.

scenic verge
#

how? ```service: weather.get_forecasts
data: {}


tried quite some combinations, pasting "{{ hourly['weather.openweathermap'].forecast[0].precipitation_probability }}"
in there, but no luck.
frail dagger
#

Dev tools > services > weather.get_forecasts. Choose your entity and the data gets returned. That's how you see the structure.

marble jackal
#

Well, exactly the same as you do it in the code for the sensor

#
service: weather.get_forecasts
data:
  type: hourly
target:
  entity_id: weather.openweathermap
response_variable: hourly
scenic verge
#

thanks, that worked....but more confusing.

marble jackal
#

How so? This is what you are using as input for your template sensor

scenic verge
#

so it returns times that are in the past, is the clock perhaps incorrect then of this integration or something?

marble jackal
#

The times are UTC

scenic verge
#

it shows 19:00 as earliest time, but it's 21:29 here.

marble jackal
#

See the +00:00 at the end. You are in the Netherlands and daylight savings is active, so you are in timezone +02:00

#

So the first time is 21:00

#

Which is the forecast of the current hour

scenic verge
#

so i need to set the +02:00 somewhere?

marble jackal
#

No

#

The times are shown in UTC

#

HA knows how to handle those

#

It knows your current timezone

scenic verge
#

ok

#

so openweathermap'].forecast[0], would grab the top datetime state?
openweathermap'].forecast[1] would grab the hour after?

marble jackal
#

correct

scenic verge
#

thanks a lot everyone here, think i got forecasts set up now, and with these examples its easier to build up additional things i might need. can probably easily create copies now.

coral gale
#

Can you try this?

{{ string(state_attr('sensor.viewassist_masterbedroom_intent',
      'intent_output')['response']['speech']['plain']['speech']) != 
      "Sorry, I couldn't understand that"}}
bronze prawn
stray ermine
#

hey, I am looking to improve one of my automations but I am struggling with how to template part of it.

The automation is fairly simple, it compares the dew point inside the house vs outside and if any windows are in the "wrong" state and someone is at home it will send a mobile app notification to that person and also announce on the assist speaker that the windows should be closed / opened.

What I am trying to do is enhance the notification (both mobile and TTS) so that it actually includes which windows specifically are in the "wrong" state.

TL;DR is there a way to pass a dynamic list of sensor entities in a specific state to the notify_mobile_app and tts service ?

crimson lichen
#

I try with map('device_name')
{{ integration_entities('mqtt') | select('is_state', 'unavailable') |map('device_name') | unique | list | join('\n') }}
But error:
TemplateRuntimeError: No filter named 'entity_name'
How to get Name of device

lucid thicket
marble jackal
#

You can also use name_by_user

#

Then you get the name you gave the device

daring turret
#
  • platform: template
    sensors:
    dag:
    value_template: "{{ ['Pazartesi', 'Salı', 'Carsamba', 'Persembe', 'Cuma', 'Cumartesi', 'Pazar'][now().weekday()] }}"
    dato:
    value_template: "{% set months = ['ocak', 'subat', 'mart', 'nisan', 'mayis', 'haziran', 'temmuz', 'agustos', 'eylul', 'ekim', 'kasim', 'aralik'][now().day | string + ' ' + months[now().month-1]}}"
#

whats problem here

inner mesa
#

aside from the fact that you didn't format it properly here

#

value_template: "{% set months = ['ocak', 'subat', 'mart', 'nisan', 'mayis', 'haziran', 'temmuz', 'agustos', 'eylul', 'ekim', 'kasim', 'aralik'][now().day | string + ' ' + months[now().month-1]}}"

#

it looks like you started with setting a variable and then went straight into some output logic

#

so you're missing the end of the first part and your output part is misformatted

#

The easiest way to proceed is to apply the format you used in the first one to the second. For some reason, you decided to do something different

daring turret
#

@inner mesa

haughty breach
#

All you need to do is replace the [ before now().day with %} {{ so the statement gets completed and the expression is properly started.

marble jackal
#

No, they need to replace {% set months = with {{

inner mesa
#

Just like in the first one, like I said earlier 🤷

robust star
#

curious about how something works, if i were to use the following in the templates developer tool i am returned the result null
{{ states.sensor.afvalinfo_home_trash_type_tomorrow.state }}
However if i were to add this below that line i get None , twice.
{{ states('sensor.afvalinfo_home_trash_type_tomorrow') }}

#

if i were to go to the entity in the GUI i am also shown None

#

Why is there a difference in stating it twice?

daring turret
haughty breach
lucid thicket
# robust star Why is there a difference in stating it twice?

This is just how the template tool, and I think Python in general, works. Python is dynamically typed, and you can see the Result type displayed next to the output. If you put {{ None }} as the only thing on the template tool, it gets typed as a dict (Result type: dict) and it will render null. If you add anything else outside of that template, like {{ None }} a then the entire template will be rendered as a string and you’ll see None a because that’s how the NoneType variable gets rendered when joined into a string

#

Or more explicitly replicating what you saw, enter one line and then both lines of this into the template tool:

{{ None }}
{{ None }}
bronze prawn
#

Asked a question in blueprints but will ask here as well as it may be more applicable. I have a BP that is accepting an input which contains a python list. I believe this is being returned as a string and the automation is not validating. Can I convert a string to a list in jinja?

#
          - if:
              - condition: template
                value_template: >-
                  {{ trigger.slots.mode in ['normal', 'night', 'hold', 'cycle'] | trigger.slots.mode in ['do not disturb'] }}

Hold on. So I think it is my formatting. Can I not do this? If I remove one of the options and the pipe it validates

inner mesa
#

That template doesn't make any sense

#

What are you trying to do there?

bronze prawn
#

I changed the pipe to 'or' and it is working.

I guess I made an assumption that I could use pipe in place of or. Apologies for the bother.

knotty idol
#

trying to create a time of day sensor and im getting a error for my template:

{% set current_time = now().astimezone('America/Chicago').hour %} {% if current_time >= 5 and current_time < 12 %} mdi:weather-sunset-up {% elif current_time >= 12 and current_time < 17 %} mdi:weather-sunny {% elif current_time >= 17 and current_time < 21 %} mdi:weather-sunset-down {% else %} mdi:weather-night {% endif %}

inner mesa
#

"a error"?

knotty idol
inner mesa
#

are you trying to use the time in a different time zone than the one you've set for your HA instance?

knotty idol
inner mesa
#

fix that before trying to work around it

knotty idol
#

I have updated the time zone but it still thinks its night right now

marble jackal
#

What does {{ now() }} return in developer tools > templates

knotty idol
inner mesa
#

pretty sure not

fringe sail
#

Hey guys. How would I sync an input number to a timer counting down?

obtuse zephyr
#

What are you looking to achieve?

fringe sail
obtuse zephyr
#

Right, but that's just restating the solution you mentioned above. What are you actually looking to do with the result of this? For example, you can just use an entities card (or other cards) to display the timer duration on a dashboard if you're looking to observe the timer

fringe sail
#

There's no other reason than trying to better understand how to make templates. In my attempt to learn, I imagine a scenario and then try to do it with a template.

lucid thicket
# fringe sail There's no other reason than trying to better understand how to make templates. ...

To be clear, I timer doesn’t actually count down. It stores a finishes_at attribute with the datetime that it should finish. Then it fires an event and changes state to idle when that datetime is == now. It’s only the frontend that makes it appear that something is counting down. Changing an input number every second would create a lot of useless entries in your history database and waste cpu time.

#

HA prevent people from doing what you want to do exactly because of the reasons I mentioned. Specifically, templates with now() are throttled to only execute once per minute

lucid thicket
#

Just for learning’s sake, yes you could create an automation or a trigger-based template sensor and trigger it using a time pattern of every second.

I hate mentioning that because someone will inevitably see this and start doing that instead of using timers, and then will come back complaining about how slow HA is and how large their database is

fringe sail
frail dagger
#

If you really want to learn templates, a good place to start is things like complex binary sensors. For instance, detecting when you are home/away during times of the day or something. Or combining different sensors together. That’s really how I learned how to do some interesting templates. Also, asking for ideas is sometimes a good idea as well.

#

I have a couple that check various conditions and combines them up into a single binary sensor. Works great for scripts and automations.

fringe sail
#

I've gotten ok at those scenarios. It's the timed based things that throw me.

frail dagger
#

Ah, gotcha. Yeah, those get complicated quickly. lol

fringe sail
#

Those damn time codes look like Mandarin to me

lucid thicket
#

For a simple starter, try creating an automation that triggers at a specific time, but use a template trigger instead of a time trigger

frail dagger
#

And tempting state holds. That was a pain to get my head around at first. lol

fringe sail
#

I think that this {{ now() }} is at the present, but don't understand the how and why.

lucid thicket
half fable
#

Hello, I ll need your help regarding a binary sensor template.

Do you know how I can fix this state template code to tell me when a battery is low or not ?

{{ states.sensor | selectattr('attributes.device_class', 'eq', 'battery') | selectattr('state', 'is_number') | selectattr('state', 'le', 15) | list | length > 0 }}

mighty ledge
#

map the state, then map the states value to an int, then select <= 15

half fable
#

@mighty ledge thanks

tulip vine
#

Can you template gods please help me, I am too stupid to write a sensor for current (hourly) weather forecast (temperature in degrees celsius)... I know that this service provides this data, and more... But i cant manage to write a sensor which updates this info on hourly basis.... I would greatly appreaciate your help!

service: weather.get_forecasts
data:
  type: hourly
target:
  entity_id: weather.home
inner mesa
#

It's not a matter of being stupid, just not reading the documentation

tulip vine
#

thank you...! It was in the example box which I needed to clap open, got you

#
sensor:
      - name: Temperature forecast next hour
        unique_id: temperature_forecast_next_hour
        state: "{{ hourly['weather.myhome'].forecast[0].temperature }}"
        unit_of_measurement: °C

UndefinedError: 'hourly' is undefined

although I am sure that my integration/entity weather.myhome provides hourly data... how can I proceed to get the hourly value?

tulip vine
#
service: weather.get_forecasts
data:
  type: hourly
target:
  entity_id: weather.myhome

provides hourly forecasts, so I am not sure why I am failing

#

response_variable: hourly is failing, neither the service call nor the template understands this line...

inner mesa
#

I'm not sure that you're really following the docs there

#

Are you following that example completely? Or are you taking bits and pieces)

#

My guess is that you're trying to put all that in sensors.yaml or something

#

Or you're using some ancient version of HA

tulip vine
inner mesa
#

You put it in configuration.yaml

fringe sail
#

I'm not understanding something. The following does list some of my entities, but one of the entities has 100% battery level. Also, is this searching for "battery_level" as part of the entity id name?```

  • sensors:
    low_batteries:
    friendly_name: Low Batteries
    unique_id: "83ns7b4d82nd"
    value_template: >-
    {{ states.sensor | selectattr("entity_id", "search", ".*_battery_level")
    | selectattr("state", "is_number")
    | selectattr("state", "le", "20")
    | map(attribute="entity_id") | list }}
    icon_template: mdi:battery-low```
mighty ledge
#

you have to use namespace if you want to count numeric states

#

you can't use a one liner

#

states are strings and 100 is less than 20 in regards to string comparisions

#

as for your question about search, no that's not correct. change it just to "_battery_level"

fringe sail
#

When you say count, would that be different than making a list

mighty ledge
#

count, making a list, same difference

fringe sail
#

The reason I asked that was I did put some other code in and it gave a number of the devices and not the device names

#

what would I need to put to get actually the devices less than my threshold

#

Does "_battery_level" include any battery entity, or just the entities with battery_level in the id name?

obtuse zephyr
#

That'd be the latter, it's checking the entity ID only there

scarlet terrace
#

Hey, hope everyone is well.
Im not sure if this is the right place to ask but i would like some help to see if a custom sensor can be made via the template helper for my Innr Zigbee Smart Plug. I want to create a sensor that would show the total consumed energy in kWh for the month like with one of my Tapo Smart Plug has as standard. Could anyone help me with some guidance on how to do this if its possible. Thanks

barren pecan
#

Hey guys, I'm trying to do a sensor that will detect how much time my server went down. I have the integration ping that knows when my server is up and down. So when my server is up again, it will send a notification and I want this notification to show how much time my server was down. So I want to do a template that gets my uh when it went from offline to online this time and get the time that was to online to offline. Get this time and subtract them to get the time that it was offline. But I cannot find a way to do this template. Could you help me please? Thank you!

inner mesa
#

use a state trigger on the binary_sensor entity that indicates the state of the server and use something like {{ trigger.to_state.last_changed - trigger.from_state.last_changed }} to get a timedelta object

#

or, {{ trigger.from_state.last_updated|relative_time }}

barren pecan
#

I think I didn’t understand your idea, but I could not implement it. I didn’t know where I can put my entity. My entity is binary_sensor.ubuntu_server and I think you didn’t understand because I don’t want to compare this current state with its last state and compare this time. I want to compare its last state with its penultimate state and find this time.

inner mesa
#

oh, I forgot they deprecated relative_time in favor of time_since, so {{ trigger.from_state.last_updated|time_since }}

#

a binary_sensor only has two states - on and off

#

when your server becomes unavailable, the binary_sensor turns off. When it becomes available, it turns on

#

when it turns on, the last state was "off"

#

the time between now and when it turned off is the amount of time it was unavailable

#

So when my server is up again, it will send a notification and I want this notification to show how much time my server was down.

#

Am I misunderstanding that statement?

barren pecan
#

Yes, you're correct. I was thinking another thing. I was thinking that I would trigger this automation after, but no, I'm triggering it in the moment that it will turn on. So yes, you're correct. I can compare my real time because it's the time that he turned on. Thank you for your help.

barren pecan
#

Actually, it will not work. I was here implementing the solution, but it will not work because it will run the automation when the states are already changed to on. So it will get the time that the state went from off to on and compare it with the current time, which will be zero. Instead of getting this off time, I need to get the penultimate time.

inner mesa
#

I'm not following

#

That's the point of using trigger.from_state

barren pecan
#

So, when the automation is triggered, the entity is already on. So, it will get the time that it was off. The last time it was off, that was 0 seconds before, because the automation was triggered right when it was on and switched. So, I need to know the time that it will be before that. So, when it's the last time it was on, basically. I don't know if you understand, this is the code that I'm using, the template code.

inner mesa
#

I say again

#

That's the point of using trigger.from_state

barren pecan
#

{% set desligado = states.binary_sensor.ubuntu_server.last_changed %}
{% set ligado = now() %}
{{ (ligado - desligado).total_seconds() | timestamp_custom('%H:%M:%S', false) }}

inner mesa
#

That's nothing like what I gave you

#

If you're not going to use what I suggested, you'll have a bad time

#

And waste mine

barren pecan
#

I didn't understand how I can implement your solution.

inner mesa
#

Clearly

barren pecan
#

Could you help me?

inner mesa
#
trigger:
  platform: state
  entity_id: binary_sensor.ubuntu_server
  to: 'on'
action:
  service: persistent_notification.create
  data:
    message: Server has been down {{ trigger.from_state.last_updated|time_since }}
#

Server has been down 9 seconds

#

fixed a typo and tested

ebon copper
#

would love something like this, but my server -is- my ha server, so ... looping dependency 😛

#

Okay, so while I'm poking bugs and stuff, I've been trying to test out a statistics sensor to address the bathroom temp sensor throwing spikes when the shower is used and triggering automations. Wanted to do a rolling 1 hour average so a five minute spike won't make it freak out (high temp warning on a grow light). But I have these gaps in data from that sensor that I can't explain with any activity from the base thermometer https://imgur.com/a/lKoO6qd

hollow tangle
#

It's been a while I know but did you figure this out?

lucid thicket
ebon copper
#

grumbles

grim lantern
#

Hello everyone, I've been using the ui minimalist theme for a few days now, and I need your help.

Indeed I manage to make work a lot of cards, but when I try to add some cards in custom-cards and I create the .yaml file, the card makes me a custom elemet doesn't exist or I have an error cannot read properties.

I have the impression that I may have an error in my way of accessing button-card-templates via the ui-lovelace.yaml file and I'd like your help. (P.S : not sure to be in the good channel)

mighty ledge
grim lantern
#

thank you !

plain magnetBOT
#

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

obtuse zephyr
#

If you just want to grab the first model from the list {{ state_attr('sensor.solaredge_inverters', 'inverters')[0].model }} should work

quiet bison
#

❤️ TYSM!

obtuse zephyr
#

You're welcome!

next helm
#

Hello,
I have 2 template conditions for my welcome home automation/announcement, they check for a state change within a certain time frame.
One to check if the front door has been opened recently (within 30 mins),
and the other to check how long the system has been up (for after restarting - beyond 30mins).
But I don’t think it’s working correctly as I just rebooted HA and not long after this the welcome home massage played :-s

plain magnetBOT
#

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

radiant grove
marble jackal
#

@next helm in both cases you are checking if the time is less than 30 minutes. Which will be true after a restart for both, as the last_changed value will be reset after a HA restart

opaque trench
quiet bison
#

Man I dorked up my sensors by adding a unique id and now there are two of them:

#

(are pasting images from clipboard disabled in here?)

#

Anyway they both have the same friendly_name now...

sensor.solar_status_panels
solar_status_panels
unavailable    
friendly_name: solar_status_panels
restored: true
supported_features: 0

sensor.solar_status_panels_2
solar_status_panels
on
friendly_name: solar_status_panels```
marsh cairn
#

Delete the old one (might need a restart before you can delete it) and rename the entity ID of the second one later

#

Entities page - select mode (button besides the search bar with the little checkmark) - select the old one - dotsvertical menu - delete selected

quiet bison
#

ty. that was weird but I got that worked out. delete the old, rename the new to the old .etc

#

hopefully next time i'll be smart about this up front

mighty ledge
#

if you add a unique_id to any template sensor, just restart and you won't get yourself in any mess

#

reloading is what gets you in the mess

quiet bison
#

aaaaah

#

that explains it. thanks also.

mighty ledge
#

what do you mean?

lucid thicket
#

I’m interested to know the difference of reloading vs restarting

mighty ledge
#

if you add a unique_id to an existing entity and reload HA see's it as a new entity

#

because the other one is already loaded, you now have a new one that has a unique_id

lucid thicket
#

Ahh. Yes got it.

#

Thanks

wet lodge
#

Since 2022.4, the issues() function exists to output all the repairs. Has anyone used this to count the number of outstanding repairs, or forward the list via a push notification? And, if so, could you share the code to do it?

inner mesa
#

Something seems broken with {{ issues() }} for me. I get a giant error in the log when I try that which starts with 2024-07-30 18:13:06.118 ERROR (MainThread) [homeassistant.components.websocket_api.messages] Unable to serialize to JSON. Bad data found at $.event.result<key and then appears to list all the repairs ever, or so it appears. And I get no output in devtools -> Templates, not even an empty list

#

I currently have no issues, but this isn't the behavior that I was expecting

mighty ledge
#

it's a set

#

so it can't be converted to json

#

use issues() | list

#

or iterate it

inner mesa
#

it's a pretty unfortunate error message when using exactly the examples in the docs

#

it also seems to still list all issues ever, not just issues yet to actetd on

#

here's an example of one:

  [
    "hacs",
    "restart_required_167885769_tags/v0.7.4b19"
  ],
#

🤷

mighty ledge
#

well it returns exactly what it says in the docs, just because you can't output it to the template editor doesn't mean it's not working

#

iterate the dictionary as items and output each value

#
{% for issue, value in issues().items() %}
  {{ issue }}: {{ value }}
{% endfor %}
inner mesa
#

sure, and I'm saying that when I turn it into a list, it's not telling me that I have no open issues. It's just listing every issue I might have had ever

mighty ledge
#

yep, but you ahve to use the keys inside the dict to determine if it's active

wet lodge
inner mesa
#

the docs show this as an example:

{{ issue('homeassistant', 'python_version') }}  # {"breaks_in_ha_version": "2024.4", "domain": "homeassistant", "issue_id": "python_version", "is_persistent": False, ...}
#

as though it should list some of them with is_persistent: False, yet none of mine have that key at all

mighty ledge
#

they all have that key

wet lodge
mighty ledge
#

what goes between the ( ) for issues is the key, which is a tuple

inner mesa
#

fair enough, just doing {{ issues()|list }} isn't a good idea

mighty ledge
#

yes, cause it's a dict using a set as the key

#

just as the docs say

inner mesa
#

it just gives me a list of lists for the first tuple of each item

mighty ledge
#

it's a key value pair

#

the key is a tuple of strings

#

this is common in coding, but not common so far in HA templates

#

use .items()

wet lodge
#

I can parse the list pretty well by reading it, but I’m no jinja expert, so I have no idea what code is required to extract the details I’m looking for. That’s why I’m asking for help.

Appreciate the responses so far.

mighty ledge
#

Are you looking for ones that are persistent?

#

and what value do you want out?

#

because this is all useless under the hood info IMO

wet lodge
#

To start, I’d settle for a count of persistent ones…. Then I could build a template sensor to surface that.

Longer term, I was hoping to forward the relevant details in a push notification when a new one is created. Though, looking more closely, I see what you mean…. The details you see in the HA UI don’t seem to be returned by this function.

Well, just the count for now, I suppose.

mighty ledge
#

if you want active repairs, you can use spook

#

and then build automations from there

#

spook is custom

wet lodge
#

I had that before, but it was a lot more than I was looking for…. Maybe I’ll take another look at it.

mighty ledge
#

anyways, for count

#
{{ issues().items() | list | selectattr('1.is_persistent', 'eq', True) | list | count }}
wet lodge
#

Thanks!

sinful bison
#

Hello :)

Did i miss something obvious ? a basic template condition never get passed, but when i use the same trigger data the the template page, it does return true

condition:
  - condition: template
    value_template: >-
      "{{ trigger.from_state.state in ['standby', 'empty', 'cold_no_control',
      'warm_no_control'] }}"
#
trigger:
  from_state:
    state: empty
fickle sand
sinful bison
#

that not my writing, but yes.
I just put the template in the gui and it alwayse does funny stuff

#

but it "should work" anyway ...

#

no ?

marble jackal
#

You need to remove the double quotes around the template if you use the multi line notation

marble jackal
sinful bison
#

Oo
I've removed it, i guess it's been a while since i've done jinja in HA, because "putting jinja in quote" is hard engrave in my mind.

It will have to wait for the next coffee cup to check if it change something

#

thank's :)

plain magnetBOT
#

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

fiery hamlet
#

I am running 2024.7.3, let me know if updating first would be suggested

lofty mason
#

that will tell you if that item is in the list

fiery hamlet
#

heey, that triggers!

#

Thanks @lofty mason !

hallow plover
#

Is it possible to make a template binary sensor that only changes state if the underlying template is true for a specified length of time?

hallow plover
#

is that something that is available in the template binary sensor UI?

lofty mason
#

no unfortunately not

#

that's a yaml option

hallow plover
#

And there is no way to have just the delay on and delay off part in the yaml (and the template is defined in the UI)

wet imp
#

Just realised your doing this from a json call, this will be coming in the 2024.8 release, I scrolled too far back in my search results.

I added an example template sensor to the documentation to get all the dinner items for today to give you a start.
https://rc.home-assistant.io/integrations/mealie/#examples

Home Assistant

Instructions on how to setup Mealie devices in Home Assistant.

obtuse lava
dark merlin
#

I have a question, I'm looking for a design for my system that is modern but also clean. Does anyone have an idea?

abstract maple
#

I think the entity id bit won't work if I place the statement into a variable instead of inside the service call directly.

#

The idea is to construct a nice timestamped file name and use that to store a snapshot and point a local_file camera to it

inner mesa
#

you're nesting templates

#

that seems common for some reason

#

I also don't know what entity_id.entity_id is supposed to be

#

is that supposed to be passed in somehow?

abstract maple
#

I think that's the problem. imagine for a moment the variables section wasn't there and the temlate was where the variable is referenced now. In that case, it would see the entity_id property of the service call, but in the variables I don't have that. So I'd have to define it ahead of time somehow.

#

But I don't know how.

inner mesa
#

there's no way to reference the entity_id in a service call as a varaible in a tempalte

#

there's only one entity_id, so don't make it more complicated than it needs to be

abstract maple
#

That's a good point, I can simply take that out.

inner mesa
#

and don't nest templates

#

{{ {{ }} }} is not a thing

abstract maple
#

I'll be sure to keep that in mind.

#

Thanks for your help

unreal dawn
#

Hi. I keep getting this error in my logs WARNING (MainThread) [homeassistant.helpers.template] Template variable warning: 'dict object' has no attribute 'action' when rendering '{{ value_json.action }}'. This seems to be related to my Aqara vibration sensor setup in Zigbee2MQTT. Is there anyway I can change my value_template to avoid this error?

    state_topic: "zigbee2mqtt/vibration/postbox"
    availability_topic: "zigbee2mqtt/vibration/postbox/availability"
    value_template: "{{ value_json.action }}"```
abstract maple
#

@inner mesa apropos of what we talked about yesterday regarding nested templates, I just wanted to say that in the right context, that nested statement did perform exactly as designed. So could one say "while nested templates aren't guaranteed to work, they aren't guaranteed to not work either"?

#

The classic "undocumented feature" so to speak?

marble jackal
unreal dawn
#

Thanks. I've just searched discord and found something that works. For the benefit of others who have the same issue this is how it is now

      {% if "action" in value_json %}
        {{ value_json.action }}
      {% else %}
        0
      {% endif %}```
mighty ledge
#

Or just

{{ value_json.action | default(0) }}
unreal dawn
abstract maple
#

I'm not the original author, so please don't ask me why it was done the way it was done.

mighty ledge
#

wtf is that template attempting to do

#

why is it outputting a template in the template?

abstract maple
frail dagger
#

Not sure why you'd need a nested template for that though.

abstract maple
#

Well if you don't know, don't ask me. I'm just acting like the average software developer copy-pasting the code of people with (presumably) more knowledge than me.

frail dagger
#

🤣

abstract maple
#

By the way, in the context of the automation posted, it works flawlessly for the time being.

mighty ledge
#

I am so confused how that works

abstract maple
#

Let me think... The value of a string part inside a template is that string, right?

#

{{ 'this is a string' }} would become this is a string

mighty ledge
#

the template will output this:

//config/videos/pics/{{ entity_id.entity_id|replace('camera.','')}}_20240802_090000.jpg
abstract maple
#

so if we apply some computational theory and assume an end-recursive evaluation loop, you could nest as many templates into each other as memory permits, so long as they all eventually evaluate to a string, the end result would be a string I think.

mighty ledge
#

so it makes no sense how the template is evaluated a second time and where entity_id object comes from

#

templates are only resolved once

abstract maple
#

Oh that's easy, it seems to take the value of the entity_id stanza in the same statement.

mighty ledge
#

no, what you're saying does not make sense

#

there's a second resolution that's occuring

#

and it's not clear where, nore is it clear where the namespace has the entity_id object added to it

abstract maple
#

As Benjamin Franklin put it: If your theory does not match ovservable reality, it's your theory that's at fault.

mighty ledge
#

my man, I write code for templates

#

there's 2 resolutions occuring

#

if that works

#

and the base template engine only does 1

abstract maple
#

And I'm in computer sciences for 25 years now, so respect from one professional to another.

#

Well. technically now().strftime('%Y%m%d_%H%M%S') already is a term requiring to be evaluated before the template itself gets evaluated, so SOME sort or recursive evaluation MUST be taking place here.

#

"now it is {{ now().strftime('%H%M%S") }} o clock" is a valid, evaluable template string am I correct?

#

And so is {{ 'this is a string' }} right?

mighty ledge
#

with entity_id linking to the camera object in the namespace

abstract maple
#

I'd have to dig out the old Abelson-Sussman to get the terminology correct, but then so must be {{ "now it is {{ now().strftime('%H%M%S") }} o clock" }} because it would be recursively evaluated

mighty ledge
#

no, it doesn't recursively evaluate

#

it resolves exactly 2 times

#

once when the service is called prior to sending the data to the service call, and a second time inside the service itself

#

This is most likely the ONLY service in all of HA that behaves this way

#

Anyways, knowing how this works now, what's your question?

abstract maple
#
template ->
  string containing template ->
    string -|
    template ->
      function ->
        string -|
      <-string
    <- string
  <- string
|- string
#

At this point, it's mostly an academic discussion. RobC pointed out that this would only be relevant if I was iterating over multiple entities, but since I'm always using the same, the whole point of resolving the entity is moot.

#

And I've certainly understood that nested templates evaluating correctly isn't guaranteed and I should avoid it unless absolutely necessary.

mighty ledge
#

there's no need to even use the double resolution

abstract maple
#

I believe ya. I've simplified that yaml significantly since then. And actually, since the blink integration I was planning on using is about as reliable as a chocolate teapot, I'll chuck the whole thing kit and kaboodle anyways.

frail dagger
#

Yeah, that's a simple template and you can just use the camera entity instead of doing the replace. What's posted there is just... no.

mighty ledge
#

I still don't know what your issue is, there's nothing wrong with the template

abstract maple
#

imagine for a moment you had the yaml I originally posted and wanted to move that template into a variable so you could re-use it in the way I did here.

mighty ledge
#

you don't need to do that

abstract maple
#

It wouldn't work because it wouldn't have any entity_id to parse, right?

#

How to make THAT work, that was my original question I came here with.

#

But as I said, RobC convinced me that it was a moot point.

mighty ledge
#
alias: Rekognition Kuechenterrasse
sequence:
  - variable:
      my_camera: camera.kuchenterrasse
      my_name: "{{ my_camera.split('.')[-1] }}"
  - service: blink.trigger_camera
    data: {}
    target:
      entity_id: "{{ my_camera }}"
  - delay:
      hours: 0
      minutes: 0
      seconds: 25
      milliseconds: 0
  - variables:
      timestamp: "{{now().strftime('%Y%m%d_%H%M%S')}}"
  - service: camera.snapshot
    data:
      filename: /config/videos/pics/{{ my_name }}_{{ timestamp }}.jpg
    target:
      entity_id: "{{ my_camera }}"
  - service: local_file.update_file_path
    data:
      entity_id: "{{ my_camera }}_file"
      file_path: /config/videos/pics/{{ my_name }}_{{ timestamp }}.jpg
  - service: image_processing.scan
    target:
      entity_id: image_processing.rekognition_kuechenterrasse_file
    data: {}
description: ""
icon: mdi:camera-wireless
#

if you want to provide the camera as a variable to the script...

abstract maple
#

Never doubted you for a moment😉

mighty ledge
#
alias: Rekognition
sequence:
  - variables:
      my_name: "{{ my_camera.split('.')[-1] }}"
  - service: blink.trigger_camera
    data: {}
    target:
      entity_id: "{{ my_camera }}"
  - delay:
      hours: 0
      minutes: 0
      seconds: 25
      milliseconds: 0
  - variables:
      timestamp: "{{now().strftime('%Y%m%d_%H%M%S')}}"
  - service: camera.snapshot
    data:
      filename: /config/videos/pics/{{ my_name }}_{{ timestamp }}.jpg
    target:
      entity_id: "{{ my_camera }}"
  - service: local_file.update_file_path
    data:
      entity_id: "{{ my_camera }}_file"
      file_path: /config/videos/pics/{{ my_name }}_{{ timestamp }}.jpg
  - service: image_processing.scan
    target:
      entity_id: image_processing.rekognition_{{ my_name }}_file
    data: {}
description: ""
icon: mdi:camera-wireless
abstract maple
#

Thanks, I'll put that in my library folder for future reference.

#

But odds are if I get proper cameras instead of those useless pieces of junk, I won't have to jump through hoops to obtain a simple snapshot anyways...

#

That's the whole point of that script. To beg a simple snapshot off the blink camera so I have something to feed the image recongniton. It's absolutely ridiculous.

#

But I'm a bone-headed ass who won't give up until somebody hits him in the face with a clue-bat.

mighty ledge
#

all of this "jumping through hoops" is normal for all cameras in HA

#

it's not unique to blink

abstract maple
#

Thanks for the warning.

mighty ledge
#

the camera snapshot service is provided by the base camera class

abstract maple
#

But I assume in most other cases, it actually works reliably if you jump the hoops in the proper way?

mighty ledge
#

Not sure what you mean?

frail dagger
#

I think that only applies to battery cameras though. With my POE cameras, I can call the snapshot service directly with no other service calls needed.

abstract maple
#

You see, last night that very script worked reliably seventeen times in a row when I tested it. Since then, no matter what I do, it will always return a snapshot from some time last night.

mighty ledge
#

is the file updating? If the file is updating but the snapshot is old, then it's the camera

#

if the file is remaining the same name/time, it's your automation

abstract maple
#

I've got teethered blink cameras as well, and they don't perform an iota better. The issue is that blink cameras aren't really cameras but cloud devices intended to be used with the blink app and no other way.

#

It's creating fresh files, but the content is identical

mighty ledge
#

that would be the camera then

abstract maple
#

I assume so.

mighty ledge
#

or the integration in HA

#

but not the automation

abstract maple
#

I'm surprised it worked at all, because usually the blink cameras are very prone to shooting back a "busy, come back later" if you try to do anything with them in quicksequence.

#

That's true even when used the official way.

#

Very annoying if you get a motion alert and want to jump in to live view to see what's going on, and your camera tells you "go away I'm busy recording a clip"

#

It's just shit engineering is what it is.

plain magnetBOT
#

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

ocean tusk
lucid thicket
#

you might have to ask in #blueprints-archived . From a non-blueprint perspective the only way I know how to trigger on a time offset is to use a template trigger: {{ my_datetime_object + timedelta(seconds=600) < now() }}

ocean tusk
lucid thicket
#

Well if all you needed was a template that gives you a time offset, then what I wrote should be what you need.

haughty breach
ocean tusk
#

If there is no other way i will go wit that with many duration helpers

#

But i have it in automations dont know why i cannot transfer it to a blueprint

haughty breach
ocean tusk
bronze prawn
#

I'm working on a voice command that will get the condition/temperature of a forecast service call at a specific time (eg What will the weather be like at 5:00 PM?) . I already have this from a different automation that converts the time to date time :

{{strptime(today_at().date() ~ ' ' ~ trigger.slots.time, '%Y-%m-%d %I:%M %p')}}

which produces something like this:

2024-08-02 17:00:00

Do I need the value in the response variable to match exactly? How do I go about finding the matching date time in the data?

#

Here's what the response looks like (edited)

weather.kagc:
  forecast:
    - detailed_description: ""
      datetime: "2024-08-02T14:00:00-04:00"
      condition: partlycloudy
      temperature: 80
    - detailed_description: ""
      datetime: "2024-08-02T15:00:00-04:00"
      condition: lightning-rainy
      temperature: 82
#

I know that this will give me the value for the first element, but how do I iterate and check through the list and does the format I have above need to be modifed to match?

forecast['weather.kagc'].forecast[0].datetime
haughty breach
#
{% set x = (strptime(today_at().date() ~ ' ' ~ trigger.slots.time, '%Y-%m-%d %I:%M %p')|as_local).isoformat() %}
{% set selected = forecast['weather.kagc'].forecast | selectattr('datetime', 'eq', x) | first %}
.....

What are you trying to do with the values from the list item?

ocean tusk
#

Oh it worked

#

But i did 10 second to try and it took 1 min

#

So its not checking seconds but is perfect for what i need thanks

haughty breach
#

The use of now() causes it to throttle to only render the template once a minute... which is why I have so many caveats in the description in my blueprint.

ocean tusk
#

Ohh sorry

#

Lol

#

Thanks for the help

bronze prawn
#

From what I see, I should just be able to pull those values from selected assuming that will provide the dictionary values. I will give this a test soon. Thank you for sharing that code!

haughty breach
#
{% set x = (strptime(today_at().date() ~ ' ' ~ trigger.slots.time, '%Y-%m-%d %I:%M %p')|as_local).isoformat() %}
{% set selected = forecast['weather.kagc'].forecast | selectattr('datetime', 'eq', x) | first %}
It will be {{selected['temperature']}} and {{selected['condition']}} 
bronze prawn
#

Thank you!

robust star
#

So this is my first template/binary_sensor, it doesnt appear to be showing up anywhere - not in dev tools or entities, what am i missing? i reloaded my conf and restarted several times already, the template is working in the template dev tool.

I put this in my configuration.yaml:

template:
  - binary_sensor:
    - name: Washing Machine Status
      unique_id: washing_machine_status
      state: >
        {{states('sensor.washing_machine_outlet_power')|float > 1.0 }}
unique turret
#

I'm looking to show icon based on which input_boolean is currently only turned on. Also, I want to pull the icon from the entity, rather than having to manually defining the mdi icon.

How do I go abouts doing this? thanks

{% else %}
{% if is_state("input_boolean.away_mode", "on") %} mdi:away
{% endif %}
frail dagger
quaint matrix
quaint matrix
# unique turret I'm looking to show icon based on which `input_boolean` is currently only turned...

There are a couple of ways of doing this - if you are literally just looking to display an icon then you could just do it with conditional lovelace cards...
That said, is there a reason why you have home and away as 2 different booleans? is there ever a time when you want it to be both home and away or both not home and not away? If not it would make sense to redefine away as input_boolean.home_mode = false

frail dagger
marble jackal
unique turret
frail dagger
#
{% if is_state('input_boolean.home_mode', 'on') %}
{{ state_attr('input_boolean.home_mode', 'icon') }}
{% elif is_state('input_boolean.away_mode', 'on') %}
{{ state_attr('input_boolean.away_mode', 'icon') }}
{% elif is_state('input_boolean.another_one', 'on') %}
{{ state_attr('input_boolean.another_one', 'icon') }}
{% endif %}
unique turret
#

Thanks, but that still doesn't pull the icon from the entity, isn't there a way to do so?

#

So basically, use the icon of the input_boolean

frail dagger
#

Fixed

#

(fixed again)

unique turret
#

Brilliant, thank you as always 😀

frail dagger
marble jackal
#

Alternative

{% set booleans = [
  'input_boolean.home_mode',
  'input_boolean.away_mode',
  'input_boolean.another_one'
] %}
{{ booleans | select('is_state', 'on') | map('state_attr', 'icon') | first | default('mdi:whatever', true) }}
marble jackal
frail dagger
unique turret
#

Thank you both

bronze prawn
lofty mason
#

Well it says you're trying to get first on an empty list

#

so just look at your list and work backwards

bronze prawn
#

Right. I'm looking at traces and don't see any changed variables. I guess I could just do some returns on the variables as conversation responses.

lofty mason
#

or try in developer tools

#

if you can extract the relevant parts

bronze prawn
#

Oh sure. I just need to get the response variable in and I can do that. thanks

#

pffft. Easy fix. I hadn't changed to the hourly forecast so the data was not correct to parse. Sorry for the bother. Still early here 🙂

spice current
#

How do i make a custom notify action that executes a existing notify action + some other service (mainly a rest_command)

obtuse zephyr
#

Delete is usually in the entity properties, not group options

#

One option for your other question is to use a notify group containing your existing notify service along w/ a restful notification

spice current
near oak
#

Hello all, I am trying to create a sensor with the following code
- name: Co Charger Power state: > {% if (states('sensor.solax_local_load_power')|float > 7200) and (is_state('binary_sensor.bluey_charger_plug', 'off')) %} 7200 {% else %} 0 {% endif %} unit_of_measurement: W
whoever im getting the followig error:

#

Invalid config for 'template' at templates.yaml, line 553: 'name' is an invalid option for 'template', check: name Invalid config for 'template' at templates.yaml, line 554: 'state' is an invalid option for 'template', check: state Invalid config for 'template' at templates.yaml, line 561: 'unit_of_measurement' is an invalid option for 'template', check: unit_of_measurement Invalid config for 'template' at templates.yaml, line 562: 'device_class' is an invalid option for 'template', check: device_class
Invalid config for 'template' at templates.yaml, line 552: 'name' is an invalid option for 'template', check: name Invalid config for 'template' at templates.yaml, line 553: 'state' is an invalid option for 'template', check: state Invalid config for 'template' at templates.yaml, line 560: 'unit_of_measurement' is an invalid option for 'template', check: unit_of_measurement

#

not sure what to do here

lucid thicket
#

Where (what file) did you put that code, and what heading is above (indented less than) that code

near oak
#

template.yaml

#

and the config is referring to the file (have other sensors there and working)

#
  • sensor:
#

right at the top

#

the - name is the 1st indentation after - sensor:

lucid thicket
#

The top heading needs to be template:
You probably have a bunch of sensors in that file, and this is your first entity on the template platform. All your other sensors probably need to get moved to sensor.yaml

near oak
#

all the other ones are working (have been working)

#

wait let me show you the config reference

#

template: !include templates.yaml

lucid thicket
#

They are either other types of sensors, or they are the old format template sensors

near oak
#

the file has a template: at the top, right at the config

inner mesa
#

template: doesn't belong in that file

near oak
#

Shouldn't the config.yaml have a
template: !include templates.yaml

?

#

My knowledge is very very basic

inner mesa
near oak
#

No no, at the top of templates.yaml there's

  • sensor:
inner mesa
#

Your posts are hard to read without formatting...

plain magnetBOT
#

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

near oak
#

Sorry 😐

lucid thicket
#

To recap, in configuration.yaml you should have:
template: !include templates.yaml

In your templates.yaml file it should start with

- sensor:

Then your code should be

    - name: blah
      state: >
        {{ blah }}
near oak
lucid thicket
#

The error message is telling you those configurations are being applied to template: and not to sensor:

#

Check your indenting

near oak
#

ok

#

ohh i think that did it 😆

#

Thank you very much!

lucid thicket
#

No problem

rocky crypt
#

Hello. I'm trying to get the minimum a sensor has read in the last 10 minutes... I thought this was working before, but it no longer is. Am I doing this correctly?

- platform: statistics
  name: "Humidity last 10 minutes"
  entity_id: sensor.h5101_6f54_humidity
  state_characteristic: value_min
  max_age:
    minutes: 10
#

When I look at the history of the humidity sensor, the lowest it has been in the last 24 hours is 43.8! However, my sensor has a reading of 36.4 and says it hasn't been updated in 16 hours??!!

#

Ok, well, I restarted HA and it updated.. So, I'm not sure what happened. But maybe it'll work now...

plain magnetBOT
#

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

undone spruce
#

I have a bit of a complicated setup I'm trying to fix and actually make work properly. I have a Utility Meter helper that collects energy_spent which is fined as a template. This is then used in another template as energy_spent_daily. The final templates are here:

https://gist.github.com/spiceywasabi/743253436f7ef97c7499e230ce19f64d

Now these do all generate data however when I try to use Calculated Home Daily Combined Consumption or Energy Spent Daily in the Energy tab it says that its the wrong units/type. How do I fix this and are there things I can do to simplify this template configuration?

(Could a mod remove the converted post by the bot since its really unreadable Thanks.).

half fable
#

Hello, anyone know if my weather service is normal ?
https://pasteboard.co/d4Ee5hZChnKZ.png
I don't understand why the first and second forecast are the same day, and why some value are null for the first forecast.
This break my template and card

#

Maybe it's normal but I don't understand why

lucid thicket
#

If you have a sensor that measures consumption, it should probably be state_class: energy and unit_of_measurement: kWh

#

You also have a lot of indentation problems in that code. Hopefully that was a copy/paste issue.

faint robin
#

Hello! I'm new to templates -- trying to essentially add two voltage numbers together, and then take total W consumed at the house, divide by voltage, and come up with a rough guess for amperage - trying to make sure I can start to set some alerts and automations if we approach maximum consumption for the panel.

I'm trying the following template code, but the preview keeps coming up with Unavailable.

{% set voltage = ((value('sensor.phase_a_voltage') | float) + (value('sensor.phase_b_voltage') | float)) %}

{{ ((value('sensor.total_power') | float) / voltage) }}

I'm brand new ... so not entirely sure what it is I'm doing here. Any help would be super appreciated!

lucid thicket
faint robin
faint robin
lucid thicket
#

Sounds good. Also make use of the template tool in Developer tools-> template. And start with small bits of code and add to it as you validate each piece

#

Not related to templates, but from an electrical standpoint I don’t see how adding voltages from two phases makes any sense

faint robin
#

Phase A is at 110, Phase B is at 115.. trying to understand total voltage across both phases divide by consumption. Total panel is (sadly) 100A, so trying to make sure we don't flirt with that.

#

The Emporia Vue (esphome) doesn't provide a total amperage value.

lucid thicket
#

Are you using the Vue utility connect (reads meter info over Zigbee) or the Vue that has current clamps?

#

Regardless, if the only info you have is voltage from each phase, and total power, then you’d have to assume equal power from each phase and you’d take the average of the two phase voltages

#

Or take power/2 and calculate amperage on each phase separately and then add the two together. Mathematically it’s the same result but it might be easier to follow logically.

undone spruce
faint robin
faint robin
bold cape
half fable
#

Hello, one of my integration has 1 entity but a lot of sensor.
Any idea how I can merge everything and have one sensor + multiple attribute ?

marsh cairn
#

Those are all entities

half fable
#

oh you are right entities

#

in the integraton entries I see 1 device + 16 entities

marsh cairn
#

As expected

half fable
#

but on card they always expect one entities so I m a bit lost

marsh cairn
#

What are you actually trying to do?

half fable
#

I m trying to display a card if the machine is on and display the remaining duration

marsh cairn
#

You can either use two cards or create an additional template sensor

half fable
#

I guess I need a template sensor because I have all the value I need but none in the format I need

plain magnetBOT
half fable
#

ok something like this:

https://pastebin.com/4UXhWtgi

Any idea how to hardcode program time ? Should I use helper to do that or can I do it directly in the template

half fable
#

Do anyone know how I can get the value in the energy dashboard for the self consumed solar energy ?

lucid thicket
# undone spruce I thought the usage of the energy meter would convert active (kW/W) to kWh? That...

agree with snighere that Riemann sum is the right way to do this. If you want to keep down the path of using the history_stats sensor to calculate HVAC duration in hours, and then multiply it by an assumed power of 4.232kW, then your template sensor is doing the calculation and your units of measurement in that sensor should be kWh and not kW that you currently have specified. Whatever you specify is what HA is going to use, it isn't smart enough to do unit conversion and override what you incorrectly specified.
In your "home daily combined consumption" sensor you should be adding two sensors that are each already in units of kWh and therefore the units of this sensor should also be kWh and the device_class should be energy instead of power.
You mention a utility helper, but I don't see anywhere in your code that you define a utility meter entity.
Another comment about your code is you only need the first entry of - sensor: underneath the template: heading. I don't think repeating it hurts, but it's not necessary.

lucid thicket
# half fable ok something like this: https://pastebin.com/4UXhWtgi Any idea how to hardcode...

For program time, you are better off calculating the ending datetime instead of updating this sensor attribute every minute for no purpose other than to subtract off a minute.
Unrelated, but you can make this a binary_sensor instead of a sensor, and your state simply becomes {{ not is_state('sensor.lave_vaisselle_operation_state', 'Ready') }}. That will also give you an icon that updates with a check mark when on and and empty circle when off (see binary_sensor device classes here if you want to specify something other than the default, which is shown in the chart as 'None')

lucid thicket
half fable
lucid thicket
half fable
#

I m thinking, the ending datetime should be calculated too, because I don't have this value anywhere.

somber basin
#

Sorry if this seems stupid, trying to use a bubble card to send a wake on lan packet to wake a windows machine and using hass agent to shut it off. I can't get my config file quite right.

#
type: custom:bubble-card
card_type: button
button_type: switch
switches:
  name: Yggdrasil
  turn_on:
    - service: wake_on_lan.send_magic_packet
      data:
        mac: xx:xx:xx:xx:xx:xx
  turn_off:
    service: button.press
    target:
      entity: button.yggdrasil_yggdrasil_shutdown```
plain magnetBOT
#

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

mighty ledge
#

looks like you're mixing card config and a template switch

#

Oh man, you're mixing a card config, legacy template yaml and modern template yaml

somber basin
#

nice, was trying to get them all in one. I'm not too familiar with config files.

mighty ledge
#

You can't do that, you have to make a separate config for each.

#

each being, your card and your template entity

somber basin
#

Ok thank you. I knew I'd messed up in the yaml file, just couldn't find any examples on how other people have done it, which I usually do

near mountain
#

How do I find out the aliases to an area given an area_id?

mighty ledge
#

area_name

near mountain
mighty ledge
#

What do you mean “alias”

near mountain
#

"Aliases are alternative names used in voice assistants to refer to this area."

marble jackal
#

You can by looking at the area details in the GUI, but not using a template

near mountain
marble jackal
#

By using Python functions built in HA. A template function could probably be built for it, but so far nobody did

#

Why would you need to have them listed?

near mountain
#

To pass them into extended openai conversation because gpt4o-mini is too dumb to infer the area names lol. I am sticking to 3.5-turbo because of this, but otherwise 4o-mini seems to be better at following instructions and also faster

plain magnetBOT
#

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

somber basin
#

how do you get multiple switches working in configuration.yaml?

#

As I have some running with template platform and some with wol but can't seem to get them both working. Also the power state on hass.agent doesn't seem to update correctly for me

half fable
#

Any idea why my Weather: Get forecasts srvice return null for the temperature during the night ?

#

how can I fix that :/

#

If I check hourly I have the temperature

#

I got the same issue yesterday and the template was fine during the day

marble jackal
somber basin
#

when I did that I couldn't have multiple platforms.

marble jackal
#

Not sure what you mean with that

somber basin
#

well I had

- platform: template
  switch1:
- platform: wake_on_lan
  switch2:```
#

minus the awful indexing

plain magnetBOT
#

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

marble jackal
#

Well, that should work fine

somber basin
#

ill give it a go again then

marble jackal
half fable
#

temperature and wind bearing time are null every night but are ok the morning

rough walrus
#

Hey guys,
I'm trying to send myself a notification about the amount of rain of the current day, everyday at 11:59pm. I'm stuck with how to extract the amount of rain from the sensor and put that into a variable. I have this code:

service: notify.mobile_app_pixel_7a
data:
  message: >-
    {% set SENSOR =
    'sensor.gw2000a_daily_rain_rate_piezo' -%} 
        {{ 'Warnung: test'+SENSOR.state|string }}

but this will only show "warning: test" and nothing more. I'm really lost, looking for the answer to this simple question 😦

frail dagger
rough walrus
#

ah, ok

frail dagger
#

There, that's a bit better.

half fable
#

If I add it:

- service: weather.get_forecasts
  target:
    entity_id: weather.home
  data:
    type: hourly
  response_variable: hourly
#

Do you think I can fix by doing something like that (this code doesn't work)

temperature: >
{% set temp = daily['weather.home'].forecast[0].temperature if daily['weather.home'] is not none else hourly['weather.home'].forecast[0].temperature %}
{{ temp }}

somber basin
#
    switches:
      yggdrasil:
        friendly_name: "Yggdrasil"
        value_template: "{{ is_state('sensor.yggdrasil_monitorpowerstate', 'PowerOn') }}"
        turn_on:
          service: wake_on_lan.send_magic_packet
          data:
            mac: ""
        turn_off:
          service: button.press
          target:
            entity_id: button.yggdrasil_yggdrasil_shutdown```
My power state doesn't update from hass.agent still. Everything else works
lofty mason
plain magnetBOT
#

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

half fable
#

I know but daily is not working the last hours of the day

lofty mason
#

oh sry didn't read the template to the end

half fable
#

I m thinking mixing both, anyway I want to use the hourly service for a detailled view

#

But I don't know how to achieve that

somber basin
marble jackal
half fable
#

Royal Meteorological Institute of Belgium

marble jackal
#

oh, I just removed that one today

half fable
rough walrus
half fable
frail dagger
#

You'd have to do this:

- variables:
    RAINTITLE: "Regenmelder"
- service: notify.mobile_app_pixel_7a
  data:
    title: test
    message: "{{ RAINMESSAGE }}"
marble jackal
#

Ah, I see, it is actually null

      temperature: null
      templow: 16
      wind_gust_speed: 10
      wind_speed: 7
half fable
#

yes for 2 values

marble jackal
#

but it exists, so basically you can just do:
{{ daily['weather.home'].forecast[0].temperature or hourly['weather.home'].forecast[0].temperature }}

half fable
#

I ll try, didn't know how to write that 😉

marble jackal
#

That will use daily unless the result is faslely, in that case it will use the hourly one

half fable
#

doesn't work probably because of the float for this attribute:

{% set T = (daily['weather.home'].forecast[0].temperature or hourly['weather.home'].forecast[0].temperature | float) %}

#

is there another way to write that ?

frail dagger
#
{% set T = (daily['weather.home'].forecast[0].temperature or hourly['weather.home'].forecast[0].temperature) | float(0.00) %}
half fable
#

doesn't work :/ sadly I can't use the template tester with action in the template

marble jackal
#

it will already be a float

frail dagger
#

Huh, I thought it would come through as a string like states(). Anyhow...

{% set T = daily['weather.home'].forecast[0].temperature or hourly['weather.home'].forecast[0].temperature %}
marble jackal
#

no, only entity states are string by definition. Attributes or service response variables can be any type

frail dagger
#

Got it. So all my casts can be dropped 😉 lol

marble jackal
#

well, it depends a bit on the integration, it could be that it's still a string. But in this case you can see that it's a float in the service response

#

well, actually an integer 🙂

#

it's not the best weather integration I know of, not very precise with all values being integers, and that precipitation_probability being null instead of 0 is also a bit annoying

frail dagger
#

Ah, gotcha... ok, so it's not a broad "this is how it is" then, but by integration/service response?

half fable
#

oh it work

#

I tought reloadeding the yaml was enough xD

#

I had to restart HA completly

marble jackal
half fable
#

so the float cast is needed ? I had it removed but I don't think it was the issue

marble jackal
#

it's not needed

#

and trigger based template sensors only update when triggered

#

so YAML reload won't work

half fable
#

Once again you saved me and I ll be able to sleep not too late 😉

marble jackal
#

a restart worked in this case because that is one of your triggers

#

you could also add an event trigger using a custom event, so you can trigger it by sending that event

half fable
half fable
sharp night
#

I'm trying to play around with the inbuilt noaa_tides integration, and I wanted to build some template sensors off of it... In the jinja2 developer panel, I tried this simple template to display the sensor state:
tide info: {{ states('sensor.tides') }}

And what comes out is: tide info: unknown.

In my states panel, I do see a state that looks like Low tide at 9:16 PM. I'm kind of feeling stupid here; other sensors are returning states, but this one is not.

lofty mason
sharp night
marble jackal
#

can you also show a screenshot from the template editor, showing the template and the result?

sharp night
sharp night
#

@lofty mason @marble jackal it's werid right?

lofty mason
#

I can't explain that

#

works for me 🤷

sharp night
#

Hah. Ok. Weird… maybe I should restart, when in doubt…

sharp night
#

a restart fixed it... ooooooooooK lol

bronze prawn
#
{% set input_cameras = "{'front':'camera.front_camera','doorbell':'camera.mydoorbellcamera'}" %}
{% set cameras = (input_cameras | from_json) %}

This gives me this error:

JSONDecodeError: unexpected character: line 1 column 2 (char 1)

Where am I going wrong? I am wanting the user to be able to enter the dictionary in a blueprint and then I am wanting to take it from a string and make it into something that can be used in the automation.

inner mesa
#

I suspect that you need to flip your quotes. Proper JSON uses " for its strings

bronze prawn
#

dang it. I think I've been through this before. let me check

inner mesa
#
{% set input_cameras = '{"front":"camera.front_camera","doorbell":"camera.mydoorbellcamera"}' %}
{% set cameras = (input_cameras | from_json) %}
{{ cameras }}
``` -> 

{
"front": "camera.front_camera",
"doorbell": "camera.mydoorbellcamera"
}

bronze prawn
#

Yeah that was it

#

thanks for the reminder. much appreciated

bitter atlas
#

Anyone have an example of a template sensor that uses power metering to determine if the object pulling the power is using more or less than normal watts/amps? Looking for a means to trigger an automation based on if the average overall normal current being drawn ever jumps or just climbs in general

hushed bison
#

I'm trying to capture a value of an entity only once at startup, so I created a trigger on homeassistant start. However, the entity return "unavailable" and I think that is because the device which this entity is being read is not available yet. Is there a trigger I can use when homeassistant starts and when the entity becomes available for the first time?

marble jackal
#

trigger on the home assistant start event, and then add a wait template as first step of the automation

wait_template: "{{ not is_state('your.entity', 'unavailable') }}"
hushed bison
#

I'm finding a lot of examples for creating automations, but not so many about template-trigger-sensor. Is using automations the common way to update entity values?

hushed bison
#

It's probably me that haven't connected all the dots yet

gilded raven
#

I have a group numeric sensor helper. how can i reference it's value in a template?

frail dagger
gilded raven
frail dagger
digital verge
#

Hey. trying to fix a broken template sensor.

#
wind_direction:
        value_template: >
          {% set direction = ['N','NNE','NE','ENE','E','ESE','SE','SSE','S','SSW','SW','WSW','W','WNW','NW','NNW','N'] %}
          {% set degree = states('sensor.openweathermap_wind_bearing')|float %}
          {{ direction[((degree+11.25)/22.5)|int] }}
#

no longer using open weather map
now using pirate weather.
the new sensor needs to read an atribute ( wind_bearing: 39 ) of weather.home_pirate_weather

obtuse zephyr
#

Middle line would be {% set degree = state_attr('weather.home_pirate_weather','wind_bearing')|float %}

digital verge
#

beauty... thanks.

clever briar
#

Im currently trying to get a RESTful sensor to work. Turned on debug logging. however, the sensor state is unknown all the time.

#

Here is the debug log and the value_template

#
2024-08-07 11:52:32.124 DEBUG (MainThread) [homeassistant.components.rest] Finished fetching rest data data in 0.081 seconds (success: True)
2024-08-07 11:52:32.125 DEBUG (MainThread) [homeassistant.components.rest.data] Data fetched from resource: { "realtime" : [
{
"text":"2024-08-07 11:58:55 Lägenhetsdörr 155, summer aktiv"},
{
"text":"2024-08-07 11:58:55 DAC/Dörr 1 ändrad"},
]}```

So it must be something with this: value_template: "{{ value_json['realtime'][0]['text'] }}"  that isn't correctly done right?
#

I want to fetch the text "2024-08-07 11:58:55 Lägenhetsdörr 155, summer aktiv" and then write it into sensor state so I could make use of it in a event.

marble jackal
#

What's the config of your rest sensor?

clever briar
#

@marble jackal ```rest:

  • resource: http://192.168.1.166/cgi-bin/cgi.cgi?action=12
    username: xxxxxx
    password: xxxxxx
    authentication: basic
    scan_interval: 1
    sensor:
    • name: "Kortläsarlogg"
      value_template: "{{ value_json['realtime'][0]['text'] }}"
      unique_id: "sensor.door.cardreader.eventlog"```
#

the log may be empty at times, but if it cannot parse the whole JSON it should not update the sensor right?
A empty log looks like this:
{ "realtime" : [ ] }

#

Tested the value_template in the template builder and it seems to work too

plain magnetBOT
#

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

clever briar
#

Updated the messages now with right formatting. The strange thing is that, I do understand that the empty log message may result in a "unknown" state for the sensor, the right messages should be shown in the sensor event log right?

marble jackal
#

You should guard for that incorrect input
Something like this:

{% set data = value_json['realtime'] %}
{{ data[0]['text'] if data else 'unknown' }}

Or this

{{ (value_json['realtime'] | first | default({})).get('text', 'unknown') }}
clever briar
#

@marble jackal If possible, I would want to ignore empty logs completely, and just retain the latest message it was set to, ergo not update the sensor at all if a empty log line was received

#

There must be a way to, like treat the sensor as no update was received kind of

#

Still unknown in the homeassistant interface even tough adding that guard

wintry bay
#

Hello! I use a smart plug with power metering on my 3d printers. Based on their W consumption I know if ['ready', 'printing', 'completed', 'off'].
The completed happens when its previous state was printing. If I had to create an automation that would be simple, but I'm trying to create a sensor.
Can somebody please help me?
https://pastebin.com/qYYLT91V

marble jackal
#

Use this.state to check on the current state of the sensor at the moment the template is rendered. If this.state == 'printing' and the power consumption is within your thresholds, you know the new state should be completed

wintry bay
#

Thanks, will try!

clever briar
#

@marble jackal TheFes: Yes, did a compelete hass restart

wintry bay
marble jackal
#

Not states(this.state) that will return unknown

#

Just this.state

#

Your whole if-statement is more complex than required BTW

#

But I'm currently on mobile, so I can't easily correct it

wintry bay
# marble jackal Just `this.state`

gotcha. updated! Well yes there's also a off too much which I just removed. Are you referring to ternary operators or similar ways to improve the code? Probably! I generally don't use them because I luckily don't have to think about lines of code or memory constraints 😐

marble jackal
#

There is no need to check on two power values in each part on your if statement, eg, you already know it's above 20 because otherwise a previous statement would have been true. So there is no need to check on that again

clever briar
#

I suspect the restful sensor somehow does not like a string value.

#

Found out now. The restful sensor returns the correct CURRENT value, but in the log, all string values seem to resolve to "Unknown". So basically, I need to completely ignore empty values, and just retain the last log line if the empty log is returned

marble jackal
clever briar
#

Neither of

#

tested with: value_template: "{{ (value_json['realtime'] | first | default({})).get('text', 'SEBBE TEST') }}" and it works, the sensor's value is set to "SEBBE TEST". But as the history shows "Unknown", I need to just retain the last log line if a empty line is sent from card reader

mighty ledge
#

oof, you may flood the event bus if you have a slow system with a 1 second scan_interval

clever briar
#

Petro: The action=12 only returns the events from the last second, thats why I need such a low scan_interval. Looked in the log and it looks fine

mighty ledge
#

make a separate script that passes the info to HA

clever briar
#

so basically, I want to do: value_template: "{{ (value_json['realtime'] | first | default({})).get('text', last_sensor_value ) }}" kind of. But how I do "last_sensor_value"?

#

Petro: It shouldn't flood the sensor bus if the sensor is unchanged right?

mighty ledge
#

You'll be flooding the main loop of HA

#

not just your sensor

#

it may not be a problem, but if you have an active HA, it can slow it down

clever briar
#

I tried to use the full event log, returning the events for the last minute instead, but that script instead crashes the access controller so it reboots

mighty ledge
#

you made this script?

#

and by script I mean, this is separate from HA as in a python or some other language script?

clever briar
#

no, the access controller have 2 methods of getting events: action=12 returns the events for the last 1000 milliseconds, or action=17 where I can specify starttime=<UNIX> and endtime=<UNIX> to get events from a longer period

#

hitting action=17 too often crashes the access controller

#

but action=12 seems to be fine to spam

mighty ledge
#

So are you just using HA and nothing in between?

clever briar
#

yep correct, im talking directly to access controller

mighty ledge
#

i.e. HA (Rest) <-> Device

#

ok, I suggest you make a script using python or some other language that just always runs on the OS

#

that script watches the rest endpoint, and then creates a webhook

#

then you make a template sensor from the webhook trigger

#

otherwise, if you go down this route, you'll need your rest endpoint with the low scan interval that could flood your event loop. And on top of it, you'll likely need a template sensor to ensure you only have the latest value.

#

Also, HA has a rest api, so if your device has the ability to send to an endpoint, that's also an option

clever briar
#

So a event is fired even if a sensor changes value from "THIS DATA" to "THIS DATA"?

mighty ledge
#

No

clever briar
#

then it shouldn't fire anything in the event loop

#

as long as a new log line isn't printed

mighty ledge
#

that's not how polling works

#

polling runs an action every 1 second

clever briar
#

I know, it runs the actual HTTP GET action

mighty ledge
#

whether that action creates a state change is a moot point

mighty ledge
clever briar
#

aha now I understand, I tought the "event loop" was the thing collecting state changes and firint the events

mighty ledge
#

it could not be a problem, but if you are running on a rpi or something else that's crappy hardware, it will slow you down significantly

mighty ledge
clever briar
#

rpi zero 2w lol... but seems it might be ok. Else I need to find a REST <--> MQTT client instead

mighty ledge
#

and the rest integration does not create a dedicated thread

mighty ledge
clever briar
#

yep

mighty ledge
#

I hope all you're doing is the rest sensor...

clever briar
#

the rest sensor and some MQTT

mighty ledge
#

that's defiitely going to run into issues if you have a ton of MQTT updates on top of the 1 second scan_interval

#

are you just running HA Core?

#

(hopefully)

#

if you are, then you're probably gonna be fine but I'd probably still consider creating a python script that handles all the rest stuff. You can hammer the endpoint too with a separate script.

clever briar
#

yep just HAcore

mighty ledge
#

Do you know python?

clever briar
#

no, but I know perl and other script languages. Im thinking of finding some HTTP endpoint <--> MQTT client and then have that MQTT client push the update into hass when it detects a new log line

mighty ledge
#

Yeah thats a good path too

#

if you go that path, you can do an MQTT trigger. But I'd try to make your script not send empty data to the MQTT topic

#

so then all you need is a simple sensor in HA

clever briar
#

yeah thats the idea basically, only send a MQTT message when it actually detects a log line.

mighty ledge
#

right

clever briar
#

but trying to find some good software that could do it

mighty ledge
#

I'd just write a script in perl if you know perl

#

I'm sure there has to be examples out there

#

"perl get info from rest", "perl send info to MQTT topic"

#

then a while loop that checks the rest endpoint every x ms, and if the data has a value, post to mqtt topic

#

super lightweight script

#

and it'll make HA do what it should be doing, automating

#

without forcing HA to do the polling

#

not only will you get faster response time, you'll have 2 lightweight softwares instead of 1 bus that's potentially flooded on a low spec system

#

anyways, that's just my 2c

clever briar
#

should try that. Im trying to just use as little software as possible, as I prefer a integrated monolithic block

mighty ledge
#

I get it

#

typically, small scripts like that rarely need any changes or maitenence

#

I wouldn't be surprised if you could do all of that with a cron job either

wintry bay
# marble jackal There is no need to check on two power values in each part on your if statement,...

Not sure how to do that. I imagined that using a range of values for each state was enough. 1-20, 20-35, 35-up. I'm also not sure the this.state the way I wrote it before works because I did not notice any change in templates-> dev_tools when the state changed (I search in the forum for other people using this.state but couldn't figure it out how to use it)
edit: tested by manually updating the sensor value and 'this' is undefined is what I get in the template of dev_tools

frail dagger
marble jackal
#

you can test this in devtools > template if you add this at the top

{% set this = dict(state = 'printing') %}
wintry bay
marble jackal
wintry bay
# marble jackal ```yaml value_template: > {% set power = states('sensor.tasmot...

testing it now. from ready to printing and back to complete works great! I basically update the value of the tasmota sensor manually. When the sensor goes back to > 0 after it hit the complete condition, it remains in complete. now it's at 14 and it's not ready
update: it just updated and it's ready. I guess this 100% works. Can't thank you enough for providing this code!

split urchin
#

Is there a way to move template sensors from yaml to the UI without losing their history, if I were to give them the same names ?

lofty mason
obtuse lava
# wet imp Just realised your doing this from a json call, this will be coming in the 2024....

Thanks. This gets the meal scheduled for the current day (dinner) and displays it nicely- I'm more interested in showing ALL the meals that are available as just text-based links- the use case is I'm in the kitchen and want to make X for dinner- I use the kitchen screen and scroll through the list until I see it, click it, and the recipe pops up so I can cook it. Do you have any thoughts or suggestions on how to create that card/display?

I have the following code in a markdown card, but it leaves a large blank space at the top (I can't get an image to paste in discord for some reason):

<div>Recipes</div>
<table>
  {% set recipes = state_attr('sensor.list_all_mealie_recipes','items')%}
  {% for i in range(0, recipes | count ) %}
  {% if recipes[i]['name'] %}
  <tr>
  <td>

 [{{ recipes[i]['name'] }}](http://localhost:9925/g/home/r/{{ recipes[i]['slug'] }})
  </td>
  </tr>
  {% endif %}
{% endfor %}
</table>
marble jackal
wet imp
obtuse lava
# wet imp There isn't an action in the integration to get all recipes, that would be a lot...

Interesting! I'm surprised there hasn't been more (any?) demand for a use case like this, to me that's the usefulness of an integration such as this. In no way do I have the foresight to schedule out dinners more than 5 minutes in advance 🙂 I understand a thousand recipes would indeed be a lot to handle, but even in a scroll window or something, with just the names? (Apologies, I'm speaking to you as if you're the developer for this integration, no clue if you are or not!)
Your explanation does help me feel feel less crazy though, thank you for sharing that information

Would it be possible to add a search box or something, so I can pull the recipe up on the kitchen screen?

ocean tusk
#

One quetion:
For this:

trigger:
  - platform: state
    entity_id: "{{ states.sensor | selectattr('object_id', 'match', 'uptimekuma_') | map(attribute='entity_id') | list }}"

i get this error
Message malformed: Entity {{ states.sensor | selectattr('object_id' is neither a valid entity ID nor a valid UUID for dictionary value @ data['entity_id']

restive socket
#

Can anyone help me figure out why passing this to spotcast - it won't play?

playlist: |
        {% set rand = range(1,100) | random %} 
        {% if rand < 30 %} 
        spotify:playlist:37i9dQZF1DWVvXA824aCbn
        {% elif rand < 60 %} 
        spotify:album:3gmIxTApzfuuADskO9zFBB
        {% elif rand < 100%} 
        spotify:playlist:37i9dQZF1E8FuFynUXCIfR
        {% endif %}
#

I have a notification that sends to my phone of what {{ playlist }} is, and it looks correct

inner mesa
#

For both of you:

plain magnetBOT
#

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

inner mesa
ocean tusk
inner mesa
#

There isn't a straightforward way to do what you want to do there

ocean tusk
#

didnt want to list all manually

inner mesa
#

Yes, it can be done, but it's complicated. I suggest just listing them

split urchin
marble jackal
#

History is not deleted when you delete an entity

restive socket
#

If I do the template directly on spotcast it plays as expected, only when it is passed in as a variable does it do nothing.....traces shows no errors

marble jackal
restive socket
#

I suppose I didn't know this method lol

#

Hah, naturally this works - which breaks my brain since logically they're the same. Would love to know the disparity

#

Oop spoke too soon, I can unbreak my brain. The common failure seems to be passing these as a variable

marble jackal
#

What do you mean with passing it as a variable?

plain magnetBOT
#

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

restive socket
#
    skip_condition: true
    variables:
      playlist: |-
        {{ ["spotify:playlist:37i9dQZF1DWVvXA824aCbn",
        "spotify:album:3gmIxTApzfuuADskO9zFBB",
        "spotify:playlist:37i9dQZF1E8FuFynUXCIfR"] | random }}
marble jackal
#

Ah, you can't use templates in a tap action

restive socket
#

it seems to pass the data just fine - the automation is aware of it

#

oooooooooooh

restive socket
#

that is why I can see the entire block instead of one item

marble jackal
#

It will just pass the whole template as a string

restive socket
#

what is the most elegant way to get around this limitation

#

and I say that because a script isnt elegant lol

inner mesa
#

Put it in a script and call the script

restive socket
#

🤦‍♂️

#

lol

#

is there a way to determine what called a script from inside the script

marble jackal
inner mesa
#

You can still pass variables

restive socket
#

oh duh

#

variable passing is pretty new to me, as in I learned it yesterday. Told the wife......this - changes everything

marble jackal
#

You could pass the playlists as list, and then just perform the random filter in the automation (which probably should be a script anyway)

restive socket
#

oooh you mean like playlist: [list,of,uri] and then in the automation do the random?

#

I kind of like that idea

marble jackal
#
  data:
    skip_condition: true
    variables:
      playlist:
        - uri1
        - uri2
        - uri3
restive socket
#

this assumes a known fixed length

wet imp
marble jackal
restive socket
#

bingo! there it is. Thank you @marble jackal - this is much better than a script 😄

edgy umbra
#

I have a sensor that shows total water usage as m3, this value is always increasing. Now i want to make a daily water usage sensor. If i make a new sensor with the utility meter it shows the value as liter, which i want but it gives a error in the logs because the original sensor has the value as m3. Is there anyway to make just one sensor without first making a template sensor that calculates m3 to L? I know I can change the value of the default sensor to L but i want to keep this as m3.

Entity sensor.water_consumed_daily (<class 'homeassistant.components.utility_meter.sensor.UtilityMeterSensor'>) is using native unit of measurement 'L' which is not a valid unit for the device class ('current') it is using; expected one of ['A', 'mA']; Please update your configuration if your entity is manually configured

mighty ledge
#

current is for electrical entities

#

which has a unit of measurement in Amps or milliamps

#

(A, mA)

#

so, change your device_class to be volume

edgy umbra
#

Seems that this can’t be done from the UI?

mighty ledge
#

Yes it can

#

show as

edgy umbra
#

Can’t share a screenshot but i don’t have that option in the mobile app.

mighty ledge
#

Then it would need to be done in yaml if you set the entity up in yaml, otherwise it's coming from the integration and you'd have to override it with customize.yaml

edgy umbra
#

This is the sensor, it shows device_class: water so no idea where the A/mA is coming from?

unit_of_measurement: m³
device_class: water
friendly_name: Water Consumed
mighty ledge
#

your source sensor

edgy umbra
#

That’s the source sensor…

#

It’s just the default consumed water sensor from slimmelezer+.

mighty ledge
#

then it's the sensor you're trying to create

edgy umbra
#

It’s just weird because I’m using the utility meter from the UI and just want to count the daily water usage.

mighty ledge
#

it's not really weird, the device_class is current when it shouldn't be

edgy umbra
#

Ok but it definitely shows water so where is the “current” coming from. 🙂

mighty ledge
#

most likely the integration, which is why I said multiple messages ago that you'll have to override it in customize.yaml 😉

edgy umbra
#

With the integration you mean utility meter from the UI or esphome where the sensor is coming from.

mighty ledge
#

it seems like utility meter is the cause

distant plover
#

I have this template sensor but it's complaining at boot that None has no element 1. What can I do? template: sensor: - name: Kaffesitater state: "{{ state_attr('sensor.kaffesitater', 'sitater')[1] }}" attributes: sitater: > {{ [ "Må kaffen din være sterk og mandagen kort."...]

still geode
#

how do i get auto complete when testing a template?

inner mesa
frail dagger
still geode
#

like IntelliSense

#

so when im tpying a var it autocompleats

frail dagger
#

That isn't available. You can get autocomplete on entity ids, but that's about it.

still geode
#

thats what i mean but its not working

#

oh not it working

frail dagger
distant plover
#

Looks like | default (0) took care of the warning at least

inner mesa
#

|random should work fine to pick a random item from that list

marble jackal
#

{{ this.attributes.get('sitater', ['Nothing']) | random }}

#

or
{{ this.attributes.sitater | default(['Nothing']) | random }}

#

You could also use an input select for the list of texts, if you use a GUI one for that, you can easily add or remove them without having to adjust YAML

still geode
#

is there a way to set a var out of a for loop scope?

still geode
#

so whats the work around

#

go thru each item alone

#

?

frail dagger
#

I've been making use of input_text helpers. There's also a template on the forums that kinda helps too. Let see if I can find the link.

mighty ledge
#

use namespace

mighty ledge
#
{% set ns = namespace(count=None) %}
{% for x in y %}
  {% if x == 7 %}
    {% set ns.count = 'foo' %}
  {% endif %}
{% endfor %}
frail dagger
#

Yeah... what petro posted... you want to use namespace. Derp.

mighty ledge
#

and?, you can aslo set outside the loop

still geode
#

but thats out of the scope no?

mighty ledge
#

please explain what you mean about scope

#

because I don't think you're using it correctly

plain magnetBOT
#

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

mighty ledge
#

namespace...

still geode
#

what is namescape and how would i use it in my case?

mighty ledge
#

i literally just gave you an example

still geode
#

pardon my ignorance but im confused

mighty ledge
#
{% set sensors = [
  'sensor.',
  'sensor.',
  'sensor.',
  'sensor.',
  'sensor.',
  'sensor.',
  'sensor.',
] %}

{% set ns = namespace(upcoming_sensor = None) %}

{% for sen in sensors %}
  {% if now() < as_datetime(states(sen), default) %}
    {% set ns.upcoming_sensor = sen %}
  {% endif %}
{% endfor %}

{{ns.upcoming_sensor}}
still geode
#

im getting 'namaespace' is undefined

mighty ledge
#

spelling

still geode
#

lol

#

still unsure what namespace dose or is but it worked thanks

still geode
#

aha i forgot i need to search jinja not home assitant

#

in short namespace makes it a global var

#

at least thats what i understood

frail dagger
#

Pretty much, yeah

mighty ledge
#

it makes an object that allows you to modify it's values that's safe for jinja

#

it's not global

still geode
#

im thinking php global but i get what you mean

still geode
#

how do i convert 2024-08-08T00:08:00+00:00 to a HH:MM in the time zone of the home assistant instance?

#

as_local().strftime('%-I:%M %p') or is there a better way?

inner mesa
#

that's the most straightfoward way

#

{{ ('2024-08-08T00:08:00+00:00'|as_datetime|as_local).strftime('%-I:%M %p') }}

still geode
#

this is giving me a value:
{{ state_attr(ns.upcoming_sensor, friendly_name) }}
this is not:
{{ state_attr(ns.upcoming_sensor, friendly_name) }}

what am i doing wrong?

inner mesa
#

You're not surrounding friendly_name in quotes

#

It's a string

still geode
#

ten faw

stuck sedge
#

I am making a template sensor for my automover, using some of the sensors it provides, but when using one of them in the template i get some internal value instead of the value the same sensor displays when added to a card on its own. Any tips on how to get that value instead?

#

I'm currently using states('sensor.willy_error')

real girder
#

I'm pirating(?) a neighbours FineOffset weather station and am trying to get the correct UV index. What kind of measurement is this? I'm struggling to find any relevant results while searching. This is the sensor in question. https://i.imgur.com/EqFXUJX.png

autumn flower
#

Scale of 0 to (at least where I live), 14

#

If you live somewhere with a higher quantity of ozone layer, pehaps a lower number

#

Also nice work getting weather station data without buying a weather station 😄

real girder
#

Yeah, that's the standard, but this sensor reports numbers in the thousands and it doesn't look right if I'd just do /1000

autumn flower
#

Oh I thought that was a decimal point, wasn't quite paying enough attention apparently

#

What's the biggest value you get at midday?

real girder
#

Heh yup, I saw someone did this as well and thought to myself hmm let me try. I think this is from the near biotechnical faculty, lots of sensors I can catch.

#

Not sure, started gathering data yesterday. Might need to wait a little and examine the data more. This is all the data I have now https://i.imgur.com/gTfMrhx.png

autumn flower
#

Gets to about 13 in mid summer on a clear day

real girder
#

Today's high should be around 6-7 according to Apple and some other local sites. I'll monitor the data and get back later. Thanks for the help!

limber sonnet
#

hi i am trying to create a summary sensor with the weather data for the next day but when i use this template {{ state_attr('weather.openweathermap', 'forecast')[0].temperature }} i get None has no element 0

marsh cairn
#

Weather entities don't have forecast attributes anymore.

slender adder
#

Question i wanna add a button in a notification that opens a website

#

is this possible?

frail dagger
#

Sure, set the tap_action in the button card to URL and enter a valid URL.

slender adder
#

a button in a notify.

frail dagger
#

Ugh... I can not read today apparently. You mean a mobile device notification or a persistent notification or something else?

slender adder
#

for on my phone

#

mobile notification

slender adder
#
data:
  message: >-
    Geschatte tijd die joey erover doet om thuis te komen is:
    {{state_attr("sensor.google_travel_time","duration_in_traffic")    |
    replace("hour","Uur")   | replace("mins","Minuten")}}

    data:
      url: "https://www.google.nl/maps/dir/{{state_attr('person.joey','latitude')}},{{state_attr('person.joey','longitude')}}\{{state_attr('zone.home','latitude')}},{{state_attr('zone.home','longitude')}}"

    
action: notify.mobile_app_joey_s24
#

i guess something goes wrong

frail dagger
#

If you take the message template and the url template and test them in dev tools > template, what do you get?

slender adder
#

those work

#

it only gives the the message as
blablabla
url: "Link in plaintext here"

frail dagger
#

Ah, you have a \ that's being interpreted into the URL.

slender adder
#

the url is fine

#

the message is also fine, you can only not press the URL in the notification

#

to go to the website

frail dagger
#

iOS or Android?

slender adder
#

need to work on both

#

XD

#

but first Android

#

then ios

frail dagger
#

For Android it's clickAction:.

slender adder
#

do i add that in the message part?

#
data:
  message: >-
    Geschatte tijd die joey erover doet om thuis te komen is:
    {{state_attr("sensor.google_travel_time","duration_in_traffic")    |
    replace("hour","Uur")   | replace("mins","Minuten")}}
    clickaction: "https://www.google.nl/maps/dir/{{state_attr('person.joey','latitude')}},{{state_attr('person.joey','longitude')}}\{{state_attr('zone.home','latitude')}},{{state_attr('zone.home','longitude')}}"
action: notify.mobile_app_joey_s24

Got it like this atm

frail dagger
#

No. clickAction: needs to be under another data:.

marble jackal
#

there's a nice section on it in the companion docs documentation
Looks like what you had before would work for iOS, but not for Android

slender adder
# frail dagger No. `clickAction:` needs to be under another `data:`.

cant work like this

data:
  message: >-
    Geschatte tijd die joey erover doet om thuis te komen is:
    {{state_attr("sensor.google_travel_time","duration_in_traffic")    |
    replace("hour","Uur")   | replace("mins","Minuten")}}

data:
    clickaction: "https://www.google.nl/maps/dir/{{state_attr('person.joey','latitude')}},{{state_attr('person.joey','longitude')}}\{{state_attr('zone.home','latitude')}},{{state_attr('zone.home','longitude')}}"
action: notify.mobile_app_joey_s24
frail dagger
#

Follow the example in the docs.

marble jackal
#

besides indentation (and the repeated data key) , it's clickAction with a capital A

slender adder
#

it doesnt like to be on the same row as message

#
data:
  message: >-
    Geschatte tijd die joey erover doet om thuis te komen is:
    {{state_attr("sensor.google_travel_time","duration_in_traffic")    |
    replace("hour","Uur")   | replace("mins","Minuten")}}
    
  data:
   clickAction: "https://www.google.nl/maps/dir/{{state_attr('person.joey','latitude')}},{{state_attr('person.joey','longitude')}}\{{state_attr('zone.home','latitude')}},{{state_attr('zone.home','longitude')}}"

action: notify.mobile_app_joey_s24
marble jackal
#

you already have a data key, put both the message and the clickAction under that same key

#

oh sorry

#

no

#

that seems to be correct

frail dagger
#

lol

inner mesa
#

yeah, it's always been confusing

marble jackal
#

Follow the example in the docs @marble jackal !

slender adder
#
automation:
  - alias: "Notify Mobile app grouping"
    trigger:
      ...
    action:
      - action: notify.mobile_app_<your_device_id_here>
        data:
          title: "Smart Home Alerts"
          message: "Something happened at home!"
          data:
            group: "example-notification-group"
#

this is what im following, but it doesnt like this setup

marble jackal
#

just add the clickAction under group with the same indentation

    action:
      - action: notify.mobile_app_<your_device_id_here>
        data:
          title: "Smart Home Alerts"
          message: "Something happened at home!"
          data:
            group: "example-notification-group"
            clickAction: https://do-not-use-this.thefes.casa
frail dagger
#
action: notify.mobile_app_bills_iphone_ha
data:
  title: "This is a test"
  message: "This is a test"
  data:
    url: "https://www.google.com"

Works perfectly on my phone.

slender adder
#
    action:
      - action: notify.mobile_app_joey_s24
        data:
          title: "Smart Home Alerts"
          message:
                Geschatte tijd die joey erover doet om thuis te komen is:
                {{state_attr("sensor.google_travel_time","duration_in_traffic")    |
                replace("hour","Uur")   | replace("mins","Minuten")}}
          data:
            clickAction: "https://www.google.nl/maps/dir/{{state_attr('person.joey','latitude')}},{{state_attr('person.joey','longitude')}}\{{state_attr('zone.home','latitude')}},{{state_attr('zone.home','longitude')}}"
#

doesnt work

#

also with the group above the click action

#

i dont get it :/

frail dagger
#

Your indentation is still wrong.

slender adder
# frail dagger Your indentation is still wrong.
action: notify.mobile_app_joey_s24
data:
  title: "This is a test"
  message: Geschatte tijd die joey erover doet om thuis te komen is: {{state_attr("sensor.google_travel_time","duration_in_traffic") | replace("hour","Uur") | replace("mins","Minuten")}}
  data:
    url: "https://www.google.nl/maps/dir/{{state_attr('person.joey','latitude')}},{{state_attr('person.joey','longitude')}}\{{state_attr('zone.home','latitude')}},{{state_attr('zone.home','longitude')}}"
#

copyed yours also nothing

inner mesa
#

what is the goal of that backslash in the URL?

slender adder
#

nothing thats just a typo

frail dagger
#

Yup, it's the backslash that is causing the issue as I said before.

#
action: notify.mobile_app_bills_iphone_ha
data:
  title: "Smart Home Alerts"
  message: 'Geschatte tijd die joey erover doet om thuis te komen is: {{state_attr("sensor.google_travel_time","duration_in_traffic") | replace("hour","Uur") | replace("mins","Minuten")}}'
  data:
    url: "https://www.google.nl/maps/dir/{{state_attr('person.bill','latitude')}},{{state_attr('person.bill','longitude')}}/{{state_attr('zone.home','latitude')}},{{state_attr('zone.home','longitude')}}"
#

That works.

slender adder
#

ok when i change it to clickaction it works

#

cool now for it to be a fysical button

distant plover
distant plover
#

A bit annoying it's not possible to EDIT the options though. Have to delete and add again to fix a small typo.

#

I also see I was wrong about the 255 chars max length but the UI won't show more than like 60 chars, hehe.

autumn flower
#

@real girder Now that you've had another 12 hours to collect data, what sort of UV figures did you get?

plain magnetBOT
#

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

half fable
#

Hello, is anyone understand why I got this error in the template I try to setup: https://pastebin.com/4ajCQTB7

Invalid config for 'template' at template.yaml, line 500: 'platform' is an invalid option for 'template', check: binary_sensor->0->platform Invalid config for 'template' at template.yaml, line 500: required key 'state' not provided Invalid config for 'template' at template.yaml, line 501: 'sensors' is an invalid option for 'template', check: binary_sensor->0->sensors
Invalid config for 'template' at template.yaml, line 500: 'bin_collection_day' is an invalid option for 'template', check: bin_collection_day```
#

in the developeur sectionn the template is working fine

#

oh I figured out this was my mistake:

bin_collection_day:
friendly_name: "Bin Collection Day"

should only be name: xxx

marble jackal
#

Looks like your mixing the modern and legacy format

real girder
stuck sedge
#

Dividing it by ~400 seems to match up with many examples i found with both uv an uvi readings...

real girder
lucid thicket
abstract maple
#

Hey guys. Suppose I wanted to pass a device as a parameter to a script and then use that device in a template, what would that have to look like? As in, what could I expect to actually arrive in that parameter, and how can I work with it, for example, access its entities?

frail dagger
#

In your script, you’ll add a field with a type of device. Then, further down, you can use something like {{ device_entities(device_field) }} to get the entities of the device.

abstract maple
#

Ok, if that works, it should be RELATIVELY easy... They wrote on his toobstone.

frail dagger
#

Yup. I can give you some samples when you get to the point that you’re writing the script.

abstract maple
#

Oh I think I can handle the template part now, but you could explain to me how to use a selector type field. How is the options stanza supposed to be formatted?

frail dagger
#

In YAML? This is one of mine:

speakers:
    selector:
      entity:
        multiple: true
        filter:
          domain: media_player
          integration: sonos
#

Pardon the formatting… 😦

abstract maple
#

Not what I meant, but never mind, I figured it out.

frail dagger
#

Oh? What did you mean? Like in other actions?

abstract maple
#

Like ```fields:
direction:
selector:
select:
options: [hoch, runter, links, rechts]

#

I couldn't figure out the options list, but now it seems to swallow it.

frail dagger
#

Use the YAML list syntax. It always works better for me.

Options:
  - One
  - Two
  - Three
abstract maple
#

🤦‍♂️ Why didn't I figure that out?

frail dagger
#

You’re still learning 🙂 It’s all good!

abstract maple
#

I'm juggling too many variables here. One cat is still missing in the being-fed list, one is playing "the floor is lava" with my new carpet, and my fan keeps falling over.

#

Can you give me a hint how to filter device_entities(..) by device type, e.g. button? I know I could simply do select ('search'... but I don't enjoy being crude...

frail dagger
#
{% set spkrs = integration_entities("sonos") | expand | selectattr("attributes.device_class", "eq", "speaker")  | map(attribute='entity_id') | list %}

This is how I do it in one of my scripts.

#

I’m not sure it’s the “best” way, but it works and it’s fast.

abstract maple
#

and rather elegant.

#

thanks.

frail dagger
#

NP!

abstract maple
#

what exactly is that expand command supposed to do there?

frail dagger
#

It expands out the entities from the integration_entities.

#

Actually, I wonder if I really need that there… 🤔

#

Yup. I need it there to expand out the return value.

#

I sent you one of my scripts in a DM that has a lot of logic in it.

abstract maple
#

Hm... {{ device_entities('dcf5ecf5efb15ee7f3dad2406ec485d2') | expand | map(attribute='attributes.device_class') |list}}gives back a list of "Undefined". could be a problem.

frail dagger
#

The attributes may not contain device_class. Let me check

#

Yeah, on mine, not a lot of the entities have device_classes defined.

marble jackal
frail dagger
#

Ooohhhhh that’s cleaner!

marble jackal
#

Had to make some fixes, should be correct now

frail dagger
#

Yeah, I like that a lot better.

marble jackal
abstract maple
marble jackal
#

No, you probably want this

{{ device_entities('dcf5ecf5efb15ee7f3dad2406ec485d2') | select('match', 'button.') | list }}
abstract maple
#

doesn't really work, returns an empty list. It works if I replace 'match' with 'search' though

#

Perhaps the "buttons" aren't really buttons?

marble jackal
#

Can you give me an example entity_id?

winter forge
#

This template:

    {% set ns = namespace(lights=[]) %} {% set groups =
    integration_entities('group')|  select('search', '^light.')   | list %} {%
    for group in groups %}
        {% set individual_lights = state_attr(group,'entity_id')%}
        {% for individual_light in individual_lights %}
        {% if "group" not in individual_light  and state_attr(individual_light, 'rgb_color') and states(individual_light) == 'on' %}
          {% set ns.lights = ns.lights  + [individual_light] %}
        {% endif %}
        {% endfor %}    
    {% endfor %} {{  ns.lights  }}

Sometimes work, and sometimes return TypeError: 'NoneType' object is not iterable .
What could cause that?

frail dagger
winter forge
bronze prawn
#

I have a custom sentence that I am trying to use as an automation trigger:

convert {amount} {fromcurrency} to {tocurrency}

Unfortunately this does not work as Assist doesn't know how to separate the two variable values so I am considering changing it to this:

convert {amount_and_fromcurrency} to {tocurrency}

My question is this. Is there an easy way to take something like:

convert 100 US Dollars to Euros

and break it down to maybe a list what would be ['100','US Dollars'] using Jinja for the amount_and_fromcurrency value?

winter forge
#

I'm confused as to why it works sometimes and sometimes not

#

I "think" i was pulling all the groups and then the lights from within those groups

frail dagger
#

Yeah, I’m not sure to be honest. I tried it here and it works fine on repeated refreshes of the editor. 🤔

winter forge
#

I know, right?

#

Works "most" of the time for me

lucid thicket
bronze prawn
abstract maple
#

Why does this:{{ states.number.somenumber.state |float * 1.1 | int }} return the ummultiplied state as a float instead of the multiplied state as an int? What am I doing wrong?

inner mesa
#

1.1 | int

#

that

#

turns 1.1 into an integer

#

you need to add parentheses

abstract maple
#

LIke so: {{ states.number.somenumber.state |(float * 1.1) | int }} It doesn't like that at all.