#templates-archived
1 messages Β· Page 95 of 1
that might be okay, as long as it's using 2-space tabs. VSCode is nice in that it shows you indentation levels by color and you can tab and shift-tab to adjust
I'll have to look into that
anyway, you're good to go?
I'll try it in the morning, the config check checks out
If this works, I def owe you a beer
Ive been scratching my head for the past 3 days with this shit
if you're going bed, I'm going to assume that we're geographically separated
Sweden
yeah, San Diego
ah
ok, hopefully it works. once you have some good working examples, the rest become easier
Well..I'll PM in the morning. I ain't forgetting that beer π
and be wary of copying somebody else's stuff, especially when it seems like they don't know what they're doing
a little from column a, a little from column b
yeah..
welp..tried it..no bueno
current temp is 22.5
it sets the fan at 3
but it should be at 2
you can debug the template in
->Template
it's probably still rounding
if I use this
- data_template:
entity_id: climate.huvudvaningen
fan_mode: >-
{% set temp1 = states('sensor.temperature_5')|float %}
{% if temp1 > 22 %} 2
{% elif temp1 > 23 %} 3
{% elif temp1 > 24 %} 4
{% else %} 4
{% endif %}
service: climate.set_fan_mode
It sets it correctly
that's not a useful template, though
not at all
Argh..I'll go at it tomorrow again
might pm
sigh
hmm..
changed the values around from rising to falling
works as well
oh, nevermind
I think you just need to set the precision via round(), or via format(). there are some good references on the web
too late..can't think.. I'll look into it tomorrow
this one, for example:
{{ "$%.2f"|format(value|float) }}
where value is replaced with states('sensor.temperature_5')
if that doesn't help, I recommend more Googling
{% set temp1 = "%.2c"|format(states('sensor.temperature_5')|float %}?
you're missing a paren
after float
I've never used that construct before, but it's typical in a Google search
yeah, I'll check tomorrow. Thank for all your help so far bro
or this:
{{ "${:.2f}".format(value|float) }}
sure, no problem
also, you put %.2c instead of %.2f
"f" is for "float"
not Fahrenheit, if that what you were going for
Mernin'
So, I did a test..
Just to see if it's actually the float value that messes things up and it seems to be the case
Works fine for me
which does? mine or floats?
The original of yours
do your temp sensors report with or without decimals?
With, but that doesn't matter here
{% set temp1 = 23.4|float %}
{% if temp1 < 22.0 %} 2
{% elif temp1 < 23.0 %} 3
{% elif temp1 < 24.0 %} 4
{% else %} 2
{% endif %}
``` returns 4
Change 23.4 to another value and it updates accordingly
hmm...
What would a value template look like in order to extract bytes from a command line sensor that provides the following data:
{"count":39,"bytes":166760163267}
and if I do this
{% set temp1 = 22.2|float %}
{% if temp1 < 22 %} 2
{% elif temp1 < 23 %} 3
{% elif temp1 < 24 %} 4
{% else %} 2
{% endif %}
it returns 3
@little gale {{ value_json.bytes }} should be enough
heck, if I put 23, it returns 4..
thanks
do I need to create a template sensor if I wish to convert the value of bytes to GB?
Yes
uh.." {% set temp1 = 22|float %}
{% if temp1 < 21 %} 2
{% elif temp1 < 22 %} 3
{% elif temp1 < 23 %} 4
{% else %} 2
{% endif %}"
returns 4

Yes, yes you are
have you ignored a few grades in math?
maybe you're looking for the following construct temp1 <=22
if something is < it means less than, so it can't be equal at the same time as being less than
between it is
Then <= for less than or equal to
between means not including 23 and 24
Also, the logic of what you said doesn't cater for is 24
{% if temp1 <= 23.0 %} 2
{% elif temp1 <= 24.0 %} 3
{% else %} 4
{% endif %}
```That matches what you've been saying better than what you're using just now,
Can values be defined in the template editor?
then basically this should work as I want it to
{% set temp1 = 22|float %}
{% if temp1 < 23 %} 2
{% elif temp1 < 24 %} 3
{% else %} 4
{% endif %}
anything below 23 = 2
anything below 24 = 3
and anything else 4
oh, didn't read, sorry
Depends on whether you want 23 and below, or below 23
You've been saying one thing, and doing the other
no, below 23, so once I hit 23, it should switch to a higher fan speed
so <
and not <=
Yes, but that's what you've had and been confused about
To say the least.. I wasn't actually understanding what < was doing
amongst other things....so I've learned a lot from this
This, I'm afraid, is basic maths - if you're going to be playing with more templates it might not hurt to refresh yourself on that
And I hate math...also sucked at it (as can be seen)
Hi together
I've just a short question. I know .. I can solve this with a template sensor as well but may there is an easier way to do that.
I have this line at the moment:
{% set h, t = states('sensor.shelly_shht_1_123456_humidity') | float, states('sensor.shelly_shht_1_123456_temperature') %}
Now I've a new entity which delivers humidity and temperature as attribute (not state).
How can I rewrite this to directly use the attributes of the new entity weather.location?
If I understand it right, it should be something like this
{% set h, t = state_attr('weather.location', 'humidity') | float, state_attr('weather.location', 'temperature') %}
is there a way to skip updating/refreshing a binary sensor if a condition isn't met? or is it always either true / false?
i have data coming from a serial port which looks like this: https://paste.ubuntu.com/p/9DqfzvWQ32/
and my binary_sensor templates are set up like shown in the above paste.
basically, if i have an active alarm (let's say smoke, for this example), and another alarm (battery) comes in, the smoke sensor will evaluate as false even though it could still be active because state_attr('sensor.kidde_serial', 'command') != "smoke")
maybe some kind of 'if' which returns old_state if command != smoke?
got it actually i think:
kidde_battery:
friendly_name: kidde battery
value_template: >-
{% if state_attr('sensor.kidde_serial', 'command') == "battery" %}
{{ state_attr('sensor.kidde_serial', 'active') }}
{% else %}
{{ state('binary_sensor.kidde_battery') }}
{% endif %}
hey folks, strptime stopped working for me....it outcomes with a string, not with a time value, as I can't do anything else with it, anyone else got some problems?
{{ as_timestamp(now()) }} works
{{ as_timestam(strptime("17-03-1993","$d-$m-$Y")) }} results None
damn change $ and %...will try now
there I go....and now I know why it stopped working...made not enought backup from my templateeditor and lost everything before using this formation and did a reconstruct from brain...
wastet 2h with this π¦
thank you very much....once again
action:
- service: cover.set_cover_position
data_template:
entity_id: cover.potager_electrovanne
position: "{{ states('input_number.valve_1_duration') }}"```
thanks :
Yes it's logical
thanks π
not working π¦
The value is well templated
but.... not taken into account π¦
seems is not possible to template with position
What's the error in the log?
noting
I found something in communauty
β{{ states.input_slider.cover_position.state | int }}β
Yeah, don't use the states...state format
β{{ states('input_slider.cover_position') | int }}β
ok
still not working π¦
in direct it's working
position: 50 for example
the templating gives me 50 too
If you're having problems with your updates to your configuration:
- Check the troubleshooting steps
- Check your log file - remembering you may need to set logger to
infoordebug - Explain what the problem you're having is - sharing configuration, errors, and logs
It's my fault π
I forgot "data_template:"
π
Works like a charm π thanks
Howdy! I want to be able to detect guests via their presence on my wifi. I have a Unifi gateway, so I can see via the attributes what network a device is connected to. The question: is it possible to make a template for a binary sensor which will return true if ANY device_tracker has an essid of Guest and false if none do?
Hey guys ... how can I retrieve only the first 5 characters of an input_select?
"{{ states('input_select.dvdo_switch')[0:5] }}"
@hollow bramble thank you π
damn you guys are good!! lol
You were asking the right person and your question was clear. It was just in the wrong place π Better to keep it here so other people can search for answers in the future.
yeah I understand ... thanks very much for the help!
the fact that you already had the template setup made it pretty trivial
I think just [:5] would also work
I'm very new to Home Assistant ... I'm still copying/pasting from the forum, etc. I wasn't even sure that was called a template
remember to always test templates in the templates dev tool
Also good to know, thanks! I have lots of learning to do....
Trying to learn MQTT, Node-RED, and Home Assistant at the same time π
Template works... thanks again guys!
Come to #node-red-archived if you get stuck on something. That's also one of my areas of semi-expertise
Awesome ... I found a bug in the node-red-node-serialport but dceejay fixed it right away. Seems like an awesome group of people like you guys π
There's generally not much gatekeeping in home automation. We're all just trying to make things work
Unless you mention the system on which you are running your home automation services. Then you're likely to get a π€’ from @wise arrow
Only if it's not HP π
SuperMicro motherboard with dual Intel Xeon E5-2643 v2
Nah. We've got people running this on everything from a Pi to an entire server farm. It's all good.
lol
Hey Mates, i have 4 arrays I set in a sensortemplate. Is there a way to set them globaly as I need them in a few templates. To be clear its a translationarray for days and months names.
Store them in an input_text?
The input_x helpers are awesome. Learn them all.
Doing my very best. Checked out how to split my config right now....will do so now and then i hope that the magic begins 
Thanks for your help you both
@hollow bramble @ivory delta the template you helped me create is working great, but the opposite direction isn't working
my input_select has options such as "HDMI1 (MiSTer)" and "HDMI2 (OSSC)"
you helped me create the template to only send [0:5] to MQTT so it only sends "HDMI1" or "HDMI2", etc.
However, how can I read the value from MQTT and select the correct option? a different system changes input and publishes "HDMI1" but I need my input select to select "HDMI1 (MiSTer)"
For that, you'll need a different template π That one's going to be messy.
Yeah, I thought so ... a bunch of if statements?
Yup
ok, thanks a bunch
Ok really basic question about templating. I'm working on an animation and I figure I'd have a much easier time if I understood templates a little better. I'm working with Input Numbers so I'm reading the docs but how do I put the info under SERVICES into a template to test it?
https://www.home-assistant.io/integrations/input_number/
oop, nevermind I just found the services tab
Note that the services tab doesn't support templates
Hi Guys, is there a way i can show the total power usage of the 24h from yesterday? I do have the current usage but would like to keep an eye on daily usage too
Sounds like maybe the history_stats or utility_meter #integrations-archived
Hello
is it possible to display a state-label with a text that is made with a template?
Not with any stock card. Some custom cards may be able to
Thankyou, i will take a look at utility_meter!
Once again I#m not sure if I'm doing the "right" thing. I have a entity from an custom component (ICS, reading a calendar showing my waste plan) which is configured via integrations (not config.yaml). I have a template reading the next occurence of the event and converting the date in a german readable date. This results in another entity. Can I "extend" the given entity with templates?
Extend, no
check....then I have to stick at 2 Sensors π Thanks once again saving me hours in search and try and fail π
Am I right that my "new" Entity replaces the other one? I used a glance card and I can't chose different sensors for one Icon...phaaa...I dunno how to explan it better, sorry
No, you can't "replace" entities
Sorry...I meant that I have 2 entities and need too use one of them.
My brain is a lil stuck right now... sorry
Is it possible for a rest sensor to attach the complete response as sensor attributes?
I use a value_template to extract the expected value for the sensor.
But I need also the complete response to be able to use it with further templates
hi all, I have a script which calls some services, each one using 'data_template'. is it possible to use a variable, but assign it a default value at the top of the script?
i mean, use the variable in each 'data_template', using the single variable declaration/assignment
Not really. But I've seen workarounds where you store the variable as an attribute to an entity using customize and use state_attr to recall it in templates...
oh, thanks @charred dagger - do you have any links/examples you could share please?
for clarity - my use case is increasing the brightness of a bunch of lights, using some 'step' value
You could use an input_number for that
I actually found an old overly complicated package I made which uses this
Here the value of cfe_switch, which is defined in yaml on line 4 is stored as an attribute to an entity https://gist.github.com/thomasloven/654ae5a4d16a75e3b0ad2d7aa8082243#file-coffeemaker-yaml-L44-L46
And it is loaded into a jinja2 variable here https://gist.github.com/thomasloven/654ae5a4d16a75e3b0ad2d7aa8082243#file-coffeemaker-yaml-L72
@buoyant pine @charred dagger using an input_number is exactly what I was just trying π
it works well; I wasn't familiar with the syntax but a bit of messing around and conversion to int and all good
one example :
- service: light.turn_on
entity_id: light.floor_light
data_template:
brightness: >
{% if is_state('light.floor_light', 'on') %}
{{states.light.floor_light.attributes.brightness + 10}}
{% else %}
{{ states.input_number.brightness_step.state | int }}
{% endif %}
bonus in that I can modify the step value via the ui
Oh, there's a brightness_step and brightness_step_pct service data option for light.turn_on
Oh nvm I see what you're doing here, that wouldn't apply
thanks @arctic sorrel
hi all. I'd like to have a script that will cycle through some states each time it is called. is this do-able?
I'm thinking the last value could be stored in a helper. But to do the cycling I'd possibly need an array-like variable (or a long if/elseif/else statement π )
You could use one of those, for instance
Oh, nice! Thanks @arctic sorrel - let me have a read through that
worked a charm, thanks @arctic sorrel !
I haven't done this for far too long... where am I going wrong with this?
{% macro humidex(T, H) %}
{% set t = 7.5*T/(237.7+T) %}
{% set et = 10**t %}
{% set e= 6.112 * et * (H/100) %}
{% set humidex = T+(5/9)*(e-10) %}
{% if humidex < T %}
{% set humidex = T %}
{% endif %}
{{humidex}}
{% endmacro %}
{{ humidex(states('sensor.family_room_temperature'),states('sensor.family_room_humidity')) }}
I'd say you're forgetting that states and attributes are strings
oh.. yes I am
{{ (states('sensor.family_room_temperature'),states('sensor.family_room_humidity')) }}
``` should make that pretty clear
{% macro humidex(T, H) %}
{% set t = 7.5*T/(237.7+T) %}
{% set et = 10**t %}
{% set e= 6.112 * et * (H/100) %}
{% set humidex = T+(5/9)*(e-10) %}
{% if humidex < T %}
{% set humidex = T %}
{% endif %}
{{ '%0.1f' % humidex }}
{% endmacro %}
{{ humidex(states('sensor.family_room_temperature')|float, states('sensor.family_room_humidity')|float) }}
there we go.. much better
hmm.. it would be nice if you could jump to customize from the settings on an entity.. I find myself wanting to do that pretty often
New Tab is a feature in most browsers
it won't jump there.. you still have to navigate through multiple menus
it's not possible to customise a template sensor? I can't find it in the list
it's probably just the integration...
How would I change the below to show the friendly state?
data:
message: '{{ states(''alarm_control_panel.area_1'')|title }}'
title: House Alarm
service: notify.all_devices
First of all, format your posts
To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks. Here's an example:
```
code here
```
Watch the animated gif here: https://bit.ly/2GbfRJE
DO NOT repeat posts. Please edit previously posted message, here is how -> https://bit.ly/2qOOf1G
Make sure to include the proper indentation. What you've posted won't work, for several reasons.
Make sure to include the proper indentation. What you've posted won't work, for several reasons.
@ivory delta I have edited my post, it does work but and shows the state, id just like it to show the friendly state instead
@worn nova what exactly do you mean by "friendly state"? Do you mean what's shown in the frontend? If so, I don't think that information is available there, since that's a, well, frontend thing.
i have a power meter which sums up consumptions from different devices in a template.
the resulting value fluctuates a lot, how can I make an average out of that for the past x minutes?
@coarse tiger use the statistics sensor
@chrome temple yes, I want the notification to show "Armed" or "Armed Away" currently it shows "Armed_away" or is that not possible?
Depends on whatβs displaying it. Any custom card that supports templating can do that. Or you could create a template sensor
The latter is the traditional way to report a different state name
@worn nova how about message: "{{ states('alarm_control_panel.area_1')|replace('_', ' ')|title }}"
why is my 'stromverbrauch_median' sometimes unknown ?
https://paste.ubuntu.com/p/8zVWk9f5c5/
Probably because there's been no stats in the last two minutes. You have max_age set to 2 minutes.
oh, i mixed the meaning of max_age and sampling_size up, thx
I've created a switch template for the unifi add-on controller. Aiming to expose this to HomeKit so i can ask Siri (via homepod) to turn it on / off when necessary. It works turning it on but anyone know what i do for the value_template so it can report its state correctly?
hi. have a problem with a binarysensor template who never change states...
- platform: template
sensors:
coffeemaschine_usage:
value_template: "{{ states('sensor.coffeplug_power') | float > 200 }}"
delay_on: '00:00:30'
plan is: if sensor.coffeeplug_power is higher as 200Watt for more than 30Sec turn coffeemaschine_usage to on. but never happens... whats wrong?
you cannot use a template for that, you need a automation with that value_template @thorny snow
i use similar with 2 phonechargerplugs - works perfect. what i really wanna do is to prevent my coffeemaschine for beeing turned of (by automation) while its pooring coffee. if its pooring it needs more than 200W and longer than 30secs. i solved it by this template + an automation. is there a better way to solf this problem?
if its not pooring it may happen that it reheat - so more than 200W but most of the time not longer as 10secs.
therefor my thinking: if > 200W > 30sec =pooring - dont turn of
Did this channel just got removed? For some reason when I'm in it it shows up under "Support" but as soon I'm clicking out out of it it get's removed from the list 
No
You've found a not-very-hidden feature of Discord
v SUPPORT is the Support section being "open"
> SUPPORT is it collapsed - so that channels without unread messages don't show
Also, if it was removed... how would you be able to post here π€
TIL! Never noticed that before
Nobody does, until they find channels missing and panic... π€£
Itβs a great feature
It is, if you know about it hehe
Even better... you can mute channels too π
But then you have to actually hide them. Itβs two steps for something that should be one
Okay, with that sorted I'm struggling with figuring out how to use nested attributes in a template. So I got this https://hastebin.com/qeqaluyiho.coffeescript and want to be able to pick from the last_checkpoint "layer". I've managed to get the first layer with the likes of {{ state_attr('sensor.aftership', 'trackings',)[1].name }} but the that second layer?
{{ state_attr('sensor.aftership', 'trackings')[1].last_checkpoint.location }}
Thanks a bunch!
Now I see what I did wrong... was trying to do this {{ state_attr('sensor.aftership', 'trackings')[1].last_checkpoint.[1].location }} π€¦ββοΈ
@ivory delta even even better, you can hide muted channels
What would a value template look like if I wanted to have a value displayed in minutes if it is under one hour, and if it is over one hour, have it be displayed as something like 1 hour, 12 min? I don't think relative_time will work; the HA docs say that will only return the largest unit. TIA, pls @ me
Does anyone know what the attribute would be for a template sensor showing what the current weather is? I.e sunny, cloudy etc so that I can use in a template sensor? This is using the Met.no weather integration
it's the state for my weather.home entity
currently 'partlycloudy'
can confirm
Just look at
->States
Thanks!
hello, surely obvious but i couldn't find answer, how could i set horizontal-stack to take the entire screen ? within lovelace-ui (dynamique mode) i tried to add sytle : width: 100% with no effect my horizontal-stack still stay as a element like the other one - thanks
Needing some guidance. Using the restful I am trying to pull into a sensor the price from the following.
@rigid coral posted a code wall, it is moved here --> https://paste.ubuntu.com/p/8yQXFjRpt2/
Nevermind
...as in you figured it out?
yes
Its sad but i game I play has some open api links. So i created a few home automations to give me updates when im away
yea my mistake
can someone help me with a template, i want it to return true if the time of day is between 545a and 615a
Need to create a time sensor and compare against it
can you elaborate? i have another template that compares time without a time sensor, but i dont care about the minutes so its an easy comparison {{ now().hour < 23 and now().hour > 12 }}
That won't work because it will never update
it does work :/
guess cuz i'm using the built in time sensor?
entity_id: sensor.time
If you are using that sensor you are fine
i just thought there might be an easier way to do what i was wanting than checking that the ((hour = 5 and min >= 45) or (hour = 6 and min <= 15))
{{ '05:45' < states('sensor.time').strftime('whatever it is) < '06:15' }}
Something like that
Or you could use now().strftime()
A quick reference for Python's strftime formatting directives.
yea, sorry, new to python and jinja...thanks..i think this does it..testing now with ```{{ '00:45' < now().strftime('%H:%M') < '00:46' }}
That will get it for between those times. Might want to do <= etc
Depending on what you want
Hey guys
I'm a bit stuck
I'm trying to make my own input_datetime changer using custom button cards
I'm struggling to get the statement correct for input_datetime to accept it
Error I'm getting: Invalid time specified: 12:"{{14}}":00 for dictionary value @ data['time']
I'm just starting at the basics to get input_datetime to accept the template before I carry on as the problem is I'm not giving it in the right format
Examples of what I have tried:
time: '10:11:00' works
time: "{{00}}:00:00" doesn't work
time: '1:1:1' works
{{ now().timestamp() | timestamp_custom("%H:%M:%S", true) }}``` example from https://www.home-assistant.io/integrations/input_datetime/ doesn't work
`time: "{{ now().strftime('%H:%M:%S') }}"` from the page above also doesn't work
You're using button-card?
Cards generally don't support templates
yes custom button card
That card requires a different style of templates: https://github.com/custom-cards/button-card#javascript-templates
It's not HA templates, so you're probably better off asking for help in #frontend-archived since it's specific to a card.
I actually used the JS to determine the name for the cardπ΅ π©
Thanks mono
will try with JS
thanks @ivory delta for the reminder!
Got my card going ==> https://paste.ubuntu.com/p/RYDZGPyCdK/
Just need to make it look nice
@hollow river you can make that generic so it works with any input datetime.
Should I just make the input_datetime a variable?
Or did I miss something on how to use entity in the button card?
Thanks for taking a look @mighty ledge
I'm trying to use a template within the data of a service call but cant seem to get it working. Would someone be able to help me?
I'm using Assistant Relay to send messages from HA to my google home speakers. But I want to include the state of a specific sensor. When using developer tools I can add command: This line will be broadcasted to google home speakers as service data to the service that broadcasts. How can I template in this?
Nevermind... Just had to use data_template: instead of data: π€¦ββοΈ
@hollow river the the entity gets passed through the entity field. So inside js all you need to use is entity.state to get the state
Thanks a million for the tip @mighty ledge!
Looks a lot better and much quicker to apply to other rooms!
https://paste.ubuntu.com/p/HtFcPG9szJ/
hey, any one can help me? I need to print value_json.20
{% set value_json = '{"20":true,"21":"colour","26":0}'|from_json
%}
stringified object: {{ value_json.20 }}
this give me:
Imitate available variables:
stringified object:
value_json['20']
thanks π
But i still have problem with getting state from my mqtt device... This is my code and logs: https://pastebin.com/d6XQGtir
My device is ON when mqtt send: 20: true
your state_template is wrong
move what you have in value_template into state_template
i try this, but without any changes
HA after turn on device, stil thinks that is turn off.
then your statement doesn't match the mqtt payload
should match:
2020-06-22 23:26:14 DEBUG (MainThread) [homeassistant.components.mqtt] Transmitting message on tuya/ver3.3/bf24dd734a72585e44yw96/cf6b639ab2ef6a3b/192.168.123.54/command: { "multiple": true, "data": {
"20": true,
"21": "colour",
"26": 0} }
2020-06-22 23:26:15 DEBUG (MainThread) [homeassistant.components.mqtt] Received message on tuya/bf24dd734a72585e44yw96/cf6b639ab2ef6a3b/192.168.123.54/dps: b'{"20":true}'
2020-06-22 23:26:15 DEBUG (MainThread) [homeassistant.components.mqtt] Received message on tuya/bf24dd734a72585e44yw96/cf6b639ab2ef6a3b/192.168.123.54/dps: b'{"20":true}'
2020-06-22 23:26:16 DEBUG (MainThread) [homeassistant.components.mqtt] Received message on tuya/bf24dd734a72585e44yw96/cf6b639ab2ef6a3b/192.168.123.54/dps: b'{"101":"QgAAAAGsJgEABwQh"}'
but you have messages without "20" on the same topic
so, you thinks that last message change state to off?
i change IF to if not value_json['20'] but this still dont help. Do you know better way?
{% if not value_json['20'] %}off{% else %}on{% endif %}
that's just the same statement written differently
you need to grab last known state of the device from HA in case the message sent to the watched topic doesn't contain "20"
is special option for this?
special option?
optimistic ?
you're not understanding what is happening with your current statement
it says if there is value with key 20 make the device on, if not make it off
yes
so whenever, f.e. "101" is received it makes your device off since 101 != 20
no
ok, good luck then
maybe this? {% if '20' in value_json %} ?
@jagged obsidian that's not what the if statement is doing. it's if value_json['20'] equates to true
{% if value_json['20'] == true %} would be redundant
and i said what?
if there is value with key 20 make the device on, if not make it off
and that is not true why?
Because it's evaluating the value of value_json['20'] not just whether it exists
this works:
state_template: >-
{% if value_json['20'] is defined %}
{% if value_json['20'] %}
on
{% else %}
off
{% endif %}
{% else %}
{{ states('mqtt_led_schody_gora') }}
{% endif %}
if it doesn't exist it will throw an error in logs anyway
no
it would equate to false
his statement said if value_json has a key "20" make it on, in all other cases make it off
but now i dont know how to add control to set color and brightness.. When i add ``` brightness: true
rgb: true
{% if value_json['20'] is defined %}
{{ 'on' if value_json['20'] else 'off' }}
{% else %}
{{ states('mqtt_led_schody_gora') }}
{% endif %}
no, that's not what it's doing
for template schema you need to define brightness value and rgb value
the true flags are for json schema
@mighty ledge: is possible to change string "mqtt_led_schody_gora" for any variable with current name?
if value_json['20'] is equal to false then if value_json['20'] would return false
@quiet kite I don't follow the question
@jagged obsidian it's not python and it's not json.
it's a dictionary in jinja
and jinja's rules for existence are different.
i'm explaining to wmp that he's looking at wrong mqtt.light setup pertaining to the config he posted first
how can i get brightness state from HA memory, when mqtt dont send me current?
pull it from the state machine state_attr('xxx.xxx', 'brightness')
thanks
if the light is off, that attribute may not exist
when i add brightness support, i have problem with state...
2020-06-22 23:49:06 DEBUG (MainThread) [homeassistant.components.mqtt] Received message on tuya/bf24dd734a72585e44yw96/cf6b639ab2ef6a3b/192.168.123.54/dps: b'{"22":255}'
2020-06-22 23:49:06 WARNING (MainThread) [homeassistant.components.mqtt.light.schema_template] Invalid state value received
lol, just noticed {{ states('mqtt_led_schody_gora') }} you don't have a full entity_id here.
needs to be domain.object_id
so, if thats a light, i would expect the entity_id to be light.mqtt_led_schody_gora
ahhh, thanks!
this is my first device
my LED controller set RGBW as: 00b7035c0064, i thinks this is R: 00b7 G: 035c B: 0064. This can be true?
make it so its red only to 100% and then repeate for G, B and W and you'll know
here's my experience with tuya led color: 14 char value in hex (can define only RGB and send HSV value as max: RRGGBBffff6464)
but that's RGB only
here's how i dealt with it {{ (value_json['TuyaReceived'].Type3Data[0:2]|int(base=16),value_json['TuyaReceived'].Type3Data[2:4]|int(base=16),value_json['TuyaReceived'].Type3Data[4:6]|int(base=16)) | join(',')}}
change ['TuyaReceived'].Type3Data to your key
Hi guys, need advice, I'm trying to set a random range in the attribute 'zones' from the lifx.set_state servive. Documentation says it should look something like '[12,13,14,15]'. Tried this template and won't work even though under dev tools it prints it ok
zones: > {% set t = range(3,20)|random%}
{% set y = range(0,49)|random%}
{% set i = range(y,t+y)%}
{% for i in i %}
{%- if loop.first %}
[{{i}},
{%- elif loop.last-%}
{{i}}]
{%- else -%}
{{i}},
{%- endif -%}
{%- endfor -%}
sorry, I pasted it wrong: ```
Templates always return a string even if it looks like a list or another data type
I'm not even sure what you're trying to do
I want the attribute zones to be random
first time I call it [1,2,3,4,5] for example, next time I call the service [30,31,32,33,34,35,36,37,38] for example
{{ range(y,t+y)|list|tojson() }}
Output is still a string though
But jsonified at least
You could make it a fixed length list with templates in each of the list items
zones:
- {{ }}
- {{ }}
- {{ }}
yeah I know but fixes length is something I don't want π
SOL then unfortunately
thanks anyways
What's the easiest way using templates to convert last_changed to local TZ?
And is it dangerous to self-reference templated sensor? I want to add a attribute to the same sensor where I'd be pulling the last_changed from (for easy AppDaemon access).
@hexed galleon as_timestamp(states.switch.foo.last_changed) | timestamp_local. Also, you can self reference all you want. Just realize that it will be the result prior to the current change. I.e. if a sensor updates and you reference itself, the result is prior to the update.
Also, why even do any of this when you can just use appdaemon to do it
Because I can't actually work out how to resolve an iteration to a function call in AD. Probably a pretty simple Python thing, but I'm still new to coding.
This is where I got to in AD:
"Washing Machine": "binary_sensor.washing_machine",
"Dishwasher": "binary_sensor.dishwasher",
"Vacuum": "binary_sensor.vacuum"
}
for k,e in entityMap.items():
strTest = f"self.entities.{e}.last_changed"
self.log(self.convert_utc(strTest).timestamp())```
Can't reference e directly inline with self.entities.e.last_changed, so thought I'd try and resolve via string, but that doesn't end up using the actual self object.
you could just get the state state = self.get_state(entity_id=e)
and what you have there doesn't really make sense
you're formatting a string, then sending the string and having it convert to utc?
but the string is the name of the entity and you add self to it. I donno, that's just all over the place
Do you understand the difference between a string and a object?
Well anyways, I suggest you take a basic python tutorial. Make sure to touch base on Classes, it will describe what self means. But you really need to understand the difference between a string and an object. Without that knowledge, you'll have a bad time. This line here tells me that you don't understand that difference. strTest = f"self.entities.{e}.last_changed"
I do understand, I just wanted to know how to parse the e object so that it could be used inline. And using self.get_state() returns the state, when I need the last_changed, which isn't actually a normal attribute, so couldn't use the attribute= arg for get_state().
E isnβt an object tho, itβs a string
And then youβre using format and placing it in another string
Sorry, yes - I tried that way because I couldn't use self.entities.e.last_changed as it wouldn't parse e, instead referencing it.
If you want the full state you need to use attributes=βallβ as an argument for get_state
Ohh, didn't realise that would also return the hidden/system attributes. That is likely the solution then! Thanks.
Oh, well now I feel even dumber. Didn't realise there was a simple get function that I could assign to a variable >_>
Thatβs why you should take a basic python tutorial
Lots of learning today! Thanks again π
It covers uses of dictionaries, lists, classes
That stuff is AD-specific though, right? I understand dicts/lists. Just didn't realise there was a .get function, and didn't know that AD would return all the attributes (even system ones that are generally harder to find in HA).
Ohh, great tip then! Will help a lot.
The function call get_state is AD specific
Everything under self. is AD specific
self is the class youβre inside, and itβs the appdaemon main class
Yeah, worked that out a while ago. Helped with variable scope to understand that.
Right but that doesnβt mean an object under AD has all AD specific methods
Er, functions. Python lingo
Yeah, makes sense. Thanks again for all your help. Much clearer now!
Why would the last_changed attribute of a template sensor be reporting the last reboot time of HA? Is it because the device/template referenced in the value is momentarily unavailable at startup?
Something like that
What about for an input_boolean then? Seems illogical to have that "changed" to the same state it was before restart.
Because at startup it has no state until it is restored from the db or defaulted via initial:
Rough π¦ So the only real way you can persist a true last_changed would be to write it as a timestamp to an input_number or as a string to a input_text then?
Something like that
is it possible to pass an entity to a macro and then have its stage read inside the macro?
@hexed galleon with appdaemon, you can store date times using json and dump it to a file and restore on startup
Not sure if this is the right channel or not, but I am wondering if there is a way to assign an area to a light template entitiy?
No
Areas are currently very limited
ok, do we know if there is a plan to add that functionality in the future?
When they were first introduced balloob was saying they were effectively going to replace groups for entity control, allowing control of multiple entities as one without the overhead of tracking states like groups. That was over a year ago, and to my knowledge they haven't changed much since then. They seem to still be directly tied to "devices"
I don't know what the plan for them is moving forward, but I wouldn't expect much anytime soon
oh ok, I was trying to clean up my HA config... but I can use regular groups instead of areas. thank you for your help.
I'm having trouble getting the brightness_pct of a lamp. brightness seems to work but with brightness_pct I always get 0
Any idea why?
brightness_pct is not an attribute
Oh, that explains a lot. Thanks.
@solemn dirge you could get the brightness_pct equivalent by dividing the brightness by 2.55
Hey All not sure if this the correct area... I am trying to track how long a scene been on for I have three Day night and Evening, an Automation will kick each one off. I wanted to track them via a sensor or something like this. any help would be great
scenes don't ever turn "off", so it's not clear what the endpoint would be
seems like that's key to solving the problem
Technically mine do π ( turn off some lights etc.. ) I was just going to try and track when the house goes from each mod. Maybe I have to achive this in a different way
Set an input_datetime at the same time you activate a scene, then use that to determine the time that's passed.
@inner mesa @ivory delta cheers for you input tho π
right, and then trigger on whatever your "off" event is, activating a new scene, turning some lights off to modify the "scene", or whatever, and do the math
Looks like {{states.sensor.fpl_1034853430.attributes.details[0].date}} gets me the first result, which is great, but without having a total of results first, is there a way to get the last value instead of setting a key?
ok, so looks like {{states.sensor.fpl_1034853430.attributes.details|last}} will allow me to get the last group
[-1]
Hi guys, I'm having issues with a template, dunno why
trying to run a Plex playlist through a template
media_content_id: >
{% if is_state('input_select.party_scenes_verano', 'Modo Energizing Verano')%}
{"playlist_name": "Energizing"}
{% elif is_state('input_select.party_scenes_verano', 'Modo Intense Verano')%}
{"playlist_name": "Intense"}
{% elif is_state('input_select.party_scenes_verano', 'Modo Hoguera Verano')%}
{"playlist_name": "Hoguera"}
{% elif is_state('input_select.party_scenes_verano', 'Modo Tibet Verano')%}
{"playlist_name": "Tibetan"}
{% elif is_state('input_select.party_scenes_verano', 'Modo Lucy Verano')%}
{"playlist_name": "Lucy"}
{% elif is_state('input_select.party_scenes_verano', 'Modo Final Fantasy IX Verano')%}
{"playlist_name": "Final Fantasy IX"}
{% endif %}
gives this error: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
.share the full thing
Please use https://paste.ubuntu.com/ or https://www.hastebin.com/ to share code or logs.
it's a play_media service
that's what creating problems
I've been able to run that very same service when just calling a single playlist
the service yielded the very same error when I single quoted every playlist_name line
wow, apparently I solved it by mere luck, I just changed every line with this {{ '{"playlist_name": "Energizing"}' }} istead of this '{"playlist_name": "Energizing"}'
thanks anyways
doors_open_count:
friendly_name: Doors Open Count
entity_id:
- binary_sensor.door_down_patio
- binary_sensor.door_up_deck
value_template: >-
{{ states.binary_sensor | selectattr('state', 'eq', 'on') | selectattr('attributes.device_class', 'eq', 'door') | list | count }}
just want to confirm something - a template sensor like that written above will always return a string, correct?
Technically a template always returns a string
but even if I appended " | float" to the end of the value_template, home assistant would not consider the result a number?
I'm trying to do math with the result of this value_template and it keeps failing, so I'm trying to confirm that this is the issue
In your maths, ensure you're filtering the entity state into some form of number
You have to do that with any entity state anyway
I'm doing this in node red, so this may be better posted there, but when I try to use the Wait Until node and compare the result of that template sensor to 0, it does not work
Then yes, #node-red-archived would be where to ask
so using " | float" and having it display as XX.X in the Dev Tools doesn't necessarily mean HA considers it a number, if it comes from a Template Sensor with the following value template, it's still a string that needs to be converted
{{ states.binary_sensor | selectattr('state', 'eq', 'on') | selectattr('attributes.device_class', 'eq', 'door') | list | count | float }}
thanks for the help @arctic sorrel. I just made another template sensor dependent on the other but this one returned true/false which let me do a string comparison in node red
Hey guys, I need help in creating a command line sensor to extract bytes from this JSON data
https://paste.ubuntu.com/p/fzJwRM3pcK/
Upload, download, or ...?
Both
Whichever you think is optimum
FFS
Ultimately I want to convert the value to Mb/s
If you don't even know what you want, why are you asking for help?
{{ THING.download.bytes }}
{{ THING.upload.bytes }}
Replace THING with the relevant context
You said I should provide you with whatever I wanted, so I did
It's unlikely to be terribly useful
Could you be any less rude?
Yes
I asked what you wanted, and you basically shrugged
Why should I help you if you can't be bothered to decide what you want
Alright, I will rephrase. I want the values (bytes) extracted and converted to Mb/s in a single command line sensor
Do you want one for upload and one for download? Do you want a combined total? What do you want?
The former, but the command should only be run once
value_template: "{{ value_json.download.bytes|int + value_json.upload.bytes }}"
``` probably
That does not add the two values?
It probably needs an |int after the second
yup, otherwise string math
The values are simply getting added
"{{ ((value_json.download.bytes|float/1048576)|round(1))|int + ((value_json.upload.bytes|float/1048576)|round(1))|int }}"
kinda seems like you have everything you need to solve this, though
You keep posting asking for complete solutions, you've already got all the parts you need to solve these yourselves
Yes I am close but not there, yet
What should a value template look like to extract latency from here?
entity - sensor.speedtest_net_download
upload:
bandwidth: 11690788
bytes: 42436536
elapsed: 3628
ping:
jitter: 0.735
latency: 1.957
unit_of_measurement: Mb/s
friendly_name: Speedtest.net Download
icon: 'mdi:speedometer'
Plenty of examples here: https://www.home-assistant.io/docs/configuration/templating/#states
What have you tried so far?
I have tried this:
{{ state_attr('sensor.speedtest_download','ping').latency }}
This seems to work but should not be used as per docs??
{{ states.sensor.speedtest_net_download.attributes["ping"]["latency"] }}
Plenty of examples here: https://www.home-assistant.io/docs/configuration/templating/#states
What have you tried so far?
Can't find anything here for nested attributes
Been following from here
https://www.home-assistant.io/integrations/rest/#fetch-multiple-json-values-and-present-them-as-attributes
And why does it say it shouldn't be used?
Avoid using states.sensor.temperature.state, instead use states('sensor.temperature'). It is strongly advised to use the states(), is_state(), state_attr() and is_state_attr() as much as possible, to avoid errors and error message when the entity isnβt ready yet (e.g., during Home Assistant startup).
Did you try {{ state_attr('sensor.speedtest_download','ping')['latency'] }}
Just did, doesn't work
That format definitely works. I get a value back for a template in my HA ({{ state_attr('sensor.sonarr_upcoming_media','data')[1].airdate }})
What comes up with just state_attr('sensor.speedtest_download','ping')
Then it doesn't have a ping attribute.
Let's play a game
Alright please check this screenshot
https://www.dropbox.com/s/k6ydt0cyy1v3uou/Screenshot 2020-06-25 23.41.36.png?dl=0
spot the difference sensor.speedtest_net_download sensor.speedtest_download
You mean you can't just make up names?!
You can, but the results won't change
What comes up with just
state_attr('sensor.speedtest_download','ping')
Yeah corrected this and it works
Thanks for your help @hollow bramble
hey guys, how do I take the timestamp from last time a door was open and let's say in last 5 minutes, something like this?
{{ ((as_timestamp(now()) - as_timestamp(states.binary_sensor.lumi_magnet_aq2_door_entrance_on_off.last_changed)) | int < 300) }}
{{ ((as_timestamp(now()) - as_timestamp(states.binary_sensor.lumi_magnet_aq2_door_entrance_on_off.last_updated)) | int < 300) }}
- the problem is when I restart ha this becomes true for the first 5 minutes, how do I overcome this, I am interested to know if the door was open in last 5, 10 minutes for tracking proposes
Please DO NOT cross post. Read the channel description, post it and wait for folks to respond.
Can this be done?
When I type in "module" and get the result
stat/xxxxx/MODULE = {"Module":{"46":"Shelly 1"}}
I only want to get "Shelly 1" but I am not sure how to do that in the templates
valur_json.Module[β46β]
what I needing is 46 to be a wildcard so I can write it up like this, so no matter if its 46 or 28, it will just give me the answer "Shelly" or whatever it is
value_template: " + '"' + "{{ value_json['Module'][???] }}
Sounds like the key (46 or 28) really needs to be the value
What's the ultimate goal here though?
I have sensors to give me certain data for each device... I want a sensor to tell me what module is set for that device
Separate template sensors then with petro's suggestion (value_json of course)
but what if the key is say 50?
Add another template sensor for it? I'm not sure what that number is supposed to represent but if it's some kind of ID for a device, why wouldn't it be static?
I forgot to mention,, this was the output from a tasmota device... so each different module name has a number and there is a lot of them built in. However I don't have a list of what each number is for each module
which is why I was hoping there was some wildcard value so it did not make a difference if it was 25, or 46 or 50. I just want the value regardless of the number
this should work:
{% for val in value_json['Module'].values() %}
{{ val }}
{% endfor %}
@simple sage βοΈ
I am trying to see if my variable 'mode' is equal to any of these values: sleep, chill, away. I wrote this but it doesn't work. What is the proper way to write this?
{% if occ == 'occupied' and mode == "sleep" or "chill" or "away" %}
{% if occ == "occupied" and mode in ["sleep", "chill", "away"] %}
Thank you!!
Does anyone know how to access Event data when templating?
in the Dev tools i can see the event being fired when i listen for it, but i'm not sure how to access the data that is returned when the event gets fired.
it's in the docs
the very first section: https://www.home-assistant.io/docs/automation/templating/
I saw that page before, i'll take another look.
when in doubt, read the docs. they're generally excellent
I guess i'm just not connecting the dots. I'm trying to get the value of "actionName" when an actionable notification is fired.
need more about the event from you, then
one of mine:
- alias: 'iOS Widget: Arm Alarm Night'
initial_state: 'true'
trigger:
- event_data:
actionName: Arm Night
event_type: ios.action_fired
platform: event
the name is whatever name you gave it
my event looks like this in the Dev Tools:
@stray raptor posted a code wall, it is moved here --> https://paste.ubuntu.com/p/YjMk7bxqs8/
ok, and you have my example
mine is old and probably outdated. I don't use it anymore
looks like the event_type has chnaged
Yes, but i'm not trying to trigger off of it, i'm trying to set a helper's value
(I need to pass the value of actionName to a rest_command)
you have to start with a trigger
and the trigger will be for a particular actionName
so I'm not really following
how else are you going to pass it to something else?
Yes, i'm triggering on the action name, but i also need to pass the action name along to a rest api command in the "Action" section of the automation
right, but i have multiple triggers based on different actions
oh, I see
so do i need to setup separate automations for each possible actionName?
I would assume trigger.event_data.actionName
i'd like to just reference the ActionName in the Action sectoin of the automation.
ok, cool, i'll give it a shot.
I have an example somewhere
is there a way i could test that in the "Template" secton of the dev tools?
- platform: event
event_type: isy994_control
event_data:
entity_id: sensor.kit_remote_kit_lights
control: DFON
condition: []
action:
- data:
entity_id:
- switch.kit_overhead_lights_scene
- light.kitchen_table_light
service_template: >-
homeassistant.turn_{{ 'on' if trigger.event.data.control == 'DFON' else 'off' }}
- service: script.fix_scene_states
oo nice.
so, just data
usually there's an example somewhere in the docs of the integration that's sending the event
ok, thanks! i'll give it a shot after dinner. sounds promising.
@inner mesa I'm struggleing with using the template like you have in your example. I'm trying to use a template when setting the value of an input_text helper
the template doesn't seem to be rendering:
data:
value: '{{trigger.event.data.actionName}}'
entity_id: input_text.babybuddy_diaper_solid
service: input_text.set_value
Nope, rule 1 of templating
When working with templates, don't forget:
- You can test them in Developer tools -> Templates
- Rule 1 and rule 2 (https://www.home-assistant.io/docs/automation/templating/#important-template-rules)
π€¦ββοΈ
I was trying to do it via the webUI and totally forgot about the data_template
Remembering these simple rules will help save you from many headaches and endless hours of frustration when using automation templates.
or, you can just spend that time π
and then still need to ask for help!
@stray raptor do u use NODE RED?
I'm working on something similar with actionable notifications
if your notifications are going into android
@idle cargo No
My notifications are for iOS. I migrated away from NodeRed recently. I felt like it was becoming too difficult to share/backup
I just started using node red this week...and seems pretty powerful
for this exercise I was able to create actionable notifications in node red and receive the actions as well.
I also was able to use node red to call HA Automation... and also receive the actions as well
@stray raptor .... not sure maybe this might help
how can i do a state + state math operation? in template?
{{ states('thing.one')|float + states('thing.two')|float }}
See the templating docs
Thx!
What is problem here?
{{ states('sensor.server_1_disk_1_usage')|float * 100 / states('sensor.server_1_disk_1_usage')|float + states('sensor.capacity_disk_1_free')|float }}
it should return 20
?
Ow
But, if you wanted a+b * c then you needed to write (a + b) * c
Could you please correct that code?
{{ states('sensor.server_1_disk_1_usage')|float * 100 / states('sensor.server_1_disk_1_usage')|float + states('sensor.capacity_disk_1_free')|float }}
Not without knowing your intent
I'm trying to come up with a template loop that shows me all the entities in the light domain so I can make sure I've got them all named right (I have a lot), but it's not working.
{{ entity_id | lower }}
{%- endfor %}```
i have like 400 * 100 / 2000 which wll make me the percentge of usage off totalt
{{ ( states('sensor.server_1_disk_1_usage')|float ) * 100 / ( states('sensor.server_1_disk_1_usage')|float + states('sensor.capacity_disk_1_free')|float ) }}
``` Maybe
Have a look at the default in
-> Templates @royal vortex
{% for state in states.sensor -%}
{{ state.entity_id | lower }}
{% endfor %}
@vagrant monolith why are you multiplying by 100 and dividing by the sum of used + capacity? shouldn't it be (usage/capacity)*100?
Have a look at the default in
-> Templates @royal vortex
{% for state in states.sensor -%} {{ state.entity_id | lower }} {% endfor %}
@arctic sorrel seeing it stated slightly differently helped.
{{ state.name | lower }} {{- '\n' -}}
{%- endfor %}```
If you're using that as a sensor it will never update
Hey guys
I would like to know how to strip the "," out of 2020-06-28, 22:46 using templates
I want to use it to trigger an automation with input_datetime
{{ states('sensor.whatever').replace(',', '') }}
ahh
.replace thanks @buoyant pine ! I was trying to use replace as a filterπ€’
{{ domain.name | lower }}: {{- '\n' -}}
{% for entity in states[mydomain] -%}
{{ entity.entity_id | lower }} {{- '\n' -}}
{%- endfor %} {{- '\n' -}}
{%- endfor %}```
I'm trying to iterate through each domain and list the entity id of all of the entities within that domain, is there a collection of domains? I can't figure out what it is and it doesn't seem to be listed in any of the docs I've looked through
{% for state in states %}
{{ state.entity_id }}
{% endfor %}
Beat me to it!
{{ states | selectattr(βdomainβ, βeqβ, βlightβ) | map(attribute=βentity_idβ) | list }}
use the filters luke
Nah jk, I should learn how to make templates like that
trying to get a template going,.. but failing miserably,.. so I turn for some help and guidance from the noble few,.. Ok so i'm trying to enable a light to be on for set delay times,.. and to be active only 1hr before sunset until 1hr after sunrise,.. but to also change the countdown timer value depending on whether it is evening or night,.. I have cobbled together a template,.. from many different threads,.. ( and although HA is happy to execute it) it does not deliver,... can anyone help,.. and can anyone shed light on the meaning of code differences such as 'duration: >-' or 'duration: >'... the dash being the only difference... rules here:- https://pastebin.ubuntu.com/p/3TQMWCGckd/ many tx guys/gals
Not specific to your template, but I recommend using sun elevation rather than sunset/sunrise to simplify and improve the conditions
> removes line breaks, but leaves a trailing break at the end. >- gets rid of the trailing break
ok,.. tx,.. I'll go for the elevation stuff,.. have tried a variant or two along the way,.. but I will revert back and try some more,... is my timer template good,? or is that missing some refinement,.. ah >, >- I get it now... rather than having one long line,... sort of similar to \ in linux.
Ok,.. have revamped to a previous incarnation of my automations.yaml with elevation the driver,.. but this is still not working as expected even though it is now dark in the UK,.. π https://pastebin.ubuntu.com/p/w3KzyzYDVq/ thanks for the pointers help
The sun's elevation isn't below -6ΒΊ in most of the UK yet π
ahhhh,.. I would not have found that ,... π so what is a good number for the UK.. say London Now....
A good number? I like -90.
Surefire way to make sure your automation never triggers π€·ββοΈ
If you don't know what values you want, experiment. If you want to see what the sun's elevation is at your location, check in
> States
I can't tell you, cos I'm not in London... and basic math says it's gonna vary based on latitude and longitude π
me personally - I'm using https://github.com/claytonjn/hass-circadian_lighting because the elivation alone doesn't work well all year round
Well that's great if you're talking about the colour temperature or brightness or bulbs... but when you want a 'night mode' for timers... π€·ββοΈ
sorry, wasn't thinking.. I have an automation that does something similar. It uses the sunset event and offsets by 15 minutes. That worked well for me but am still thinking of building a lux measurement.
wait what are we talking about?
I do a decent amount with lights.
I use node red though
@ivory delta,... ah tools=>states,.. perfect,.. now I can see -6 was never going to work,... more like 25,.. as mid-day is at approx. 60degrees...
thanks for the pointers
Midday is around 60 degrees at some times of the year.
Seasons exist because of the Earth's tilt. The sun's elevation varies year round.
If you want a more accurate solution, you'll have to take that into account... but elevation is good enough for most purposes.
at some times of the year, at some latitudes...
Well, yeah. I was taking it as a given that diyhouse won't be moving around the globe constantly π
Can someone bring some sanity here? Here is a self contained template that sets var, then sets entity based on the value of var, then prints it. It works fine if var is less than < 10, but the moment i get into 2 digit numbers, it breaks.
Practically speaking, var is actually a counter, but its working the same way
{% if var <= '1' %}
{% set entity = 'light.osram_lightify_flex_outdoor_rgbw_2904a300_level_light_color_on_off' %}
{% endif %}
{% if var >= '6' %}
{% set entity = 'light.kitchen_island_lights' %}
{% endif %}
The entity is: {{ entity }}```
so if var is set to 1-9, I get the value entity, the moment I set it to 10 it breaks
You're trying to do math on a string
is this because I wrapped the int in single quotes?
wrapping something in quotes makes it a string
right, when I remove the quotes the template fails completely though
fails in what way?
let me test it again, it is possible I had quotes in portions of the template, and not others.
{% set var = 10 %}
{% if var <= 1 %}
{% set entity = 'light.osram_lightify_flex_outdoor_rgbw_2904a300_level_light_color_on_off' %}
{% endif %}
{% if var >= 6 %}
{% set entity = 'light.kitchen_island_lights' %}
{% endif %}
The entity is: {{ entity }}
this renders The entity is: light.kitchen_island_lights
@buoyant pine if we're being honest I didnt realize there was elif in jinja, but clearly I didnt look hard enough
soooo thank you lol
admittedly new to templating. thank you both!
Ah, small update I knew I wasnt totally crazy. Looks like the result of my state call to the counter
states('counter.kitchen_occupancy_counter') was actually returning a string, which is why when I tried to compare it to an int the template failed
Now that I filter the state response into an int states('counter.kitchen_occupancy_counter') | int everything works as expected.
Thanks again!
Does anyone with template/webhook and JSON experience what to take a look at this issues I'm having: https://community.home-assistant.io/t/json-in-webhook-notification/208428
try trigger.id
@dreamy sinew gives me the same error.
Is it possible whatever "{{.Service.Id}}" is rendering to is breaking the json string?
@worn nova posted a code wall, it is moved here --> https://paste.ubuntu.com/p/d7fjYykD3B/
@hollow bramble Same error I'm afraid
@worn nova Rule #6: Spam will not be tolerated, including but not limited to: self-promotion, flooding, codewalls (longer than 15 lines) and unapproved bots.
Please take the time now to review all of the rules and references in #rules.
was that for me @arctic sorrel ?
Not as such...
same error as what? Your other error was json related. You're still getting a json error when you use {{trigger.data}}?
@hollow bramble Yes same error as in the link.
try changing the payload to a static json string
sorry example?
{
"id": "id",
"online": true
}
again same JSON error. Just going to reboot HA as previously it was triggering but getting no json output in the persistent message.
@hollow bramble and the same error. A reply in the HA forum suggested that the payload wasn't being sent as JSON but looking at Statping it shows the correct content type (application/json) and POST.
@hollow bramble thanks for your help, I'll keep testing and trying π
It does seem like it's not posting a json string, but if you don't have access to what it's really sending then it's pretty much impossible to know without introducing something other than HA
is there anywhere in HA to intercept the actual payload and display whats been sent/received or another tool that does something similar?
Node red would work
Hello all, i have a question about json, mqtt and directing the data to different sensors.. am i in the right place or is there somewhere more appropriate?
You're possibly in the wrong place, but until you say more we won't know
ok, so i have some homemade sensors giving me json messages like this.. ESPNow/key {"temp":"29.00","station":"1"} ESPNow/key {"temp":"29.00","station":"2"}
I can extract the temperature, they are all coming in on the same mqtt topic.. what i am looking for is to find out if there is a way to look at the "temp" and the "station id" and decide to which topic the data should be assigned...
so 2 different sensors coming in to the same gateway
No
ok, so just not manageable? i guess i will have to build that in at an earlier stage or preprocess in node-red
Well thanks anyway
@dreamy sinew https://hastebin.com/didahuhuci.sql
hmm, i don't see anything wrong with that. Only problem would be if you're not getting valid json back from that topic
It works if I publish from node red, but not from the code itself, however, I can hear the code publishing from node red
hi I'm just wondering if it's possible to make my automations a little more dry with a template and how I'd go about this. I've used a consistent naming convention throughout so for example the entityId for the lights in a room would be light.<room_name> and lamps would be light.<room_name>_lamp(s) and the timer would be timer.<room_name> and finally the motion sensor would be motion.<room_name>. With that in mind my light motion automations are all identical and very repetitive. So I wondered if it would be possible to some how match the motion and timer triggers using a wildcard and extracting the room name to control the time and light entities accordingly
hi, so i got the int comparison to work. now the next step i can't figure out is the same for a string
train_a1:
value_template: >-
{% if states.sensor.a_to_b.attributes.products = AKN, S %}
off
{% endif %}
eh it would just do off / none π
didnt copy it :/ Here is the complete one
{% if states.sensor.a_to_b.attributes.products = AKN, S %}
off
{% else %}
failed
{% endif %}
{% if is_state_attr('sensor.a_to_b','products','AKN, S') %}
off
{% else %}
failed
{% endif %}
Didn't copy it...
You copied the whole thing then cut parts out... don't do that
ok sorry! won't do it again
value_template: "{{'off' if is_state_attr('sensor.a_to_b','products','AKN, S') else 'failed' }}"
That is indeed the most compact version
If I create a sensor for the products i get ['AKN', 'S']. Seems like they are 2 seperate strings? How can i do this?
Or is it possible just to match the AKN string? Something like a products contain AKN = true
So with ['BUS'] it is working good when there is only a bus. But when there is a the aforementioned string, then i does not work :/
Ok yeah now it's working even though it was the first thing i tried.. super weird. Thanks for your help!! How do i make quotes like you?
To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks. Here's an example:
```
code here
```
Watch the animated gif here: https://bit.ly/2GbfRJE
DO NOT repeat posts. Please edit previously posted message, here is how -> https://bit.ly/2qOOf1G
Same answer as the last time you asked... the payload doesn't have the property value_json
'value_json' is undefined means it doesn't exist.
Okay but how do I fix it?
First, check what you actually get back in the payload.
Second, use something that exists.
Where's it coming from? Where's your config?
So you're using MQTT Cover... what's the MQTT payload for that device?
No. No, it's not.
Listen to that topic (AB_Left_Curtain/state), wait until there's a message, share that message here.
> MQTT > Listen to a topic
I am working on coding the curtains from scratch, that's how I can verify the messages
I don't care how you made it. Share the message.
Okay
Found it?
I had to restart my HA because of a network issue, I'll share it as soon as I can!
I keep getting a socket err on the program, I think I'll just retry this tomorrow as I've been getting issues all day, thank you anyways though
Does a logged error tell me which template is having an issue?
Source: helpers/template.py:230
Integration: Home Assistant WebSocket API (documentation, issues)
First occurred: 3:02:58 PM (2 occurrences)
Last logged: 3:02:58 PM
The error, https://pastebin.com/raw/ETHsMtF4, doesnt appear to point to any specific template and I'm confused by websocket component in the logger
Anyone know where I should look?
Check the actual log file
with 0.112.0 Update i see MQTT tab missing under developer tools
also not a #templates-archived question lol
not even really a question
Damn, didn't even notice that had moved there
I kind of get why it's there, but it's slightly odd π
yeah... maybe an "integrations" tab on dev tools would have been a little easier of a transition
It has been...quite jarring
That's why I have a server controls panel redirect now (to get to the logs quicker)
using the frontend logs 
And reloads for automations, scripts, etc
Moving to #frontend-archived
What is wrong with this script
alias: Ring_test
sequence:
- data:
data_template:
filename: '{{state_attr(''camera.front_door_2'', ''friendly_name'')}}'
subdir: '{{state_attr(''camera.front_door_2'', ''friendly_name'')}}'
url: '{{ state_attr(''camera.front_door_2'', ''video_url'') }}'
service: downloader.download_file```
data_template: doesn't go under data:, it replaces data:
that is what i said π
now i get invalid error for url error
When working with templates, don't forget:
- You can test them in Developer tools -> Templates
- Rule 1 and rule 2 (https://www.home-assistant.io/docs/automation/templating/#important-template-rules)
help,.. so I placed/copied a template in the dev. tools template,.. and then triggered it from an Events form and check result,... Humm that does not work for me,.. well more correctly 'I aint doin' right',.. pls help,.. what should I be doing,.. I'm a wally for missing the obvious I assume...
@fallen sorrel Please use https://paste.ubuntu.com/ or https://www.hastebin.com/ to share code or logs.
Without seeing what you're doing, and you explaining what you want... π€·
https://pastebin.ubuntu.com/p/Dv949h3q5n/,.. testing this template,.. which fails during HA reboot with
Invalid config for [sensor.mqtt]: [time_of_day] is an invalid option for [sensor.mqtt]. Check: sensor.mqtt->time_of_day. (See ?, line ?).
Component error: time_of_day - Integration 'time_of_day' not found.
Component error: entity_id - Integration 'entity_id' not found. Component error: time_of_day - Integration 'time_of_day' not found. Component error: friendly_name - Integration 'friendly_name' not found.
Error loading /config/configuration.yaml: while scanning for the next token found character '%' that cannot start any token in "/config/configuration.yaml", line 89, column 6
line 89 is the start of the if statements in my configuration.yaml file....
but I was trying the template tester stuff out that has just popped up on the chat here,. so I thourght I'd give that a whizz..
sorry guys,.. this is the error message I get from my config.yaml...Invalid config for [sensor.mqtt]: [time_of_day] is an invalid option for [sensor.mqtt]. Check: sensor.mqtt->time_of_day. (See ?, line ?).
Component error: time_of_day - Integration 'time_of_day' not found.
Component error: entity_id - Integration 'entity_id' not found. Component error: time_of_day - Integration 'time_of_day' not found. Component error: friendly_name - Integration 'friendly_name' not found.
Error loading /config/configuration.yaml: while scanning for the next token found character '%' that cannot start any token in "/config/configuration.yaml", line 89, column 6
Invalid config for [sensor.template]: [time_of_day] is an invalid option for [sensor.template]. Check: sensor.template->time_of_day. (See ?, line ?).
https://pastebin.ubuntu.com/p/TQpMfCNvsK/ and this is my config.yaml,.. I have tried the code supplied by Tediore,.. and many variations,.. there of,.. trying to get my 2 spaces correct,.. I assumed because I have a 'sensor:' entry already in the file I add extra sub sensor: bits by prefix'ing with a dash '-',.. but apparently not!... where is my formatting failure... many tx for your patience...
hello my dearest friends π
@fallen sorrel your indentation is off, check the template sensor docs again
I hope someone here may help me π iam currently building a rest sensor and wanting to query "tomorrow as yyyy-mm-dd"
resource_template: http://192.168.5.195:8089/api/mealplancount/{{ now().strftime('%Y-%m-%d') "Idontknow what I shoudl do here because Iam a noob" }}
today is no problem works with resource_template: http://192.168.5.195:8089/api/mealplancount/{{ now().strftime('%Y-%m-%d') }}
wah discord encodes it π
To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks. Here's an example:
```
code here
```
Watch the animated gif here: https://bit.ly/2GbfRJE
DO NOT repeat posts. Please edit previously posted message, here is how -> https://bit.ly/2qOOf1G
stops that problem
ok
heyy π i wanted to add 2 minutes to a timestamp but can't figure it out.. can you help me?
train_akn:
value_template: "{{(state_attr('sensor.hamburg_horgensweg_to_hamburg_langenfelde','departure')+(120|timestamp_custom('%H:%M', false))) }}"
heyy π i wanted to add 2 minutes to a timestamp but can't figure it out.. can you help me?
train_akn:
value_template: "{{(state_attr('sensor.hamburg_horgensweg_to_hamburg_langenfelde','departure')+(120|timestamp_custom('%H:%M', false))) }}"
The output is somehow departuretime00:02
The output is somehow departuretime00:02
You could convert it to a timestamp (seconds since the epoch) then add 120 seconds, then convert back
@arctic sorrel sry to bother, do you maybe also know how I can add one or two days to {{ now().strftime('%Y-%m-%d') }} in resource_template: http://192.168.5.195:8089/api/mealplancount/{{ now().strftime('%Y-%m-%d') }}

eeek ss π
ok I'll try ty !
i use as_timestamp for the conversion right?
so
value_template: "{{(as_timestamp(state_attr('sensor.hamburg_horgensweg_to_hamburg_langenfelde','departure'))) }}"
should give me some number right? only getting none..
as_timestamp requires the right kind of input π
Odds are that your entity isn't providing an actual datetime
The output is like 20:44
Then you can't convert that to a timestamp
Add a date
You need something like 2016-06-02 20:44:00
is the an option to test such commands except in the configuration.yaml?
When working with templates, don't forget:
- You can test them in Developer tools -> Templates
- Rule 1 and rule 2 (https://www.home-assistant.io/docs/automation/templating/#important-template-rules)
Ah way better, thanks!
Hi! I'm trying to get the max value a sensor has been. I've been trying through examples on the web but no luck yet. Anyone have a good idea?
Yeah I have that, then did {{ state_attr('sensor.total_solar_energy_stats', 'max_value') }} so the attribute is the statistics version of the sensor but it seems to output the current state
The attribute has the correct value?
You may also need to play with the max age setting
Ah that looks to be it. It doesn't say in the docs, do you know what format the max_age should be?
alright, thanks!
still working on the smae problem with another try. I got 22:34 and want to seperate both and then add the time. Time adding is working good so i get 36 with the code but when i want to add the hour i can't render anymore
value_template: "{{((state_attr('sensor.hamburg_horgensweg_to_hamburg_langenfelde','departure')[0:3])+(state_attr('sensor.hamburg_horgensweg_to_hamburg_langenfelde','departure')[3:5]|int+2) )}}"
So last part is working good with conversion to int, but now i want to keep first part as a string
got it working
now when I'm finished π
[0:2]?
my solution is not very elegant
value_template: "{{((state_attr('sensor.hamburg_horgensweg_to_hamburg_langenfelde','departure')[0:2]|int)|string+":"+(state_attr('sensor.hamburg_horgensweg_to_hamburg_langenfelde','departure')[3:5]|int+2)|string )}}"
I actually dont know what you try to do
your issue meight be taht you take the semicolon with
Imitate available variables:
{% set my_test_json = {
"temperature": "22:34",} %}
{{ (my_test_json.temperature)[0:3] }}
{{ (my_test_json.temperature)[3:5] }}
{{ (my_test_json.temperature).split(':')[1] }}
{{ (my_test_json.temperature).split(':')[1]| int+2 }}
=
22:
34
34
36 ```
so the split takes everything after the ":" ?
you set the symbol where you like to cut stuff and pack it in an array
[0],[1],[2].... to get the data out
ah okay nice. thank you!
{% set my_test_json = {
"temperature": "22:34:i want to:27:50:say hi",} %}
{{ (my_test_json.temperature).split(':')[2] + " >>:<< " +(my_test_json.temperature).split(':')[5] }}
i want to >>:<< say hi
I need inspiration with this Ikea Tradfri on/off dimmer switch.
I can compfortable turn on / off devices but got my issues templating the brightness_down > brightness_stop messages.
some pointers maybe?
is there a place other than configuration.yaml to put template sensors? I don't like having to restart home assistant to add one, and you can add scripts etc without doing so
not yet
god willing, one day...
can anyone help me template out the NWS weather. I'm trying to get just a single forecast from the list.
I have {{ state_attr('weather.kelp_daynight', 'forecast') }}
But if I try to do {{ state_attr('weather.kelp_daynight', 'forecast')[0] }} It fails
{{ states.weather.kelp_daynight.attributes.forecast[0] }}
Please use https://paste.ubuntu.com/ or https://www.hastebin.com/ to share code or logs.
try {{ states.weather.kelp_daynight.attributes.forecast.detailed_description[0] }}
nada
@dull ledge 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.
oh.
you must have something wrong in the name or something. i just tried {{ states.weather.home.attributes.forecast[0] }} in my own editor and it worked fine
returns {'datetime': datetime.datetime(2020, 7, 4, 12, 0, tzinfo=<DstTzInfo 'America/New_York' EDT-1 day, 20:00:00 DST>), 'temperature': 82.8, 'condition': 'sunny', 'pressure': 1016.1, 'humidity': 65.7, 'wind_speed': 12.2, 'wind_bearing': 20.5}
and weather.kelp_daynight is a different entity?
idk what is wrong then. should be working based on what you have said
try restarting ha i guess?
what version of home assistant are you on? i think there was an issue with dev tools > template in 0.112.0
oh yeah
also Barbados, it's good practice to use {{ state_attr('weather.home', 'forecast') }} instead of the method you're using
112
same idea with using states() instead
ill be honest, i'm too lazy to hold shift for the parentheses
but i know you are right lol
lmao
@dull ledge your syntax looks fine, the template tool is just acting up and cuts off the first few lines of output
so this should be valid then?
yeah
im on 112.1 and it is working for me so update and youll be good
tomorrows_forecast:
friendly_name: "Tomorrows Forecast"
value_template: "{{ state_attr('weather.kelp_daynight', 'forecast')[3].condition }}"
and yeah, just update to 0.112.1 (i'm doing it now)
mashing that button
SMASH THAT MF UPDATE BUTTON
like & subscribe
alright. Thanks for the help. Hopefully when it comes back up everything will behave.
this is how i update π
matt@debian-server:~$ update
What Home Assistant version do you want to update to? (Enter x to cancel.)
[1] Stable
[2] Beta
[3] Dev
[4] Custom
1
Update to the newest stable version? (y/n)
y
Ok, updating.
do you snapshot beforehand?
does that work on the docker supervisord install?
i don't run supervised so i don't have snapshots
oooo
that's a bash script i made
livingOnTheEdge.gif
i mean, i have automated backups
big dick tediore
hahahaha

i loled at that
im such a pussy, i had an update fail like 2 years ago and ever since i wont even look at the update button without snapshotting
non-supervised is nice though in that it doesn't roll you back if there's a config issue, you can just check the logs, fix the issue, and restart
lol. I've been playing with this for 3 weeks
look at the big brain on BigD
I was trying to build it all with docker-compose. But it was a PITA so I went to an easier install
i just have a separate compose file for everything lol... kind of defeats the point but it works for me
ive always used frenck's install script for docker and never had reason to look elsewhere
but it ties in to my update bash script for EZPZ updates
let's move to #the-water-cooler
I need inspiration with this Ikea Tradfri on/off dimmer switch.
I can compfortable turn on / off devices but got my issues templating the brightness_down > brightness_stop messages.
some pointers maybe?
zha, DeCONZ or Ikea Bridge?
Oh forgotten about the other integrations. The 4th, zigbee2mqtt
Don't just say you have issues. Explain what you're trying to do, and share any relevant logs/config.
Bad padawan. Bad.

