#templates-archived
1 messages ยท Page 45 of 1
Okay, any log messages now
Okay, open the log again
First occurred: 11:44:49 AM (1 occurrences)
Last logged: 11:44:49 AM
Invalid config for [template]: invalid template (TemplateSyntaxError: unexpected char "'" at 118) for dictionary value @ data['sensor'][0]['state']. Got "{% set inside = states('sensor.studio_temperature') | float %} {% set outside = state_attr('weather.home', temperature') %} {{ min(inside, outside) }}\n" invalid template (TemplateSyntaxError: unexpected char "'" at 93) for dictionary value @ data['sensor'][0]['availability']. Got "{{ states('sensor.temperature_sensor') | is_number and state_attr('weather.home', temperature') | is_number }}". (See /config/configuration.yaml, line 10).
same eror I think, new timestamp
wait
am I issing a ' at the start of temperature ?
https://discordapp.com/channels/330944238910963714/672223497736421388/1123983894367195257
The system cannot restart because the configuration is not valid: Error loading /config/configuration.yaml: while parsing a block mapping in "/config/templates.yaml", line 11, column 7 expected <block end>, but found '<scalar>' in "/config/templates.yaml", line 11, column 32
you have backticks...
use quotes that don't match interior quotes
or multiline notation
OK fixed that, and put a|| float after weather.home. itis probably unnecessary but it looks neater
the sensore has reappered
but it is showing state ;unkown'
unkown
unknown goddamit
ValueError: Template error: float got invalid input 'unknown' when rendering template 'template:
and the the text from config, and then complainign about not having a default set
oh my bad this time
I had setudio_temperatur instead of temperature_senosr
that was the olld name then I changed it
Ill correct that ehn I think it should work
yay !! working now !

