#templates-archived
1 messages ยท Page 87 of 1
so timestamp_local doesn't work on ios?
no
if I use timestamp_local it works fine on windows but on iOS I just get Invalid Date
what's your timestamp_custom look like?
value_template: >-
{% set hours, mins = value_json.ProgramEnd.End.split("h") %}
{{ (now() | as_timestamp() + ((hours | int*60*60) + (mins|int*60))) | timestamp_custom('%Y-%m-%dT%H:%M:%S', true) }}
T is needed for iOS i guess
When I remove the "T" between Date and Time it doesn't work in iOS
is timestamp_custom the right time in android/windows?
or is it offset like ios?
cause you could just add an hour
is it possible your ios is set to the wrong timezone but the right time?
no
๐คท
is set to the correct time zone, 24h and "auto"
and this happens on Chrome, Safari and the App on the iPhone.
Chrome on Windows 10 comupter is working fine.
If I open the entity it looks correct. But the value in the card is wrong at all.
If I use {{ (now() | as_timestamp() + ((hours | int*60*60) + (mins|int*60))) | timestamp_custom('%Y-%m-%dT%H:%M:%S', true) }} it works on Windows but is +1h in iOS because it adds an extra hour because time zone is UTC+1. But this only happens on the card.
If I open the entity, it has the correct time
How to paste a picture?
imgur, link it here
As you can see... the time is 16:27 .. duration of washing machine is 13min so it should finish at 16:40 ...
is that an entities card?
try a different format
Valid values are: relative, total, date, time and datetime.
i use "time" because I only want to see the time (wihtout date)
try datetime, see if it's the right timezone...would at least narrow the issue down
Wohooooo I got a solution!!!
๐
value_template: >-
{% set hours, mins = value_json.ProgramEnd.End.split("h") %}
{{ (utcnow() | as_timestamp() + ((hours | int*60*60) + (mins|int*60))) | timestamp_custom('%Y-%m-%dT%H:%M:%S+01:00', true) }}
I now use utcnow() to get it as UTC time. Then add "+01:00" manually (not %z as it would) and then say true that is is local time. In this case Windows and iOS showing the same time
but this is really a wired issue.. that shouldn't happen.
@pseudo musk thanks four your support! ๐
"{{ states('sensor.date_time') < (state_attr('input_datetime.fiffi_aufwachlicht_de_aktivieren', 'timestamp') | int | timestamp_custom('%Y-%m-%d, %H:%M', True)) }}"
Can anyone help me with this template? I want a result of true, if the input_datetime is in the future.
Got it working
is there a way to loop through all of a specific type of device in a template, for example, all device trackers?
Go to
-> Templates
There's an example there for sensor
For loop example:
{% for state in states.sensor -%}
perfect
would that dynamically update?
Depends entirely on the context
So, yes, but no, but maybe
trigger โ
Elsewhere, most likely
i was looking to use it in a condition on an automation, so should work for me right?
should work in a condition
i'm trying to filter on connections to my guest wifi...
{% set guests = states.device_tracker | selectattr('essid', 'equalto', 'GUEST') | list %}
{{ guests }}
guests is [] ๐ฆ
Test it in Templates
yea, thats what i'm doing...i can use selectattr('state','equalto','home') and get everything on my wifi, but when i try to filter on the essid attribute, it doesnt seem to work
{{ dict((states|selectattr('entity_id', 'in', state_attr('group.my_downstairs_windows', 'entity_id'))|list)|groupby('state'))['on']|map(attribute='name')|list|join(', ') }}``` is one I use
is it a different function to get an attribute over state?
ahhh...attributes.essid ๐
umm...stupid question..but how do you do the opposite of selectattr(... 'equalto') ? i found rejectattr online, but cant seem to make it work...
What are you trying to do?
from my list of dtrackers, i need to exclude one...bascially, my son has 24 hour nursing because of a disability, and there is one device always on the guest network, the nurse's tablet they use to chart with, but i'm trying to determine if anyone is in the house by counting devices connected to guest, excluding that one device
yea, i was able to do it in a loop, i was trying to do it in the initial selection if that was possible
filtered_list | filter_further_here_by_excludingsomethingsomehow
Why don't you share what you're doing, so we don't have to guess ๐
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
i did above already
{% set guests = states.device_tracker | selectattr('essid', 'equalto', 'GUEST') | rejectattr('attributes.entity_id','device_tracker.android_3ab9bf0a993f40b5') | list %}
{{ guests }}
just want one more filter before | list
It doesn't have attribute you can use to reject it with?
https://jinja.palletsprojects.com/en/2.11.x/templates/#list-of-builtin-filters are all the default filters, HA has more
i tried rejectattr() and kept getting a test by that name doesnt exist or something
Yeah, except the entity ID isn't an attribute
perfect
i couldnt find "NE" when i was searching for negating equalto lol
my googlefu is weak
It helps to know what to search for
true story
is there a startswith? ๐
nevermind, i'm trying to abstract this out too much.....
hey guys, need some help ๐ i'm stuck with the template: 3 switches action 1 light. https://hastebin.com/ohidowaruj.coffeescript
(not a programer, but i learned alot in 2 weeks ๐ )
no one ๐ฉ
@tender junco gotta have patience for peopel to come around....on first glance it looks like you added your sensor with your lovelace? if so that is not correct.
why? because the first light it's working everything (room pictures, light pictures) just like i want
@tender junco it looks like you are mixing and matching the front end code with backend code.
The code ```yaml
- platform: template
switch:
hol:
...
aaaahaaa, oky, that's a step forward for me ๐
and the template code is right?
ty
@queen meteor
the template code also contains lovelace code in it
hmmm, how can i identify the backend/ frontend code?
documentation should be the primary source of information for it.
If you follow documentation and sample code as-is, you cannot go wrong. If you add your own stuff, it might not work
yeah i read it, but i put all in lovelace because i don't know what goes where ๐ฆ
ok - are you using GUI to add/edit lovelace?
no, i write everything in vscode
ok - great. Then, all the lovelace code goes into the lovelace files, and other stuff can go in configuration.yaml or packages...etc
@tender junco browse through my repo to get an idea - I have all lovelace code in a folder called lovelace, and everything else in packages folder. https://github.com/skalavala/mysmarthome
the frontend code goes into lovelace. all the templates, sensors, automations, scripts, scenes goes into other files
i will ๐
the frontend code goes into lovelace. all the templates, sensors, automations, scripts, scenes goes into other files
@queen meteor ok, i try to understand them wher goes where
one more question
i learned about c++ in my highschool
ok - good!
unfortunately, you cannot.
i don;t want to write everything in conf .yaml
Home Assistant uses two languages - YAML and Jinja. YAML is a descriptive language, where as Jinja is the more dynamic python templating language
all the configuration is typically in YAML, and automations, scripts...etc can have jinja code to do dynamic stuff - like accessing run time information, finding out what triggered an automation, call scripts, and access and pass parameters...etc
good, ty for all the good info you ave me, now i know what to search for and where
The C++ templates has nothing to do with Jinja templates
try spending time in browsing code in others repositories and see how they are using it... that should give you some idea.
if-else ๐
yes, you can have loops, if/else conditions...etc in Jinja
ok, so good so far.
i want to automate my apratment, not only light, i got thermostats that i want to integrate into HA, my roles and my AC
on what should i go
yaml or gui
?
yes, everything is possible. first, make sure the thermostat you have in your apartment is supported in HA, If it is, copy and paste code in your config by providing information like IP addresses, user, password...etc should get you started.
You can use either - GUI or YAML. Both options are supported.
the thermostat is not yet suported by HA, they are silvercrest, but i found an app that could work with HA
or plugin
smth like that
You are going to have to do some research on that to bring it into Home Assistant. If there are custom components, you should be able to bring it inside HA.
I have some custom components that I use - that should give you some idea as well. All the custom components are usually under custom_components folder
yesterday i installed hacs, so that should help me with my plugin you say?
I am not a hacs user, but if it is available via hacs, you are good to go!
ok, thank alot for all of this, i will do some research on your link, but i need help in the future if smth i wond understnd
๐
yes, you can always post your question here - someone will be able to help you if they have information
thank you again, see you around and have a good night
or day
depending where you stay
๐
thank you! ๐
how can i make a template sensor that updates but based on time?
- platform: template
sensors:
decorative_night_lighting_on:
entity_id: sun.sun
friendly_name: "Exterior Decorative Lighting Is On"
value_template: >-
{{ state_attr('sun.sun', 'elevation')|float < 0 and now().hour < 23 }}
It gives me the right value, but doesn't update
hello i woud like to make a template but i'm stuck, Im using rest API to get data from wierguar, and i want so make a sensot to get last handshake data => to make an automation. Right now im here: {{states("sensor.rest_sensor")}} and my output is {"AiPhone":{"endpoint":"x.x.x.x:15614","latest_handshake":1584083263,"transfer_rx":1367360,"transfer_tx":6566120},"LiPhone":{"endpoint":"x.x.x.x:3234","latest_handshake":1584083123,"transfer_rx":2134544,"transfer_tx":25109900}} i woud like to get for each device the last handshake time in diferent sensor. can somboyd help me?
Guys, I'm stuck with accessing the right attributes from json rest api.
Please have a look here?
https://paste.ubuntu.com/p/KmNb3VN7Nq/
๐คทโโ๏ธ
@coarse sable I struggled with the same. This may help https://github.com/home-assistant/core/issues/32064
I still don't think I understand the json_attributes
the value_template definitely does not look right
anyone have an example of value_template that joins data from multiple entities with wildcard? ie. i have multiple ( around 50+ z-wave devices that go along: sensor.light__*_kwh_meter that i would like to join into one sensor
so I rather not type them manually out ๐
@fast vigil Definitely thanks for your info. I don't think that bug is relevant though.
I am simply(?) struggling with how to reference the JSON attributes in the REST data.
The value_template is based on the docs for the rest sensor platform.
Is this the right way to reference connected ?
{
"connections":{
"76Y7FMR-BXLYM4E-2FPKPU6-GMLUVJN-MMK6UWN-VBCQ7IA-6RIRBEF-YHY5KAM":{
"at":"2020-03-13T16:40:54.026157492+01:00",
"clientVersion":"v1.3.4",
"connected":True
}
}
}```
Is it possible to run a for loop in yaml to declare my sensors? I've got 96 sensors that I declare that normally I'd use a for int loop to interate through in javascript
@coarse sable looked i to it yesterday. It is not a valid json.
Try pasting the json in jsonlint.com
I did, the only errs i noticed were Caps related?
I've been running the above code these last few hours...seems to function, even tho it ain't pretty
@queen meteor jsonlint is also pointing to capitalization errors. (i.e. True should be true ).
is that the output for state_attr('sensor.syncthing_connections','connections')["76Y7FMR-BXLYM4E-2FPKPU6-GMLUVJN-MMK6UWN-VBCQ7IA-6RIRBEF-YHY5KAM"]["connected"]?
the one you pasted above
yes
that is working...but I feel this isn't the way to do that?
I guess i'm just not getting the jinja way of referencing values from a json dictionary
well that is definitely the way to parse json
state_attr('sensor.syncthing_connections','connections')["76Y7FMR-BXLYM4E-2FPKPU6-GMLUVJN-MMK6UWN-VBCQ7IA-6RIRBEF-YHY5KAM"]["connected"] returns true?
yes... well...it returns True
i'm frustrated that it took me just about 24h to get there.
isn't that what you are looking for? or you just want to see if there is a better way to get it?
yes and yes
well, I did not realize that is what you were looking for earlier...I thought you were struggling with json_attributes
no worries.
look at the positive side....you learned a little :p
yes, but only if this is the correct way, and not some kludge I stumbled upon.
well that is a correct way
argh, lol
it just looks ugly as you have the huge string there
wel, i tried replacing that with things like [1] but no joy.
and in the end-result, the huge string ain't so bad in a packege file.
also that can lead to bugs as the order may change
yes
so I would leave the string there
it is not the most elegant looking template, but it works
not that I did much
on a separate yet related note, digging into this I came across https://jsonformatter.curiousconcept.com/
Which seems pretty nice, specially compared to the spartiate jsonlint.com
yeah, that is what I use
I thought the json_attributes thing should be able to handle something like that....if we cna figure it out
json_attributes wasn't choking on True vs true to be fair.
it is the same structure...so the rest sensor should be able to get all the sensors
ok I see
the problem is the unique strings
i wasn't getting errors, just no result...because I wasn't finding the proper syntax to get to that damn connected key.
yeah, without the string identifiers, no way to get to the connected key
anyways, you have something for now ๐
The real problem was/is between chair & keyboard.
@coarse sable after I fixed the json, I was able to access attributes last night... if you have control over how the json is created, you may want to use array instead of nodes
when creating the json structure, think about how you are going to access each and every piece of data easily - think about indexing, lists, attributes and hierarchy.
@queen meteor is it possible to refer to the first element?
without specifying the entire string
it is not an array - no easy way to refer to it unless you use the key. you could use a for loop, and access first item
I thought the recent change to rest sensor where we could specify json_attributes was supposed to do that.
json_attributes makes it easier to directly access data - I think you can also choose to ignore and go DIY route, where you specify the full path
I am trying to make a standard notification for my light automations, I am printing it to a slack channel
What I would like is to be able to create a template that print out the name of the automation not what triggered the automation
but how do i get the alias of the automation to use in a template within the automation?
quick one ๐ ... I do have one sensor with attributes like this:
memory:
free: 71
cache: 8
buffers: 1
used: 20
storage:
internal:
- name: system
used: 11
how to reach memory -> used in the template sensor ?
this does not work and gives 0.0: value_template: "{{ (state_attr('sensor.fibaro_hc2_diagnostics', 'memory.used') | int) | round(1) }}"
any idea why this wouldn't properly update itself?
power_light_kwh:
friendly_name: Light Usage
entity_id: sensor.time
unit_of_measurement: kWh
value_template: >
{% set ns = namespace(states=[]) %}
{% for s in states.sensor %}
{% if s.object_id.startswith('light') and s.object_id.endswith('kwh_meter') %}
{% set ns.states = ns.states + [ s.state | float ] %}
{% endif %}
{% endfor %}
{{ ns.states | sum | round(2) }}
sensor.time should make it update value every 1 min?
unless i need to add sensor.time
Q.Q
what are you trying to do?
do you get the right value when you test it in template editor?
try manually updating the sensor using homeassistant.update_entity
that should update the value
that will consume unnecessary resources. I would just create an automation to update the sensor every 30 seconds or so
sensor.time updates every 1min
small step ahead ๐
value_template: "{{ (state_attr('sensor.fibaro_hc2_diagnostics', 'memory').used | int) | round(1) }}"
this works for memory -> used
but if there is one more level below don't
value_template: "{{ (state_attr('sensor.fibaro_hc2_diagnostics', 'storage').internal.used | int) | round(1) }}"
can anyone guide me ?
how does the hc2 sensor look like in HASS?
@fallow quarry posted a code wall, it is moved here --> https://paste.ubuntu.com/p/rCQGFZN3nq/
thank you ๐ works ๐
np
@fast ginkgo you could also use entity_id: sun.sun instead of entity_id: sensor.time
could anyone give me a hand for a data_template in an automation?
@rose reef what do you need?
show the code?
just getting it ๐ 1 sec
@rose reef posted a code wall, it is moved here --> https://paste.ubuntu.com/p/kzdr6z3DHc/
can you see that paste link?
so I've tried manual data and that works
all I can think is the template content is wrong :/
is it definitely states.?
have you tried in template editor?
you should use {{ states('input_text.assistant_command_text') }} instead of ```
{{ states.input_text.assistant_command_text.state }}
ahhh I shall try
i'm getting responses, but it's like the wrong data is being passed
thank you @queen meteor that worked
@queen meteor do you know if there's a way to stop it triggering again when the text input is emptied? I'm currently getting around it by turning the automation on and off
@rose reef posted a code wall, it is moved here --> https://paste.ubuntu.com/p/bhjPTBtKTT/
Have a condition and check for empty
gahhh @queen meteor I came back to add the condition and now neither the trigger or the service call are working
Post code?
@rose reef posted a code wall, it is moved here --> https://paste.ubuntu.com/p/Nr2x9jq2kN/
haven't added the empty check in yet as I was trying to get this workiong again
@queen meteor i'm restarting HAss as it's being funky
@rose reef your automation code has changed somehow - maybe it is the UI editor doing it. quotes are missing from the data_template code.
ah yeh
but it's not even triggering now
I assume it doesn't need specific quotes @queen meteor ? Just appropriately matched
that's why it is not triggering. paste the code as-is for data_template ```
- data_template:
command: "{{ states('input_text.assistant_command_text') }}"
service: rest_command.assistant_relay
the bad action would make it fail to trigger?
also, if you want to add condition, you can add something like: ```
condition:
- condition: template
value_template: "{{ false if states('input_text.assistant_command_text') | string | trim == '' else true }}"
instead of
condition: []
the bad action would make it fail to trigger?
yes, it does. it will throw errors in the log and may fail to run altogether
@rose reef posted a code wall, it is moved here --> https://paste.ubuntu.com/p/kMrTJKjsKR/
no luck :/
double check after saving in the UI editor. it may have added or removed quotes.
what editor are you using to edit code?
do you see any errors when you run config validation?
i've cleared out the assistant relay stuff
so it should just clear the text field when it's updated
and that's not even triggering
oooh
something in the logs
oh no it's an old one
ok @queen meteor , I've got it working, somethign was seriously up as I had to delete and re-created it
@rose reef posted a code wall, it is moved here --> https://paste.ubuntu.com/p/YFtR6HdwNF/
the condition isn't working to debounce it though
i'll come back to this tomorrow
thank you
I'm creating a template Switch for my Android TV. To create a on/off toggle switch. I'm setting up the value_template, which would normally have an 'on' state. But Android TV has standby, playing, paused and idle instead of on
Can I set the value template to be true if state is any of the 4 states?
I'm trying just listing 4 states, but that's not working
Ok found it, I need to separate each with an OR
@queen meteor @fast vigil the json is the result of a rest call to a Syncthing https://syncthing.net/ host . My sensor's conf is here : https://paste.ubuntu.com/p/KmNb3VN7Nq/
I don't see a proper way I could manipulate the json result, perhaps faffing about with my sensor in HA. But...would that be worth it ?
hi guys good afternoon. I have a csv with this values
Home Assistant notifications (Log started: 2020-03-15T00:41:36.229161+00:00)
20,1
29,1
24,5
22,7
15,1
how i can read this values with template?
platform: file name: 'Acurite Barometric Pressure' file_path: /config/externaldata/acuriteweatherdata.txt value_template: > i dont know what i can put here unit_of_measurement: 'inHg'
@mighty void {{ states('media_player.whatever') in ['playing', 'paused', 'standby', 'idle'] }}
@buoyant pine Ohh, that's a lot shorter than what I came up with. Thank you, I'll plug that in
@thick cipher put ```yaml
value_template: "{{ value }}"
@queen meteor but this file has 5.. i need do create 5 sensores each sensor read one value.
that's not how it works... it only loads the last value.
so .. i changed
{"date":"2020-03-15 15:39:00"; "value":"20,4"}
{"date":"2020-03-15 15:39:01"; "value":"30.4"}
{"date":"2020-03-15 15:39:02"; "value":"34.5"}
{"date":"2020-03-15 15:39:03"; "value":"56.4"}
is it possible read each value ?
or only the last value ?
not with file sensor. file sensor is designed to read only the last value.
what sensor can i use?
you may have to write custom code for it. Easier using python_script, where you can create a bunch of sensors easily by reading file contents.
ohh, i though that was easier.
@thick cipher something like this in python_script should work. this is a pseudo code and may not work. Just to give you some idea...
f = open("file.txt", "r")
index = 1
for item in f:
hass.states.set('sensor.temp_' + index++, item, {
'unit_of_measurement': 'inHg',
'friendly_name': 'Temperature'
})
that should create a bunch of sensors with temp_1, temp_2 ...etc based on number of entries in a text file.
check out the calling services section. You call using service: python_script.loadtemps if the filename is loadtemps.py under python_scripts folder in your root config folder.
i will try
Error loading script py.py: Line 4: SyntaxError: invalid syntax at statement: "hass.states.set('sensor.temp_' + index++, item, {"
@queen meteor
f = open("counter_total.json", "r") index = 1 for item in f: hass.states.set('sensor.temp_' + index++, item, { 'unit_of_measurement': 'inHg', 'friendly_name': 'Temperature' })
try
f = open("counter_total.json", "r")
index = 1
for item in f:
hass.states.set('sensor.temp_' + str(index), item, {
'unit_of_measurement': 'inHg',
'friendly_name': 'Temperature'
})
index = index +1
@queen meteor
Error executing script: name 'open' is not defined
Traceback (most recent call last):
File "/usr/src/homeassistant/homeassistant/components/python_script/init.py", line 196, in execute
exec(compiled.code, restricted_globals)
File "py.py", line 1, in <module>
NameError: name 'open' is not defined
๐คทโโ๏ธ
the file libraries are not accessible from python_scripts out of the box it seems. You cant really import python libraries in python_scripts. for that, you have to use AppDaemon
the options are limited - other thing you can do it drop messages into MQTT from a python program, and run the python program as a command line every minute or so...
just realized how restrictive it is to use python_script by looking at the code! https://github.com/home-assistant/core/blob/dev/homeassistant/components/python_script/__init__.py
Hi, can anyone help me out with my template?
https://pastebin.com/cawMFcsi
I'm tryig to apply a rgb colour to the lights in a group that are on. The lights in the group that are off should stay off. I tried to find something in the docs but didn't manager to find anything. Whats wrong with my approach? I get the following error when checking my config:
Invalid config for [script]: expected a dictionary @ data['script']['apply_rgb_colour_to_turned_on_lights_fabian']['sequence'][0]. Got '{'.
templates doesn't work that way. you can't generate code by using template like that. you can only set values dynamically using templates.
So I would have to make (number of lights in group) sequences and make the template inside the sequence-call? What would work best then for lights that are off? call the turn off service? Or is there a way for a service call to do nothing?
@analog remnant posted a code wall, it is moved here --> https://paste.ubuntu.com/p/pmhvngjgkr/
That is correct.
I want to make a switch in lovelace that triggers a single command for both it's on state and off state.
I don't have sensor date to provide it info in the value_template. Is there a way to just have HA start this thing in the off state, and toggle the state to on (and have the switch reflect that) when I actually flip the switch?
@wicked parrot probanly its just me, but i am unable to follow your objective. Could you try rephrasing what is it that you want? I think you may be looking for template switch. BTW you cannot create a switch in lovelace, you just add a switch created in configuration
Many times people get confused about what goes into Lovelace vs what goes into configuration code. Since everything is YAML, people think they can mix and match.
So, i'm not sure if this applies here, but i might be using -platform template wrong
Please use https://www.hastebin.com/ or https://paste.ubuntu.com/ to share code or logs.
What issue are you having?
So, i have a number of sensor templates i'm trying to pull from various switches and stuff
I was just looking through my rats nets of config.yaml and i used -platform: sensors a couple times in different spots
what is the 'proper' way of calling sensor templates, or definign them in your conf.yaml, do I need -platform, sensors: for each sensor?
Do you mean - platform: template?
sorry, yes
- platform: template
sensors:
I have it defined in at least 2x differnt spots in my conf.yaml
No prob, just checking. So that has to go under sensor: in your config, like this:
sensor:
- platform: template
sensors:
You can only have one of each top-level key (sensor: at the very top in this case) in configuration.yaml (unless you're using packages, then you can have more than one)
yes
but i can use sensor:
- platform: template sensors:
as many times as i wish? should i use that for each template?
No, the individual template sensors should go under sensors:
Again, you can only have one of each top-level key in configuration.yaml
yep, go it. only one sensor top-level key, but what about - platform: template? Is that considered a top level key as well
Some integrations (like history stats) use multiple - platform: history_stats so no
@wheat fulcrum posted a code wall, it is moved here --> https://paste.ubuntu.com/p/nFYRqDpTm7/
right now i'm doing the above
If you're not getting any config validation errors and you see all the sensors you're expecting to at developer tools > states then you're good
Not sure why you'd want to do that though when you could just use comments
i think I need to clean up my entire sensors; and move out of the conf.yaml
I did it because everything grew up without much though. I was reviewing my config.yaml and the i was like "wow, this is a mess'
Not a bad idea. I have my entire config split up into different packages/files
If you wanna take a look:
It's dangerous to go alone! Check out my GitHub.
that's really clean ๐
Note that packages are an exception to the one top-level key rule. You can have multiple of the same top-level key in more than one package even if it's already in configuration.yaml
The only thing I need to do is make a seperate yaml file and include it in config.yaml ?
I understand what this does
!include conf/.calendar.yaml
Mmh. Sorry, packages?
We should probably take this to #integrations-archived
well, thanks for clearing that up. I'm looking through your config and it's so easy to read
No prob! Splitting up the config/packages are nice that way
this is returning false. What am I missing:
{{ is_state('now().weekday()', '1') }}
you are trying to get the state of something that isn't an entity
{{ now().weekday() == 1 }}
got it, thanks. Think you are missing a () there ๐
I want to change a attribute of the Google Calendar component (the start date) into a human readable "March twelfth" for use in a TTS, can I do that in a template? If so could someone give me a hand? The value it gives me in the attribute for the upcoming event is 2020-04-27 00:00:00 and all I want is a month and day out of it. I was thinking use a template to delete the first 5 characters, and the last 9, then use a ton of if statements to convert the month and day to spelled out so they're speakable.
Is there an easier way to do this?
{{ as_timestamp(state_attr('calendar.work', 'start_time')) | timestamp_custom('%B %d') }}
returns March 17
change the calendar entity ID obvi
here are the other options for timestamp_custom: https://docs.python.org/3/library/time.html#time.strftime
awesome! that makes that so much easier!
I was about to write 43 lines of if statements lol
{% set date = as_timestamp('2020-04-01 00:00:00') | timestamp_custom('%B %d') %}
{{ date.replace('0','') }}
returns April 1
nooooo
lmao
yeah... I was about to say..
good lord
what about on the 10th
yup
If the leading zero doesn't end up working right in the TTS, I may change gears and say "event happens in x days from now" instead.
%-d
thank you lol
{{ as_timestamp(state_attr('calendar.work', 'start_time')) | timestamp_custom('%B %-d') }} then
{% set date = as_timestamp('2020-04-01 00:00:00') %}
{{ date | timestamp_custom('%B') }} {{date | timestamp_custom('%-d') | ordinal}}
this works fine
{{ as_timestamp('2020-04-01 00:00:00') | timestamp_custom('%B %-d') }}
sure, but @queen meteor did the hard work to add ordinal, and no one uses it ๐ฆ
oh well in that case
I want that ordinal!
oh right you did want that
So all together it's {% set date = as_timestamp(state_attr('calendar.birthday', 'start_time')) %} {{ date | timestamp_custom('%B') }} {{date | timestamp_custom('%-d') | ordinal}}
and it outputs ๐ April 27th
yeah i get that
It's for a greeting when my dad opens the door after using his code to unlock it. He keeps asking for me to add more stuff to it. it's been really fun playing and learning templates with this stuff.
nice! the first automation here probably has my favorite template i've ever written: https://github.com/Tediore/My-HASS-config/blob/master/conf/automations/speaker_volume.yaml
That's not flippyboimadness
true. reminds me, did you see my home assistant rube goldberg machine?
I doub't I want to
@oak juniper posted a code wall, it is moved here --> https://paste.ubuntu.com/p/KSqDYw4NnH/
Sorry, let's break that up
Hi folks. I'm trying to figure out what the best way is to monitor the status LED of my gate opener, and let me know what state it is in based on the flashing pattern.
This is the documentation for the status LED that I want to monitor:
Off - Gate is closed.
Slow continuous flash - Gate is opening.
On - Gate is open.
Fast continuous flash - Gate is closing.
1 Flash/sec - Pillar light on permanently.
2 Flashes/sec - No mains.
3 Flashes/sec - Battery low detection.
4 Flashes/sec - Collision detector operated.
5 Flashes/sec - Microprocessor reset
I'm happy to use Tasmota, or ESPHome, or whatever.
Is the easiest/cleanest way to do this via a template considering the state, previous state of the GPIO, and time since last change?
e.g. previous state is off, time since last update is > 1 second, current state is on, increment a counter and save the current time as "start time".
previous state is off, time since "start time" < 1 second, current state is off, increment the counter.
once "now() - start time > 1 sec", observe the counter and translate the number to a status, then reset the counter
Ordinal filter was written mainly for TTS, to make it sound natural ๐ค
I never used it since! ๐
@buoyant pine where is the template code in there? https://discordapp.com/channels/330944238910963714/672223497736421388/689555005711450216
?
/dev/bull
lol
It is not a template code if you donโt have loops, filters, and namespaces, complex decoding and encoding of entity ids and regular expressions.
lol
what about tuples?
in the namespace, sure
i was given the following template to set a value to 0 if the other sensor is unknown or unavailable:
value_template: >-
{% set value = states('sensor.test') %}
{{ value|float|round if value not in ["unavailable", "unknown"] else 0 }}
this works fine if it's unknown or unavailable, but if it's actually a valid value, then it's still set to 0
so there's evidently something wrong with this
if there is the issue is what sensor.test has as it's state
{% set value = "13" %}
{{ value|float|round if value not in ["unavailable", "unknown"] else 0 }}
Returns 13 in developer tools -> template
{% set value = "Not A number" %} returns 0
works if i use set value = states.sensor.test instead
That gives you the entire State object, and not just the state of it
well, that worked
if i used set value = states('sensor.test'), then i got returned 0, even if the value of the sensor is a non-zero integer
or an integer
arrrr.. then i got unavailable back for the non-integer ones
i wonder if the way i set the value variable is the problem here
when using the rest platform for a sensor, is it possible to rename the json_attributes to something more friendlier?
i'm attempting to use the state_attr instead to grab the value.. the problem is that the key contains spaces.. so .'Some key' doesn't work
i've tried different variants.. like " and also ", but it doesn't stick
TemplateSyntaxError: expected name or number
Sounds like a broken integration
You should raise an issue with the dev, so that the slugs are valid
what do you mean? i'm getting this off a rest sensor i've set up myself
Then it's your fault ๐
Fix it so that the slugs are valid
but basically, i shouldn't have spaces in the keys?
the entity name is correct.. that contains underscore instead of spacess
spaces*
the problem is inside the entities attributes
Same rules apply to attributes
ah, ok
so also lower case it, i guess
what about localization? international characters and so on?
only ascii?
I'm setting up a virtual switch using a value template. For the off position I want to call two services. Is this possible? Or am I limited to one?
Call a script
is there some built-in functions in python that can do all that for me?
Search for home assistant slugify
i found the module unidecode
Ok, so create a script that calls two services, and then call that in the value template. Not possible to call both services in the value template natively?
Ok, thanks again :)
whats the best way to save a date and compare it with the current one.
I currently save the the now().date() when it happens. then i want to compare it with the new now().date with as_timestamp. but as_timestamp(now().date()) returns None
{{now().date() | as_timestamp }}
argh.. i'm not getting this to work.. i have attempted to use state_attr() to get a key from an entity's attribute dict.. so now i have:
{% set value = state_attr('sensor.test', 'cases').Key1.Key2["confirmed"]|int %}
{{ value|int if value not in ["unavailable", "unknown"] else 0 }}
the problem is if either Key1 or Key2 is not present in the dict
then i get an UndefinedError.. dict object has no attribute 'Test'.. how do i work around this? and then just set the value to 0?
@torn ruin both appear to be working for me
Arm has issues with that
Any elegant ways to handle a null value coming in and still do an average? {{ ((float(states.sensor.master_bedroom_temp.state) + float(states.sensor.nursery_temp.state) + float(states.sensor.boys_room_temp.state)) / 3) | round(1) }}
states('sensor.master_bedroom_temp')|float The float() function fails if the input cannot be interpreted as a number, but the |float filter will output zero (by default.)
is this the right syntax for checking not state - is_not_state('switch.fancontrolspeed', 'unavailable')
not is_state(...
And to count only non zero returned values to calc the average..... 
thanks!
Arm has issues with that
@rugged laurel thanks fro the explanation
is a timestamp to datetime conversion really missing in jinja2?
@long basalt https://www.home-assistant.io/integrations/min_max/
thanks -- elbow bump! ๐
Works great, so much better! Using this to feed a generic thermostat
meta on meta on meta
I'm trying to figure out how to get a template to produce a list that can be consumed as a list by a service call. Specific case right now is to enumerate a list of scenes, and send that list to an input_select as a list of available options
currently, this is what I have
- service: input_select.set_options
data_template:
entity_id: "input_select.hasp_plate01_page1button4scene"
options: "[{% for item in states.scene %}'{{ item.entity_id }}'{% if not loop.last %}, {% endif %}{% endfor %}]"
That template renders as ["scene.daylight", "scene.lights_off", "scene.lights_on", "scene.night"]
which, if pasted into the service call, works like expected. However, I'm pretty sure it's just rendering as a long string and I need it to somehow be returning a list
i don't believe you can since, as you discovered, the template returns a string even though it looks like a list
it'd have to be something like
data_template:
options:
- {{ }}
- {{ }}
- {{ }}
which isn't helpful for a list of dynamic length
balls ๐ฆ
Can I use a check for the multiple state (or condition) in the state platform? Or must I only use template? The config fails for below, but I wondering if there is a workaround - alias: Turn off Fan Plug Relay when Fan is not running for 10 mins trigger: platform: state entity_id: switch.fancontrolspeed to: 'off', 'unavailable' for: minutes: 10 action: service: switch.turn_off entity_id: switch.fanplugrelay
@fossil totem I've suggested using a python_script in cases like these.
@rare panther I'm pretty sure you can. You might have to do: to: ['off', 'unavailable'] or something like that.
ah let me try
yep. or
to:
- 'off'
- 'unavailable'
Yep, either way, it just has to be a YAML list.
Thanks, it works. Preferred to: ['off', 'unavailable'] as I use lot of "in" checks so it will be consistent throughout my yaml
@chrome temple i'm not 100% sure i follow
do you mean do the whole thing in python (run a python script that enumerates scenes and calls the service to setup the input_select)?
@rare panther FYI, I believe the way it works is, if it changes to either of those states it will then begin the for period, and during that period it has to stay the value it changed to (in this case off or unavailable). If it changes to the other state, then the for period will start over. At least I think that's how it works.
what's frustrating about this is that the same approach worked with group.set https://github.com/aderusha/HASwitchPlate/blob/master/Home_Assistant/packages/plate01/hasp_plate01_00_components.yaml#L205-L217
@fossil totem I mean use a python_script to call the input_select.set_options service. How it gets the values, and how much other processing it does, depends on what you're trying to do.
Yeah, I'm pretty sure the group.set service schema knows how to take a string with multiple entity IDs separated by commas and split them out into a list, whereas input_select.set_options doesn't. Same issue, e.g., with rgb_color parameter of the light.turn_on service.
@chrome temple Thanks. I agree. However, need to check on "If it changes to the other state, then the for period will start over' through code. because then I think it is not an optimize config. I might then go for the timer option
welp. turns out i can't use a python_script along with packages
I do, why do you say that?
random forum post, maybe the person was wrong?
It would seem so.
i'm trying real hard to avoid this approach because i don't speak a lick of python ๐
Well, if you search the forum you can probably find one or two times I suggested how to do this with code samples.
annoying that it worked w/ group.set but not input_select.set_options
I tend to agree. Entity IDs are treated special. I can see lots of other use cases for comma separated lists (as opposed to true YAML lists.) I tried to change, e.g., the light.turn_on service so that rgb_color, xy_color, etc. would accept these, because it makes templating MUCH easier, but no go.
I tried to use it in the life360 integration and was told not to.
@rare panther you could always create a template binary_sensor that is on when the state of switch.fancontrolspeed is off or unavailable, then use that in your state trigger.
of course, just wanted to play around my various entities
@chrome temple running into some of your examples on using python scripts in the forums and they're helpful, thanks for sharing that my friend!
one more time I need a help in templating ... this {{ states.sensor.unifi_gateway_wan.attributes.gw_system-stats.cpu }}
gives me error UndefinedError: 'stats' is undefined ... it must an issue with char "-" ... is there a way to correct it somhow without |replace ?
The attribute's name is gw_system-stats?
yes
{{ state_attr('sensor.unifi_gateway_wan', 'gw_system-stats').cpu }}
tank you ๐ works ๐
@fiery flax posted a code wall, it is moved here --> https://paste.ubuntu.com/p/gM4wp24wPJ/
Oops. Well I have a question about mqtt formatting nested objects from the config file
and I don't quite know how to post it without it turning into a wall of code, so sorry for that ๐ฆ
Let me check my config real quick.
i have a lot of repetitive code to set up a lot of template sensors.. is it possible to set up some macros for this instead?
@keen flame you should do that with a condition on a automation.
@ebon yoke try scripts
@rare panther do you have an example of that?
scripts won't work for template sensors
yep it won't work for templates, but I was stating for general code reduction & repeatability. For example, I have a fanControlScript which has all the logic for starting different Fans, in my Automations, various trigger points just call that Fan Script. So tomorrow I include a new Fan, I would just add in fanControlScript . If I add another input, say ikea remote, then a edit existing or add a new automation.
yep, can't do that for template sensors
@ebon yoke do a search on YAML anchors & aliases. That might be what you're looking for.
@keen flame posted a code wall, it is moved here --> https://paste.ubuntu.com/p/2hsRnpHPqX/
@keen flame now that you have a cover entity you can use the service call cover.toggle to perform an action to either open or close....its just toggling it
its a service call for the cover domain....are you trying to use 1 button in the UI or something?
yeah in lovelace.
more of a #frontend-archived question but you should be able to use https://www.home-assistant.io/lovelace/button/ and set the tap_action to call cover.toggle service call...i think that should give you what you want
How do I access a property of the state of another object media_player.speakers.volume_level when calling a service (I want to sync volumes):
service: media_player.volume_set
data_template:
entity_id: media_player.kitchen_speakers
volume_level: "{{ media_player.speakers.volume_level }}"
Logs say media_player is undefined, do I have to create a variable that's setup to track this property of the state just to use it in a template? If so, why is this not easier to do in Home Assistant? It seems like very common behavior to want to read the state of other objects in the system to use as part of templates in other parts of the system. Haven't to setup watching variables feels very arduous and is a huge limitation to making automation more accessible.
@edgy socket "{{ state_attr('media_player.kitchen_speakers', 'volume_level') }}"
https://www.home-assistant.io/docs/automation/templating/
https://www.home-assistant.io/docs/configuration/templating/
ah thanks i'm an idiot
For just the state it's {{ states('media_player.kitchen_speaker') }}
cool. Wehn i turn on my bonus speakers i want the volume to sync. I'm wondering if i want the second speakers to follow the volume of the first one as an automation, but then they'd be stuck together. I'm wondering if there's an easy way to create a slider that controls both speakers at the same time?
like would i make a fake entity or a fake slider ui that just calls set_volume
The input_number component allows the user to define values that can be controlled via the frontend and can be used within conditions of automation. The frontend can display a slider, or a numeric input box. Changes to the slider or numeric input box generate state events. These state events can be utilized as automation triggers as well.
# Example configuration.yaml entry
input_number:
slider1:
name: Slider
initial: 30
min: -20
max: 35
step: 1```
Then make an automation that triggers on any state change of the input_number entity
so i'd have to declare the variable, the ui, and the automation?
can i set the initial value to a template? {{ state_attr('media_player.speakers', 'volume_level') }}
like would i make a fake entity or a fake slider ui that just calls set_volume
@edgy socket this is the solution to that
The automation would trigger on any state change of the input number and set both speakers' volumes to what the input number is
You'll have to convert the input number to float and divide it by 100 to get the right number for the set volume service call
in the automation can i tell if the state change was triggered by an automation or by something else?
The input number won't change unless you change it yourself or with an automation
touche, then can i identify WHAT automation triggered it?
I want to have it follow my primary speaker volume, but when i change it in the UI i want it to update both
And one automation will trigger the other without a conditional filter
You don't need to use the input number for the one speaker to set the volume of the other
You only need it if you want to set both to the same volume based on the input number
So I guess I could just in the always render the current volume as the primary speakers
and not the current value of the variable?
Sorry, I'm not following what you mean
You'll have two automations:
One that sets the slave speaker to the master speaker's volume level when the master speaker volume level changes
Another that sets both speakers at the same time to the number that the input_number is changed to
no i want to use the slider instead of slaving one speaker to the other
that way if i want to separate them i can, and changing the primary spkears won't sync the secondary
so it's more like a "Toggle All" type behavior
When you have multiple entities
Oh I see
but it's like "Slide All" or slide each, and the current value displayed is that of one of the entities (not the last value of the variable necessarily)
Ok so you actually want the input number to display the current volume of one of the speakers?
And not just use it to set both at the same time?
Yeah at least in the UI i don't care what the variable has
What do you mean by variable
Well I want it to DISPLAY the main speakers volume but when you slide it, it changes BOTH
I know what a variable is I'm just confused what you're saying
Got it, I see now
give me a few minutes
Man I keep losing track of the restart server button, It's like confusing that some stuff is under supervisor and some stuff is under configuration
configuration > server controls.
ok, so these two automations should be what you need: https://paste.ubuntu.com/p/6qSzjJqPcq/
for this to work you'll want to make a template sensor that grabs the volume_level attribute of the master speaker (sensor.master_speaker_vol in this example). you'll also want to create an input boolean (input_boolean.master_vol in this example).
the first automation will set the volume of both speakers to whatever the input number is changed to but ONLY if the state change wasn't triggered by changing the master speaker volume
that's what the input_boolean is for
Interesting
also some stuff is under supervisor because those who run Core only (like me) don't have that page
Do you use the UI for automations generally speaking?
to create them or as part of a trigger?
Creating
nah, i just write them manually
VSCode?
It's dangerous to go alone! Check out my GitHub.
Is id mandatory for automations? The file created by the UI uses randomly generated ones
it's only needed if you want to edit them with the UI editor
otherwise you don't need it
Gotcha, yeah when I found I couldn't use custom files AND the UI I deferred to the UI
you actually can use both
But I can't use both file structures
The UI doesn't seems to know where to save them
you need one dedicated file for the UI editor, and you can have whatever structure you want for your non-UI-created automations
Interesting, I MAY do that but I'm afraid I'd forget about my custom ones and run into lots of debugging headaches cuz of that alone
yeah, up to you
configuration > server controls.
ok, so these two automations should be what you need: https://paste.ubuntu.com/p/6qSzjJqPcq/
for this to work you'll want to make a template sensor that grabs thevolume_levelattribute of the master speaker (sensor.master_speaker_volin this example). you'll also want to create an input boolean (input_boolean.master_volin this example).
@buoyant pine having some trouble , what kind of sensor am i making
Tediore is away for 2m 37s with a message :point_right: apex legends time ๐ฎ
ugh i'm not sure i'm following
@edgy socket posted a code wall, it is moved here --> https://paste.ubuntu.com/p/zbqJRsfr3y/
@edgy socket posted a code wall, it is moved here --> https://paste.ubuntu.com/p/pCrhZv56hG/
Second link is my automation file
I don't think i grok the input_boolean
Oh I get it now, you turn on a boolean, update the volume, then turn it off
Man the documentation is kinda hard tos earch
I had no idea you could call a service on an array of entity id's
"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 16). " for the first automation script
figured it out, I don't really follow how "off" and off differ and when it's okay not to wrap it in quotes or not
Thank you @buoyant pine got it working! Took a while to understand the relationship of everything
Tediore is away for 45m 43s with a message :point_right: Apex ๐ฎ
Okay had it working for a minute but now it's not working. strange
No prob, what's not working?
I kinda am not sure, I ended up rewriting the file a few times and it's like the UI kludged the file?
I was getting an error on value: "{{ state_attr('media_player.speakers', 'volume_level') | float * 100 }}"
I have no idea what was wrong, tried editing in the UI editor, saved, it messed up the syntax. Opened it in the file editor instead, fixed it, retried, seemed to work
Iunno, maybe it was failing to retrieve the volume_level of the device
Oh. I don't think the automation editor supports templates
Although I don't know unfortunately because I don't use it
No this was when executing the automation. Yeah I really with the UIs had template support
I gave up on the UI editor and switched over to doing it your way cuz I'm slowly picking up how to write things from scratch
Oh. Make sure you're using data_template: when you have a template in the service data
Yeah tbh I think manually writing the automations is the best way to learn things
I accidentally put data: instead of data_template: in the action in the second automation, sorry about that @edgy socket
i have lots of templates like this:
corona_db_kvanangen:
value_template: '{{ state_attr("sensor.dagbladet_corona_self_registration", "municipalities")["5429"]["totalTestedPositive"] }}'
attribute_templates:
stats: >-
'{{ state_attr("sensor.dagbladet_corona_self_registration", "municipalities")["5429"] }}'
friendly_name: "Testet positivt Kvรฆnangen"
unit_of_measurement: people
corona_db_gildeskal:
value_template: '{{ state_attr("sensor.dagbladet_corona_self_registration", "municipalities")["1838"]["totalTestedPositive"] }}'
attribute_templates:
stats: >-
'{{ state_attr("sensor.dagbladet_corona_self_registration", "municipalities")["1838"] }}'
friendly_name: "Testet positivt Gildeskรฅl"
unit_of_measurement: people
it's a lot of repetitive code.. is there a way to simplify this? for instance a dict with the name, sensor key and also the id of the attribute to retrieve?
and then just iterate over this and create the different template sensors?
Trying to get the numbers of days between two times. I have this template but it is returning 1584697287 instead of roughly "6 days". What do I have wrong?
- platform: template
sensors:
covid_elapsed_days:
value_template: '{{ (as_timestamp(now()) - (states.input_datetime.covid_start.attributes.timestamp) | int /60/1440) | round(0) }}'
unit_of_measurement: 'days'
entity_id: input_datetime.covid_start,sensor.time
How is input_datetime.covid_start configured? Does it have both date & time? Or at least date?
it has both, I think it i a ( issue, working on it now
yep, forgot my order of operations
D'oh! I specifically looked for that but because it broke across two lines the grouping wasn't as easy to see clearly. BTW, timestamps are floats, so you should probably use the float filter instead of int, but I guess what's a few microseconds between friends? ๐
haha, could you explain the difference?
A timestamp is the number of seconds since "the Epoch", expressed as a floating point number, which can include fractional seconds. Actually, now that I think about it more, you don't need either filter, since you're not dealing with a string representation of a number (like you would with the state.) Does that make any sense?
That is to say, the timestamp attribute is already a (float) number.
I have a group of sensors. can I retrieve a list of the sensor states?
or what I actually want is the highest value of the sensors within the group
what do you want to do with it?
just have the highest value of all values in the group
and do what with it?
The XY problem is asking about your attempted solution rather than your actual problem. This leads to enormous amounts of wasted time and energy, both on the part of people asking for help, and on the part of those providing help.
The problem occurs when people get stuck on what they believe is the solution and are unable to step back and explain the issue in full.
the sensors calculate which room is the most urgent for the my vacuum
each room has one. the one with the highest value will be cleaned next
@torn ruin do you have that working!? ^^^^ that sounds amazing!!1
partly...
Creating a Gait analysis / capture algorithm via 4 PIRS + Jinja2 templating.
Xiaomi PIR -> Zigbee2MQTT -> MQTT Discovery -> Jinja2 templating
Miiiiiight be looking for a little help on the Jinja2 side of things. will keep ya'll posted
๐
Hi, How to get local time from now()?
now() should be your local time
If it isn't then either the time on your computer is wrong, or the timezone is wrong
Okay, So if I want get datetime with format should call which filter or function?
What are you trying to do?
I am reading this page and python refrence but can not find this
I am trying to get time format with HH:MM:SS
timestamp_custom allows you to get out whatever you want
What is this? a filter from HA, or python function? How to call?
See the link I posted
Oh sorry. Thanks
{{ as_timestamp(now()) | timestamp_custom("%H:%M:%S") }}
Sorry, Why should we use syntax like this?
Whats mean of piping as_timestamp(now()) to timestamp_custom("%H:%M:%S")?
the timestamp_custom("%H:%M:%S") should not work standalone?
Go to Developer tools and then Templates
Try stuff
You're using Jinja, there's a lot of good documentation
Please can somebody help me out with a template? I'd like to put tome words in an array. Example: door, window, garage, alert, leak, etc. When a persistent notification is created an automation triggers and searches the currently created persistent notification message for all words given in the above array. If one of the words is found inside the massage gives true else false. How can I achieve this?
Hello!
I am trying to check several lights color and set brightness for single light after. How I should do this ion a right way?
Right now I have this code and got the error:
{% if states.light.hue_color_lamp_1.attributes.rgb_color == (255,255,255) %}
255
{% else %}
0
{% endif %}```
`expected int for dictionary value @ data['brightness']`
PS: never mind, I found it. In script there should be not `data:`, but `data_template:` to be able to use the expressions inside
PS2: here is correct script that checks, if the lights have proper color and brightness. If TRUE, set lights OFF on run. If FALSE, set lights color and brightness.
```data_template:
brightness: >-
{% set lights = [
'light.hue_color_lamp_1',
'light.hue_color_lamp_2',
'light.hue_go_1',
'light.hue_go_2',
'light.bedroom_ceiling_light' ] %}
{% set lights_state = namespace(on = true) %}
{% for light in lights %}
{% if not (state_attr(light, 'brightness')
and state_attr(light, 'brightness') >= 254
and state_attr(light, 'rgb_color')
and state_attr(light, 'rgb_color') >= (254, 254, 254))
%}
{% set lights_state.on = false %}
{% endif %}
{% endfor %}
{% if lights_state.on%}
0
{% else %}
255
{% endif %}
entity_id: light.bedroom_lights
rgb_color:
- 255
- 255
- 255
transition: 0.25
entity_id: light.bedroom_lights
service: light.turn_on```
light.bedroom_lights << the same lights from the array in a group
On color/brightness change not all the lights set the same values, so sometimes there 254 instead of 255, so that is why there is a ">=" check.
Is there a way to check the platform of an entity within a template?
I want to iterate over all lights, but skipping groups of lights.
{% for light in states.light if not platform(light, "group") %}
{% endfor %}
I have a sensor that show all entities that are unavailable. Mostly to track any zigbee devices not responding or that someone switched off physically. The sensor works great.
unavailable:
friendly_name: 'Enheter utan data'
value_template: >
{{ states | selectattr('state', 'in', ['unavailable', 'unknown', 'none']) | list | length }}
entity_id: sensor.time
attribute_templates:
entities: >
{{ states | selectattr('state', 'in', ['unavailable', 'unknown', 'none']) | map(attribute='entity_id') | list | join('\n') }}
Now I'd like track unused automations the same way, with a sensor, counting the number of automation whose last_triggered is for example "now() - 6 weeks". With the automations fulfilling this criteria in an attribute to that sensor.
Any suggestions?
hey guys
whats up
i have a few sensor values that i want to do some math on, could anyone help me with this?
i have: sensor.power_consumption, sensor.power_production (both positive values both wattage, dsmr component), sensor.pv_power_production (wattage, positive value) and a battery sensor.victron_battery_power (wattage, negative or positive value where positive is charging and negative is discharging)
with this i want to calculate what my energy usage is
power_consumption goes from grid to my house
power_production goes from house to grid if battery is full
pv_power_production are my solar panels
victron_battery_power is my batterybank
would anyone know how to go about this?
Hey everyone, I have a problem with a template since 0.107. - it used to work just fine: (Result: {{ (trigger.to_state.state | float / trigger.from_state.state | float * 100 -100 ) | round(1) }}% / Result: {{ (trigger.to_state.state | int / states.input_number.someinputnumber.state | int * 100 -100 ) | round(1) }}%) I am using this as the content of a push message, bu it is not working anymore - can someone help me find the error? The log says: Error executing script. Unexpected error for call_service at pos 1: division by zero
Seems likely that input_number.someinputnumber (or the from_state) is zero ๐ค
i have some data provided over the rest platform where the json attributes i'm interested in is without key.. how do i grab the right json_attributes then?
there's no parent key, basically
and i'm interested in ALL values
hm, let's try just value_json
hm, no.. that didn't work
@opal igloo how are you utilizing that script though with your bulbs?
whats the purpose?
@topaz walrus I have RF wall buttons to turn lights on and off, and change color scene (Philips Hue + IKEA Tradfri). So three buttons, three scenes with different lights setup and colors.
It works this way: if lights OFF or color|brightness don't match selected scene (pressed button) - turn lights scene on. If match - turn lights off.
ahh ok pretty sweet, thought i was gonna be able to help lol
I'm trying to learn date handling, but I'm not there yet..How to template "now() minus 6 months"?
hey fellas.. I try to get a template working but I think I miss something
any idea?
also wrong ๐ฆ
i'm importing a json structure using attribute_templates.. i'm getting the values in, but is there a way to convert them from the json structure to a more readable structure?
it looks like: {'key1': 89, 'key2': 20}.. but i'd rather for it to look like two columns with:
key1 89
key2 20
Invalid config for [automation]: expected a dictionary for dictionary value @ data['action'][0]['data_template']. Got None. (See /config/configuration.yaml, line 88).
but i have something in data_template
@arctic sorrel do you know how i can convert that to a more human-readable variant?
.... ๐ค
no errors in config chekc but when triggering i get :
2020-03-23 22:54:19 ERROR (MainThread) [homeassistant.components.automation] xmpp-bot - help: Error executing script. Invalid data for call_service at pos 1: Service lock.unlock
data_template: >
lock.main_door does not match format .
@arctic sorrel could '| tojson' do something here?
Why do you keep tagging me and asking?
@olive moth gotta be something like this: https://paste.ubuntu.com/p/Q24zywpYMn/
because you've proven your expertice again and again ๐
but i'll stop tagging you.. sorry
And... if I thought I could help I would - right up until you started tagging
It comes across as you demanding help to tag folks not already helping you on something
i'm sorry.. i just saw you were active.. again, sorry about that
(i made an assumption about your script entity ID based on what you had @olive moth)
But I also want to use other entities like climate based on the sensor value
Sounds good but fails I guess by using more than one same entity
nope
let me try ๐
verify your script entity ID first
Anyone RESTful json parser wizbangs in here? Trying to pull a .json file from my server and I'm getting a response like An appropriate representation of the requested resource could not be found on this server. This error was generated by Mod_Security.
Is it just not possible to pull json data from a file?
For anyone else that might search and be wondering... you need to do a command_line sensor with a curl request, not a rest sensor
Do jinja templates work in customize entity? For an attribute name or value?
Bah doesn't look like it
i have been returned a json structure from a rest sensor.. and i want to extrapolate this json structure into key value pairs.. so that i get that data instead of the json structure presented in the attribute_templates.. how can i do this?
i have attempted stuff like this:
attribute_templates: >-
{% for i in state_attr('sensor.vg_municipality_stats', 'municipalities')["5427"].items() %}
{{ i[0] }}: {{ i[1] }}
{% endfor %}
but that fails with "Invalid config for [sensor.template]: expected a dictionary for"
whats the best way to get the time elapsed from now() since a input_datetime
can anyone give me some pointers for the play_media function. I can't get my script to execute on the media player
looks like this
media_content_id: >-
{ "library_name" : "TV Shows", "show_name" : "Paw Patrol", "season_number" :
1, "episode_number" : 10, "shuffle": "1" }
media_content_type: EPISODE
entity_id: media_player.plex_plex_for_roku_roku_3_living_room
service: media_player.play_media
@keen flame you need to use escape characters before all the quotes: https://www.home-assistant.io/integrations/plex/#service-play_media
How can I force this to be an integer that home assistant to recnogize it as something it should be making a graph for?
sensor:
- platform: rest
resource: https://sil.ph/card/cardData.json?&user_id=3607
name: "Fortes SilphArena Rank"
value_template: "{{ value_json.data.arenaGlobalRank |replace(\"<sup style='font-size:14px;'>#<\/sup>\", \"\")|replace(\",\",\"\") | int }}"
This is what the result gives me: https://i.imgur.com/bSeDE6j.png
If you want it graphed, see https://www.home-assistant.io/docs/configuration/customizing-devices/#unit_of_measurement
so this value is a rank, so what would that unit be? Just like a # then?
Well I don't have any unit I want it to really be. Could I just do like unit_of_measurement: "" so there is a blank unit specified?
Ya know, nevermind lol. I'll just test it. That's probably easier to just test ๐ thanks for pointing out I need to add units
Then it wouldn't have a unit... ๐คท
I don't care for a unit, I just want HA to understand this is a number to graph and not just a string to label the bar history with.
It needs a unit for graphs, as simple as that
So what I understand is that there is no way to specify a blank unit in the circumstance where you have a sensor that doesn't have a unit, like the rank of something, but you still want it to be graphed. I tested unit_of_measurement: "" and it didn't work.
Yeah, after a few tests that seems to be the case. Okay, I'll just use # as the unit.
Hello all.. hope your are doing well? I have a nother tmplate question: I want some notification when a door or window opens / closes. For this I use mod_browser to send toast notifications (the black grey/black bar on the buttom of the home assistant webinterface) but I need to filter out the binary_sensrs for words like window or door. For the mooment have have following automation /temlpate but it will notify about all binary_sensor changes.
@queen meteor are you around ๐
@olive moth Don't just tag folks demanding asking for help like that, it's rude, and people will block you ๐
Please can somebody help me out with a template because I'm lost. I'd like to search some words in string. For the example: search for door, window, garage, alert, leak, etc in another string. If one of the words is found inside the string it gives true else false. How can I achieve this?
I know you can do
{% if ('Banana' in states('sensor.fruit')) %}
Silly me. I don't why I have struggled with for loop. Thank you @arctic sorrel . Shame on me.
I only know about that because somebody else told me about it ๐
@thorny snow you can also do something like
{{ states('sensor.fruit') in ['apple', 'banana', 'grape'] }}
that will look to see if the state matches any of the values in the list
{{ "banana" in states('sensor.fruit') }}
{{ states('sensor.fruit')| regex_search("[banana|apple|orange]") }}
apparently a banana is "botanically a berry" 
ah yeah that's nice if you're not looking for an exact match
Thank you @rugged laurel @buoyant pine . Problem solved. ๐
@arctic sorrel skalavala always was pleased to help ๐
and I know that he's good in templating
he could be doing family stuff and you randomly blasted him with a ping
not everyone is in the same country either
So, post questions, stop tagging folks demanding help
basic question, somehow I cannot recall it. How can I get all the attributes of a entity in a JSON format? like the way it is dispayed in the developer tools -> states
@rare panther
{{ states.alarm_control_panel.abode.attributes }}
of course, replace alarm_control_panel.abode with your entity ID
yes - thanks so much. somehow I feel this basic thing should be mentioned in the https://www.home-assistant.io/docs/configuration/templating/
though be aware that returns a python dictionary instead of JSON. it uses single quotes instead of double quotes
might not matter for whatever you're using it for
also one of the links on the page you linked above explains the state object more: https://www.home-assistant.io/docs/configuration/state_object/
yeah I am good with dict as well. Yes, now that you mentioned in it is indeed defined in state_object
but still think states.entity_id.attributes should be specifically mentioned as an example in https://www.home-assistant.io/docs/configuration/templating/#attributes Not everybody may understand the state.attributes in state_object
how do i convert a json structure returned from a rest sensor platform to something more readable in the attribute_templates for the entity..
?
i have the json structure in the attribute for the entity, but i would like for that to be set up as columns instead
i have attempted the following:
i have attempted stuff like this:
attribute_templates: >-
{% for i in state_attr('sensor.vg_municipality_stats', 'municipalities')["5427"].items() %}
{{ i[0] }}: {{ i[1] }}
{% endfor %}
but that didn't work
Are you trying to display that in the UI in columns, or what?
Attributes are "simple" key/value pairs
yup, that's what i'm trying to do..
Well, displaying in the UI is more a #frontend-archived but you'd need a custom card for that I suspect, maybe the markdown card
@arctic sorrel but i see that other attribute templates are formatted more like a column.. isn't this something that's possible directly in the attribute_templates?
without any markdown cards
I have no idea what you're talking about, but ... how things look in the #frontend-archived is a thing for #frontend-archived
for instance the sun.sun entity.. its attributes are next_dawn, next_dusk, next_midnight, elevation, and so on
Please use imgur or other image sharing web sites, and share the link here.
Why don't you show us what you're talking about ๐
they are formatted as:
next_dawn: 2020-03-26T03:03:29+00:00
next_dusk: 2020-03-26T18:19:23+00:00
next_midnight: 2020-03-25T22:41:19+00:00
...
in the attributes for the entity
They're attributes, single attributes
this means that if i click on the sun entity in the UI, then they're displayed properly underneath the entity state
If you want things to look like that, you have to make them individual attributes
yup, exactly.. and that's what i'm trying to do ๐
But not with a loop
see my attempt above
ok.. but can it be done from a json structure?
without having to spell out each individual attribute?
Question: ~8ball Do you know which one?
Answer: Chances Aren't Good
https://www.home-assistant.io/integrations/rest/#json_attributes
A list of keys to extract values ...
According to the docs, that's your option
the problem is that this is a big json object.. it's a multi-dimensional dict
so i have created template sensors to extract the dicts i'm interested in into separate sensors
(i'm sorry if i'm using the wrong terminology)
Some of the other template sensor types have more options
you mean not this: https://www.home-assistant.io/integrations/template/ ?
what other template sensor types are there?
MQTT and more
That one however has an attribute template, I still doubt loops are permitted
so then i basically just need to spell out each and every attribute?
For things like this, better to write a custom component or do it in AppDaemon. if you do it in Jinja, it would be ugly and you may have a lot of repetition.
{{ (35.74 + 0.6215 * state_attr("weather.home","temperature") - 35.75 * state_attr("weather.home","wind_speed") ** 0.16 + 0.4275 * state_attr("weather.home","temperature") * state_attr("weather.home","wind_speed") ** 0.16) | round(1)}} Bwahahaha. There are probably easier ways to get wind chill but I'm happy now.
might need to cast some values otherwise you might be doing some string math
@charred oar posted a code wall, it is moved here --> https://paste.ubuntu.com/p/D4PcDXX8Hc/
Hi guys, question: i want to convert this part of a automation to a template:
But its not working
~codewall @charred oar
@charred oar 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.
If you're wanting to do stuff in Node Red, ask in #node-red-archived ๐
https://www.json2yaml.com/ is your friend though
i'm creating a sensor.template based on a device_tracker.... there a way to just copy all attributes that are available from another entity? something like
attribute_templates: '{{ states.device_tracker.number1.attributes }}'
i guess i gotta do something like this:
source_type: '{{ states.device_tracker.wm1_c75dcc8d4560488a93cce725ed339604.attributes.source_type }}'
latitude: '{{ states.device_tracker.wm1_c75dcc8d4560488a93cce725ed339604.attributes.latitude }}'
longitude: '{{ states.device_tracker.wm1_c75dcc8d4560488a93cce725ed339604.attributes.longitude }}'
gps_accuracy: '{{ states.device_tracker.wm1_c75dcc8d4560488a93cce725ed339604.attributes.gps_accuracy }}'
scanner: '{{ states.device_tracker.wm1_c75dcc8d4560488a93cce725ed339604.attributes.scanner }}'
yuk
so if you're just copying everything from one entity to another, why do it?
because i'm customizing the value... only the attributes are copied
but creating my own component is scary...
Only the first time. Then it's fun.
i can't even grasp how to turn my shitty python program into a component and all it does it scrape a website for the name and artist of the song currently playing on my favorite radio station lol
so in the meantime i'm writing the info to a file and using a file sensor in home assistant
like an animal
works though
Use AppDaemon - easy to port existing python code and easy to create sensors
@charred dagger fun? Your components must not have any users..
Fun...
There's a big difference between one-off components for your own use and custom integrations.
Hi im trying to set up a template like so:
maciekish_discord_status:
friendly_name: "Maciekish Discord Status"
entity_id: sensor.discord_maciekish_1045
value_template: >-
{% if state_attr('sensor.discord_maciekish_1045', 'game') == None %}
{{ state('sensor.discord_maciekish_1045') }}
{% else %}
{{ state_attr('sensor.discord_maciekish_1045', 'game') }}
{% endif %}
But it returns "Unavailable". state_attr('sensor.discord_maciekish_1045', 'game') is None, and the main state is "online"
What am i doing wrong? I also tried is_state_attr('sensor.discord_maciekish_1045', 'game', 'None') and is_state_attr('sensor.discord_maciekish_1045', 'game', null) with same result
The raw value of game atribute in Developer Tools is null
sensor.discord_maciekish_1045 online game: null
Its driving me nuts, should be so simple...
Hello, can i please get some help with this template? Works for the most part but the spacing and commas are a little messed up.
- service: notify.mobile_app_iphone_xs
data_template:
title: "Alarm Status"
message: "The alarm has been triggered, the following sensor: {{ dict((states|selectattr('entity_id', 'in', state_attr('group.door_sensors', 'entity_id'))|list)|groupby('state'))['on']|map(attribute='name')|list|join(', ') }} {{ dict((states|selectattr('entity_id', 'in', state_attr('group.window_sensors', 'entity_id'))|list)|groupby('state'))['on']|map(attribute='name')|list|join(', ') }} {{ dict((states|selectattr('entity_id', 'in', state_attr('group.motion_sensors', 'entity_id'))|list)|groupby('state'))['on']|map(attribute='name')|list|join(', ') }} {{ dict((states|selectattr('entity_id', 'in', state_attr('group.garage_doors', 'entity_id'))|list)|groupby('state'))['open']|map(attribute='name')|list|join(', ') }}"
@next shell what do you see in the template editor? You should really use multi-line template instead of yaml message: "xxxxxxx long text" you could use ```yaml
message: >-
xxxxxxx long text line 1
xxxxxxx long text line 2...
@visual aspen It is not {{ state('sensor.discord_maciekish_1045') }} it should be {{ states('sensor.discord_maciekish_1045') }}. Notice the difference between state and states
This is what it looks like with all the sensors on. You can see there's no comma between the different groups, if sensors are off then there are some extra spaces.
"The alarm has been triggered, the following sensor: Front Door Sensor, Garage Door Sensor, Patio Door Sensor Kitchen Window Sensor, Left Great Room Window Sensor, Left Office Window Sensor, Right Great Room Window Sensor, Right Office Window Sensor Foyer Motion Sensor, Master Bedroom Motion Sensor, Mudroom Motion Sensor "
@next shell ok - how would you like to have the spacing and commas?
yes, made it a multi-line and now have empty lines if there're no active sensors in one of the groups.
ok - you can add {{- instead of {{ and also -}} instead of }}. play in the template editor until you get it right
adding - would eliminate white spaces
i'm starting to think it'll be easier to create a single group with all related sensors for the alarm.
ok, i'll try that
I was going to suggest that - add all the interested sensors in a single group
Thanks for the help, Iโll play with it a bit more and create the new group if I canโt get it right.
@queen meteor is there a way to use that same template with two states?
ah, let me see..
Yea because most are binary sensors and two are the garage sensor with open, closing, close and opening states.
@next shell you could do something like this: ```
{% set group_name = 'group.kitchen' %}
{% for item in state_attr(group_name, 'entity_id') if states[item].state in ['on', 'open'] %}
{%- if loop.first %}{% elif loop.last %} and {% else %}, {% endif -%}
{{ states[item].name }}
{%- endfor %}
change the group name and you should be set
it is not going to be one liner like you had before, but this should do it
Ok Iโll try it in a couple minutes and report back. Thanks.
@queen meteor thank you very much for helping me again, it works perfectly.
Is there a way to get the current Logged in user's name in template? First guess is no. (Without using a custom card)
no as the front end doesn't support templates and the backend stuff doesn't care
it's not possible to use {% if %} in an attribute_templates?
Should be. Did you remember to quote it?
hm
attribute_templates: >-
{% if "5427" in state_attr("sensor.vg_municipality_stats", "municipalities") %}
confirmed: {{ state_attr("sensor.vg_municipality_stats", "municipalities")["5427"]["confirmed"] }}
{% endif %}
this is how it looks now
"Invalid config for [sensor.template]: expected a dictionary for dictionary value @ data['sensors']['corona_skjervoy_confirmed']['attribute_templates']. Got '{% if "5427" in"
that's what i'm getting instead
You need some else ๐
If it's not in the confirmed you have a blank
{% if "5427" in state_attr("sensor.vg_municipality_stats", "municipalities") %}
confirmed: {{ state_attr("sensor.vg_municipality_stats", "municipalities")["5427"]["confirmed"] }}
{% else %}
confirmed: 0
{% endif %}
``` for example
still didn't validate
Ah. I see
You probably can't define the attribute key in the template. Try yaml attribute_templates: confirmed: >- template goes here
oh no.. so i need a if else for all of the attributes? ๐
i have a bunch
the example was just for one of them.. but there's 5 of them..
so there will be one if/else for each attribute? ๐
Let me test something
basically i have a json structure that i want to represent as a more readable attribute structure.. so instead of a truncated json object like this in the attribute list:
{'confirmed': 63, 'ratio': 0.82, 'recovered': 0, 'dead': 0, 'population': 76974}
then i want this as a column output, like other attributes.. so that each of them is their own attribute
so it'll be like this:
confirmed: 63
ratio: 0.82
recovered: 0
dead: 0
population: 76974
and yes, this is corona time ๐
Ok, try {{ state_attr("sensor.vg_municipality_stats, "municipalities").get("5427", {"confirmed":0})["confirmed"] }}
Or maybe {{ state_attr("sensor.vg_municipality_stats, "municipalities").get("5427", {}).get("confirmed",0) }}
yaaaay!
let's see
let's see if it works where the key is not present
looks like it's working.. though i'd rather for it to not create the attributes if the key is not present
and is there a way to loop through all the keys and automatically create the attributes or do i have to spell out each and every one?
That's can't be done with a template entity, I'm afraid.
ok, so i need to spell out each and every attribute?
Afraid so. Or move onto something more powerfull, like appdaemon, netdaemon, python_script (won't be easy in this case) or make a custom component.
what about not creating the attribute if the value is 0 (or non-existent)?
Would work for some people and not at all for others.
attribute_templates:
confirmed: '{{ state_attr("sensor.vg_municipality_stats", "municipalities").get("5428", {}).get("confirmed",0) }}'
dead: '{{ state_attr("sensor.vg_municipality_stats", "municipalities").get("5428", {}).get("dead",0) }}'
population: '{{ state_attr("sensor.vg_municipality_stats", "municipalities").get("5428", {}).get("population",0) }}'
ratio: '{{ state_attr("sensor.vg_municipality_stats", "municipalities").get("5428", {}).get("ratio",0) }}'
recovered: '{{ state_attr("sensor.vg_municipality_stats", "municipalities").get("5428", {}).get("recovered",0) }}'
this is how it looks for each of the attributes
but can i set a variable earlier on that can be used? to set the "5428" earlier on as a variable for this entity? and then reuse the code?
because i have around 20 sensors like this
No. It would have to be in the same template, which is delimited by the string - i.e. ' '