#templates-archived
1 messages · Page 72 of 1
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
You have () in there
in the name only, but in the entity id it's script.men_guest_room_ac_on16
would it still be a problem?
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
-> States, I don't see why the service call would fail
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
switch.turn_on is nowhere there, which suggests that something is stale
where should I include the switch.turn_on?
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
🤷
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
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?
|int(0)
I think int(0) is more readable
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
@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)
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.
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
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
now() is the current time, that will be 0 seconds ago
"We missed it."
"When?"
"Just now."
"When will then be now?"
"Soon."

@stark vale I converted your message into a file since it's above 15 lines :+1:
@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
For reference see the example from the docs: https://www.home-assistant.io/integrations/integration/#energy
Oh I thought that the new template format also applied to everything else
but even using the other format it doesn't work
The logs could tell you why
I cant find anything in the logs regarding integration
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?
I just woke up, first thought is to check dst
yes, it's because of DST
and good morning
but I would expect it would take that into account
I only have this in configurations.yaml:
mqtt: sensor: ...
template: sensor: ...
`sensor:
- platform: integration
...`
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
2 timestamps? those are already in seconds
{{ timestamp1 - timestamp2 < x }}
or do you mean 2 datetime objects?
{{ datetime1 - datetime2 < timedelta(seconds=x) }}
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
@mighty ledge to come back to my earlier question/comment
Isn't this a bit strange?
ChatGPT?
start1 == start2 and end1 == end2 but the results are different
Not sure what you're asking? I didn't use chatgpt for this.
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
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
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”
the bottom one is, the top one is correct, as there were actually 23 hours
I’m not sure which one is correct
depends on your point of view maybe 😉
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.
But if would have received 1 dollar for every 60 minutes of the day, I would have 23 dollar
I.e. when you fall back, 2am occurs twice
Confused why the difference if I try what I have is
-21117 seconds when the difference is actually
2024-04-02 00:57:02.767431-04:00
2024-04-02 06:49:00.567106-04:00
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
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
I will have a look
anyway, I actually need the 23 here, so I converted it to UTC now to calculate the hours. It works now (in the past)
Yeah but it's way more than 6 hours in seconds
nope
Going in the future, you might have odd results. But if you’re always looking in the past you should be fine
21117.799675 / 3600 = 5.866055465277777
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. 🎉
Oh yeah lol oops my math was off I didn't use a calculator properly
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() }}
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
Is now() | string timezone aware? As that's how I set the value for humidity_automation_memory['humidity_automation_action_time']
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.
Butting into your convo, this was blowing my mind. Was trying to figure out how two variables which equal each other could have different subtraction results. For me it finally clicked when I looked at start1.tzinfo and start2.tzinfo and realized they were not the same. Now the results of the subtractions makes sense to me.
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
Ah. So when you use an explicit time offset (-0500) instead of Americas/Chicago (for example) the dst() method will always return None
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
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() }}
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
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
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
This is a good time for the melting crying emoji. I will study this and probably have more questions later. Thanks for this detail
[[[
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
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
It's not too complicated, but I hate reusing code which makes it LOOK complicated.
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
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
the why is because how it's stored under the hood
Perhaps we should just get rid of DST
Should be computer programmers leading the charge
It's beneficial for your health as well
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.
there's no way without something custom
or browsermod
but you already know those limitations
Yep. I just had a suggestion in #frontend-archived that I'm going to try. Thanks for the info
Do I need to use something like this to avoid issues with dst for my simple logic to get total_seconds?
you don't need anything for dst, that convo was for thefes's question
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?
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?
Yeah it would throw off my logic as I care if total seconds between the two times is < 10 seconds
na it won't, it'll trhow off the calc for 2 10 second spans over the year
you'll be fine
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.
that's assuming your data under the hood is local
As in the time data? I'm referencing in the template
Yeah the var I'm using the value when I create it is now() | string and it gets stored in a sensor attribute.
use utcnow() then
What's the difference between the 2?
it's in utc, the other is local
Essentially it's better to use when calculating seconds of DST is a concern?
in general, it's better to use utc for time calc if you can
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
{% set annoucements.data = announcements.data + [{'foo': 1, 'bar':2}] %}
TemplateRuntimeError: cannot assign attribute on non-namespace object
{% set announcements = namespace(data=[]) %}
{% set annoucements.data = announcements.data + [{'foo': 1, 'bar':2}] %}
{{ announcements }}
You have a typo
I do?
announcements vs annoucements
oh, whoops
Yes
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?
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()
neat, thanks!
-0.0000007
@tired sandal I converted your message into a file since it's above 15 lines :+1:
Ah ok
{{ state_attr('announcements', 'data') }}
produces null
-06 means 6 zeros before it and the decimal place
if it was -7e06 it would be -7000000
Makes sense
it's not an entity
unless you reloaded
then go to developer tools -> states page
yeah it shows up there
ok, then what's the entity_id?
sensor.announcements
so then that's what you use as the first argument in state_attr
Ah. Gotcha!
Yep, that did - thanks!
Random question - is it possible to get all the attributes of a sensor as a dictionary?
Gotcha, thanks!
Template in the template
@tacit sun I converted your message into a file since it's above 15 lines :+1:
I did a quick reload and that fixed it.
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) }}
What kind of trigger is this for?
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.
So, then trigger.to_state.last_changed and so forth
🙂
{{ 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
Wow, that is awesome!
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
heck, I fluked on an additional action:.
You're overwriting sensor
you also have an action in the sensor section
@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:
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 ^
Even better, wasn’t sure there. Will adjust accordingly. Thx
nice! and using this syntax, the template also makes more sense 😉
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
I think I'm doing something wrong. Shouldn't this return false?
{{ ('sprout' and 'feed') in ( 'peachy feed x2' | lower ) }}
no
{% set value = 'peachy feed x2' | lower %}
{{ 'sprout' in value and 'feed' in value }}
Ok thank you.
{{ ('sprout' and 'feed') }} returns 'feed'. Not completely sure why though
I feel like there must be a less repetitive way, but I haven't found it yet
cause python
python returns the last item in the ands if all results are "true" in python eyes
and with or it returns the first one
nope (to rob)
hehe
Both are Truthy
and and or do not return booleans
they return the value that "sparked the statement to pass"
yeah that makes some sense
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
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?
{{ as_datetime(state_attr('calendar.astrokalender', 'start_time')).strftime('%d/%m/%Y') }}
for more options check https://strftime.org
states('sensor.livingroom_tv_sbb') this will always be true it returns a string which will always be considered true
service: notify.mobile_app_pixel_7_pro data: message: >- {{ states.calendar.astrokalender.attributes.message }} {{ states.calendar.astrokalender.attributes.start_time }} title: Astrokalender data: ttl: 0 priority: high notification_icon: mdi:star color: black
Doesnt work in this
you are not using it
Doesn't work 🤷
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
Thats weird, i just changed and execute but still old output and now it works
😅
you should not use states.your.entity.attributes.some_attribute
K thanks 😁
sooo 2024.4 broke my weather template forecast, how can I set the forecast for a weather template? the example in this page doesn't give results https://www.home-assistant.io/integrations/weather.template/
@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
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']
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
you are missing a closing paranthesis in the template (or you could just remove the first opening paranthesis
that has nothing to do with templates, you might want to try #zigbee-archived
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
The action run is working now, but nothing is sent to this group for some reason...
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?
maybe not all group members support that?
support what? If I remove the data and image lines, I get the message without the image.
well that, not all group members support that image part
try the individual group members
It's telegram group, I created 2 groups one I'm using telegram_sendphoto instance and it's working with images
maybe I should use telegram send photo and target id this specific group
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
so I have to write down the id there?
I'm not understanding the relevance of that
my automations.yaml is public in github.
yes, but I don't understand why you would need to specify the target, and can't use the secret
I have no idea why it wouldn't let me... anyway I will write down the id there.
Thanks!
when does it complain about that, what is your yaml then?
Isn't the problem that target expects a integer while !secret ... is basically a string reference
What's the difference between {{ (now() - xyzdatetime).seconds }} and (now() - xyzdatetime).total_seconds }}
is there a way to bypass that?
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
.seconds is a datetime method/property, .total_seconds() is a timedelta method
Idk
to add to this, you need to use total_seconds()
if you run this yaml in devtools > services, do you get that error?
Oh yeah whoops thank you
Where am i can find that icon
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
Those are emoji, not icons
Makes sense I figured it's better to use total_seconds()
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)],
})
how is meta defined?
this is the full code that worked until today
https://github.com/dbuezas/lovelace-plotly-graph-card/discussions/213
thank you so much for your help in advanced
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
there is not way to make this "on the fly" as I had before?
No
Service YAML contains syntax errors, please fix the syntax
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')) }} ! ⚠️.
I don't believe you can use secret expansion outside of the files themselves
I was thinking in those lines as well, maybe try it in a script
a script with just that as the sequence
trying now, thanks!
thank you
Message malformed: Unable to determine action @ data['sequence'][0]
when trying to put that as sequence in a script
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') }} ! ⚠️.
I am struggling trying to pull information from this device's attributes:
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
Are you wrapping that in quotes or using a multi-line notation when you're using that?
FYI that's an entity not a device, and that might be part of your confusion.
and state_attr only gets information out of entities, not devices
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?
This is what I see in dev tools
apologies that I did not include the entity name in the OP
{{ state_attr('sensor.thinksmart_lr_intent', 'intent_output').response.data.success }}
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'
{{ 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?
.split('.')
shouldn't there be a listerener on label_entities()
this works
but it would be nice if expand() wasn't needed 🙂
I don't think any of the *_entities register entity_id's
okay, so I need to use this workaround if I want to replace automations on groups with labels
I think that would be a good feature request. Possibly an argument added to label_entities, listen=True
or something like this
{% set entities = label_entities('always_on') %}
{{ entities | select('is_state', 'off') | list }}
oh wait
ah and is_state() invokes the states function
well
I made a post that highlights what registers listeners
probably can paste it here and pin it
Check out this link to see when a template will update
why is expand blue
it thinks it's some random language
the markdown
I changed it to js so that it looks nice(r)
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?
post the errors, they tell you exactly whats wrong
chances are you don't know how to read them
and share the non working YAML
Please use a code share site to share code or logs, for example:
- https://dpaste.org/ (select YAML for the language, and consider picking a longer expiry)
- http://pastie.org/ (select YAML for the language)
- https://paste.debian.net/ (you guessed it, select YAML as the language)
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.
won't let me save it after pasting it via YAML.
Guess I just caught it at a bad time. I commented it out. Waited a bit. Tried again. And it updated without error 🤷
Yeah, I realized I missed the deprecation
this is what I had, is there a way I can keep using the forecast from weather.home_2 ?
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']
I've made a PR to update the docs for weather template
Here is how my proposed update looks like, it includes an example to get the forecast data
https://deploy-preview-32163--home-assistant-docs.netlify.app/integrations/weather.template/
thank you that should be enough, so new solution requires an intermediate sensor that is populated from the service call, a little more convoluted IMO but if it works
oh nevermind! I was missing an endif
one question where are the defaults for time_pattern documented? I don't see them here https://www.home-assistant.io/docs/automation/trigger/#time-pattern-trigger is it 0 * or someting else
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?
@rocky crypt
And see the convo right above you, I linked that specific message to you in #frontend-archived
@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
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
Hmm. I'm so lost 😦 I guess I'll have to really research and figure this one out. Wonder why such a complex change??
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
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
this is the way
@rocky crypt see what I said in #frontend-archived
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:
...
FYI that doesn't check the high
that checks the temperature of this hour...
and in the most verbose way possible 🙂
yep
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?
Yeah, but if you want to replicate that just use the temperature you stated existed in #frontend-archived
Forecast does not return high
it returns the temperature for each hour
0 is the current hour
It does when there is also a templow attribute
Gotcha. Then, I apparently had it wrong form the begining. I deffenitly want it to pull the high for the day.
but he's not using that
(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)
This is a condition in the action part, right? So it should be possible
Correct.
@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?
Yes. And there isn't.
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...
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 🙂
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...
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...
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
what you have there will work as a template entity
well you have thte time pattern set to once every 3 hours
So I have to wait 3 hours for the first reading?
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)
you have to wait for the timepattern to hit
or just add a startup trigger
@minor jolt I converted your message into a file since it's above 15 lines :+1:
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
it triggers when you reload template entities
it gets the first event summary if the first event exists
Ok. Cool. Thanks @mighty ledge for all your help! I REALLY appreciate it!!!
Ah, i see, when i tried that it actually worked, thanks
The calendar has different types of events, "paper, plastics and garbage", is it possible to sort based on the type and also show the date? (what i am actually trying to do is to show the date of the next garbage pickup is for the different types, but not a calendar)
sure but that all depends on how your items are listed
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)
for daily forecasts the temperature is the highest forecasted temperature of the the day
this is the entity from the plugin
perform the service call in the service caller and post the results here
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"
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.
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"
{% set next_event = garbage.events | select('summary','eq', 'Restavfall') | first %}
{{ next_event.summary }}: {{ (next_event.start | as_datetime | as_local).date() }}
@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?
thanks, I probably misunderstand how this works but i tried putting it in like this:
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.
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() }}
{{ state_attr('sensor.daily_weather_forecast', 'forecast').temperature }}
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
You need to have a trigger and an action section for that to work
I do, that is the same as before, this is the whole thing
@minor jolt I converted your message into a file since it's above 15 lines :+1:
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() }}
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?
It does. I tried it. Does not supply hourly.
ok
there are forum threads on this
the change was made last year
and there are examples in the docs: https://www.home-assistant.io/integrations/weather/#service-weatherget_forecasts
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.
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
I tried that as well, but i still get the unavailble also with this code
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.
My current template.yaml looks like this:
https://dpaste.org/BmiGw
the modified sensor from the forum looks like this:
https://dpaste.org/64acf
Seems like these will be incompatible if I try to merge the two to use forecast
Look in your logs for errors
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
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() }}
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?
You want only the date in the format MM-DD?
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
excellent, works perfectly, thanks a lot bot TheFes and petro, very helpful 🙂
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.
It has to be based on an MQTT trigger, so the way is to create separate trigger-based MQTT sensors.
alright... back to the drawing board 🙂
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?
Your question lacks context
What is 'shield_id'?
And how doesn't it work?
And where is it being used?
Never mind
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?
Trigger-based template sensors now support an action section so that you can call a service, and the response from that service can be used in the template sensor. This example is exactly what you want: https://www.home-assistant.io/integrations/template/#trigger-based-handling-of-service-response-data
Thanks, that looks like a perfect starting point to work from. Much simpler than having to do an automation
Got it all fixed now. Thanks again
that's what I'd like to debug. I'm not sure how to see what these states return. But the "shield_id" is a variable of an input:
https://github.com/kroecks/hass-blueprints/blob/main/play-next-episode.yaml
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
post a screenshot of the entity in developer tools -> states page
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
@alpine prism switch to the new template style, add a trigger and an action.
direct example in docs.
How can I fix my weather template
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?
Close the tag again after the word you want to have big
<big>something</big>
I don't have the ability to paste screenshots here for some reason
@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.
No one does, use Imgur
kk
the above is the "off" state, the second is the "on" state which shows a value for app id
@tacit sun I converted your message into a file since it's above 15 lines :+1:
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. 🙂
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
Looks fine, the only reason it wouldn't work is if you have the app_id incorrect
or if shield_id is worng
@tacit sun start: "{{ today_at('05:00') }}"
that does seem a bit more simple than what I came up with. Thanks!
actually...
I'm pretty new to the template syntax. I was trying to add a log for "state_attr(shield_id, 'app_id')" but i couldn't get it to log
What is the difference between {% %} scopes and {{ }} scopes?
start: >
{% set t = today_at('05:00') %}
{% if now() < t %}
{{ t - timedelta(days=1) }}
{% else %}
{{ t }}
{% endif %}
gotta subtract a day if you're before 5am
check the pins
- "Check out this link to see [when a template will update](https:..."
- "How frequent will a template update? Click [here](comm..."
- "You can do anything in templates"
- "Jinja uses various delimiters in the template strings.
{% %}..." - "you need to use a namespace if you're planning modify a variable..."
- "I see a lot of folks ask for how to know, of a group, who was th..."
- "To count lights which are on, and exclude light groups, note tha..."
- "Jinja (Template) Built-ins jinja.palletsprojects.com/en..."
- "Distinguishing Yaml from Jinja (templates) community.ho..."
- "Confused about the 2022.2 breaking
defaultchange? c..." - "Understanding types to parse JSON community.home-assist..."
- "@689168555861737485 Here's a template that looks up a friendly..."
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.
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'
would this do the same thing?
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) }}"
yes, but it's not optimized
so, what makes it more optimized is that your version only does the time conversion once?
vs 3 in my version?
3 best case
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') }}"
Nice work!
Remove square brackets from result
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
no
meh :/
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
Hi Gang,
I am trying to fix a workaround after 2024.4 update to add a template but i dont get it to work
https://docs.nspanel.pky.eu/stable/prepare_ha/#workaround-for-homeassistant-202404
I get sensor state unknown
@dense vine I converted your message into a file since it's above 15 lines :+1:
anyone that can see something wrong or is this the wrong forum
the only thing that i see is friendly_name: Weather Forecast Daily
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.
{{ 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
you need map('device_id') if it supports that
I wrap all of what is in the curly braces to map('that stuff')?
I don't know what that means, really
Sorry, I'm still really new to the syntax
{{ map (device_id (expand('group.assist_satellites') | map(attribute='attributes.display_device') }}
if it supports it, you would do {{ expand('group.assist_satellites') | map(attribute='attributes.display_device') | map('device_id')|list }}
ahhh.. ok
Yeah, that's a winner. Thanks for your patience and kindness in answering these
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
you can put a template in the secret with a variable or to return the state of an entity
I did wonder about that. Can you elaborate on what that would look like?
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
->
specifically I'm looking at doing something like this
secrets.yaml
ipgeolocation: https://api.ipgeolocation.io/astronomy?apiKey=[redacted]{{ coords }}
sensor.yaml
- platform: rest
scan_interval: 900
resource: !secret ipgeolocation_astronomy_resource
where I would stuff {{coords}} with something like {{ state_attr('zone.home', 'latitude') | round(2) | string }}&long={{ '{:.2f}'.format(state_attr('zone.home', 'longitude')) }}
yes but resource template doesn't support secrets from what I've read
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
you put !secret in the middle there
you cannot do that
as you said in the beginning, put the whole thing in a secret
so even the lat long substitution will still work?
all of it
you may need to construct the string within a single template, but I doubt it
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
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?
first, remove the quotes around false
done. no difference in output
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
do_not_disturb: False
FYI, this is what I see in states
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
it's a boolean, so it should be a boolean
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.
gotcha. Does the case matter when setting?
that view_timeout is a number. should I be handling that without quotes?
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
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?
so I use: - platform: availability_template as well as the above or move the whole thing into the new one?
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
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.
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?
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.
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…
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
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.
@minor jolt I converted your message into a file since it's above 15 lines :+1:
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:
template:
- trigger:
- ...
action:
- ...
sensor:
- name: Sensor 1
- name: Sensor 2
- name: Sensor 3
binary_sensor:
- name: Binary Sensor 1
@heavy crow I converted your message into a file since it's above 15 lines :+1:
omg, ignore me, I was just impatient. I must have a slow update on it
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?
timestamp_custom expects a timestamp, so use as_timestamp instead
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
You're still using timestamp_custom?
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') }}"
state: "{{ as_timestamp(states('sensor.posten_sensor_next')) | timestamp_custom('%d-%m') }}"
ah, so the problem was that i used datetime instead of timestamp?
Correct
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.
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.
ah, i see, thanks
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.
It will be documented in whatever integration you used. What integration are you using?
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?
This is what I tried. I do see the sensor but the forecast attribute does not exist.
https://i.imgur.com/4zV6P6V.png
Any help is most appreciated
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
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...
you would need to replace weather.daily with your weather entity's entity_id
Ok, I thought that, but after not seeing openweathermap in his, I was unsure. Thank you.
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.
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.
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.
Yeah, I've got a few weather entities.
Sad to say but my log is full of entries and I'm having a hard time finding this one. I grepped for 'daily' and did not get back any hits. I am also not being shown an issue.
I have changed to weather.get_forecasts and no difference. I am unsure why I need to use the one with the 's' versus without. They appear to return the same data with the excpetion of the first line.
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
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.
Worked fine for me
The one without the s at the end is depreciated and will be removed in a few months. The one with s at the and supports multiple entities as target
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
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
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'
OHHHHHH
It's as clear as it can be
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.
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.
You should reference this: https://www.home-assistant.io/integrations/weather/#examples
The sensor I created worked except for the temp and humidity. I'll try to see what's wrong with those.
weather is the key for the weather entity. Ignore everything I was saying.
<edit: I removed all the bad information in my previous messages>
Ok, thanks again.
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
I lucked up on that...lol.
if you don't have temperature and humidity sensors with those names ('sensor.outside_temp' and 'sensor.outside_humidity'), then what you have obviously won't work.
I just figured that out. I used sensor.openweathermap_temperature and the same setup for the humidity.
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
Good advice.
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?
This makes me dizzy
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?
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
ugh. that is ugly. I really need a this.raw_state or something
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
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.
@flat cave I converted your message into a file since it's above 15 lines :+1:
The forecast attribute was deprecated, you need to use the weather.get_forecasts service to get the data.
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.
install the beta version of the card
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.
Of which weather card?
{{ integration_entities("zwave_js") | select('in', area_entities('kitchen')) | list}}
the animated card...
Ok
hmm. That was what I was trying, but I was pretty unimpressed by the fact that it appears to be doing an area_entities lookup and search through the list for each integration entity :/ I mean, I don't have enough stuff (yet) that the O(n²) behaviour is really a problem, but still :/
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
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.
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
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.
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
integration_entities('something') returns a list, right? And area_entities('something') also returns a list, right?
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
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)
it's not even a performance issue with thousands
.001 microseconds with thousands of entities
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" :/
i suppose another way to improve this might be to add filters for some set theory operations like ansible has: https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_filters.html#selecting-from-sets-or-lists-set-theory
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
Is it possible to set multiple variables/assignments within a single Jinja block? Or need a new block for each assignment?
what do you mean by "block"?
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
%}```
no, you can't do that
you can test this yourself
-> Templates
TemplateSyntaxError: expected token 'end of statement block', got 'set'
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.
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
) %}
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
%}```
actually, that might not work because you're setting the entity while using it
right
yep, you got it
Thanks friends!
Man Jinja is flexible. So cool! Flipped it to a dict for cleaner referencing.
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
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
true. - I'll remove that
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
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
ok, then get rid of the availabilty and last_changed attribute
I want it to show the last time it showed changed state
every entity shows that
without needing to make an attribute
you making that attribute makes it update once a minute on the minute
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 %}
......```
yeah, you're doing this all wrong
so I am guessing there is a better way 🙂
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
ahhh makes sense
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
also, keep in mind, last_changed is not persistent through restarts
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
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() }}
when I do:
{{ (now() - states('sensor.nas_status') | as_datetime | as_local).total_seconds() }} I get:
AttributeError: 'NoneType' object has no attribute 'tzinfo'
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?
i use Xiaomi Miiot Auto
The supported services are defined on that integration's page: https://www.home-assistant.io/integrations/xiaomi_miio/#xiaomi-mi-robot-vacuum
As it says there, it will utilize the services that exist in the vacuum integration also
if you have further question on how to set it up, head over to #integrations-archived
@rose sail I converted your message into a file since it's above 15 lines :+1:
{{ states('binary_sensor.nas_status') | as_datetime | as_local.total_seconds() }} gets me:
TemplateAssertionError: No filter named 'as_local.total_seconds'.
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.
You’ve got multiple problems. The first, which the error refers to, is exactly what the error says: there is no filter named 'as_local.total_seconds'. If you don’t know what a filter is, this is a great post that shows the difference between a filter and a function (although the point of the post is about using the default argument).
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 }}
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"
start_date_time: >
{% set t = today_at('20:00') %}
{{ t if now() < t else t + timedelta(days=1) }}
Can somebody give me a hint? Thanks
You can define an availability template: https://www.home-assistant.io/integrations/lock.template/#availability_template
I did try with availability_template: "{{ has_value('binary_sensor.shelly_plus_1pm_input_0_input') }}"
The problem still persist
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 }') }}
Use string concatenation
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 ... %}
I am still confused.
Which part needs to change. I understand enough basics. But I made a mix of templates years ago
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] }}"
- name: "mainvalve_120h_count_minutes
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.
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
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.
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?
that's right
@haughty kiln I converted your message into a file since it's above 15 lines :+1:
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?
Well what is the state of the binary sensor during reboot? I assume it is reporting off for a brief period of time after restart before it reports on. You don’t have a problem with your lock, you have a problem with your binary sensor
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
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') }}
Fliar error Nobe default value
Thanks, I fixed all unique_id(s) in my config.
I did change the value_template to be in the same row, it is valid?
value_template: "{{ is_state('binary_sensor.shelly_plus_1pm_input_0_input', 'on') }}"
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"
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
I already had unique_id's but they were set as the lock sensor, using spaces and capital letters. Just removed quotes, replaced spaces with underscore and all minuscole
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)
Tried with new config and still reporting as locked for 12s
And the binary sensor reports correctly that entire time?
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
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?
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
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
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
@neon laurel I converted your message into a file since it's above 15 lines :+1:
i don't. my jinja skills are an F- 😦 i'll give your suggestion a try later, though. thanks!
Do you suggest asking in a different "section" here?
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
Thanks
You can replace the compound if/then with a sort and slice:
{%- set ww_clamped = ([0, warm_white, 255]|sort)[1]%}
{%- set cw_clamped = ([0, cold_white, 255]|sort)[1]%}
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 🤣
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.
@haughty breach do you know if it's possible to set the lock status also as "unlocking" and "locking"?
you can't set states, also please don't tag people. If you want to change the state of an entity, you call a service that tells the device to perform an action that will put it in the desired state that you want.
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.
@thorny snow I converted your message into a file since it's above 15 lines :+1:
Morning everyone, I have the above lines which don't seem to be working. I'm trying to have an mp3 play on a device but I want the entity the mp3 is played on selected based on the attribute. Can someone point out my error?
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.
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.
Have you considered one (or more) of the options from the filter integration?
That's an intimidating list of configuration options lol
Not sure which to even use.
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
Anyone have any ideas on what options I should use
Thanks Fes 🙂 so for the end time I'd just replace the 20:00 yeah but keep the rest of it?
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
@crimson lichen I converted your message into a file since it's above 15 lines :+1:
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 }}"
Many thanks.
Its work
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' }}
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'
this.attributes.min_color_temp_kelvin
You need to access the attributes section first
You need to check if it's before or after 20:00 for the end time as well, otherwise you might set the end time to 22:00 today (assuming the duration of the event is 2 hours) and the start time to 20:00 tomorrow
thank you
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 🙂
Not sure why you do the more complicated replace instead of just using today_at('20:00')
I was getting errors when it came to the next day event if it was already past the selected time.
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
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
What is the full code of the template sensor
How are you providing the duration? As a string, or are you using the duration selector?
i'm using a duration selector
well a time selector technically i guess
Please use a code share site to share code or logs, for example:
- https://dpaste.org/ (select YAML for the language, and consider picking a longer expiry)
- http://pastie.org/ (select YAML for the language)
- https://paste.debian.net/ (you guessed it, select YAML as the language)
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.
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
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
}
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 🙂
yeah sorry, i thought i had it up but my test had duration[3], which was giving 3
updating it to 2 did show : as expected, i just can't count today it seems
I already posted how to get out the minutes
you need to covert it to a number to calculate with it
i'm not quite sure how to use this - do i do something like (this is just for testing purposes):
metadata: {}
data:
value: "{{ duration['hours'] }}"
target:
entity_id: input_text.testtext```
when i try this, it doesn't work for some reason?
that's because you are not using a duration selector, but a time selector
duration.split(':')[0] this will give the hours
Because you use the time selector that outputs a string 😉
ahhh, i didn't even see the duration selector - i'm with it now sorry, i thought it was only a time
🎉
that makes it much easier - thanks so much!
Dict items also start with 0 so the second item has id 1
yeah, but I guess it's more clear to refer to the key 🙂
Raising this again. I set up
- platform: filter
name: "Office Humidity Sensor Filtered"
entity_id: sensor.office_temperature_sensor_humidity
filters:
- filter: outlier
window_size: 4
radius: 2.0
Is there way to do something similar with a template?
Of course you can do that, a filter is nothing more than some math application on a dataset. But the filter has it all built in for you so why bother?
It doesn't seem like it gets a lot of attention since it can't be reloaded via the UI like templates can for example.
@fair elk I converted your message into a file since it's above 15 lines :+1:
@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
So how should my code roughly look, to include weather.get_forecasts?
You mean the configuration can not be reloaded through the UI?
Yeah it can't.
reload all yaml configurations does it
that only reloads yaml for config which can be individually reloaded from the list below
roughly like documented here in the 1st example https://www.home-assistant.io/integrations/weather/#examples
That makes all very misleading...
yep, that's true
Although there seems to be a service for it https://github.com/home-assistant/core/blob/dev/homeassistant/components/filter/strings.json