Original sensor:
sensor.ttgo_poe_001_zone01_state
ttgo-poe-001 Zone01 State: OK
icon: mdi:door
friendly_name: ttgo-poe-001 Zone01 State
Binary translation of above sensor
binary_sensor.alarmo_zone_01_state
Alarmo Zone 01 State: unavailable
friendly_name: Alarmo Zone 01 State
Changed code here in the thread ignore the txt. Not sure if I corrected it properly?
https://discordapp.com/channels/330944238910963714/672223497736421388/1123983894367195257
Sorry I'm not totally understanding.
The sensor.ttgo_poe_001_zone01_state that it is looking at currently says OK yet the binary clone is showing unavailable
@tulip ibex I converted your message into a file since it's above 15 lines :+1:
What value do you want the sensor to get you can not set a sensor state to the whole list. You could set the list into the attributes for the sensor.
attributes:
source_value: "{{states("sensor.alarm_front_door_state")}}"
availability: > {{ states("sensor.alarmo_front_door_state") in ['OK', 'ALARM'] }}
You are using two different sensors here, surely they should be the same and both should be your original sensor
NonaSuomy, you haven't fixed any of the changes I said
this is a backtick `
that's wrong in your template
you also have the multiline notation >
but you have everything on the same line
move it to the next line
and by it, i mean the template
i.e. everything inside {{ }}
I don't see any backticks at the end of that thread
...
I feel like you guys are looking at the txt file instead of the thread under it
Yeah the text file not the thread below it.
there is no thread below it
@echo shard I converted your message into a file since it's above 15 lines :+1:
This is so frustrating, even when I set the state to 'on' it still comes through as off / Away???!
No errors in the logs, no help whatsoever to debug it ๐ฆ Feel like I waste ages trying to decode the YAML syntax rather than actually every achieving anything
OK, the following works:
- binary_sensor:
- name: "Craig's iPhone connected to Home Wifi"
device_class: presence
state: "{{ is_state('sensor.craigs_iphone_bssid', state_attr('input_select.home_bssid', 'options')) }}"
Yes, that was what I was about to suggest
So maybe only the homeassistant start trigger was firing...
I was wondering why you were using a trigger based template sensor here
I think I saw in a tutorial somewhere that you need to force an update on start for some reason...
But I wonder why the trigger doesn't fire
Not for state based template sensors
hey, I got this template which working fine
http://pastie.org/p/4VGBV5oiZumbJnRcYGcRve
now I have got new reolink camera and did added an option to my automation that I will receive the sub image when the automation is triggered, however I cannot put this template into the 'caption' of the Telegram send photo
service: telegram_bot.send_photo
data:
authentication: digest
file: /config/www/tmp/snapshot_aquarium_sub.jpg
caption: test
I tried to change the caption to the "message" that in the link that I sent above, it did created an error.
Is there a way to use this template inside service like telegram_bot.send_photo?
This is the entire automation yaml if needed:
http://pastie.org/p/1Q2YUwhrozTC9oCf2cUjXZ
Btw, finally tested this and it worked great!
"Hello, {USER}. Welcome to Our Home!
Motion detected in 3 rooms, (2 downstairs and 1 upstairs). The average temperature inside is 70.9ยฐF, (70.6ยฐF downstairs & 71.3ยฐF upstairs). The sun rose 5 hours ago."
I stole that sun rose code from the template in Developer Tools - anyone know how to make one that will also say "The sun will set in {X} hours. / The sun set {X} hours ago" ? ๐
The Sunrise and Sunset fields are always the next ones, so you will need to create some helpers to contain the previous ones then check if the current value is on the same date or the next day and get the previous one. It was something I was looking to do, but I have not had time to build all the elements.
yep. first bit is easy. the second bit less so. however if you only care about the number of hours, you can cheat
Hours literally only, or minutes as well?
{% if ( s < 46400) %} {{ (s // 3600) |int }} hours till sunset
{% else %}
{{ (((s-86400)*-1) // 3600) | int }} hours past sunset
{% endif %} ```
Might need to adjust numbers a little. that 46400 for example
you can cheat with hours, because sunset doesn't move that much
if you want to cheat less, then do what Jane_T says. have an automation which goes off early in the day to save the next_setting into an helper. then refer to that.
how can I test if a variable is null -- I am trying to condition on null parent_id's in triggers
=='' doesn't seem to behave wel
The sun rose {{ relative_time(states.sun.sun.last_changed) }} ago.
{%- else -%}
The sun will rise at {{ as_timestamp(state_attr("sun.sun", "next_rising")) | timestamp_local }}.
{%- endif %}```
This is the code for the sunrise one. Could I do something similar with an if/else to make two separate sentances?
"The sun will set in x hours."
"The sun set x hours ago."
Maybe using "below_horizon"?
in a template, test for not is defined
if not variable is defined
That seems like a reasonable option
Hmm - this still doesn't seem to work: in my trigger I have
context:
id: 01H44AQ59HYG98SVVK59WSPDQX
parent_id: null
user_id: a0b44a5b08a84cbf912658588c58bca7
And yet "{{not trigger.to_state.context.parent_id is defined}}" seems to evaluate to false
alias: "Iphone battery above 50%"
condition: template
value_template: "{{ (state_attr('device_tracker.iphone', 'battery_level')|int) > 50 }}"```
hmm. actually no, looks like it does also work that way
I used the easy_time macros from https://github.com/Petro31/easy-time-jinja
{% from "easy_time.jinja" import easy_time %}
{% set diff_rose = as_timestamp(states('input_datetime.sun_rise_today'))
< as_timestamp(now()) %}
{% set diff_set = as_timestamp(states('input_datetime.sun_set_today'))
< as_timestamp(now()) %}
The sun {{'rose' if diff_rose}}{{ 'will rise in' if not diff_rose }} {{easy_time('input_datetime.sun_rise_today')}} {{ 'ago' if diff_rose }}
and {{ 'set' if diff_set }}{{ 'will set in' if not diff_set }} {{easy_time('input_datetime.sun_set_today')}} {{ 'ago' if diff_set }}
It is defined
having set up two date time helpers which are set using
Use
"{{ trigger.to_state.context.parent_id is not none }}"
@lyric comet I converted your message into a file since it's above 15 lines :+1:
Why are we making a datetime for that?
IIRC there's already sun entities with those times
Ah, why would you want it tho after? Just curious
"The sun set X ago"
ah
and someone else was dealing with automations which switched stuff off a few hours after solar noon, because they were getting solar power.
I used helpers, as I thought they would be simpler for the OP to use. it would be more elegant to make trigger template sensors, but they need YAML confidence to use.
(elegance is overrated ๐ )
@lyric comet how can I use that code you sent me? It doesn't work in the mark-down but it looks like a manual sensor code or something, but I'm still so new to this.
That is simply template code for mark downs, but as I said you need to install easy_time the details are in the link I posted along side it
You also need to set up the two helper entities and add in the automation.
What's the best way to deal with: 'ZeroDivisionError: float division by zero'? When it's inevitable that one sensor goes "0".
Shouldn't availability deal with it?
availability: "{{ states('sensor.XXX') | float > 0 }}"
{{ (4.186*(80000*(58-states('sensor.heater_temperature')|float(0)))/states('sensor.heater_watts')|float(0)) | round(0) }}
It's inevitable that the sensor.heater_watts will be at 0, at some point.
availability: "{{ states('sensor.heater_watts') not in ['0', 'unavailable', 'unknown', 'none'] }}"
This also, doesn't do the trick...
That did the trick! Thanks
I would do something like:```
{% set watt = states('sensor.heater_watts')| default(0) | float(0) %}
{% if watt > 0 %}
{{ (4.186*(80000*(58-states('sensor.heater_temperature')|float(0)))/watts) | round(0) }}
{% else %}
{# What ever value you want #}
{% endif %}
You should always provide a default value or you will get errors when the template is evaluated before the sensors are loaded.
hi, I am from Argentina and I need your help
after the HA updates I can red an MQTT string in a mqtt sensor configuration
Json Example:
@humble lichen I converted your message into a file since it's above 15 lines :+1:
mqtt:
- name: "Maquina id 1 Mac"
state_topic: "talleresBanfield/fabrica/produccion/monitoreo"
value_template: >
{% if value_json['1'].mac is defined %}
{{value_json['1'].mac }}
{% else %}
{{ states('sensor.maquina_id_1_Mac') }}
{% endif %}
@lyric comet Is there a way to add a second condition, something like: {% if watt > 0 | temperature > 58 %} , after defining the '58', in the equation, as 'temperature'?
As it is, when the temperature goes beyond '58' the result gets negative...
{% if watts > 0 and temperature > 58 %}
Did it.
but not any more, only numbers can be
@humble lichen I converted your message into a file since it's above 15 lines :+1:
the ['1'] doesn't match the JSON input your provided
is there more to the JSON that you didn't post?
Out of interest, I found a slightly tidyier way to format the sentence.
{% from "easy_time.jinja" import easy_time %}
{% set diff_rose = as_timestamp(states('input_datetime.sun_rise_today')) < as_timestamp(now()) %}
{% set diff_set = as_timestamp(states('input_datetime.sun_set_today')) < as_timestamp(now()) %}
{{-('The sun will rise in %s and ' | format(easy_time('input_datetime.sun_rise_today'))) if not diff_rose}}
{{- ('The sun rose %s ago and ' | format(easy_time('input_datetime.sun_rise_today'))) if diff_rose}}
{{-('will set in %s' | format(easy_time('input_datetime.sun_set_today'))) if diff_set}}
{{- ('set %s ago' | format(easy_time('input_datetime.sun_set_today'))) if not diff_set}}
is there a reason you use as_timestamp so often?
it's best to avoid it if you can because it doesn't always take TZ into account
e.g.
{% set diff_rose = states('input_datetime.sun_rise_today') | as_datetime < now() %}
it's best to use datetime objects which are TZ aware
How do I get one from a sensor?
states('sensor.xyz') | as_datetime
Thanks I will change my template over.
assuming it's the state and it's a timestamp sensor
Is now() a datetime object or do I need a different method
those input datetimes will need a | as_datetime | as_local
yes, now is a datetime object
it makes it easy to offset times too
Excellent. I just picked up as_datetime from examples.
e.g. {{ now() + timedelta(hours=45) }}
or
e.g. {{ now() + timedelta(hours=45, minutes=32, seconds=12) }}
Looks good, I try and read the docs as much as possible, but some of the jinja2 stuff is a bit scattered.
I will try those out on the template trigger sensor I am building to avoid the input_datetime fields and to give me a sun_plus sensor, with todays dawn and dusk and solar noon as attributes.
I think I have seen a time difference as well haven't I?
what do you mean?
((sunset - sunrise) / 2 ) + sunrise = solar_noon
Yeah
I will go off and play now, thanks for the instructions
{% set sunrise = states('input_datetime.sun_rise_today') | as_datetime | as_local %}
{% set sunset = states('input_datetime.sun_set_today') | as_datetime | as_local %}
{{ sunrise + (sunset-sunrise) / 2 }}
FYI, jinja uses pedmas
oh, you can just divide a timedelta in half
parenthesis, exponent, division, multiplication, addition, subtraction. Applied in that order
I'm 99% sure you can
Let me check ๐คฃ
yep
ah, nice
(Everyone should use UTC. keep things simple)
The whole point of them is to make math easy with time, so I just assumed it worked
with datetimes, it doesn't matter what TZ you use
it handles it all for you
input_datetimes are not TZ aware, so you have to use as_local
unless you made it UTC
other than that, if it has a TZ attached to the timestring, just use as_datetime and don't care about the TZ
I'm meaning in all things. So I can tell an American I'm going to talk to them at 4pm and no conversion is needed ๐ Sure, it might mean that Australians are getting out of bed at 9pm, but still ๐
And instead of summertime, we just do everything 1 hour earlier in the months April - October?
(assuming northern hemisphere)
probably, what do you want to achieve?
If you start with states.calander you already only have the calendar entitties
ok, thanks
you can't use wildcard format, you have to use regex or jinja's version of wildcards
what's jinja's version of wildcards? ๐
i hate regex ๐
ah
"airquotes"
or search if it's somewhere in the middle
around jinja's widlcards
we can help you with the regex
all fine, i use now mutpile actions :), better to read and unterstand it later
working in the community, but this is an isolated thing: how to set an empty list as default? {% set msgs = state_attr('sensor.persistent_notifications','notifications')|default([]) %} {{msgs|count}} throws errors on reloading:TypeError: object of type 'NoneType' has no len()')
none is valid, so it won't apply the default
use | default([], true) to apply the default when the input is none
or that ๐
I consider using that style "voodoo" because I have to look up how it works every time I use it
it does work though ๐ like it
Yes, it will work
but it gets complicated if notifications is anything other than a list or None
which won't happen
But if it did happen.... shit gets weird
you wrote some template a long time ago which provided more details about it, when I tried to look for them I could't find them anymore ๐
I've copied Fes' answer too for when I run into trouble..
yeah, you can do a simple test to see all the fucntionlity
writing it now
sec
@marble jackal https://dpaste.org/Sj5hM
that's the code if you want to run it
here's the output
the bad or bad is where voodoo happens
Oh, I guess I just learned the voodoo
by doing that table ๐คฃ
bad or bad chooses the 2nd arg every time
TIL
no more voodoo
the last good or bad is labeled wrong, thats bad or bad
and good or good appears to always choose the first item
whcih makes sense because it bails when it finds something good
indeed, makes sense
0:00:00 | [0] -> [0]
0:00:00 | {0: 0} -> {0: 0}
0:00:00 | 1 -> 1
0:00:00 | True -> True
0:00:00 | 0 -> 0
0:00:00 | 0:00:00 -> 0:00:00
``` it takes the 2nd one here
but it's still good, as shown in the last one
the only thing that is sometimes run into with these kind of things is that I actually need 0 as a valid value
That might be a unique scenario for timedelta objects
0's might return 'false'
so that might not be "good"
I was just trying to find that opposite of None, which is a populated object
but timedeltas probably have an implemented or override
Well, what I sometimes do (which is related) is using | select(), but that filters out 0 as well
nice trick, yes that's related for sure
Thanks for the help earlier with the solar noon. I have done a new trigger template which will get tested at 5 past midnight tonight. ๐ซฐ
Hi any idea's on how to create a sensor that shows the date and time of when a file was last updated?
command line sensor?
Hmm let me look into that thanks
stat is an appropriate command to use to get the last modification time of a file
stat -c "%y" filename
Oh that is cool, let me give this a try, thanks!
(you might want to use %Y to get it as a timestamp.)
This if to create a time-stamp of a camera snapshot jpg file (the camera does not support time-date stamp on the photo). How would the output of this sensor look like as written?
command_line:
- sensor:
name: Bird Feeder Snapshot
command: "stat -c "%Y" /local/bird_feeder/blink_camera_still_image.jpg"
scan_interval: 1800
i'm wondering if I need a value template if its some number in seconds from 1970 ๐
something like this, maybe
command_line:
- sensor:
name: Bird Feeder Snapshot
command: "stat -c "%Y" /local/bird_feeder/blink_camera_still_image.jpg"
scan_interval: 1800
value_template: "{{ value | timestamp_local }}"
correct, 30 min is what I'm looking for
๐
ahhh. I see an issue.
replace the "%Y" with '%Y'
using double quotes there will conflict with the double quotes around the whole thing
oh good catch, thanks I would not have noticed that
do I need a device class?
like number or something
I think you're good without
I think it's just going to store as a string.
(I think what I said was out of date, so I'm stripping it out)
if you do assign a device class, I think you'll probably want timestamp
I was looking for that list, thanks for finding it for me!
I'm having some word issue with the syntax of setting this command line sensor. I know this was changed in the last release, I'm using the !include function where I refer to a command_line.yaml file, But if you have 2 sensors and following the example in the documentation, it seems to fail just regular syntax checking.
It seems I cannot use the appended file with !include when setting up command line sensors
command_line:
- sensor:
command: SENSOR_COMMAND
- sensor:
command: SENSOR_COMMAND_2
If I remove the first 2 lines from this and then make it left most in the command_line.yaml file it fails syntax
so you're doing like
name: my nifty sensor
command: mycommandhere
- sensor:
name: my other nifty sensor
command: myothercommandhere
in a file you included with something like
command_line: !include command_line.yaml
?
what's the syntax error?
Oh never mind, of course. It was the double quotation versus single quotation. I completely mis-read your message, LOL.
HA restarted, but there was a couple of issues in the logs for this sensor. Any ideas?
Actually, when I put that command right into terminal, it says no such file or directory.
But that's not true, it actually is there, and it does exist. So might be a permission issue?
OK the path should be
config/www/....
rather than local.That works!
Thanks for your help and patience ๐ mission accomplished.
I have been tinkering with the Sun settings to store todays using a trigger template when the midnight value change on sun. Any comments or suggestions for improvements - http://pastie.org/p/2jkX4G7uzp9RPseXjjdixL
I don't think the this variable is available in the trigger, and if it is, you should use this.entity_id in that template for the trigger
But I would advice to just use the entity_id, and not refer to the this object there
Thanks, I will change it back over to the standard format. See how that works tonight.
As a test, you can set the state of the entity trigger in rhe dev tools so you don't have to wait.
So I would like to monitor how long has an automation has run. based on
last_triggered
I can get that time string, how can I compare that string with a time duration for exmaple 30 seconds?
{{now() - state_attr('automation.sofa_light_ikea','last_triggered')}}
timedelta(seconds=30)
thanks I found if I do it this way it's a string ''0:00:00.000000'' it's a string
and i was searching for a way to convert this string to that time type
Ok, I thought I solved this issue, but it seems not. Here's the yaml for a sensor that I simply want to know the last time it was modified:
- sensor:
name: Bird Feeder Snapshot
command: "stat -c '%Y' /config/www/bird_feeder/blink_camera_still_image.jpg"
scan_interval: 600
value_template: "{{ value | timestamp_local }}"
device_class: timestamp
unique_id: db187e8e-867e-4fb1-9d5e-c9f7ab9d8d84
but the sensor state is unknown and the error message is here:
http://pastie.org/p/7in6mqG9T2ZCYnyG1JTzrt
am I missing like a | float or something somewhere? thanks
Does HA light entity has something like a previous state
So by refering to it I can set the light to the previous status?
no that's not stored
make a scene snapshot if you want to save a state for recall later
okay a scen it is. will check on that thanks
I don't know what you mean by that.
{{ now() - state_attr('automation.alarm_armed', 'last_triggered') }}
{{ now() - state_attr('automation.alarm_armed', 'last_triggered') > timedelta(hours=12) }}
->
13:56:18.660600
True
thanks I also figured it out.
i wanted to do that mainly to quit an automation if it hangs
I mean it's quite a large automation so there can be many unexpected behaviors but if it runs longer than say 20 seconds it will just quit
Hi, I have used the scene.create and scene.turn_on but it seems not the right scene is restored
The create scene part:```
service: light.turn_on
data:
hs_color:
- "{{ range(360)|random }}"
- "{{ range(40,80)|random }}"
brightness: "{{ range(1,255)|random }}"
transition: 0.2
target:
entity_id: light.0x6c5cb1fffe6882ca
service: scene.create
data:
scene_id: sofa_light_prev_state
entities: light.0x6c5cb1fffe6882ca
snapshot_entities: light.0x6c5cb1fffe6882ca
On another branch the turn on scene part:```
service: scene.turn_on
data:
transition: 0.2
target:
entity_id: scene.sofa_light_prev_state
I doubt you want both of these:
entities: light.0x6c5cb1fffe6882ca
snapshot_entities: light.0x6c5cb1fffe6882ca
I also tried removing the entities line and it's still the same
So the first part of the code creates a scene and gives the light a random hs_color. And the 2nd part turns on that scene. But after the random color action, executing part 2 (scene turn on part) does not restore the color to the previous one before the random color
you're running scene.create before light.turn_on right?
so you created the scene after you set it to the new value
yeah sorry I also realized that and corrected that so now it's create scene first and random 2nd
but still it's the same. when i turn on that scene no matter what color previously it will restore to a yellowish color
service: scene.create
data:
scene_id: sofa_light_prev_state
snapshot_entities: light.0x6c5cb1fffe6882ca
service: light.turn_on
data:
hs_color:
- "{{ range(360)|random }}"
- "{{ range(40,80)|random }}"
brightness: "{{ range(1,255)|random }}"
transition: 0.2
target:
entity_id: light.0x6c5cb1fffe6882ca
service: scene.turn_on
data:
transition: 0.2
target:
entity_id: scene.sofa_light_prev_state
Just to be clear this is my now code
I am using the Radio Thermostat integration and struggling trying to create sensors to enable graphing of the hourly HVAC runtime, target temp and actual temp over time (would like 2 yr to enable yoy reporting.
I would like to get some feedback on my template configuration.yaml file additions. I an a newb with HA but I have spent a lot of RTFM time. I have et to successfull create anything but I feel like I am getting closer to understanding the plumbing. Need a helping hand to get me over the hill.
just share what you have and your questions
@tight hinge I converted your message into a file since it's above 15 lines :+1:
Or maybe int as in:
value_template: "{{ value | int | timestamp_local }}"
check the automation traces.
Do I have to put all the command_line sensors together in config? I would like to intersperse command_line with templates, ... and keep things that are logically connected (e.g., sensor, battery of sensor, derived sensors or sensor, ...) together
It doesn't seem to like having the device_class defined, the following works for me:
- sensor:
name: Bird Feeder Snapshot
command: 'stat /config/www/bird_feeder/blink_camera_still_image.jpg -c %Y'
scan_interval: 600
value_template: |-
{{value|as_datetime|as_local}}
unique_id: db187e8e-867e-4fb1-9d5e-c9f7ab9d8d84
It tolerates having device_class set via customization.
@faint gyro to the rescue! Thanks I will use your template. Cheers bud!
I never knew about these packages! This looks promising. I'll play with it more. It may even more strongly enforce a structure inside by (scattered) config file. Thanks!
What part should I check on trace?
So this is working now. It achieves right clicks assigning random color to light and one left click restores the previous randomly assigned color
But it can only restore once since I only have 1 scene and 1 snapshot.
Is there a way to create multiple snapshots of a scene and scene.turn_on you can choose which snapshot to restore?
I am trying to create a template sensor based on attributes of 2 sensors to calculate average rainfall. Added the below code to configuration.yaml without issue but I cannot seem to be able to find the sensor.
template:
- trigger:
- platform: time_pattern
minutes: 1
- sensor:
- unique_id: current_ave_rainfall
name: "Current Ave Rainfall"
unit_of_measurement: "mm"
state_class: measurement
device_class: precipitation
state: >
{{ ((state_attr('sensor.tp_rainfall', 'Value') + state_attr('sensor.ts_rainfall', 'Value')) / 2)
@shut flint To format your text as code, enter three backticks on the first line, press Shift+Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks.
```yaml
example: here
```
Don't forget you can edit your post rather than repeatedly posting the same thing.
@shut flint are you sure there is actually an attribute called Value? Check this in:
Open your Home Assistant instance and show your state developer tools
My guess is you actually want the sensor state
Which you can get with states('sensor.foo')
Do note that states are always strings, so you need to convert it to a number using | float or | int
I'm trying to extract some json attributes from my airtags json file. HA can pull the file, but I'm told it's not a dictionary. Jsonpathfinder would leave me to believe I'm calling the right path. Example JSON and and YAML posted here for anyone that might be able to help: https://pastebin.com/LtYC1pxi
I don't see timestamp in location
"location" : null
I did a lot of sanitizing
Oh wait, you're right
I have a lot of other json type things set up that work fine, so I'm not sure what I'm missing here
This thread is what makes me think I'm not far off: https://community.home-assistant.io/t/how-to-configure-value-template-to-extract-data-from-json-array-without-name/384094/3?u=bobby
Can you post the actual error?
HA
Ok, and this is a rest sensor?
No, it's a command_line sensor
Ok then your command isnโt working
It may be working, but you may be using json attributes which would cause the error
Are you using jsonattibutes?
Ah yes you are
Thatโs the problem
Json attributes are expecting a dict
Your endpoint returns a list
Transform it into a dict and you should be good
I guess I don't know how to do that
I donโt have it memorized
Because it keeps telling me it is a dictionary
Itโs not though
And I've tried using jq to change that
What you output above is a list of dicts
Oh an array
Yes
Which I thought was fairly normal
And gets referenced in that thread above
Yeah but thatโs the rest integration
I didn't realized that rest and command_line would treat the data any differently
All integrations are different
True, but I thought the method use to handle the data would be part of some underlying shared library
Nope
So I'm left trying to do some sort of data massaging to use the airtag json file I'm retrieving via ssh
Because rest can't use ssh
I would imagine
Thereโs a way to use command line to transform the data
You should look into that
I think itโs as simple ass plopping it into another dictionary so you can call out a single attribute that contains all the information
Looking for it now
Command central did it on the forums replying to me about a year or so ago
I feel like I've already tried this. I end up with the error: homeassistant.exceptions.InvalidStateError: Invalid state encountered for entity ID: sensor.find_my. State max length is 255 characters.
Which is why folks want to send their json to state attributes that don't have the length restriction
Yep, I put "OK" or the retrieval datetime in the State and then use template sensors to pull out what I need from command results.
@sonic sand I converted your message into a file since it's above 15 lines :+1:
In other words, I want to somehow implement this template into the telegram_bot.send_photo action, if it's possible as the caption of the photo; instead of having 2 messages which spam my telegram.
Is there a means in jinja (filter etc) to turn an integer into written numerals? like, int(73) | something == "seventy three"?
I use this to get HA to read telephone numbers: {% set value = "123" %} {%- set number_list = [ 'oh','one','two','three','four', 'five','six','seven','eight','nine' ] -%} {%- set out_number = namespace(value = ' ') -%} {%- for c in value %} {%- if c != '-' %} {% set out_number.value = out_number.value + ' ' + number_list[c|int] -%}{%- endif %} {%- endfor %} {{out_number.value}}
There might well be an easier way.
that's a starting point!
How big can the numbers get?
in my situation, reading off temperatures in ยฐF, so from below zero to a hundred and some change.
correct!
You could create a list with the written out numbers 0 to 19
And a second list with 20, 30, .., 100
No mappings would be better
{% set value = -20 %}
{% set v = value | abs %}
{% set m1 = {
2: "twenty",
3: "thirty"
}
%}
{% set m2 = {
1: "one",
2: "two",
18: "eighteen",
19: "nineteen"
}
%}
{% set a = v // 10 %}
{% set b = v % 10 %}
{% if v == 0 %}
zero
{% else %}
{{ 'minus' if value < 0 }} {{ m1[a] if v >= 20 }} {{ m2[b if v >= 20 else v] | default() }}
{% endif %}
Something like this
Just add the missing values in the mappings
{% set numbers = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"] %}
{% set tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"] %}
{%- macro to_words(n) -%}
{%- if n < 0 -%}
negative {{ to_words(-n) }}
{%- elif n < 20 -%}
{{- numbers[n] -}}
{%- elif n < 100 -%}
{{- tens[n // 10] }} {{ numbers[n % 10] if n % 10 != 0 else "" -}}
{%- else -%}
{{- numbers[n // 100] }} hundred {{ to_words(n % 100) if n % 100 != 0 else "" -}}
{%- endif -%}
{%- endmacro -%}
I had GPT-4 walk me through this answer. It works well! I did constrain the input values to -199 to 199, but it seems to work within that range in my limited testing.
to_words(73): seventy three
to_words(173): one hundred seventy three
to_words(17): seventeen
to_words(-17): negative seventeen
to_words(0): zero
Okay, mine works for -99 to +99, but could be adjusted to work with hundreds as well
yeah it turns out this works from -999 to 999 kinda for free
the more i look at this the more i dig it, the recursion for negative values is clever. i doubt i would have come up with this on my own, can't take much credit for the machine here.
It's kinda funny the macro uses itself
Okay, final version of my approach, which works from -1999 to 1999 if the mappings would be complete
{% set value = 111 %}
{% set v = value | abs %}
{% set m1 = {
2: "twenty",
3: "thirty"
}
%}
{% set m2 = {
1: "one",
2: "two",
11: "eleven",
18: "eighteen",
19: "nineteen"
}
%}
{% set a = v // 100 %}
{% set b = (v - a * 100) // 10 %}
{% set c = v % 10 %}
{% set d = v % 100 %}
{% if v == 0 %}
zero
{% else %}
{% set p1 = 'negative' if value < 0 %}
{% set p2 = (m2[a] ~ ' hundred') if a %}
{% set p3 = m1[b] if v % 100 >= 20 %}
{% set p4 = m2[c if d >= 20 else d] | default() %}
{{ [p1, p2, p3, p4] | select() | join(' ') }}
{% endif %}
does it cover eleventy-one?
Hmm, no ๐
Now it does, it will say one hundred eleven though
Mine was originally done for Phone numbers as my other half did not like missed calls being read by Alexa as three thousand and forty three two hundred thousand four hundred and forty six!
That makes sense
on both of ours, "1023" comes back as "ten hundred twenty three" ๐
it's almost to proper MIddle Earth
I have a state based binary sensor which is defined as below```
- trigger:
- platform: state
entity_id:
- sensor.0x943469fffec8d2eb_action
- sensor.ikea_bedroom_remote_action
to: 'brightness_stop'
binary_sensor:
- name: "Brightness stop"
state: "on"
auto_off: '00:00:01'
Previously it only has 1 entity now I expanded it to 2. It worked but I did not really find how this can be done on the template part of the docs. Can anyone point me to the io site about this info?
there are lots of examples, like https://www.home-assistant.io/integrations/template/#trigger-based-sensor-and-binary-sensor-storing-webhook-information
first example
Yeah but it did not show cases with multiple entities
it does
right there
template:
- trigger:
- platform: webhook
webhook_id: my-super-secret-webhook-id
sensor:
- name: "Webhook Temperature"
state: "{{ trigger.json.temperature }}"
unit_of_measurement: ยฐC
- name: "Webhook Humidity"
state: "{{ trigger.json.humidity }}"
unit_of_measurement: %
two entities
Something. not quite right : 27 = zero hundred twenty seven
I'm not very familar with webhook. In this case the trigger is using 1 entity or 2?
neither
After I fixed the index error.
the entities don't affect the trigger at all
ignore the webhook trigger, I'm just copying the example from the docs. Use whatever trigger you want
I've got my template working in template editor. It returns a list of the entity_ids I'd like included on this card. But what's the syntax to get the entities card to accept my generated list?
type: entities
entities: >-
{{ states.sensor
| rejectattr('attributes.device_class', 'undefined')
| selectattr('attributes.device_class', 'eq', 'power')
| rejectattr('entity_id', 'in', area_entities('energie'))
| map(attribute='entity_id')
| sort()
| list() }}
results in "Entities must be specified". Please help me find the correct syntax for this situation?
It's actually not state based, it's trigger based
oh, you just added another entity? I'm not even sure what the question is then
You can't do that in an entities card.
Use the custom card auto-entities for that
ah! thank you so much.
yes, Im having an issue with lower (than 100) numbers too, eg use 1, and it returns UndefinedError: dict object has no element 0 ?
is there a way to create fake entities (like sensors) to aid building a template?
The idea of if I have a sensor.light or person.max, can I create a fake version of that to dev against?
my question is where do I find concrete info on using trigger based snesors from more than 1 entities on HA io website?
I did not find it but I took a guess and it worked
use them how? It's exactly the same as with automations, if you mean using the trigger variable
anyway, if you figured it out..
yeah and just to check 1 last thing there, if the trigger is based on both entity 1 and 2, then it's either or?
So still the old rule about multiple triggers?
it is impossible for a single trigger to refer to more than one thing
this is not possible:
if the trigger is based on both entity 1 and 2
- trigger:
- platform: state
entity_id:
- sensor.0x943469fffec8d2eb_action
- sensor.ikea_bedroom_remote_action
to: 'brightness_stop'
binary_sensor:
- name: "Brightness stop"
state: "on"
auto_off: '00:00:01'
But this code works for both 2 entities
yeah I don't know what would happen when both entities are triggered but in my case the likelihood of that is very low. so
if both change state to that value, you will get two separate triggers
can't say I fully follow what you said.
Let's talk about the edge case here
If both entities triggerd at the same time than I have 2 triggers? Than which trigger is the binary sensor I created is based on?
yes, two triggers. the entity will be based on the last one
okay so there's a possibility that the first entity's state change won't influence the binary_sensor's value
Good to know thanks
Yes there is an attribute named โValueโ. The output JSON from the source REST is really poorly defined. I had to use json attributes to filter out the readings from the weather station that I wanted. Hence the rainfall value became an attribute instead of a state. Using state_attr would be correct in this case?
Hey! I want to somehow implement this template into the telegram_bot.send_photo action, if it's possible as the caption of the photo; instead of having 2 messages.
service: telegram_bot.send_photo
data:
authentication: digest
file: /config/www/tmp/snapshot_aquarium_sub.jpg
caption: test
In that case you need to use state_attr() are you sure the attribute uses a an uppercase V?
Greetings.. I would appreciate some advice for setting up some ESPHome based smart plugs (8). They are automatically detected and are working well, but their sensors show up as 'sensor.athom_smart_plug_v2_power', 'sensor.athom_smart_plug_v2_power_2' etc. I would like to map these to 'sensor.kettle_power' and 'sensor.dryer_power' etc. Is there a nice way of doing this? I could make sensors for all of these, but with 'power', 'current', 'voltage' for each one it's going to get lengthy.
adjust it in the ESPHome config
you are probably using the same config for all, so it will use the same names
Another option is to rename the device in Settings, it will rename all the sensors as well, but prefix the name for the sensors with athon. eg sensor.athon_kitchen_power etc
or do that ๐
@marble jackal Yes, but I would rather not mess with the ESPHome ๐ It is putting the MAC address on the end, so the ESPHome device names are unique -abcdef, but the 'nice' names are all the same.
@lyric comet I have done that with a couple of the sensors, but the name change hasn't propagated through..
Strange I did it yesterday for a plug and on changing the device it asked if I wanted to change the sensors. Perhaps it does not work if you have already edited the entities.
you can try to remove the ESPHome integration for one of the plugs, and wait until it's discovered again
then after re-adding, you can try the rename option again
can anybody help for a templatesensor? Try to get an number sensor from the 7th june this yeahr to the actual day
{{ (now().date() - as_datetime('2023-06-07').date()).days }}
ive been looking at this now for the last 20 min.... {{state_attr('sensor.low_level_batteries','low_batteries')}} outputs a list of entity_id's. I want this to be used in a notification to show the names. cant make it happen . Ive tried the map(attribute='friendly_name') and expand on the list, but nothing succeeds.
the attribute itself is low_batteries: > {%- set alert_level = states('input_number.battery_alert_level')|int(default=0) %} {% from 'batteries.jinja' import batteries %} {%- set ns = namespace(batt_low=[]) %} {%- for s in expand(batteries().split(',')) if s.state|int(default=0) < alert_level %} {%- set ns.batt_low = ns.batt_low + [' ' + s.entity_id] %} {%- endfor %} {{- ns.batt_low|join(',')}}
aarghh, there was an oddity in the main template creating that attribute. see{%- set ns.batt_low = ns.batt_low + [' ' + s.entity_id] %} addin an extra space in that list. Ive taken that out, and {{expand(state_attr('sensor.low_level_batteries','low_batteries')) |map(attribute='name')|list}} now makes it happen
bringing another challenge: can we map this replace structure?```
{{-expand(state_attr('sensor.low_level_batteries','low_batteries'))
|map(attribute='name')|join(', ')
|replace('sensor Battery','sb')
|replace('draadloze dimmer','dd')
|replace('hygro temp Battery','htb')
|replace('bewegingssensor','bw')
|replace('afstandsbediening','ab')
|replace('door: Battery level','dbl')
|replace('Battery Level','bl')
|replace('flood sensor: Battery level','bl')
|replace('dimmer switch battery level','dsb')
|replace('dimmer switch Battery','dsb')
|replace(' Internal','')
|replace('Battery','')}}
in pseudo code something like replace(['a','b','c']['1','2','3']) ?
friendly_name is an attribute of the entity, so you should have used map(attribute='attributes.friendly_name).
name is not an attriubute, it's on the same level in the state object as state and last_changed, so there you can just use map(attribute='name')
yes, I tried all of that, but it broke because of that extra [' ' + . Cant even remember why I had put it there, and its really remarkable, as the output of that attribute was used for a long time in my auto-entities filter. That must have been smart enough to dont be bothered by it.
btw the main template attribute itself is based on this custm_template: {%- macro batteries() -%} {{- states.sensor |selectattr('attributes.device_class','defined') |selectattr('attributes.device_class','eq','battery') |rejectattr('state','in',['unknown','unavailable']) |map(attribute='entity_id')|join(',') -}} {%- endmacro -%}
you could combine the ones with the same outcome if you use regex_replace()
eg regex_replace(' Internal|Battery', '')
a yes, I was looking for that syntax yes! forgot it was regex.. thx! this only works for the same outcome? can not use it to swap those items on the left, with items on the right?
not sure
ok, let me try
you could also use a mapping, but then you need to do the replacing in a for loop
this doesnt work: |regex_replace('sensor Battery|draadloze dimmer |afstandsbediening |hygro temp Battery', '1|2|3')}} as it replaces any of the left strings with the complete right string ๐
the regex behavior is a bit more complicated than simply replacing those strings and replacements in my template above. even replacing all with an empty ' ' or even '' has unexpected results. for now I guess Ill keep it at message: > {{-expand(state_attr('sensor.low_level_batteries','low_batteries')) |map(attribute='name')|sort|join(', ') |replace(' sensor Battery','') |replace(' draadloze dimmer','') |replace(' hygro temp Battery','') |replace(' bewegingssensor','') |replace(' afstandsbediening','') |replace(' door: Battery level','') |replace(' Battery Level','') |replace(' flood sensor: Battery level','') |replace(' dimmer switch battery level','') |replace(' dimmer switch Battery','') |replace(' Internal','') |replace(' Battery','')}} and move the opening line to the notification title, to save some extra space in the notification (it gets truncated on those long outputs, reason for all of this finetuning)
Hi Is it possible to put this template into the telegram_bot.send_photo service as caption message?
service: telegram_bot.send_photo
data:
authentication: digest
file: /config/www/tmp/snapshot_aquarium_sub.jpg
caption: test
{% if values.error %}
๐ โ The fishes have not been fed at {{ values.timestamp }} โ
{% else %}
๐ The fishes have been fed {{ values.value }} portions at {{ values.timestamp }}.
{% endif %}
I get this error:
Error rendering data template: UndefinedError: 'values' is undefined
Where is values coming from? Did you define it as a variable?
Remember template variables are not passed through scripts.
http://pastie.org/p/1WJonDSKmNoa2yq8mI7Emt
This is the entire automation, TheFes helped me with this template, but I'm trying to improve it now with adding a photo of the feeding aquairum because sometimes it does not feed them as it say so..
I presume if you remove/disable the telegram action it works ok? If you look at the trace how far through is it getting?
The telegram action work fine if the caption is "test" and not my template.
I want somehow to put this template inside the telegram action; that way I will receive one notification instead of 2
If you use a simple template like
caption: "{{ 'This is a test' }}"
for your caption what comes through or do you get an error?
let me try, thanks for help
https://imgur.com/plSMuuh
Seems to work!
*heading quickly to bathroom, brb
Now try changing it to
caption: "{{ values.error }}"
If you look in Traces for the changed variables can you see your values table there?
Error rendering data template: UndefinedError: 'values' is undefined
It does not as if for some reason values which is defined in your variables section of your script is not available for some reason. Can you see it in the trace?
I can't even run it, it sending this error straight away
you are using RUN ACTIONS?
I might be tempted to create another variable and try using that. You will not be able to run the section on it's own as the variables will not be set.
the variables are based on trigger variables, there is no trigger if you use run actions
oh wait, they are not
is there a way to set those variables to the actions?
because it does using them on conditions too
No, I was mistaken, they are based on the actual state
the condition is based on the trigger, but that's fine
the condition is not used when you use run actions
the actions i'm using are send message (which i want to get rid off), and camera take snapshot
does the template for values work if you put in in developer tools > template right now
hold on let me try
Could you add a time trigger to run it every few minutes to test it
You mean this right?
{% if values.error %}
๐ โ The fishes have not been fed at {{ values.timestamp }} โ
{% else %}
๐ The fishes have been fed {{ values.value }} portions at {{ values.timestamp }}.
{% endif %}
no
I meant:
{% if state_attr('switch.hfjh_v2_eadb_fish_tank_2', 'event.4.1') is not none
%}
{% set value = (state_attr('switch.hfjh_v2_eadb_fish_tank_2', 'event.4.1') | from_json).value[0].value.split(',') %}
{% set timestamp = (state_attr('switch.hfjh_v2_eadb_fish_tank_2', 'event.4.1') | from_json).timestamp %}
{% endif %} {% set timestamp = timestamp | default() |
timestamp_custom('%H:%M %A', default='unknown') %} {% set value = (value |
default())[6] | default('unknown') %} {% set error = (value | default())[5]
| default() == 0 %} {{ dict(timestamp=timestamp,value=value,error=error) }}
Result type: dict
{
"timestamp": "20:30 Sunday",
"value": "2",
"error": false
}
This template listens for the following state changed events:
Entity: switch.hfjh_v2_eadb_fish_tank_2
okay
I can't even save the line you wanted because of that error...
Hello, I'm trying to get an alert firing based on when garbage is due to be collected. Currently, collection is due tomorrow: {{state_attr("sensor.general", "daysTo")}} returns 1, so I'm validating that this is tomorrow by calling {{state_attr("sensor.general", "daysTo") == 1}} which returns true. So far, so good. However, when I try and use this in an alert:
alert:
garbage_general:
name: General Bin Collection Due Tomorrow
entity_id: sensor.general
state: '{{state_attr("sensor.general", "daysTo") == 1}}'
repeat: 60
can_acknowledge: true
notifiers:
- mobile_app.iphone
The alert unfortunately remains in an idle state. I appreciate this is probably me doing something stupid with the alert, and the templating is probably fine, but this felt like the best place to ask. Any tips?
so it's impossible to make that template in the caption field? should I just stick to the two messages ?
no, it should just work
but can you explain step by step what you are doing and when do you see an error?
templates are not accepted there, create a template (binary) sensor and use that for the alert
Sure!
I replaced caption: "{{ 'This is a test' }}" line with
caption: "{{ values.error }}"
as soon as I press run or save it showing me an error message
Error rendering data template: UndefinedError: 'values' is undefined
@quiet spruce I converted your message into a file since it's above 15 lines :+1:
@marble jackal - the helpful bot above changed my reply to a file. Any further tips?
You removed the state line in the alert config, it should have state: "on"
DO NOT Press run. Just save it. Then add an extra trigger to run the automation every few minutes to test it.
As I believe Fes explained the value field is not available if you just run one line of the automation.
Oh because it skips the value variable? ok let me try that.
You can put the variables as the first action and they won't be skipped
https://imgur.com/jpuFUhh
with caption "{{ values.error }}"
(i disabled the conditions just for this test)
https://imgur.com/yg4NDud
it works, thank you guys!
I feel so stupid today
what am I doing wrong here?
- platform: template
sensors:
- players_online:
friendly_name: "Players Online"
entity_id: sensor.minecraft_server_players_online
value_template: {{ state_attr('sensor.minecraft_server_players_online', 'players_list')[0:] }}
I just want to make an attribute it's own entity
and stuff I find online is incomprehensible
You didn't surround your template in quotes
Also, I don't know why you have [0:]. I don't think it does anything useful
thank you!
What is entity_id doing there?
not sure, I'm just copying random things from the internet as I said
Yeah I'll adjust, one moment
See the docs
yepp
- platform: template
sensors:
players_list:
friendly_name: "Players List"
value_template: "{{ state_attr('sensor.minecraft_server_players_online', 'players_list') }}"```
should be good now, according to HA
restart time
Lovely, it works
thankies~
How can I use the result below, and turn into automation/script to switch.turn_on switches that have same 'entity_id' as list of results? End goal is to have automation/script that is triggered when Sun=sunset.
{% for state in states.sensor | rejectattr('attributes.RStatus', 'undefined') | selectattr('attributes.RStatus', '==', 'O') %}
{{ state.entity_id }}
{% endfor%}
start by just outputting an actual list
service: switch.turn_on
data:
entity_id: "{{ states.sensor|rejectattr('attributes.RStatus', 'undefined')|selectattr('attributes.RStatus', '==', 'O')|map(attribute='entity_id')|map('replace', 'sensor.', 'switch.')|list }}"
@silent flicker I converted your message into a file since it's above 15 lines :+1:
is there any way i can get a graph of how many minutes an entity has been in a state, by day?
actually, i guess it's a little more complicated than that - i want to see daily AC usage, my entity "thermostat_cooling" is set to 0 when the AC is off, and some value like 72 when the AC is on, so i wanna know how many minutes it's been non-zero for the day
you can do something with history_stats https://www.home-assistant.io/integrations/history_stats/
perfect, thanks!
apologies, i am rewriting mine because it got a little ugly. hope that is okay. i am using the weatheralerts HACS addon. I am trying to figure out what to write in my template to get the output of the "description" field in the weather alert.
for example, i want to get the data that is only inside "description" or "area":
@silent flicker I converted your message into a file since it's above 15 lines :+1:
right now i can write this to get the full alert:
{{ state_attr('sensor.northumberland', 'alerts') }}
So the output you posted is the attribute 'alerts' of the sensor.northumberland ?
yes that is right
but i wanted to text to speech the alert
but not the whole thing, because thats huge
https://i.imgur.com/LbopGbb.png - if that helps
would there be an easy way to search or split by "description:" to extract just that bit?
Look in developer tools > states, it will have an actually readable output
But probably this will work
{{ state_attr('sensor.northumberland', 'alerts') | map(attribute='description') | list }}
Probably still a lot of text
thats better. it just looks like this:
['THE NATIONAL WEATHER SERVICE HAS ISSUED SEVERE THUNDERSTORM WATCH\n440 IN EFFECT UNTIL 10 PM EDT THIS EVENING FOR THE FOLLOWING\nAREAS\n\nIN PENNSYLVANIA THIS WATCH INCLUDES 12 COUNTIES\n\nIN CENTRAL PENNSYLVANIA\n\nADAMS COLUMBIA CUMBERLAND\nDAUPHIN FRANKLIN LANCASTER\nLEBANON MONTOUR NORTHUMBERLAND\nPERRY SCHUYLKILL YORK\n\nTHIS INCLUDES THE CITIES OF BERWICK, BLOOMSBURG, CARLISLE,\nCHAMBERSBURG, DANVILLE, GETTYSBURG, HARRISBURG, HERSHEY,\nLANCASTER, LEBANON, NEWPORT, POTTSVILLE, SHAMOKIN, SUNBURY,\nWAYNESBORO, AND YORK.']
Add |first
what the heck does that do lol
@silent flicker I converted your message into a file since it's above 15 lines :+1:
it looks way better
Just what sounds like - returns the first item in the list
it got rid of all the weird spacing and \n
Because it actually converts the \n to a line break
But if there are multiple alerts active, you'll only see the first one
I guess you could do |join('\n')
You could do something like
{{ state_attr('sensor.northumberland', 'alerts') | map(attribute='description') | join('\n') }}
Pfft
What he said
Thanks I will try that in a few. Only reason I need this now is because we had 2 tornadoes yesterday and no alarms.
You said only the first. What if there's more than 1? Can I have it format correct and read each description
Yes, with the last version I posted
Hi, I'm trying to send the username to the script. I have code that used to work, until a few weeks ago.
action: call-service
service: script.tooglescript
data:
notify_id: |
{{ user }}```
Now it's not sending anything.
Any idea how to fix this?
You can't use templates in a tap action
Ooo, do you have any suggestions on how to do this?
Good night
I have some windows sensor entities that are all of the form binary_sensor.<room>_<identifier_might_have_underscores>_window_open I want to make sensors per room that indicate that any window is open. What is the yaml for that?
Is there a way to multiply a decimal value (as a percentage), then substract that value from the multiplicand; all in the same expression?
ex:
{{ (10.60 * 0.01) | round(2) }} = 0.11
Then substract the "0.11 " to the "10.60".
Instead of calculating 1 % and substracting it, I'd suggest to calculate 99%.
{{ (10.60 * 0.99) | round(2) }}
Yeah, but value of the multiplicand keeps changing.
Good point; the percentage is always 1%.
You could also alter it to use changing percentages by using (1 - percentage) instead of 0.99 - "percentage" to be replaced by a proper variable
In the 0.01 format
Indeed. Thanks for the ideas!
For a custom button card, I'm trying to write a states > value: that's basically capturing all states but off, I am not sure how to exactly write that
Any pointers?
or if a value that contains a certain string of text
Is there any docs/guidance on writing messages in templates to handle singular/plural language? I'm writing TTS templates with variable numbers refering to singular or multiple things.
Sure, I want write two different sentences depending on the value of a state. "There are {{ count }} people at the front door" vs "There is someone at the front door" depending on the value of count, which is set from a sensor.
Is the (only) way to use if/else?
yes, someting like There {{ 'is someone' if count == 1 else ('are ' ~ count ~ ' people') }} at the front door
To understand it correctly: You want to check if a certain state is not equal to off?
@edgy gorge custom:button-card uses javascript, this channel is for jinja templates. You should ask in #frontend-archived
Thank, that' a syntax I wasnt aware of.
if (entity.state != 'off')
{
}
how do I add a string to the end of each result in the list? I need to add '_FP' to each.
service: switch.turn_on
data:
entity_id: >
{{
states.sensor
| rejectattr('attributes.RStatus', 'undefined')
| selectattr('attributes.RStatus', '==', 'O')
| map(attribute='entity_id')
| map('replace', 'sensor.', 'switch.')
| map('regex_replace', '$', '_FP')
| list
}}
@fair wind
Howdy. I've created a template to return the timestamp of when a device will finish charging. The charge_rate below is in kW and charge_required is kWh.
{% set charge_rate = states('sensor.battery_charge') | float(default=0) %}
{% set charge_required = states('sensor.kwh_remaining') | float(default=0 %}
{% set time_to_charge = charge_required / charge_rate %}
{% set battery_full_time = now() + timedelta(hours=time_to_charge) %}
{{ battery_full_time }}
You can probably see the issue. It works fine if charge_rate > 0, otherwise there is a divide by 0 involved.
I can do a conditional to only set time_to_charge if charge_rate > 0 but I'm not sure what timestamp to return in that case. Any ideas? Thanks.
I guess a simpler way to put the question is, if there is no valid timestamp from the template sensor, what's the best way to handle that? Setting to none maybe?
unavailable
{% else %}
{% set time_to_charge = (states('sensor.kwh_remaining') | float(0)) / (states('sensor.battery_charge') | float(0)) %}
{% set battery_full_time = now() + timedelta(hours=time_to_charge) %}
{{ battery_full_time }}
{% endif %}```
Would you mind to try this? I'm at work right now and cannot use my template development tab. ๐
That works, thank you! Is the unavailable keyword the best way to handle this event then?
is it better to use an availability template than set the state to unavailable? https://www.home-assistant.io/integrations/template/
https://www.home-assistant.io/integrations/template/#availability
If it is part of a template sensor, indeed.
Ah, I'll give the availability template a try. Does the availability: template get rendered first? i.e. if the output of that is false or 0, it doesn't bother rendering the state: template.
From the template sensor documentation: An availability template may be defined to suppress rendering of the state template.
Perfect. Thanks both for your help ๐
Is it possible to access statistics recorder data in template without defining new template for it? I want to show 5min mean value. Same value you see in a statistics card. Something along the lines:
{{ statistics('sensor.grid_in_power', '5m', 'mean') }}
No
I'm no expert on templates, but does this help you? It returns the number of binary sensor devices that have a device_class of 'door' and are in a particular room ('woonkamer' in my example) and that have a state of 'on'.
{{ states.binary_sensor
| rejectattr('attributes.device_class', 'undefined')
| selectattr('attributes.device_class', 'eq', 'door')
| selectattr('entity_id', 'in', area_entities('woonkamer'))
| selectattr('state', 'eq', 'on')
| map(attribute='identity_id')
| list()
| length() }}
Hi guys, can I use templates within the automation action "define variables"?
I'am trying to do something like this:
variables:
user: >
{% if states.sensor.keypad_code.state.startswith('2865') %}
{{"Majuss"}}
{% elif states.sensor.keypad_code.state.startswith('7127') %}
{{"Sandra"}}
{% else %}
{{"Jemand"}}
{% endif %}
so setting a variable based on the keycode and then use it in a TTS message
I know that I could use the template directly inside the tts message but It would spare me a lots of code if I just could set a variable..
It was a frontend bug for me. When I save the template text 2 out of 3 cases wierd stuff is happening...
I'm losing my mind here. But I'm trying very hard to keep it short lol.
- Are all sensor values stored as strings? Meaning...if I create a sensor or binary sensor and then try to use that sensors value in another template, will that value always be a string? Or will it be picked up as a boolean?
- Depending on the answer to the first question. Is there a way to convert a string boolean value into an actual boolean value?
all states are always strings
I figured that for "sensor" entities. But I was hoping that would not be the case for "binary_sensor".
sure. is_state('input_boolean.whatever', 'on')
it's true of every state for everything since the dawn of time ๐
Okay I'll try that. I've been banging my head on my desk for a while. I'm trying to make a sensor/binary sensor which returns a boolean indicating whether today is a holiday observed by my electric utility. I have all the logic worked out, but trying to use that value in another template has been driving me insane.
since it's just a string, any form of comparison will yield a boolean
Yeah, I was just trying to be fancy and was hoping I could do something like:
{% if states('binary_sensor.energy_meter_tariff_holiday') %}
...
if you added == 'on', you would have had it ๐
in any case, all states are strings, and probably will always be
Yeah, I see that now. I've been using == true and that's what led me here.
Yup, but I know YAML and similar can be weird sometimes and will treat certain literals as booleans implicitly
So I was hoping true / false would work, and was also hoping it would work without using the comparison.
I mean, it's just a few extra characters so it's not a big deal either way.
However, I did not think to actually use "on" or "off". For some reason I thought those were just UI conversions from a boolean underneath.
The template should be indented two spaces compared to user:
But maybe that was already mentioned ๐
states('input_boolean.whatever') | bool(false) could be used as an alternative approach ๐
There are many places where translation or prettyfying is done to the state, but
-> States is always the source of literal truth
Oh that's interesting, | bool actually converts "on"/"off" properly
lots of good stuff in the topic links
like an entire paragraph about bool: https://www.home-assistant.io/docs/configuration/templating/
Yeah, but who reads documentation.....kidding. That's a good link, thanks. I didn't even bother checking the HA docs. I read something about as_bool in the jinja docs a StackOverflow answer, which the HA template editor said wasn't a thing, so I just assumed there was no bool parse function.
@arctic quail I converted your message into a file since it's above 15 lines :+1:
Whoops, meant to edit before clicking enter. Something like:
temperature: 68
fan_speed: 3
mode: "cool"
i need some help
{{ states("input_datetime.inicio_evento_calendario") + timedelta( hours =
states("input_number.duracion_horas_evento_calendario") | float, minutes = states("input_number.duracion_minutos_evento_calendario") | float ) }}
im getting this error
TypeError: can only concatenate str (not "datetime.timedelta") to str
Comment the input datetime state to a datetime first using as_datetime
thanks
@silent vector I converted your message into a file since it's above 15 lines :+1:
Didn't realize it was that long whoops
@silent vector I converted your message into a file since it's above 15 lines :+1:
๐คฆโโ๏ธ
one more sorry
how can i reset the data after running a script
script:
add_calendar_event:
sequence:
service: calendar.create_event
target:
entity_id: calendar.calendar
data:
summary: '{{ states("input_text.titulo_evento_calendario") }}'
description: '{{ states("input_text.descripcion_evento_calendario") }}'
start_date_time: '{{ states("input_datetime.inicio_evento_calendario") }}'
end_date_time: '{{ states("input_datetime.inicio_evento_calendario") | as_datetime + timedelta( hours =
states("input_number.duracion_horas_evento_calendario") | int, minutes = states("input_number.duracion_minutos_evento_calendario") | int ) }}'
you want in
i want to reset to defaults
As in | select('in',second_list)?
you need another level
random_name['bar'] | selectattr('name', 'in', second_list) | list, I think
without testing
Unless I'm doing something wrong I get an empty list
I was doing something wrong lol
@ebon peak I converted your message into a file since it's above 15 lines :+1:
How do I escape the ">" character?
Yes
My issue is I am trying to add another sensor, but it seems to be hung up in the multiline
that's not the problem
the problem is that you're mixing up the old and new template sensor formats
Oh lame.
what you have is some weird and invalid amalgam
Is this up to date? https://www.home-assistant.io/integrations/template/
yes
I'll go from there then. Thank you @inner mesa
So based on the new format, I have this in my configuration.yaml:
history: !include history_state_sensors.yaml
In that I am trying:
sensor:
- name: Lamp ON today
entity_id: light.my_lamp
state: "on"
type: time
start: "{{ now().replace(hour=0, minute=0, second=0) }}"
end: "{{ now() }}"
I have tried history: and history_stats: , but I get the same error as sensor: which is - Invalid config for [history]: [sensor] is an invalid option for [history]
Oh wait
So I it should be?
history_stats: !include history_state_sensors.yaml
no, it needs to be under sensor:, as in the example: https://www.home-assistant.io/integrations/history_stats/
I think you're getting mixed up because you had both a history_stats sensor and a template sensor (using the new format) together, and they can't be combined like that
just follow the docs for each sensor type
I was commenting on your template sensor, not the history_stats sensor
as that's the one you were concerned with, and was also wrong
@ebon peak I converted your message into a file since it's above 15 lines :+1:
So removed history_stats: !include and just added it my configuration.yaml, but no sensor shows
Running Check Config results in no errors, and my reload results in no related logs either
I'm usually not this dumb, but yea, needed to restart. Thank you.
hi, i'm having trouble with history_stats, i have a entity (my AC) that always has state="cool" (whether it's running or not) - i want to use history_stats to track when it's running, but the only thing that changes is the "state attribute" hvac_action changes between "idle" and "cool", is there a way to use history_stats to track an attribute of an entity?
No, but you can make your attribute into a template entity, and then track that.
oh great, thanks!
@ivory harbor I converted your message into a file since it's above 15 lines :+1:
I didnt format right, aprops of above ^ I'm trying to use a template to pull calendar info... it doesnt error but the calendar data doesnt populate. If I go to my calendar dashboard, I notice it takes 2-5 seconds to populate. How should I handle this? can I add some sort of delay in my template?
Good morning, yesterday I accidentally deleted the energy dashboard, how do I install it again?
@normal moat I converted your message into a file since it's above 15 lines :+1:
*and I dont know how to use code block on discord ๐ sorry about that
To format your text as code, enter three backticks on the first line, press Shift+Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks.
```yaml
example: here
```
Don't forget you can edit your post rather than repeatedly posting the same thing.
so you only want the next 4 hours of prices?
You don't really explain how you want to use the timestamp, other than you just said you want to use it
Sorry, the sensor contains all 24h of the current day.
I want to use use the time stampes to plot a graph of todays price.
I got it working with the the unmodified sensor.
Then why do you need the second sensor?
If you just want to filter
just do it in whatever's plotting, no reason to make a second sensor when you're still just making a list of dicts
so the tarrifs I want to add change depending on summer/winter and what time of day it is.
yeah, you can do all that, you have to be using something custom to generate the graphs
because that's only doable via the energy pannel and you can't use historical data like you are with the energy panel
anyways, if you're dead set on the second template..
{% set ns = namespace(items=[]) %}
{% set s = today_at() %}
{% set e = s + timedelta(hours=24) %}
{% for price in value_json.prices if s <= price.localTime | as_datetime | as_local <= e %}
{% set ns.items = ns.items + [{'price': price.rawPriceInclVat, 'time': price.localTime}] %}
{% endfor %}
{{ ns.items }}
however, you'll most likely need to use
state_attr('xxxx.xxx', 'prices') instead of value_json.prices
if it's coming from an entity
Thanks I'll give it a go
has anyone been able to get a list of daily calendar apts via a template? I'm having trouble iterating the list
you cant't using a template, as a calendar enttiy only has one event
you can do it using the new service call responses introduced in HA 2023.7 (released yesterday)
hummm I know about the new service call feature... but I'm surprised there's no way to iterate via templates. clearly I dont understand how the calendar integration works ๐
what if I only wanted to pull the one event (the one I see when I look at the state of calendar.my_calendar)? shouldn't I be able to get that in a template?
Templates only work with what's available in the state machine. They don't communicate with the integration directly
If you don't see it in
-> States, in general templates can't see it
(worth noting, I have set my own code aside for a moment in favor of testing @thorny snowtro's example here: https://community.home-assistant.io/t/how-to-list-multiple-calendar-event-in-a-template/349139/9?u=spacebass )
copy that... what I see in the state is my next calendar entry with attributes like start_time, end_time, etc
you could shedule an automation on a time pattern, or on a state trigger of the calendar entry, use the new service call in the action, and send the results you need in an event
then use that event for a trigger based template sensor, and put the data in an attriubute
and voilla you have it in the state machine, and get it out using templates ๐
makes sense... or I could just fully adopt the new service call which is probably the easiest option ๐
is stubbon when I want to learn something even if what I want to learn isn't possable ๐
depends on where you need it, if you want it in a markdown card for example, you can't run the service call
Hello?
sorry, @mighty ledge not you - somehow a space got introduced
Is there a way to define the possible states for a template sensor?
So, for example, they would should up in the automation visual editor from/to state dropdowns?
Can you make it a template select instead of a template sensor? Actually maybe that's not so good as it will appear to be modifiable on a dashboard.
Integrations can create enum-class sensors with defined options, but I'm not aware that's possible with a template (could be wrong though)
on my Cards I currently have this - https://i.imgur.com/zoPxLYX.png
when I go into Templates and run
{{ states('climate.bedroom_heater') }}
all I get is
off
Is there a way to retrieve the info like in the card displays?
{{ state_attr('climate.bedroom_heater','temperature') }} for the attribute temperature
Or according for whatever attribute you want
its a custom integration for the thermostat, so im not sure that works. it currently says NONE when i do that. so i might be out of luck here lol
ahh. yeah i forgot about that lol
You need to look at the dev tools for the states. The available attributes are shown there
any hackz0r HA users here who can help me with a template? i have all my sensors in configuration file. is that bad? ๐ i'll get errors. duplicated mapping key (66:1) with states and template:
were you going to share something?
you repeated template:, as the error mentioned
you also have two different ways of formatting the sensors underneath each
template:
sensor:
name: "stromverbrauch"
unit_of_measurement: kWh
and
template:
- sensor:
- name: sophamtning_days
state: >-
use one template: tag and follow the docs to get the formatting right: https://www.home-assistant.io/integrations/template/
It shows how to define multiple sensors
Thanks!
Hi everybody, I am new to HA and busy with this blueprint: https://community.home-assistant.io/t/zha-lidl-livarnolux-tuya-silvercrest-4-button-remote/372186/12
The problem is buttons 1 and 2 are working properly, but buttons 3 and 4 do nothing on either short or long press.
By using traces I figured that the conditions for button 3 and 4 are wrong, so no action is taken.
I will do anything to solve it and deliver any information necessary and any help or hint will be appreciated, since the original poster doesn't seem to react to this post anymore. I am willing to publish any working solution.
You could simply correct the conditions in a copy of the blueprint, if you have worked out what is incorrect. Blueprints are just script files and if you have the File Editor or VScode add in installed you can edit them on your HA instance, or install the Samba Add in to edit them on your normal desktop computer.
That's what I would do
I have only figured where is goes wrong, but not what is going wrong. As I said: I'm a noob!
How do I that?
you can share an image or if you know how to get to the text, you can share text
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.
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.
Thanks, gimme a second. I guess the choice step is the one you want to see?
the failed condition
or the trigger with the changed variables page shown
and the trigger being the 3rd and 4th case
can you show the changed variables tab?
you're on the step config tab
the lower right set of tabs
on the trace
here for the trigger: http://pastie.org/p/4QXpsHPDRCpM2IjfDMuBhP
here for the choice:
command: step
args: '[<StepMode.Up: 0>, 51, 10]'
So the blueprint is now broken because it's using enums instead of strings
in the condition for 3, change
- conditions: '{{ command == ''step'' and stepmode == ''StepMode.Up'' }}'
to
- conditions: '{{ command == ''step'' and stepmode == 0 }}'
ok, thank you , the rest has to be changed accordingly?
You'll need to look at the trace again and see what number stepdown mode is, then make similiar changes to that one
You only need to change condition 3 and 4. 3 is stepup which should be == 0, step down will be another number. For example, if it's <StepMode.Down: 7> then you'd use == 7 for the 4th
I will do, as far as I remember it is 1 but I will check again
Can I do this in the original blueprint.yaml?
I believe so but i'm not 100% sure
If I want to use long press, then I need to use move and movemode, right?
is templates still the only way we can do: {{[0,states('sensor.netto_verbruik')|int(default=0)]|max}}? figured Id go the UI helper route, but cant find an option to use 0 there, only entities
no idea what you're asking
Quick question, as I am having a brain freeze. I have a string 20230707105416 (2023/07/07 10:54:16) which I need to get to a date time object to use with easy_time, but I can't seem to find the right combination to convert it.
wtf kind of date string is that
The filename from a voicemail file which comes in from my phone system
Ui only seems to use input entities
lol aight, so you'll have to split it because format won't work while it has 2 dates
It is one date. the string is 20230707105416 I put the other to show the layout
sorry to not being clear
{% set x = value.split()[0] %}
{% set fmat = "%Y%m%d%H%M%S' %}
{% set input = strptime(x, fmat) %}
oh ok
just use strptime
it will be UTC though
so you'll need to do | as_local
and I might have the arg order wrong on strptime
Thanks I was close but I think I had the format wrong ๐ฆ
If you have a lot of these cases, make one sensor.zero with a fixed value of 0 and use that in the GUI
sorry, no idea what that says
Ha, yes, I was actually writing that up for testing as we speak! seems a bit hacky, but indeed I have a few of those
If I undertand correctly, I don't see that as hacky
its the min/max helper in the Ui, and I want the max of an entity and 0
yes I gathered that after the fes posted
I'm getting a "problem" warning about deprecated YAML (command line switch). Does everyone get this, tasteless of whether that YAML is even used in the installation? Asking because I can find any use of it in my YAML, but I still get the warning
that's a unix timestamp
Wondering whether I need to search further, or just ignore it
You only get that warning if you have the old format in your config
well, this has nothing to do with templates, but search your files for platform: command_line
Oh, I thought it's template related
nope, it's command_line
Will search, but I don't think I ever used it.. Don't even know how it works. So maybe in some component or add-on
Now I'm starting to doubt my brain rather than my installation
it'll be in your switch section of your configuration.yaml
Will go hunting again
or in a package if you use those
it should be easy to find, literally just do a 'find in files' using vscode or notepad++ for platform: command_line
hmm, not that simple apparently,```
-
sensor:
- unique_id: sensor_zero
state: 0```
- unique_id: sensor_zero
and yet the ui helper produces unknown
it says max entity_id is sensor.zero, which is correct, because Im returning power to the grid currently
could it be it requires the correct and full set of classes before being a valid entity for those helpers?
apparently not, Ive set that now, and still the helper remains unknown
not sure where the issue lies, is it this template sensor, or the UI helper causing the issue
DOH! I did add it, but in an include file. Thanks!
o well, I deleted it because it showed unit_of_measurement: ERR, which I hadnt seen before. Recreated it using the exact same entities and now it returns a correct value 0.0 (the template returns a clean 0 int, but thats a minor issue probably..)
ah apparantly the unit of measurement needs to be the same for all sensors
dont know why that unit would show ERR though, maybe it was the fact I had it created in 2 rounds, and needed to be fixed in 1 go. Anyways, seems to be working now. Hoping the UI helper will be seeing a subtract option too any time in the future
I can see that could be a bit more complex than sum (needs am entity to subtract from, so not equal entities), but having quite a few of these{{(states('sensor.zp_actuele_opbrengst')|float(0) - states('sensor.netto_verbruik')|float(0))}} would benefit from that subtract
in the condition for 3 change
hi all, how do I use the image entity? Some research has lead me to believe that I need to template it but instructions are very scant
in this case, I'd like to convert a camera steam as a single image
Hey, I have the following trigger:
platform: state
entity_id:
- sensor.samsung_last_notification
to: " Someone is at your Front Door "
The notification sometimes contains and sometimes doesn't contain an emoji for some reason, so I'm trying to change this somehow to check if the state contains these words or not
I'm trying to get it to something similar to :
[\w\W]*Someone is at your Front Door[\w\W]*
meaning [anything]Someone is at your Front Door[anything]
Any ideas?
Can I add a wildcard somehow?
You have to use a template trigger
{{ 'some string' in states('sensor.whatever') }}
Or you can use these: https://www.home-assistant.io/docs/configuration/templating/#regular-expressions
- image:
name: Ebony Screenshot
url: http://homeassistant.local:8123/local/EBONY.png
In your Templates: section
thank you!
what would be the opposite of in?
value_template: "{{ (name | lower) in state_attr('sensor.shopping_list2','content') | lower }}"
not in
thanks
or not xxx in dljadlfj
Can an icon color in a button or card be a dynamic RGB color?
Like this rgb_color: '{{state_attr('light.tv','rgb_color')}}'
This is in a mushroom template card
Where did the 'rgb_color' tag come from?
found it in dev tools for my hue light
so if that's what that attributes provides, then get rid of the rgb_color: tag that you added there
it has nothing to do with the card
I tried that, did not work
you keep saying that
Well yeah, because I did
here's an example of a static RGB color that I'm using:
icon_color: "{{ 'green' if is_state(entity, 'armed_to_night') else '#696969' }}"
you can construct that string from the attribute
Its not static, I dont want that
icon_color: >
{% if is_state('light.hue_play_1', 'on') %}
#{{state_attr('light.tv','rgb_color')}}
{% else %}
red
{% endif %}
I have no idea what that attribute's value is
{{state_attr('light.tv','rgb_color')}} = (72, 8, 255)
It comes out that, with the parentes
alright
Do I need to convert the XX,XX,XX to #XXXXXX to make it work?
So I need to make a whole program that first converts the value to that then use it in the icon color?
{% set value = (72, 8, 255) %}
{{ "#%02x%02x%02x" % (value[0], value[1], value[2]) }}
-> #4808ff
is there any way to compare a string in a json file?
in theory, {{ "#%02x%02x%02x" % state_attr('light.tv','rgb_color') }}, but I don't have one to test
i want to check before add a new item in the shopping list
This one worked! Thanks
how is a JSON file related to the shopping list?
the shopping list creates a json file in config/
@ocean tusk I converted your message into a file since it's above 15 lines :+1:
how can i check before adding a new one if its on the list already?
The easier way is to use the remove item for the item you are adding then add it again.
You might even find adding the same item again has no effect, but I don't use the shopping list integration.
that integration is one of the more primitive and unfriendly ones
it needs a service that returns the list, at least
now that we can do that
that wolud be nice
i will try that thanks
Got this to work! Would this make sending images with notifications your phone easier/different than current methods?
- service: notify.mobile_phones
data:
message: "Someone is at the front door"
data:
ttl: 0
priority: high
image: "https://blahblah.jpg"
Use {% else %}
lol
in any case, this is all just Jinja
yeah I tried your example first but didnt work ๐
there are several links in the channel topic
Thanks
This also would have been okay, but the PR was just closed. A service is probably the better option, anyway
https://github.com/home-assistant/core/pull/85389
command_line:
- sensor:
name: Media3/G Used
command: ssh -i /config/.ssh/ha -o 'StrictHostKeyChecking=no' myserver.com "df -k | grep nas | sort -k 6 | awk 'NR==2 {print \$3}'"
scan_interval: 1800
unit_of_measurement: "GiB"
value_template: >-
{% set data = default.split("\r\n") %}
{% set data_split = data[1] %}
{% set data_int = int(data_split) %}
{{ (data_int / 1048576) | round(2) }}
What is the default variable for data passed to a value template?
I used to use data.split here, but it stopped working.
so value. thank you
i'm guessing the custom integration i used to use had a data variable.
Hi, is it possible to make a for loop over every light that is on via templating?
And how would one go about the for loop? Cause i tried making a group of all the lights but I couldn't find out how I'd loop though those lights to even check if they were one so
I'm trying to loop though lights that have been on for longer then 10 minutes and then if it has detect what room its in then call a alexa actionable notifications for that room to ask if i can turn the light off. If no response then turn off etc etc
{{ states.light|selectattr('state', 'eq', 'on')|map(attribute='entity_id')|list }}
Alright, well, that's a start
Is there a way to filter out groups?
All groups have that attribute
Defined?
Yeah but then wouldn't that reject every light? Since they all have that attribute?
?
For some reason its not showing up that entity_id id an state attribute on either
Are there any attributes that define how long a light is been on for?