#templates-archived
1 messages ยท Page 88 of 1
Are you scraping the data or did VG publish it as json?
VG has published everything as json
one sec, and i'll dig up the url
that's the json structure for the different municipalities
they have quite a few others as well.. they also publish the hospital stats, case-by-case stats and a few others as well as json structure
same with dagbladet.. they have also json structures for the self-reporting map: https://www.dagbladet.no/app/crowdsource-corona-api/api/v1/municipality-stats
and here is the county-wide stats from VG: https://redutv-api.vg.no/corona/v1/sheets/norway-table-overview?region=county
@rugged laurel if you'd be interested in working on a custom component for the data from VG, please let me know ๐
no need, a rest sensor is enough
let me know if you want to take a look at my, admittedly feeble, attempts ๐
i had to set up a python web server to present the municipality structure from vg into a structure with a parent key
to be able to address it properly.. if you find a different way of doing the same, please let me know
ah, you want multiple..
You need custom_component/appdaemon/netdaemon for that
yeah, i'm monitoring several municipalities
if that's what you mean by multiple?
i just wrote a python script to put the json structure with a new parent key "municipalities"
and then used that key in json_attributes
i'm not sure that is the best way of doing it, though
Creating a custom_component for it should be easy enough, probably 15-20 min work, 30 if you want config_flow
i'd be more than happy to create one, but i have no idea how to start out ๐
what kind of component will it be?
which integration?
a new one, that spin up sensors
the config_flow should have a dropdown to select a municipality
hm.. the home-assistant repo has changed its name to core?
yes
maybe use the coronavirus component as a starting point
Sounds good
er.. where does that component get its data from?
hehe, d'uh.. but WHERE.. i see no references to any urls or similar there
all core integrations require that a pypi package handle the communication to the api
buuut, this is now no longer #templates-archived , #integrations-archived are probably better to continue under
Newbie here, this should be simple but i could not find any examples that helped. I have this action:
service_template: |
{hdmi_cec.{% if trigger.data['action'] == 'on' %}
power_on
{%- else -%}
{% if trigger.data['action'] == 'off' %}
power_off
{%- endif %}
{%- endif %}}
It's based on a webhook trigger and the if-statement does resolve correctly. But it comes out to: 'hdmi_cec. power_off'. To get rid of that whitespace I need a concat-function, but any operator I put is taken as a literal string, meaning 'hdmi_cec. ~ power_off'. What would be the correct way to make a proper service call out of that?
You can simplify it to just if hdmi_cec.power_on else hdmi_cec.power_off endif
Unless you expect trigger.data["action"] to ever have a different value than on or off, in which case you're not handling that now anyway.
service_template: "hdmi_cec.power_{{ trigger.data['action'] }}"
@tender dagger โ๏ธ
both of these look right but now result in 'hdmi_cec/power_off' for some reason. is the . now treated as a magic word?
Should be ok, I have several service templates like that
will try a reload
Also let's see the whole automation
Please use https://www.hastebin.com/ or https://paste.ubuntu.com/ to share code or logs.
https://hastebin.com/onunocokiz.sql
Does this work?
That's just the internal name of the service.
Do you see hdmi_cec.power_off in the list in
->Services?
And do you see hdmi_cec in the integrations list in
-> Info?
checking it I found that it is .standby not .power_off for turning off, your suggestions now work as intended. Thank you both for your help and time.
Has anyone else had any issues with cover templates not being able to get states changes from sensors when updating to 0.107.7?
Basically, everything is working in 0.107.6, but when I updated to .7 it all broke. I have multiple blinds using esphome, and some of the blinds I have grouped together using cover templates (ie two living room blinds that are next to each other. If I have 1 blind open, the template cover is showing the opposite state of the sensor it's supposed to read. I can use the template cover to then close the blinds (everything displays correctly), and then open the blinds (everything displays correctly), but then can't close them again because for some reason the template cover isn't reading the state from the sensor. Here's my code: https://hastebin.com/elinuvuzey.cs
Like I said, it all works in .6, but upgrading to .7 breaks it.
@mighty ledge
The reason I'm using a template instead of a group is because I want my group to only show open if ALL the blinds are open
https://www.home-assistant.io/integrations/group#all @pale laurel
I meant cover group, so instead of cover group or cover template, just use a group?
You can create groups that are only open if all the members are open - see the link
I get that part, I should have also mentioned that the reason I'm using cover is because telling Alexa to "open living room blinds" will only work if it's a cover
Your template looks good but you aren't updating the templates based on the sensor.
so there could be a race condition there
isn't that what value_template does?
Yes, but the value template only has listeners for cover.living_l_blinds, and cover.living_r_blinds
it should also have a listener for sensor.living_room_blinds, but sometimes the parser doesn't work
well that will help, i don't know if it will fix your issue.
everything looks good the way you have it on the surface
without the extra entity_id
also, why aren't you just using a cover group?
when I used cover group, the group was reading open if even just one blind was open. In the documentation, it didn't show an all condition like the light groups do.
Ah
I only want the group to show open if every blind is open
that's a good enough reason
yeah, i know that one thing is making this way more complicated lol
ok so try this
value_template: >
{% set covers = [ states.cover.living_l_blinds, states.cover.living_r_blinds ] %}
{{ covers | selectattr('state','eq','open') | list | length == covers | length }}
And you can remove your sensor template
dumb question, having "set covers =" is fetching the state of the covers, not trying to set the state of the covers?
Jinja variable setting magic
sorry, I'm using to = being assigning and == being a comparison
yah, you're assigning a variable equal to the current value of your covers
value_template: >
{% set some_thing_here = [ states.cover.living_l_blinds, states.cover.living_r_blinds ] %}
{{ some_thing_here | selectattr('state','eq','open') | list | length == some_thing_here | length }}
Same thing, just less "friendly"
OH gotcha
(I think, if I replaced all the right things)
you did
is that covers var local or global? like it's not going to affect other templates?
Local
ok
everything in jinja is what tinker just said
Jinja variables tend to "hyper-local" too, you can't set things in loops and then use them outside for example
- trims the output
so why wouldn't you just use it all the time?
lol gotcha
I never use it because it makes no difference
yeah I saw some people using {- -} instead of {} and I wasn't sure why
If this were another package, it would make a difference
but home assistant trims all whitespace by default
gotcha
now... if you using the editor...
no
it makes a difference
i use sublime
the one in the gui?
that's why I meant by no, I don't use any addon editors or stuff in the gui, I prefer to just use sublime text
gotcha
that little - removes that space
so, it's pretty much only useful there.
It's also useful for sending notifications because the message field retains spaces.
yeah i was wondering if >- actually did anything. good to know it doesn't lol
but yeah, {%- and the like are useful
it's pointless unless in the message: field for notifications
there might be other areas where it's useful but I haven't found any
outside messages
Probably the markdown card
you're gonna hurt the hyphen's feelings
Lol
won't anyone think of the hyphens??
what about the icon template, right now I'm using the sensors to define that
that should be fine
see where I'm using sensor.living_room_blinds to get the state for the icon?
just so I get what's happening there, you are setting the blind states into an array called covers, then piping that into the selectattr function to get a list of states, and if the number open states match the length of the array it's uses it?
{% set covers = [ states.cover.living_l_blinds, states.cover.living_r_blinds ] %}
{% set open = covers | selectattr('state','eq','open') | list | length == covers | length %}
{% if open %}
mdi:window-shutter-open
{% else %}
> mdi:window-shutter
{% endif %}
minus that arrow
no need for shutter-alert because that will never get hit
the only reason I have that in there is so when one goes offline for some reason, I'll notice
Have you ever seen that Icon?
gotcha
let's say a blind goes offline then, how do I have error handling to show me that?
{% set covers = [ states.cover.living_l_blinds, states.cover.living_r_blinds ] %}
{% set open = covers | selectattr('state','eq','open') | list | length == covers | length %}
{% if open %}
mdi:window-shutter-open
{% elif covers | selectattr('state', 'eq', 'unknown') | list | length > 0 %}
mdi:window-shutter-alert
{% else %}
mdi:window-shutter
{% endif %}
unknown or unavailable?
I just went and pulled the plug on one and it's state is unavailable
unavailable
Use that then
kk
restarting everything and testing
then after I snapshot it I'll update to .7 again and see if that fixed it
I seriously felt like I was chasing my tail trying to figure out why the heck it wouldn't read that sensor
It looked good but itโs always good to remove unnecessary layers
everything seems to be good in .6, going to try it in .7
How do I use templates?
{{ 1 + 2 }}
.topic @bitter lagoon
@bitter lagoon Become a real Jinja2 Ninja! Don't worry my Genin, we are here to help! You can find the docs at https://www.home-assistant.io/docs/automation/templating/ - and don't forget rule #1! Please use https://www.hastebin.com/ or https://paste.ubuntu.com/ to share code or logs
Carefully
~share @teal phoenix
@teal phoenix Please use https://www.hastebin.com/ or https://paste.ubuntu.com/ to share code or logs.
Guy's... small problem.
https://paste.ubuntu.com/p/tcW7YMjGX4/
Hi guys, can somebody tell me what's wrong with this?
- data_template:
data:
message: Warnung - SSL Zertifikat lรคuft in weniger als {{ trigger.to_state.state }} Tage(n) ab. Automatische Erneuerung ist fehlgeschlagen, Logs checken!
service: notify.mobile_app_fabian_seins
service: notify.mobile_app_fabian_seins```
Error: ```Error rendering data template: UndefinedError: 'trigger' is undefined```
ah, maybe because I trigger it manually?
...
Could be.
You also have a weird structure.yaml data_template: data: service: service:
You probably want yaml data_template: message: service:
That's the UI editor which messes up my order
The UI editor doesn't do templates ๐
Yes, but If you add the template afterwards the order doesn't change from alone ๐
Can someone help me with an template from seconds to days , hours, minutes? I tried a lot from home assistant community but no1 worked fine.
I think I have one but it has a little bug if I recall correctly
What do you have so far?
'''
Maybe you can use mine and customize it to your liking: https://pastebin.com/TL8wQSxr
@marble lily posted a code wall, it is moved here --> https://paste.ubuntu.com/p/wgPgYZswHD/
~codewall @marble lily
@marble lily Rule #6: Please do not post codewalls (longer than 15 lines) - use sites such as https://hasteb.in/, https://paste.ubuntu.com/, or others.
Please take the time now to review all of the rules and references in #rules.
What is happening? What is not happening?
proxmox_server_uptime
40 seconds ago
Unknown
Successfully saved
what need to be here: {% set time = states.sensor.proxmox_server_uptime_s.state %} , after the sensor? I'm getting data from netdata.
I get it working. ๐ thanks for the post.
Try putting one piece at a time into the editor in
->Templates, and add things like {{ time }} here and there to print out the value of variables to see if they are what you expect.
What was the problem?
I changed attributes.uptime with .state
Ok, I see, my sensor didn't have the uptime as the state but as an attribute but glad you could get it to work. The template should be fine and always display correctly. Glad I could help ๐
And one more thing.
If I want to change the icon for this template sensor, i need to do in the customize.yaml?
I used the icon_template option but didn't specify any template. https://www.home-assistant.io/integrations/template/#icon_template
Oh and one more thing, think about excluding that sensor from your recorder, otherwise it will fill up the database really fast, I had problems with my Pi crahsing when accessing the history panel
is is_not_state('sensor.pixel_3_alarm','set') valid? or how do i not with jinja templates?
{% if not is_state('sensor.pixel_3_alarm','set') %} this works
@young jacinth you can also do ```
{{ states('sensor.pixel_3_alarm') != 'set' }}
Thanks!
i guess {{ states('sensor.pixel_3_alarm') > 0 }} would work too?
{{ states('sensor.pixel_3_alarm') | float > 0 }} does work ๐
I have an sensor for idle cpu (proxmox host), i can't get a usage cpu sensor. How can i Convert the idle to used?
100% - sensor?
yes, i get like 90.88% idle
sensor:
- platform: template
sensors:
cpu_usage:
friendly_name: "CPU Usage"
unit_of_measurement: '%'
value_template: "{{ 100 - (states('sensor.idle')|float) }}"
Test it out in
-> Templates
Mhm it's working but i get like 1.519999999999996 %
I need to add an round(2) somewhere.
value_template: "{{ (100 - (states('sensor.idle')|float))|round(2) }}"
``` probably
yes?
on netdata i can get system%+user%+sftirq%+guest%
can i add all of that into one sensor?
yes?
It's Jinja
Thanks ๐
The best thing to do is just try stuff out in the Templates menu
and look at the documentation
๐ค
That sounds like advanced thinking. Doesn't everybody just throw the manual out before trying to build something?
There are manuals? ๐ฎ
Which reminds me, must go through the 0.107 breaking changes now I've upgraded ๐
Yeah, I've got them open, I'm just checking the little details now. I did my usual - upgrade, config check, fix the big things ๐
Looks like the only thing that snuck in was the addition of idle to the Sonos states
hey all, what's the syntax to do else if in a template without nesting?
{% elif ... %}
literally just found the example ๐ thanks
I'm using that power sensor I was looking at yesterday and using thresholds to infer a state
oooooh nice documentation, thanks
Hello
I'm not sure if this is the correct place
But there is a way to make templates more dynamic
I mean
I have for example 7 tplink outlet with energy meter
Also I have created utility meter for adding all of them to get the total amount of energy
But if I add a new outlet I need to copy from one and change the entity name and also add it to the utility meter section
There is some way to make this process more dynamic
Like using variables or something similar?
If you are trying to create sensors for each outlet you setup, you may have to copy and paste the code multiple times. You could however use some sort of variable custom component, and have an automation on state_changed event, and update those variables - defining those set of variables is static, populating dynamic values into those variables can be dynamic/real-time with just one block of code. You decide whether it is worth going through a custom component and set it up, or just duplicate the code.
On the other hand, having some sort of variable component can come in handy - it can also be used elsewhere. I personally found that to be very valuable for my setup
@queen meteor
Any examples how to do it
@dry bison I use something called input_label which is basically a sort of label placeholder - like variable. Since everything in Jinja is strings, it stores values as strings. I also have examples where I populate battery values of various sensors into those variables. Check out my repo for examples.
@dry bison Skalavala's github repo and his blog
@dry bison I use something called input_label which is basically a sort of label placeholder - like variable. Since everything in Jinja is strings, it stores values as strings. I also have examples where I populate battery values of various sensors into those variables. Check out my repo for examples.
@queen meteor thanks I will try to have a look but Im very newbie reading gitbub lol
is there any way to uuse a template to display the number of days until a time?
I.E "5 days, 3 hours, 2 minutes until X"
Yep, strftime which is listed on the ha template docs
And probably a timedelta claws
is a javascript template literal the same thing as an HA template?
No
var countDownDate = new Date("Aug 17, 2020 00:00:01").getTime();
var distance = countDownDate - now;
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
return "Semester Starts in " + days + " days, " + hours "hours, " + minutes + " minutes, and " + seconds + "seconds";
ended up using this
ok.. thought you were looking to do in jinja - no limits on python!
i thought i was doing it in jinja too but the add-on i was using uses plain JS templates
hi, I have a template {{as_timestamp(states.binary_sensor.back_door_contact.last_changed) }}, it returns 1585527125.312935. I see the jinja helper example, and it's exactly what I want, to turn it into weeks/hours/minutes. How do I merge these segmets so that I can use it in a markdown card? I want to say "the back door was last opened 'weeks/hours/minutes' ago"
@unreal cave ```
{% set seconds = as_timestamp(now()) - as_timestamp(states.binary_sensor.back_door_contact.last_changed) |int %}
{%- set map = {'Week': (seconds / 604800) % 604800,
'Day': (seconds / 86400) % 7,
'Hour': (seconds / 3600) % 24,
'Minute': (seconds / 60) % 60,
'Second': (seconds % 60) } -%}
{%- for item in map if map[item] | int > 0 -%}
{%- if loop.first %}{% elif loop.last %}, and {% else %}, {% endif -%}
{{- map[item]|int }} {{ item -}} {{- 's' if map[item]|int > 1 -}}
{%- endfor -%}
beautiful
this gives the time format you are looking for.... you need to make it into a sensor and display the value in markdown. Markdown is frontend, the and the code above is backend
yep works immediately, thanks so much.
wow this templating makes HA ridiculously awesome. feels like it goes on forever
there are limitations, but it gets you going pretty good once you get hang of it
how do you insert a space right after the variable script? it says "secondsago". only way I can get it to insert a space is {{ ' ' }}ago. must be an easier way
simple hack would be to add a space to the 'Second': (seconds %60) section...
cant, it has to come after the s
the reason I said hack is because I don't how what your script looks like. The code has - right after {% and before %}. you can remove that -.
the s is appended to week(s) hour(s) etc so you end up with spaces everywhere
can you post your code? May be I can show you exactly where to change that
yup - the hyphen removes white spaces
nice. learing.
best to play in the template editor
the back door was last {% if is_state('binary_sensor.back_door_contact', 'on') %} open {% else %} closed {% endif %}{% set seconds = as_timestamp(now()) - as_timestamp(states.binary_sensor.back_door_contact.last_changed) |int %}
{%- set map = {'Week': (seconds / 604800) % 604800,
'Day': (seconds / 86400) % 7,
'Hour': (seconds / 3600) % 24,
'Minute': (seconds / 60) % 60,
'Second': (seconds % 60) } -%}
{%- for item in map if map[item] | int > 0 -%}
{%- if loop.first %}{% elif loop.last %}, and {% else %}, {% endif -%}
{{- map[item]|int }} {{ item -}} {{- 's' if map[item]|int > 1 -}}
{%- endfor %} ago.
so thats the code and it works beautiful now
@unreal cave also, you don't have to have to have if and else... you can simplify it into something like this if you want: ```
the back door was last {{ 'open' if states('binary_sensor.back_door_contact') == 'on' else 'closed' }} ...
now just need to swap the back door for all the doors automatically
Hello guys.
I am using a geocoded location via the mobile_app for iOS. It delivers data in form of "Street 7\n6850 Dornbirn\nรsterreich".
I tried to remove the \n with a template sensor.
value_template: >-
{{ (states.sensor.phone_geocoded_location.attributes["Name"] | string|regex_replace(find='\n', replace=' ', ignorecase=False))}}
Sadly it does not work. Any help would be appreciated.
Tried simple split and join?
Hey all, using a icomfort thermostat, cant figure out how to change unit of measure to F.
climate:
- platform: myicomfort
name: firstfloor
username: MYUSERNAME
password: MYPASS
system: 0
zone: 0
cloud_svc: lennox
You have to change your whole HA system to use imperial measurements
ahh ok.
Hi guys, can I define a default value when calling a script with variables? Or do I have to always provide the script with the variables when calling it?
Like is there a template I can use to use a default value if the other variable isn't set
What error/problem are you getting?
none
If I remove the template and (both from payload_template and the templates inside the string) the siren sounds, only when I provide it with templates it doesn't do anything
That sounds like a problem ๐
If I call the script via the dev-panel via service: script.sound_siren with the service_data: variables: duration: 1 strobe: true nothing happens, no error as well
Also I added a second sequence to create a persistent notification with the payload as a message and it looks like this:
{"warning": {"duration": 2, "mode": "emergency", "strobe": True}}
That looks like it should: https://www.zigbee2mqtt.io/devices/HS2WD-E.html#triggering-the-alarm
Therefore I think I've got an error with the mqtt.publish service call. But I don't get it
Ok, it has to do with the template, I've listened to what is being sent via mqtt and the template values are not sent
@analog remnant I'm no template expert, but shouldn't that be data_template: instead of data:?
Not according to the docs
But Iโll try that tomorrow, the persistent notification worked with data_template.
Hi all, can anyone share their climate automation with me? I have been searching for one for awhile with no luck. Ideally i want my AC to turn on to heat when the temperature drops to a certain degrees and visa versa..
@tranquil grove https://github.com/skalavala/mysmarthome/blob/master/packages/nest_thermostat.yaml some example code in there
Can someone point me what I miss here, got Error rendering template: UndefinedError: 'None' has no attribute 'state' when try this:
{% if states.input_select.wul_alex_time_hour.state|round(0)|string|length == 1 %} {% set time = 0 %} {% endif %}
{% set time = time|string + states.input_select.wul_alex_time_hour.state|round(0)|string + ':' %}
{% if states.input_select.wul_alex_time_minute.state|round(0)|string|length == 1 %} {% set time = time|string + '0' %} {% endif %}
{% set time = time|string + states.input_select.wul_time_alex_minute.state|round(0)|string %}
{{ time }}
states.input_select.wul_alex_time_hour.state = 06
states.input_select.wul_alex_time_minute.state = 40 when I check them.
Rather than states.input_select.wul_alex_time_hour.state try states('input_select.wul_alex_time_hour') (etc)
I tried this, and it render, but with output 06:unknown ๐
{% if states('input_select.wul_alex_time_hour')|round(0)|string|length == 1 %} {% set time = 0 %} {% endif %}
{% set time = time|string + states('input_select.wul_alex_time_hour')|round(0)|string + ':' %}
{% if states('input_select.wul_alex_time_minute')|round(0)|string|length == 1 %} {% set time = time|string + '0' %} {% endif %}
{% set time = time|string + states('input_select.wul_time_alex_minute')|round(0)|string %}
{{ time }}
So its something with the 4th row, but cant figure out what.
This one {% set time = time|string + states('input_select.wul_time_alex_minute')|round(0)|string %}
haha, I had misspelled the name on that row. This is too early.
But one good thing, I wrote in the right channel ๐
Templates are supported in - delay right?
like:
- delay:
minutes: "{{ states('input_select.wul_alex_how_many_minutes') | int }}"
how do you correct to 0 decimal place?
|round I think it is
am I doing this correctly to create a sensor with the temp data?
sensor:
- platform: template
sensors:
temp:
friendly_name: "Temperature"
unit_of_measurement: 'Celsius'
value_template: "{{ states('weather.datasky'),'temperature'|round }}"
https://www.home-assistant.io/docs/automation/templating/
https://www.home-assistant.io/docs/configuration/templating/
YAML is the mark up language used by Home Assistant. Consistent indenting (two spaces per level) is key
issue with indentation?
sensor:
- platform: template
sensors:
temp:
friendly_name: "Temperature"
unit_of_measurement: 'Celsius'
value_template: "{{ state_attr('weather.datasky','temperature')|round }}"
Indentation and template
I'm assuming your entity is valid, and you're not using DarkSky
i am using dark sky. why?
weather.datasky
sensor:
- platform: template
sensors:
temp:
friendly_name: "Temperature"
unit_of_measurement: 'Celsius'
value_template: "{{ state_attr('weather.dark_sky','temperature')|round }}"
``` would have the actual entity correct
how do you add the colors like that?
```yaml
damn thanks for the tip
so I saved this and restarted HA but no sensors showed up, nothing in the logs
- platform: template
sensors:
temp:
friendly_name: "Temperature"
unit_of_measurement: 'Celsius'
value_template: "{{ state_attr('weather.dark_sky','temperature')|round }}"
humidity:
friendly_name: "Humidity"
unit_of_measurement: '%i'
value_template: "{{ state_attr('weather.data_sky','humidity') }}"
you should see sensor.temp and sensor.humidity
you still have weather.data_sky in the second one. also confirm that the entity ID is in fact weather.dark_sky
finally, you can test templates at developer tools > template. helpful before using in template sensors
you still have
weather.data_skyin the second one. also confirm that the entity ID is in factweather.dark_sky
@buoyant pine intentional as dark sky also provides that info.
@little gale posted a code wall, it is moved here --> https://paste.ubuntu.com/p/pc9dznVZRd/
~codewall @little gale
@little gale Rule #6: Please do not post codewalls (longer than 15 lines) - use sites such as https://hasteb.in/, https://paste.ubuntu.com/, or others.
Please take the time now to review all of the rules and references in #rules.
Test templates in
-> Templates
delete the stuff in the text field and paste this in:
{{ state_attr('weather.dark_sky','temperature')|round }}
and this:
{{ state_attr('weather.data_sky','humidity') }}
and check the output
again, check that the entity IDs you're using in the templates are correct. you're using weather.dark_sky in one and weather.data_sky in another
also again, you should see sensor.temp and sensor.humidity at developer tools > states
delete the stuff in the text field and paste this in:
{{ state_attr('weather.dark_sky','temperature')|round }}
@buoyant pine this outputs it correctly although the other one says None
dude, change the entity ID in the humidity template sensor to weather.dark_sky
also run a config check:
Always run the configuration check command when you make changes. Don't trust the UI check - it misses some problems.
@little gale posted a code wall, it is moved here --> https://paste.ubuntu.com/p/y5VWHRhYvX/
It's literally that
- platform: template
sensors:
temp:
friendly_name: "Temperature"
entity_id: weather.dark_sky
device_class: temperature
unit_of_measurement: 'Celsius'
value_template: "{{ state_attr('weather.dark_sky','temperature')|round }}"
humidity:
friendly_name: "Humidity"
entity_id: weather.dark_sky
device_class: humidity
unit_of_measurement: '%i'
value_template: "{{ state_attr('weather.data_sky','humidity') }}"
{{ state_attr('weather.data_sky','humidity') }}
no, it's not. you don't need the entity_id: weather.dark_sky part anyway
and that's the first time we're seeing that part
well I tried to paste it but...
Configuration valid!
the config check command, not the UI check
I need to SSH in for this?
Yup
This is a supervised installation and this is what docker exec home-assistant python -m homeassistant --script check_config --config /config output:
Always run the configuration check command when you make changes. Don't trust the UI check - it misses some problems.
pi@pi4:~ $ docker exec home-assistant python -m homeassistant --script check_config --config /config
Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: Get http://%2Fvar%2Frun%2Fdocker.sock/v1.40/containers/home-assistant/json: dial unix /var/run/docker.sock: connect: permission denied
Click the link above
sudo
sudo?
pi@pi4:~ $ sudo docker exec home-assistant python -m homeassistant --script check_config --config /config
Error: No such container: home-assistant
you actually can run the docker config check command on the host with a supervised install, but the container name is likely homeassistant, not home-assistant
but that's not explained in the docs, so i guess it's unofficial
pi@pi4:~ $ sudo docker exec homeassistant python -m homeassistant --script check_config --config /config
Testing configuration at /config
pi@pi4:~ $
if the config check comes back ok and there are no errors in the log, then the sensors should be at developer tools > states
Assuming you restarted
yup
yeah did that again and it showed up
sensor:
- platform: template
sensors:
cpu_usage:
friendly_name: "CPU Usage"
value_template: "{{ (15.53 - (states('sensor.proxmox_memory_free')|float))|round(2) }}"
I get a string on value_template, I don't understtand what i'm doing wrong.
Nevermind, that "" on front and end.
what comes out of a template is always a string
value_template: {{ (15.53 - (states('sensor.proxmox_memory_free')|float))|round(2) }} - i get an error on vscode : incorrect type.
I have the following script set up to play a particular playlist on a particular speaker. If I set up an input_select for each of my speakers, could I replace "living_room" below with a template that would pull in the speaker name that I selected?
play_70s:
alias: Play 70s
sequence:
- service: media_player.shuffle_set
data:
entity_id: media_player.sonos_living_room
shuffle: "true"
- service: media_player.select_source
data:
entity_id: media_player.sonos_living_room
source: 70s Road Trip
@spiral imp simple answer is yes. It looks like a script, and assuming you are calling that script from an automation, you could pass parameters to it.
Keep getting this error
Invalid config for [sensor.template]: value is not allowed for dictionary value @ data['sensors']['aqi']['device_class']. Got 'pm25'. (See ?, line ?).
Please use https://www.hastebin.com/ or https://paste.ubuntu.com/ to share code or logs.
Show us the config so we don't have to guess ๐
https://www.home-assistant.io/integrations/sensor#device-class are the only supported device classes though
aqi:
friendly_name: "AQI"
device_class: pm25
value_template: "{{ state_attr('sensor.waqi_belur_math_howrah_india','pm_2_5') }}"
There's your problem ๐
That's maybe a unit of measurement
It's certainly not a class
All sensors that have pm25 as part of their entity_id or pm25 as their device_class
as per homekit kb
I don't think there's a unit of measurement
Looks like the HomeKit docs are wrong
And yes there is, if there wasn't I wouldn't mention it
Looks like for HomeKit purposes you need to add pm25 to the entity
no device_class then?
Invalid config for [sensor.template]: Entity ID pm25 is an invalid entity id for dictionary value @ data['sensors']['aqi']['entity_id']. Got 'pm25' value is not allowed for dictionary value @ data['sensors']['aqi']['device_class']. Got 'pm25'. (See ?, line ?).
It's nice not to have to ask somebody for the error for once, but the error without the context is pretty much pointless ๐
Also, check the docs, see if the thing your doing is valid
You still haven't fixed your device class error either
AQI doesn't have a unit of measurement
๐คฆ
aqi:
friendly_name: "AQI"
entity_id: pm25
unit_of_measurement: ''
value_template: "{{ state_attr('sensor.waqi_belur_math_howrah_india','pm_2_5') }}"
```:
```css
Invalid config for [sensor.template]: Entity ID pm25 is an invalid entity id for dictionary value @ data['sensors']['aqi']['entity_id']. Got 'pm25'. (See ?, line ?).
aqi: - that forms the entity_id
That is the thing you should be changing
Set the unit of measurement to something to get a pretty graph
I thought that was user customizable?
what?
sensor names are entity_ids?
When you define a template sensor, the tag you use to define it forms the entity_id
You're defining sensor.aqi
If you want to add pm25 as specified in the homekit docs, add it there
aqi_pm25: for example
its working now, thanks
i have a bit of an unstable rest api i'm calling to get data in.. a few template sensors are based on input from this.. what happens is that if the rest api is not working correctly, then these integer sensors are reset to 0
can i work around that somehow?
because i have an automation that will trigger if the sensor increases
i have a template condition like this: "{{ trigger.to_state.state | int > trigger.from_state.state |int }}"
You could check to see if the state isn't zero?
0 is still a valid value.. most of the sensors are in fact 0
but what i want to catch is a value going from positive, non-zero to 0 and then back to the same positive, non-zero number
because that's what happening
Trying to trigger an automation when any input is selected except "None". Is this correct syntax?
value_template: "{{ not is_state('input_select.sonos_playlist', 'None') }}"
yes, but it will only trigger when the template evaluation goes from False to True
assuming you're using that in a template trigger
got it, yes, I am
the solution is to make the trigger a simple state trigger with that input_select entity ID and no to or from
then use what you have as a condition
assuming you want it to trigger any time the input is changed as long as it's not 'None'
I was worried that if I had "not None" as a condition, that it would not fire if None was the current input
yes, that is exactly what I want to happen
Like so?
alias: 'Play Sonos'
trigger:
- platform: state
entity_id: input_select.sonos_playlist
condition:
- platform: template
value_template: "{{ not is_state('input_select.sonos_playlist', 'None') }}"
yup, looks good
Config doesn't like 'None'
probably because it's a reserved python word
None
thought it might not be an issue since you're making it a string by using quotes
Should be fine in quotes
that's what i thought... what's the error Cosco?
getting errors in quotes too
Error loading /config/configuration.yaml: while parsing a block mapping
in "/config/includes/automation.yaml", line 478, column 7
expected <block end>, but found '<scalar>'
in "/config/includes/automation.yaml", line 479, column 72
you're missing the hyphen before alias:
if you're not using !include_dir_list for your automations then that's the problem
I can just use a word besides "none". I have a hypen, it is in the line above with id:, i just didn;t paste it, sorry
@spiral imp posted a code wall, it is moved here --> https://paste.ubuntu.com/p/Gr7j3Z49t8/
oh you have double quotes inside double quotes
that's an issue
this:
"{{ not is_state('input_select.sonos_playlist', "None" ) }}"
``` should be:
"{{ not is_state('input_select.sonos_playlist', 'None' ) }}"
~codewall @spiral imp
@spiral imp Rule #6: Please do not post codewalls (longer than 15 lines) - use sites such as https://hasteb.in/, https://paste.ubuntu.com/, or others.
Please take the time now to review all of the rules and references in #rules.
dat 2
Tried that and also tried changinh 'None" to 'Walrus' (just for fun), I still get this config error: Invalid config for [automation]: Unexpected value for condition: 'None'. Expected numeric_state, state, sun, template, time, zone, and, or, device @ data['condition'][0]. Got None. (See /config/configuration.yaml, line 118).
oh. platform: template under condition should be condition: template
forgot to mention that, sorry
so this:
trigger:
platform: state
entity_id: input_select.sonos_playlist
condition:
- condition: template
value_template: "{{ not is_state('input_select.sonos_playlist', 'None' ) }}"
no
sorry, just fixed it
yep, its working,. Have a few other things to sort out but the template is good
thanks
no prob
I created a template sensor to pull information from another sensor and do a little processing, I initially screwed this up and forgot to cast the result to a float so the first value in the history of my template sensor is a string so I'm unable to use the Lovelace history-graph card to show a plot of this sensor. Is there a way to delete the history of a given entity?
@vernal girder you can use SQLite to edit the database if you use default database to log events and states
@queen meteor Thanks, I deleted the entities completely and that got my plots working correctly.
I wonder if anyone could help me, I'm trying to create a button that would toggle between two scene, I have a scene called cinema_on and another called cinema_off . basically they just change philips hue tints. I couldn't figure how to make that work with a button card. I've been able to do something similar using the custom:button-card with a group but scene aren't working the same way it seem.
@latent spear #frontend-archived
thx!
what is this error all about Unable to load the panel source: /api/hassio/app/entrypoint.js.
my HA stopped working
hw to resolve
#330944238910963714 @edgy dirge
I'm using the bwalarm component and this used to work (on a much older version);
'ALARM TRIGGERED!!! {{ states[states.alarm_control_panel.house.attributes.changed_by.split(".")[0]][ states.alarm_control_panel.house.attributes.changed_by.split(".")[1]].name }}'
It now gives me;
Error rendering template: str: Invalid domain name ''
Any ideas?
Trying to write a template binary sensor based on users from tautullii that are actively playing something on plex instead of just paused....not sure how to properly loop over attributes for each user to determine teh proper Activity value. Anyone have any pointers on this?
each user shows up as an attribute but the value is in JSON {'Activity': None} so its a bit difficult to iterate
like if i just want to display which users are not None this code isnt working and just displays every single attribute even ones that don't have ['Activity'] attribute https://hastebin.com/dajofejabu.php
Hi - anyone know what I'd put in a template to get the number of hour since 06:00 each morning?
@heady crow
- platform: template
sensors:
kitchen_table_dimmer_state:
friendly_name: 'Kitchen Table Dimmer Last Button Push'
value_template: >-
{% if states('sensor.kitchen_table_dimmer_state_2')[0] == "1" %}
On
{% elif states('sensor.kitchen_table_dimmer_state_2')[0] == "4" %}
Off
{% else %}
None
{% endif %}
replace relavant info
@weary jasper sorry, not sure what tis is response to
didnt you want yes or no instead of off and on?
yeah sorry, confused me as you responded in a different channel
i thought it was something id have to do in the customize UI editor
ill try and learn how to make the above work for me
templates are powerfull but tricky to learn ....test in dev>template
yes sir
awesome
thank you for your help
more learning for me ๐
between has and nodered, crazy amounts of hours are lost
Hello, I need to add/delete a string from an input_text depending on an input_boolean
{% if is_state('input_boolean.deebot_cucina', 'on') %}
'{{states(''input_text.valuestanze'')}}Cucina, '
{% else %}
'{{states(''input_text.valuestanze'') | replace("Cucina,", "")}}'
{% endif %}
What is wrong here?
remove quotes ie:
- service: light.turn_off
data_template:
entity_id: light.kitchen
transition: >-
{% if is_state("input_boolean.boolean_evening_time", "on") %}
{{ states('input_number.evening_mode_transition_value') | int }}
{% elif is_state("input_boolean.boolean_movie_time", "on") %}
{{ states('input_number.movie_mode_transition_value') | int }}
{% elif is_state("input_boolean.boolean_sleep", "on") %}
damn i suk at pasting ๐คฃ
"{{ states('input_text.valuestanze') + 'Cucina, ' if is_state('input_boolean.deebot_cucina', 'on') else states('input_text.valuestanze') | replace('Cucina,', '') }}"
it is
if it's not working for you:
a) you are using it wrong.
b) the data you pasted is worg
c) ๐คทโโ๏ธ
I fixed it, thanks!
@rugged laurel show off
{% if is_state('input_boolean.deebot_aurora', 'on') %}
{{states('input_text.valuestanze') + "Aurora, "}}
{% else %}
{{states('input_text.valuestanze') | replace("Aurora, ", "") }}
{% endif %}
Why it doesn't add the space at the end?
๐ฆ
How about you tell the whole story, what are you trying to do?
I need to concatenate strings depending on 8 booleans flag
add if flag is on
remove if flag is off
if works, but when Adding, it doesn't add the space at the end....
"Aurora, "
--> This space
I read that jinja trims automatically
{% set bools = [
{"entity": "input_boolean.deebot_aurora", "name": "Aurora"},
{"entity": "input_boolean.deebot_cucina", "name": "Cucina"}
] %}
{% set stuff = namespace(names=[]) %}
{% for bool in bools %}
{% if is_state(bool["entity"], "on") %}
{% set stuff.names = stuff.names + [bool["name"]] %}
{% endif %}
{% endfor %}
{{ stuff.names | join(", ") }}
Expand the top part to fit your need
My problem was different
I need the space at the end
and Jinja trim it automatically
btw I fixed it, thanks!
If you are new to templates, there is something called Template Editor. You can write template code in that editor and test the results. Go to developer tools -> Templates, clear the text you see there and paste your code. Refresh page to restore defaults.
It is surprising that many folks donโt see the template editor until they come here. Hoping this pinned message will help (only if they care to read pinned messages).
@queen meteor do a server ping to all to notify
lol. It is not that urgent ๐
Although, it could be part of welcome message. Not that people read that too.
@queen meteor a required checklist ....know where dev templates is and etc and it only checks the box if you navigated to it
Oh man, love that idea. Not sure if discord lets you implement that way. @weary jasper
Discord should not let folks post any messages until they acknowledge some required things.
Could probably bot some things
@queen meteor make it happen sir ... you got my vote
Hi! How can I get the Device an entity belongs to within a template? I want to get a list of the device names of all the devices that have an entity with the attribute 'update_available' set to True.
The entity_id of the matching states are something like binary_sensor.0x1234567890ab_update_available, part of a device with the name 0x1234567890ab
(These are the zigbee2mqtt devices for which an OTA update is avaliable)
It would be more natural to loop over all devices and filter out the ones that have such an entity, but I see no documentation that devices are even accessible in templating.
@queen meteor very helpful!!! Thanks.
@lunar osprey 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.
@lunar osprey 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.
@lunar osprey Please use https://www.hastebin.com/ or https://paste.ubuntu.com/ to share code or logs.
Hi! an mqtt sensor with this config gives me:https://hastebin.com/ehumesepib
how can i get the sensor to show only the degrees?
Can it be done in the sensor with some kind of value_template or do I need to get it done in the automation publishing it?
Does anyone know if it's possible to list everything in a group as entities in an entities card?
It's not, not with a stock card anyway
@robust nexus timkerer is right, in case you don't know which custom cards enable it, take a look at auto-entities. Or see fold-entity-row for a different take on it.
is there a way to template a group so that it only includes switches that are on or a way to template a script to only turn off switches that are on?
If they're already off, turning them off shouldn't do anything
I use template switches to join my Sonos speakers. I have them all in group. I have script to turn off the group (unjoin all speakers), but doing this also stops music playing from the master speaker
Thanks @willow cosmos I'll take a look at them both.
I'm trying to set up some template sensors for a Tuya heater so I can track the on/off status over time, changes to the target temperature and current temperature better. I have some questions:
- For unit_of_measurement what is the syntax for degrees centigrade?
- For on/off do I need to do anything special or can I just specify no unit_of_measurement?
- Any other advice for getting values from Tuya devices?
Aware that may be a different kind of template to what is being discussed here!
I have this template that works on the dev tab but does not seem to work when I turn it into a sensor value template. Any advice?
sensors:
octoprint_time_elapsed_format:
friendly_name: 'Printing Time Elapsed'
value_template: "{{ states('sensor.octoprint_time_elapsed') | int | timestamp_custom('%H:%M:%S', 0) }}"
do you see any errors in the logs?
you could try giving entity_id.
Anyone that can help with - platform: history_stats?
I have it that my device is publising state now but the stats is still not counting
sensor:
- platform: version
history of flow meter
#daily
- platform: history_stats
name: flow_rate_daily
entity_id: binary_sensor.flow_state
state: ON
type: time
start: '{{ now().replace(hour=0).replace(minute=0).replace(second=0) }}'
end: '{{ now() }}'
Sorry... I'm not sure if this is the right area to post about this.
@stray cape state: ON likely should be state: 'on' (the quotes around on and the case are important)
Confirm the state at developer tools > states
Damn you are good.. THANKS @buoyant pine !!! it worked right away... I've been strugling with this for the last 2 days...
sadly... now that is working I'm realizing that it is not going to give me what I want.... DAMN... wasted so much time on this....
have to rethink this thing and find the right area to ask about it... THANKS a lot for your help!!!
No prob! Yeah, states are case sensitive and using quotes around them is a good idea (except for numbers in some cases)
will remember the next time LOL!!!
Hey guys I'm having a hard time with something that should be simple. I have a input_select that cycle between color names ("blue", "red", "green"...) but I can't make it work on a color_name. I use it like this:
color_name: "{{ states('input_select.light_color_cycle') }}"
And what I get on log is:
- Got unknown color {{ states('input_select.light_color_cycle') }}, falling back to white
Weird thing is that the same works on a notification with message: "{{ states('input_select.light_color_cycle') }}" - I get a notification with "blue" on.
Any ideas? Thanks!
@lofty sphinx looks like you're not using data_template:
But...you should share all the relevant code so we can see.
Please use https://www.hastebin.com/ or https://paste.ubuntu.com/ to share code or logs.
@lofty sphinx looks like you're not using
data_template:
@buoyant pine That was itthanks!
Lol no prob
I've been loving using state_filter card with the header_toggle...
I understand that we can't use header_toggle as an entity but is there a way to implement something similar?
I use it to turn of devices of choice off at night
yes
{{ dict((states.light|list)|groupby('state'))['on'] | map(attribute='entity_id') | list | join(', ') }}
That looks awesome. What goes in between (", ")?
Also where should I put this template? Binary sensor? ๐
Nothing.
As the value of entity_id in a script/automation
Nice, Ok I'll give it a go.
Thanks mate
{{ dict((states.light|list)|groupby('state'))['on'] | map(attribute='entity_id') | list | join(', ') }}
@rugged laurel Really awesome, thanks!
The template works in the template section in developer tools but sorry I can't seem to implement it as a script
sequence:
- data:
entity_id: '{{ dict((states.light|list)|groupby('state'))['on'] | map(attribute='entity_id') | list | join(', ') }}'
service: light.turn_off
Rule #1 of templating
Become a real Jinja2 Ninja! Don't worry my Genin, we are here to help! You can find the docs at https://www.home-assistant.io/docs/automation/templating/ - and don't forget rule #1! Please use https://www.hastebin.com/ or https://paste.ubuntu.com/ to share code or logs
I have tried data_template instead of data and it didn't work
Well, with data: it can't work
lol I did try service_template also but still no dice
Stop torturing me and give me the answer lol
This is the error
can not read an implicit mapping pair; a colon is missed at line 676, column 123:
... ity_id') | list | join(', ') }}'
^
How do you assign a switch template to an automation?
The quotes on the outside and inside of the template can't be the same
@upbeat saffron use the switch. entity?
@buoyant pine Thanks, I'd doing that, but the GUI doesn't show it as a device and if I remove the device_id I get a domain error
-> States for the list of all entities
The Devices and Entities views under Configuration don't show every entity in your system. If you want to see everything, look under Developer Tools then States.
Thanks @buoyant pine
sequence:
- service_template:
entity_id: "{{ dict((states.light|list)|groupby('state'))['on'] | map(attribute='entity_id') | list | join(', ') }}"
service: light.turn_off
Still not working
What's the error
All good, had to change service_template to data_template
Goes against the template rules #1
You must use service_template in place of service when using templates in the service section of a service call.
I guess not in this case....
Thanks anyway @buoyant pine
That's rule #2 ๐
yeah that lol
Now tell me, how can I specify which lights I was in that group instead of all? ๐
@lime olive you use service template instead of service when you're templating a service
You're templating service data in your template
Thus data template... so the docs are correct
I didn't even notice that you used service template there lol
For example:
service_template: "script.lights_{{ trigger.to_state.state }}"
Right! Gotcha now. I'll prob fall victim to this again next time
you could make a group of lights and iterate through that instead
or make a light.group and just use that
So I can't incorporate specific entities within this template?
Wait...why not just use entity_id: all here?
no filter named 'all'
Well I basically wanted to mimic the header_toggle on a state_filter card that I have.
I use it to switch off all the lights that are on before bed
and so Ludeeus came up with that great template
the code as provided will turn off all lights that are on
which was the original AC
yeah that's the problem now. I'd like to specify which because some are night lights
daytime
Also if I can somehow include other entities like scripts for my gate and garage switches etc that would be great!
To make sure they're closed
do other service calls in the sequence
{% set night_lights = ['light.honeywell_39351_zw3005_inwall_smart_dimmer_level'] %}
{{ dict((states.light|list)|groupby('state'))['on'] | map(attribute='entity_id') | list | reject('in', night_lights)| join(', ') }}```
for example, that works on my system
Yeah that look like it'll do the job nicely! Thanks mate
could put all the night lights into a group and make another list out of them if you wanted but that's the jist
phnx vs phoenix ๐
Lol didn't notice that ๐คฃ
lmao
That reject filter is kinda obnoxious. It's not super clear how it works from the jinja2 docs
Yeah. Most things (like filters) that are available in Jinja is not available in HA too. We have to explicitly code for them.
I was using this wait_template with my google home device:
wait_template: "{{ is_state('media_player.home', 'idle') }}"
And all was working as expected. Now i want to use that template with one of my echo devices and used this template:
wait_template: "{{ is_state('media_player.echo_show_5', 'idle') }}"
But i noticed the echo devices doesnโt go to idle state as it remains always in standby state so the template doesnโt work.
How to change that template to have the automation working again ?
Now the question is how can I incorporate this with the multiple domains into one script?
This obviously is a no go
sequence:
- data_template:
entity_id: "{% set ignore = ['switch.bedroom_power', 'light.night_light', 'media_player.bedroom_gh', '', '', '', '', ''] %}
{{
dict((states.switch|list)|groupby('state'))['on'] | map(attribute='entity_id') | list | reject('in', ignore)| join(', '),
dict((states.light|list)|groupby('state'))['on'] | map(attribute='entity_id') | list | reject('in', ignore)| join(', '),
dict((states.media_player|list)|groupby('state'))['on'] | map(attribute='entity_id') | list | reject('in', ignore)| join(', ')
}}"
service: light.turn_off
You cant light.turn_off a switch or media_player but you can homeassistant.turn_off a switch and light
seems it works for media_player too
Nice, can it also control other domains like mediaplayer?
For now my only solution was
sequence:
- data_template:
entity_id: "{% set ignore = ['light.office_1', 'light.office_2', 'light.office_3', 'light.cinema_1', 'light.cinema_2', 'light.cinema_3', '', '', '', '', '', ''] %}
{{ dict((states.light|list)|groupby('state'))['on'] | map(attribute='entity_id') | list | reject('in', ignore)| join(', ') }}"
service: light.turn_off
- data_template:
entity_id: "{% set ignore = ['switch.receiver_vol_up', 'switch.all_blinds', 'switch.bedroom_main_2', 'switch.christmas_tree_2', 'switch.porch_blinds', '', '', '', ''] %}
{{ dict((states.switch|list)|groupby('state'))['on'] | map(attribute='entity_id') | list | reject('in', ignore)| join(', ') }}"
service: switch.turn_off
- data_template:
entity_id: "{% set ignore = ['', '', '', '', '', '', '', ''] %}
{{ dict((states.media_player|list)|groupby('state'))['on'] | map(attribute='entity_id') | list | reject('in', ignore)| join(', ') }}"
service: media_player.turn_off
Oh ok cool! I'll do that instead then, thanks!
If you are turning the same things off every time then why not just create a scene? I have a bedtime scene that turns anything that should be off off
Good idea too but I'm constantly adding new devices that don't need to stay on when going to bed or when we leave the house (arming the alarm)
This way I'm not gonna have to add new devices, just add the ones I'd like to ignore
nifty
Hello
I have this code snippet
params:
cleanings: >
{%- if is_state('input_boolean.deebot_times', 'on') -%}2{%- else
-%}1{%- endif -%}
rooms: >
{{states('input_text.idstanze')[:-1]}}
I got this result...
('async_send_command %s (%s), %s', 'spot_area', {'cleanings': '2', 'rooms': '6'}, {})
instead I should have this one
('async_send_command %s (%s), %s', 'spot_area', {'cleanings': 2, 'rooms': 6}, {})
without the apex next to 2 and 6
how shall I do it?
I'd like to have a sensor to show if the coffee machine is brewing or just warming. the wall plug reports power so I can template from that - but the pattern is like "if power > 0, then if power > 750w for more than 45 s = brewing else keeping hot"
basically: is there a "duration parameter" in templates?
or do I need to create a helper sensor and an automation that set the helper sensor's state after a duration?
750w? Jewsus Christ do you have an industrial coffee machine? 
Many are like that actually
@buoyant pine really? I have a medium sized brewer, I'm would be surprised if it pulled more than 200w when heating
Yeah, my small single-serve one is 650W, the large 12-cup one is 1200W
hmm, i haven't checked to see what mine is
Gotta heat that bitch up real fast
Yup
lol
instant water heaters are intense
Also why kitchens in the US at least have been required to have 20A circuits for a long time
mine is 1500w apparently
Which is a lot at 110v, not that bad at 220v
12.5 A at 120V
13.636A
Which in Norway would mean a second level fuse in older houses
It's 120 at the outlet...with resistance it might go down to around 110
ah ok
We used to have mostly 10a, then we got 13a on the same wires, but 16a would be one step up in wire diameter, and 25 would be even one more step up
still sub 20 ๐
Yup
{{ states.light | count }} <-- this will count all entities under the light domain. But is there a way to just count them that isn't Unavailable ?
{{ states.light|rejectattr("state", "eq","off")|list |count }}
change off
and probably change all the quotes, i was lazy
Oh thanks!
when adding two values I need |int for the sensor value right?
int or float
otherwise you get string math which is the bad kind of math
"4" + "5" = "45"
ah |float
ok
thanks
and to get this senor updated I add entity_id: of one sensor
preferably the one that changes most of the time
right?
value_template: "{{ (states('sensor.sonoff01_momentane_leistung'))|int + (states('sensor.sonoff02_momentane_leistung'))|int + (states('sensor.fibaro_system_fgwpef_wall_plug_gen5_power'))|int }}"
``` will result in the template sensor updating if any of those update
cool thank you
as a part two of my question earlier, the pattern on the coffee machine is like this:
https://imgur.com/a/x91qPRc
..so full power for like 3,5 minutes while brewing, then full power for ~20 secs every five minutes.
the goal it to show "brewing", "keeping warm", "off" to for use on dashboard and in automations.
hmm.. suggestions on how to make some kind of smart template sensor showing the status from that?
..or maybe it's time to change to #automations-archived
you could probably get complex with a template, but the simpler solution would just be "heating" vs "not heating"
First attempt at templates and not really getting it. I want to loop through my sensors to extract information about my GitHub repos but I'm struggling to even identify which sensors are repos in the first place.
I've got this so far, ({{ sensor }}) will be replaced with more meaningful data once I can select the sensors I want.
All repos:
{% for sensor in states.sensor %}
{% if state_attr(sensor, 'latest_commit_sha') %}
{{ sensor }}
{% endif %}
{% endfor %}
Any ideas how I fix the loop to identify repos?
What math is used to make an sensor based on battery charging and battery level to make an sensor say average battery chargign time
Can anyone please help?
"{{ dict((states.media_player|list)|groupby('state'))['on'] | map(attribute='entity_id') | list | join(', ') }}"
how must it look like, if i need state 'on' and state 'playing'?
must?, have no clue... can, like this:
"{%set c=namespace(e='entity_id',o='on',p='playing',d=dict((states.media_player|list)|groupby('state')))%}{{((c.d[c.o]|map(attribute=c.e)|list)+(c.d[c.p]|map(attribute=c.e)|list))|join(', ')}}"
This is cool. Thank you very much!
Hi guys, is there a template I can use to manually colorloop some lights using hs_color? Thanks
There's no media_player template is there?
I know there's the Universal Media Player but it's a bit unclear whether it can do what I want it to...
Well, what do you want to do?
I have my TV setup like so:
- TV has Xbox on HDMI1, 5x1 HDMI Switch on HDMI2
- HDMI Switch has Nintedo Switch, PS4, etc on each input
- I have a Logitech Harmony Hub
I'd like to expose Xbox, Switch, PS4, etc as Sources for a Media Player on Homekit
So the Harmony would set the TV input and the Switch input by Activity
And I'd get the TV as a Media Player with On/Off, Volume and Sources for those in Homekit
It's a little unclear as to how the sources part of the UMP works though...
Oh, can it take an input_select?
Unless there's a way to change sources with that HDMI splitter in home assistant I don't think that'd work
That's what the Harmony Hub is for
Ah
Granted it does also have RS232
This example on that page shows how to handle sources: https://www.home-assistant.io/integrations/universal/#chromecast--kodi-control-with-switches
Yeah, though it takes an existing source list there. Did find a thread that seems to indicate it can take an input_select though which is what I'd want ๐ค https://community.home-assistant.io/t/help-for-a-universal-media-player/84607
Assuming that's correct
Gonna need quite a few helpers I suspect lol
Hi
I want time offset in given template
{{ states.sensor.time.state == states("sensor.dhuhr") }}
What offset?
Like, i want to trigger this template about after 1 hour, or before 1 hour
Like below example
{{ as_timestamp(strptime(states("sensor.time_date"), "%H:%M, %Y-%m-%d")) == as_timestamp(strptime(states("sensor.islamic_prayer_time_dhuhr"), "%Y-%m-%dT%H:%M:%S")) + 3000}}
This example runs after 50 minutes or 3000 seconds
What is the state of sensor.dhuhr?
And ... what is the state so we don't have to play guesswork ๐
I used this in automation. Which works and trigger on time, when this templates ==
{{ states.sensor.time.state == states("sensor.dhuhr") }}
"Sensor.dhuhr" is time afternoon time. It changes daily and gets latest time from aladhan website, using api
But... without knowing the actual state value you're seeing, it's incredibly hard to help you
Is it HH:MM or HH:MM:SS or ... what?
@alpine surge posted a code wall, it is moved here --> https://paste.ubuntu.com/p/h3WYv3B2dY/
~codewall @alpine surge
@alpine surge Rule #6: Please do not post codewalls (longer than 15 lines) - use sites such as https://hasteb.in/, https://paste.ubuntu.com/, or others.
Please take the time now to review all of the rules and references in #rules.
Ok
- platform: rest name: "Prayer Times" json_attributes: - data resource: "http://api.aladhan.com/v1/timings?latitude=24.9307479&longitude=67.0674637&method=1&school=1" value_template: '{{ value_json["data"]["meta"]["method"]["name"].title() }}' scan_interval: 86400 - platform: template sensors: dhuhr: friendly_name: 'Dhuhr Prayer Time' value_template: '{{ states.sensor.prayer_times.attributes.data.timings["Dhuhr"] | timestamp_custom("%H:%M") }}'
Actually, i pasted to show you all.
'{{ states.sensor.prayer_times.attributes.data.timings["Dhuhr"] | timestamp_custom("%H:%M") }}'
This is H:M
And you want an offset of 50 minutes?
I want given time offset, like 50 minutes after, or sometimes 1 hour before
Whatever we enter in - or + offset
Enter where?
Like in this given example
Like below example
{{ as_timestamp(strptime(states("sensor.time_date"), "%H:%M, %Y-%m-%d")) == as_timestamp(strptime(states("sensor.islamic_prayer_time_dhuhr"), "%Y-%m-%dT%H:%M:%S")) + 3000}}
- 3000 second mean 50 minutes after this template will execute
Same like, i want in my template
{{ states.sensor.time.state == states("sensor.dhuhr") }}
But it sounded like you want a variable offset, not a fixed offset
Yes
So... input_number?
{{ states.sensor.time.state == states("sensor.dhuhr") +3000 }}
Like this
But is not working
You'd need to compare timestamps at that point
Which is quite do-able, but not trivial
Yeah time offsets in templates are kinda tricky
Well, easier with dates, since you can convert to timestamps
Here you'd have to add the current date, convert to a timestamp, do the maths
Yup...fun stuff
Like below example
{{ as_timestamp(strptime(states("sensor.time_date"), "%H:%M, %Y-%m-%d")) == as_timestamp(strptime(states("sensor.islamic_prayer_time_dhuhr"), "%Y-%m-%dT%H:%M:%S")) + 3000}}
In this template
Whatever i enter + or -
Yup, that's easier since it has a date
Hhmmm
@arctic sorrel like this
{{ as_timestamp(strptime(states("sensor.time_date"), "%H:%M, %Y-%m-%d")) == as_timestamp(strptime(states("sensor.islamic_prayer_time_dhuhr"), "%Y-%m-%dT%H:%M:%S")) + 3000}}
yes
{{ as_timestamp(strptime(states("sensor.time"), "%H:%M")) }}
``` does give a value, I wonder if
{{ as_timestamp(strptime(states("sensor.dhuhr"), "%H:%M")) }}
Try it, see if you get some values that are vaguely similar
Ok thanks.
The timestamp is going to be negative, because of the lack of a date
{{ as_timestamp(strptime(states("sensor.dhuhr"), "%H:%M")) - as_timestamp(strptime(states("sensor.time"), "%H:%M")) }}
``` should, if `dhuhr` is in the future, give a positive value that's relatively small, or negative value that's relatively small if it's in the past
If that works, it comes down to how you want to manage the variable offset - specify in minutes, use https://www.home-assistant.io/integrations/input_datetime/, or what
Hi, how can I ask for or condition like this: {{is_state(('binary_sensor.motion_sensor_bedroom_right', 'off') or ('binary_sensor.motion_sensor_bedroom_left'))}}
it says Unknown error rendering template
is_state((
``` ๐ค
{{is_state('binary_sensor.motion_sensor_bedroom_right', 'off') or is_state('binary_sensor.motion_sensor_bedroom_left','off')}}
and
Replace or with and 
for example: (A and B) or (C and D)
Just like that
It's worth reading the templating docs ๐
It links to the Jinja2 docs, which explain a lot too
yeah I know for all operators, Im on the templating docs, but some more complicated examples are arising ๐
It's basic logic
Don't try to make up operators, and remember that templates may be slower than "standard" triggers or conditions
Templates can be overly complex ๐
Here's some fun templating for you @sonic nimbus: https://github.com/Tediore/My-HASS-config/blob/master/conf/automations/speaker_volume.yaml
Lol
this is similar to my picker for radio stations with these elif's ๐
I view templates like regex - possibly the only solution, but should rarely be the default solution ๐
Yeah this is for a very specific automation involving several variables
Used to be 10 or so separate automations which is a PITA to manage
I would be always for more complex code and much less lines of code..
it's kind a easier..
or
is_state('binary_sensor.motion_sensor_bedroom_right', 'unavailable'))
and
(is_state('binary_sensor.motion_sensor_bedroom_left', 'off')
or
is_state('binary_sensor.motion_sensor_bedroom_left', 'unavailable'))
}}```
here is my and/or query ๐
{% set off_states = ['off', 'unavailable'] %}
{{ states('binary_sensor.motion_sensor_bedroom_right') in off_states and states('binary_sensor.motion_sensor_bedroom_left') in off_states }}
thanks @dreamy sinew much more elegant ๐
Can I take a mqqt value that is "1" and make it into OK/NOT_OK with the data/value_template?
under the mqtt platfom
{{ "OK" if whatever == 1 else "NOT_OK" }}
There are, of course, many MQTT integrations
what do you mean? mqqt lights, etc?
Yes, I am trying to use mqtt for everything now
rtl_433 in this case
I am trying to find the differnce between a dat atemplate and a value template...
Which
Integration
are
you
talking about
There's a load of them, and being vague isn't helping us help you
Context in each may be different
Oh, I thouhgt I said platform: mqtt
" - platform: mqtt"
OHhh sensor, sorry
The fsck are you talking about
Finally
That only has value_template - no data_template
So now I'm even more confused
howso?
I am trying to find the differnce between a dat atemplate and a value template...
rtl_433 spits out ambient waether data to mqtt
Well, I'd start with when supported by the integration in question
That's like asking when would you use a hammer
when you want to bang things
Please stand up a little straighter then ๐
I don't know the difference between a value template and a data template
Find an integration with both, and then we can continue the conversation
I'm all for existential discussions, but this one ....
make the inside quotes single quotes
and "value" is like a self.value reference, correct?
assuming value is defined
Here's what I am not understanding...
I want to transform the data as it comes in to OK from a 1 or 0... if I put value_template: "{{ 'OK' if sensor.master_battery == 1 else 'NOT_OK' }} .. isn't that self-referential??
The data coming in is a "1".. I can't change that data to 'OK', or it's not 1 anymore...
how do I say "whatever value I get from mqqt"
oh this is regarding mqtt. i have no clue then. i was just validating syntax lol
you might need to use a template sensor then to display whatever value you want. not ideal as you said but it might be the only choice
wait, 1 or 0? is it a binary sensor?
might as well give it a shot with the value template using value like you did
no, not a binary sensor, but maybe i can treat it that way?
oh look.. safe mode ๐ (remove those double tikcs LOL)
Well, they successfully say "NOT_OK" now on the dash... but it's wrong of course
what do you mean?
I mean the data coming in is indeed a "1", but HA is saying NOT_OK
but value =/= 1 if value isn't a variable for this input
1 != "1"
correct... it's just coming in as 1 I presume?
value_template: "{{ 'OK' if value == '1' else 'NOT_OK' }}"
ditch the quotes around the 1
'1' is a string, 1 is a number
oh.. dang
he tried the number first
ah. then yeah try whatever you didn't do
i haven't tried what works... let's try that ๐
just a heads-up all states in home assistant are stored as strings
not sure how things work with mqtt specifically though
which is stupid obnoxious ๐
ohhh.. important to know
but then, everything that comes out of a template is a string so... ยฏ_(ใ)_/ยฏ
yup
that makes sense... python underneath, right?
python doesn't care
what's fun is that state attributes aren't always necessarily strings
oh jeez go away
nope, python has standard types
hahah...
Maybe that's why I liked perl so much back in the day... befoe I knew data types
python interprets down to C iirc
AHHA!!! Now it's working correctly!
Thanks fellahs! @arctic sorrel gave up on me, but he helped a lot
example of state attribute that is not a string
I gave up on your being vague and confused ๐
VERY confused
heh state attrs can be objects to make it even worse
woooof. let's build that bridge when we get there
/r/boneappletea
that's an proper idiom
burn that bridge when we get tehre is a brooks and dunn song ๐
i've only ever heard "let's cross that bridge when we get there" lol
now you got me thinking
Burn that bridge
I'm a fan of that one
oh no, I am wrong it seems
thanks!
