#templates-archived
1 messages Β· Page 139 of 1
then it should be working if your template is correct.
you aren't using state_color are you?
if you are, you'd want to use --paper-item-active-icon-color
it might be --paper-item-icon-active-color, it's one of the 2
i think the template is correct as no errors in Dev>template. here is what i have card_mod: style: | :host { --paper-item-icon-color: {% if is_state('group.security_locks', 'locked') %} green {% elif is_state('group.security_locks', 'unlocked') %} yellow {% elif is_state('group.security_locks', 'unavailable') %} red {% endif %}
again, are you using state_color?
no not that i am aware of. here is the rest of my code - type: state-icon entity: vacuum.roborock_vacuum_s5 icon: mdi:lock-smart style: top: 91.5% left: 51% width: 55px color: white opacity: 0.5 '--mdc-icon-size': 65px card_mod
- type: state-icon
that's not a card
are you sure that's the correct card_mod path?
Also, pretty sure you have to mod from the card down, not the row on that one
actually, that's a picture elements, which has it's own style
Just looking at a recent post in the card-mod thread, your selector for the element should be:
style:
state-badge:
$:
ha-icon:
$: |
ha-svg-icon {
color: {{ }};
}
Also, the code you are writing doesn't have a closing ;
Seems like you need to refresh yourself on card-mod, picture-elements, and generating selectors for each item.
Use this thread as a guide, and use the forum search to find what you need to do if you don't want to learn about the selectors: https://community.home-assistant.io/t/card-mod-add-css-styles-to-any-lovelace-card/120744
Back the drawing board a bit. So the template below works when Glances returns an uptime of greater than 24 hours because the format is "X days, HH:MM:SS". This template returns "3.75 days" for example.
{% set d = states('sensor.glances_ubuntuserver_uptime').split(', ') %}
{% set t = d[1].split(':') %}
{{ (d[0][:2] | float + (t[0] | float / 24) + (t[1] | float / 1440) + (t[2] | float / 86400)) | round(2) }}
But I rebooted the server Glances is running on and when less than 24 hours, it only returns "HH:MM:SS". Any ideas how I can alter my template so I can get the output of "0.75" days for example.
okay cool , I'll did in.
When i place...
{% set degree = states('sensor.openweathermap_temperature') | round(1) %}
{% set weather = {
"temperature": degree,
"unit": "Β°C"
} %}
at the beginning of my automations.yaml file it throws a bunch of syntax errors.
how do i define degree, and weather
That isn't meant to be used by itself. It needs to be in the template that it's associated with
will that insert it into the file on its own
Let's take a step back. What are you trying to use this with?
build an if statement based on how many items are returned from the .split(', '). 1 item means no days, 2 items means days. Use the length filter to see how many items are in d.
I believe the .split(',') will return an error if there is no "," correct?
no
I have an automation that updates a text box, i need it to dynamically check the temperature and use the temperature from open weather maps in the string it updates the text box to
In the template editor, I am currently getting "UndefinedError: list object has no element 1" and the uptime sensor is 18:39:37. So .split(',') would be = 0?
just look at the value of d when you split it
FYI I already gave you the answer
just reading my initial response, you can gather what d will be without needing to test it, but if you need to test it, test it properly by looking at the value.
I found this if statement in the forums and it seems to work. Returns 18.78
{% set d = states('sensor.glances_ubuntuserver_uptime').split(', ') %}
{% set x = 1 if 'day' in d[0]|lower else 0 %}
{% set t = d[x].split(':') %}
{{ (d[0][:2] | float + (t[0] | float / 24) + (t[1] | float / 1440) + (t[2] | float / 86400)) | round(2) }}
That's one way to do it, but copying/pasting code will never teach you how to do this
especially with lazy variables
yep
I understand, but that if statement is testing if "day" is present in d[0]. If it is (X Days, HH:MM:SS) then it sets x=1 which makes d[x] in the next line d[1] which is the second split (HH:MM:SS) . If "day" is not present, then it sets x=0 which makes d[x] in the next line d[0] which is the first split (also HH:MM:SS)
I understand the logic behind it for sure. What do you mean by lazy variables?
d, t, x
d/x/t are very bad for readability
doesn't tell you crap
gotcha, so spelling them out would be better. Day, time, for example
{% set uptime = states('sensor.glances_ubuntuserver_uptime') %}
{% if uptime not in ['unknown', 'unavailable'] %}
{% set uptime = uptime.split(', ') %}
{% set days = uptime[0] if uptime | length == 2 else 0 %}
{% set hour, minute, second = uptime[-1].split(':') | map('float', 0) %}
{{ days + hour / 24 + minute / 1440 + second / 86400 }}
{% endif %}
much better, easier to understand.
if you use an availability template, you can reduce this down to just the meat inside the if statement
That is giving the following error in the template editor: TemplateRuntimeError: No filter named 'split' found.
Also. just an FYI adding seconds into your calculation is useless when you round it to 2 decimal places
good point
see if you can spot the split error
| means filter
one of your splits work, the other doesn't
so how would you fix the one that doesnt?
the first split (row 3) should work because it is splitting uptime which is set to "X days, HH:MM:SS"
yep
but the error has nothing to do with the output of what it's splitting
it's a syntax error
| means filter
your error is: TemplateRuntimeError: No filter named 'split' found.
Not sure what happened but when I pasted it, I ended up with `uptime[-1] | split(':') which caused the error
I fixed it by removing the | and it works
well you should have changed it from | split to .split
I edited the post when you said the error before I pointed you to where the error is
Sneaky but helpful π
π
I understand uptime[0] and uptime[1] with splits. What is uptime[-1]?
you can go backwards in lists
forward: [ 0, 1, 2, 3, 4 ... n]
backward: [ n ..., -4, -3, -2, -1]
so... in your case, if the split worked: [-2, -1], if the split didn't work [-1]
but isn't HH:MM:SS uptime[1] after the first split of X Days, HH:MM:SS
it is
but time will always be the last item in the list π
uptime (If has a comma)
[ 'x days', 'HH:MM:SS']
uptime if it doesn't have a comma
[ 'HH:MM:SS' ]
{{ [ 'x days', 'HH:MM:SS' ][-1] }} #returns 'HH:MM:SS'
{{ [ 'HH:MM:SS' ][-1] }} #returns 'HH:MM:SS'
try it yourself
do you use the template editor?
yes, but i thought uptime[0] would be the first item in the list and uptime[1] would be the second item in the list. Am I thinking of that wrong?
yes, just trying to make sense out if it. I will play around with it in the editor
do you understand forward and backward on a list?
yes, i do now
you can access items forwards or backwards
a negative determines the direction you're accessing it
got it. Makes sense now
0 is the first item, 1 is the second
-1 is the last item, -2 is the second to last
so you can do it however you want
was just going to type that
in your case, time will always be the last item
and this filter must provide the position in the split of HH:MM:SS map('float', 0)
no, that maps all values in a list to a float
and if it fails, it maps the value to 0
['0', '1', '2', '3', 'a' ] | map('float', 0) will return [0,1,2,3,0]
because a can't convert to a float
got it
when using set if you have 3 items, you can list them in the order they come without needing to specify an index
{% set a, b, c = 1, 2, 3 %}
a will be 1, b will be 2, c will be 3
as opposed to doing the following
but hours, mins, secs are not "in order" so you have to define an index
{% set a = 1 %}
{% set b = 2 %}
{% set c = 3 %}
they are in order
the format is HH:MM:SS
hours first, minutes second, seconds third
when you split 'HH:MM:SS' it will always return ['HH', 'MM', 'SS']
Got it. I thought you mean alphabetical order
first in, first out
I have an automation that updates a text box, i need it to dynamically check the temperature and use the temperature from open weather maps in the string it updates the text box to
I'll follow up with you tonight if nobody gets to it by then
kk
OK, I should have asked here, instead I was thinking out loud in #automations-archived and wandered into the template realm from there. I'm very much a rookie in templates, so I'm not sure if this is possible, but here's the situation and what I'd like to do.
For my bath fan, I have a normal toggle switch and a Shelly1 connected to it. Currently, I have an automation that catches the turn on event, turns the fan off, then back on (go see the automation channel for why), sets a 15 min delay then turns it off. This is the "Clear the air" automation.
I've got an Rh sensor set to turn the fan on when Rh > 65%
I want to use a double-toggle to lock out the Rh sensor for 15 minutes so the bathroom can steam up when desired.
I'm thinking I can use the "Turning an event into a binary sensor" section of the template docs to catch the Shelly switching state. If it turns on & Rh < 65%, create a binary_sensor called "ManualOn". If it turns on then off but takes at least 1 second but less than 5 seconds to do so, then create a binary_sensor called "HoldTheFan".
do you have a motion sensor in the bathroom?
When "HoldTheFan" is true, start a timer. Finally create a binary_sensor called "TurnOnTheFan" that is ( (Rh > 65% and "HoldTheFanTimer" is idle) or (ManualOn)) which would actually determine if the fan goes on or off.
No - no motion sensor.
that seems reasonable then
I keep thinking that I need a button shield for the WeMos with the Rh sensor and use one tap on the button for "clear the air" and a double-tap for "steam it up" and just leave the toggle switch out of the equation. However, I don't have that either...
well, I'm glad to hear my pie-in-the-sky dreaming is reasonable! π
is the event coming in to HA? if so, you could probably skip the sensor and just fire an automation on the event
I see delay_on in the binary_sensor template parameters, so I think I'll need to use that for the "on" template
Part of the problem is that this is a smart fan with its own built-in Rh sensor that doesn't work very well any more. Turn the fan on, the blue light comes on and it's in auto mode. Flip power off, then back on and the yellow light is on and it's in manual on mode. So the automations require a triple-flip dance to get it to come on (for "clear the air", it's catch the switch-on for 5 seconds event, turn power off, delay 500ms, turn power on).
So, I have to work around the fact that the power is going off and on multiple times just to get the fan to turn on, and everything I do has to work around that.
ah ok
Of course, it might be easier to replace the bloody fan with a stupid-out-of-the-box one instead of stupid-because-it's-broken one, but hey, I'm up for a challenge and not spending extra cash! π
The power-on for 5 seconds is easy to capture and deal with. It's the power-on briefly then off to set the "steam it up" mode that I'm not sure how to best handle. An automation, a template, or what...
My thoughts after reading the docs is that a template to determine the ultimate, desired fan status that takes into consideration Rh, manual on, and manual delay is the way to go, I'm just not sure how to get there.
wonder if you could just replace the controller with a shelly or esp or something
I've got a Shelly in the box with the switch, and just built an esp as the Rh sensor. Are you talking about replacing the fan's controller with my own hardware?
there's probably a relay somewhere in there that switches the motor on and off
Up next on this week's episode of "Hacking bathroom hardware"...
haha
I s'pose I could take a look at it. I'm not quite the electrical genius I would like to be. Household wiring? No problem. Actual electronics? I'm... a bit lost...
Though I did just solder a couple of wires to my garage door opener switch to be triggered by another ESP out there...
Something to think about. The wife is amused and tolerating the playing so far. Blowing up the fan and needing to replace it may be a bridge to far at the moment. π
so in the unit should be a cuby thing that has wires coming from the mains and going to the motor
Yeah. I installed it a couple of years back (got tired of people not turning it on or forgetting to turn it off), but I never opened it up to look at the guts of the thing.
though you would just need to detatch the motor side, run it to your own relay that can handle mains power. run the control signal from some sort of board you control
and that's exactly where I get lost... π¦
Big picture brush strokes like that, I'm with you 100%. Actually figuring it out is the tough part. Sure there's not a software way around it? π
probably some, but things like shelly and esp make it pretty easy
OK. Am about done for the night. will set it back up for semi-automatic operation for tomorrow's showers. I might just try popping the box open tomorrow evening to see if it looks obvious enough to attempt a hardware hack. Otherwise, I'll continue to prod at it with HA.
thx for the thoughts!
good luck!
if by "text box" you mean an input_text, try this:
- service: input_text.set_value
data:
entity_id: input_text.whatever
value: >
{% set temp = states('sensor.openweathermap_temperature') | round(1) %}
The temperature is {{ temp }}
How do I find where this error is coming from? ('from_side' is not anywhere in the yaml files) ```WARNING (MainThread) [homeassistant.helpers.template] Template variable warning: 'dict object' has no attribute 'action_from_side' when rendering '{{ value_json.action_from_side }}'
it happens when I run an automation for a xiaomi cube (triggering using rotation, not sides) and possibly prevents it from finishing the automation
I do mean input_text, and if it's that easy i might cry.
Hey, uh, that worked. Thanks. Took 2 days of asking, but i understand more about defining variables and templating now. Thanks a lot.
You also taught me, input_text.set_value was a thing. I was using a script i found online.
Always chilling words π
guess i need to learn python
hi. i was wondering if this is possible
{{ is_state('sensor.superb_iv_charger_max_ampere', states('input_number.ampere_step')) }}
or should i use {% if ... instead of
ah, nevermind. it's working but input_number is 6.0 and not 6
|int will fix that
any template / sensor gurus around?
not a one
Don't ask to ask, just ask your question. Then people can answer when they're around.
When you do ask a question, try to provide as much background detail as possible. Ask yourself these questions first so that others don't have to:
- What version of the Home Assistant are you running? (remember, last isn't a version)
- What exactly are you trying to do that won't work?
- Is the problem uniform or erratic?
- What's the exact error message?
- When did it arise?
- What exactly don't you "get"?
- Can you share sample code, ideally with line errors where the error occurs?
None
haha - trying to install the following card -
https://github.com/davidrustingha/F1-Calendar-Card/
as you can see here
https://github.com/davidrustingha/F1-Calendar-Card/issues/3
I am struggling hard on this one - Cannot get the sensor code to be seen in HA
yea im almost at the end of my rope on this one and going to rebuild a new sensor,.... butttt would wbe the most complex thing i've dabbled in
using attributes, i've never done - wondering if someone would mind throwing me an example bone and i can run from that - or I may just do individual sensors
Yea im going to remove the dutch?
I don't have any, but there's one in the docs: https://www.home-assistant.io/integrations/template/#device-tracker-sensor-with-latitude-and-longitude-attributes
Thanks @inner mesa
and then there's this: https://www.home-assistant.io/docs/configuration/templating/#states
I'll start with those - spent like a week on this and his "copy / paste" is not working
OK, thinking my install may have an issue now - i removed all other sensors and copied the first example (updated to my phone for both GPS and NMAP device) and i still dont get the template in my entities
any ideas on how to specify a default for int here? map('int')
map('int', 0)
i tried that - it didn't seem to like it
map(('int'),default=0) it what I just used... let me try yours
{{ ["foo", "9"]|map('int', 45)|list }}
yes
that makes the default for int 0 when it fails to parse
thanks
3rd arg is base
very sorry to ask but i'm not getting around itπ« . From restful i am getting this sensor with this attributes: watt_hours_day: '2021-10-28': 7756 '2021-10-29': 3541 '2021-10-30': 3578 '2021-10-31': 3411 friendly_name: FV production estimate SE
how can i extract each day and make a sensr template from it? the number of days will vary and every day they will change
i can extract the dictionary with the follow jinja code: {{ state_attr("sensor.fv_production_estimate_se", "watt_hours_day") }}
Hi. As all stupid questions begin, I am very new to this. I have a wifi plug connected via localtuya (HACS). This plug is configured as a switch which has the power statistics as its attributes (current, voltage, current_consumption). My end-goal is to be able to trigger based on something like "average current in the last 15 minutes > 10".
I have added this configuration to my configuration.yaml: ```sensor:
- platform: template
sensors:
washer_power_sensor:
value_template: {{states.switch.doubleplug.attributes.current}}
unit_of_measurement: mA
history_graph:
power:
name: Washer Power Graph
entities:
- sensor.washer_power_sensor```
A restart is rejected with the error invalid key: "OrderedDict([('states.switch.doubleplug.attributes.current', None)])" in "/config/configuration.yaml", line 18, column 0.
I found that the documentation says I should probably be using state_attr() instead, so I tried replacing value_template: with something like {{ state_attr('switch.doubleplug', 'current') }} but this fails too with a different error message while parsing a flow mapping in "/config/configuration.yaml", line 18, column 26 expected ',' or '}', but got '<scalar>' in "/config/configuration.yaml", line 18, column 69
I somehow found that doing this bespoke with InfluxDB and python was felt less complicated and like less work but I wanted to try a solution like HomeAssistant as it should scale a bit better and be more manageable... Maybe someone can point out where I'm making a dumb mistake π
if you're trying to get today:
{{ state_attr("sensor.fv_production_estimate_se", "watt_hours_day").get(now().date()) }}
yesterday
{{ state_attr("sensor.fv_production_estimate_se", "watt_hours_day").get((now()-timedelta(days=-1)).date()) }}
templates that are in line with the field requrie quotes.
field: "{% set x = 4 %}{{ x }}"
templates that do not require quotes use the 'multiline identifier (>)'
field: >
{% set x = 4 %}
{{ x }}
How can I get rid of this warning every time I boot HA: "Template variable error: 'None' has no attribute 'last_changed' when rendering '<font size=4>......"? It's part of this markdown card: https://pastebin.com/LCCKwL9U
check for none
on states.sensor.xxxxxxx before accessing states.sensor.xxxxxxx.last_changed
uh that template is odd too
but I guess it works so
You can also use expand instead
which will get around checking for none
{%- set fmat = "%d/%m/%Y %H:%M:%S" %}
<font size=1>
{%- for s in expand('sensor.brukskonto_2222', 'sensor.brukskonto_22223') %}
{{ s.name }} endret: {{ as_local(s.last_changed).strftime(fmat) }} | Oppdatert: {{ as_local(s.last_updated).strftime(fmat) }}
{%- endfor %}
</font>
Ah I had it quoted when I received the error but the version I pasted here did not but Iβll double check
if you use quotes in your template, you need to use opposite quotes outside
"{{ 'inside' }}"
as a beginner, I suggest you just use the multiline indicator
otherwise you'll get these errors all the time if you don't know how to properly quote.
What about {% if states.sensor.brukskonto_2222 == None %} Loading... {% else %} <font size ....... {% endif %}?
I don't understand expand yet π
there's nothing to understand..
it gives you a list of entities that you request
states.abc.xyz gives you the state object
expand('abc.xyz') gives you the state object in a list
however expand doesn't return stuff that doesn't exist
which avoids your none check
Ah, I see. Thanks.
@mighty ledge It was my quoting π€¦ββοΈ Thank you
Hi.
I am trying to fix a special name in a entities-card but I cant get it correct. The entity is sensor.balcony_temperature but I want the name to be the state of a sensor named sensor.balcony_temperature_stats_max_age.
I have got the entity to work but not the name.
What am I doing wrong?
card:
type: vertical-stack
cards:
- type: entities
card_mod:
class: content
entities:
- entity: >
[[[ return entity.entity_id ]]]
name: Aktuell temperatur
- entity: >
[[[
return entity.entity_id + "_stats_max";
]]]
name: >
[[[
return states['sensor.balcony_temperature_stats_max_age'].state;
]]]
This works but I want it more like:
name: >
[[[
return states['entity.entity_id + "_stats_max_age"'].state;
this channel is really for Jinja templates, not anything from the frontend (as in the topic)
In any case, I wasn't aware that that template style was supported there, but the problem with your "I want it more like this" example is probably that you put quotes around the whole expression in the square brackets
entity.entity_id is a variable, and you probably want return states[entity.entity_id + "_stats_max_age"].state;. But again, I'm surprised that that template style works at all there
I will try it tomorrow when I wake up. I thought it was the correct channel since it was template I worked with π
I will try it anyway when I wake up, Thx!
Hmm, maybe I should put this here, lol
The following template does not appear to be working.. what is wrong with it? value_template: '{{ now().month != 10 and now().day != 31 }}'
It appears to look to see that month IS in fact 10, and just stops.. Should the 'and' not make it look at both?
you would want OR if you want "either"
thank you, i am also trying to assign a name to the sensor with the date embedded on in, i tried sing the unique_id and change the name with a name template like this: `template:
- sensor:
- unique_id: pv_forecast_today
name: "production for: {{ now().strftime('%Y-%m-%d') }}"
state: >
{% set day = now().strftime('%Y-%m-%d') %}
{{ (states.sensor.pv_forecast_rest_se.attributes['result']['watt_hours_day'][day] + states.sensor.pv_forecast_rest_so.attributes['result']['watt_hours_day'][day]) | float() / 1000 }}
attributes:
unit_of_measurement: "kWh"
device_class: power
icon_template: "mdi:solar-panel" `
- unique_id: pv_forecast_today
but the name does not show up
Hey! I found Bear Stone's HA Rep and I am trying to use some of his code but first I need to understand it so I can adapt it to my needs. I am especially in love with his speech engine and all that template stuff. I understood the macro he is using but now I don't understand this template(?)
It is getting a little dark inside the house because of the {{trigger.entity_id.split('_')[2]|replace('precip','rain')|replace('counter','lightning')|replace('carlo','rain') }} {{trigger.entity_id.split('_')[3]|replace('intensity',' ')| replace('carlo','and clouds')}} outside. I will turn on some extra lights in the living room.
It's this automation. https://github.com/CCOSTAN/Home-AssistantConfig/blob/0314ddf9ef28f4ab4305983d73365f852713594f/config/automation/dark_rainy_day.yaml
What needs to be changed or what exactly is being done there?
Look at the triggers in the automation. He is using the name of the trigger in his notify and substituting words that make sense.
Google jinja split
So basically in this replace('precip','rain') it replaces precip with rain? Where is precip from? From the trigger I guess but why does it just needs precip and not dark_sky_precip? Also what does split('')[2] or split('')[3] do ? Tried googling jinja split but I am more of an user than a dev so its pretty much gibberish for me which I cant apply to my problem.
Anyone?
Buehler...
replace('x', 'y') replaces any instances of the substring 'x' in the input with 'y'
{{ "foobar"|replace("bar", "blah") }} -> fooblah
That jinja expression looks like it's designed for a very specific set of specifically-named entities. It's not any sort of general-purpose template
And @naive plank Isnt active anymore :/
There's really not much to that and you can tell what it's doing by looking at the triggers. It simply turns on lights if it's dark outside using a lighting counter, rain sensor, and an awake sensor. That template on the other hand is horrendous. You can build a better template now adays using trigger id's instead of parsing the trigger entity_id's apart.
you can't template the name, you can only template the friendly_name. Which needs to be in the attributes.
Looks like you can
name template (optional)
Defines a template to get the name of the sensor.
I thought the same
not sure I believe that
you'd get into a chicken - egg scenario if you have a template without a unique_id
Yah, looking at the code I don't see how it would be possible
you need either the name or the unique id and a name template wouldn't produce a valid unique_id
unless it just defaults to senso.template_x
which is possible, I'd have to brush up on the unique_id/naming crap they implemented a while back
in a quick test, it initially creates the entity_id with the state of the template at time of creation, but future changes to the template create and modify the friendly_name
yeah, it was more of my attempt to get Discord support to fix the persistent unread channel issue
template:
- sensor:
- name: foo_{{ states('input_text.test')}}
state: "foo"
yah, but in @thorny snow 's case, he's using a date. I'm not sure how they attach to the correct unique_id because it's constantly changing
restart with input_text set to blah
doing it now. I'm betting that it stays with sensor.foo_bar
I also didn't give it a unique_id
is yours a dev box?
no, it runs my house
ha! it's now sensor.foo_blah
ah it is?
!
see if it got a unique_id?
yah
kinda had to
it would be in enitty_registry
boy that's a bug
and why it shouldn't be a template
lol
that's weird. foo_ is no where in .storage
π€·ββοΈ I would assume it has to be in the entity_registry
all my templates are there
and yet
and from
-> Entities, more-info
This entity ('sensor.foo_blah') does not have a unique ID, therefore its settings cannot be managed from the UI. See the documentation for more detail.
You can overwrite some attributes in the entity customizations section.
nope
it's useful if you do this tho
template:
- sensor:
- unique_id: foo
name: "{{ ... }}"
lemme see if that makes it more dynamic
that will plop it into the registry
because it now has a unique_id
i'd wager that your entity_id would be sensor.template_foo or sensor.foo and the unique_id would be foo (in the registry) and you'd be golden because the startup process would always get the same unique_id
it's in there now, but the name still doesn't change dynamically
Whops, sorry thought I've been there
Now that it has a unique_id, the entity_id is frozen and only the name and friendly_name are changing
I see little use for this functionality
I guess the displayed name will update, if that matters. but it's usually the state that you care about
@floral shuttle has use cases for it
no doubt
hahaha, now that you're asking for it:``` - unique_id: dark_sky_forecast_0
name: >
Today: {{states('sensor.dark_sky_forecast_icon_0d').replace('-',' ')|capitalize}}
state: >
{{- states('sensor.dark_sky_forecast_daytime_high_temperature_0d')}}Β°/
{{- states('sensor.dark_sky_forecast_overnight_low_temperature_0d')}}Β°/
{{- states('sensor.dark_sky_forecast_precip_probability_0d')}}%
picture: >
{{'/local/weather/icons/' ~ states('sensor.dark_sky_forecast_icon_0d') ~ '.png'}}
It's always weather related!
ofc.... or pond: - unique_id: sensor_vijverpompen name: > {% set temp = states('sensor.pond_buiten_sensor_calibrated_temperature')|float(0) %} {% set dark = 'Licht' if is_state('binary_sensor.dark_outside','off') else 'Donker'%} {{dark}} en {{temp}}Β°C - Vijverpompen {{'moeten: ' if is_state('binary_sensor.vijverpompen','on') else 'mogen: '}} availability: > {{states('sensor.pond_buiten_sensor_calibrated_temperature') not in ['unknown','unavailable']}} state: > {{'Aan' if is_state('binary_sensor.vijverpompen','on') else 'Uit'}} icon: > {% if is_state('binary_sensor.vijverpompen','on') %} mdi:engine {% else %} mdi:engine-off-outline {% endif %}
also some weather....
perfect tank you but anyway also with the friendly name the date does not shows up: `template:
- sensor:
- name: pv_forecast_today
state: >
{% set day = now().strftime('%Y-%m-%d') %}
{{ (states.sensor.pv_forecast_rest_se.attributes['result']['watt_hours_day'][day] + states.sensor.pv_forecast_rest_so.attributes['result']['watt_hours_day'][day]) | float() / 1000 }}
attributes:
friendly_name: "production for: {{ now().strftime('%Y-%m-%d') }}"
unit_of_measurement: "kWh"
device_class: power
icon_template: "mdi:solar-panel"
`
- name: pv_forecast_today
@thorny snow Your message has been deleted as it contains a link or a domain name 'pasteboard_dot_co' that is on the blocked list because of: 'Virus detected!'.
Please re-post by removing/changing the domain name/link. Your original message has been DM'ed to you.
on friendly name it show the fixed part but the templete does not show up, maybe i am doing something wront on templating the date
Question about the 'new' Template integration, please. In the example here: https://www.home-assistant.io/integrations/template/#all-sensor-binary-sensor-number-select-entities, it shows both Sensor and Binary Sensors under Template:, and below that Sensor and Binary Sensor TRIGGER-BASED sensors. The figure seems to indicate that you can only have a single Trigger for all your sensors/binary sensors, but I know that CAN'T be right. Would you just duplicate the - trigger: block as needed?
And is everybody converting their old style sensors to the new template:?
Yes you add multiple - trigger: blocks. I cant speak for everyone but I switched all mine over. There was no real reason to, but it did give me a good understanding of the new method.
Cool. Thanks Tom.
Conversely, I haven't converted mine because I can't be bothered to lol
So, I'm working to consolidate my Templates, and am running into issues. Do you have only a single - sensor:, - binary_sensor: and - trigger: in the template: section, or one for each of the sensors? Only my first Sensor is showing up (after making the various tag name changes).
And things like sensor.date and any other sensor that relies on a - platform: must remain in the sensor: section, right, not under template:. For example:
- platform: time_date
display_options:
- 'time'
- 'date'
additional sensors are nested under the type of sensor you're defining - - sensor:, - binary_sensor:
That's what I thought, but when I do the following, only the first is valid after reload.
- sensor:
- unique_id: solar_angle_st
name: 'Solar Angle (ST)'
unit_of_measurement: 'degrees'
icon: mdi:angle-acute
state: "{{ state_attr('sun.sun', 'elevation') }}"
- unique_id: nextsunrise_st
name: 'Next Sunrise (ST)'
icon: mdi:weather-sunset-up
state: "{{ as_timestamp(states.sun.sun.attributes.next_rising) | timestamp_custom(' %I:%M %p') | replace(' 0', '') }}"
I'm not using the new format, but that's what it shows here: https://www.home-assistant.io/integrations/template/#storing-webhook-information
Oh, wait, I edited a card that was showing unavailable, entere the exact same sensor, and when saved, it appeared OK. The other one is still unavailable. I'll edit it too. sb.
best to check in
-> States
Oh, SHITE! It's not using my unique_id as the entity_id. I thought that was the purpose of it. It changed the entity_id to a conflagration of the name:.
well that sucks...
the unique ID is just a identifier to uniquely identify that entity and differentiate it from others
I don't think it ever had any relationship to the name
when you have one, you can edit the name from the UI
but it isn't the name
How can I select an entity_id from a drop down?
specifically a media_player, I already have my input_select entity created but I dont know how to create the script systax.
target:
entity_id: '{{???}}'
entity_id: "{{ states('input_select.whatever') }}"
and the input select options need to be "media_player.tv"
can that have a pretty name?
or if the input_select just says TV you could do
"media_player.{{ states('input_select.whatever').lower() }}"
makes the result lowercase
Thanks again Tediore

@ruby pollen Your message has been deleted as it contains a link or a domain name 'pasteboard_dot_co' that is on the blocked list because of: 'Virus detected!'.
Please re-post by removing/changing the domain name/link. Your original message has been DM'ed to you.
data:
message: ESP32 Sensor down
``` Is there any nice way to add the sensor name here?
"{{ trigger.to_state.name }}"
hello one question i have multiply two sensors with this: value_template: β{{ ( (states('sensor.aaa') | float ) * (states('sensor.bbb') | float) ) | round(2) }}β
why i am getting:
β47.16β β¬
how to get only 47.16 β¬
Where do you see that?
lovelace
In a card?
yes and in developermode
You will see that in
-> templates because itβs just interpreting the template
in templates i see this: 47.16
there it is working but why i am getting in lovelace this apostrophes
Right, my dst sensor is a day offβ¦
In 15 hours π now why does is say Fall change is on 2022-11-01.. hmm
{%- set today = strptime(states('sensor.date'),'%Y-%m-%d').astimezone().replace(hour=ns.previous) %}
{%- for i in range(365) %}
{%- set day = (today + timedelta(days=i)).astimezone() %}
{%- if ns.previous - day.hour == -1 %}
{%- set ns.spring = today + timedelta(days=i) %}
{%- elif ns.previous - day.hour == 1 %}
{%- set ns.fall = today + timedelta(days=i) %}
{%- endif %}
{%- set ns.previous = day.hour %}
{%- endfor %}
{{([ns.spring,ns.fall]|min).isoformat()}}```
while this is correct: dst changed today: > {% set dt = now() + timedelta(days=-1) %} {{now().astimezone().tzinfo != dt.astimezone().tzinfo}} and ``` dst change tomorrow: >
{% set dt = now() + timedelta(days=1) %}
{{now().astimezone().tzinfo != dt.astimezone().tzinfo}}
Petro, I notice your sensor is also a day off:https://github.com/Petro31/home-assistant-config/blob/master/template/daylight_savings_time.yaml ..
You didnβt set previous properly
What time does dst change in your time zone?
For me, it changes at 2am, hence I put in 2
@floral shuttle
Hello. Can You help me with this error:
Template warning: 'as_timestamp' got invalid input 'unknown' when rendering template '{% if (((states.sensor.hideki_rain_0|float) - (states.sensor.rain_10_minutes_ago.state|float))*6) > 0 %} {{ as_timestamp(now()|timestamp_custom("%Y-%m-%d %H:%M:%S %Z")) | timestamp_local }} {% else %} {{ as_timestamp(states.sensor.last_rain.state|timestamp_custom("%Y-%m-%d %H:%M:%S %Z")) | timestamp_local }} {% endif %}' but no default was specified. Currently 'as_timestamp' will return 'None', however this template will fail to render in Home Assistant core 2021.12
gosh I never realized that would impact it . its 3 am over here..
Yep
set it to 4 to be unless you're feeling luckly like myself. I chose exactly on the time it changes
set it t 3 now, and the future times have changed accordingly π will check to be sure on the official time site. thx
sure
Ok give me a minute.
np just ping me
put this into your template editor
{%- macro tod(day) %}
{%- set day = strptime(day | string, '%Y-%m-%d').astimezone() %}
{%- set ns = namespace(tz=day.strftime('%z') | int, return=none) %}
{%- for i in range(0, 60*24) %}
{%- set t = (day + timedelta(minutes=i)).astimezone() %}
{%- set change = t.strftime('%z') | int %}
{%- if change - ns.tz and ns.return is none %}
{%- set ns.return = t %}
{%- endif %}
{%- endfor %}
{{- ns.return.isoformat() }}
{%- endmacro %}
{%- set ns = namespace(previous = 0, spring=none, fall=none) %}
{%- set today = strptime(states('sensor.date'), '%Y-%m-%d').astimezone().replace(hour=ns.previous) %}
{%- for i in range(365) %}
{%- set day = (today + timedelta(days=i)).astimezone() %}
{%- if ns.previous - day.hour == -23 %}
{%- set ns.spring = tod((today + timedelta(days=i-1)).date()) %}
{%- elif ns.previous - day.hour == 23 %}
{%- set ns.fall = tod((today + timedelta(days=i-1)).date()) %}
{%- endif %}
{%- set ns.previous = day.hour %}
{%- endfor %}
{{ [ns.spring, ns.fall] }}
paste the results
[
"2021-10-31T02:00:00+01:00",
"2022-03-27T03:00:00+02:00"
]
well, it is the exact minute it changes, which drops it or raises it
any specific reason for this change? is it more robust?
it finds your exact minute
that the change happens
{%- set today = strptime(states('sensor.date'), '%Y-%m-%d').astimezone() %}
{%- set ns = namespace(tz = today.strftime('%z') | int, next=[], tz2=none, return=none) %}
{%- for i in range(365) %}
{%- set day = (today + timedelta(days=i)).astimezone() %}
{%- set tz = day.strftime('%z') | int %}
{%- if ns.tz - tz != 0 %}
{%- set day = (today + timedelta(days=i-1)).astimezone() %}
{%- set ns.tz2 = day.strftime('%z') | int %}
{%- set ns.return = none %}
{%- for i in range(0, 60*24) %}
{%- set t = (day + timedelta(minutes=i)).astimezone() %}
{%- set change = t.strftime('%z') | int %}
{%- if change - ns.tz2 and ns.return is none %}
{%- set ns.return = t %}
{%- set ns.next = ns.next + [ns.return.isoformat()] %}
{%- endif %}
{%- endfor %}
{%- endif %}
{%- set ns.tz = tz %}
{%- endfor %}
{{ ns.next }}
try that
[
"2021-10-31T02:00:00+01:00",
"2022-03-27T03:00:00+02:00"
]
ok, so same times
yes
Ok will do when I get back from 007 π
I'm going today to see that
me too, have fun
thanks for all the work on the dst sensors, experimenting right now to see if things change. A related (probably automation trigger question, so please indulge me here): do we still need the - platform: homeassistant event: start - platform: event event_type: call_service event_data: domain: template service: reload on event: start, if the template reload is also there? I mean, doesnt a restart also always cause a template domain to reload by default?
reload is separate from a start
so if you reload your templates without restarting, it will update
yes, but i was asking the other way round: on restart, doesn't it also automatically 'reload' templates. And wouldnt it suffice having that in the trigger?
It does
but what happens when you just want to reload the templates
it would set those to none
ok, its of no importance really, was just trying to minimize where possible. for now, I can see the 'Daylight Savings: Next' state template in dev-tools, but can not get it to work as template at all
Not sure what you mean
ok so I just restarted, and now have a functional trigger template sensor. However, upon entering the Phrase template in dev tools, I get ValueError: not enough values to unpack (expected 3, got 1)
yah, check out the thread again, changes were made
ok will do. I do believe I copied it from the community post opening post though.. you did edit that did you?
yep
I use the following trigger to check for template reloads:
- platform: event
event_type: event_template_reloaded
Hi everybody, dunno what to do with it:
2021-11-01 15:17:26 WARNING (MainThread) [homeassistant.helpers.template] Template warning: 'strptime' got invalid input '2021-11-02T11:45:25+00:00' when rendering template '{{ as_timestamp(strptime(state_attr("sun.sun", "next_noon"), "")) | timestamp_custom("%H:%M") }}' but no default was specified. Currently 'strptime' will return '2021-11-02T11:45:25+00:00', however this template will fail to render in Home Assistant core 2021.12
is this strftime ?
no, strptime is doing nothing. strftime is for converting to a string, strptime is for converting to a datetime
Could be replaced by : {{ as_timestamp(states.sun.sun.attributes.next_noon) | timestamp_custom('%H:%M')}} ???
Yup , thant worked. Thanks Petro π
np
So, i'm tryng to send a sensor's temperature using rest command, but it always sent a [Object object] string,
Tried those, several ways of write the templating, but no luck
The sensor name is 'sensor_botao_temperature'
Could any one give some light? Tries google it in the foruns and like by problems
This is the right place right? Because my doubt is over the templating aspect of the problem
Then that's not a rest endpoint
Hopefully someone clever can help - I'm trying my first template.... the plan: on a button press to increase brightness value by 15, but using an if/else condition so that if the brightness value would exceed 255 it would just be 255
https://paste.debian.net/1217685
That's my best attempt so far, although clearly still haven't got it working!
{{ min(state_attr('light.light_example', 'brightness') + 10, 255) }}
And it's just data. data_template is deprecated.
thats a function that automatically provides a max value, so avoiding the need for if/else statements?
Yes. It will always pick the lowest of the two values, which in this case means it maxes out at 255.
and can presumably switch min to max and set a low point for reducing value too?
Indeed. Or max(lowest, min(highest, value)) to clamp value between lowest and highest.
sounds exactly what I've been trying to badly create!
whats the name of teh function so I can read further in docs?
Hm... well, the templates are jinja... but they do a bit of python... so I guess here, maybe? https://docs.python.org/3/library/functions.html
ah - I've been trying to stick to the HA docs like https://www.home-assistant.io/docs/automation/trigger/ as I tend to get confused by multiple languages and syntax etc!
The link I gave is in the templating docs too https://www.home-assistant.io/docs/configuration/templating/.
Turns out min and max are there too https://www.home-assistant.io/docs/configuration/templating/#numeric-functions-and-filters
Think it helps when you know what you're looking for!
certainly all seems to work when in templating, but when I throw it together in an automation I get error of a missing colon...
- id: '1016'
alias: b1 rn 6
description: 'click b1 rn up'
trigger:- platform: state
entity_id: binary_sensor.b1_rn_6
to: "on"
action: - service: light.turn_on
entity_id: light.bed1_headboard_3
data_template:
brightness: '{{ min(state_attr('light.bed1_headboard_3', 'brightness') + 15, 255) }}'
mode: single
- platform: state
I wrote a template sensor to change my gas meter's unit of measurement. Whenever I restart HA I get 0 readings which makes it look like I have had my gas meter's entire history of usage when it restarts.
How do I prevent it from considering missing data as zeros?
My template state is "{{ (states('sensor.gas_meter') | float * 0.02831684659) | round(3) }}"
`template:
- sensor:
- name: Gas Meter Metric
unique_id: gas_meter_metric
device_class: gas
unit_of_measurement: "mΒ³"
state: "{{ (states('sensor.gas_meter') | float * 0.02831684659) | round(3) }}"
state_class: total_increasing`
- name: Gas Meter Metric
Is there a more appropriate place for me to be asking this?
Nope, just gotta be patient
probably need an availability template
Try this```
state: "{{ (states('sensor.gas_meter') | float(none) * 0.02831684659) | round(3) }}"
availability: "{{ (states('sensor.gas_meter') not in ['unavailable', 'unknown', 'none'] }}"
What does the none part of float mean? I need to find me an end to end tutorial on template markup/language. Everywhere I have looked so far only a small part is documented. For instance I didn't see availability: being a thing for template: sensors
Cool thanks. I will read that more carefully tomorrow. Obviously I missed the common parts earlier. D'oh.
There's also a good explanation of float(none) here: https://community.home-assistant.io/t/updating-templates-with-the-new-default-values-in-2021-10-x/346198
Thanks!
Is there a quicker way of doing this? A filter/function?
{% set temp = states('sensor.temperature')|float %}
{% if temp % 1 == 0 -%}
{{ temp|round }}
{%- else -%}
{{ temp }}
{%- endif %}
(for sending messages/tts)
You can do an inline if statement
{{ temp|round if not temp % 1 else temp }}
thanks @mighty ledge , thats pretty close to the imaginary
temp|round(0, if_int) that I had in my head π
Yesterday I was asking about a templatized sensor and dropouts being equated to 0. Based on the answers I found here I came up with the following which appears to work.
`template:
- sensor:
- name: Gas Meter Metric
unique_id: gas_meter_metric
device_class: gas
state_class: total_increasing
unit_of_measurement: "mΒ³"
state: >
{% if states('sensor.gas_meter') not in ['unavailable', 'unknown', 'none', none] %}
{{ (float(states('sensor.gas_meter')) * 0.02831684659) | round(3) }}
{% endif %}
availability: "{{ states('sensor.gas_meter') not in ['unavailable', 'unknown', 'none', none] }}"`
I suspect I don't need to check twice for undefined state. Also all the availability examples I could find used 'none' but when using the template designer none didn't equate to 'none'.
- name: Gas Meter Metric
none does not equate to 'none'
none is like null, it's a keyword in the jinja language
You'll never get 'none' or none from states() though
so all you need for the availability template is
availability: "{{ states('sensor.gas_meter') not in ['unavailable', 'unknown'] }}"
and you can change your state to
Is the if statement in the state extraneous?
{{ (states('sensor.gas_meter') | float(0) * 0.02831684659) | round(3) }}
it's just not needed
Cool
you can also get rid of availability if you leave the if statement
because '' is unavailable
Great, that's what I expected. The availability version is cleaner.
but, i like being explicit
I guess I need to answer what will @topaz galleon have an easier time reading next time.
Lol. Every once in a while I find old code that I actually like.
Not often though
Thank you @mighty ledge
np
hey Petro, did you see this: https://community.home-assistant.io/t/daylight-savings-time-dst-template-and-automation/351889/40
I did not, I'm not getting those at startup either
is that with the latest?
Could anyone spot a mistake, please ? {{ states('counter.sensor_house_power_meter_kwh')int + states('sensor.house_power_meter_kwh')|int }} Me making templates never goes well.
missing a | before the first int
Can I ask, if the "sensor.house_power_meter_kwh" is like 0.0002 It counts it as 0, why ?
ints don't have decimal places
You forced it to an int
if you want the decimals you should use float
Yeah, I see. It solved it.
I'm calling the zwave_js.setvalue with this script snippit as the value:. zwave_js appears to be interpreting the results of this as a string instead of a boolean based on the error message returned:
value: >-
{% set en = "{{ entity }}" %}
{% if is_state(en, 'on' ) %}
false
{% elif is_state(en, 'off') %}
true
{% else %}
false
{% endif %}
Am I missing something? This resolves OK in the dev tools > template
For a boolean use {{true}} or {{false}}
also, this is curious: {% set en = "{{ entity }}" %}
if it's a variable, use the variable
entity is passed in like this: - service: script.zwave_switches_toggle data: entity: switch.mbath_fan_shower
just use entity
Also this does the same thing as your whole template {{ is_state(entity, 'off' ) }}
you're turning it into a string, then back into a variable
hmmm, actually, I'm also using it in a macro on my floorplan {% macro fan_button(entity, x, y, size, border, background) -%} {# {% if not no_other %} #} - entity: {{entity}} type: custom:button-card style: { left: {{x}}%, top: {{y}}% } show_name: false show_label: false show_entity_picture: true tap_action: {# action: toggle #} action: call-service service: script.zwave_switches_toggle service_data: entity: switch.living_room_fan ...
where entity is a variable when im not testing it with a constant
I like the simplification tom l. I'll play with that some.
Perfect. Thank you both for the help.
hi, tryin to make a sensor via template from a mqtt aircon integration
but the lines from HA seem to be different from the ones specified in the docu
can someone take a look and tell me how they'd go about making a sensor out of one of these values?
f_humidity for instance, tryin to set it up as a sensor but it doesn't even show up in HA (im thinkin cos it's read only)
this is what does show up https://pastebin.com/3cK5NNcz
sorry missed your reply. yes that is with the latest. upon each restart.
Is that the full error?
I've updated the community post with the full error:https://community.home-assistant.io/t/daylight-savings-time-dst-template-and-automation/351889/43
Can anyone help with some templating oddity?
I've condensed my problem down to this example: {{ (1 | float /1000) + 1 | round(2) }}
with the +1 in there, the round appears not to work. If I remove the + 1 then it works properly. What am I missing?
you're rounding the value "1" to 2 decimal places
ah ok I think I see where I went wrong in my original code then
you really have to bracket everything
Thanks for the pointer π
I figured it would take everything before the pipe and send that into the round function but it's trying to round the 1 and then adding the result of that to the original unrounded result giving me too many decimal places
I spent an hour or so trying to figure this out, playing with the developer tools template etc. Doh
Can I please have some help with this error?
Template warning: 'float' got invalid input 'unknown' when rendering template '{{ states('sensor.washing_machine_energy_power')|float > 10 }}' but no default was specified. Currently 'float' will return '0', however this template will fail to render in Home Assistant core 2022.1
your sensor reported "unknown" at some point rather than a number
This is after a restarted HA
you should fix that by adding a default to |float like |float(0.0), or revisit the sensor
there's a section in the breaking changes of the last release on this
Ok RobC, thanks I'll have a play
can anyone help with converting value_template: "{{ state_attr('sensor.MainArylic', 'Album') }}" from hex to ascii? current JSON response is in hex.
I've got a template that selects the next lighting effect on a WLED Light, it achieves the desired result in the template area of developer tools. I would like to know how I can use this triggerd by a button press on an Ikea remote...
{% set effect = state_attr('light.wled', 'effect') if state_attr('light.wled', 'effect') else effect_list[0]%}
{{ effect_list[effect_list.index(effect)+1] if effect_list.index(effect) < effect_list|count-1 else effect_list[0]}}
Hi there! I've created a template, that sums all my sensor.energy (shelly EM x 4); I can't get it in the Energy. Also, I've created tariffs and utility meter, but I can't use it as a cost, it does not show up, except for the "current price" option; any ideas?
maybe I should post this in Energy channel
so ended up with my own solution using a commandline sensor instead. called out to a python script that converts
Did you provide unit_of_measurement: "kWh", state_class: total_increasing and device_class: energy to your sensor? Furthermore, this channel is to discuss the actual template, not the template sensor #integrations-archived or the #energy-archived dashboard.
I'm getting a warning about this template:
{% set reject_entities = [ 'sensor.tv_lamp_power', 'sensor.samsung_soundbar_power_meter', 'sensor.measured_power', 'sensor.unknown_power', 'sensor.zolder_bol_power' ] %}
{{
states.sensor | selectattr('entity_id', 'search', '_power')
| rejectattr('entity_id', 'search', 'estimated_power')
| rejectattr('entity_id', 'in', reject_entities)
| selectattr('attributes.state_class', 'eq', 'measurement')
| map(attribute='state')
| map('int')
| sum
}}```
The warning is: `Template warning: 'int' got invalid input 'unavailable' when rendering template`
But I don't use int except to map the values.. Where does this warning come from?
That's it. It applies int to each of the items in your list. One of them is unavailable.
Another rejectattr('state', 'eq', 'unavailable') might do it.
Ah okay, would map('int(0)') also work?
I could test that of course, and no, it doesn't π
Does this one make sense as a condition for an automation to run it only when it has not been ran for the last two minutes?
{{ now() > state_attr('automation.oue_varav','last_triggered') + timedelta(minutes=2) }}
map('int', 0)
Yes that should work
@gusty nimbus posted a code wall, it is moved here --> https://hastebin.com/ofaricosuq
maybe someone could find my template problem? π its not alot code i think since month 10 i get this error as a warning that things will change
anyone has a fix? π tx
This probably happens after a reboot. The entities used in the template are not ready yet, so the | float part is used on something unknown. To get the result you had without the warnings you can use | float(0) or | float(default=0)
hm ok tx
Hi, I want to use a OR condition in the value_template, but cannot find how. I tried: {% if (states('sensor.pv_power') == 'unknown' OR states('sensor.pv_power') == 'unavailable') %}
or should work. You can also use {% if states('sensor.pv_power') in ['unknown', 'unavailable'] %} or {% if is_state('sensor.pv_power', 'unavailalbe') or is_state('sensor.pv_power', 'unknown') %}
Thanks! or must be in lowercase, else it doesn't work. I like the in [] solution.
Is there a way to generate a template to list zwave devices with specific manufacturer / model? I know this used to be possible with the inbuilt zwave, but not sure if itβs still possible with zwave-js. Basically I want something like {{ states.light | selectattr(βmodelβ, βeqβ, βLZW31-SNβ) }}, but I have no idea If itβs even possible to access device data in a template.
I believe that device attributes were added a few months ago for this
See the templating docs
Why is it that I receive a config error when I set state_class: "measurement" to a template sensor? I want to get longterm statistics from this template sensor as it's a OCR reading of my gas usage but HA will not accept a state class.
~share your sensor definition
Please use a code share site to share code or logs, for example:
- https://www.codepile.net/ (select YAML as the language)
- https://paste.debian.net/ (select YAML as the language)
- https://hastebin.com/ (sometimes may not allow you to save)
Please don't use Pastebin, since it can randomly add spaces to the main view.
and what is the actual error?
https://imgur.com/a/Owx2qfM before and after I add state class and the error I get when checking the conf
yeah, looks like it's not allowed in the legacy template sensor format: https://www.home-assistant.io/integrations/template/#legacy-sensor-configuration-format
you can add it as an attribute, though
See above, it triggers an error when added. Maybe the documentation lacks details.
it's not allow, as per the docs
but you can add it as an attribute
or, see above π
I guess I won't. Thank you. I don't get it.
Simply put: place them under the attributes_template section
Hi guys. I have made a little sensor that refuse to pass the ha core check, and can't seem to find why... It works fine in dev_tools... Any idea?
{% if is_state('input_boolean.wakeup', 'on') %}
{% if now().isoweekday() in [6,7] %}
{{ today_at(states('sensor.morning')) + timedelta( hours = 2 ) }}
{% else %}
{{ states('sensor.morning') - timedelta( minutes = 15 ) }}
{% endif %}
{% else %}
{{ states('sensor.morning') }}
{% endif %}
Error I get is expected <block end>, but found '<block sequence start>', but cannot see I have any open brackets or if's...
found it. indentation issue, misplaced by one space
it has syntax errors
{% set morning = states('sensor.morning') | today_at %}
{% if is_state('input_boolean.wakeup', 'on') and morning %}
{% set delta = timedelta(hours=2) if now().isoweekday() in [6,7] else timedelta(minutes=15) %}
{{ morning + delta }}
{% else %}
{{ morning }}
{% endif %}
basically, your template will fail on weekdays because you're missing today_at on the morning in that if statement
that's why it's always best to use variables and perform an action once
another way to write it
{% set morning = states('sensor.morning') | today_at %}
{% set delta = 120 if now().isoweekday() in [6,7] else 15 %}
{% if is_state('input_boolean.wakeup', 'on') and morning %}
{{ morning + timedelta(minutes=delta) }}
{% else %}
{{ morning }}
{% endif %}
@quartz dust posted a code wall, it is moved here --> https://hastebin.com/iwajafopek
How does one format this properly? It is malformed:
service: script.tts_sonos_tts_engine
data_template:
data: |-
{%- set room = states("sensor.last_alexa")|replace('media_player.','') -%}
{%- if room == "bedroom_echo_show" -%}
speaker: media_player.family_room
volume: 0.4
message: Good night Bedroom
{%- elif room == "theater_echo_show" -%}
speaker: media_player.theater
volume: 0.4
message: Good night Theater
{%- endif -%}```
Remove volume: and message: lines from each if and it works fine so my issue is how to pass the speaker: volume: and message: variables to the script inside the template?
you can't template blocks of key-value pairs like that; you have the template the values of each key
you should also get rid of data:, and data_template: can just be data:
service: script.tts_sonos_tts_engine
data:
speaker: "media_player.{{ 'family_room' if is_state('sensor.last_alexa', 'media_player.bedroom_echo_show') else 'theater' }}"
volume: 0.4
message: "Good night {{ 'Bedroom' if is_state('sensor.last_alexa', 'media_player.bedroom_echo_show') else 'Theater' }}"
I have this error in my logs Template warning: 'float' got invalid input 'None' when rendering template '# The heating is set to {{ state_attr('climate.lounge', 'temperature')|float | round(0, default=none) }} degrees.' but no default was specified. Currently 'float' will return '0', however this template will fail to render in Home Assistant core 2022.1 I thought I had read that to resolve it I had to add (0, default=none) but apparently not, does anyone have any tips please?
| float(0)
Great thank you!
Perfect! made those changes and I'm off to the races. Thanks!
hi guys im hoping someone can help me ... i've been playing with this for some time now and i cant manage to figure it out. i have an mqtt cover which works OK. i want to extract the state (open/close) from that cover into a template binary_sensor so i could show the open/close state seperately. i've been trying different variations of the state parameter but cant seem to get it right, its only showing closed. this is my setup:
cover:
- platform: mqtt
name: "Garage 2 door"
... etc ...
template:
- binary_sensor:
- name: "Garage 2 state"
device_class: garage_door
state: "{{ states('cover.garage_2_door') }}"
- name: "Garage 2 state"
Heyho. This template https://www.toptal.com/developers/hastebin/duzavomuli.csharp is giving me this error message. https://www.toptal.com/developers/hastebin/losazifoto.sql Whats going wrong? The template is from @queen meteor and a bit changed to my needs. Trying to call the script with a test message.
ValueError: dictionary update sequence element #0 has length 1; 2 is required
covers have a state of open and closed. Do open/closed translate to on/off? No. Change your state template to reflect that.
ohh i see, thanks. works now π
Anyone?
I want to convert a float with values like 0.34999999999999 into an integer like 35, I've typed in this but it doesn't seem to work, why?
"{{ state_attr('media_player.bedroom_speaker', 'volume_level') | round(2) | int }}"
The round(2) is unnecessary if youβre just going to truncate with int
That will make it 0
but wouldn't it convert it to a very long integer if I don't round it?
i need it to be between 0 and 100
you'll still need to round to avoid an epsilon error: {{ 0.58|multiply(100)|round }}
Good evening. I was looking at the light group (https://www.home-assistant.io/integrations/light.group/) and the entities property says it takes string or list. So I was wondering if I could do this:
- platform: group
name: "All Lights"
entities: >
{% set domain = 'light' %}
{{ states[domain] | map(attribute='entity_id') | list }}
I'm fairly new to HA, and I'm trying to understand the concept here. I would be grateful for a point in the right direction
that's the right idea, but you may need this:
actually, looking at the docs, I don't think you can use a template ther
_< damn
I'm just trying to create an all-lights light group. But been struggling for quite a while now as actually want to understand what I'm doing and not just grab any script.
indeed
you can use group.set, as mentioned further down in that thread, to get a group that will allow you to turn all lights on or off
it might even let you add data: to it to set brightness, etc., as I've seen some folks do, even though I don't think that was intended to work
if you have a group of just lights, you can provide light-based attributes when turning the group on
I see, but they differ from actual light groups, right ?
in name only
some cards or service calls may restrict entities to light.* entities, which would be problematic
I ran a test a while ago making groups of only lights and mixing lights and switches and was able to have them behave just like light.groups
you'll just get an error in the log for any entity that's not a light if you specify light attributes, but it still works for the lights in there
dynamically creating a group at startup is kind of a hack, and I do wish that groups and light.groups took templates (in addition to allowing users to create both in the UI)
true
Is this the correct way to provide a default value in case the state is, say, unavailable which will break the float filter? states('sensor.bedroom_hallway_4in1_humidity') | float | default(0.0)
states('sensor.bedroom_hallway_4in1_humidity') | float(0.0)
you can test this in
-> Templates
Thanks. I appreciate it.
I'm sure I'm missing something obvious, but I can't get a value to display as an integer. I'm testing it in the templating tool and adding "int" or round(0) doesn't seem to change anything.
value_template: "{{ states('sensor.heatpump_kw') | float * 1000 | int }}"
always results in a value like 216.0
your int is only applied to the 1000
Ah, that I certainly didn't realize π
So I need to apply the int to the whole output somehow
pemdas*
Have tried to reformat this several ways with no joy to get rid of the HA warning "The entity definition format under template: differs from the platform configuration format." for this template sensor. Any advices?
sensors:
last_alexa:
value_template: >
{{ expand(states.group.echos) | selectattr('attributes.last_called','eq',True) | map(attribute='entity_id') | first }}```
Petro, I see I need to group the float * 1000 together so the int applies to it all. WHat I can't figure out is how. Surrounding it with {{ }} doesn't work in the value template.
The p in pemdas stands for parenthesis
It's math, filters apply to the item to the left of the |
the item to the int's left is 1000
so using parenthesis, how do you apply it to everything?
seems like you're declaring it more than once
use the new format or the old format, not both.
I also tried parentheses before trying the {{ }}. I tried:
value_template: "{{ states('sensor.heatpump_kw') | (float * 1000) | int}}"
and what is the | float applied to?
order of operations
| float needs to be next to states()... So where should your parenthesis go?
np
And I appreciate you walking me through it and not just giving it to me. I understand the failure in my logic
Is there a template filter that would basically work like a low-pass filter? I know I can use the filter platform to do this at the cost of creating additional sensors for that purpose. I was hoping to take care of it along with the above calculation.
hey guys, any regex gurus around here? Looking to extract the first number 15 from a sensor with this value: $OK 6 32 15 15^17
assuming there are always three values separated by spaces before the value you want, .split(' ')[3] will work:
{% set val = '$OK 6 32 15 15^17'.split(' ')[3] %}
{{ val }}
that returns the first 15
nice and and yes the value always contains the format above
cool, you should be good to go then
{% set val = sensor.gc_return.split(' ')[3] %} is correct for passing in sensor?
{% set val = states('sensor.gc_return').split(' ')[3] %}
Anyone can help me with this template?
I see this error message: Error: dictionary update sequence element #0 has length 1; 2 is required when I look at Script Debug in HomeAssistant at this Step Config: https://pastebin.com/b6e22Uht
i got an error in my automation here and iam 99% sure the error is within the templates....
can somebody take a look?
https://pastebin.com/WSW16Gsk
Youβre not outputting anything if the input boolean is off
And the error is...?
I don't see any branches there that don't have an else that would output something
@young jacinth Along with Tedioreβs comment, I am guessing this is an issue {% if set_direction == 'close' and == 'off' %}
Indeed
It looked that way but Iβm on cell
It looked like it was paired with the main if and had no else
okay, that solved the error but the output is 100 even if it should not
Invalid config for [automation]: invalid template (TemplateSyntaxError: unexpected '==') for dictionary value @ data['variables']['set_position']. Got None. (See ?, line ?).
this is what iam getting with this
do i have to use brackets in the variables definition? like:
night: "{{ is_state('binary_sensor.night','on') }}"
Which will change the rest of your template to true/false no?
Which is why you always get 100
Plug it into the template editor.
You keep changing it. And pictures of text π€’
i wanted to show the output
And it is unclear if you are getting an error or the automation isnβt performing as expected
the automation is available, gives an error, and does not work the way i expect
I am not sure about the error but it looks like it is rendering the template properly
iam going crazy
With the error?
both. the error and the automation always outputting 100
altough the template editor showing the correct results
solution
i pasted the template editor code into the variable set_position
lol
you can't output multiple values in a template
you should only be outputting the position for set_position
Also, there's no reason to do what you're doing. Just use true/false
{% set is_night = is_states('binary_sensor.night', 'on') %}
{% set is_occu = is_states('binary_sensor.eg_occu', 'on') %}
{% set door_open = is_states('binary_sensor.terassentuer', 'on') %}
{% if is_night and not door_open %}
{% if is_occu %}
50
{% else %}
0
{% else #}
100
{% endif %}
@mighty ledge Even with the input_boolean removed it doesnt work and still gives the same error at that stage. https://pastebin.com/sdzHzSYN
target needs the entity_id feild
Hi,
trying to get a name of a device by {{device_attr('1445ec2c5205bea4e33f286c7dac4bb9','name')}}
and it's resulting in an old name (I changed it already from the devices panel)
how to force HA to reload new name?
Hello guys:) I found a script to turn off all lights except some excluded. It's working fine but if they're already off it throws an error because of the empty entity_id. Does anyone know a workaround for this?
btw. it uses homeassistant.turn_off if that matters
Nevermind. Solved it by using variables and checking my condition (excluded entities list is not empty) before calling homeassistant.turn_on
Even seems cleaner^^
I want to make sure my grid consumption template sensor becomes unavailable if one of the individual sensors is unavailable: https://pastebin.com/ytFjC70N . Should I add something like this? availability_template: "{{ states('sensor.bad_taklampe_kwh') not in [ 'Unavailable', 'None', 'Unknown' ] and states('sensor.bad_termostat_gulv_kwh') not in [ 'Unavailable', 'None', 'Unknown' ] and states('sensor.entre_taklampe_kwh') not in [ 'Unavailable', 'None', 'Unknown' ] etc...... }}"
or if you actually want to do a template,
{{ expand(sensors)|selectattr('state', 'in', ['unavailable', 'unknown'])|list|length == 0 }}
or put them all in a group and you can skip the list part
Regular expression question. Trying to make caldav exclude events with a specific word. I have no clue how to use regular expression so I googled around and found this but it does not seem to do the trick ^(?!.*ignoredword).*
regex101 is a good resource for testing regex. you put the stuff want to test against in the bottom and your query in the top
it has descriptions of the things to use
Yeah that's where I'm testing right now and it seems to work there but not in caldav. Might be that caldav does not work with excludes
search: "^(?!.*ignoredword).*"
probably more of an #integrations-archived thing for that integration
my log throws this on boot but the sensor works. is there any way to re-write this to eliminate the log error?
'''
Template variable warning: No first item, sequence was empty. when rendering '{{ expand(states.group.echos) | selectattr('attributes.last_called','eq',True) | map(attribute='entity_id') | first }}'
'''
'''
template:
- sensor:
- name: last_alexa
state: "{{ expand(states.group.echos) | selectattr('attributes.last_called','eq',True) | map(attribute='entity_id') | first }}"
'''
- name: last_alexa
selectattr returned an empty set
Maybe the template sensor was loaded before the Alexa integration did the update of the entities after reboot
You can do something like this (or something smarter probably, but this should work):
{% set echo_last_called = expand(states.group.echos) | selectattr('attributes.last_called','eq',True) | map(attribute='entity_id') %}
{% if echo_last_called | lenght > 0 %}
{{ echo_last_called | first }}
{% else %}
None
{% endif %}
change your template to:
"{{ expand(states.group.echos) | selectattr('attributes.last_called','eq',True) | map(attribute='entity_id') | first | default(none) }}"
BOOM! That was it! Thanks petro for the help and making the community a great space.
Hi folks, came across a bit of a logic puzzle today, with a counter and a boolean switch. The counter moves based on user interaction via other automations. When the boolean switch turns off, Iβd like a sensor to equal the highest integer the counter has been at since the boolean was turned on. Any ideas how to grab that?
I would use a separate input_number and an automation that triggers whenever the counter changes state, and has a condition that the input_boolean is on. When it triggers, set the input_number helper to the max of the existing value and the new one. Another automation would reset the input_number when the input_boolean turns on
I think I follow, thanks!
I guess Iβd just need an automation in there to change the intermediary input number as the source one changes.
And you can do templating in conditions, right? So I can set a condition that requires my intermediary input number to be less than the source one. As the counter moves up and down, the only changes that the intermediary picks up are the peaks. And then when boolean goes off, move that intermediary to another input number which only records those per-session maximums.
I added an entity tracking the energy cost from my energy company. in the unit_of_measurement field, should I put the value as {currency}/kWh' or just $/kWh?
Thanks, ya, definitely trying not to overcomplicate with this project, or at least planning to circle back all the time and trim fat
Ooh this is great, I didn't realize you could use max like that
it occurs to me that the first one really should be this:
- alias: initialize
trigger:
platform: state
entity_id: input_boolean.blah
to: 'on'
action:
- service: input_number.set_value
data:
entity_id: input_number.max
value: "{{ states('counter.xxx')|float }}"
Thanks @mighty ledge! I did not see this until now. I will try your code. Error you mention may very well explain the issues I have = exactly what you said... π
USD/kWh
Still learning syntax π Why does peck evaluate properly to the integer 4 and peckc evaluates to 'unknown'?
{{ peck }}
{% set pecka = 'theater_symfonisk' %}
{{ pecka }}
{% set peckb = 'media_player.' + pecka + '.attributes.media_duration' %}
{{ peckb }}
{% set peckc = states('peckb') %}
{{ peckc }}```
Because you are doing states('media_player.theater_symfonisk.attributes.media_duration') Which is just not right. You can do states.media_player.theater_symfonisk.attributes.media_duration or better yet use state_attr('<entity_id>', '<attribute>')
Thank you, Tom - I will go study state_attr('<entity_id>', '<attribute>')
Still not getting it. peck evaluates properly to 4 and peckc evaluates to 'none' now using state_attr...
{{ peck }}
{% set pecka = 'theater_symfonisk' %}
{{ pecka }}
{% set peckb = 'media_player.' + pecka %}
{{ peckb }}
{% set peckc = state_attr('peckb', 'media_duration') %}
{{ peckc }}```
Don't quote your variable {% set peckc = state_attr(peckb, 'media_duration') %}
Otherwise state_att() will use the literal string 'peckb' as the entity_id instead of it's contents.
That worked of course. Thanks again, Tom.
I found the following warning in my HA log file and wonder how to solve the problem. I am pretty sure that I saw a suggestion while doing some RTFM quite a while ago, but I cannot find it anymore. Nice that HA lets one know when the template is going to fail, but I would have appreciated a hint towards solving the problem rather.
Here is the warning from the log file:
Template warning: 'int' got invalid input 'unavailable' when rendering template '{{ states('sensor.xiaomi_l2_bathroom_battery') | int < 20 }}' but no default was specified. Currently 'int' will return '0', however this template will fail to render in Home Assistant core 2022.1
I created a few binary sensors using the template this way:
- binary_sensor:
- platform: template
sensors:
xiaomi_low_battery_l2_bathroom:
friendly_name: Xiaomi low battery L2 bathroom
value_template: >-
{{ states('sensor.xiaomi_l2_bathroom_battery') | int < 20 }}
change it to | int(0)
I am attempting my first regex (template calculation) to calculate my current stock totals($). I am playing in regex101 and I think I am getting worse not better. haha Any tips on best places to read up and learn more would be appreciated.
- name: 'PTN Stock Total'
unit_of_measurement: "$"
state: >
{% if is_number(states('sensor.yahoofinance_ptn')) and is_number(states('input_text.ptn_shares')) %}
{{ (states('sensor.yahoofinance_ptn') * states('input_text.ptn_shares')) }}
{% else %}
None
{% endif %}```
I donβt see any regex there
In any case, you need to convert the states to numbers before doing math. Add |float to each states() call that needs a number
I have this template: https://paste.debian.net/1218990/
It takes three attributes of a single sensor, determines the one occurring next and sets a state and attribute with the numbers of days (state) and due date (attribute). You will see in the template that each attribute in the original sensor is defined as chore[#].attribute. Each chore has an id: attribute as well. Is there a way to set as an attribute in the new sensor, the id: of the chore that is occurring next? I hope that makes sense
Adding floats returns an unavailable sensor.
- name: PTN Stock Total
unit_of_measurement: "$"
state: >
{% if is_number(states('sensor.yahoofinance_ptn' | float)) and is_number(states('input_text.ptn_shares'| float)) %}
{{ (states('sensor.yahoofinance_ptn') * states('input_text.ptn_shares')) }}
{% else %}
None
{% endif %}```
Does the is_number even matter in this ?
you didn't add them in the right place
{{ (states('sensor.yahoofinance_ptn') * states('input_text.ptn_shares')) }}
that's multiplying two strings together
and you don't put filters inside the function call
{{ states('sensor.yahoofinance_ptn')|float(0.0) * states('input_text.ptn_shares')|float(0.0) }}
I added defaults to handle the case where the states aren't numeric values, which is one way to accommodate that case
ok ok I copy. I am going to go back to the drawing board and do a little more self educating before i continue to get ahead of myself. I very much appreciate you taking the time to point me in the right direction.
I messed with this far longer than I am willing to admin this AM. But that worked like a charm. Thank you thank you thank you
From my earlier specific example, what I need to do is compare a time sub-attribute from three different attributes (same sensor) and return a different sub-attribute for the earliest of the three time sub-attributes
So I have been searching all day trying to find a way to get the modulus of two helpers. One(numerator) Is a counter for the number of minutes a workout is going and the other(denominator) is a specified number for modulus. I am using this to control how often Alexa Media will announce the time. Currently I use two scripts (one calls the other until the workout helper button is turned off and each count a minute and do updates to the counter...alexa...etc. I have tried several ways of templates which seem to change based on each page for format and none work. Several (even though both of these helpers are never 0 have cause Division by Zero errors). They never call alexa though. This is my most recent...I removed "states(" from it before this. This is driving me nuts. I even tried to avoid templates which I am not liking since as stated their formatting seems flexible enough to cause variable examples) using variables in my script but they did me no good either...plus..they were of course templates as well.
"{{ (('counter.workoutcount') | int) % (('input_number.workouttimettsmins') | int)==0 }}"
I do realize I may be doing this all wrong but if there is a comprehensive documentation for templates (not a 2 page with few examples) that can explain all of the varying types of them...please point me to it
this wasn't corrrect:
This is my most recent...I removed "states(" from it before this.
π Only did it cause states wasnt working either. I had states over each () as well as another with one states( over the whole list. I have been programming for over 20 years....I dont give up to much....but I just aint getting it
worst part too is I love the debugger but I couldnt find any way to get it to tell me the states of the template variables...so I am working in the dark
Here are the three different ways I templated in Developers Console and none of them work in the script:
{{ (states('counter.workoutcount') | int) % (states('input_number.workouttimeannouncemins') | int) }}
{{ workoutTime%workouttimeannouncemins }}
{% if (states('counter.workoutcount') | int) % (states('input_number.workouttimeannouncemins') | int)==0 -%}
Its Zero!!
{%- endif %}
I also used another example that just didnt seem right to me but it worked in the developers console too...something like {{ "1" if (states('counter.workoutcount') | int) % (states('input_number.workouttimeannouncemins') | int)!==0 else (states('counter.workoutcount') | int) % (states('input_number.workouttimeannouncemins') | int)}}
thats from memory but I did copy off of several pages...it seems quite useful but the syntax seems backwards to me π
Hey guys, quick question regarding triggers. Is there a speed difference between using an event (template ;p) trigger compared to a state trigger ? Im guessing the event happens then the state is changed but are we talking noticeable difference?
prob best to ask this in automation's ehehe
I have this script using a template:
execute_chore:
sequence:
service: grocy.execute_chore
data_template:
chore_id: >
{{ state_attr('sensor.spa_water', 'next_id') }}
But I am getting this error (missed comma between flow collection entries at line 743, column 51:
... tr('sensor.spa_water', 'next_id') }}
The carrot is pointing between the t & e in water. Not sure what I am missing here
post the full error, not abbreviated VMCosco error
The...what?
event triggers are not template triggers, so which are you referring to?
The "I'm going to only post the information that I think is relevant but I didn't so the helpers are left guessing" error
Oh lol
i'm stealing that line
that was all that the pop up in file editor showed
post the error from the log
I changed from data_template to service_template and am no longer getting the error in file editor
there was no error in the log, I got the error as I was typing out the code in file editor
it is just enabled in configuration.yaml..i thought
I'm trying to find out where this error is coming from
what utility are you using to edit configuration.yaml
File Editor. it is in my side bar
Yes, is that an addon?
Only you have the answer to this, that's not a standard item.
and it's not an integration.
I guess we have to assume its the file editor addon
yes, official add on. Sorry
Ok, sorry don't have experience with Ace Editor's yaml linting.
Hi, Unable to parse output as JSON: Invalid macro definition. Does anyone know what macro definition this is referring to? It is (and has been for a long time) a valid JSON output it is complaining about: {"cpu_percent": "63", "hdd_percent": "17.1", "ram_percent": "40.8", "cpu_temp": "65.75", "uptime": "14:43:10"}
no problem, I am not getting the error now. For that script, would I needto use data_template or service_template? I do not understand the difference
both data_template and service_template are deprecated
you should be using service or data
do you understand the difference between service and data?
yes, can i use a template in data
you can use a template in both
the difference is: Service is the service you are using, data is the data that goes along with the service
i understand that so my script should just be:
execute_chore:
sequence:
service: grocy.execute_chore
data:
chore_id: >-
{{ state_attr('sensor.spa_water', 'next_id') }}
yep
That looks like valid json
macro definitions start with {% macro
I have used variables in scripts before. I have multiple sensors that could use this script. Can I put a variable in place of "spa_water" so that I don't need to have multiple scripts?
yep, it would probably be easier to just replace the entire entity_id
unless they are all going to be sensors
they are all sensors: sensor.spa_water, sensor.spa_filer, sensor.lawn_fertilizer, etc
the weird thing is, I never changed that ancient script since forever and suddenly it complains about a macro. The json comes from a command line sensor that connects via ssh to a remote machine. Now even running that command line in the hass terminal complains about "Invalid macro definition". 
I'm not sure what "macro" is meant here
hmm, no clue then.
then you can concatenate 'sensor.' ~ my_variable_name with a variable name and pass in the second part of your entity_id as my_variable_name: xyz
I am not familiar with that syntax
well it's a good thing I gave it to you then
so like this:
execute_chore:
sequence:
service: grocy.execute_chore
service_data:
chore_id: >-
{{ state_attr('sensor.'~ chore, 'next_id') }}
yep
and a tap_action would look like:
tap_action:
action: call-service
service: grocy.execute_chore
data:
chore: spa_water
nope
oops sorry
check the tap action docs
pasted too fast
tap_action:
action: call-service
service: script.execute_chore
data:
chore: spa_water
action can be removed now right?
nope
it's a field name
one of them is wrong, and it's covered in the tap action documentation
.tap_action
bah, @arctic sorrel fix bot
I donβt think thatβs ever been a thing
probably not, but it should be
no u, i just wanted to ping you
oh, here i have to use service_data?
yes
got it, thanks
Does anyone know how to do a comparison between dates in a template sensor? The API returns a date in a string format such as 22/11/2021 but I then need to calculate the days between todays date and that date, and then return Today, Tomorrow, X days time
That's easier said than done. You have to use strptime because you don't have a normal date format.
I can probably get the date format by passing it through a JS function and parse it with dayjs if it helps?
date: 2021-11-22T00:00:00.000Z like that
{% set time1 = strptime(whereveryougotyourdate, '%d/%m/%Y', none) %}
{% set time2 = strptime(whereveryougotyourdate, '%d/%m/%Y', none) %}
{% if time1 and time2 %}
{% set delta = time2 - time1 %}
{% if delta.days = 1 %}
Tomorrow
{% elif delta.days = 0 %}
Today
{% else %}
{{ delta.days }} days time
{% endif %}
{% endif %}
if you use isoformat, it would simply be:
{% set time1 = whereveryougotyourdate | as_datetime | as_local %}
{% set time2 = whereveryougotyourdate | as_datetime | as_local %}
{% if time1 and time2 %}
{% set delta = time2 - time1 %}
{% if delta.days = 1 %}
Tomorrow
{% elif delta.days = 0 %}
Today
{% else %}
{{ delta.days }} days time
{% endif %}
{% endif %}
if you rtimezone is utc you can drop the as_local
is there no way to get current date/time within jinja?
there is
now()
but you said you're getting it from an api
if you want to compare it to now, then replace time1 with now
{% set t = whereveryougotyourdate | as_datetime | as_local %}
{% if t %}
{% set delta = t - now() %}
{% if delta.days == 1 %}
Tomorrow
{% elif delta.days == 0 %}
Today
{% else %}
{{ delta.days }} days time
{% endif %}
{% endif %}
Yeah sorry, 1 time comes from API, and to compare it against now
MMmm TemplateSyntaxError: expected token 'end of statement block', got '='
i'm guessing you didn't use the multiline indicator for the yaml
also, i left out ==
Hm, i think my error message is from ssh. Even just ssh user@host python -V asks for the pw and then before printing the python version "Invalid macro definition"
Is there a way to prune that message before setting the value here? value_template: "{{ value_json.pc_data }}"
something like {% set value_json = "my perfectly nice json just without that weird line" %} ? π
I'm really puzzled with this bit of code - can anyone help?
{{ ((('574115881' | float) /100000000) | round(2) ) + 17 }} In dev tools templating, this doesn't seem to round properly
but if I remove the + 17 or change the round(2) to 1 or 3 it does work as you'd expect. But why doesn't 2 work? It had been working for the last 2 weeks and now today it's not rounding properly
I enquired about something similar here a week or two ago and discovered I hadn't bracketted properly which I fixed and you can see above everything should be fully bracketted
Youβre only rounding the 100000000 not the whole division. Take a trip back to pedmas and use parentheses properly
Aka order of operations with math equations
If you donβt know what pedmas is, Google it
are you sure?
I thought I had parentheses around the whole conversion to float and division
then piped the result of that section to the round function
I also thought that for a moment, but you are not.
But you have some unneeded parantheses.
{{ ('574115881' | float /100000000) | round(2) + 17 }} will do the same
then the end result of that I add 17 to by bracketing the end result
When I asked the other week here I was told that you need strict parenthesis so I just made sure everything was done to ensure the groupings were explicit
Also, my rest sensor template the above is taken from to test with is working again to 2 decimal places. The only thing that has changed is the first number in single quotes
There is indeed something strange here, I checked in developer tools, and it works with round(1) and round(3) and without the +17 (like you already said). But not with round(2)
This does work though {{ (('574115881' | float /100000000) +17) | round(2) }}
and why would changing round(2) to round(1) and round(3) in the above example work correctly - but not round(2)
yes
it's very weird
Your working suggestion looks more readable and tidier so I can use that. But I'm still trying to get my head around why it behaved like this in the first place
it seems that the behaviour changed based on that first number as it changed. So perhaps some very specific values are doing something odd
You can remove some parantheses there as well: {{ ('574115881' | float / 100000000 +17) | round(2) }} (because of pedmas)
I tend to prefer explicit parentheses because it's easier at a glance to see what the order of execution is without having to remember which operators take precedence over others
do exactly the same thing with the number 587361197 and it works fine - to 2 decimal places
multiple parenthesis usually takes longer to read, especially if you don't have a linter
I assume that instead of '574115881' you will use a entity state? You might want to add a default for the float then to avoid template warnings (and errors after 2022.1 or something)
yes - it's from a rest api - I presume it therefore comes back as a string
so for testing purposes (and you can't integrate a rest call into the template dev tool that I know about) I just hard coded the json value applicable
rest has the ability to return json, so it could be a number, but it depends on the output of the rest endpoint
value is always a string, but value_json will be json
the rest api would return this (when the url called from a browser): {"data":{"balance":587361197}}
Is what I have in the code value_json.data.balance
ah ok
probably because I cut and copied from another bit of code I had somewhere else
{{ (value_json.data.balance / 100000000 + 17) | round(2) }}
I am trying to write to a file with a shell command using an input_number. Writing to the file is not a problem, like this:
shell_command:
set_brightness: βecho 80 > /config/screen_settings/brightnessβ
But it fails if I try to use an input_number value:
shell_command:
set_brightness: βecho {{ states(βinput_number.brightnessβ) }} > /config/screen_settings/brightnessβ
Anyone knows what I am doing wrong??? Help is very much appreciated!
so these two examples: one returns 2 dp, th other lots:
{{ (((574115881) /100000000) | round(2) ) + 17 }}
{{ (((587361197) /100000000) | round(2) ) + 17 }}
because you aren't rounding the entire equation...
I only need to round the big number/1000000000 don't I, not the +17
you need to round it all
if you add an integer to a float, you can end up with epsilon error
which is what you're seeing
if I get 5.65 out which I imagine is a float, then add +17 I should get 22.65
epsilon error is error induced by computers when performing math
ahhh that makes some sense
if I did +17.0 then it would be ok? (in theory) π
got it
Think I put the +17 there to try and simplify the problem previously when I had precedence issues due to a lack of bracketing
you copied and pasted that code from an unformatted source which resulted in incorrect quoting characters. Don't copy and paste unformated code
so was I hitting that episilon error with a certain number then?
Learning stuff everyday! Now I understand why Excel sometimes gives these strange results when adding cells, it's an epsilon error π
you're hitting epsilon error in general
With the following it gives 2dp with both the test numbers correctly:
{{ ((((574115881) /100000000) +17) | round(2) ) }}
{{ ((((587361197) /100000000) +17) | round(2) ) }}
but with that +17 the other side of the round(2) one is rounded the other is not
why do you have a parenthesis around the first number
it's just what computers do
if you don't want to learn about bytes and how numbers are represented in memory, then there's no point in learning about epsilon error. All you need to remember is to round the entire equation
Thanks. Memo to self - make sure you do your rounding on the final result
So sorry I messed that up.. I tried to put the enclose the code in triple backticks... π©
where did you copy it from?
I read something similar on the integrations page for shell_command
set_ac_to_slider: 'irsend SEND_ONCE DELONGHI AC_{{ states("input_number.ac_temperature") }}_AUTO'
no fancy quotes there π
Yes but it's impossible for it to be incorrectly formatted unless it was pasted into an engine that auto formats text, then copied again
I haven't learnt about defaults. However I have encountered problems where an api fails (or works but gives an error result) and then the templating still tries to calculate into a sensor value. Which ends up giving me 0 values and graphs with spikes in them. I'd tried fixing that by putting an {{ if }} section around it to check it the return code before doing some manipulation on it
I'm still pretty new to templating
you need an availability template on your sensor
well, its not available on rest sensors, however you can return none and it will be unavailable
Would this result in proper formatted code? {{ just anexample }}
No you still aren't understanding
quotes like this β are invalid in yaml
they ONLY come from microsoft word when using quotes or a forum post with unformatted code
' correct quote type
notice the difference
so your original code that you posted above will not work with those bad quotes and they appear after you used backtics
which means you copied it from an unformatted code source like the forums or microsoft word
or an email
or anything that formats text as you type
My god, I didn't know they were different, I could not tell the difference... So if I replace these quote characters the shell command should work?
yes
and never copy unformatted code again
this is why everyone gets bent out of shape when new people don't take the time to format the code with backticks
because it just leads to more questions and screwups
Does this still contain the wrong quote characters? 'echo {{ states("input_number.screen_brightness") }} > /config/rpi_brightness/bright' Please forgive me my ignorance...
