#templates-archived

1 messages · Page 72 of 1

lethal locust
#

works 🙂 thanks again a lot

heavy minnow
#
sequence:
  - service: mqtt.publish
    data:
      qos: 0
      retain: false
      topic: zigbee2mqtt/ir-remote_men-guest-room/set
      payload: >-
        {"ir_code_to_send":
        "BwUOCwYtApsEgAMBawHgAQNAE8APQAtAA0APwAfAC8APQAdAA0AXQAPgDwtAG+AvA+APU0AXQAPgD1dAG+ADA+AHJ0AbQBNAB+ADA0AT4FsDAI/hAnfAC8AH4AN/QBNAn+ADEwObBC0C"}
mode: single
icon: mdi:air-conditioner```
#

sorry, I didn't turn off the ping

#

The script by itself works fine though

inner mesa
#

You have () in there

heavy minnow
#

in the name only, but in the entity id it's script.men_guest_room_ac_on16

#

would it still be a problem?

inner mesa
#

I don't know what the alias: line does there, and you're only sharing part of your script defintion

#

in any case, if the script shows up in devtools -> States, I don't see why the service call would fail

heavy minnow
#

I've removed the (16)

sequence:
  - service: mqtt.publish
    data:
      qos: 0
      retain: false
      topic: zigbee2mqtt/ir-remote_men-guest-room/set
      payload: >-
        {"ir_code_to_send":
        "BwUOCwYtApsEgAMBawHgAQNAE8APQAtAA0APwAfAC8APQAdAA0AXQAPgDwtAG+AvA+APU0AXQAPgD1dAG+ADA+AHJ0AbQBNAB+ADA0AT4FsDAI/hAnfAC8AH4AN/QBNAn+ADEwObBC0C"}
mode: single
icon: mdi:air-conditioner
#

and also the entity_id men_guest_room_ac_on

#

still same error

inner mesa
#

switch.turn_on is nowhere there, which suggests that something is stale

heavy minnow
#

where should I include the switch.turn_on?

inner mesa
#

;shug:

#

just reading your error message

heavy minnow
#

literally the same code for the living room is working just fine

  - platform: template
    switches:
      living_room_ac_switch:
        value_template: "{{ states('sensor.living_room_ac_energy_meter_current') | float > 0.150 }}"
        turn_on:
          service: script.living_room_ac_on20
        turn_off:
          service: script.living_room_ac_off
        friendly_name: "Living Room AC"
        icon_template: >-
          {% if states('sensor.living_room_ac_energy_meter_current') | float > 0.150 %}
            mdi:air-conditioner
          {% else %}
            mdi:fan-off
          {% endif %}```
#

and the script code is literally the same

inner mesa
#

🤷

heavy minnow
# heavy minnow and the script code is literally the same
sequence:
  - service: mqtt.publish
    data:
      qos: 0
      retain: false
      topic: zigbee2mqtt/ir-remote_living-room/set
      payload: >-
        {"ir_code_to_send":
        "C1ojiRGdAnAGnQIdAoADQAvgAwPAF0AHQBdAB+AbA0ArQAPgCyvAF8AHQCPACwNbTp0CwAtAF0AD4BcP4AsjQBPgIwPAY0AHAcic4XEXQH9AA8C7wAtBF8AT4D8HwFvAB+APVwdwBp0CcAadAg=="}
mode: single
icon: mdi:air-conditioner
#

so what do I do now

balmy wedge
#

Hi everyone. I'm trying to have a default state of 0 when my light is off, with {{ state_attr('light.kitchen_strip_controller', 'brightness')|default(0) }} but that still returns None. I tried passing | int but that broke my template completely. Can I cast None to 0 without building a whole if structure?

balmy wedge
#

Ahhhh!

#

Thank you so much.

mighty ledge
#

or

#

or 0

balmy wedge
#

I think int(0) is more readable

heavy minnow
# inner mesa 🤷

I fixed it, even though I have the entity id as "men_guest_room_ac_on16" in the UI.. in the scripts.yaml it was "men_guest_room_ac_on20ice" and was never changed for some reason

marble jackal
#

@balmy wedge | default(0, true) would also have worked, that applies the default to input which is falesly (false, [], {}, 0, "" and none) (and maybe another one I forgot)

slate fossil
#

Is there a way to get a template to return the last value before a sensor went unavailable? Use case: my laptop reports battery percentage via HASS.Agent but when it goes to sleep the sensor is unavailable.

inner mesa
#

Create a trigger-based template sensor for it and use from_state

#

Point is, you need to capture it when it happens and store it

visual matrix
#

Can somebody help me convert now().isoformat() into something similar to relative_time? ex: {% set time = now().isoformat() %} {{ relative_time(time) }} To get it showing ex: x seconds/mins ago

marble jackal
#

now() is the current time, that will be 0 seconds ago

marsh cairn
plain magnetBOT
#

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

fickle sand
#

@stark vale The syntax of the yaml keys is incorrect. First remove integration, than rewrite to the following:

  sensor:
    - platform: integration
      name: energy_consumed_from_grid
      source: sensor.power_consumed_from_grid
      unit_time: h
      unit_prefix: k
      method: left
      round: 2
stark vale
#

Oh I thought that the new template format also applied to everything else

but even using the other format it doesn't work

fickle sand
#

The logs could tell you why

stark vale
#

I cant find anything in the logs regarding integration

marble jackal
#

do you have another sensor: section below this one in your configuration.yaml?

#

@mighty ledge shouldn't this both return 23 hours?

{% set start = '2024-03-31' | as_datetime | as_local %}
{% set end = '2024-04-01' | as_datetime | as_local %}
{{ start }} || {{ end }}

{{ (end-start).total_seconds() / 3600 }}
{{ (end.astimezone(utcnow().tzinfo)-start.astimezone(utcnow().tzinfo)).total_seconds() / 3600 }}

Result:

2024-03-31 00:00:00+01:00 || 2024-04-01 00:00:00+02:00

24.0
23.0
#

does it only look at the times when subtraction two datetimes, and not at the timezone change?

mighty ledge
#

I just woke up, first thought is to check dst

marble jackal
#

yes, it's because of DST

#

and good morning

#

but I would expect it would take that into account

stark vale
silent vector
#

I forget the most efficient way to see if the difference between 2 time stamps is < x seconds.

That won't run into issues with 12am or dst

marble jackal
#

2 timestamps? those are already in seconds

#

{{ timestamp1 - timestamp2 < x }}

#

or do you mean 2 datetime objects?

#

{{ datetime1 - datetime2 < timedelta(seconds=x) }}

silent vector
#

Yeah I was trying

{{ as_timestamp(humidity_automation_memory['humidity_automation_action_time']) - as_timestamp(states.sensor.hvac_operating_mode_text.last_changed) }}

Where {{ humidity_automation_memory['humidity_automation_action_time'] }}
Is 2024-04-02 00:57:02.767431-04:00

and last changed of the sensor is
2024-04-02 10:49:00.567106+00:00

marble jackal
#

@mighty ledge to come back to my earlier question/comment

#

Isn't this a bit strange?

marble jackal
#

start1 == start2 and end1 == end2 but the results are different

silent vector
mighty ledge
# marble jackal yes, it's because of DST

The transition across dst is really fucked. If you do the calc with dst in the future the result is different than if you did it with dst in the past. Also when converting to utc, you need to add or subtract the dst timedelta if you’re crossing the line depending on your past/present viewpoint

marble jackal
#

everything is in the past in my screenshot above

#

I'm looking into this because someone wanted to use my macro to calculate the average energy price of the whole day, and ran into an error because his input said he wanted to use the data of 24 hours, but there were only 23 prices on that day (as one hour was missing because of DST). So I wanted to use this to caculate the number of hours in the data

mighty ledge
#

Right, so what’s happening is your top calc isn’t subtracting the dst difference because you’re creating it in relation to the current dst offset

#

Which is the “oddness”

marble jackal
#

the bottom one is, the top one is correct, as there were actually 23 hours

mighty ledge
#

I’m not sure which one is correct

marble jackal
#

depends on your point of view maybe 😉

mighty ledge
#

Technically speaking, the dst day, there’s 2 hours in the day that are the exact same time but have an offset of 1 hour.

marble jackal
#

But if would have received 1 dollar for every 60 minutes of the day, I would have 23 dollar

mighty ledge
#

I.e. when you fall back, 2am occurs twice

silent vector
marble jackal
#

because the first timestamp is lower than the second

#

you are doing 2024-04-02 00:57:02.767431-04:00 - 2024-04-02 06:49:00.567106-04:00 which is a negative number of seconds

mighty ledge
#

Fes try to look at my dst calculation. It properly calculates the dst transition hour and minute. If you know that transition, you should be good to calculate any delta. Otherwise I’d just ignore the data that day and always use 24 hours

marble jackal
#

I will have a look

mighty ledge
#

There’s no simple way to calc it either.

#

In any language

marble jackal
#

anyway, I actually need the 23 here, so I converted it to UTC now to calculate the hours. It works now (in the past)

silent vector
marble jackal
#

nope

mighty ledge
#

Going in the future, you might have odd results. But if you’re always looking in the past you should be fine

marble jackal
mighty ledge
#

You’ll want to verify your calc next dst change too

#

You should get 25 hours.

#

But you won’t be able to check it until after it occurs. 🎉

silent vector
#

What's better between these 2 methods and using as_timestamp?

{{ (as_datetime(humidity_automation_memory['humidity_automation_action_time']) - (states.sensor.hvac_operating_mode_text.last_changed | as_local)).total_seconds() }}
{{ (humidity_automation_memory['humidity_automation_action_time'] | as_datetime | as_local - (states.sensor.hvac_operating_mode_text.last_changed) | as_local).total_seconds() }}
marble jackal
#

you don't need to convert last_changed to local time, and according to what you provided above, the other one is also already timezone aware, so as_local is not needed

silent vector
#

Is now() | string timezone aware? As that's how I set the value for humidity_automation_memory['humidity_automation_action_time']

mighty ledge
#

yes

#

however, it does not return what you think it does

#

well, nevermind. Seems __str__ was overriden in HA

#

but it is TZ aware.

#

when you use as_datetime on the result

#

as_local is only needed if the datetime string does not contain +xx:xx at the end of it.

lucid thicket
mighty ledge
#

take a look at the is_dst() method on datetimes and the dst_offset property

#

what's fucked about it is that when you create the time, depending on when you create it, it may or may not have the correct dst offset

#

it's super complex and hard to learn in 1 go

#

sorry, it's dst()

#

dst() is the timedelta

#

all func's available for datetime objects
['__add__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__radd__', '__reduce__', '__reduce_ex__', '__repr__', '__rsub__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', 'astimezone', 'combine', 'ctime', 'date', 'day', 'dst', 'fold', 'fromisocalendar', 'fromisoformat', 'fromordinal', 'fromtimestamp', 'hour', 'isocalendar', 'isoformat', 'isoweekday', 'max', 'microsecond', 'min', 'minute', 'month', 'now', 'replace', 'resolution', 'second', 'strftime', 'strptime', 'time', 'timestamp', 'timetuple', 'timetz', 'today', 'toordinal', 'tzinfo', 'tzname', 'utcfromtimestamp', 'utcnow', 'utcoffset', 'utctimetuple', 'weekday', 'year']

#

so, dst() is the only method

lucid thicket
#

Ah. So when you use an explicit time offset (-0500) instead of Americas/Chicago (for example) the dst() method will always return None

mighty ledge
#

yes, but if you're in -5 the offset will show none, but if you're in -4 the offset will show -1

#

and if you're in the future, in -4 and you create it, it will be the opposite

lucid thicket
#

Now you’ve lost me. Are you saying I can change my system clock or HA’s timezone and there is a scenario where this code will not return None?

{{ ('2024-03-11 00:00:00-05:00' | as_datetime).dst() }}
mighty ledge
#

