#templates-archived

1 messages ยท Page 39 of 1

obtuse zephyr
#

Share the macro

clear mist
# obtuse zephyr Share the macro
    {% set value_json = state_attr('sensor.suburb_coordinates', 'entries') %}
    {% for x in value_json %}
        {% set testPostcode = x["postcode"] | int %}
        {% if testPostcode == postcode %}
            lat={{ x["lat"] }}&lng={{ x["long"] }}
            {% break %}
        {% endif %}
    {% endfor %}
{% endmacro %}```
#

The suburb coordinates bit is just a text file that I've made into a sensor - the idea is that I give it a postcode and it gives me a lat/long coord back

#

Then I want to append those coords to a url and attach that to a rest sensor

obtuse zephyr
# clear mist ```{% macro suburbCoords(postcode) %} {% set value_json = state_attr('sensor...

There's a bunch of literal whitespace in there, you need to use modifiers on the tags to strip the excess whitespace

{% macro suburbCoords(postcode) %}
    {%- set value_json = state_attr('sensor.suburb_coordinates', 'entries') -%}
    {%- for x in value_json -%}
        {%- set testPostcode = x["postcode"] | int -%}
        {%- if testPostcode == postcode -%}
          lat={{ x["lat"] }}&lng={{ x["long"] }}
          {%- break -%}
        {%- endif -%}
    {%- endfor -%}
{% endmacro %}
cursive ice
#
    sensors:
      washing_machine_door_lock:
          friendly_name: 'Machine Door lock'
          value_template: >
            {{ 'on'  if is_state('binary_sensor.front_load_washer_door_lock', 'on') else 'unlocked' }}``` this is what I use when item has a strange name in idle state, but entity normally happens to be on/off open, is there a template or way that if a item has a state between 400 and 1400 I can just make a sensor from the the entity so it only changes the not_selected one? or do I have to list all the values, or just simply use between 400 and 1400.
obtuse zephyr
cursive ice
obtuse zephyr
#

What should be values be? Do you want it to be a binary_sensor w/ on within the range and off outside?

cursive ice
obtuse zephyr
#
{% set spin_speed = states('sensor.front_load_washer_spin_speed') %}
{{ 'your value' if  spin_speed == "not selected" else spin_speed  }}

I think this is what you're looking for, obviously replace your value with whatever you want not selected to be

cursive ice
obtuse zephyr
#

I'd say so.... you did say earlier not_selected and then later said not selected, so just confirm if there's an underscore or not

cursive ice
#

Works but was Not Selected (exact case)

#

Thank you so much, will help me in the future too ๐Ÿ™‚

obtuse zephyr
#

Awesome, glad to help

stuck sphinx
#

Hello all. First timer and just now getting into the HA scene. I've added all my DSC Door/Window and Garage door sensors using RTL_433 and MQTT. Trying to show the Open/Closed status of all but unsure of the code to do so. Any help would be appreciated, not much of a coder but can understand patterns and this would help me to connect other dots. States/JSON Template? Lost.
mqtt.yaml
binary_sensor:

  • name: "Master_Bedroom_Sliding_Door"
    unique_id: "2152649"
    state_topic: "rtl_433/DSC-Security/2152649"
    device_class: door

Payload from RTL_433
{"time":"2023-05-06 22:37:00","model":"DSC-Security","id":2152649,"closed":1,"event":1,"tamper":0,"battery_ok":1,"xactivity":0,"xtamper1":0,"xtamper2":0,"exception":0,"esn":"20d8c9","status":131,"status_hex":"83","mic":"CRC"}

#

Hope this is the right section. Can move if not.

stuck sphinx
#

The "closed":1 changes to 0 when opened.

frozen kite
rustic raft
#

Question/Issue:
I have a trigger in a blueprint that looks like:

    entity_id:
      - !input motion_sensor
    to: "off"
    for:
        hours: 0
        minutes: 0
        seconds: "{{(seconds_delay if is_state('binary_sensor.night_mode', 'off') else seconds_delay * 2)|int}}"```
`seconds_delay` is defined in the blueprint under `variables:` as `seconds_delay: !input seconds_delay`

This code doesn't work - i.e. never triggers - because of the template string. If I replace the template string line with `seconds: !input seconds_delay` then it works.

My template evaluates to a valid number when testing it in Developer Tools. Any idea what may be wrong?
rustic raft
#

Ahh that's likely it, thank you! Didn't know that was a thing ๐Ÿ™

analog nexus
#

I have the following template that pulls an event from the local HA calendar and works as intended. However I actually want to use the CalDav entities and when I change the calendar name it fails to work.

Any suggestions? Or is this only possible with local calendars?

what's for dinner tonight? {% if now() >= state_attr("calendar.dinner_2", "start_time")|as_datetime|as_local %}
{{ state_attr("calendar.dinner_2", "message") }}
{% else %}
{{
state_attr("calendar.dinner_2", "message")
}}
{% endif %}

stuck sphinx
#

Figured it out.
binary_sensor:

  • name: "Master_Bedroom_Sliding_Door"
    unique_id: "2152649"
    state_topic: "rtl_433/DSC-Security/2152649"
    device_class: door
    value_template: "{{ value_json.closed }}"
    payload_on: "0"
    payload_off: "1"
solar hemlock
#

I'm working with a sensor attribute and I'm trying to pull it into a template / notification . But I'd like to format the template so it shows the time format like this 8:30 AM. Right now it'll show times like this. 726 AM , 930 AM I'm also guessing they could be formatted like this at times too; 726am / 726pm / 726PM / 727AM. Is there a way I could detect when the time format is outside of what I'm looking for and to reprint the message to show the time in a format like this 9:30 AM?

orchid oxide
solar hemlock
#

This is what the output from the two sensor attributes looks like:

Attention!!! Weather alert for place. A Special Weather Statement issued May 1 at 7:45 AM EDT. Strong thunderstorms will impact portions of place, place, place, place and place through 1030 am edt.
At 726 AM EDT, Doppler radar was tracking strong thunderstorms along a line extending from 6 miles southeast of place to place to near another place. Movement was east at 40 mph.

HAZARD...Penny size hail.

SOURCE...Radar indicated.

IMPACT...Minor damage to outdoor objects is possible.

Locations impacted include... list of places...

If outdoors, consider seeking shelter inside a building.

Is it still possible to use timestamp formatting like that since it's a timestamp randomly in the middle of the attribute?

orchid oxide
#

you would have to use regex to find and replace it. if thats the case you may just be better off doing it all in regex

orchid oxide
#

only thing it doesnt do is capitalize am/pm if its not capitalized

solar hemlock
#

Thank you for the example! ๐Ÿ˜€

halcyon owl
#

I am looking to extract the title field information from rss feeds to display on a LED ticker. I have feedparser sensor set up which displays the information in link below. Could anyone tell me how i could extract this infromation using a template? Its for a bbc news rss feed and this is how its displayed in the feedparser sensor - https://pastebin.com/PaCjp41A

orchid oxide
dense swan
#

can you do a rejectrattr on entity_id to remove all devices with light.*_status_led?

#

rejectattr('entity_id', 'search', '_status_led$')?

#

yup...

halcyon owl
orchid oxide
#

is this using the rss feed templat eintegraiton

halcyon owl
#

Using feedparser custom component which creates a sensor name sensor.bbc_news_feed and that sensor displays the text as show in pastebin link above

ashen terrace
#

anyone have a template to count zigbee devices online or can help me make one

marble jackal
#

Which Zigbee integration?

orchid oxide
#

{% for entity in integration_entities('zha') if states(entity) == 'unavailable'%}
  {%if device_attr(entity, 'name_by_user') != None%}
    {%if device_attr(entity, 'name_by_user') not in ns.list %}
      {% set ns.list = ns.list+[device_attr(entity, 'name_by_user')] %}
    {%endif%}
  {%endif%}
{%endfor%}

{{ns.list|sort}}```
 ~~(i was bored, feel free to correct me if it can be done better), also fixed~~
#

yay for not preserving formatting

remote ocean
#

wondering if someone can help me understand what I am doing wrong.. I have the following in the Developer Tools->Templates and it works fine. Driveway Gate: {{ {% is_state('light.driveway_gate', 'on') | iif('Closed', 'Open') %} }} But when I use it in the automation, it errors and I can't save it. -service: telegram_bot.send_message data: message: >- Driveway Gate: {{ {% is_state('light.driveway_gate', 'on') | iif('Closed', 'Open') %} }}

orchid oxide
#

im gonna guess its the {% %} but i would think that woudl cause an error in dev tools template as well

remote ocean
#

I have tried it with {{ and {%

orchid oxide
#

it would be with {{ }}, so take out the {% that should work from what my eyes see

remote ocean
#

This is what is working in Templates: Driveway Gate: {{ is_state('light.driveway_gate', 'on') | iif('Closed', 'Open') }}

orchid oxide
#

what does it actually say the error is when you try to save

remote ocean
#

I think I need to sleep... the {{ }} worked this time. I think I had too many {{ {{ }} }}

#

or in this case {% %}

orchid oxide
#

lol, happens to the best of us

remote ocean
#

appreciate it... thanks

plain magnetBOT
orchid oxide
#

@plucky temple

ashen terrace
#

I have error: mplicit map keys need to be on a single line

plucky temple
orchid oxide
#

it removes the whitespace, and honestly idk which places exactly lmao

#

you can start and end with it everywhere..even if its not necessary in all places so

#

thats the easy route

plucky temple
#

That does seem to be working, thanks! Now I thought that was causing it to output false when it should have been true, but its still saying false. Any ideas?

#

And yes, it is supposed to rain so thats not my problem lol

orchid oxide
#

its overwriting the variable every loop, you need to set a break if true so it doesnt write over it

plucky temple
#

But its only writing true if it will rain, it is never writing false.

#

I need it to say true if even only one of the forecasts says rainy.

orchid oxide
#

oh, cause variables set inside a loop dont carry out of a loop

#

so you can either use namespace or break

plucky temple
#

Even if it's declared before the loop?

orchid oxide
#

yep

#

if you want to do it that way you need to use namespace

plucky temple
#

Huh thats very different from other languages. How would I go about that?

#
{%- set forecast = state_attr("weather.forecast_home_hourly", "forecast") -%}
{%- set rainy_in_next_5_hours = False -%}
{%- for item in forecast[:5] -%}
  {%- if item.condition == "rainy" -%}
  {{"Working maybe?"}}
    {%- set rainy_in_next_5_hours = True -%}
  {% endif %}
{% endfor %}

{{- rainy_in_next_5_hours -}}
#

That is my code right now.

orchid oxide
#
{%- set ns = namespace(rainy_in_next_5_hours = False) -%}
{%- for item in forecast[:5] -%}
  {%- if item.condition == "rainy" -%}
  {{"Working maybe?"}}
    {%- set ns.rainy_in_next_5_hours = True -%}
  {% endif %}
{% endfor %}

{{- ns.rainy_in_next_5_hours -}}```
#

i think this is right, i can never remember namespace syntaxc

plucky temple
#

UndefinedError: 'rainy_in_next_5_hours' is undefined

inner mesa
#

ns.rainy_in_next_5_hours

orchid oxide
#

oh, missed the one at the end

plucky temple
#

Yep it seems to be working as expected now.

#

Thank you for the help!

timber flume
plucky temple
timber flume
#

@ashen terrace

mighty ledge
ashen terrace
#

Thank you, that was easy... Thanks for help ๐Ÿ™‚

cursive ice
#

I sort have a issue with a template, works in template editor but not in config, I get the triangle of shock lol ๐Ÿ˜› - platform: template sensors: washing_machine_run_state: friendly_name: 'washing machine run state' value_template: > {% set run_state = states('sensor.front_load_washer_run_state') %} {{ 'Standby' if run_state == "-" else run_state }} yes for some reason the standby is shown as state (-) when in standby.

marble jackal
#

@cursive ice I have no clue what you mean with the triangle of shock. However the template editor only checks the jinja part. It doesn't check the yaml

#

so it could be there's something wrong there

#

is this code placed under sensor:?

cursive ice
ivory lily
cursive ice
#

none

#

thats what state label returns from that template

ivory lily
#

OK, what is the state of washing_machine_run_state?

cursive ice
#

Standby

marble jackal
#

well, in that case the sensor seems to work

#

this is an issue with the card, not a template issue

cursive ice
#

what makes it even more confusing is this one displays correctly - platform: template sensors: washing_machine_current_course: friendly_name: 'Washing Machine Current Course' value_template: > {% set current_course = states('sensor.front_load_washer_current_course') %} {{ 'Program set' if current_course == "-" else current_course }} which is very strange to me

ivory lily
#

I guess you should check the card configuration.

cursive ice
#

Omg what a newb mistake... - type: state-label entity: washing_machine_run_state style: top: 96% left: 50% pointer-events: none font-size: 15px font-family: var(--font-family) color: AliceBlue line-height: 30px lol ๐Ÿ˜ณ

#

I think sensor. missing was not helping

sacred sparrow
#

how can I have a wait template that does
{{ is_state('input_select.home_status', 'Off') }} OR 3pm ?

mighty ledge
#

or now() >= today_at("03:00")

sacred sparrow
mighty ledge
#

no, add 12

sacred sparrow
#

{{ is_state('input_select.home_status', 'Off') or now() >= today_at("15:00") and now() <= today_at("15:01") }}

#

would that work?

#

I want it to only continue the automation if its between 03:00pm and 03:01pm

mighty ledge
#

sure

sacred sparrow
#

thanks for your help ๐Ÿ™‚

sturdy steppe
#

Hi All, I'm fairly new to HA (a few months) and I've create some nice macros (introduced in 2023.4) for my templates.

Now my question is: Is it possible to add a sensor template to all entities of domain or whole entity glob (device_tracking.*) automatically?

mighty ledge
#

No

#

You can't alter existing entities with templates

sturdy steppe
#

Okay, thank you for your quick answer

floral shuttle
#

did OpenWeatherMap change its uv index value? before I had this working because it returned integers, but now get all unknowns in the attributes

#

so, I have to add a round(0) there on the index, and change all mappers to use numbers instead of strings?

obtuse zephyr
#

Well, if you get unknown in the uv_index attribute, is the actual state of sensor.openweathermap_uv_index unknown, too? Maybe it's not reporting the value right now?

floral shuttle
#

it reported integers before. see my js code for the button I have:```
variables:
text_color: >
[[[ var index = entity.attributes.uv_index;
var colors = ['green','green','green','green',
'orange','orange','blue',
'maroon','maroon',
'red','red'];
return colors[index] || 'grey'; ]]]
icon_color: >
[[[ return (entity.state == 'on') ? 'var(--alert-color)' :'grey' ; ]]]

[[[ return (entity.state == 'on') ? entity.attributes.awareness_level.split(' ')[1].slice(0,-1) :'grey' ; ]]]

icon: >
[[[ return 'mdi:numeric-' + entity.attributes.uv_index + '-circle'; ]]]``` all relying on those numbers

#

somehow its returning 4.96 all of a sudden...

#

wondering if that is a fluke, a resource change, or a HA integration thing

mighty ledge
#

uv index is a number that ranges from 0 to 10. It's a float

#

the api is probably returning more significant figures

floral shuttle
#

yes, I suspect that to be the case, and it seems to be doing this since this afternoon.... my buttons were fine yesterday ๐Ÿ˜‰

mighty ledge
#

did you update HA? If no, then the api changed

floral shuttle
#

hmm, I did update to the latest yes, but not yesterday. now you're making me doubt that.

mighty ledge
#

Ok, then openweathermap updated how it sends data

#

looking at the source, it hasn't changed in 3 months

floral shuttle
#

yes, I had checked that, but figured maybe some other part of HA was changed influencing the state

mighty ledge
#

that's not how code works

floral shuttle
#

on the final state I need: I'd use round(0) and not |int right?

mighty ledge
#

unless it's inheriting from a base class

#

you can use whatever you want, round or int

#

the weather entity wasn't updated either, so it's definitely coming from the API, not HA

floral shuttle
#

heck, it changed from 4.96 to 5.11 now.... before the |int made 4 of that, and the |round resulted in 5

mighty ledge
#

Just confirmed, it's 100% coming from their api

mighty ledge
#

int chops, round rounds

floral shuttle
#

check. this works too now: variables: text_color: > [[[ var index = Math.round(entity.attributes.uv_index); var colors = ['green','green','green','green', 'orange','orange','blue', 'maroon','maroon', 'red','red']; return colors[index] || 'grey'; ]]] icon_color: > [[[ return (entity.state == 'on') ? 'var(--alert-color)' :'grey' ; ]]] icon: > [[[ return 'mdi:numeric-' + Math.round(entity.attributes.uv_index) + '-circle'; ]]] sorry for the JS, but it underlines the change in the API output

#

Math.round() required now to create integers

#

so they changed it at 11.36 this morning ๐Ÿ˜‰

marsh goblet
#

Hi there! I'm trying to get the temperature reading from a climate entity (climate.mh1 => current_temperature attribute). I added the lines below to my configuration.yaml. No errors, but can't get it to appear into my "Developer Tools>States>Filter: "temperature" listing. Any tips?

configuration.yaml:

..
..

template:

  • sensor:
    • unique_id: temperature_mainbuilding_mh1
      name: Temperature > MainBuilding > Bedroom1
      value_template: >
      {{ state_attr('climate.mh1', 'current_temperature') }}
      unit_of_measurement: ยฐC
      icon: mdi:thermometer
      attributes:
      template: temperature
obtuse zephyr
#

Looks like you're mixing modern and legacy config. value_template should be state

marsh goblet
#

Omg, thanks! Tried to get it to work for hours mindblown

peak juniper
#

Anyone have any idea how to adapt the following code but to look at state attributes for "last_period" ?

#
{% set ns = namespace(items=[]) %}
{% for s in expand('sensor.plex_usage_monthly_john', 'sensor.plex_usage_monthly_brian', 'sensor.plex_usage_monthly_carl',  'sensor.plex_usage_monthly_terry', 'sensor.plex_usage_monthly_hank', 'sensor.plex_usage_monthly_jobe', 'sensor.plex_usage_monthly_larry', 'sensor.plex_usage_monthly_muriel', 'sensor.plex_usage_monthly_ryan') %}
  {% set ns.items = ns.items + [ {'name': s.name, 'state': s.state | float(0) } ] %}
{% endfor %}
{% set items = ns.items | sort(attribute='state', reverse=True) %}
๐Ÿ† *Top 5 Users: {{ states.sensor.month.state }} {{states.sensor.year.state }}*
1. {{ items[0].name }}
  _{{ items[0].state }} hours of content watched_
mighty ledge
#

i.e. you only have sensor.plex_usage_monthly_john, you don't have an entity sensor.plex_usage_last_monthly_john

#

if those entities don't exist, you'd need to come up with a way to get them.

peak juniper
#

ah damn, I thought there might be something I can add to pull state attributes like you can name and state

#

thanks ๐Ÿ™‚ will go back to the drawing board

orchid oxide
peak juniper
#

yes that's right. It's a utility meter sensor that counts how many hours people are watching content on my plex server

#

the last_period stores the last month's hours watched

#

the above code tracks which user watches the most content in a month

#

but I want to be able to manipulate it to send out a notification to our telegram group with last month's data, without several automations to store the data at the end of the month when it's already stored as a state_attr

orchid oxide
#

{% set ns.items = ns.items + [ {'name': s.name, 'state': s.attributes.last_period | float(0) } ] %}
does this give you the desired result

#

'state': s.attributes.last_period

peak juniper
#

ah yes, that's perfect, thank you!

#

I had tried a variation of that code but couldn't pin down exactly what was missing

#

thank you so much ๐Ÿ™‚

orchid oxide
#

you can get attributes that way by using .attributes.attributename where youd use .state

#

yw

peak juniper
#

thanks - that was the missing piece of the puzzle

#

I really appreciate it!

glacial swan
#

When doing an icon template in a sensor, is there a shortcut to refer to "id or value of the sensor that i'm defining"?

orchid oxide
#

i am dumb my value template was not enclosed in quotes

glacial swan
marble jackal
#

Do note that it contains the values before the templates are rendered, so this.state will be the current state value, and will probably change soon

orchid oxide
#

is is_state(state, value) vs states(state) == value just preference or is there a benefit of one over the other

mighty ledge
#

is_state gives you odd results when there is no state.

#

er no, i'm thinking of is_state_attr

#

when your attr is none but you check for none, it'll still return false

marble jackal
#

Ah, you mean like this {{ is_state_attr('sensor.foo', 'bar', none) }}

mighty ledge
#

Yes

#

it's an odd scenario where it always returns false if your attribute is none

orchid oxide
#

is this because there technically is no attribute?

mighty ledge
#

No, it's because the attribute is None

#

the attribute exists, but it has no value

orchid oxide
#

strange that it would return false

mighty ledge
#

why would it return true?

#

it's grey area

orchid oxide
#

because youre checking if the attribute is equal to none would be my first line of thought

mighty ledge
#

well for 1, you shouldn't be checking for none with ==

#

and that's what is_state_attr does

#

none is an object, it should always be checked with is none or is not none

orchid oxide
#

dont have that much knowledge here, so what exactly is the difference in how its interpreted

orchid oxide
#

ahh, i see, til

marble jackal
#

But can you actually distinguish between using state_attr() on an attribute which doesn't exist, or which does, but with value none?

#

In both cases state_attr() will return none right?

thorny snow
#

hi, i have a problem with my templatein. at least i think so. maybe someone could help ๐Ÿ˜„

#

okay here is my problem, i am trying to get a message on my phone when a new licence plate is detected by my plate detection system. the message on the phone needs to include the detected plate. as of now i have it set up so that the plate detection software sends a webhook trigger with data attached to my ha server. here i gather the data and try to filter out het 'plate' value listed unther 'results'. but in this filtering i have a error, i cant seem to get de value of the plate key in my message. the webhook data send is x-www-form-urlencoded.
this is the data ha recieves when the webhook is triggerd: https://pastebin.com/UYCWyEnU

obtuse zephyr
#

Are you able to send it as application/json?

thorny snow
#

unfortunately not because i cant edit the sending part of the plate detection code ;C

#

if i could i had solved it already. i tested the same data in correct json format with postman and it worked like a charm...

mighty ledge
obtuse zephyr
mighty ledge
#

it's json after the 6th character

orchid oxide
#

my eyes

mighty ledge
#

so if it truely comes over as json: {... then...

#
{{ (trigger.data[6:] | from_json).data.results[0].plate
obtuse zephyr
# mighty ledge that's not json

Sending it as form data though and it looks like it's getting deserialized appropriately in the data repr (line 44 of the trace)

mighty ledge
#

well that shows it being completely different

#

I didn't see the trace

#

where is he getting json: then in his first post?

#

also, the presentation of the data for the trigger is odd

#

it's showing repr

thorny snow
#

for someone just beginning in templating this is a huge help, have been struggling for 2 days now

mighty ledge
#

repr's are meant for general public

#

it should display it as a dictionary

#

I'll write it up

orchid oxide
#

so odd to me some of the stuff check config doesnt flag
{%if {{states.sensor.lumi_vibration_tilt is defined}} %}

orchid oxide
#

im getting this
2023-05-08 18:23:48.198 WARNING (MainThread) [homeassistant.helpers.template_entity] Template loop detected while processing event: <Event state_changed[L]: entity_id=binary_sensor.dishwasher, old_state=<state binary_sensor.dishwasher=off; door=closed, last_run=2023-05-08 22:23:48.117643+00:00, device_class=running, icon=mdi:dishwasher, friendly_name=Dishwasher @ 2023-05-08T18:23:47.858189-04:00>, new_state=<state binary_sensor.dishwasher=off; door=closed, last_run=2023-05-08 22:23:48.144391+00:00, device_class=running, icon=mdi:dishwasher, friendly_name=Dishwasher @ 2023-05-08T18:23:47.858189-04:00>>, skipping template render for Template[{{states.binary_sensor.dishwasher.last_updated}}]
is it possible to see which entity is causing in my template is causing it

#

nvm, its at the bottom..

#

ok i actually do need help, the following attribute is the problem. i changed it to this, but its still doing the same thing
last_run: '{{this.last_updated}}'

#

can i stop it from looping or do i just ignore it

compact rune
#

I think the answer is "no", but would like to confirm: is there any way to access statistics data in a template? In particular, what I'd love to be able to do is access the most recent 5-minute or hourly change in sum for a total/total_increasing sensor and the same period mean for a measurement type sensor. That way I could, for example, calculate the from-grid low-carbon amount myself from a grid consumption and fossil percentage sensor.

marble jackal
#

Templates can only access real time data, not historical data

#

you can use an SQL sensor to get access to historical data

plain magnetBOT
marble jackal
#

or that one

compact rune
#

Yeah, I figured. I don't actually want anything actually historical -- I want the most recent values of the statistics -- is why I wasn't sure, but a SQL sensor might be the way to do it. I didn't want to use history_stats because I wanted the actual stored statistics value (so it will exactly match the energy dashboard, or at least what the energy dashboard should show, since low-carbon energy is buggy)

sacred sparrow
marble jackal
#

@sacred sparrow I would guess the device_class

#

it expects a numeric state, and a unit_of_measurement of either d, h, min or s

#

not a string

marble jackal
#

There's probably a message about that in the log

sacred sparrow
#

that did it ๐Ÿ™‚ thanks for that

#

its worked for well over a year - strange it stopped now

marble jackal
#

HA became more strict in checking the selected device_class with the values

stuck kelp
#

Interested in listing all entities in light or vacuum.

Running {{ states|....}} gives me too many results, and {{ states.light|...}} too few

How can I get a union between domains?

compact rune
#

Can probably do (states.light + states.vacuum)|...

stuck kelp
#

Seemed like a perfect solution. Got this error, sorry mate:

TypeError: unsupported operand type(s) for +: 'DomainStates' and 'DomainStates'
compact rune
#

Ah, yeah. They may need to be turned into proper lists first

stuck kelp
#

This didn't error:

{{(states.light|list + states.vacuum|list)}}
compact rune
#

Yup, like that is what I was thinking. I don't know all the consequences of casting things to a list like that so ymmv, but hoping it works for you

stuck kelp
#

Feels clunky but it is working; that's the important part ๐Ÿ˜„
Thanks @compact rune!

marble jackal
#

What do you exactly want as the end result? You could do the selection per domain first and add the results together

stuck kelp
#

End result is a list of all objects that are on for both light and vacuum @marble jackal

marble jackal
#
{% set l = states.light | ... | list %}
{% set v = states.vacuum | ... | list %}
{{ l + v }}
#

My vacuum never has the state on

stuck kelp
#

Ah that's a good catch .... your solution means I could select on cleaning

marble jackal
#

Yep

stuck kelp
#

Going to run with this.

Thanks @marble jackal and @compact rune

clear mist
#

hey guys, not sure if this is the right channel but i'm trying to use this integration https://www.home-assistant.io/integrations/rest/

i'm trying to use it to, given a postcode/zip code of my choosing, find the cheapest petrol for the area

my json that i'm using returns the 10 closest stations, and the json has a thing for "Stations" so that "Stations[0]" is the first one, "Stations[1]" is the second and so on

i was hoping to make a single sensor that had all 10 stations in it so i could manipulate it, but the only thing i'm seeing is to make a single sensor for each station and then manipulate them from there? is there a better way?

clear mist
mighty ledge
#

You want it sorted by price, but just want the names?

#

You can also make a template sensor with a stations attribute that just has all that data stored

#

then you can use that however you want

#

just keep in mind that may fill up your database

#

I'll be honest, I'm jealous that the US doesn't have resources like this

clear mist
clear mist
mighty ledge
#

Ok, then your only choice is to just get all the data

#

and then make template sensors

plain magnetBOT
clear mist
#

that's fine

#

how would i do that though - i'm still very new to HA and programming and whatnot and haven't done that stuff before

mighty ledge
#
rest:
- resource: https://www.racq.com.au/ajaxpages/fuelprice/fuelpricesapi.ashx?lat=-27.4650118&lng=153.0132267&fueltype=37
  sensor:
  - name: All Petrol Data
    device_class: timestamp
    value_template: "{{ value_json.Timestamp | as_datetime }}"
    json_attributes:
    - Stations
clear mist
#

oh man, i just had an awesome thought that ties in with year of the voice - being able to ask your assistant where the cheapest petrol is nearby and have it answer for you! or even to be able to ask by "brand" in case you have discounts or anything at particular places!

mighty ledge
#

Then you'll need template sensors to sort and chug through the data

#

which is where all the templating will occur

clear mist
#

template sensors?

mighty ledge
#

Yes

clear mist
#

sorry, i'm still learning things - what are template sensors? i don't think i've come across them yet

mighty ledge
#

Template sensors are sensors that run code to get things into separate entities for use in automations

orchid oxide
mighty ledge
#

either way, that rest sensor will get all the data into HA, then you can do whatever you want after the fact.

clear mist
#

hmm, sounds complicated but i'll give it a shot

alternatively isn't there the option to group sensors? maybe i'll try all separate so i can present it nicely in some mushroom cards or whatever and do a group to get the cheapest one or something?

mighty ledge
#

Well that's my point, if you want to sort it, you need template sensors

#

you can't manipulate data from a rest endpoint without using a template sensor

clear mist
#

fair enough - i'll have a look and see what looks good then! thanks for the help!

mighty ledge
#
template:
- trigger:
  - platform: state
    entity_id: sensor.all_petrol_data
    variables:
      sorted: >
       {{ trigger.to_state.attributes.Stations | sort(attribute='Price') | list }}
- sensor:
  - name: Cheapest Petrol
    state: "{{ sorted[0].Name }}"
    attributes:
      name: "{{ sorted[0].Name }}"
      brand: "{{ sorted[0].Brand }}"
      price: "{{ sorted[0].Price }}"
      address: "{{ sorted[0].Address }}"
      suburb: "{{ sorted[0].Suburb }}"
      last_updated: "{{ sorted[0].LastUpdated }}"
#

but to be honest, it looks like it's already sorted by price

#

so you might be able to just skip this step

clear mist
#

doh, i think you're right about it already being sorted by price!

#

that'll save time!

stuck kelp
orchid oxide
#

yep same way, just use in and a list

stark hamlet
#

Hi, is someone here with expertise on "limited templates" ?

mighty ledge
#

what's the question

stark hamlet
#

trigger_variables:
ย  controller_device: !input controller_device
ย  controller_id: "{{controller_device}}"
ย  controller_entity: "{% for entity in expand(device_entities(controller_id)) | selectattr('attributes.device_class', 'defined') | selectattr('attributes.device_class', 'eq', 'motion')ย  %}{{ entity.entity_id }}{% endfor %}"
trigger:
ย  - platform: event
ย  ย  event_type: state_changed
ย  ย  event_data:
ย  ย  ย  entity_id: "{{ controller_entity }}"
ย  ย  ย  attributes:
ย  ย  ย  ย  device_class: motion

mighty ledge
#

You can't use those functions in limited templates

#

you also can't use templates in event data

#

templates can only be used in specific places on triggers, spelled out in the documents

#

MQTT topics for mqtt triggers, for in state triggers, and value_template for template triggers.

stark hamlet
#

Okay, your first statement seems to be valid, the second one, I can prove. that i have working solutions like that

mighty ledge
#

limited templates are limited in that you cannot use the state machine at all

#

that means, almost all HA custom functions, filters, and tests cannot be used

stark hamlet
#

okay

mighty ledge
#

basically, you're stuck with base jinja

stark hamlet
#

Do you know which developer is responsible for those limitations?

mighty ledge
#

it's limited because access the state machine is not possible in triggers

#

it's the nature of triggers, it's literally impossible to change

#

in regards to the code, the hass object is not usable, so any function that uses the hass object is not usable in limited templates

#

I've worked on this code as well as many others.

#

So, I suggest you find a different route

stark hamlet
#

I do understand that this should not be possile in a usual automation. Due to make things more convienent to use, I would like to discussion the idea to make this avaible during setup of an automation by using a blueprint. I'm a developer myself, I understand the difference between an entity and a device and how things relate to each others. But there are tons of users which do not understand. that's why I try to enhance the convienent use of such blueprints.

So I would suggest, the idea, having templating fully available during setup, so that those variables are filled once, would make really sense to broaden the user base. What do you think?

mighty ledge
#

it's been tried in the past and it's been denied

#

templates themselves are only available in specific locations as well and the documents spell this out

#

limited_templates are only useful for MQTT triggers, and that's the reason they were created

stark hamlet
#

I know that the document spells out alot. But aren't we developers to change this?

mighty ledge
#

Sure we are, but you're trying to change the foundation of all HA

#

and not to mention, you can do pretty much all of this already via conditions and variables that are executed after the trigger

stark hamlet
#

I do not agree. than the automation (blueprint) would be executed several more times. Esecially those stuff like "mode: restart" would effect many broken automations, because it will be triggered without a match.

mighty ledge
#

no?

#

the condition stops the automation from firing

#

trigger starts the automation. Condition decides whether it continues

#

actions are what occur after the condition is met

#

mode would not impact this

stark hamlet
#

so this condition section will have not limited templates?

mighty ledge
#

it has templates

#

and variables

#

triggers are limited to limited templates

#

all other sections are not

stark hamlet
#

maybe I had a miss-understanding there. If seen many snippets defining trigger_variables which have been used in this condition-section.

mighty ledge
#

I have no idea why people are using limited_templates

#

that is people doing the wrong things

#

most things should be included in the variables section

#

which executes between triggers and conditions

stark hamlet
#

this changes a lot ...

mighty ledge
#

order is: limited_templates -> triggers -> variables -> conditions -> actions

stark hamlet
#

thanks for your help

mighty ledge
#

np

#

FYI you can include DIRECTLY to your triggers btw

#

as long as the trigger accepts that object

#

e.g. a device trigger would be able to use !input controller_device

#

without a template extracting it

#

most of his blueprints are well built

#

I can't comment on their actual jinja code, but those blueprints use !inputs, triggers, and variables properly.

marble jackal
#

wew, 1100 lines of blueprint

mighty ledge
#

I can't find any short blueprints that have good examples of "best practices

#

most blueprints aren't great

#

I'd use blueprints, if they could also create scripts on the fly

gray nova
#

I was previously using the garbage collection integrations from HACS but this is being removed in favour of Calendar.

I had been using a template with mushroom cards to change the colour of the mdi based on how many days until garbage collection etc.

Currently trying to figure out how I can run a similar template off of calendar data. Has anyone got any suggestions? It doesnโ€™t seem to be anywhere near as simple to do

mighty ledge
#

You can make a template entity to count the days until your calendar event

gray nova
#

Hero. Thank you

plain magnetBOT
lofty mason
#

second line of the template has ( but no )

mighty ledge
native fable
#

Any suggestions on how I could modify this to count instances of different attributes?

I tried 'attribute' instead of domain, but I get a "UndefinedError: 'homeassistant.helpers.template.TemplateState object' has no attribute 'attribute'" error.

{%- for d in states | groupby('domain') %} {% if loop.first %}{{loop.length}} Domains: {% endif %}- {{ d[0] }}: {{d[0]|count}} {%- endfor %}

plain magnetBOT
latent geyser
#

Any guidance would be appreciated, even to loop it twice with a delay, I'm very new to YAML and could use guidance.

lofty mason
#

Do you not have a close_cover action? Seems like its complaining that it doesn't find that, and I don't see it in your template.

modest shore
#

How do I do this?
value: "{{ [7, states('sensor.ender5_bed_temperature') - 40)/25 | float]|max }}"

#

I know that if sensor.ender5_bed_temperature was a number it would all be fine, but I think it's seeing it as a string(it definitely returns a number in the human sense).

#

I just want to subtract 40 from that sensor reading and then divide by 25

orchid oxide
#

put |float after the sensor to make it a number

modest shore
#

Awesome. So simple. Thanks for the super fast response. It worked.

#

I struggled with it for like 30 minutes, and after your solution, it's SO obvious.

orchid oxide
#

haha, just takes some understnanding of whats going on

#

all states are strings, so if they arent supposed to, you just need to tell the templating engine what its supposed to be

ivory harbor
#

I have a command_line sensor that returns multiple json keys .... can I have multiple value_template entries to map each one?

inner mesa
#

No. That would imply multiple states

ivory harbor
#

think I'm tracking

inner mesa
#

You can, however, put them in attributes

ivory harbor
#

that's what I've been trying.... and I see the JSON fields if I run from the command line... but they aren't making it into HA

#

- platform: command_line name: water-meter unique_id: watermeter2023 command: /usr/local/bin/rtlamr -server 10.15.100.16:1234 -filterid=1569772012 -msgtype=r900 -format=json -single -duration=1m | jq -c '. |= del(.Message) + .Message' command_timeout: 45 device_class: water value_template: '{{ value_json.Consumption | float / 10 }}' unit_of_measurement: 'gal' json_attributes: - Time - BackFlow - Consumption - Leak - LeakNow

#

but for attributes all I have is:
unit_of_measurement: gal friendly_name: water-meter

full crescent
#

I've seen 2 YT'ers in the last week put out videos training templates in the deprecated format. Kind of sad..
Anyone have a hint when the old format will be killed. I'm expecting that might happen soon...

#

Me thinks it's been about a year since the new was introduced.
I sent a note with his code correctly formatted and links to the HA docs to the first guy and he deleted it without response.
And he had people in the comments thanking him for the help with templates and the fantastic training. Really sad.

marble jackal
full crescent
#

MQTT took about a year, so I'm expecting it sooner than later.

dry narwhal
#

Good morning everyone
Is it possible to list all devices of a certain integration?
E.g. I would like to see all my tasmota devices and all my shelly devices.

#

Sorry, found it

#
{{ integration_entities('hue') }}  # ['light.hue_light_upstairs', 'light.hue_light_downstairs']
marble jackal
mighty ledge
#

I doubt it will ever happen

#

unless there's an overhual that will cause it to not work. But, knowing the code, even an overhaul will unlikely kill it because all we do is pass the old format yaml to the new format when creating the entities.

mighty ledge
inner mesa
final sun
#

oh sry misclicked

hearty verge
#

Does the state object in templates contain the integration/domain - aka how could i get a list of all my SONOS media players?

#

integration_entities('sonos')

#

I see ๐Ÿ™‚ and pull out media players

#

Given 2 lists does Jinja support the intersection?

inner mesa
#

You can use integration_entities()

hearty verge
#

Right but how do i filter that for juts media players?

inner mesa
#

That gives you a list of entity_ids

#

Trivial to filter for specific domains from there

hearty verge
#

Do i pipe it to a regex match?

inner mesa
#

That's one way

hearty verge
#

is there a better way?

mighty ledge
#

just select things that search for media_player.

inner mesa
#

{{ integration_entities('Roku')|select('contains', 'media_player.')|list }}

hearty verge
#

Ah! Thats a bit better than:

{{ integration_entities('sonos') | regex_findall('media_player\.\w+') }}

#

Thanks...

inner mesa
#

or: {{ integration_entities('Roku')|select('match', 'media_player')|list }}

#

depends on what you want to do with the list, really

hearty verge
#

Thanks rob! ๐Ÿ™‚

full crescent
# mighty ledge Are you active on here often?

I've adopted the BluePrints channel here and kind of ignore everything else. With Moddin on Drzzs channel and my own stuff going on, it's about my bandwidth limit. Also stick with what you know,,, My BP's are under SirGoodenough nick, so thanks for the kind words above.

ivory harbor
#

can I pass the value of a timer to the duration field in an automation? When i try this, and save it, it gets replaced with 'null'

#

delay: hours: 0 minutes: {{ state_attr('timer.sprinkler_offset', 'duration')}} seconds: 0 milliseconds: 0

mighty ledge
#

it needs to be in quotes

#

or use multiline notation

#

by it i mean the tempalte

inner mesa
ivory harbor
#

thanks! little stuff like that keeps getting me

#

just confirming:
delay: "{{ states('input_number.spinkler_offset' )}}"

inner mesa
#

that will use seconds

#

in the first example, you're using minutes

ivory harbor
#

got it, so I have to specify which time field the helper is being used for

inner mesa
#

the last example takes minutes and turns it into seconds

ivory harbor
#

when I use that example with a helper number, I get 'no default specified' ... I'm ok to use the hours minutes seconds field and just apply the template to the minutes field

inner mesa
#

does your number helper have a valid value?

#

it probably says other things too

ivory harbor
#

it does have a value, in this case, '3.0'

#

but if I do the multiply (60) before converting to an int, then it works

inner mesa
#

you would need to share the actual code that you're using

ivory harbor
#

I think this is working...
delay: >- {{ ((states('input_number.sprinkler_run_minutes') | float + states('input_number.sprinkler_run_minutes') | float) * 60) | int }}

#

now I'm trying to set the value of a value of a helper using a timestamp attribute of another entity:
service: input_datetime.set_datetime data: time: "{{ as_timestamp(state_attr('sun.sun', 'next_rising')) | timestamp_custom("%H:%M:%S", true) }}" target: entity_id: input_datetime.sprinkler_am

inner mesa
#

is time() a thing?

ivory harbor
#

oops...type in my paste, edited

autumn sedge
#

Hey, struggling with how to get the item selected in an input select to work in a script to play the media file of the same name. I'm editing a script I had working which pulls the info from a sensor, but I want to use an input select so I can choose a track.

#

one sec I'll paste the code in

#
        'file_list')
#

That's what I have working, I want to replace it with the item selected in an input select

#

I tried:

lofty mason
#

states() not state()

summer ice
#

someone now how to remove the date of the attr?

input:
{{ state_attr('calendar.www_*****_gmail_com', 'start_time') }}

output
2023-05-11 09:10:00

autumn sedge
#

Aha! Thanks, I'll give that a go. Another basic question, I have to edit the filepath, I have a "replace" command working fine, but is there one to prefix some info?

#

eg the input select says "track.mp3" and in the script I need to say path/to/track.mp3

orchid oxide
summer ice
#

yes

orchid oxide
#

timestamp_custom filter

plain magnetBOT
#

When working with templates, don't forget:

  • You can test them in Developer tools -> Templates
orchid oxide
#

eh not that

#

info about it here

summer ice
#

thanks

autumn sedge
pastel moon
#

This used to work, but in dev-templates it evaluates to 'evening', which should be night, so guess something is up here... Can this be rewritten more efficiently perhaps?


                {%- if (as_datetime(states('input_text.morning'))
                    <= as_datetime(cTime) <= as_datetime(states('input_text.day'))) -%}
                    morning
                {%- elif as_datetime(states('input_text.day'))
                    <= as_datetime(cTime) <= as_datetime(states('input_text.evening')) -%}
                    day
                {%- elif (as_datetime(cTime) <= as_datetime(states('input_text.night'))) -%}
                    evening
                {% else %}
                    night
                {% endif %}```
autumn sedge
#

OK, next question. I have my input select being populated by the contents of a folder (and I'm removing the path to make it look better). How can I randomise the order? If I include random in the template it just picks one item from the folder and puts that in the input select, instead of all items.

service: input_select.set_options
target:  
  entity_id: input_select.big_red_button_playlist
data: 
  options: "{{ state_attr('sensor.big_red_button', 'file_list') | map('replace', '/media/Sounds/Big Red Button/', '') | list }}"
orchid oxide
autumn sedge
orchid oxide
#

not sure if this is the best solution, but this works

{%set ns.newlist=[]%}
{%for each in ns.oldlist%}
{%set ns.newlist = ns.newlist + [ns.oldlist|random]%}
{% set ns.oldlist = ns.oldlist|reject('in', ns.newlist)|list%}
{%endfor%}
{{ns.newlist}}```
#

obviously where oldlist is your list

plain magnetBOT
obtuse zephyr
#

Just use {{ trigger.from_state.state == "on" }} if you want to see if it was on

pliant egret
#

annnnd it works. Thanks folks

inner mesa
pliant egret
#

Gotcha, figured it must be something like that.

#

and got it all working! thanks all!
And thanks for the help the other night pointing my Rob! Got the blueprint working and will use that to push to multiple switches!

sick ice
#

when using |int(default=0) in templates, is there a way to use the most recent value in history in stead of a defined integer?

marsh goblet
#

I'm building a sensor for getting forecasted electricity price for the next 24h through a restful API. Can I just add the forecasted data to a custom named attribute to visualize it? Are there any reserved names for a forecasting data to enable easy integration to my GUI?

grim flicker
#

i have a mqtt sensor on which i would like to use a template. If the value of the mqtt output is 0 it should ignore that value. if not it should go through. i can seem to find how to do this properly.

- name: "Gasverbuik test met filter"
  state_topic: "p1monitor/smartmeter/consumption_gas_m3"
  device_class: gas
  state_class: total_increasing
  unit_of_measurement: mยณ
  value_template: |-
    {% if value_json == 0 %}
      {{ false }}
    {% else %}
      {{ value_json }}
    {% endif %}

I have this at the moment.

#

This seems to work. atleast i get the right value. Will this work when the value hits 0? or will this render an error when it posts false? or should false be something else

jagged dune
grim flicker
#

The problem is dlthat it drops to 0 which adds nothing but then the value becomes normal again to aroun 2000 M3 and then the energy integration thinks nice! Let's add 2000 M3 in a few seconds!!

jagged dune
#

so the problem is, why is the source dropping to 0?

#

according to the docs, that shouldn't matter

#

Doesn't adding it to the energy board just work?

#

not sure how you connected your P1

compact rune
marble jackal
#

value_template: "{{ this.state if value_json == 0 else value_json }}"

grim flicker
#

Thanks

marble jackal
#

other options (as 0 is falsely):

{{ value_json | default(this.state, true) }}
{{ value_json if value_json else this.state }}
{{ iif(value_json, value_json, this.state) }}
{{ value_json | iif(value_json, this.state) }}
grim flicker
#

its hard for me to understand how these options really work because my knowledge for this is very limited. if im correct value_json is the actual value received from the mqtt message. for example {{ value_json | iif(value_json, this.state) }} what does this do? this.state is the current state before a new value is received i guess? so the iif will check if value_json == this.state?
normally im used to write the if statement first and the action afterwards. but {{ value_json if value_json else this.state }} is written the other way around correct? so it will post value_json when value_json has a value or else it will keep the old state right?

Sorry for this but i would like to understand how this works so i dont need to ask all these questions everytime ๐Ÿคฃ

jagged dune
#

im trying to create a fan.
To change the fan speed, I call an API endpoint http://esp.local/api?rfcommand={{command}}.
There are 4 presets, auto, low, medium, high.
To read the current speed percentage, I use a sensor sensor.itho_percentage

I was using the fan template from the docs, but can't figure out how to set it

#

I can't control it with the percentage

#

the percentage is from an mqtt

#
     - name: "Itho Percentage"
       state_topic: "itho/ithostatus"
       unit_of_measurement: "%"
       device_class: "power_factor"
       value_template: "{{ value_json['Absolute speed of the fan (%)'] }}"
       unique_id: "itho_percentage"
marble jackal
#

iif is and immediate if which can be used as a filter or function which you can use instead of "foo" if x > y else "bar"

grim flicker
#

ok thanks! its allot more clear now

long hinge
#

hello guys

I am trying to add a sensor that makes me a simple calculation of multiplication between 2 sensors. The problem is that I didn't have created the file "sensors.yaml" I just created it and I added in config.yaml the "include".

It detects the new sensor created, but it gives me value 0, because it is not taking correctly the value of the sensor that I already had configured. In fact I have checked all the .yaml documents and I can't find them anywhere and where they are located.

I suppose that there is the problem, as they are not in the same place it is not able to read the value of the sensor to make the operation.

Can someone help me to solve it?

Thank you very much!

#

i'm new in home assistan and i'm trying in VM

plain magnetBOT
#

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

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

mighty ledge
#

Post all your code please.

long hinge
#

from which file?

mighty ledge
#

at this point, configuration.yaml and sensors.yaml

#

and include the name of the file you used for sensor.yaml

hearty verge
#

Is there a way to turn a whole set of state objects into JSON with the attributes and all?

#

I know i can pass to the expand filter a set of entities but I haven't figure out the next step

#

TypeError: Type is not JSON serializable: TemplateState

#

I run into that problem

long hinge
#

configuration.yaml:

Loads default set of integrations. Do not remove.

default_config:

Load frontend themes from the themes folder

frontend:
themes: !include_dir_merge_named themes

Text to speech

tts:

  • platform: google_translate

automation: !include automations.yaml
script: !include scripts.yaml
scene: !include scenes.yaml
sensor: !include sensors.yaml

#

sensors.yaml

  • platform: template
    sensors:
    total_energy_cost_p1:
    friendly_name: 'Total cost P1'
    value_template: '{{ ((states.sensor.acumulado_mensual_punta.state | float * 0.2)) | round(0) }}'
    unit_of_measurement: 'โ‚ฌ'
autumn sedge
# autumn sedge I think maybe I need to include "| shuffle" instead of "| random" but it gives a...

I got this sorted by the way. This template (created with the help of Google Bard!) looks at a sensor monitoring files in a folder, then generates a shuffled list of the file names, which is different each time it's run.
options: "{% set songs = state_attr('sensor.big_red_button', 'file_list') | map('replace', '/media/Sounds/Big Red Button', '') | list %}{% set ns = namespace(x = songs) %}{% for i in range(ns.x | length - 1, 0, -1) %}{% set j = range(0, i + 1) | random %}{% if j != i %} {% set ns.x = ns.x[:j]+[ns.x[i]]+ns.x[j+1:i]+[ns.x[j]]+ns.x[i+1:] %}{% endif %}{% endfor %}{{ ns.x }}"

mighty ledge
mighty ledge
#

add 3 backticks before and after

#

`

#

or use a code sharing website like I linked before.

plain magnetBOT
austere basin
#

I think I found my problem....
Platform template not ready yet: The template button platform doesn't support trigger entities

#

which is not what the docs say, so I am hoping an update will fix it up

mighty ledge
#

@long hinge you need to use an availabilty template and also use the states() function

- platform: template
  sensors:
    total_energy_cost_p1:
      friendly_name: 'Total cost P1'
      value_template: "{{ (states('sensor.acumulado_mensual_punta') | float * 0.2) | round(0) }}"
      availability_template: "{{ states('sensor.acumulado_mensual_punta') | is_number }}"
      unit_of_measurement: 'โ‚ฌ'
plain magnetBOT
mighty ledge
#
  - button:
     - name: "Matthew Desktop Mute"
       unique_id: "muteymeetingahoy"
       icon: >-
         {% if is_state("binary_sensor.matthew_meeting_mute","on") %}
         mdi:volume-off
         {% else %}
         mdi:volume-high
         {% endif %}
       press:
           service: button.press
           target:
             entity_id: button.desktop_toggle_mute
#

trigger is unnecessary anyways

#

you weren't even using the trigger

austere basin
#

ok

#

The problem is it's not a binary sensor ๐Ÿ™‚

mighty ledge
#

if you're interested in optimizing...

  - button:
     - name: "Matthew Desktop Mute"
       unique_id: "muteymeetingahoy"
       icon: mdi:volume-{{ iif(is_state("binary_sensor.matthew_meeting_mute","on"), "off", "high") }}
       press:
           service: button.press
           target:
             entity_id: button.desktop_toggle_mute
mighty ledge
#

Your code was using a binary sensor.

austere basin
#

matthew_meeting_mute

mighty ledge
#

so what

#

then why'd you use that?

austere basin
#

yeah, but for some reason it wasn't working as a binary sensor so I changed it

mighty ledge
#

is this an entity or not binary_sensor.matthew_meeting_mute?

austere basin
#

it isn't. It WAS, but not anymore.

mighty ledge
#

so what do you have now?

austere basin
#

it works now ๐Ÿ™‚

#
    button:
     - name: "Matthew Desktop Mute"
       icon: >-
         {% if is_state("sensor.matthew_meeting_mute","True") %}
         mdi:volume-off
         {% else %}
         mdi:volume-high
         {% endif %}
       press:
           service: button.press
           target:
             entity_id: button.desktop_toggle_mute
#

it's beautiful. Using mutesync, now I can have visibility and control of the mute status not just of the audio device, but within teams.

#

Then I can use it to display status on the RGB LEDs I have put in my mic

long hinge
#

How can I make it show 2 decimals?

Thanks

long hinge
#

where do I have to add this part?

mighty ledge
long hinge
#

nice!! thanks!

foggy mortar
#

Hi, im trying to change a sensor which provides a date into "Tomorrow" "in x days" etc. From the forums i found the following snippet which seems close to what im trying to achieve. However when i replace set event= '2020-11-03' with my sensor, its throwing error. Anyone who can push me in the right direction?

{% set midnight = now().replace(hour=0, minute=0, second=0, microsecond=0).timestamp() %}
{% set event = '2020-11-03' | as_timestamp %}
{% set delta = ((event - midnight) // 86400) | int %}
{% if delta < 0 %}
  {{ -delta }} Days Ago
{% elif delta == 0 %}
  Today!
{% elif delta == 1 %}
  Tomorrow
{% else %}
  In {{ delta }} Days
{% endif %}```
inner mesa
winter cape
#

Hi, I have this template:

#

{% set num_adults = expand('group.adults_home_tracker') | selectattr('state','eq','home')|list|count %}
{% set num_adults_beds = ['binary_sensor.bedroom_daddys_bed_occupancy', 'binary_sensor.bedroom_mommys_bed_occupancy' ] | list %}
{% set occupancy_adults_beds = states | selectattr('entity_id', 'in', num_adults_beds) | selectattr('state', 'eq', 'on') | list |count %}
{% if num_adults <= occupancy_adults_beds and num_adults != 0 %}
on
{% else %}
off
{% endif %}

#

Why: "This template listens for all state changed events" and trigger looks like that:

#

Turned off triggered by state of Tรกta was detected at home
6:48:43 AM - 15 hours ago
Turned on
6:10:46 AM - 15 hours ago
Turned off triggered by state of Bathroom Washing machine plug changed to 0
5:08:04 AM - 16 hours ago
May 10, 2023
Turned on
11:58:26 PM - 22 hours ago
Turned off triggered by state of Dining room ATC Signal Strength changed to -92
11:47:26 PM - 22 hours ago
Turned on
11:45:26 PM - 22 hours ago
Turned off triggered by state of Living room ATC Temperature changed to 21.48
11:40:26 PM - 22 hours ago

orchid oxide
#

its very difficult to read otherwise

winter cape
#
        {% set num_adults_beds = ['binary_sensor.bedroom_daddys_bed_occupancy', 'binary_sensor.bedroom_mommys_bed_occupancy' ] | list %}
        {% set occupancy_adults_beds = states | selectattr('entity_id', 'in', num_adults_beds) | selectattr('state', 'eq', 'on') | list |count %}
        {% if num_adults <= occupancy_adults_beds and num_adults != 0 %}
          on
        {% else %}
          off
        {% endif %}```
orchid oxide
#

your template listens for all state changes because youre using state. as for why its triggering on unexpected state changes, maybe someone who knows better can tell with less info, but to me it appears that occupancy_adults_beds is selecting entities that you dont want

winter cape
#

the sensor works perfect, its not a problem, but the triggers looks weird

orchid oxide
#

because youre listening for all states with states

#

you can narrow it down with states.binary_sensor

winter cape
#

here? ['binary_sensor.bedroom_daddys_bed_occupancy', 'binary_sensor.bedroom_mommys_bed_occupancy' ] ?

orchid oxide
#

right here {% set occupancy_adults_beds = states | selectattr('entity_id', 'in', num_adults_beds) | selectattr('state', 'eq', 'on') | list |count %}

#

actually, you should just be using num_adult_beds|selectattr('state','eq','on'|list|count) on that line

#

you only need to be listening for state changes of things in that group, right?

winter cape
#

This template listens for the following state changed events:

Domain: binary_sensor
Entity: group.adults_home_tracker
Entity: person.daddy
Entity: person.mommy

#

not binary_sensor.xxxx occupancy

orchid oxide
#

not sure i follow what youre saying

winter cape
#

i am not sure, after this change, it listen to 'binary_sensor.bedroom_daddys_bed_occupancy', 'binary_sensor.bedroom_mommys_bed_occupancy'

orchid oxide
#

why are you using state|selectattr('entity_id', 'in', 'num_adult_beds') when you could be using num_adult_beds instead

winter cape
#

ok, I dont know... I will try it

orchid oxide
#

that should fix your issue with it firing on every state change, by only listening for things that happen in that list rather than every state change

#

expand(num_adults_beds) btw

winter cape
#

group is number of people at home, what you mean?

orchid oxide
#

num_adult_beds is the beds that youre looking for occupancy in, youre checking to see how many beds are occupied

#

right?

#

oh, sorry i miss understood your question. when i said group i meant the list num_adult_beds

winter cape
#

Exactly.

#

comparing how many people are home and how many beds are occupied.

orchid oxide
#

yeah, and you were iterating through every single state object with state when you only needed to iterate through the objects in num_adult_beds

winter cape
#

Yes

marble jackal
#

It also limits the updates in the templates, if you use states it's limited to once per 10 seconds

orchid oxide
#

im guessing thats why completely unrelated state changes were showing up as being the trigger?

marble jackal
#

Most probably yes

ebon drift
#

How to get the time since a person entity changed states? For ex. Person.Marcin in my logbook was โ€œhomeโ€ nearly 5,5hrs ago, but using person.marcin.last_changed gets me: โ€œ24 minutesโ€ ๐Ÿ˜ณ

plain magnetBOT
orchid oxide
#

^

#

wait

#

well yeah

#

last changed doesnt persist on reboot

#

which is why it only shows 24 minutes

ebon drift
#

But I didn't restart my HA

#

Even if, is there any other way to mitigate this?

#

An easier way to get the value that is in the logbook?

orchid oxide
#

try last_updated then

#

but the value wont be consistent on restart

ebon drift
#

I tried ChatGPT, but it gave me code like this:
{% set person_id = 'person.user' %}
{% set last_home = states[person_id].attributes.last_changed %}
{% set last_not_home = as_timestamp(history.state(person_id, 'not_home').last_changed) %}
{% if last_home > last_not_home %}
The person was last seen at home on {{ as_local(last_home).strftime('%Y-%m-%d %H:%M:%S') }}.
{% else %}
The person has not been seen at home recently.
{% endif %}

orchid oxide
#

nah i think last_changed is what you wanted (honestly can never remember which is which)

#

chatgpt is stupid

ebon drift
#

I don't think such a thing as "history.state" exists

orchid oxide
#

it makes up stuff that doesnt exist

ebon drift
#

Well, I wish history.state would exist ๐Ÿ˜„ It's just imagining things I guess

orchid oxide
#

you can use the history stats integration to make a sensor that tells you how long an entity has been in a state

ebon drift
#

Oh, which one is it?

orchid oxide
#

scroll up a tad

#

states.person.last_changed should persist though until restart or state change (based on my limited knowledge)

ebon drift
#

I'll give that history_stats a go, thanks!

plain magnetBOT
mighty ledge
#

@final sun you can only get the previous state when the state is changing and store it in another sensor. Or in an automation by looking at the 'from_state' if you used a state change trigger.

marble surge
#

hello...
I have an mqtt sensor with a value template like this:

{
   "name":"Glow Worm Luciferin Version",
   "icon":"mdi:numeric",
   "unique_id":"Glow_Worm_Luciferin_Version",
   "state_topic":"lights/glowwormluciferin",
   "value_template":"{{ value_json.ver if value_json.ver is defined else states('sensor.glow_worm_luciferin_version') }}",
   "unit_of_measurement":" ",
   "force_update":true
}
plain magnetBOT
marble surge
#

since the latest HA update I get this error in the logs (modificato)
ValueError: could not convert string to float: '5.5.5'
but who said it that it's a float? I want it as a string
it seems that this sensor does not accept strings like this "pippo"
can't understand why HA things that it's a numeric field instead of a string one

mighty ledge
marble surge
#

thank you very much petro

silent vector
#

Is it possible to do a regex replace if there's only 1 word. Replace with upper? Meaning there's no whitespace between characters essentially. If there is whitespace as in more than 1 word then just do filter title.

inner mesa
#

How is that different from just using |title in both cases?

silent vector
#

Title would turn foo to Foo not FOO. The values would be dynamic so that's why I was trying to see if there's some way to just detect 1 word by checking for no whitespace between characters. And do upper else title

haughty breach
#

Not regex, but ....
{% set x = "foo bar" %} {{ x|upper if x.rsplit(' ')|count==1 else x|title}}

silent vector
#

That is awesome. Thank you.

mighty ledge
#

if you're looking for speed, you'd want to use ' ' in x instead

plain magnetBOT
mighty ledge
#

@jagged dune templates fans only accept on/off as the main state. You cannot put other values into the state

jagged dune
#

Do you perhaps also know how to use the preset modes with Google home?

#

When i use them, Google just searches the web.
My language is set to Dutch.

full crescent
#

So Template extensions. I tried some, they didn't seem to work I trird an inport that was just false, and it didn't seem to do what I thought it should. I don't really need to share code yet that you'all have to look at. Just wondering if the Developer sandbox is set-up to accept the extensions so we can do some pretesting? It doesn't seem to be, so assuming that it is not, it this a thing that's possible? Asking the experts here before I bother to add an FR.

inner mesa
#

I just created /config/custom_templates/test.jinja with this content:

{% macro groot() %}
  {{ "I am Groot" }}
{% endmacro %}

called the homeassistant.reload_custom_templates service
and put the following in the template dev tool:

{% from 'test.jinja' import groot %}
{{ groot() }}
#

the result: I am Groot

full crescent
full crescent
jagged dune
#

I can give commands in numbers. The preset words don't work ๐Ÿฅฒ

#

They do show up in the entity of Google

full crescent
#

I tell my google a percent and it works

marble jackal
jagged dune
#

I rather say put it on medium, or put it on auto

#

If i say, put it in 1%, it responses with: i will put it on low

full crescent
final sun
#
entity_id:
  - sensor.saugroboter_eg_cleaning_history
id: Saugroboter Modus wechseln
to: unavailable```

Can I modify the trigger to only trigger if the sensor didn't change to unknown or unavailable?
obtuse zephyr
#

You can use not_to instead of to and pass in a list of those both

final sun
#

Ah ty. Didn't know what to search for

sonic ember
#

Hi! Checked the release notes already, but can't find it. Somehow some templates I had were working perfectly a month ago, and now they don't (was on holiday in between, and only difference is I moved from 2023.3 to 2023.5). Anything in here that might not be compatible anymore?

  # Find the cheapest time in before an input time for the washing machine
  - name: "NextEnergy Cheapest Hour Washing Machine"
    unique_id: 2019ac19-72b2-407c-8609-403b2305732e
    icon: mdi:clock
    unit_of_measurement: "EUR"
    state: >
      {% set hour_threshold = states('input_number.washing_machine_hours_ahead') | int - 3 %}
      {% set time_threshold = now().replace(minute=0, second=0, microsecond=0) + timedelta(hours=hour_threshold) %}
      {% set items = state_attr('sensor.energyprices','raw_today') + state_attr('sensor.energyprices','raw_tomorrow') %}
      {% set lowest = items | selectattr('start', '>', now()) | selectattr('start', '<=', time_threshold) | sort(attribute='value') | first %}
      {% set lowest_price = lowest.value * states('input_number.nextenergy_additional_electricitycosts') | float(0) %}
      {% set cheapest_time = lowest.start %}
      {{ cheapest_time }}
#

This is the error (in the log, not very clear)

Error while processing state change for input_number.washing_machine_hours_ahead
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/components/sensor/__init__.py", line 579, in state
    numerical_value = int(value)
ValueError: invalid literal for int() with base 10: '2023-05-14 11:00:00+02:00'
inner mesa
#

You seem to have a datetime string in an input_number

#

You can and should add a default for the |int conversions like |int(0), but you should also figure out what caused the broken input_number value

sonic ember
#

The strange thing is it worked before. So something must have changed. Either the input from a sensor, or the way my template is parsed.

inner mesa
#

The error message is clear enough. Go look at the state of the entity

sonic ember
#

Oh wait, I think I found something else in the error.

#

: Sensor sensor.nextenergy_cheapest_hour_washing_machine has device class None, state class None unit EUR and suggested precision None thus indicating it has a numeric value; however, it has the non-numeric value: 2023-05-14 11:00:00+02:00 (<class 'str'>)

#

Damn, remnants from a previous way of doing it. I see some leftover code I should remove

#

Works! Damn. So in 2023.3 that bit of code had no effect, but now it does. Should I share this somewhere? I had unit_of_measurement: "EUR" for a template that is a datetime.

river tinsel
#

So, I want a template binary_sensor driven by the span of a specific calendar event (i.e. by message), so it turns on X hours before the start, and then turn off Y hours later (or relative to the end time, either way); I thought I'd be able to add a trigger to that template sensor, with my -X offset, and then set the state by checking trigger.calendar_event.message, such as: state: "{{ trigger.calendar_event.message == 'Trash day' }}". But by doing it this way, don't we lose the ability to have a one-to-one relationship of event-to-entity? That is, this works if the calendar contains ONLY my trash day event (or at least, does not contain any other event within X-Y hours of trash day) - if there's another event, say 30 minutes after the "trash day" event, then that will not satisfy the state template, and therefore my binary sensor will turn off, even though it's still within the window of the trash day event. Am I missing something obvious?

still plank
#

i am trying to save a snapshot:

#

service: camera.snapshot data: filename: "/tmp/snapshot_{{ entity_id.name }}.jpg" target: entity_id: camera.gate_high

#

but i get Error rendering data template: UndefinedError: 'entity_id' is undefined

#

but the docs say "Template of a Filename. Variable is entity_id."

neon bolt
#

Hi, I have a setup already working in Home Assistant with 1 wall switch, would like to add a 2nd dumb switch to make it work as a 2 way, I found the trigger.to_state,state ... but unsure it'st the best way

orchid oxide
#

for a dumb switch you can just make a helper toggle

neon bolt
#

I will check that !

#

That's exactly what I need, thanks a lot !

ruby vault
#

Hi, I am trying to make a template trigger, that will trigger when any of my zwave 'node_status' sensors go dead.

{{ integration_entities('zwave_js') | unique | list is search('node_status') }}

Is where I am starting, but that node_status returns a bool.. I need a list of the actual entity

inner mesa
#

|select('contains', 'node_status')

ruby vault
#

yeah, nice shout. I just found select also

{{ integration_entities('zwave_js') | unique | list | select('contains', 'node_status') | list | select('is_state', 'awake') | list }}

#

and for the main event

{{ integration_entities('zwave_js') | unique | list | select('contains', 'node_status') | list | select('is_state', 'dead') | list | length > 0}}

inner mesa
#

You can get rid of the first two |list

ruby vault
#

ah, ok. Yep

#

ok, thank you!

orchid oxide
#

so it appears to me that macros cant use variables from within the automation. i suppose i could specify in the macro to provide them, is there any way for it to reference those variables otherwise?

inner mesa
#

Do you have an example?

orchid oxide
#

which isnt inherently a problem, just if i have a lot of variables

inner mesa
#

I'm not really following. In any case, you have transition in one place and transitions in another

orchid oxide
#

im not seeing it

inner mesa
#

I see now. Did you change one of them?

#

I would believe that the variable scope of a macro is separate from the one in which it's used

#

You can pass a dict...

#

Or maybe a namespace works?

orchid oxide
inner mesa
#

namespace doesn't work, either. I suspect it's just the way the scope of macros works

#

Itโ€™s important to know that imports are cached and imported templates donโ€™t have access to the current template variables, just the globals by default. For more details about context behavior of imports and includes, see Import Context Behavior.

#

eureka!

#
{% set ns=namespace(foo='blah') %}
{% from 'test.jinja' import groot with context %}
{{ groot() }}

->

I am Groot - blah
#

test.jinja:

{% macro groot() %}
  {{ "I am Groot - " ~ ns.foo }}
{% endmacro %}
#

that should help you

orchid oxide
#

interesting! that solves my woes, tysm

orchid oxide
#

do script variables and/or macros reevaluate when a state changes? ie, can they be used in the in a condition of while or until of a for each

#

for context, i use the following in a few difference places, so id like to just define it once if possible:

plain magnetBOT
digital harness
#

Good Morning. i have a gas sensor template for a sensor.yaml file. But i dont have a sensor.yaml file. How should that look, when i want to put it into my conifguration.yaml ?

#
  • platform: template
    ย  sensors:
    ย  ย  gasverbrauch:
    ย  ย  ย  value_template: ย >
    ย  ย  ย  ย  ย  {% if states('sensor.gasverbrauch_esp') | float == 0 %}
    ย  ย  ย  ย  ย  ย  {{ states('sensor.gasverbrauch') }}
    ย  ย  ย  ย  ย  {% else %}
    ย  ย  ย  ย  ย  ย  {{ states('sensor.gasverbrauch_esp') | float }}
    ย  ย  ย  ย  ย  {% endif %}
    ย  ย  ย  unit_of_measurement: mยณ
    ย  ย  ย  device_class: gas
    ย  ย  ย  attribute_templates:
    ย  ย  ย  ย  state_class: total_increasing
mental violet
#

Hi, I created a trigger based sensor which should save my finances. The sensor has 12 attributes for the 12 months. But since last month the values doesnt get saved anymore. When I restart home assistant a very big chunk just gets lost. I paste here the sensor with just the first month and the sensors which should create a nice graph based on the finance list sensor.

obtuse zephyr
#

You'll have to paste that on dpaste.org or something else

mental violet
obtuse zephyr
#

What does your home-assistant.log say during start up? And what do you mean by a very big chunk just gets lost?

mental violet
#

I dont have screenshots sadly. But I have a graph that shows what I have spend this month and another graph how much money I got this month. When I look at the data it all is normal and all states are correct. When I restart HA then a lot (for me random chunks) of data in the past gets lost.

obtuse zephyr
#

So, is the sensor itself right and the front-end is wrong?

mental violet
#

in the present yes. But after a restart backend data is lost as well. In history tab there is shown: no data for this period

obtuse zephyr
#

Some of your sensor.legro_ and sensor.miri_ entities are not numbers. You need to track down what's wrong with those

#

I suppose if those are also templates though, it could just be a temporary issue

mental violet
plain magnetBOT
marble jackal
#

It's probably too big, I guess you have a warning in your log about an attribute exceeding xxx bytes and therefore not being saved

mental violet
#

I went through all of the errors with bytes and the only error I get is this:

``` but this is from the HA app
#

but in general I have these errors alot (70 times):

mental violet
mental violet
#

do I have to create then a sensor for each month? would that evade the problem with to many bytes ?

native prairie
#
  • platform: template
    sensors:
    current_rain_per_square:
    friendly_name: 'Tomaten Regen'
    value_template: {{ states('sensor.openweathermap_forecast_precipitation') | float 0.1 }}
    unit_of_measurement: 'mm'

Hey guys,
Im trying to create a new sensor by multiplying the value of the existing sensor, but I keep getting these invalid key errors.
Does anybody know why and how I can fix it?

invalid key: "{'states.sensor.openweathermap_forecast_precipitation | float 0.1': None}" in "/config/sensor.yaml", line 7, column 0

#

copied wrong. I didnt forgot to multiply
{{ states('sensor.openweathermap_forecast_precipitation') | float * 0.1 }}

obtuse zephyr
#

Surround it in "s

inner mesa
#

and please format your code

plain magnetBOT
#

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

lunar fjord
#
- sensor:
  - name: Time
    unique_id: time_am_pm
    state: "{{ now().strftime('%-I:%M %p') }}"
  - name: Date
    unique_id: date_month_day_year
    state: "{{ now().strftime('%B %d, %&') }}"``` - Should this work for date when i did and restarted the yaml it was blank.
inner mesa
#

...

lunar fjord
#

I screwed up it looks like ๐Ÿ™‚

#

with the %&

#

Was supposed to be %Y ๐Ÿ™‚

pastel moon
mighty ledge
plain magnetBOT
lean yacht
pastel moon
plain magnetBOT
mighty ledge
#

@lean yacht read the first pin in the channel

lament dust
#

Is there a way to filter entities by which have a speaker?

#

For instance I want to do something like this:

{{ (area_entities('Some Room') | selectattr('device_class', 'eq', 'speaker') | list)[0] }}
#

Then want to play some TTS using it

inner mesa
#

is that a real device_class?

#

if so, you just need to add |expand after area_entities()

lament dust
#

apparently not, UndefinedError: 'homeassistant.helpers.template.TemplateState object' has no attribute 'device_class'

#

Is there a better way to filter by speaker or media player?

inner mesa
#

media_player is a domain

lament dust
#

hmm okay perhaps I can filter on entity name if I name them all so they end in _speaker?

inner mesa
#

{{ states.media_player|map(attribute='entity_id')|list|first }}

#

no idea

#

you need to figure out what constitutes a speak for you

lament dust
#

Well for me its all just unifi cameras with speakers/mics

#

I just need to do it by area

inner mesa
#

by that I mean, something that you can actually filter on

lament dust
#

Basically trying to do when a person is detected speak in said room but wanted to avoid using a choose

inner mesa
#

I have found no such thing, other than media_player entities typically have speakers

lament dust
#

hmm okay

#

yeah I dont really get why I cant do it by device class as I can see it in the states list

obtuse zephyr
#

Try adding selectattr('device_class', 'defined') before the other speaker filter

inner mesa
#

you can, but I see no evidence that there's a "speaker" device class

#

maybe there is and I just don't have any

lament dust
#

hmm no that didnt work

inner mesa
#

you wanted selectattr('attributes.device_class', 'defined')

lament dust
#

hmm I dont think that worked either

#

the other way was better

#
UndefinedError: 'str object' has no attribute 'attributes'
#

This works:

 area_entities('greatroom') | 
selectattr('device_class', 'defined') |
list

But gives back an empty array

#

so I feel like its missing something let me double check the room name is right

obtuse zephyr
#

You still need expand

lament dust
#

Like this:

{{
 area_entities('entryway') | 
 expand |
 selectattr('device_class', 'defined') |
 list
}}
obtuse zephyr
#

{{ area_entities('entryway') | expand | selectattr('attributes.device_class', 'defined') | selectattr('attributes.device_class', 'eq', 'speaker') | list }}

lament dust
#

I double checked the area and there is for sure a device in it

#

Seems like that worked

#

Can you set variables in an automation? Just want to store this in a variable temporarily to make things easier to read

obtuse zephyr
lament dust
#

Can I set it part way through an automation though?

#

Like I think Ive seen elsewhere people do a set variable

obtuse zephyr
#

You can set variables within a sequence as well, yes

#

same syntax

lament dust
#

oh okay cool

obtuse zephyr
#

There's an example

lament dust
#

thanks

hollow root
#

lol jfc

#

Ok trying to figure out what unit of measurement and/ or state class to use for this template sensor. Goal of the sensor is to parse out hvac action from my nest thermostat and save it in a way that I can plot it along with my temp sensors in grafana

http://pastie.org/p/4O1CbO0sgSH1g3WuIcMFJf

inner mesa
#

ok

#

no need to repost it without formatting

novel vortex
#

Can someone please paste a template/way for "sunrise effect" by controlling brightness of a smart bulb, from 1%-100% in 1hr time span?

Grateful

hollow root
#

yeah sorry I thought I saw something about enter three tildes and ctrl enter and all that but can't find now

marble jackal
#

Unit of measurement is for sensors with a numeric state

#

For this I would use a binary sensor

inner mesa
#

and the logic could be simplified

hollow root
#

yes I may have an extra case in there for 'off' that is not needed but I think I was seeing some error when hvac was set to off and it successfully evaluating the other cases

marble jackal
#
  - binary_sensor:
      - name: "Addition HVAC Running"
        state: "{{ is_state_attr('climate.addition', 'hvac_action', ['cooling', 'heating']) }}"
        unique_id: "addition_hvac_running"
hollow root
#

thank you

#

ok thanks again, i'm up and running with that (and another HVAC) as binary sensors. For some reason, I was convinced that they needed a unit of measurement to show up in influx db/ grafana

hearty verge
#

Is there a way to print the type of a "thing" ... i'm struggling to get relative_time to work correctly for looking up how far in the future is the next calendar "thing"

#

My start time looks like 2023-05-16 07:30:00 so I try to get a timezone in there by tossing it through: as_datetime(states.calendar.test.attributes.start_time).isoformat()

#

And then I wanted to run the relative time on it and i just get the same value: ISO Format: 2023-05-16T07:30:00

#

Am i missing something here?

inner mesa
#

the standard "relative_time" only works for things in past

inner vault
#

Is there a way to get whether an entity is exposed to assist? (Something that would be along the line of state_attr(entity, 'is_exposed') ?

marble jackal
#

not that I'm aware of

mighty ledge
#

voice assistants don't support weather entities

#

so, even if you could, it wouldn't do anything

#

@inner vault ^

inner vault
#

Good to know on the weather entity as I did not know that, but you probably misread whether as weather ๐Ÿ˜„

mighty ledge
#

lol

#

ok

#

So as the fes said, no that's not possible

#

Sorry!

marble jackal
#

I guess you can get results of weather entities using custom intents

mighty ledge
#

but TBH, there's no point when voice assistants do weather naturally

silent vector
#

Is it possible to do {{ listvar is regex("\d{3}$") }} to check each item in a list and be true if either matches the regex? I keep getting false

- foo001
- foo002
- foo003
obtuse zephyr
silent vector
#

Result if any match.

#

In this instance if 1 has it they all do.

obtuse zephyr
#
{{ ['foo001','foo002','foo003'] | map('regex_search','\d{3}$') | select | list | count > 0 }}

Should do that

mighty ledge
silent vector
#

Perfect thank you guys

mighty ledge
#

or

#

{{ listvar | map('regex', "\d{3}$") | select('true') | list }} if you're going to set that to a variable and do {% if x %}

obtuse zephyr
silent vector
#

Yep that's what I just noticed

mighty ledge
#

Unless you're doing this for HA, then you need to use regex_search, if you're doing this at your job (IIRC ansible), then regex exists

silent vector
#

You're right this is for Ansible

mighty ledge
#

Ok then, you can use regex

silent vector
#

I guess my local Ansible doesn't have the filter.

#

Need to check why lol

mighty ledge
#

ah, it's only a test

#

so

#
{{ listvar | select('regex', "\d{3}$") | list }}
#

FYI you should learn the differences between a test, filter, and function and then use the ansible docs

#

iv'e never used ansible, but I can read docs ๐Ÿ˜‰

silent vector
#

Lol I have been reading them. It's crazy because the list is empty when I try that. It doesn't make any sense. Going to keep messing around with it.

#

These code snippets are still helpful for how to approach this

silent vector
#

Is there a way to remove a key and it's associated value from a json array with Jinja?
So "foo": "bar" would be removed simply by searching to remove foo

#

And even better providing a list of keys to remove the kvp from the array

inner mesa
#

You cannot modify a dict once created, but you can create a new one based on a filtered version of the original

silent vector
#

How would I do that?

mighty ledge
#

you can use xxx.pop('key')

#

to remove

#

to add, it's a whole ordeal and I've shared the code with you in the past

#

although pop might be blocked

silent vector
#

Yep I remember that, do you have that url? I may need to actually try this lol. I need 99% of a dict to be reused but change some key values to different values.

mighty ledge
#

nope, you can't pop

#

it's blocked

silent vector
#

Yeah I didn't think so.

mighty ledge
#

the method required depends on your keys

inner mesa
#

Example of replacing a key:

{% set month = 'mai' %}
{% set x = 110 %}
{% set paid = {'januar': 85,'februar': 85,'mรคrz': 85,'april': 85,'mai': 0,'juni': 0,'juli': 0,'august': 0,'september': 0,'oktober': 85,'november': 85,'dezember': 85} %}
{{ dict(paid.items() | rejectattr('0', 'eq', month) | list, **{ month: x }) }}
mighty ledge
#

That method will only work if you don't have spaces in your keys

silent vector
#

No spaces.

mighty ledge
#

then you can use that

#

you also can't have special characters

#

so a-zA-Z0-9, starting with a letter

#

if your keys start with numbers, you have to use from_keys

#

or fromkeys

silent vector
#

Interesting ok let me try this example.

inner mesa
#

I saved that a long time ago because it would take me too long to try to build it from scratch ๐Ÿ™‚

silent vector
#

I'm saving it too lol

amber hull
#

I have a template that converted degrees from a NOAA buoy to direction. It worked fine until recently. friendly_name: '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 = state_attr('sensor.buoy', 'MWD')|float (0) %} {{ direction[((degree+11.25)/22.5)|int] }}

#

The degrees still show in my sensor.buoy. Any ideas on what changed that is causing this to fail?

#

Also in the template editor it shows correctly. The degrees show as 189. The sensor shows N, the template editor shows S.

inner mesa
#

fail how?

#

explosion?

amber hull
#

It shows the wrong value. The degree is 189. This converts to S. It shows south

#

If I past the template into the editor. It shows south.

#

wind direction N for the sensor created by the template.

#

Value in Editor is now SSW as the degree has changed from before.

#

MWD: 193

#

Not sure how this is happening. Saw another user questioning his senor in the forums and this caused me to look at mine.

inner mesa
#

what does the template editor say that it's listening for changes for?

amber hull
#

Entity: sensor.buoy

#

The template editor has the correct value

inner mesa
#

you can convert that sensor to the modern format and add a state trigger for it, but I don't see why you should have to

amber hull
#

I have two Identical sensors, one works and the other doesn't. What is the modern format I should use?

lofty mason
#

If I was debugging this I would start by replacing with something like this, and see what it says:

    friendly_name: '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 = state_attr('sensor.buoy', 'MWD')|float (0) %}
      {{ degree }}

If that works, then just slowly build back up to what you had:

      {{ ((degree+11.25)/22.5) }} 
      {{ ((degree+11.25)/22.5)|int }} 
...
amber hull
#

Where am I debugging?

orchid oxide
amber hull
#

Again, I'm not sure what I am debugging? The code above works in the template editor. It also works correctly for my sensor.weather. It just recently stopped working for my sensor.buoy. All identical code

lofty mason
#

I don't know what you want me to say, obviously the sensor is not working, so I suggested trying to break it down in steps to see what exact part of the template is not working in the sensor.

amber hull
#

I understand this, but where do I break it down? In the yaml file?

lofty mason
#

yes literally just replace your existing template sensor with what I posted, and reboot (or reload yaml). When it comes back, see what it says:

    value_template: >
      {% set direction = ['N','NNE','NE','ENE','E','ESE','SE','SSE','S','SSW','SW','WSW','W','WNW','NW','NNW','N'] %}
      {% set degree = state_attr('sensor.buoy', 'MWD')|float (0) %}
      {{ degree }}

If the sensor value shows "0", than you know something is not working in the state_attr correctly.

#

at least this gives some idea of where things are breaking down for further investigation

amber hull
#

The above pasted in my template editor shows 0

#

Just looked at the buoy and the buoy did not send the direction for some reason. I'll try again after it updates

empty furnace
#

I am having a similar issue to what @amber hull posted above. My sensor template looks like:
value_template: > {% set direction = ['N','NNE','NE','ENE','E','ESE','SE','SSE','S','SSW','SW','WSW','W','WNW','NW','NNW','N'] %} {% set degree = state_attr('sensor.bibuoy', 'MWD')|float %} {{ direction[((degree+11.25)/22.5)|int] }}
This returns "unknown". But if I place this same code into the developer tools template editor, it return "SW" as it should.
I tried the following, and it returns "218" so the sensor is working, it is the template that doesn't seem to fetch the value from the string array.
value_template: > {% set direction = ['N','NNE','NE','ENE','E','ESE','SE','SSE','S','SSW','SW','WSW','W','WNW','NW','NNW','N'] %} {% set degree = state_attr('sensor.bibuoy', 'MWD')|float %} {{ degree }}
I tried a few more things in the sensor template to try and debug the issue. In that last line, I did {{ direction[3] }} and it also returned "unknown" instead of the expected "ENE". I also tried having the direction array store integers in each item instead of strings, and that worked. But of course it is the strings that I actually want.
I have several sensors just like this and they are all acting the same way. They had been fine for half a year but just started acting like this recently. And no changes have been made to any of the code. Not sure what other debugging steps to take.

lofty mason
# empty furnace I am having a similar issue to what <@576690342707986434> posted above. My senso...

What does 'acting like this recently' mean. It broke on a HA update? Or it just stopped working unrelated to any updates?

I just tested something similar on 2023.5.3 and it is working as expected, for me at least:

  - platform: template
    sensors:
      wind_1:
        value_template: >
          {% set direction = ['N','NNE','NE','ENE','E','ESE','SE','SSE','S','SSW','SW','WSW','W','WNW','NW','NNW','N'] %}
          {% set degree = states('input_number.direction')|float (0) %}
          {{ direction[((degree+11.25)/22.5)|int] }}
stuck dock
#

I was trying to create some rest sensors but got the value error ```yaml

  • platform: rest
    scan_interval: 60
    name: '5G Temp'
    resource: http://192.168.12.123/status-data.jsx
    method: POST
    payload: _http_id=dfsdnfsdnfsdklfnds
    headers:
    Content-Type: 'text/plain;charset=UTF-8'
    Authorization: 'dfnsdjkfnsd=='
    User-Agent: Home Assistant
    value_template: '{{ value | regex_findall_index("eth2: 5G - (\d+)") | int }}'
    state_class: measurement
    device_class: temperature
    unit_of_measurement: 'ยฐC'
#

error in developer tools > templates UndefinedError: 'value' is undefined

inner mesa
#

Well, it is undefined there

#

Where did you expect it to come from?

stuck dock
#

from the router whose ip is 192.168.12.123

inner mesa
#

Not in devtools -> Templates

stuck dock
#

I have added it in configuration.yaml but no sensors created

stuck dock
#

how to fix it?

fickle kettle
#

What is the response format of the url? can you see HA hitting it?

stuck dock
#

now sensors have created but value unknown still

stuck dock
fickle kettle
#

curl or similar, then see what comes back. you probably need to pick the value out of the json

stuck dock
fickle kettle
#

use curl. in browser you're missing authorization.

#

if you don't get back something useful from curl, HA isn't going to fare any better

stuck dock
#

should I try in ssh?

fickle kettle
#

do it from your workstation if you like.

curl -v \
  -H "Content-Type: text/plain;charset=UTF-8" \
  -H "Authorization: dfnsdjkfnsd==" \
  http://192.168.12.123/status-data.jsx

Or something like that

#

use ssh if that's easier, or you don't have curl on your local

#

Your auth value looks a bit suspicious too

stuck dock
plain magnetBOT
stuck dock
#

this is from ubuntu 20.04 wsl2

fickle kettle
#

Your authz is no good. 401 Unauthorized

stuck dock
#

I think word basic is missing

fickle kettle
#

yeah

#

get it working in curl first, then move up to template

grand quarry
#

What provides http://192.168.12.123/status-data.jsx?

fickle kettle
#

afk

plain magnetBOT
stuck dock
stuck dock
#

working fine now

fickle kettle
#

๐Ÿ‘

digital verge
#

I need help with a template condition
need to check script.clean_upstairs is not running, and has not run since midnight (I feel those 2 statements may be redundant?)
I tried using Chat-gpt for the first time (for the lolz) and it gave me this non-working code:

{{ not is_state("script.clean_upstairs", "running") and (as_timestamp(now()) | int - as_timestamp(now().strftime("%Y-%m-%d")) | int) == 0 }}
obtuse zephyr
#
{{ is_state('script.clean_upstairs', 'off') and state_attr('script.clean_upstairs', 'last_triggered') < today_at('0:00') }}

Should work

digital verge
#

condition passes~!

#

are the 2 statements redundant?

obtuse zephyr
#

Left side checks that it's not running and right side checks that it was last triggered before midnight

digital verge
#

if it was running now, would it not show as "has run since midnight?"

obtuse zephyr
#

state is on when it's running

#

ah I understand what you're saying

#

That's true, last triggered is updated immediately

digital verge
#

thought so. not after completion.

obtuse zephyr
#

Yeah, you could nuke the left side of the and then

digital verge
#

thanks.

#

{{ state_attr('script.clean_upstairs', 'last_triggered') < today_at('0:00') and is_state("vacuum.bitch_vac", "docked") }}

empty furnace
# lofty mason What does 'acting like this recently' mean. It broke on a HA update? Or it just ...

Thanks Tim. Interestingly, mine looked like yours (at least the template), but yours worked. See mine below. So then I decided to remove other sensor options one by one and turns out that the culprit was the line unit_of_measurement: "". Removed that single line and all my sensors are fine now. Weird that this has worked for a long time but a recent update seems to not like that line. Anyway, back in business so thank you again.
`

  • platform: template
    sensors:
    bi_wave_direction:
    friendly_name: "Mean Wave Direction"
    unique_id: "bi_wave_direction"
    icon_template: mdi:waves-arrow-right
    unit_of_measurement: ""
    value_template: >-
    {% set direction = ['N','NNE','NE','ENE','E','ESE','SE','SSE','S','SSW','SW','WSW','W','WNW','NW','NNW','N'] %}
    {% set degree = state_attr('sensor.bibuoy', 'MWD')|float %}
    {{ direction[((degree+11.25)/22.5)|int] }}
    `
mighty ledge
pastel moon
#

Trying again. I seek to simplify this if possible. https://paste.debian.net/hidden/df1825a8/ It is one of four sections that will (or should) update input helpers with a timestamp in a rolling manner. I guess I could use input_datetime, but that won't simplify anything really. Can this be done smarter?

mighty ledge
#

smarter, yes by using datetimes. Optimized? No

#

without getting into heavy template*

pastel moon
#

Shouldn't this work according to the docs? If keeping "initial" it does not...? This is from my configurations.yaml

input_datetime:                                                              
  morning:                                                        
    name: Morning                                       
    has_date: true                                      
    has_time: true
    initial "05:00:00"
inner mesa
#

you didn't provide a date

pastel moon
#

ouch!

#

So true, will try that, thanks

#

Worked a treat! ๐Ÿ™‚

hearty verge
#

How can i find the domain of a given sensor via templates?

inner mesa
#

sensor itself is a domain

hearty verge
#

oh!

#

๐Ÿ˜ฆ

mighty ledge
#

what are you really looking for?

#

integration?

dim roost
#

Is there a simple way to have a switch helper whose value is based on whether another switch's on or off button has been pressed?

#

Right now I have that as two automations but that seems... very clunky and wrong

inner mesa
#

the state of a template switch can be whatever you want

#

I'm not sure what you mean by "switch helper"

peak juniper
#

Any way to count how many of a particular sensor have the same state_attribute? For example, I pull in my wine data from cellar tracker and want to make a template sensor that will count how many bottles have the country argentina, france, portugal, etc.

#

but would prefer not to define the countries as they are dynamic and would hate to think I might have missed one out

#

these are the attributes of one of my sensors:

count: 1
value_total: 21.3744
value_avg: 21.3744
%: 1
Wine Name: Tulloch Shiraz JYT Selection
Vintage: 2016
Colour: Red
Country: Australia
Best after: 2022
Best before: 2025
unit_of_measurement: bottles
icon: mdi:bottle-wine
friendly_name: cellar_tracker.tulloch shiraz jyt selection_2016
dim roost
#

as in, defined on the Helper page as type "switch"

peak juniper
#

want to collect all my sensor.cellar_tracker_* sensors and categorise them by country

#

bonus points if I can just do this easily enough in custom:flex-table-card which I can't seem to see at the moment

peak juniper
dim roost
inner mesa
dim roost
#

oh, sorry, I mean binary_sensor.

peak juniper
#

You can map a switch to states, so if a state is on, the switch will say it's on, then you can define an action which toggles another action (like switching it off), but it can sometimes be slow

#

I use it to convert media players to easy to use on/off toggles

dim roost
#

basically: when zha switch fires "on", set binary sensor to true; when zha switch fires "off", set it to false.

#

but the switch is only a device, not an entity

inner mesa
#

that sounds like a template binary_sensor with a trigger

dense swan
#

I am trying to lump some devices together in a template as a light but it isn't working. Any thoughts?

  - platform: template
    lights:
      esphome_status_leds:
        value_template: >-
          {{ states.light  | selectattr('entity_id', 'search', '_status_led$')  | map(attribute='entity_id') | list   }
inner mesa
#

for one, you're missing the trailing }

dense swan
#

Ugh

inner mesa
#

but please do elaborate on "isn't working"

#

in every report in the future

dense swan
#

It's there in the config.

#

Well it isn't showing up in the entities list

#

I know the code template works as it returns the list of lights I'd like to control all at once

#

Ahh I know the issue

dim roost
# inner mesa that sounds like a template binary_sensor with a trigger

I tried this, but 'trigger' is apparently undefined according to the dev tools:

template:
  - trigger:
    - device_id: 3a8fdb75a216f23f8431e58838bc73b2
      domain: zha
      platform: device
      type: remote_button_short_press
   binary_sensor:
     - name: test
       state: '{{ trigger.subtype == 'turn_on' }}'
haughty breach
#

You can't directly test trigger variable based templates in the Template editor tool, because the trigger variable is undefined.

dim roost
#

ah

#

not a fan of "reboot 1000 times to get it right"

haughty breach
#

You don't need to reboot even once, just set up the binary sensor, reload Template entities, then watch its state in the States tool when you press the button.

dim roost
#

Thanks! I'll try it when it's not 11:30pm

#

or not, got it

plain magnetBOT
peak juniper
#
        {{ states.sensor | select('search', 'cellar_tracker_') 
        | selectattr('colour', 'Red') | list | count }}

Template is returning TemplateRuntimeError: No test named 'Red'. Am I missing something?

plain magnetBOT
dim roost
#

Thanks @haughty breach

plain magnetBOT
dense swan
#

How do I use this? Getting an error about not in dict.

#

Error executing script. Error for call_service at pos 1: Error rendering data template: Result is not a Dictionary

inner mesa
peak juniper
#

thanks

amber hull
#

I used state_attr in templates to get an attribute of a sensor. I was told this is the old way of doing it. What is the correct way now? i.e value_template: "{{ state_attr('sensor.kohler_sensors', 'lube_oil_temperature') }}"

inner mesa
#

there's no better way

#

the "old" way would have been states.sensor.kohler_sensors.attributes.lube_oil_temperature

amber hull
#

So this is correct?

inner mesa
#

what you have is correct