#templates-archived
1 messages · Page 90 of 1
You can't change the state of a sensor 😉
If you want the switch to turn it on and off, you need an entity that turns on and off (such as the switch) in there
You could have the automation turn on and off an input_boolean and use the state of that in the tempalte
value_template: '{{ states("input_boolean.garage_door") }}'
Ah, OK! Taking a step back, am I going about this the right way or is there an easier way to track the status of a door where my only indication of it's status is a guess based on an initial state of closed and a switch that toggles it between open and clsoed?
its'? /grammarfail
"its" is the possessive form 😛
Seems the cover template solves my issues. I'll stop trying to reinvent the wheel 😄 https://www.home-assistant.io/integrations/cover.template
I'd put an actual sensor on the door though 😛
Was thinking that too. An inexpensive Xaomi door sensor would do the trick.
Could have one for both positions to be 100%
I think I'll have too as usually the garage door is being activated by the remote, not my switch.
hi, anyone can help me templating some sensor values? I need to hook up 6 soil humidity sensors but the reading I have is ~6000 for 100% water emerged probe and 14000 with fully dry probe.
Now I need to template what i receive from the ESP and on HA convert it to 0-100% scale.
Can someone help me understant this formula?
- platform: template
sensors:
humidity_plant1_percent_templated:
unit_of_measurement: "%"
value_template: "{{ (172.04819247 - states('sensor.growbox_analog_A0') | float * 0.240963855) | round(0) }}"
I have it runing before but with esp internal ADC now im trying to use ADS1115 with multiple devices
But I havent found yet how to create the maths for that conversion
So, you have a 20,000 point scale
At the simplest, add 6,000, then divide the total by 200. That'll give you 0 for wet, 100 for dry. Subtract it from 100 if you want it the other way around
@arctic sorrel Thank you! I got it to display the correct friendly name using your instructions, but I am having an issue setting up the notify.your_notifier_here. I am having a very difficult time setting up the notify.notify. Do you know if it would be possible to setup the notification to send to something that would then allow me to see it in homekit?
Do you have an example of how to setup any of the notify.notify services? I haven't been able to figure that part out at all, and once I see how it is setup with any integration and then I can try to tinker with it to make it work for my use. I am so inept on the notify.notify that I had to use the persistant notification action just to confirm that the correct friendly name would appear for the alarm
Notifications ... #integrations-archived
Pick one that works for you, then somebody can help
Thank you!
can I ask for quick support ? trying to set loop in template ... goal is to show status of all switches:
{%- for i in [1,2,3,4,5,6,7] -%}
{{ states('switch.rainbird_zone_[i]') }},
{%- endfor %}.
haw to pass "i" to states function below
must be trivial 🙂
{{ states('switch.rainbirdzone' + [i] |string) }},
thanks @queen meteor but still not good ... simple {{ states('switch.rainbird_zone_1') }} shows off
but when put in the loop
{%- for i in [1,2,3,4,5,6,7] -%}
{{ states('switch.rainbird_zone_'+[i]|string) }},
{%- endfor %}.
i got unknown,unknown,unknown,unknown,unknown,unknown,unknown,
@fallow quarry that's because you are missing underscore
sic .. _ is being removed by discord
nono
in my script I do hev them 🙂
only here discord removes for some reason .. I do no know how to past code 🙂
*have not *hev
@fallow quarry 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
OMG so simple .. .
{%- for i in [1,2,3,4,5,6,7] -%}
{{ states('switch.rainbird_zone_' + [i] | string) }},
{%- endfor %}. ``` simple to paste it but still does not work 😦
@next ridge posted a code wall, it is moved here --> https://paste.ubuntu.com/p/P7ytXj99v3/
But im not suposed to calculate the slope and constant to put on that formula?
Ive been trying with this formula
https://paste.ubuntu.com/p/P7ytXj99v3/
But when i test i get 160% with wet and 60% at dry.....
I have a strange feeling that im making a mistake in terms of maths
My guess is that somehow im making mistakes when calculating the slope because the dry gives me 60% as you can see at following excel
but strangely the deviation remains 60% on the upper and lower thresholds so maybe just a simple -60% could do the trick
Still with no more ideias how to make the 4500 100% wet and 14500 0%
@thorny snow to return a number between 0% and 100% where 4500 is 100% and 14500 is 0%, do something like this:
{% set val = 14500 %}
{{ ((((val - 4500)/10000)-1)*100) | abs }}
@thorny snow to return a number between 0% and 100% where 4500 is 100% and 14500 is 0%, do something like this:
{% set val = 14500 %} {{ ((((val - 4500)/10000)-1)*100) | abs }}
@buoyant pine
You mean in this field
- platform: template
sensors:
Humidity_plant_percent:
unit_of_measurement: "%"
value_template: "{{ (170.967718 - states('sensor.your_sensor') | float * 0.3225806) | round(0) }}"
Sorry bad templating
better yet:
{% set val = 4500 %}
{{ ((((4500 - val) / 10000) + 1) * 100) }}
and yes, it would go in the value_template field
better yet:
{% set val = 4500 %} {{ ((((4500 - val)/10000)+1) * 100) }}
@buoyant pine
Sorry could you explain me better the calculation? Need to understand it to apply it to HA
the term val is my sensor.your_sensor
?
the difference between the highest and lowest values is 10000. to compare the values to a scale of 0 to 10000, you subtract the value from 4500. then you divide that value by 10000. you then add 1 to the value since the lowest value is supposed to be 100%. then you multiply by 100 to display it as 100%, 55%, etc.
Sorry im kind of newbie in this so making this "complicated" templates just go out of my knowledge
this is more math than it is templating
- platform: template
sensors:
Humidity_plant_percent:
unit_of_measurement: "%"
value_template: "{% set val = 4500 %}
{{ ((((4500 - sensor.yoursensor)/10000)+1) * 100) }}"
I am right?
you don't need the first line of my template if you're going to use sensor.yoursensor in the second line
the first line just defines a variable named val
well im going to copy this chat for future reference in case i make things crazy
play around with that template i gave you at developer tools > template with different values for val and you'll see how it works
- platform: template sensors: Humidity_plant_percent: unit_of_measurement: "%" value_template: "{{ ((((4500 - >sensor.yoursensor)/10000)+1) * 100) }}"
Thank you very much for your kind help @buoyant pine
you have two options:
value_template: >
{% set val = states('sensor.yoursensor') | float %}
{{ ((((4500 - val) / 10000) + 1) * 100) }}
or
value_template: "{{ ((((4500 - states('sensor.your_sensor') | float) / 10000) + 1) * 100) }}"
Could you explain the pros and cons of each? or same thing via different ways?
same thing via different ways. defining one or more variables can be nice if you're referencing multiple entities in the template
it can also make the template itself shorter and cleaner
I will use multiple esp's for the maryjanes greenhouse eheheh.
I have one 2ch dimmer for 2 extractors.
This one will read 6 soil probes and 1 dht22
Watering system is another ESP8266 with mcp23017 for multiple water valves.
So this calculation is the key that will drive the self watering system.
(still have to add nut's by hand) but is supposed that in near future 5 peristaltic pumps will add nut's as per my request. The ideia is to be a hassle free grow
Maybe this will read also a VEML6070
you have two options:
value_template: > {% set val = states('sensor.yoursensor') | float %} {{ ((((4500 - val) / 10000) + 1) * 100) }}
@buoyant pine
Humm now im stoped by HA itself
nvalid config for [sensor.template]: invalid slug Sonda_de_humidade_com_conversao_templated#1 (try sonda_de_humidade_com_conversao_templated_1) for dictionary value @ data['sensors']. Got OrderedDict([('Sonda_de_humidade_com_conversao_templated#1', OrderedDict([('unit_of_measurement', '%'), ('value_template', "{{ ((((4500 - states('sensor.growbox_soil_probes_dth22_ads1115_48_a0') | float) / 10000) + 1) * 100) }}")]))]). (See ?, line ?).
Can only use lowercase letters, underscores, and numbers in the sensor name
It provides a suggestion in the error message
So i have a guage card with a min/max value. Can i use a template to set a max value?
I've tried but can't seem to get the card to recognize the value that the template should return.
@thorny snow read the first sentence in the error message, it tells you what to do
@thorny snow read the first sentence in the error message, it tells you what to do
@buoyant pine I removed the # signal but same trouble
maybe too long name?
I'd like to do something like:
type: gauge
entity: sensor.nextcloud_system_mem_free
min: 0
max: {{states('sensor.nextcloud_system_mem_total') | int}}
unit: bytes
name: Nextcloud Free Memory
@thorny snow can't use capital letters either
@thorny snow can't use capital letters either
@buoyant pine This way im going to buy you dinner 🙂
Restarting the HA to see if the code will give the values I want
You can (should) test templates at developer tools > template
That way you can check if they work before adding to a template sensor and restarting
nvm. i just realized that templating isn't supported on built-in lovelace cards :/
is there a way i can figure out how long a sensor has been in its off state?
through a template?
i basically want to calculate a time delta for the time between whenever a sensor goes from on to on again
do i need a "variable template" just to store the previous time?
If you're using a state trigger, you can get it from the .last_changed value
Probably {{ trigger.from_state.last_changed }}
Never tried it though
i have a binary sensor.. so i want the time interval between each time this sensor goes into the "on" state
trigger is the sensor?
https://www.home-assistant.io/docs/automation/templating/
https://www.home-assistant.io/docs/configuration/templating/
{{ (states.binary_sensor.float_switch_top.state) }}
that shows "off"
.from_state outputs nothing
Look at the first link I just shared
yes, i see that.. but what is "trigger"? is that a hardcoded something?
The trigger data made is available during template rendering as the
triggervariable.
Yes...
so i can't access these variables through template editor?
No
https://www.home-assistant.io/docs/automation/templating/#available-trigger-data
The following tables show the available trigger data per platform.
You only get those in automations
but, if this is a binary sensor.. that is either off or on.. whenever the sensor goes into "on", wouldn't then .from_state then refer to when the state was in "off"?
i'm looking for the time delta between each "on"
Right, and that's what you'll get
If you have the previous state object then the .last_changed value is when it turned off
Aka the end of the previous on time
yes, but i'm looking for the start of the previous on time
That isn't what you'd initially asked
off -> on (when?) -> off -> on (when?)
is there a way i can figure out how long a sensor has been in its off state?
Yes, but now you'll have to resort to other logic
yeah, i asked because resorting to just using the off to on could potentially be good enough, since the sensor is in its on state for roughly the same time each time
i already have an automation that starts a pump whenever this binary sensor goes into on state.. would it make sense to add another action to this?
Sure, you could toggle a boolean, then you can track how long the boolean was on
sigh this is giving me a headache 🙂
what i want to end up with is a simply sensor called "pump_interval" that is the number of seconds between each pump run
the pump starts every time the binary sensor binary_sensor.float_switch_top goes into the on state AND the binary_sensor.float_switch_bottom is in on state
and then the pump stops when the float_switch_bottom goes into off state
so i need to know the time delta between each on to see if the intervals are increasing or decreasing
how would you go about solving that?
Toggle a boolean
but i need a sensor that is the number of seconds
because i want to graph the change in intervals
ah, sorry..
Automation runs
Checks how many seconds the boolean has been in the current state
Stores that somewhere (input_number?)
Toggles it
Turns on the pump
Or some other thing, this ain't hard, and I'm done...
why would you use input_number for this? the documentation says that this is for defining values that can be controlled via the frontend.. isn't it better to use a simple numeric sensor?
but i need a sensor that is the number of seconds
input_number looks like it's meant to be used as input for automations.. and something that is intended to be changed by the user
Tell you what, since you want to argue, I'm out
i'm trying to understand. i'm not here to argue.
You can set the value of an input_number, which might be what he’s suggesting you do. Every time the entity turns on, set the value of the input_number to the current time minus the last updated time of the input_number.
@inland hazel the logic makes sense, but i don't understand why i should use an input_number for this instead of a sensor?
You can't update a sensor
from what i'm reading input_number seems to be something that's to be used for "input".. meaning something that the user should manipulate directly through the frontend
You can update those any way you want
You cannot set the value of a sensor.
Not a single one of my input_x entities are updated by humans
In this case, you’re using “input number” as a variable.
(Research my historical configurations...I do it a lot)
oh? but i'm able to update any sensor through developer-tools/state .. but this is not the same?
(And those were updated last around Nov 2017)
Not the same
No, it is not the same.
ok, so h-a can't update the state of sensors through automations? developer-tools is kind of a backdoor into the states?
You can set the value of any entity via the REST API, but in this situation I do not recommend doing just that.
Or, look at it this way, look in
-> Services - find the service that updates the sensor 😉
Dev tools is basically allowing you to mess with HA's "memory" directly
You can tell it that reality is not what it though, for testing
ah, ok.. thanks for the clarification 🙂
Sensors are intended to be read-only.
then input_number makes more sense
but they need to be defined beforehand in configuration.yaml, right?
In this use case, input number is what makes most sense to me.
And yes they do, but you can reload that
is there a list of the "valid" unit_of_measurement that can be used?
"seconds"? is that a valid unit_of_measurement?
So is banana
hehe
The only other thing I would think to use is a SQL sensor, but that would entail a lot more than updating an input number each time it’s turned on.
You can use anything, it's used for graphing
yeah, but it seems like some units triggers some special meaning.
Well, when linked with a device_class
Some units do, but that’s based on the front end.
is there a list of those units somewhere?
Which units?
those "Some units" that @inland hazel mentioned
unit_of_measurement @arctic sorrel
🤣
They are defined in the source code.
Other than for graphing, where it purely cares that it's set, I've never noticed the frontend care 🤷
@arctic sorrel you’re better at HassBot than I am, so I’ll leave this one to you.
Eh, I don't remember all the magic incantations
I did have a sensor on a test install that had bananas as the unit of measurement, graphed that just fine 😄
@arctic sorrel There are a few times where C/F come into play and get overridden.
Yeah, but I think that's the back end trying to be "smart"
haha
the pump is operated using a neo coolcam power plug.. this already has an entity called "interval" :p
guess what that does.... :p
btw., what is the exporting entity for z-wave devices? what does that do?
#zwave-archived would be a good place to ask 😉
Hi, I have made a template sensor to keep track of the sun hours per day, the sensor is switching status as it should, but when I try to use the history_stats component to list the ammount of hours I get into issues, it seems like the template sensor is not part of the history. How do I make sure it/they are added to the history? I have restarted HA a few times already.
this is the code for the sensor:
# Sun counter binary sensor
- platform: template
sensors:
sunny:
friendly_name: "Sunny"
value_template: >-
{{is_state('weather.lovkulla', 'sunny')
and is_state('sun.sun', 'above_horizon')}}
This is the code for the history_stats:
# History stats for sun
- platform: history_stats
name: Sun last 48h
entity_id: binary_sensor.sunny
state: 'true'
type: time
end: '{{ now().replace(hour=0, minute=0, second=0) }}'
duration:
hours: 48
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
Check and see if the entity is showing history in the more info popup
Ah, it says "this entity does not have any unique ID, therefore it can not be handles from the UI", or similar (translated by me), so how do I add that... need to search...
You can still use it - you still customize it, just not change the entity_id
You can still use it - you still customize it, just not change the
entity_id
@arctic sorrel can you please explain, I have found it using the "states" panel under "developer tools", but I cant find the arrow to change the ID, I did find thou that it is not true/false it "on/off" as it seems...
Yeah, but that gives me the same error, "no ID, cant handle in the UI"
Doing what... I have zero issues changing the icon/device class/etc of any entity
Sorry for the links, I cant upload screenshots here it seems....
But I have solved it using the the correct states, it should have been "on" or "off" instead of "true" or "false"
Looking at the docs for the cover template. In the beginning it states that the open_cover and close_cover are scripts that are run when the cover is opened/closed. Later on they give an example with a switch.garage_door and implies that the switch is controlling the garage (at least, that's how I understood it). So is open_cover or close_cover something that happens when the cover is moved or something that moves the cover?
Moves the cover
Good, that makes more sense.
Am I crazy in how it was written early on makes it a bit confusing?
It's what happens when devs write stuff, and/or their native language isn't English
The wording is technically correct, if unhelpfully misleading
I have enough trouble with English and it is my native language.
As a discussion I was having with somebody else today went - and which version of English do you mean 😉
Not just which country, but which part of it, 'cos when I'm full on local dialect my London colleagues can't work out a damn thing I'm saying 😄
Yeah, I moved from the UK to the US when I was younger and had to learn "US" English 😉
I asked a classmate for a rubber, got a funny look 😄
I had a colleague I worked with for a while, and we wrote a Scots <> Canadian translation guide
I'm in Germany now and most Germans have a near impossible time understanding Scottish (or Irish for that matter) acents.
Hell, I can't understand it half the time
Most Scots struggle with another Scot from any distance away 😉
It's ... an odd set of dialects and accents
So, if I make a Github account can I suggest an edit to help my fellow noobs understand cover templates? Or how does the edit process normally work?
Pretty much
Top right of the page Edit this page and submit a PR with your proposed clarification
There's a template you get for the PR to help ensure you've followed the documentation standards, are using the right branch, etc etc
...correct version of English.
at least you didn't ask for a Handy
First week in Germany we went to the supermarket and asked for 500g of "Kinderhackfleisch" 🤦♂️
Rinderhackfleisch = Ground beef. Kinderhackfleisch means ground children
Close...
Well did you want ground beef or ground children?
Well did you want ground beef or ground children?
@buoyant pine Ask me after the lockdown 😉
😱
OK, made my first PR.
I want to use a fan template to control my AC, is there any way to block controls of the fan device as long as the device is turned off?
Hi team. Can someone tell me why my code is throwing render error.
{% set date_now = strptime(now().strftime("%Y-%m-%d 00:00:00"),'%Y-%m-%d %H:%M:%S').timestamp() %}
{% set date_last = as_timestamp(state_attr('automation.notify_arrival_m','last_triggered')) %}
{{ date_now > date_last }}
{% set date_now = strptime(now().strftime("%Y-%m-%d 00:00:00"),'%Y-%m-%d %H:%M:%S').timestamp() %}
{% set date_last = as_timestamp(state_attr('automation.notify_arrival_m','last_triggered')) %}
{{ date_now > date_last }}
Got it I had the wrong automation name
Need a little help with this template. Not sure why its not working
{% for x in range(24) %}
{{ state_attr('sensor.axpert_power_output', x) }}
{% endfor %}
it loops through but returns None 24 times but if i put {{ state_attr('sensor.axpert_power_output', '17') }} it returns the correct value
ignore that. |string fixed it
My final goal was to sum all 24 attributes as a value_template for another sensor. For the life of me Im just not getting it right
probably hitting namespacing issues
test code for your reference:
{{ ns.sum }}
{%- for x in range(4) -%}
{%- set ns.sum = ns.sum + x -%}
{% endfor %}
{{ ns.sum }}```
that did the job!! thanks
where are you trying to use this template?
template sensor
ok, just as a heads up, it won't auto-update
@serene merlin 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
would a binary sensor from template be set to on if the template returns "True"?
or, to ask another way, what is the correct way of setting a binary sensor to on/off based on other binary sensors?
i've used is_state('binary_sensor.something', 'on')
Rinderhackfleisch = Ground beef. Kinderhackfleisch means ground children
@sinful ridge hahaha living in Austria myself and I can confirm knowing zero German I have had countless misunderstanding of the same kinder
hehe
Hello
How can I write a sensor that stores the last known values/attributes of another sensor?
This is my original sensor:
- platform: command_line
name: Face Veranda 2
json_attributes:
- Faccia1
- Faccia2...
command: 'python C:\GoogleHome\Python\CameraFaceDetection.py Veranda2 rtsp://admin:xxxxxx@192.168.1.12:14000/tcp/av0_0'
value_template: '{{ value_json.Stato }}'
scan_interval: 10
command_timeout: 120
@lunar osprey 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
Please format your code so that it's fully readable
@lunar osprey ☝️ Please edit your post and format your code
done
Any idea why this doesnt trigger a template sensor? {{ states.person | selectattr('state','eq','home') | list | count > 0 }}
but if no person is home and then anyone arrives home surely it should trigger?
does it have to reference a specific entity and not just the domain
Specify an entity that forces an update, or re-write the template to specify entities
https://www.home-assistant.io/integrations/time_date is a cheat option, to force an update once a minute
Using, say, a group of the entities would force it to update on first arrival/last departure
I was hoping to get a dynamic list of entities so that I dont need to change it
Then templates would be processed every second
That would be a performance nightmare
Depending on your goal, the time_date option may work
ok back to the old manual way of adding entities i guess
Or that...
Depending on your goal, the
time_dateoption may work
@arctic sorrel how now? I have the date sensor but how does that tie into the template?
Read what it says there 😉
If you have a sensor that updates every... minute, then the template will update every ... minute
so something like {{ states.person | selectattr('state','eq','home') | list | count > 0 or states('sensor.date') == '' }} as sensor.date will never = ''
i just figured it out lol
so pretty much
entity_id: sensor.date
value_template: "{{ states.person | selectattr('state','eq','home') | list | count > 0 }}"
Yup, except that sensor updates once a day 😉
oh fook
i will use my sensor.uptime then. that updates every minute
I have my moments when i shine. this wasnt one of them
It's easy to get lost in the details
just a gradule glow
if an entity has many different states you cant specify say only 3 to listen for in a state trigger? you would have to use a template trigger right
Or a template condition and a state trigger
State triggers don't need to or from 😉
Im currently monitoring a weather entity but only want to action on 3 states. without to or from it will trigger on any change including attributes. was wondering if this would be the better way of doing it or just a template
Template trigger is an option, I'm just saying there's more than one way to solve it
Im sometimes pedantic on being efficient. prefer minimum code and load on server
template does seem the better way in this case
I suspect it's not very different in this case
It'd be interesting to run tests and find out though
Is there a way to fallback to an empty string in case of an UndefinedError? jinja's default() didnt work for {{ trigger.to_state.attributes.friendly_name }} (looked like this, but didnt work: {{ trigger.to_state.attributes.friendly_name|default("") }})
Don't trigger manually?
Yeah, but wanted to make sure it always works. Got it working btw:
{% if trigger %}
{{ trigger.blabla }}
{% endif %}
You can't use the trigger object of there is no trigger
Hello everybody. Is it possible to use the combination of the status from more than one entitiy to get a status on a card in lovelace? I got the hint to the template from the #frontend-archived channel. Does anyone have a card like this working?
I am already working through the template help site.
but i do not know anything about templates. so i thought if there's anyone who had this problem in the past.
Without knowing what you're wanting to do ... nobody can help you
We don't know what you want to do
How can we help you if you don't tell us exactly what you want?
Hm. Sorry.
I installed a 4 channel relais in my network which is controlling our house ventilation. Status 0 to 3 for different ventilation strength. I got 4 switches in home assistant from the relais. For setting the ventilation on strength 2 for exmaple , the switches 1 has to be on, all other 3 off. For the ventilation strength 1, the switches 1 and 3 have to be on, 2 on and 4 off. So for each ventilation step there is an other combination ob witches on and off.
All i want to have in lovelace is a card with 4 Switches. Ventilation Step 0 to 3. Behing every step, there must be a combination of the sates of the 4 switches from the relais
Ok, that actually doesn't sounds like a status thing
Is this understandable? 😄
That sounds like some automations
You'd have an input select or input number to select the speed, and an automation to control the relays
You're not after displaying a status after all
my wish would be to see the status of the ventilation.
but it would be enough to see which lever is active
Do you have the relays in HA already?
I would think 4 binary template sensors reading the states of your relays would be fine. then on the frontend add 4 buttons with the binary sensor as the entities
Yes, i have switch.sonoff_10009f091d_1 to switch.sonoff_10009f091d_4
An input select for off through full speed, automation to toggle things, and then a glance card to display the state
Okay, i'll have a look into binary template sensors. Uff
Depends on what you really want
A display showing the mode (template sensor)
A control (see above)
A display showing the state of each switch (just cards)
I already have the last one (A display showing the state of each switch (just cards)) but thats only the switch position of the relais, not the "resulting heating level"
is each level a combination of 2 relays?
Then you want a single template sensor
It's basically a set of if statements
{% if is_state('switch.sonoff_10009f091d_1','on') and is_state('switch.sonoff_10009f091d_2','on') and ... %}
Full power!
{% elif is_state('switch.sonoff_10009f091d_1'...
Okay, let me see what i can make 🙂
when i create atemplate sensor, can i create card to get the status from it?
Ah got it.
Pretty much everything is an entity - if it isn't it's a service
only thing i would change is {% to {%- to remove line break in case you use the value in a notification
hey does anybody know how to add an offset to
{{ now() }}
so that it will always return 5 hours earlier than the actual time?
probably something like {{ now() - now().timedelta(hours=5) }}
not sure it will let you do the - operation, but if it does, that should do it
or you might try the timedelta on it's own
it is saying 'datetime.datetime object' has no attribute 'timedelta'
Well, now is supposed to be a datetime object for python, and pythin 3 has a timedelta on it's datetime object, so maybe it's an old integration
you can look for how to do it on a python timedate object it should give you the answer
ok thanks
Here's a good answer : https://stackoverflow.com/questions/14043934/python-time-offset
i just realized this works
{{ (as_timestamp(now()) - (5*3600)) }}
i can just convert my sensor over to using timestamps instead of formatted time
nah that won't work either. damn i may give up on this. starting to think what i want to do is not possible the way I'm trying to do it
you can always turn that timestamp into a real number
i realized i was going about it all wrong in the first place
also, it's easier to just use : now().timestamp()
im trying to make a tracker that tells me how much time i'm spending on my computer and i was trying to use history_stats. but that integration relies on relative time only so i can't make one that can track for one day but start/stop at 5am instead of midnight.
(without changing my timezone)
so i'm just gonna use an input number and a series of automations and sensors
Ah, yeah, that sounds complicated... Good luck tho
haha a lot of effort for basically no benefit at all. story of my HA life
We all do that at times, it's part of the fun, I spent like two hours today making an automation for my bedroom lights on HA that i've had working on the HUE bridge for months
oh yeah ive spent days redoing stuff that was already working lol
do what now?
It was written poorly
I figured out the required string manipulation and got the desired output
in the future, share the whole thing if you need help
Hi, any idea why this code seems to work when checking in template tool but not when I add it in the config and reboot?
# Sun counter binary sensor
- platform: template
sensors:
sunny:
friendly_name: "Sunny"
value_template: >-
{{is_state('weather.lovkulla','sunny')
or is_state('weather.lovkulla','partlycloudy')
and is_state('sun.sun', 'above_horizon')}}
Did you run a config check?
Yes
No issues
It works it just gives me a "false" result, while in the template tool it gives me a "true"
I guess the logic could be questioned, I want the first "or" part to run first and then check for the "and" state, maybe that is not correct way to formulate my code
Priority ordering may be the problem, maybe you need some brackets so that it's clear what you mean
Like this?
# Sun counter binary sensor
- platform: template
sensors:
sunny:
friendly_name: "Sunny"
value_template: >-
{{(is_state('weather.lovkulla','sunny')
or is_state('weather.lovkulla','partlycloudy'))
and is_state('sun.sun', 'above_horizon')}}
Would epic if that would be that simple...
If that's what you're looking for, yes 🤞
But still weird that it shows one result in the template tool and a different one when integrated into configuration.yaml
It is...
Well that code above now gives me a "false" in template tool, lol, but that is change so one step forward I guess...
simplify in your testing. {{ True or (True and False) }}
that's True
is from_state available in a template sensor or only in automation
Automation only
I want to buy a sonoff mini for behind my wall switch. I already have smart lights everywhere. Is there a possibility to create a light template so when i turn on a light, the sonoff mini goes on and i can change the light brightness etc?
With the sonoff the power is switched so otherwise i can't turn on my light
How does one get rid of the milli/micro seconds from a timedelta object?
How does one get rid of the milli/micro seconds from a timedelta object?
Figured it out. Need to do.replace(microsecond=0)on both datetime objects before the calculation
Having a media_player.universal manual entity, how can I provide custom source_list for it?
https://hastebin.com/rivetukuxo.yaml
i'm doing this way and it's not working
- Invalid config for [media_player.universal]: value should be a string for dictionary value @ data['attributes']['source_list']. Got ['INPUT 1', 'INPUT 2', 'INPUT 3', 'INPUT 4', 'INPUT 5', 'INPUT 6', 'INPUT 7', 'INPUT 8', 'INPUT 9', 'INPUT 0']. (See ?, line ?).
@ornate pecan it has to be an entity ID and its attribute separated by a pipe (|)
From the example:
source_list: media_player.receiver|source_list
@buoyant pine the thing is this is a manual media player and I want to provide custom source list that does not exist in other place
but i already managed to do it via input_select|options
Right, I was just explaining the syntax that the docs state
I've read a lot that starting with 0.108.x there's a {{ user }} for templating which holds the current users name. I'm on 0.108.9 and the variable is empty for me. Does anyone know how I can access the name of the current user?
oooh, thanks for the clarification
No worries
Getting more into using templates and I am looking to get the previous state of an input select... I have looked into this and found 3 ways this is commonly approached. 1) Templates getting the from_state of a template sensor; 2) HACS Variable to store a value as a history and recall the variable; 3) Appdaemon. I would love some input on achieving the ability to have a pop-up on an input select, “yes” completes the action and “no” returns the input to the previous value. If anyone has any input on how to best go about this and perhaps some example code of an automation calling the from_state of an input select or sensor. Or is this something another plug in does natively?
In an automation, you can do that with {{ trigger.from_state... }}
This will work with the input select directly or still need the template sensor to record the history?
https://www.home-assistant.io/docs/automation/templating/
https://www.home-assistant.io/docs/configuration/templating/
It works with any entity - see the first link
So perhaps I am missing something in that document as I have read it and several others from HA. I can’t seem to find an example of exactly what we are trying to do. Below is some of my code from the automation but for the life of me I’m not wrapping my head around the format or one of the keywords.
action:
- data_template:
option: "{{ trigger.from_state.state }}"
entity_id: input_select.tv
service: input_select.select_option
Ok, so that selects the previous state when run in an automation
Gotcha! And this automation can be triggered by the “no” button. It does not have to have a trigger?
It needs to have a trigger - the entity in question changing
Otherwise, there's no state object for it to work with
Gotcha! That may have been my issue then and not the template! Thanks for the input!
AAAARGGGHH! Trying to round a simple number - please someone put me out my misery! What stupid thing am I doing?? This works fine in the template editor, but does nothing in the sensor card configuration
I need some help with my templates. I want to create a for loop that find all my calendar.rolfberkenbosch items. If i look into the Dev Tools -> States. I see only 1 event. But when I search in the SQL lite database of home assistant I find more (sqlite> select * from states where entity_id LIKE 'calendar.rolfberkenbosch';). Can anybody help me with this ?
Just returns: Expected a value of type undefined for value_template but received {"[object Object]":null}.
The sensor card doesn't support templates 🤔
You're right though, for templates you need that, but the card docs shows nothing about templates 🤷
yea i dont do fancy ui stuff
template sensor then display that one instead?
^^^^^
@velvet glen 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.
Ok so to have a sensor card with a rounded number (ie not displaying 20.6253745648563475475455C ), then best route is to just recreate the whole card as a custom card and this'll let me round it? (I thought templates could be applied to all cards, but obviously not!)
@velvet glen they're saying make a template sensor
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)
has anyone set up homeassistant supervisor on unraid?
Can i access the area of a sensor from a template?
@stark palm #330944238910963714
@verbal bramble I haven't tried that. Might be able to dig around in the state object to see what's available
The last time I poked, it looked like areas contain entities, rather than entities being linked to areas
The last time I poked, it looked like areas contain entities, rather than entities being linked to areas
@arctic sorrel is there a way to access areas from a template and figure it out?
Probably
I'm making changes to my sensors.yaml file and trying to test. Should I be reloading core? or do i have to restart hass (from file editor) for changes to take affect.
restart "hass"
Always run the configuration check command when you make changes. Don't trust the UI check - it misses some problems.
great, thanks
Probably
@arctic sorrel any hints? I have all my sensors sorted by area and it seems redudant to have to put the area name also in the device name just to access its location in a template
If I had anything detailed I'd have shared it - I'm afraid I've had zero interest myself so don't know
No prob. I'd be suprised if this couldn't be done as it seems like an obvious use case
Anyone know of a way to filter out entity_ids from a domain that start with a given string? For instance all lights that match light.room__%
{% for state in states.light if 'room_' in state.entity_id %}
{{ state.entity_id }}
{% endfor %}
better yet:
{% for state in states.light if state.object_id.startswith('room_') %}
{{ state.entity_id }}
{% endfor %}
That seems to do the job. Is there no way to apply some type of filter instead of looping through each item?
there's a |reject() filter but its just doing a loop in the backend
reject() doesnt seem to have a test that can match with wildcards or a startswith
reject("in", "thing")
its the wildcard thats the problem.
I tried selectattr('object_id','in','room*') but didnt work
without the * it only returns the light if the object_id = 'room' and not any object_id that starts with room
with the * it returns nothing 😩
looks like it won't work that way as you need to be a level deeper in the lookup
because this works:
{{ l1|reject("in", "1-thing")|list }}```
['2-other-thing', '3-foo']
so need to be in a loop
a loop will have to do then. Thanks
i wanted to get the "state" value from the sensor.latest_vesion but im not being able to get just the state. i tried many templates such as {{state_attr('sensor.latest_version', 'state')}} but i am not being able to get the value
any clue?
states('sensor.latest_version') should be enough
@dreamy sinew i tried that,but it doesn't return the state value
i am testing it in the templates section
okay, scratch that
my bad
Go to the states page and look at the attributes
I am trying to have an automation reference the last state that an input select is in... I had this working on it's own, but adding complexity seems to have broken the chain... Anyone have any ideas on why the trigger.from_last.state would not work properly under these circumstances?
- alias: Previous State Recall
description: ''
trigger:
- entity_id: input_boolean.popup_no_display_boolean
platform: state
to: 'on'
condition: []
action:
- data_template:
option: '{{ trigger.from_state.state }}'
entity_id: input_select.display_1
service: input_select.select_option
- delay: 00:00:03
- data: {}
entity_id: input_boolean.popup_no_display_boolean
service: input_boolean.turn_off
Because the trigger is the toggling of the input Boolean
The automation cannot be triggered by the input boolean being turned on and then reset it to off?
It will trigger by that toggle but the trigger entity will be that bool not the select
Sorry if we are misunderstanding... I am trying to trigger the last state of an input select when another automation chanes the input boolean to "on".
Is there a way to work here without the group and specify some entities?
{% set open_windows = states | selectattr('entity_id','in', state_attr('group.fenster_alle','entity_id')) | selectattr('state','eq','on') | map(attribute='name') | list %}
That is not possible here as you are not triggering an automation based on that change
@humble beacon Please use https://paste.ubuntu.com/ or https://www.hastebin.com/ to share code or logs.
Share the whole thing
@dreamy sinew https://paste.ubuntu.com/p/s3y9hwtZhd/
Ok, what are you trying to do?
I want to remove the group and specify entities.
And do you still want the open check?
Yes
It's possible but the group would be a bit easier
Can you tell me how?
I'm on mobile, kindof a pain to work out
Thought that pulling together the code would help explain my situation. It is a complex scenario for me personally and all of my steps are pulled from HA resources and forum posts. Not sure if this is the best way to go about it. Suggestions welcome. (will send beer) 🍻
https://hastebin.com/wahusatogi.http
So I have a odd dimmer that supports MQTT but it only will post a single value of 1 through 127 for britness I made a template that i can turn it on and off but how would i add dimmin support
there is no seperate britness value
https://www.home-assistant.io/integrations/light.mqtt is what you're using?
Which of the three schemas?
I tryed britness however the format the dimmer outputs is just a value of say 0 of off or 127 for full brite so the mqtt value is (topic)=127 no other values
I made the template i got now but its eather full on or off and the dimmer slider wont adjust the value at all
~images @upbeat iron
@upbeat iron Please use imgur or other image sharing web sites, and share the link here.
Please use https://paste.ubuntu.com/ or https://www.hastebin.com/ to share code or logs.
Show us what you've done
ok
You can "simply" apply some maths to the value to adjust it to cover 0 to 255
your topics 🤔
your actual config would have been handy, rather than something made up 😉
I used auto discovery for the others
If that is your actual config, it's very wrong
oh my full yamal?
So, show us the actual light config
I must be confused m8t im sorry
oh
Not even in the same continent as valid
one sec
The device only understands a value of 0-127 the other info is completly innored from what the dev told me
So... brightness scale 😉
And you can use the state value to have 0 being off and not zero being on
is basicaly what i was trying to use last time i attempted this
It turns on and off fine and if i manualy push a command to change the = to a valuse of say 50 it dimms
Those topics are still wrong 😉
state_topic: "REC/HA-Utility-Room-Switch"
``` is more likely to be right
I dont realy understand MQTT yet im super new to this
I'm also not sure what
brightness_state_topic: "/REC/HA-Utility-Room-Switch/brightness"
brightness_command_topic: "/REC/HA-Utility-Room-Switch/brightness2"
```is doing for you
Given that you said it doesn't have those 🤷
it dont do anything rn i think
The state and command topic will be the main topic, and you'll need the scale I linked to
I was told i should use it by some on on a nother discord but what it does is nuthing i can tell
Of course, anything other than 127 is neither on nor off, so ... not sure how that's gonna work
You may want to junk it and get something that's vaguely standard 😛
I tryed setting the britness to the same topic as the on off value but the slider goes gray
and only reflect the current on or off value and i cant slide it to adjust it
if i manualy change it it does move tho
its like somthing in HA dont like having the same topic for on off and britness
< is so overwelmed lol
I ended up removeing it thats why the topics went set in the first post
Im adding the other devices first then going to restab it when im done getting all the autodiscovery stuff working
I get overwelmed easly (part of my mental state) so i step back and take nibbles at it
Im tryging to decode a json respons from a automation trigger.event.data
but when im trying this i get an error:
'{{ trigger.event.data | value_json.args[0].degrees }}'
when just using trigger.event.data i get the full json respons
In jinja templates | is a pipe. So you're trying to run the results of trigger.event.data through the function value_json.args[0].degrees - which doesn't exist.
That's why it fails. It's trying to find a function with that name, but function names can't contain [, thus the syntax error.
I don't know what the data looks like, but maybe trigger.event.data.args[0].degrees?
Hey all. So heres an interesting thing. In template editor this works 100% but when I put it into a template sensor it give me an error
{{ states.group.tracked_things|expand|selectattr('state','eq','home')|list|count }}
Error as follows:
Invalid config for [sensor.template]: invalid template (TemplateAssertionError: no filter named 'expand') for dictionary value @ data['sensors']['tracked_things']['value_template']. Got "{{ states.group.tracked_things|expand|selectattr('state','eq','home')|list|count }}". (See ?, line ?)
what's the error
What's the full sensor too...
value_template: "{{ states.group.tracked_things|expand|selectattr('state','eq','home')|list|count }}"
That sensor will almost never update
I initially tried to have a sensor from person.xxx but HA had an issue with that
Your sensor will update when group.tracked_things changes state
Other than it not updating it just doesnt work
That can be fixed in other ways. The problem is that expand isn't a thing.
For some reason.
{{ dict((states|selectattr('entity_id', 'in', state_attr('group.tracked_things', 'entity_id'))|list)|groupby('state'))['on']|length }}
``` is from one of mine
(quickly hacked, brackets may be off)
I dont need the sensor actually. I just wanted the count for the frontend to change the icon but HA didnt like that hence me making the sensor
I wanted this icon_template: "mdi:numeric-{{ states('sensor.tracked_things') }}-box-outline"
value_template: "{{ dict((states|selectattr('entity_id', 'in', state_attr('group.tracked_things', 'entity_id'))|list)|groupby('state'))['home']|count }}"
``` should give you something similar
The problem still is that it won't update until the state of the group changes
Yay no errors
You'd need to set https://www.home-assistant.io/integrations/template#entity_id
You'd need to set https://www.home-assistant.io/integrations/template#entity_id
I remember this from the last convo
Thanks
Somebody else wrote the templates above, I just use them without fully understanding the magic 😂
And here I thought you were a wizard of sorts
I'm lazy, it works, that's enough for me until I need to change it
if you are getting json - you could probably store the Key-value pair from {% set keyvalue = ( trigger.event.data | from_json) %}
was responding to earlier comments - somehow my feeds are being delayed
yeah, discord does that sometimes
Hello everyone. I would like to use the output of a shell script in a template. The output is text, not a value. I tried creating a command_line sensor but I only want the script to be executed when the template is actually to be used. Any ideas how to do this?
Could somebody point out what is wrong with this:
service: climate.set_preset_mode data: entity_id: climate.thermostaat preset_mode: > {% if states('sensor.people_home') | int == 0 %} away {% else %} Winter {% endif %}
the error: Preset mode '{% if states('sensor.people_home') | int == 0 %} away {% else %} Winter {% endif %} ' not available
Rule 1 of templating
being?
thanks man
data_template:
preset_mode: |
{{ 'away' if states('sensor.people_home') | int == 0 else 'Winter' }}
entity_id: climate.thermostaat
service: climate.set_preset_mode
Other than IF/THENs.. what's the best way to assign the text based on value with this sort of data? An array?
Is there a more elegant way to do this?
{%- set eventlist = {
'1':'No events',
'2':'High line voltage',
'3':'Brownout',
'4':'Loss of mains power',
'5':'Small temporary power drop',
'6':'Large temporary power drop',
'7':'Small spike',
'8':'Large spike',
'9':'UPS self test',
'10':'Excessive input voltage fluctuation' } %}
{{ eventlist[value] }}
in this scenario, can I reuse "eventlist" (since i am going to copy and paste this all over now) or is it global for some reason?
Array is probably the easiest
Is this fine at the end there? {{ eventlist[value] | "Unknown" }}
neverminsd, I can test derp
Might be able to do eventlist.get(value, 'Unknown')
nice!
You're killin it today
... and again, it doesn't hurt to reuse "eventlist" since it's instantiated each template?
awesome, thanks!
hey folks, is it possible to put a !secret into a value_template or say a url. examples:
url: "http://" + '!secret base_ip + "/api/location"
AND
value_template: "{{ is_state('!secret device', 'on') }}"
No, but you can put the entire URL and value template in secrets
booo - that would mean 15 different secrets :(
i'm trying to create a package and pull from one common value
the IP of the host
is there another way to do that by any chance?
it will be used by more than just me, so trying to enable a user to just specify the IP and then re-use it
I mean if you're really open to anything you can write a script in any programming language that generates and saves yaml to a spot home assistant will read it from but that's quite advanced and will just lead to more problems
thanks for the reply @candid valve its for a theme, and there was a glimpse of hope that it could be relatively simple to install with 3 steps.
!secret was basically a way for me to easily use a global value in the package
nvm
Is there an easy way to trigger an update for a template sensor that is waiting for a attribute change in a group?
Depends on the template, but typically you'd have to define an entity that updates regularly enough, such as using a time sensor
So the template is for gathering problematic plants and it has set entity_id: group.all_plants. But after an update/restart etc. the sensor always displays "unknown" till something happens. Is there no "manual" way? Updating it all the time is unnecessary
homeassistant.update_entity may work
That's a service call
However, it sounds like the way you've prepared the sensor means it's just going to rarely update without help
I'm trying to create a template (i think) that shows when a speedteest was last run, using the speedtest integration, can anyone point me in the right direction please?
Hello 🙂 I got this simple sensor setup:
- platform: template
sensors:
ftx_power:
friendly_name: FTX power usage
unit_of_measurement: "W"
value_template: "{{ float(state_attr('switch.sonoff_10007ca1b5', 'power')) }}"
Is there any way to also calculate kWh into this sensor?
You could define that as an attribute - https://www.home-assistant.io/integrations/template#attribute_templates
Yeah but how? Isn't there some calculation that needs to be done?
You'd have to divide by (1000 x hours)
https://www.home-assistant.io/integrations/utility_meter/ might be better suited to what you're after
hm..... Okey. Looks promising. Because my Sonoff Pow R2 only gives me Watt in realtime.
But isn't that utility meter for when you have accumulated kWh?
I don't get it. I've got a template sensor which work fine in the Dev tools but always display unknown in the Front end:
{%- if is_state('group.all_plants', 'ok') -%}
Good
{%- elif is_state('group.all_plants', 'problem') -%}
{%- set problems = namespace(plants = '') -%}
{%- for plant_id in state_attr('group.all_plants','entity_id') -%}
{%- if is_state(plant_id, 'problem') -%}
{%- set problems.plants = problems.plants ~ state_attr(plant_id, 'friendly_name') ~ ': ' ~ state_attr(plant_id, 'problem') ~ ', ' -%}
{%- endif -%}
{%- endfor -%}
{{ problems.plants | regex_replace(', $','') }}
{%- else -%}
Unknown
{%- endif %}
It'll only update when group.all_plants changes state
how the F did u see that so fast?
@arctic sorrel Even if I have removed #entity_id: group.all_plants?
Hm, makes sense. So I can change the entity_id from the sensor to something better. Is there an easy was to have it changed if any of the sensors of any of the plants changes?
Sure, list them all 😉
or, as I said before, use https://www.home-assistant.io/integrations/time_date in the entity_id: line so it updates once a minute
Ok ok, you convinced me. Something inside of me wants to manage these things not through time but through events. But listing 20 sensors is stupid too.
There's elegant, and then there's elegant but time consuming
You sound like my supervisor.
Call it... experience
Sometimes elegance is the right solution, sometimes hitting it with a hammer until it works is
Sometimes finding somebody else to solve it is the right solution 😛
I guess you're right :(
I added sensor.time (works in the state view) and changed my config:
plants_detail:
friendly_name: "Pflanzen Detail"
entity_id: sensor.time
value_template: >
{%- if is_state('group.all_plants', 'ok') -%}
Good
[etc]
It still displays unknown 😦
Uh, it works... It just took like 5 minutes after restart to change. Better late than never
What are you doing with your plants?
Does anyone know if a value template can be used for a friendly name of a template sensor?
Docs don't show that, so I'd say no
Hey guys has anyone got any idea of a "how to do templates with no prior knowledge at all?"
I tried to look into learning templating yesterday but it's all just gobbledegook to me. I was very tired though.
What I'm trying to learn to do is make a cheap smart bulb that doesn't have transition capabilities gain said ability from a script or automation maybe, so my bedroom light turns down over a period of say 15 minutes when I call it though my bedtime power off automation.
The trouble i had yesterday was using data_template: in the UI, it didn't like it for some reason. I was trying to call a script i found that lowers the level by X from current value.
I'm assuming this means I'm going to have to try editing the automations.yaml to do anything.
This is what I was trying to call in the services part of the dev tool
data_template:
brightness: '{{states.light.light_name.attributes.brightness + 10}}
You probably want brightness_step from https://www.home-assistant.io/integrations/light 😉
Actually I changed it to - 30. I tried removing the attributes part. It kept saying that it was expecting an int
@arctic sorrel what I'm looking for is a way to loop something like that until the light is off. I was thinking of dropping it 10/255 every 30 seconds
Sure, but you don't need templates for that
There's services for stepping the light brightness up and down 😉
So I just stick that in a script with delays in the middle?
Rather than the template, yes
Ok thanks I'll look into that. It was kind of half a project that needed doing and half a project to learn templates though. Know what I mean? I was looking for some kind of noob proof templating guide
I use an app called Tasker to automate my Tuya bulbs on my phone through IFTTT. Smart Life just notified me that they're taking away IFTTT support
https://www.home-assistant.io/cookbook/dim_and_brighten_lights/ is the "old school" way
Do I was going to try to learn how to do everything on my pi instead
So do I, I just copied what I was putting in IFTTT and it worked
But my Tasker script is a bit crap, you can see the brightness lowering in steps. I was looking at how to put brightness setting in the webhook but got lost
Don't 😉
Have Tasker trigger an automation, have the automation do the magic
At most, pass data about how far you want it dimmed, in the JSON
I've seen that last link before. I'll have a go at doing something similar when I get to sit down at my pc
https://github.com/DubhAd/Home-AssistantConfig/blob/master/automation/people/tasker_hook.yaml is my slightly overkill way
Thanks for these
Nice, I'll have a dig in there
I'm sending
{"action":"call_service","service":"light.turn_on", "entity_id":"light.740660434c11ae14c791"}
ATM and have no idea why it works lol
Probably you're hitting up the IFTTT webhook API
Which is designed to let you do that
Ok makes sense
You really want https://www.home-assistant.io/docs/automation/trigger/#webhook-trigger and what I do above
So using that I could just call a script up
Sure, but I'd move the intelligence to HA
Have Tasker send a webhook saying dim and let HA handle what that means
hi, how can i use my regex strings from regex101.com in a ha value_template: ?
I have the following string:
WDC_WD40AFRX-68N22N0_WD-W17K02E9YF5: 34
and want to extract 34
which works with : (.*) on that website
https://www.home-assistant.io/docs/automation/templating/
https://www.home-assistant.io/docs/configuration/templating/
": (.*)"
You're awesome. I'm gonna have to bookmark all this.
So, you need to do that in Jinja2 - rather than a regex @left patio
So I use your example to set up the webhooks with that walkthrough, write a script following that example and call it through Tasker. Thanks @arctic sorrel
https://github.com/DubhAd/Home-AssistantConfig/blob/master/automation/people/person2/person2_next_alarm.yaml is one of the automations that consumes the event, if you want to go utterly overkill @rigid basalt - I use events so I can have one webhook and feed it different payloads for different automations
I was considering doing that with the brightness, have a variable that I set to whatever however on my phone and have a task send a webhook and change the brightness to the variable I set, then ramp the brightness with a loop in Tasker
As I said, let HA handle that "ramp"
Move the brains to HA, otherwise you've got logic in multiple places, and it'll cause you confusion later
It already has. I bought a Pi 5 weeks ago as a lockdown project. No idea what to do with a pi, but after a week I had Hassio running
Now I'm looking at templates
Templates are like what happens when somebody gives you a toolbox full of random tools you've never seen before...
{{ string|split(': ')[-1] }}
@dreamy sinew this is called jinja? -> value_template: '{{ value | regex_findall_index(": (.*)") }}'
ill try yours now
you haven't said where the data is coming from
|split(': ')[-1] is a valid way to pull something out of a string in jinja2. but you need to have the "thing" in the front to actually work with
from an linux server over snmp
dont know why but i dont get it with your regex working
Doesn't matter, templates are templates
That there is just a convenient place to test things
i think it works 🙂
now i have to find a way to get this long name out of my sensor card 😄
anyway thx for your help @arctic sorrel & @dreamy sinew !
Searching isn't getting me too far on this one: I've got some sensor templates that get updated based on a rest sensor returning some JSON data. Works fine, but occupationally the server times out for whatever reason and the resulting sensors based on the JSON data blank out, throwing off the graphs that do some math based on those sensors. Is there a more graceful way to handle the error: Empty reply found when expecting JSON data?
(removed) oops - wrong section
something easy and user friendly
template aka skin
sounds like you want #frontend-archived and themes
@karmic oar might be able to add a check to see if it is a valid response before trying to do stuff with it
Thought about that, but haven't tried it. Was thinking logically... whatwould I do with it? Say NaN? Not sure that would help me
yeah, that's the tricky part
random question - why is the value_template for a binary_sensor different in that it needs a statement to be true = ON
rather than an if statement?
You can use an if statement but it's redundant and unnecessary
{{ x == 1 }}
``` is nicer than
{% if x == 1 %}
True
{% else %}
False
{% endif %}
not if i want the result to be false
{{ x != 1 }}
if i have 5 things that mean the sensor is ON, but 1 that is off, how can i simplify without naming all the things that is could be with OR statements
that is an if statement
You can use if statements
No one is saying you can't, but depending on what you're testing it could be unnecessary
{% if is_state('sensor.blah'), 'not_home' %}off{% else % }on{% endif %}
Right. It needs to be True or False. So replace on and off with true and false
Or do
{{ not is_state('sensor.blah', 'not_home') }}
That will be True (on) when it's in a state other than not_home
thats what i'm looking for, will try that - thanks
No prob, that's also what I meant by this: https://discordapp.com/channels/330944238910963714/672223497736421388/705200421303746640
docs made it sound like only true was possible
got it, didnt know you could throw a not in there 🙂
That's talking about what the template evaluates to
If it evaluates to True the binary sensor will be on, if False it will be off
right, but my limited knowledge only knew how to formulate a true statement lol
so many sensors i can remove all the list of states it could be ha - thanks!
No prob!
Has anyone ever had an issue where the Light Template cannot update color and brightness at the same time?
Share what you're trying to do
Please use https://paste.ubuntu.com/ or https://www.hastebin.com/ to share code or logs.
OK, here is the template: https://hastebin.com/vuhokubedu.cs
This is convoluted but the only way i could figure out how to do it. I have RGB lights controlled via HTTP. Most of what makes it annoying is that the set_color part only gives hs color, not RGB, and there are no util/helpers available in templating, so I have to set the HS value and then grab the converted RGB from it into input_numbers
And here is what I am trying to do:
- service_template: light.turn_on
data_template:
entity_id: light.room1_color_lights
color_name: red
brightness: 76.5 # 0.30 * 255
The above service example will set the brightness but not the color. If I separate them and set them one at a time it works. Adjusting the light from Lovelace works fine
What do you mean "but not the level"?
That's not a template 😛
That too lol. None of that requires _template either
Typo sorry. It sets the level but not the color. edited
oh lol yes I don't need the _template stuff. The issue is really with the light template platform not behaving properly
It seems that when I call light.turn_on, it only runs set_color or set_level or it does both but messes one up
Found it! It is indeed a bug—it only looks at one at a time https://github.com/home-assistant/core/blob/dev/homeassistant/components/template/light.py#L335-L354
Opened an issue https://github.com/home-assistant/core/issues/34915
Share the link to the code you previous posted please 😉
You've got the maths working correctly?
on my template ?
yes the result :
Then... https://www.home-assistant.io/integrations/trend/ maybe?
🤣
Did you know if it's normal if this template don't accept icon templating ?
Yeah, relatively few things support icon templates
There's various CSS wizardry you can do in the #frontend-archived but I've never investigated
No need icon for automation... Maybe do another template just for use icon. But i think this may be implemented...
I have a template with several if condition, how can I hide the visual white row when the if condition is not met?
with -
Is it possible to change custom css on a card based on the currently active theme?
Something like:
"""{if: states(theme) | string dark}"""
#frontend-archived would be where to ask
Okay, thanks
Need a help. When I execute this command echo -en '\xfa\x24\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x24\xfb' | mosquitto_pub -t topic -s the techlife Pro bulb work fine. However, when the same hex chars are directly published from developer tools -> Mqtt they do not {{'\xfa\x24\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x24\xfb'}}.
See the image of the messages. First message is from command line tool and the second one from the direct message publish thru HA. See that the first and last byte are different https://imagebin.ca/v/5Ky3vZhEasy2
Is there some way to send exactly what command line sends?
well I was providing as {{'\xfa\x24\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x24\xfb'}} in MQTT payload
put that as the data payuload? "{{'\xfa\x24\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x24\xfb'}}"
quotes around the whole thing so HA doesn't treaf those ticks as special?
I am taking an education guess but I am bad at math
nope does not work. They should match the output from the echo command as in the screenshot I shared. Those start and end part of the message in echo command are generated as a '�'
hmm... ok
Looks like the MQTT payload generates a ASCII but does not match the bytes from what is generated from echo command
just found out that The '�' character is what shows up when an invalid encoding is encountered. So the MQTT explorer I am using to display the codes does not correctly recognize the encoding from echo command
How can I create a binary sensor where the payload differs slightly? I have a RF motion sensor which sends signals varying from payload "70A860", "70A868", "70A86C" and "70A86F". So the last characters changes. Can I use a wildcard "70A86*" for this to trigger? If I search for 'binary sensor wildcard payload' on the internet, I get several other results..
Found it;
value_template: '{{ value_json.RfReceived.Data[:5] }}'
hey i have a question
i use a sonoff to monitor temperature & hum
but i want it in my HA show as curve
not blocks
sensor:
- platform: template
sensors:
temperature_purifier:
friendly_name: Temperature
device_class: temperature
value_template: "{{ state_attr('switch.sonoff_10009e86ef', 'temperature') }}"
humidity_purifier:
friendly_name: Humidity
device_class: humidity
value_template: "{{ state_attr('switch.sonoff_10009e86ef', 'humidity') }}"
is the code i have now in configurations
what could i do?
i'm not that good in coding 😉
Ensure that the unit_of_measurement is set - https://www.home-assistant.io/integrations/template#unit_of_measurement
i tryed that but wasn't working
Well, that's how you get line graphs 🤷
Yup
It just needs to be set to something
Normally it'd be '°C' (or F) for temperature and '%' for humidity
oh ok
sensor:
- platform: template
sensors:
temperature_purifier:
friendly_name: Temperature
unit_of_measurement: '°'
device_class: temperature
value_template: "{{ state_attr('switch.sonoff_10009e86ef', 'temperature') }}"
humidity_purifier:
friendly_name: Humidity
device_class: humidity
value_template: "{{ state_attr('switch.sonoff_10009e86ef', 'humidity') }}"
i have now for testing
HA looks the same after F5 hm
oh damn i have to restart HA 😉
ok works
but it only shows graph of 2minutes
how could it show of 24h or more?
It'll show up to 24 hours in the more info pop-up
Beyond that you need to use a card in the #frontend-archived to show up to the duration you've got in the history
PONG!
Bot working in all channels? Saw a message in #botspam Just checking.
@south monolith posted a code wall, it is moved here --> https://paste.ubuntu.com/p/6W9X4rKPGy/
hello everyone I modified this script to make an audio fadein for the alarm clock ... instead of the maximum volume 0.3 I would like to put an input_number to be able to change this value of mine at will ... how should I write it? thanks
{% if state_attr('media_player.googlehome5227', 'volume_level') < states('input_number.whatever') | float %}
thanks I try ubito unfortunately with the templates I'm still not good
would be a good idea to switch from
states.media_player.googlehome5227.attributes.volume_level
``` to
state_attr('media_player.googlehome5227', 'volume_level')
that's what i did above
ok I correct it
Last couple of days it's been acting up - but maybe only for me - in channels at random @queen meteor 🤷
likely discord side issues. its been a bit wonky
Likely something to do with discord. Everything looks good on the bot server side. I see some errors with discord server being disconnected - which is pretty normal for the bot. Bot auto-connects when that happens almost 99% of time.
That would be my bet, that or gremlins 😄
Hi, Any help on this would be awesome. I have a sensor that displays the rgb_color of a light, any idea how to get it to showthe color name? I tried color_name but it does not show anything. I currently have: light.soda_ash_night_light.attributes.rgb_color and this shows the rgb numbers but I would love it to show the color name.
You'd have to build a lookup table from the RGB to the name, and account for fuzzy matching. It's not likely to be trivial
Dark goldenrod
Nuts I was afraid of that. can i circumvent that if I only need know one color. Fo example How could I get it to show: if(light.soda_ash_night_light.attributes.rgb_color =0,255,63, "Green", "Red")? When I use that it always shows red even if the rgb matches the 0,255,63
Well, you can simply display the name if it matches and "unknown" otherwise
Of course, that attribute isn't a string, which is likely the issues
{{ "Greenish" if state_attr('light.soda_ash_night_light','rgb_color') = [0,255,63]) else "Unknown" }}
Probably
I will try that, thanks
"Some" tweaking may be required - test in
-> Templates
thank you
I tested it but my igniorance is showing now. I get the following error: Error rendering template: TemplateSyntaxError: expected token ',', got '='
I altered it a lot but can not figure out the issue
Are you testing in the templates menu?
==
Always get that wrong 
Question regarding mqtt binary_sensor with template
Basically , I need this sensor turn on when I some1 press button on Intercom.
the user just turn on --> the topic DahuaVTO/BackKeyLight/Event get json with Action == 'Pulse' and later on automation i decide on which button he pressed by extracting the attribute( value_json.Data.State)
- platform: mqtt
name: intercom_calling
state_topic: DahuaVTO/BackKeyLight/Event
value_template: "{{ 'ON' if value_json.Action == 'Pulse' else 'OFF' }}"
json_attributes_topic: DahuaVTO/BackKeyLight/Event
json_attributes_template: >-
{"state":"{{value_json.Data.State}}"}
payload_not_available: offline
all is working but I need to go back to off and not stay on
meaning --> user press button --> sensor show on and return off
after 2-3 seconds
I tried add expire_after: 3
but it setting the sensor to unavailable
@feral sage #integrations-archived
Hi, I would like to have a mqtt sensor that is on by default. This:"- platform: mqtt
name: "rob_present":
state_topic: "domoticz/out/floorplan/rob"
value_template: "{{ is_state(value_json.nvalue, 'on') }}"
payload_on: "1"
payload_off: "0"doesn't do the trick. Can someone suggest me how to do this?
{{ value_json.nvalue == 'on' }}
I have temperature sensors in all of the rooms in my house, I'd like to create a "coldest room" sensor. Essentially just take all of the temperatures from the sensors I have and find which one is the lowest and display it. Can anybody reccomend some way I can do this?
There’s a min max sensor https://www.home-assistant.io/integrations/min_max/
@sage zodiac
@mighty ledge Thanks I'll check that out
Does this look correct? It is returning "None" for me for some reason.
sensors:
ping_google_average:
value_template: "{{ state_attr('states.binary_sensor.internetping', 'round_trip_time_avg') }}"
unit_of_measurement: ms```
The binary_sensor is working, I verified that
Remove states.
The first argument for state_attr() is the entity ID
You can also test templates at developer tools > template before deploying them in sensors
@lusty silo ☝️
@feral sage I think that what you're looking for is: off_delay: 3
I need somehow help.. I can't figure this out after hours of tests.. I created an MQTT Binary Sensor, but it keeps remainin on "off" state even if the payload is "true" (As far as I remember a payload of true would translate to on, no?) This is the code: ```state_topic: "zigbee1mqtt/bedroom_luca_light_1"
value_template: "{% if value_json.update_available is defined %}{{ value_json.update_available }}{% endif %}"
(I also tried to add payload_on: "true" without success)
The payload is JSON coming from zigbee2mqtt, I think the path is right but maybe I am not seeing something very clear? {"state":"OFF","linkquality":57,"last_seen":"2020-05-03T14:32:59.356Z","brightness":255,"color":{"x":0.323,"y":0.329},"update_available":true,"device":{"friendlyName":"bedroom_luca_light_1","model":"LED1624G9","ieeeAddr":"0x680ae2fffe24c059","networkAddress":12060,"type":"Router","manufacturerID":4476,"manufacturerName":"IKEA of Sweden","powerSource":"Mains (single phase)","applicationVersion":17,"stackVersion":87,"zclVersion":1,"hardwareVersion":1,"dateCode":"20170315","softwareBuildID":"1.3.002"}}
why not just value_template: '{{ value_json.update_available }}'
or does it err if update_available doesnt exist?
I tried that too, ssame result
That was just a validation I copied from the PIR sensor just to test something else
Kind of a failover in case zigbee2mqtt doesn't send a value for that somehow
Im having wled integration, and now I want to create a script that when I call it randomly sets animations of my led strip
I have already setup everything
I want just set up effect randomly each time when I press a button
{{ state_attr("light.wled_lights", "effect_list") | random }}
maybe something like this
- service: mqtt.publish
data_template:
topic: wled/all/api
payload: "{{ state_attr("input_select.wled_presets", "options") | random }}"```
Im getting an error
its underlines wled/all/api error: cannot read an implicit mapping pair ; a colon is missed
in "/config/scripts/lights/setup_on_wled.yaml", line 5, column 7
expected <block end>, but found '<scalar>'
in "/config/scripts/lights/setup_on_wled.yaml", line 6, column 32```
what are your input selec values?
these are my input_select.wled_pressets:
- "[PL=01] Preset 1"
- "[PL=02] Preset 2"
- "[PL=03] Preset 3"
- "[PL=04] Preset 4"
- "[PL=05] Preset 5"
- "[PL=06] Preset 6"
- "[PL=07] Preset 7"
- "[PL=08] Preset 8"
- "[PL=09] Preset 9"
- "[PL=10] Preset 10"
- "[PL=11] Preset 11"
- "[PL=12] Preset 12"
- "[PL=13] Preset 13"
- "[PL=14] Preset 14"
- "[PL=15] Preset 15"
- "[PL=16] Preset 16"```
I tested in template editor in HA
and I receive correct
string
if I put just like to get the value from input_select what is selected currently
data_template:
topic: wled/all/api
payload: "{{ states('input_select.wled_presets') }}"```
it works
but if I just want to randomize my input_select.wled_pressets
my coinfig is wrong
"{{ states('input_select.wled_presets') }}"
#Doesnt work
"{{ state_attr("input_select.wled_presets", "options") | random }}"```
this works: '{{ state_attr("input_select.wled_presets", "options") | random }}'
single quotes 😉
and how to catch that ranndom option and updated my input_select
data_template:
topic: wled/all/api
payload: '{{state_attr("input_select.wled_presets", "options") | random }}'
- service: input_select.select_option
data_template:
entity_id: input_select.wled_presets
option: '{{state_attr("input_select.wled_presets", "options") | random }}'```
I'm having fun with templates. I want sensors reporting how many doors, windows are open, or lights that are on. Here's the generic template. (Note that the expand() function recurses through groups of groups to the complete atomic entity list)
value_template: >
{% macro countgroupstate( group, state_test ) %}
{%- for state in expand( group ) %}
{%- if is_state(state.entity_id, state_test) %}
{% set ns.count = ns.count + 1 %}
{%- endif -%}
{%- endfor -%}
{%- endmacro -%}
{% set ns = namespace( count = 0) %}
{{ countgroupstate( 'group.all_lighting', 'on' ) }}
{{- ns.count }}
You can also pass a series of {{ countgroup...}} and they'll be added together
That one probably won't auto update though
@dusty hawk You should read up on filters, can save you some complexity.
{% set state_test = 'on' %}
{% set group = 'group.all_lighting' %}
{{ expand(group) | selectattr('state','eq', state_test) | list | count }}
@sonic nimbus you'd have to make a script and send the random option to it.
script:
my_script:
sequence:
- service: mqtt.publish
data_template:
topic: wled/all/api
payload: '{{ option }}'
- service: input_select.select_option
data_template:
entity_id: input_select.wled_presets
option: '{{ option }}'
service: script.my_script
data_template:
option: '{{state_attr("input_select.wled_presets", "options") | random }}'
Anyone had a chance to see my message from yesterday?
@fossil summit you're returning true but what does payload_on require? By default it's 'ON' or 'OFF' so you should be returning one of those in all paths. Or use true/false without quotes for on/off setting.
@mighty ledge this option is like input variable to my script right?
when I calling my script, I just pass option that I will randomize it ad hoc? 🙂
@sonic nimbus option is passed to the script through the variable 'option'. See the service call that I posted calling the script. That's exacty how it would be called.
@mighty ledge Yep I got that, but also if I configure payload_on: "true" it doesn't seems to "accept" it.. also, the json is like "update_available": true, so it is returning a clean "true" value without quotes
ah... maybe I got what you mean, I should use payload_on: true instead of "true"
I'll try that
It worked! Thanks @mighty ledge , I thought I had to wrap in quotes... Well I actually thought a true from the json would had been enough 😄
Thanks, @mighty ledge. And, it works across multiple groups too, and filters out duplicates as well:
{% set state_test = 'on' %}
{% set group = 'group.all_lighting','group.dining_kitchen_lights', 'group.office_lights' | join %}
{{ expand(group) | selectattr('state','eq', state_test) | list | count }}
@sonic nimbus option is passed to the script through the variable 'option'. See the service call that I posted calling the script. That's exacty how it would be called.
@mighty ledge zup, that I meant when I said that zou are passing a input argument calledoption
hey all i m working on my first templates / intents and i wonder howdo i get the siteId value from the json of the intent
{{ siteId }} doesnt seem to work
your question is ambigous, we need to know what you're doing.
mmm well
ChangeLightState:
action:
- service_template: 'switch.turn_{{state}}'
data_template:
entity_id: 'switch.{{room}}_{{objet}}'
this intent is working alright
but i want to replace {{room}} with siteid
and siteId doesn t return any value
when listening to the MQTT intent i have that json:
{
"input": "on 0 lumière",
"intent": {
"intentName": "ChangeLightState",
"confidenceScore": 1
},
"siteId": "salon",
"id": "8986546d-9468-4723-b849-d4a41585ee02",
"slots": [
{
"entity": "state",
"value": {
dont know how to grab this value "siteId": "salon",
anyone ? 🙂
Anyone had any success with input_selects for the media_player.play_media service? Been tried to make a radio list and echo device to pick from and play but it doesn't recognise the template on the automation/script 😦
share what you've tried
Please use https://paste.ubuntu.com/ or https://www.hastebin.com/ to share code or logs.
should just be
sequence:
- data_template:
entity_id: '{{ states.input_select.playback_device.state }}'
media_content_id: '{{ states.input_select.radio_station.state }}'
media_content_type: TUNEIN
service: media_player.play_media
i don't know if that's a valid content type or if the resulting template is a valid content id though
I made it through the UI and did that automatically
next to it (docs are outdated)
-> Customizations