I'm saying that dst() returns the value differently depending on WHEN you make the datetime object

#

if you make the datetime object during dst() for a time that's not in dst, you get odd results

#

if you did vice versa

lucid thicket
#

I can understand that if as_local is used. But I was in the process of convincing myself that there is a concept of what I’d call “dst-naive” and when a datetime object is created with an explicit time offset it will be created as dst-naive

mighty ledge
#

no, dst is just handled oddly

#

it's not something you can look ahead for either based on how the systems handle it under the hood

#

it's all in relation to your current viewpoint

#

e.g. here is something I use to translate tz between timezones that works regardless of dst

#
{%- macro _to_utc(dt) -%}
{%- set time = now() -%}
{%- set offset = time.utcoffset() - time.dst() if time.dst() else time.utcoffset() -%}
{{- dt.astimezone(utcnow().tzinfo) + offset -}}
{%- endmacro -%}
#
{%- macro _hms(t) %}
{%- set dststr = t.dst() | string if t.dst() is not none else "00:00:00" %}
{%- set h, m, s = dststr.split(':') | map('int') %}
{{- h * 60 * 60 + m * 60 + s }}
{%- endmacro %}

{%- macro _is_dst(t) %}
{{- _hms(t) | int != 0 }}
{%- endmacro %}

{%- macro _finddst(t, kwarg, rng) %}
{%- set ns = namespace(previous=_is_dst(t), found=none) %}
{%- for i in range(rng) %}
  {%- set ts = t + timedelta(**{kwarg:i}) %}
  {%- if ns.previous != _is_dst(ts) and ns.found is none %}
    {%- set ns.found = i %}
  {%- endif %}
{%- endfor %}
{{- ns.found }}
{%- endmacro %}

{# next daylight savings time #}
{%- macro next_dst() %}
{%- set t = now().replace(hour=0, minute=0, second=0, microsecond=0) %}
{%- set d = _finddst(t, 'days', 366) | int - 1 %}
{%- set h = _finddst(t + timedelta(days=d), 'hours', 25) | int - 1 %}
{%- set m = _finddst(t + timedelta(days=d, hours=h), 'minutes', 61) | int %}
{{- (t + timedelta(days=d, hours=h, minutes=m)).isoformat() }}
{%- endmacro%}
#

that finds dst

#

but if you extend it to find the dst AFTER the found one, it will be off by an hour without magic

#

same if you go backwards

lucid thicket
#

This is a good time for the melting crying emoji. I will study this and probably have more questions later. Thanks for this detail

bronze prawn
#
        [[[
          var assistbid = hass.states['group.assist_satellites'].attributes.entity_id
           .find((eid) => hass.states[eid].attributes.browser_id === localStorage.getItem("browser_mod-browser-id")) ?? "sensor.assistsat_viewlr";
          var mediadevice = hass.states[assistbid].attributes.mediaplayer_device;
          return `${mediadevice}`
        ]]]

You guys have been so helpful and I hate to bother but can someone tell me how to do what I have in JS but in Jinja? Particularly, I am not sure how I can access that localStorage.getItem

fickle sand
#

localStorage is an explicit JS method that has nothing similar in jinja. Jinja is only backend and has no way to interact and is not aware of the frontend

mighty ledge
#

alot of it is to get around jinja bullshit

#

in python, it would probably be shorter

#

and easier to understand

#

I already see how _hms could be changed to

{%- macro _hms(t) %}
{%- set td = t.dst() if t.dst() is not none else timedelta(seconds=0) %}
{{- td.total_seconds() }}
{%- endmacro %}
#

I probably made these a long ass time ago, they could use some love.

#

and I should probably remove the nested functions from the _is_dst macro to return a value or an empty string to make it faster

#

e.g.

{%- macro _is_dst(t) %}
{%- set td = t.dst() if t.dst() is not none else timedelta(seconds=0) %}
{{- '1' if td.total_seconds() != 0 else '' }}
{%- endmacro %}
#

basically, all it does is loop through the days, to get the day the change happens, then loops through the hours to get the hour it changes, then loops through the minutes

lucid thicket
#

I don’t think I’ll have an issue figuring out the code, it’s more the time it will take to understand why you have to use that logic to account for dst. That’s what I’ll have to play around with until I can really grasp it

mighty ledge
#

the why is because how it's stored under the hood

inner mesa
#

Perhaps we should just get rid of DST

#

Should be computer programmers leading the charge

marble jackal
#

It's beneficial for your health as well

bronze prawn
# fickle sand `localStorage` is an explicit JS method that has nothing similar in jinja. Jinja...

I was afraid that was the case. I'm needing to identify the browser id so that I can know what device I'm on. This is handled in JS nicely but now I need to do it in Jinja as well for some conditional displaying of cards. I'm trying to show when the associated media player is muted, the associated microphone is muted, and maybe one other thing.

Is there any way of storing these JS variable values that could also be accessible to Jinja if they can't be shared directly? Maybe I could use a helper for this but that probably won't scale well.

mighty ledge
#

or browsermod

#

but you already know those limitations

bronze prawn
#

Yep. I just had a suggestion in #frontend-archived that I'm going to try. Thanks for the info

silent vector
mighty ledge
#

you don't need anything for dst, that convo was for thefes's question

silent vector
#

Ah ok. Because the date time object already is already time zone aware so when there's 2 2ams it will be fine to calculate seconds?

mighty ledge
#

Well, I'm not sure you need it at all

#

are you going to be calculating over dst? and if yes, does it matter that it's an hour off those 2 days a year?

silent vector
#

Yeah it would throw off my logic as I care if total seconds between the two times is < 10 seconds

mighty ledge
#

na it won't, it'll trhow off the calc for 2 10 second spans over the year

#

you'll be fine

silent vector
#

Yeah the worst thing that would happen is if by chance the seconds are < 10 and dst mucks it up that a 30 minute delay occurs in my automation for changing the temperature that's all so I guess it's not very worth it to a bunch of extra code lol.

mighty ledge
#

that's assuming your data under the hood is local

silent vector
mighty ledge
#

yes

#

if it's utc under the hood, it doesn't matter

silent vector
#

Yeah the var I'm using the value when I create it is now() | string and it gets stored in a sensor attribute.

mighty ledge
#

use utcnow() then

silent vector
#

What's the difference between the 2?

mighty ledge
#

it's in utc, the other is local

silent vector
#

Essentially it's better to use when calculating seconds of DST is a concern?

mighty ledge
#

in general, it's better to use utc for time calc if you can

tired sandal
#

Quick sanity check - what am I doing wrong here?

{% set announcements = namespace(data=[]) %}
{% announcements.data.append({"foo" 1, "bar": 2}) %}

That raises TemplateSyntaxError: Encountered unknown tag 'announcements'. error

mighty ledge
#

{% set annoucements.data = announcements.data + [{'foo': 1, 'bar':2}] %}

tired sandal
#

TemplateRuntimeError: cannot assign attribute on non-namespace object

#
{% set announcements = namespace(data=[]) %}
{% set annoucements.data = announcements.data + [{'foo': 1, 'bar':2}] %}

{{ announcements }}
marble jackal
#

You have a typo

tired sandal
#

I do?

mighty ledge
#

announcements vs annoucements

tired sandal
#

oh, whoops

marble jackal
#

Yes

tired sandal
#

Whoops! Good catch

#

thanks!

#

Second question - I'm trying to extract all of this to a template sensor because I have logic that creates notifications from this info and logic that displays it on the dashboard. Right now it's basically duplicated in two places but it sure would be nice to centralize all of that in the template sensor and only have the logic once.

#

Thus far I've found that I have to set up some pretty funky data structures in my template sensor to get this to work at all

#

Also - can I use jinja macros in templates in HA?

mighty ledge
#

Yes you can create macros

#

you can create global macros too

silent vector
#

What's -7e-06

{% set utcz = '2024-04-02 16:29:16.416478+00:00' %}
{% set nowz = '2024-04-02 12:29:16.416485-04:00' %}

{{ ((utcz | as_datetime) - (nowz | as_datetime)).total_seconds()  }}

Where utcz is utcnow() and nowz is now()

tired sandal
silent vector
#

Ah ok

#

How did you figure that out

mighty ledge
#

it's scientific notation

#

-7e-06

#

-7 is the significant figure

plain magnetBOT
#

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

silent vector
#

Ah ok

tired sandal
#
{{ state_attr('announcements', 'data') }}

produces null

mighty ledge
#

-06 means 6 zeros before it and the decimal place

#

if it was -7e06 it would be -7000000

silent vector
#

Makes sense

mighty ledge
#

unless you reloaded

tired sandal
#

I did reload.

#

...should it be sensor.announcements?

mighty ledge
#

then go to developer tools -> states page

tired sandal
#

yeah it shows up there

mighty ledge
#

ok, then what's the entity_id?

tired sandal
#

sensor.announcements

mighty ledge
#

so then that's what you use as the first argument in state_attr

tired sandal
#

Ah. Gotcha!

#

Yep, that did - thanks!

#

Random question - is it possible to get all the attributes of a sensor as a dictionary?

mighty ledge
#

it is a dictionary

#

states.xxx.xxx.attributes

tired sandal
#

Gotcha, thanks!

wary shoal
#

Template in the template

plain magnetBOT
#

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

tacit sun
#

I did a quick reload and that fixed it.

sick ice
#

Hi, for templates using trigger.entity_id in an automation condition, is this a valid substitution, so that I can use multiple trigger entities?

    value_template: >-
      {{ as_timestamp(states.image.entrance_cam.last_changed) == as_timestamp(states.image.entrance_cam.last_updated) }}

    value_template: >-
      {{ as_timestamp(states.trigger.entity_id.last_changed) == as_timestamp(states.trigger.entity_id.last_updated) }}
inner mesa
#

What kind of trigger is this for?

sick ice
#
trigger:
  - platform: state
    entity_id:
      - image.entrance_cam
      - image.driveway_cam
#

Just trying to keep the unrelated lines down - I've got a bunch of cameras with trigger ID that feed in to a 'choose' action. Triggering from the camera motion is causing outdated image notifications. The idea here is that triggering from the image entity getting updated, then confirming that the triggering image has indeed been updated shoudl be more reliable.

inner mesa
#

So, then trigger.to_state.last_changed and so forth

sick ice
#

🙂

{{ as_timestamp(trigger.to_state.last_changed) == as_timestamp(trigger.to_state.last_updated) }}

This worked

#

awesome - it's much easier to come here and speedup the testing. Because you need real triggers, the testing process is a bit tedious when the syntax isn't quite right

lucid thicket
#

You can do that in order to use the template editor

sick ice
#

Wow, that is awesome!

floral shuttle
#

having a set of get_weather_forecasts but I cant find the reason why only the top trigger based templates works, and the ones below no longer work, and throw an error on the ' 'buienradar_forecast' is undefined'

#

silly thing is this started erroring after adding the top listed sensor.

#

testing the various hourly/daily in services works alright for the mentioned KNMI and Buienradar weather entities

floral shuttle
#

heck, I fluked on an additional action:.

mighty ledge
#

You're overwriting sensor

#

you also have an action in the sensor section

#

@floral shuttle ^

floral shuttle
#

thx! yes, as I already wrote, I missed an action there. Ive now changed it like this (and tbh, wsnt aware we could do it like this, first create several repsonse variables on the same trigger, and next crate templates on those:

mighty ledge
#

get_forecast accepts multiple entity_ids

#
     - service: weather.get_forecasts
        target:
          entity_id: 
          - weather.knmi
          - weather.buienradar
        data:
          type: daily
        response_variable: weather

then...

{{ weather['weather.knmi'].forecasts }}
{{ weather['weather.buienradar'].forecasts }}
#

@floral shuttle ^

floral shuttle
#

Even better, wasn’t sure there. Will adjust accordingly. Thx

floral shuttle
marble jackal
#

The multi entity support was the reason the other service call was depreciated after a month, and why it's needed to specify the entity used when using the service response

wicked parrot
#

I think I'm doing something wrong. Shouldn't this return false?

{{ ('sprout' and 'feed') in ( 'peachy feed x2' | lower ) }}

mighty ledge
#

no

#
{% set value = 'peachy feed x2' | lower %}
{{ 'sprout' in value and 'feed' in value }}
wicked parrot
#

Ok thank you.

marble jackal
#

{{ ('sprout' and 'feed') }} returns 'feed'. Not completely sure why though

inner mesa
#

I feel like there must be a less repetitive way, but I haven't found it yet

mighty ledge
#

python returns the last item in the ands if all results are "true" in python eyes

inner mesa
#

That's pretty weird

#

I would have expected True

marble jackal
#

and with or it returns the first one

mighty ledge
#

nope (to rob)

marble jackal
#

hehe

inner mesa
#

Both are Truthy

mighty ledge
#

and and or do not return booleans

#

they return the value that "sparked the statement to pass"

marble jackal
#

yeah that makes some sense

swift gull
#

Dunno where to post this but how do i convert the output from states.calendar.astrokalender.attributes.start_time to dd/mm/yy and hh:mm ? Output now is yy/mm/dd and hh:mm:ss

sonic nimbus
#

Hello why this template trigger wont trigger:

alias: "Harmony Set: TV"
platform: template
value_template: >-
  {{states('sensor.livingroom_tv_sbb') and not is_state('remote.harmony',
  'TV')}}
id: set-harmony-tv
#

this template value is True I checked, but it's not trigger in my automation?

inner mesa
#

I think it will always be true

#

Triggers happen on state transitions

marble jackal
marble jackal
swift gull
#

Doesnt work in this

marble jackal
#

you are not using it

swift gull
#

No this was the old one

#

I just tried with yours

inner mesa
#

Doesn't work 🤷

marble jackal
#
service: notify.mobile_app_pixel_7_pro
data:
  message: >-
    {{ state_attr('calendar.astrokalender', 'message') }} {{ as_datetime(state_attr('calendar.astrokalender', 'start_time')).strftime('%d/%m/%Y') }}
  title: Astrokalender
  data:
    ttl: 0
    priority: high
    notification_icon: mdi:star
    color: black
swift gull
#

😅

marble jackal
#

you should not use states.your.entity.attributes.some_attribute

swift gull
#

K thanks 😁

keen zealot
marble jackal
#

@keen zealot That example should be adjusted

#

The forecast attribute for weather entities was depreciated 7 months ago, and removed in this release, which is also mentioned in the backwards incompatible changes.

#

We will be able to help you better if you can show how you were using the forecast attribute

sonic sand
#
service: notify.home_assistant_group
data:
  title: 🧹 Vacuum Robot has finished and returned to base!
  message: >-
    🧹 🤖 Automation - Robot Vacuum is trapped or stuck in {{
    ( states('sensor.roborock_s8_pro_ultra_current_room') }} ! ⚠️.
    data:
      image: /local/tmp/snapshot_vacuum.jpg
enabled: true

Trying to write a template to know where the robot got stuck, getting error Message malformed: template value should be a string for dictionary value @ data['action'][1]['then'][2]['data']

frail ravine
#

hello guys, i just want to control tuya zigbee smart curtain from home assistant. i am using zigbee bridge and curtain. i already installed tasmota on zigbee bridge and made my homeassistant server. they are connecting with each other by mqtt mosquito. problem is i dont know how to controll that curtain.
can someone teach me about of button configuration and entity

marble jackal
marble jackal
sonic sand
#

I assume it has something to do with the

    data:
      image: /local/tmp/snapshot_vacuum.jpg

part, because when I paste this template on Devtools it seems OK.
What am I doing wrong here?

marble jackal
#

maybe not all group members support that?

sonic sand
marble jackal
#

well that, not all group members support that image part

#

try the individual group members

sonic sand
#

maybe I should use telegram send photo and target id this specific group

sonic sand
# marble jackal try the individual group members

only problem for me now is how do I assign it to the other group? I don't want to write down the id of it, need to use !secret in this case.

service: telegram_bot.send_photo
data:
  authentication: digest
  target: !secret telegram_groupChatId
  file: /config/www/tmp/snapshot_vacuum.jpg
  caption: >-
    🧹 🤖 Automation - Robot Vacuum is trapped or stuck in {{ (
    states('sensor.roborock_s8_pro_ultra_current_room')) }} ! ⚠️. 

I am getting error because of the !secret

#

expected int @ data['target'][0]. Got None

marble jackal
#

you can't assing this to a notify group

#

it's not a notify service

sonic sand
marble jackal
#

I'm not understanding the relevance of that

sonic sand
#

my automations.yaml is public in github.

marble jackal
#

yes, but I don't understand why you would need to specify the target, and can't use the secret

sonic sand
marble jackal
#

when does it complain about that, what is your yaml then?

fickle sand
#

Isn't the problem that target expects a integer while !secret ... is basically a string reference

silent vector
#

What's the difference between {{ (now() - xyzdatetime).seconds }} and (now() - xyzdatetime).total_seconds }}

silent vector
#

With

{% set x = '2024-04-04 05:59:05.247181-04:00' | as_datetime %}
    {{ (now() - x).total_seconds > 30 * 60 }}

I get TypeError: '>' not supported between instances of 'builtin_function_or_method' and 'int

fickle sand
fickle sand
marble jackal
marble jackal
silent vector
crimson lichen
marble jackal
# silent vector Oh yeah whoops thank you

so timedelta.seconds shows the number of seconds of the day, and is therefore limited to 1 day of seconds. timedelta.total_seconds() shows the total number of seconds, and is not limited to 1 day of seconds

marble jackal
silent vector
hushed siren
# marble jackal The `forecast` attribute for weather entities was depreciated 7 months ago, and ...

it´s true... fully removed in this release.. 😦
could you please help me how should I adapt this code to be compatible with the new coding? The part of meta.forecast.map is the one that now is not working

fn: |-
({ meta, vars }) => ({
xs: [vars.temperature.xs.slice(-1)[0],...meta.forecast.map(({ datetime }) => new Date(datetime))],
ys: [vars.temperature.ys.slice(-1)[0],...meta.forecast.map(({ temperature }) => temperature)],
})

marble jackal
#

how is meta defined?

hushed siren
#

thank you so much for your help in advanced

marble jackal
#

you need to create a trigger based template sensor and use the weather.get_forecasts service call to get the forecast out and store it in an attribute

hushed siren
#

there is not way to make this "on the fly" as I had before?

marble jackal
#

No

sonic sand
#

that's the error I'm getting in services ^

#
service: telegram_bot.send_photo
data:
  authentication: digest
  target: !secret telegram_groupChatId
  file: /config/www/tmp/snapshot_vacuum.jpg
  caption: >-
    🧹 🤖 Automation - Robot Vacuum is trapped or stuck in {{ (
    states('sensor.roborock_s8_pro_ultra_current_room')) }} ! ⚠️. 
obtuse zephyr
#

I don't believe you can use secret expansion outside of the files themselves

marble jackal
#

I was thinking in those lines as well, maybe try it in a script

#

a script with just that as the sequence

sonic sand
#

trying now, thanks!

hushed siren
sonic sand
marble jackal
#

what if you do this?

sequence:
  - variables:
      target: !secret telegram_groupChatId
  - service: telegram_bot.send_photo
    data:
      authentication: digest
      target: "{{ target | int(0) }}"
      file: /config/www/tmp/snapshot_vacuum.jpg
      caption: >-
        🧹 🤖 Automation - Robot Vacuum is trapped or stuck in {{ states('sensor.roborock_s8_pro_ultra_current_room') }} ! ⚠️. 
bronze prawn
#

I am struggling trying to pull information from this device's attributes:

https://dpaste.org/BCNpS

I thought I could use {{ state_attr('sensor.thinksmart_lr_intent', 'data') }} to pull this and then start pickiung at those results to get what I want but I keep coming up with none as the return

obtuse zephyr
#

Are you wrapping that in quotes or using a multi-line notation when you're using that?

mighty ledge
#

and state_attr only gets information out of entities, not devices

bronze prawn
#

Good to know. As you know I'm still pretty new to all of this. Is there any way I can pull information from this device?

mighty ledge
#

what information

#

you linked a conversation intent, not an enttiy or device

bronze prawn
#

This is what I see in dev tools

#

apologies that I did not include the entity name in the OP

mighty ledge
#
{{ state_attr('sensor.thinksmart_lr_intent', 'intent_output').response.data.success }}
bronze prawn
#

Thanks. These are the two that I need:

{{ state_attr('sensor.thinksmart_lr_intent', 'intent_output').response.speech.plain.speech }}
{{ state_attr('sensor.thinksmart_lr_intent', 'intent_output').response.data.success }}
#

What I'm trying to do is to display a page to show what assist intent did. what I'd like to know is if the item in success is type:area then return that name otherwise return the name of the first entity and I need to know what the id is so I can determine what class device it is.

So for my example, it would return 'Living Room' and the entity id is light.blahblah so class is light so show the button card with name 'Living Room' and icon 'mdi:lightbulb'

bronze prawn
#
{{ state_attr('sensor.thinksmart_lr_intent', 'intent_output').response.data.success[1].id }}

returns:

light.monoprice_z_wave_on_off_plugin

Is there an easy way to split on the '.' character and return the device class?

mighty ledge
#

.split('.')

marble jackal
#

shouldn't there be a listerener on label_entities()

#

this works

#

but it would be nice if expand() wasn't needed 🙂

mighty ledge
#

I don't think any of the *_entities register entity_id's

marble jackal
#

okay, so I need to use this workaround if I want to replace automations on groups with labels

mighty ledge
#

I think that would be a good feature request. Possibly an argument added to label_entities, listen=True

marble jackal
#

or something like this

{% set entities = label_entities('always_on') %}
{{ entities | select('is_state', 'off') | list }}
#

oh wait

mighty ledge
#

has_value

#

entities | select('has_value') | list

marble jackal
#

it already works without setting a variable first

mighty ledge
#

yah, that's expected

#

the states functions register entity listeners

marble jackal
#

ah and is_state() invokes the states function

mighty ledge
#

well

#

I made a post that highlights what registers listeners

#

probably can paste it here and pin it

marble jackal
#

why is expand blue

mighty ledge
#

it thinks it's some random language

#

the markdown

#

I changed it to js so that it looks nice(r)

twin cargo
#

Hey, im trying to figure out this weather forecast stuff and it is just erroring out with vague errors about data not existing despite all the entities being correct without this templating. Is there any way to troubleshoot what it’s getting and why it errors out?

mighty ledge
#

post the errors, they tell you exactly whats wrong

#

chances are you don't know how to read them

marble jackal
#

and share the non working YAML

plain magnetBOT
#

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

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

sonic sand
twin cargo
keen zealot
floral steeple
#

hi all, im trying add a new sensor to be part of the conversation on a morning greet automation here, which I forked from Allen Porter's blueprint.
https://gist.github.com/Anto79-ops/d926fa8655da7cad0a383e1fa35c40de
Specifically, what I want to know is if this is correct for the state of the CPAP sleep sensor on line 157:

        {%- if cpap_score is defined %}
        Sleep Score: {{ states('sensor.cpap_total_myair_score') }}

I also defined the CPAP sensors above in the variables and inputs

#

The error message I get when I try to save it is:
Message malformed: template value should be a string for dictionary value @ data['action'][2]['data']

marble jackal
keen zealot
floral steeple
keen zealot
rocky crypt
#

Hey there. I have had an automation I have been using that references the current hight temprature for the day, however it no longer is working...

              value_template: >-
                {% if (state_attr('weather.my_ecobee','forecast')[0].temperature | int) > 76 %}
                  {{ true }}
                {% else %}
                  {{ false }}
                {% endif %}

I was told that forecast attribue has been removed. How would I go about doing this now?

fickle sand
#

And see the convo right above you, I linked that specific message to you in #frontend-archived

marble jackal
#

@rocky crypt you don't need the intermediate sensor, but you need to add a trigger and the action part to this binairy sensor and then use the response variable

inner mesa
#

Ideally, we shouldn't be directing folks to replicate the sensor with the giant attributes, but instead show how to do it inline with variables

rocky crypt
#

Hmm. I'm so lost 😦 I guess I'll have to really research and figure this one out. Wonder why such a complex change??

inner mesa
#

to avoid unconditionally putting a ton of data into attributes that are stored and tracked all the time

#

instead, ask for exactly what you want when you want it

fickle sand
#

You mentioned you will use it in an automation so you only need the service call and use that response variable it generates in the rest of the automation. An example of what you have can help us to help you to write it the new way

inner mesa
#

this is the way

mighty ledge
rocky crypt
#

The Value template is what I had. If it returned true, it processed a sequence.

#
        - conditions:
            - condition: template
              value_template: >-
                {% if (state_attr('weather.my_ecobee','forecast')[0].temperature | int) > 76 %}
                  {{ true }}
                {% else %}
                  {{ false }}
                {% endif %}
          sequence:
            ...
mighty ledge
#

FYI that doesn't check the high
that checks the temperature of this hour...

inner mesa
#

and in the most verbose way possible 🙂

mighty ledge
#

yep

rocky crypt
#

Well, now it doesn't check anything! HAHA 🙂

#

So, I get that

service: weather.get_forecast
data:
  type: daily
target:
  entity_id: weather.my_ecobee

Returns the forecast and the high temp is in the returned value, but how would I put that into my automation for a condition?

mighty ledge
mighty ledge
#

it returns the temperature for each hour

#

0 is the current hour

fickle sand
rocky crypt
#

Gotcha. Then, I apparently had it wrong form the begining. I deffenitly want it to pull the high for the day.

mighty ledge
inner mesa
#

(I guess that's one of the downsides of the new service call - can't be used in a trigger or condition without creating a separate entity)

fickle sand
#

This is a condition in the action part, right? So it should be possible

rocky crypt
#

Correct.

mighty ledge
#

@rocky crypt did you check to see if there was a 'high' or 'max' entity on the device? Specifically in the disabled entities button on the devices page?

rocky crypt
#

Yes. And there isn't.

mighty ledge
#

if not

action:
- service: weather.get_forecast
  data:
    type: daily
  target:
    entity_id: weather.my_ecobee
  response_variable: response
- condition: template
  value_template: >
    {{ response['weather.my_ecobee'].forecast | map(attribute='temperature') | reject('none') | max > 74 }}
- ... rest of actions here...
rocky crypt
#

Hmm. Ok. I can give that a try 🙂 I was in the process of adding the sensor, and was running into issues... Haha 🙂 So, I can definitely try your sollution 🙂

mighty ledge
#

actually, that's the high for the week if you choose daily

#

there's only templow or temperature, so I guess we'll just have to use what you were using in the past

#
action:
- service: weather.get_forecast
  data:
    type: daily
  target:
    entity_id: weather.my_ecobee
  response_variable: response
- condition: template
  value_template: >
    {{ response['weather.my_ecobee'].forecast[0].temperature > 74 }}
- ... rest of actions here...
rocky crypt
#

I'm 99% positive that was pulling the high temp before with what I was doing... So very strange...

#

I can't even get the template to work in HA either...

mighty ledge
#

if you use exactly what i wrote, it will work

#

it will not work in the template editor

#

so don't bother testing it there

rocky crypt
#

Oh.

#

HAHA 🙂

mighty ledge
#

what you have there will work as a template entity

rocky crypt
#

I tried that.. But it says "unknown"

#

It never gets a value.

mighty ledge
#

well you have thte time pattern set to once every 3 hours

rocky crypt
#

So I have to wait 3 hours for the first reading?

minor jolt
#

Hello, I am trying to get some info out of a calender in a non-clander format (as a sensor), i tried googling it, and found the following, where i don't wuite understand everthing (this is the integration, https://github.com/jonkristian/wasteplan_trv)

mighty ledge
#

or just add a startup trigger

plain magnetBOT
#

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

rocky crypt
#

Got it 🙂

#

Is there a way to force run it as a service call?

minor jolt
#

there are two things i don't understand, the trigger, it triggers at every midnight i think, but when does the "event template reloaded" trigger?

#

And i don't understand quite what the "state" part at the end does, at the moment i only get "unknown" back from the sensor

mighty ledge
mighty ledge
rocky crypt
#

Ok. Cool. Thanks @mighty ledge for all your help! I REALLY appreciate it!!!

minor jolt
minor jolt
mighty ledge
#

sure but that all depends on how your items are listed

minor jolt
#

somthing like: 07.04 : Paper
09.04: Garbage
11.04: Plastics

#

the plugin creates a calender entity

#

with the dates for the different pickups

#

(i also see a warning that i should use calendar get_events instead of list_events)

marble jackal
minor jolt
#

this is the entity from the plugin

mighty ledge
#

plugin isn't something that's a term in HA

#

are you talking about the integration?

minor jolt
#

yeah, integration, sorry

mighty ledge
#

perform the service call in the service caller and post the results here

minor jolt
#

events:

  • start: "2024-04-05T08:00:00+02:00"
    end: "2024-04-05T16:00:00+02:00"
    summary: Papp og papir
  • start: "2024-04-12T08:00:00+02:00"
    end: "2024-04-12T16:00:00+02:00"
    summary: Restavfall
  • start: "2024-04-19T08:00:00+02:00"
    end: "2024-04-19T16:00:00+02:00"
#

that was from "list events", but "get events" seems to produce the same

#

events:
- start: "2024-04-05T08:00:00+02:00"
end: "2024-04-05T16:00:00+02:00"
summary: Papp og papir
- start: "2024-04-12T08:00:00+02:00"
end: "2024-04-12T16:00:00+02:00"
summary: Restavfall
- start: "2024-04-19T08:00:00+02:00"
end: "2024-04-19T16:00:00+02:00"
summary: Plastemballasje
- start: "2024-04-26T08:00:00+02:00"
end: "2024-04-26T16:00:00+02:00"
summary: Restavfall
- start: "2024-05-03T08:00:00+02:00"
end: "2024-05-03T16:00:00+02:00"

plain magnetBOT
#

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

minor jolt
#

guess it would be easiest with one sensor for each type, that is one for "Papp og papir" one for "Restavfall" and one for "Plastemballasje"

mighty ledge
#
{% set next_event = garbage.events | select('summary','eq', 'Restavfall') | first %}
{{ next_event.summary }}: {{ (next_event.start | as_datetime | as_local).date() }}
rocky crypt
#

@petro One other question. I'm trying to understand the sensor template for the weather... I modified the template to only pull the current day...

       - unique_id: daily_weather_forecast_template_sensor
         name: Daily Weather Forecast
         state: "Today's Forecast"
         attributes:
           forecast: "{{ forecast['weather.my_ecobee'].forecast[0] }}"
#

This works as expected...

{{ states.sensor.daily_weather_forecast }}
<template TemplateState(<state sensor.daily_weather_forecast=Today's Forecast; forecast=condition=sunny, wind_bearing=98, datetime=2024-04-04T18:02:00.327588+00:00, temperature=87, templow=53, wind_speed=15.66, friendly_name=Daily Weather Forecast @ 2024-04-04T11:01:00.328284-07:00>)>
#

However, {{ state_attr('sensor.daily_weather_forecast','temperature') }} returns "None" instead of the temperature value. Why would this be?

minor jolt
#
 sensor:
    - name: Next Garbage 
      unique_id: next_garbage_collection
      state: >
        {% set next_event = garbage.events | select('summary','eq', 'Restavfall') | first %}
        {{ next_event.summary }}: {{ (next_event.start | as_datetime | as_local).date() }}
#

but i get back "unavailable" from the sensor

#

sorry, I am a bit useless when it comes to templates.

haughty breach
#

If you are using calendar.get_events make sure you specify the calendar's entity ID

{% set next_event = garbage['calendar.tommeplan'].events | select('summary','eq', 'Restavfall') | first %}
{{ next_event.summary }}: {{ (next_event.start | as_datetime | as_local).date() }}
marble jackal
minor jolt
#

Thanks, but i seem to get "unavalilable" then as well

#

doesn't this part put it in the "garbage" variable?

 - service: calendar.list_events
      target:
        entity_id: calendar.tommeplan
      data:
        duration:
          days: 21
      response_variable: garbage
mighty ledge
minor jolt
#

I do, that is the same as before, this is the whole thing

plain magnetBOT
#

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

mighty ledge
#

If you're using get_events, you need to alter the templates like @haughty breach mentioned

#
- trigger:
    - platform: time
      at: '00:00:00'
    - platform: event
      event_type: event_template_reloaded
  action:
    - service: calendar.get_events
      target:
        entity_id: calendar.tommeplan
      data:
        duration:
          days: 21
      response_variable: garbage
  sensor:
    - name: Next Garbage 
      unique_id: next_garbage_collection
      state: >
        {% set next_event = garbage['calendar.tommeplan'].events | select('summary','eq', 'Restavfall') | first %}
        {{ next_event.summary }}: {{ (next_event.start | as_datetime | as_local).date() }}
bronze prawn
#

Can someone explain the weather forecast change? From the doc page it looks like we need to set up custom template sensor if we want to have this data available? If so, is there an example for how to create one that does a daily update rather than hourly? Is it just a matter of changing the example to a different time pattern and data type to daily?

inner mesa
#

yes

#

assuming that your weather service provides that

bronze prawn
#

It does. I tried it. Does not supply hourly.

bronze prawn
#

Sure. I'm looking through the docs now. The example given is for hourly and I'm just trying to adapt for daily. This may be an easy thing for most to do but this seems a bit odd in that it has to be set up in yaml. I'd guess this wouldn't be the easiest thing for a new user to do themselves.

inner mesa
#

it's only to support templates, which are already an advanced topic

#

well, generally

#

and the examples in the docs show exactly what to paste

minor jolt
#

is there a way to test this in the template devoloper tool? I can paste in the template-part, but it points to data (from the calandar) that isn't available in the devoloper tool.

bronze prawn
minor jolt
#

Error rendering state template for sensor.next_garbage: TemplateRuntimeError: No test named 'summary'.

#

thats weird

#

it said summery when i did the service call

#

let me check again

#

calendar.tommeplan:
events:
- start: "2024-04-05T08:00:00+02:00"
end: "2024-04-05T16:00:00+02:00"
summary: Papp og papir

#

yup, it says summary

marble jackal
#

selectattr('summary' instead of select('summary'

#
- trigger:
    - platform: time
      at: '00:00:00'
    - platform: event
      event_type: event_template_reloaded
  action:
    - service: calendar.get_events
      target:
        entity_id: calendar.tommeplan
      data:
        duration:
          days: 21
      response_variable: garbage
  sensor:
    - name: Next Garbage 
      unique_id: next_garbage_collection
      state: >
        {% set next_event = garbage['calendar.tommeplan'].events | selectattr('summary','eq', 'Restavfall') | first %}
        {{ next_event.summary }}: {{ (next_event.start | as_datetime | as_local).date() }}
minor jolt
#

nice, thanks a lot, that works, it now shows "Restavfall: 2024-04-05"

#

hope i am not to bothersome, i was wondering what the 'eq' part does? And is it possible to not show the year? I tried the docs, but but didn't seem like there was an easy way at least. If i understand it correctly, if i want to to remove "restavfall" from the sensor, i could just remove the "next_event.summary" correct?

marble jackal
#

You want only the date in the format MM-DD?

minor jolt
#

if possible yeah

#

or DD-MM even

marble jackal
#
  sensor:
    - name: Next Garbage 
      unique_id: next_garbage_collection
      state: >
        {% set next_event = garbage['calendar.tommeplan'].events | selectattr('summary','eq', 'Restavfall') | first %}
        {{ (next_event.start | as_datetime | as_local).strftime('%d-%m') }}
#

Discord messed up the indentation of the first line, but replace the sensor part with that

minor jolt
#

excellent, works perfectly, thanks a lot bot TheFes and petro, very helpful 🙂

quasi seal
#

Hey guys, anyone know if its possible to get the value of a MQTT topic in automation ? I realise there is mqtt trigger to initiate an automation, but im trying to use the last received value of a given topic in a variable. Basically im just trying to work-around haveing to create several mqtt sensors.

inner mesa
quasi seal
cold rune
#

Hey, can anyone tell me why this doesn't work?
value_template: "{{ is_state_attr(shield_id, 'app_id', 'com.plexapp.android') }}"

Is there any way to see what the results are when tracing?

inner mesa
#

Your question lacks context

#

What is 'shield_id'?

#

And how doesn't it work?

#

And where is it being used?

#

Never mind

solemn frost
#

I have a template for an Alexa Flash Briefing that pulls a weather description from the forecast data in a weather entity which is formatted as text for the Alexa device to read out loud, but with the recent change that moves the forecast data to a service call, the template of course stopped working. Is there any way to call that service in the template? Or if not, would the most sane way be to just create an automation that updates a text helper?

lucid thicket
solemn frost
#

Got it all fixed now. Thanks again

cold rune
#

When I look at it in developer tools, I can see the "app_id" of a given entity, so I'm trying to use that info as a condition

mighty ledge
gray urchin
#

I making a HA temple widget , is it possibly to change line with some command in the tex or something, hard to make it look good

#

Like Enter in word,

#

Now all the text just flows together

#

For mobile i talk about 🙂

#

Widget

mighty ledge
#

@alpine prism switch to the new template style, add a trigger and an action.

#

direct example in docs.

alpine prism
#

How can I fix my weather template

gray urchin
#

I fixed it

#

You may also use HTML to format the text displayed such as adding a new line (<br>), making something bold (<b>) or large (<big>), changing the color (<font color='#03a9f4'>) or aligning it to the start or end of a line (<p style="text-align: end">).

#

If i use the <big> in my text, all text get big, how do i get only one word in the HA widget temple to get big?

marble jackal
#

Close the tag again after the word you want to have big
<big>something</big>

gray urchin
#

Thanks

#

Working

cold rune
plain magnetBOT
#

@cold rune Please use imgur or other image sharing web sites, and share the link here.

Image posting is blocked in most channels to discourage people from sharing text as images. Sharing text as images assumes that everybody sees the world as you do, which isn't the case. Some people are colour blind, or have visual impairment that means they can't make sense of an image of text.

mighty ledge
cold rune
#

kk

#

the above is the "off" state, the second is the "on" state which shows a value for app id

plain magnetBOT
#

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

tacit sun
#

I prefer to go with simple if possible. Another possible solution would be to change the template of the initial sensor to only be true during a defined timeframe...

#

maybe:

start: "{{ now().replace(hour=5, minute=0, second=0) if now().hour >= 5 else now().replace(hour=5, minute=0, second=0) - timedelta(days=1) }}"
#

I think that did it... I'll know more after watching it a day or 2. 🙂

tacit sun
# cold rune https://imgur.com/a/d1ifgRe

perhaps something like this?

- alias: "Nvidia Shield App Attribute Changed"
  trigger:
    platform: template
    value_template: >
      {% set app_id = state_attr('media_player.nvidia_shield', 'app_id') %}
      {% set state = states('media_player.nvidia_shield') %}
      {{ state == 'on' and app_id == 'com.google.android.tvlauncher' }}
  action:
    - service: your_desired_service
      # Your desired service call or action here
mighty ledge
#

or if shield_id is worng

#

@tacit sun start: "{{ today_at('05:00') }}"

tacit sun
#

that does seem a bit more simple than what I came up with. Thanks!

cold rune
mighty ledge
#

gotta subtract a day if you're before 5am

tacit sun
#

This may be an unpopular opinion, but... I use chatGPT for guidance with the yaml, templates, and automations. It is not always right, and can come up with total garbage, but... can also help get me closer to my goals by suggesting things that are at least close to the correct answer, at which point, I can research deeper into those specific things.

#

It is not advised to rely on chatGPT though as most of the time it's suggestions won't work.

cold rune
#

How do you debug issues like this?

Ken - Play Next Adventure Time: Error executing script. Error for call_service at pos 1: Error rendering data template: TypeError: unhashable type: 'dict'

tacit sun
mighty ledge
#

yes, but it's not optimized

tacit sun
#

so, what makes it more optimized is that your version only does the time conversion once?

mighty ledge
#

it only gets 2 time objects

#

now and 5 am

tacit sun
#

vs 3 in my version?

mighty ledge
#

3 best case

tacit sun
#

makes sense. Thanks!

#

Thanks also for explaining why it was better that way to me. 😄

cold rune
#

I got it working

#

The issue was the dict, as @tacit sun pointed out- The fix was to refer to the nested entity id;
"Playing Adventure Time - Shield= {'entity_id': 'media_player.shield_ken'} Entity= media_player.shield_ken"

So
this:
value_template: "{{ is_state_attr(shield_id, 'app_id', 'com.plexapp.android') }}"

became
value_template: "{{ is_state_attr(shield_id.entity_id, 'app_id', 'com.plexapp.android') }}"

tacit sun
#

Nice work!

wary shoal
#

Remove square brackets from result

devout dragon
#

hmm is it possible to get the state of a sensor for like a month ? i want to calculate the average electricity price over a month from my hourly_energy sensor, and nordpool current price to be able to add them together by the hourly rate and make a mean price out of it 🙂

#

like an array with the values for a month back in time

inner mesa
#

no

devout dragon
#

meh :/

inner mesa
#

create a template sensor for whatever calculation you want and then use a helper to calculate the mean price

#

there also seem to be 1000000 people caring about Nordpool prices, so perhaps there's already something for what you want

dense vine
#

I get sensor state unknown

plain magnetBOT
#

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

dense vine
#

anyone that can see something wrong or is this the wrong forum

#

the only thing that i see is friendly_name: Weather Forecast Daily

haughty breach
#

You've probably realized this by now, but the values will only populate at the top of the hour because that is the trigger you selected.

bronze prawn
#

{{ device_id (expand('group.assist_satellites') | map(attribute='attributes.display_device') | first) }}

I'm trying to modify this to show the device_id for all members in the group instead of just the first. Can someone tell me how that is done? I've tried removing the pipe first and changing to pipe list but that doesn't work

inner mesa
#

you need map('device_id') if it supports that

bronze prawn
#

I wrap all of what is in the curly braces to map('that stuff')?

inner mesa
#

I don't know what that means, really

bronze prawn
#

Sorry, I'm still really new to the syntax

#

{{ map (device_id (expand('group.assist_satellites') | map(attribute='attributes.display_device') }}

inner mesa
#

if it supports it, you would do {{ expand('group.assist_satellites') | map(attribute='attributes.display_device') | map('device_id')|list }}

bronze prawn
#

ahhh.. ok

inner mesa
#

I have no idea if that will work

#

if not, you would need a loop

bronze prawn
#

Yeah, that's a winner. Thanks for your patience and kindness in answering these

west loom
#

hey everyone. I know there's been several community posts about api keys in the url for custom sensors and the suggestion is usually "put the whole url in secrets" However, I have a url that needs the key and additional bits. I'm wondering if I can do platform: rest and have it use a rest_command to provide additional details. The end url would be something like .com/api?key=asdf&extra=bits

inner mesa
#

you can put a template in the secret with a variable or to return the state of an entity

west loom
#

I did wonder about that. Can you elaborate on what that would look like?

inner mesa
#

secrets.yaml:
test_secret: This is some {{ secret }} text
scripts.yaml:

secret_test:
  sequence:
    - variables:
        secret: scary
    - service: persistent_notification.create
      data:
        message: !secret test_secret
west loom
#

where I would stuff {{coords}} with something like {{ state_attr('zone.home', 'latitude') | round(2) | string }}&long={{ '{:.2f}'.format(state_attr('zone.home', 'longitude')) }}

inner mesa
#

you can put whatever template you want in there

west loom
#

yes but resource template doesn't support secrets from what I've read

inner mesa
#

they're just a string substitution

#

there's nothing to support

west loom
#

resource_template: "https://api.ipgeolocation.io/astronomy?apiKey={{!secret ipgeolocation}}&lat={{ state_attr('zone.home', 'latitude') | round(2) | string }}&long={{ '{:.2f}'.format(state_attr('zone.home', 'longitude')) }}" this does not work

inner mesa
#

you put !secret in the middle there

#

you cannot do that

#

as you said in the beginning, put the whole thing in a secret

west loom
#

so even the lat long substitution will still work?

inner mesa
#

all of it

#

you may need to construct the string within a single template, but I doubt it

west loom
#

that might be working. I'm annoyed I didn't just try that lol. I'll have to see if the states get updated. Thanks for your help

bronze prawn
#
    selectattr('attributes.do_not_disturb', 'eq','false') |
    map(attribute='attributes.mediaplayer_device') | list) }}

Back for more. What I had hoped this would do would be to look at all entities in the group, check their attributes are equal to false and then return the attribute mediaplay_device of that group member. What I am getting back is the list of group members rather than the attribute value stored in mediaplayer_device . What am I doing incorrectly?

inner mesa
#

first, remove the quotes around false

bronze prawn
#

done. no difference in output

inner mesa
#

what you're saying doesn't make sense

#

look for errors in the log

#

there's no way that that returns the list of entities in the group

bronze prawn
#

do_not_disturb: False
FYI, this is what I see in states

inner mesa
#

still

#

it is likely a boolean value

bronze prawn
#

This is from my custom device definition. To be honest, I am uncertain how I should be setting it with or without quotes.

#
    state: ""
    attributes:
      mode: "normal"
      mic_device: "sensor.tablet_master_stt"
      mediaplayer_device: "media_player.tabletmaster"
      display_device: "sensor.tabletmaster_browser_path"
      browser_id: "TabletMaster"
      view_timeout: "20"
      message_font_size: "3vw"
      cycle_view: ""
      do_not_disturb: false
inner mesa
#

it's a boolean, so it should be a boolean

bronze prawn
#

Show I be using quotes for things like mode, mic_device, etc? When I look at this device the do_not_disturb shows up as capitalized false instead of lower case.

inner mesa
#

it's quite simple

#

strings are strings

#

true/false are booleans

#

strings get quotes

bronze prawn
#

gotcha. Does the case matter when setting?

inner mesa
#

booleans do not

#

I don't think so

#

generally, use lowercase

bronze prawn
#

that view_timeout is a number. should I be handling that without quotes?

inner mesa
#

you also have view_timeout with "20", making it a string

#

surely you want that to be a number, which also shouldn't be surrouded in quotes

#

yes

#

quotes are for strings, always

vital grotto
#

Im sorry to ask this but im struggling to get the syntax on this right. I have a simple template sensor:

reddog_current:
  friendly_name: RedDog Charging Current
  unit_of_measurement: A
  device_class: power
  value_template: >- 
    {{ state_attr('sensor.reddog_charger_power', 'charger_amps_actual') | float}}

however if the sensors are unavailable, then my log gets flooded with errors. How can I make this default to 0 if the sensors are unavailable?

inner mesa
#

add an availability_template

vital grotto
#

so I use: - platform: availability_template as well as the above or move the whole thing into the new one?

inner mesa
#

if you just want to make the default 0, then just do that

#

{{ state_attr('sensor.reddog_charger_power', 'charger_amps_actual') | float(0)}}

#

no, no no

#

there's no "platform: availabilty_template"

#

here:

#
    reddog_current:
      friendly_name: RedDog Charging Current
      unit_of_measurement: A
      device_class: power
      availabilty_template: "{{ not is_state('sensor.reddog_charger_power', 'unavailable') }}"
      value_template: >-
        {{ state_attr('sensor.reddog_charger_power', 'charger_amps_actual') | float(0) }}
#

or whatever it means for that sensor to be unavailable

vital grotto
#

ah - i see. I find the whole syntax of these very confusing. (my experience in programming is mostly assembler! - (showing my age)..... thanks for your help, i'll go and try this.

bronze prawn
#

I'm thinking about 'disposable' timers and alarms. Wondering if it is possible to do something like storing a value like:

{{ as_timestamp(now()) + 120 }}

For a timer that wold expire in 120 seconds from now. I would then do a compare template of current time and that future time and then when true would do something. My question is is this possible? I think I heard somewhere that these are not evaluated at a frequency that would allow this sort of precision or am I misremembering/misunderstanding?

bronze prawn
#

Looks like this evaluates about every minute. Any thoughts on using something similar to create timers without having to make a helper? I'd like to be able to create multiple timers without having to create multiple helpers.

lucid thicket
#

Where are you proposing that you would store the result of that ‘disposable’ template? You’d need a helper, or a template sensor, to store it…

bronze prawn
#

I would store it, and any others, as a list value in my device's attributes. The device is a template device

#

I think the real issue is that these template comparisons don't happen soon enough. Setting a one minute timer will not be evaluated often enough that it won't provide much precision. FYI, I'm working on replicating what commercial voice assistants provide but for assist. "Set an <egg> timer for two minutes" "Remind me to <go for a walk> at 5:30pm"

#

This could be done with helpers but what a mess if you want to do a bunch of these on a handful of devices. Helpers everywhere

#

Maybe someone knows of an easy way that I don't know about

lucid thicket
#

Could you make an entity on the fly by a POST call to the /api/states/<entity_id> endpoint (using a UUID for the entity), and then reference that entity in a time trigger? Entities created that way will disappear upon restart.

plain magnetBOT
#

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

minor jolt
#

this is the example from the docs about "TRIGGER BASED HANDLING OF SERVICE RESPONSE DATA"

#

i was wondering if it works to have more than one sensor "created" from the same trigger and action? Or do i have to copy the entire thing several times do that?

#

that is, can i make

trigger:
action:
sensor1:
sensor2:
sensor3:
#

or does it have to be

trigger:
action:
sensor1:

trigger:
action:
sensor2:

trigger:
action:
sensor3:
marble jackal
plain magnetBOT
#

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

heavy crow
#

omg, ignore me, I was just impatient. I must have a slow update on it

minor jolt
#

trying to make a date from a sensor on the foloowing format "2024-04-09" show this instead "09-04"

#

tried the following template sensor

- sensor:
    - name: neste_post
      unique_id: neste_post
      state: "{{ as_datetime(states('sensor.posten_sensor_next')) | timestamp_custom('%d-%m') }}"
#

but the log gives me the error "'datetime.datetime' object cannot be interpreted as an integer"

#

so maybe datetime isn't the right way to read the date here, but what should i use instead?

obtuse zephyr
#

timestamp_custom expects a timestamp, so use as_timestamp instead

minor jolt
#

thanks, that works in a sense, but the data is shown in a weird fashion, the sensor now gets a value, but it is "1712613600.0" instead of a date

obtuse zephyr
#

You're still using timestamp_custom?

minor jolt
#

no, this is the new template sensor

#
- sensor:
    - name: neste_post
      unique_id: neste_post
      state: "{{ as_datetime(states('sensor.posten_sensor_next')) | as_timestamp('%d-%m') }}"
obtuse zephyr
#

state: "{{ as_timestamp(states('sensor.posten_sensor_next')) | timestamp_custom('%d-%m') }}"

minor jolt
#

ah, so the problem was that i used datetime instead of timestamp?

obtuse zephyr
#

Correct

minor jolt
#

works now, thanks

#

when i googled it it gave me the impression datetime was the same as timestamp, just with a wider range of possible values.

obtuse zephyr
#

Nope, not actually the same, even if they're representing a similar value. Timestamp is a numeric value of seconds that elapsed since 1/1/1970.

minor jolt
#

ah, i see, thanks

crimson lichen
#

Hi
How to use vacuum.send_command on Hass for
1 - change mode : Vacuuming, Vacuuming & Mopping, Mopping.
2 - change level of mopping: Low, Medium, High.
I have Vacuum Mijia C3.

lucid thicket
bronze prawn
#

I'm late in the transition to the new weather forecast simply because I have been confused. I want to replicate what was there before for a daily forecast and I'm not seeing an example on the doc page. I think the part I most need help with is modifying this:

    sensor:
      - name: Temperature forecast next hour
        unique_id: temperature_forecast_next_hour
        state: "{{ hourly['weather.home'].forecast[0].temperature }}"

I would like to somehow store everything that is sent back from the response variable in a sensor and then parse it the way I was before. I don't think that state will allow for all that data, right? If so, I can create an attribute. But what is the template for the whole response? is it {{ daily['weather.home'].forecast }} ?

#
    sensor:
      - name: Daily Forecast
        unique_id: daily_forecast
        state: ""
        attributes:
          forecast: "{{ daily['weather.home'].forecast }}"
#

Is that correct?

inner mesa
#

Review your logs and the issue that your code creates

#

The fix is to call weather.get_forecasts

#

I pasted exactly your code in my config and it not only produced a useful error in the logs, but created an issue with exactly what to do

fringe sail
#

Hey guys. I'm trying to keep using my animated icon weather card, but now that the weather forecast method has changed, it's no longer showing the forecast. I'm having trouble understanding the new method. I found a template to show the weather forecast. The maker said that he was using openweathermap, but I don't see openweathermap represented in his template, so I'm confused. I'm using a weather entity that gives a daily forecast, but I don't know exactly how to substitute my weather entity into his template, since I didn't see his weather entity in his template. Can somebody tell me anything? Here's the template...

https://pastebin.com/etU7zvh8

lucid thicket
#

you would need to replace weather.daily with your weather entity's entity_id

fringe sail
lucid thicket
#

openweathermap is the name of the integration he used to create the weather.daily entity. You could use any of 100 different integrations to create weather entity. The entity name doesn't have to contain the name of the integration.

fringe sail
#

Do you think there's another template that he used to define that openweathermap was the weather entity? If not, I'm still confused. I'm not confused about what you said about me inserting my weather entity, but about how his template sensor would get its values.

lucid thicket
#

Step 1 is to get a weather entity into home assistant. You can do that by going to settings -> device & services, then clicking "add integration". You can choose from openweathermap or any of a bunch of other integrations. If the integration you want isn't listed, you can install custom integrations from HACS or manually. However you do it, you will eventually go through that process and end up with a weather entity.

#

The template sensor you create then references whatever that weather entity is called.

fringe sail
#

Yeah, I've got a few weather entities.

bronze prawn
inner mesa
#

I literally added an s and added an event, which I fired to get it to update

#

And I did it all from my phone

#

Otherwise, I got nothin

bronze prawn
#

My apologies. It is working. I tried loading the modified template instead of restarting. Apparently the restart is necessary and the ondemand load did not work.

inner mesa
#

Worked fine for me

marble jackal
inner mesa
#

That's what the issue says

#

And how I knew what to do

#

It's a shame that some of the interesting bits get truncated

bronze prawn
#

So because I'm getting multiple days that's why I need to use forecasts? Still not certain but it doesn't really matter. Moving on

inner mesa
#

And the log:

2024-04-06 10:04:14.130 WARNING (MainThread) [homeassistant.components.weather] Detected use of service 'weather.get_forecast'. This is deprecated and will stop working in Home Assistant 2024.6. Use 'weather.get_forecasts' instead which supports multiple entities
2024-04-06 10:04:14.130 ERROR (MainThread) [homeassistant.helpers.template] Template variable error: 'dict object' has no attribute 'weather.home' when rendering '{{ daily['weather.home'].forecast }}'
2024-04-06 10:04:14.131 ERROR (MainThread) [homeassistant.helpers.sensor] Error rendering state template for sensor.daily_forecast: UndefinedError: 'dict object' has no attribute 'weather.home'
bronze prawn
#

OHHHHHH

inner mesa
#

It's as clear as it can be

bronze prawn
#

I didn't think that was an old service call and thought everything that was old way was deprecated like the attributes being moved.

#

got it now. Thanks.

fringe sail
#

Ok, here's my first attempt at creating my daily weather forecast template(https://pastebin.com/XTgXVjdu). My question is can I put in a unique_id so that I can use settings to affect it in HA? If so, where in the yaml code would I put the unique_id? I'm confused because it has more than one section.

lucid thicket
fringe sail
#

The sensor I created worked except for the temp and humidity. I'll try to see what's wrong with those.

lucid thicket
#

weather is the key for the weather entity. Ignore everything I was saying.
<edit: I removed all the bad information in my previous messages>

fringe sail
#

Ok, thanks again.

lucid thicket
#

yours is fine. If you want to add a dash before the name: key you can do that, but it's only necessary if you define multiple entities underneath the weather key (which is unlikely in this instance)

#

and to answer your original question, the unique_id goes in the block with the name and templates

fringe sail
#

I lucked up on that...lol.

lucid thicket
fringe sail
lucid thicket
#

it is a good habit to get into to try your templates in the template editor (developer tools -> template) before you put them into a yaml config

fringe sail
#

Good advice.

lucid thicket
#

anyone know if there is a way to self-reference the state of an entity but return original value of the entity, rather than the value of the entity after the units were changed in the UI?

marble jackal
#

This makes me dizzy

lucid thicket
#

for example, I have a mqtt sensor which receives values in km, but when I use this.state I get the value in miles because I selected miles from teh UI

#

maybe that's a bug?

marble jackal
#

Ah yes, changing the unit of measurement actually changes the state

#

So I don't think you can see the original state provided by the integration

lucid thicket
#

ugh. that is ugly. I really need a this.raw_state or something

marble jackal
#

I always thought it was just for representation on the GUI as well, like setting precision

#

But recently found out it wasn't like that

lucid thicket
#

There’s no easy way to make a max sensor now. If you set up a trigger-based template sensor that takes the max of some sensor and this.state, and then change the units of your template sensor, you have to go back into your template code and add the conversion there too

#

I’m dealing with it on a mqtt sensor where value is in km but this.state is in miles. Ugh.

plain magnetBOT
#

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

haughty breach
#

The forecast attribute was deprecated, you need to use the weather.get_forecasts service to get the data.

fringe sail
#

I'm really not understanding something. I was using an animated icon weather card. All I had to do was reference a weather entity and it showed a multiple day forecast. Since the 2024.4 update, no weather card I've tried will show a multiple day forecast. I've created a trigger template sensor that shows a multiple day forecast when I click on the sensor in settings, entities. When I use that same sensor in a card it only shows the forecast for today, but nothing that I've tried shows a multiple day forecast. What am I missing?

#

I was wrong about one thing. The only card that will show a multiple day forecast is the weather forecast card, but I want animated icons, and it doesn't have that.

mighty ledge
#

install the beta version of the card

inner pagoda
#

What would folks recommend for getting a list of entities that match multiple conditions? Some specific examples: I want to find all the entities provided by a certain integration which are in a certain area. Or entities which are in a certain area and have a certain label applied.

fringe sail
mighty ledge
mighty ledge
fringe sail
#

Ok

inner pagoda
mighty ledge
#

what?

#

it pulls the integration entities and only selects what's in the area

#

and it's just a list of entity_ids

#

it's not doing a DB lookup

inner pagoda
#

Well, it's just the way the some_list | select('in', some_other_list) works in general requires one by one checking if each entry in the first list is in the second list, by scanning through the second list.

mighty ledge
#

it's a generator

#

it uses yield

#

it's much faster than you're amking it out to be

#

it's not a for loop

inner pagoda
#

if i run the output of that through a | list it makes the generator process all the input, so it is effectively a for loop.

mighty ledge
#

it process the output, not each item in both lists.

#

it's still a yield

#

so only what you use is provided to the list and accessed

inner pagoda
#

integration_entities('something') returns a list, right? And area_entities('something') also returns a list, right?

mighty ledge
#

fine, if you want to be a fucking pedant, use

{{ integration_entities('zwave_js') | map('area_name') | select('eq', 'kitchen') | list }}
#

it's the same shit

inner pagoda
#

well, that just returns the area names, i wanted a list of filtered entity ids :/

#

but yeah, i don't expect this is actually a performance issue unless you're getting into thousands of entities

#

(probably millions tbh)

mighty ledge
#

it's not even a performance issue with thousands

#

.001 microseconds with thousands of entities

inner pagoda
#

hmm. well, even if it's not a performance issue, it is kinda non-obvious how to write this sort of filtering in the first place. I was stuck for a while trying to figure out how to work around the fact that jinja2's select filter only allows using tests, and there's no test available to answer "is the entity with this id in a certain area" or "does the entity with this id have a certain label" :/

mighty ledge
#

You can use sets

#

which has .difference

#

if you want anything else, feel free to add it to HA

#

all would be easy implementations

#

Just keep in mind that you're complaining to people who are volunteers. We add things we need, if we don't need it, we don't add it. Also, we aren't a sounding board, if you want features, add them. Complaining is the fastest way to get ignored

hexed galleon
#

Is it possible to set multiple variables/assignments within a single Jinja block? Or need a new block for each assignment?

inner mesa
#

what do you mean by "block"?

hexed galleon
#
  set entity = states.light.office_lights
  set hue = entity.attributes.hs_color[0]
  set sat = (entity.attributes.hs_color[1])*0.75
  set val = (entity.attributes.brightness/255)*100
%}```
inner mesa
#

no, you can't do that

#

you can test this yourself

#

devtools -> Templates

#

TemplateSyntaxError: expected token 'end of statement block', got 'set'

hexed galleon
#

Yeah, I have been testing. Just wasn't sure if there was another syntax that worked.

#

Looks like comma-separated assignment works the best for shortening it.

mighty ledge
#

well, you sort of can

#
{% set entity, hue, sat, val = (
     states.light.office_lights,
     entity.attributes.hs_color[0],
     (entity.attributes.hs_color[1])*0.75,
     (entity.attributes.brightness/255)*100
) %}
hexed galleon
#

That almost works, but looks like it does all assignment at the same time, so entity needs to be its own. This is where I got.

{% set hue,sat,val =
      entity.attributes.hs_color[0],
      (entity.attributes.hs_color[1])*0.75,
      (entity.attributes.brightness/255)*100
%}```
mighty ledge
#

actually, that might not work because you're setting the entity while using it

inner mesa
#

right

mighty ledge
#

yep, you got it

inner mesa
#

it doesn't

#

yeah, you need to do it two steps like that

hexed galleon
#

Thanks friends!

#

Man Jinja is flexible. So cool! Flipped it to a dict for cleaner referencing.

sacred sparrow
#

is there a way to make the last_changed not change with everytime the state goes above 40?

    - name: "NAS Status"
      icon: phu:nas-v2
      availability: "{{ is_state('sensor.server_smartplug_power', 'unavailable') or is_state('sensor.server_smartplug_power', 'unknown') or states('sensor.server_smartplug_power') | is_number }}"
      delay_on:
        seconds: 10
      delay_off:
        seconds: 10
      attributes:
        last_changed: '{{ now() }}'
      state: "{{ states('sensor.server_smartplug_power')| float(0) >= 40 }}"```
#

I want it to show the last time on or off was triggered not every state change of above 40

mighty ledge
#

that whole template seems.. odd

#

why do you even have an availability template with that? It's always true.

#

and the delay on or off seems odd too

sacred sparrow
#

true. - I'll remove that

mighty ledge
#

are you just trying to make it always available?

#

if yes, you should do that differently

#

lastly, you have minutely updates happening in your last_changed attribute

#

which makes no sense

sacred sparrow
#

I have a hard drive caddy attached to my NUC - when its on stays above 40watts the nas is on - sometimes it dips below 40 but just for 5-7 seconds but goes back up so 10 seconds keeps the state

#

and vice versa

mighty ledge
#

ok, then get rid of the availabilty and last_changed attribute

sacred sparrow
#

I want it to show the last time it showed changed state

mighty ledge
#

every entity shows that

#

without needing to make an attribute

#

you making that attribute makes it update once a minute on the minute

sacred sparrow
#

because I am using it here:

    - name: NAS Uptime
      icon: mdi:sort-clock-descending
      availability: "{{ not is_state('sensor.ha_server_uptime', 'unavailable') }}"
      attributes:
        last_changed: '{{ now() }}'
      state: >
        {% set time = ((as_timestamp(now()) - as_timestamp(state_attr('binary_sensor.nas_status', 'last_changed')))) %}
        {% set minutes = ((time % 3600) / 60) | int %}
        {% set hours = ((time % 86400) / 3600) | int %}
        {% set days = (time / 86400) | int %}
......```
mighty ledge
#

yeah, you're doing this all wrong

sacred sparrow
#

so I am guessing there is a better way 🙂

mighty ledge
#

get rid of all your last_changed attributes

#

not better ways, correct ways

#

when you make a template with now() the entity will update it's state once a minute on the minute

#

so your last_changed's... all of them are wrong

#

there's 3 properties on state objects

mighty ledge
#

last_changed, last_updated, and last_reported

#

states['sensor.ha_server_uptime'].last_changed

#

is the last time the state changed

#

as for your template

- sensor:
    - name: NAS Uptime
      icon: mdi:sort-clock-descending
      device_class: duration
      unit_of_measurement: s
      state: >
        {{ (now() - states['sensor.ha_server_uptime'].last_changed).total_seconds() }}
#

that will show up as a duration sensor

#

x days HH:MM:SS

sacred sparrow
#

perfect thank you so much

#

I'll play with that

mighty ledge
#

also, keep in mind, last_changed is not persistent through restarts

lucid thicket
#

if you really want to optimize it, you should make it a timestamp of when the device started, so that you don't have updates every minute filling up your recorder database. Then, if you want to see how long it has been running, you put that template code in your frontend so it is only calculated when you're looking at it

mighty ledge
#

I'm thinking that he really wants this:

- sensor:
    - name: NAS Uptime
      icon: mdi:sort-clock-descending
      device_class: duration
      unit_of_measurement: s
      availability: "{{ 'sensor.ha_server_uptime' | has_value }}"
      state: >
        {{ (now() - states('sensor.ha_server_uptime') | as_datetime | as_local).total_seconds() }}
sacred sparrow
#

when I do:
{{ (now() - states('sensor.nas_status') | as_datetime | as_local).total_seconds() }} I get:
AttributeError: 'NoneType' object has no attribute 'tzinfo'

lucid thicket
#

test out your templates in developer tools -> template. And check out the state of sensor.nas_status on the states page, or using a template. I thought you had a binary_sensor.nas_status and a sensor.nas_uptime?

lucid thicket
plain magnetBOT
#

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

sacred sparrow
haughty breach
#

A binary sensor will never have a state that is a datetime string or timestamp... so as_datetime can't do anything with the input you've supplied.

lucid thicket
#

To get rid of that error, you have to apply that method to a timedelta object, and you would do that by putting parentheses around the code leading up to that method. But that is your second problem: your code (once you remove the total_seconds() method) is trying to give you a datetime object, not a timedelta object

#

Which is your third problem, which Drew already mentioned. You can’t convert the state on or off to a datetime

#

The code you originally shared should be fine, assuming your sensor can actually be converted to a datetime:

{{ (now() - states('sensor.nas_status') | as_datetime | as_local).total_seconds() }}

You might start with the portion that converts the sensor state to a datetime, to see if that first bit actually works:

{{ states('sensor.nas_status') | as_datetime }}
naive swan
#

With the create calendar event, how would you write the start date so its the next time 8pm occurs. I had it set to create a calendar at 8pm on the same day however the obvious flaw on this is if its triggered after 8pm with start_date_time: "{{ states ('sensor.date') }} 20:00:00"

marble jackal
#
start_date_time: >
  {% set t = today_at('20:00') %}
  {{ t if now() < t else t + timedelta(days=1) }}
rose sail
rose sail
wise sluice
#

am i able to place a templated entity in a value template?

scenario:

  • I have a trigger that is a switch action with a trigger id 'kitchen'
    -the switch controls a light with an object id that is the same as the trigger id (light.kitchen)
    -I have an input boolean that needs to turn on or off based on the state of the light entity that the switch controls (the switch doesn't have a state)
    -i want to send a variable that lists the state of the light entity from the automation to a script using a template

something like:
variables:
state: "{{ states('light.{ trigger.id }') }}

mighty ledge
#

Use string concatenation

wise sluice
#

hmm. i'm not sure i've ever done that in an automation. i don't know if i'm understanding what i'm reading online.

would it be: {{ states('light.'~trigger.id ) }}
or i actually need to manually define each part with {% set ... %}

flat cave
heavy crow
#

Hello, I am sure I have any easy one for you experts. This is failing in my configuration yaml

#
  • sensor:
    • name: "mainvalve_120h_count_minutes
      #unit_of_measure: minutes
      state: "{{ (timedelta(hours=states('sensor.mainvalve_120h_count') | float(0)) | string)[:-3] }}"
    • name: "bottomvalve_120h_count_minutes
      #unit_of_measure: minutes
      state: "{{ (timedelta(hours=states('sensor.bottomvalve_120h_count') | float(0)) | string)[:-3] }}"
#

missed comma between flow collection entries (78:94)

75 | ...
76 | ...
77 | ...
78 | ... _count') | float(0)) | string)[:-3] }}"
-----------------------------------------^
79 | ...

#

but all the examples I can see that seems like okay code

#

that arrow points on the | system before the string BTW ...

#

Sorry about the formatting .... it did not look like that before I pasted it in here.

#

the code works in the template sections of the developer tab too - just doesn't like it when I put it in the template sensor state.

heavy crow
#

All good, got it! it is the silly have to press " twice setting on my keyboard which I just figured out how to change. I did not close the name section

plain magnetBOT
#

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

cinder lotus
#

I made a template sensor:

    - name: autoladen_in_W
      unique_id: autoladen_in_w
      unit_of_measurement: "W"
      state: "{{ ( states('sensor.lader_laadstroom')|float(0) ) * ( states('sensor.lader_voltage')|float(0) )}}```
The result is 4,660.75784480932 W
How to change this to 4,660 W?
inner mesa
#

Put |int after the last )

#

Or |round if you really wanted to round it

plain magnetBOT
#

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

inner mesa
#

Everywhere you have | rejectattr('attributes.device_class', 'defined') you need to change it to | selectattr('attributes.device_class', 'defined') and move it before where you filter on it

#

Do you understand what that is doing?

lucid thicket
rose sail
# lucid thicket Well what is the state of the binary sensor during reboot? I assume it is report...

The sensor is still reported as “true” during reboot, doesn’t change his status.

I see duplicated “locked” status in HA logs: first time because goes triggered by the sensor before the reboot. Second time after the reboot that it gets “locked” (but not because it gets triggered). No log about getting triggered or changing status. I can see only in the UI and using a logbook card, that it goes to “unlocked” for about 11/12 seconds

lucid thicket
#

before going any further it is probably worth getting your sensor to at least conform to the documentation so we know that isn't causing issues. Remove spaces and quotes from the unique_id, and change your value_template so that it renders a value that is either true or false. For example:

    unique_id: dca99c81-e346-4769-b274-f9b71c6674ed
    value_template: >-
      {{ is_state('binary_sensor.shelly_plus_1pm_input_0_input', 'on') }}
sonic nimbus
#

Fliar error Nobe default value

rose sail
hallow dock
#

I am trying to set up a mqtt device tracker and the integration page says to use a json_attributes_template. I cannot figure this out. the longitude and latitude come in as "longitude_i" and "latitude_i" and home assistant expects "latitude" and "longitude"

lucid thicket
# rose sail Thanks, I fixed all unique_id(s) in my config. I did change the value_template ...

Yes using quotes is the proper format for a single-line template.

You’ll have to be careful changing unique_id’s; I would have started with the one and gone from there. When unique_id is changed (and maybe even added?) HA will think a new sensor was created and the old one will go to unknown. Since the 'new' one will attempt to use the same entity_id HA will append _2 to it

rose sail
lucid thicket
#

Yes I just don’t know if HA will slugify it (which corrects it for you) or ignore it (which means you really didn’t have a unique id)

rose sail
#

Tried with new config and still reporting as locked for 12s

lucid thicket
#

And the binary sensor reports correctly that entire time?

rose sail
#

Just cheked, binary sensor always on. Does not change during reboot

#

After the reboot, the log of lock template reports only that it changed to locked status, giving no other information.
When it changes because it was triggered by the binary_sensor, it also display that info

lucid thicket
#

Well a state-based template lock (or sensor or binary sensor etc.) doesn’t retain state across restarts, but it should be unknown until it’s template is first rendered. I haven’t used a template lock but some seems wrong that it shows unlocked before the state is first rendered. Can you share the latest config you are using? Does it still include the availability template?

rose sail
#

The binary_sensor I'm using does not change status during reboot at all, even in logs never gets unknow/unavailable

#

`lock:

  • platform: template
    name: "Cancello scorrevole"
    unique_id: cancello_scorrevole
    value_template: "{{ is_state('binary_sensor.shelly_plus_1pm_input_0_input', 'on') }}"
    lock:
    service: switch.turn_on
    target:
    entity_id: switch.shelly_plus_1pm_switch_0
    unlock:
    service: switch.turn_on
    target:
    entity_id: switch.shelly_plus_1pm_switch_0
    availability_template: "{{ states('binary_sensor.shelly_plus_1pm_input_0_input') not in ['unknown', 'unavailable'] }}"`
#

I might try using another entity that goes in unknow/unavailable status during reboot

lucid thicket
#

You’re going to need some help from someone who knows the intricacies of HA startup much better than I do. I think you’ve used up what little knowledge I have

rose sail
#

It logs that changes to not available because of the new triggering entity but then it does report that it changed to locked (without reporting any triggering entity).
In UI still appears as "unlocked" for some seconds and also my logbook card is gets logged for 12s as unlocked

plain magnetBOT
#

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

haughty kiln
rose sail
lucid thicket
#

A template lock is an integration, and so you may have better luck in #integrations-archived If you are having an issue with the actual code of a template that is used in the config you would use the templates channel

haughty breach
neon laurel
#

cheers

#

can I define this as a macro in a template light?

#

my goal is that when I use the set_temperature service call for the light, the macro is executed and sets the ww_clamped and cw_clamped value which I can then reuse in the service call

#

I've seen that I can centrally define macros but I'm writing this as a tutorial so if I could define everything in the same spot without additional steps that would be ideal

#

as an alternative I could convert it to a one liner and execute on every rgbw channel but that's gonna hurt readability

#

with your clever sort and slice method it's not too bad I guess:

{{ ([0, ((255 * (1 - (color_temp - 2000) / (6500 - 2000))) | round), 255]|sort)[1] }}```
#

wonder if I can reference the templated light inside itself to avoid hardcoding the minimum and maximum temp 🤔

#

yes it works but then I'm hardcoding the name of the light so not sure that's better 🤣

haughty breach
#

It's been a while since I messed with template lights, but you should have access to the self-referencing variable this, so you may be able to leverage that instead of hardcoding some values.

rose sail
#

@haughty breach do you know if it's possible to set the lock status also as "unlocking" and "locking"?

mighty ledge
inner mesa
#

Locks don't support 'unlocking' or 'locking' intermediate states. Only locked and unlocked.

#

The integration providing your particular lock entities may provide that in the attributes, or maybe not.

plain magnetBOT
#

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

thorny snow
lyric comet
#

I find the simplest way to debug these things is to use a variable action, to set the attribute to a variable and then set the target as a variable. That way you can use the trace to easily see what values are being set.

#

Also you could test the whole if statement in the dev tools does it work there.

silent vector
#

I have a set of sensors and I'm trying to avoid 1 updating with an outlier number as in high number suddenly only for it to drop a few minutes later. Using this method suddenly reduces the number of inputs to 1 or 0 depending on how fast things are updating.

It's almost as if somehow I would need to track each sensors before and after state to ignore their state change and keep the previous state if they jump +5 until the state remains the same for 60 + seconds for example.

{% set humidity_sensors = ['sensor.master_bedroom_temperature_sensor_3_humidity','sensor.master_bedroom_temperature_sensor_2_humidity','sensor.front_door_area_temperature_sensor_humidity','sensor.office_temperature_sensor_humidity'] %}
          {{ expand(humidity_sensors) | selectattr('last_changed','>=',(now() - timedelta(seconds=60))) | map(attribute='state') | list }}
#

The sudden increases can cause issues for my automation as it leads to useless triggers.

haughty breach
silent vector
#

That's an intimidating list of configuration options lol

#

Not sure which to even use.

honest elk
#

Does anyone know if {% elif states... can be used as template sensors in config.yaml?

#

ignore that question.. it works now. I was being impatient

silent vector
naive swan
quick stag
#

Just spent some time re-writing my bindicator script to make it easier to share with a mate that's just jumped down the HA rabbit hole. Previously it was a mishmash of googled bits and pieces: command line / python script to set a sensor to a value based on whether it was an odd or even week number, and if the day of the week was >Thursday then week+1. I then used another template sensor to look at that value and set its own entity_picture based off that (as it didn't seem to work directly on the commandline one).
It's now all together in a single Template sensor, but would love for someone to have a look at it and offer suggestions to tidy it up. I'm sure there's a better way to do the "if its after Thursday then look at next week" bit than just another nested if-then... as well as perhaps setting the entity_picture from within the previous if-thens...
https://dpaste.org/2Mrab

plain magnetBOT
#

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

haughty breach
#

Fix the quote marks and it should be fine...

action:
  - service: xiaomi_miot.set_miot_property
    data:
      entity_id: vacuum.xiaomi_c103_dbe2_robot_cleaner
      siid: 4
      piid: 2
      value: "{{ trigger.to_state.state }}"
lucid thicket
# quick stag Just spent some time re-writing my bindicator script to make it easier to share ...

how about this:

{% set is_after_thu = today_at().isoweekday() > 4 %}
{% set is_even_weeknumber = bool(today_at().isocalendar()[1] % 2) %}
{{ 'Recycling' if (is_after_thu == is_even_weeknumber) else 'Garden' }}

in the new/recommended template format with the icon template:

template:
  - sensor:
      - name: Bindicator
        state: >
          {% set is_after_thu = today_at().isoweekday() > 4 %}
          {% set is_odd_weeknumber = bool(today_at().isocalendar()[1] % 2) %}
          {{ 'Recycling' if (is_after_thu == is_odd_weeknumber) else 'Garden' }}
        entity_picture_template: >
          /local/images/{{ 'bin_yellow.png' if is_state(this.entity_id, 'Recycling') else 'bin_green.png' }}
neon laurel
# haughty breach It's been a while since I messed with template lights, but you should have acces...

ty, wasn't sure if 'this' worked in template lights but it does. I cannot get the short version to work tho.
this works:
state_attr(this.entity_id, 'min_color_temp_kelvin')
this doesn't:
this.min_color_temp_kelvin
Failed to call service light/turn_on. Error rendering data template: UndefinedError: 'homeassistant.helpers.template.TemplateStateFromEntityId object' has no attribute 'min_color_temp_kelvin'

marble jackal
marble jackal
neon laurel
#

thank you

naive swan
# marble jackal You need to check if it's before or after 20:00 for the end time as well, otherw...

Ended up getting it with this

   {% set current_time = now() %} {% set start_time =
   current_time.replace(hour=20, minute=0, second=0, microsecond=0) %} {% if
   current_time.hour >= 20 %}
     {{ start_time + timedelta(days=1) }}
   {% else %}
     {{ start_time }}
   {% endif %}
 end_date_time: >
   {% set current_time = now() %} {% set end_time =
   current_time.replace(hour=20, minute=30, second=0, microsecond=0) %} {% if
   current_time.hour >= 20 %}
     {{ end_time + timedelta(days=1) }}
   {% else %}
     {{ end_time }}
   {% endif %}```
#

This is part of an automation if my automated backup ever fails, can quickly create a calendar event to fix it 🙂

marble jackal
#

Not sure why you do the more complicated replace instead of just using today_at('20:00')

naive swan
#

I was getting errors when it came to the next day event if it was already past the selected time.

worldly plank
#

can I filter out unavailable, unknown, and NULL from my template sensor?
{{state_attr('climate.heat_pump', 'target_temp_high')}}

#

there are a bunch of them in the states table and I only want a record if the value is a number

#

This template listens for the following state changed events:

Entity: climate.heat_pump
clear mist
#

hey guys, i have a time duration field for a script i'm working on - is there a way to split the duration by hour, minute and second? i thought it would be duration[2] for the minutes, but it's actually the second character, not the 2nd item

marble jackal
marble jackal
clear mist
#

well a time selector technically i guess

marble jackal
#

that matters

#

so don't guess 🙂 can you share the code of the script?

plain magnetBOT
#

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

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

clear mist
#

so i'm making a script and have it set up here as a time selector, and i'm calling it from the dev tools sevices menu: https://imgur.com/a/JLMJpTD

the only code i've tried is something along the lines of {% if duration[2] == 0 %} but duration[2] is the second character of my duration, not the second item in my duration - for example if my duration is 12:34:56, i want to get the 34 to separate the minutes, but duration[2] is giving me a result of 2

fickle sand
#

Based on that the character is selected it must be the time selector which provides a string of format HH:MM:SS The duration selector provides a dict

{
  'hours': 12,
  'minutes': 30,
  'seconds': 15
}
marble jackal
#

split on the : character, and then take the 2nd part (which will be 1 as counting starts at 0)

#

duration.split(':')[1]

#

and duration[2] will be : in your example 🙂

#

oh, you already removed your post 🙂

clear mist
#

updating it to 2 did show : as expected, i just can't count today it seems

marble jackal
#

I already posted how to get out the minutes

#

you need to covert it to a number to calculate with it

clear mist
marble jackal
#

that's because you are not using a duration selector, but a time selector

#

duration.split(':')[0] this will give the hours

fickle sand
#

Because you use the time selector that outputs a string 😉

clear mist
#

ahhh, i didn't even see the duration selector - i'm with it now sorry, i thought it was only a time

marble jackal
#

🎉

clear mist
#

that makes it much easier - thanks so much!

fickle sand
#

Dict items also start with 0 so the second item has id 1

marble jackal
#

yeah, but I guess it's more clear to refer to the key 🙂

silent vector
fickle sand
silent vector
plain magnetBOT
#

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

marble jackal
#

@fair elk the forecast attribute has been removed from all weather entities after being depreciated for 7 months

#

you need to change this to a trigger based template sensor so you can use the weather.get_forecasts service call in the action section to retreive the forecast data

fair elk
#

So how should my code roughly look, to include weather.get_forecasts?

fickle sand
silent vector
fickle sand
#

reload all yaml configurations does it

marble jackal
#

that only reloads yaml for config which can be individually reloaded from the list below

fickle sand
marble jackal
#

yep, that's true

fickle sand
marble jackal
#

then it should work, but it will only show in the list after HA started with at least one filter sensor in it

#

so after adding the first one a restart is needed, after that they can probably be reloaded using the yaml reload

#

I don't have any in my config, so I can't check