#templates-archived
1 messages · Page 147 of 1
How would I get n minutes in the future within a template?
I know there's now() but I'm a little disoriented to figure this out on my own because there are things missing I would have expected like the type() builtin. Not sure how to go about searching
Worked it out:
{{ now() + timedelta(minutes=5) }}
Thanks 
any tips on why this is not working https://pastebin.com/NEtYwKqd
https://postimg.cc/N5jhSxtZ is the helper
have I over complicated it ?
hello, i'm trying to create month dependent template sensor like this
{% set winter = ['1', '2', '3', '11', '12'] %}
{% if now().month not in winter %} not winter {% else %} winter {% endif %}
But it does not work.. what i'm doing wrong?
doh.. {% set winter = [1, 2, 3, 11, 12] %} worked, maybe i've mixed strings with integers
😆😆😆😆😆 dammm you are my personal hero number 1... I can't believe the time that I waited for this.... This should have been the top change of this release... I didn't noticed it at all.. tks
you did mix them. now().month is an int. a number in quotes is a string
look at your template, then look at the states you chose for the input_select... You're making a simple mistake
- platform: mqtt
name: "Outdoor Power Temperature"
state_topic: "rtl_433/Blueline-PowerCost/12080/temperature_C"
unit_of_measurement: '°C'
value_template: “{{ (value | round(1)) | float }}”
Anyone know why my temperature is still showing up as a string in my dashboard?
How would you know?
After adding the value template, it changed to this : https://i.imgur.com/TfRsp12.png
you should be getting other errors in your logs if the curly quotes are coming through.
Oh, yeah. The quotes are fancy
I use this in my cover template:
{{ states('sensor.wohnzimmer_curtain_2_position') }}"
which goes from 0 (open) to 100 (closed)
I use this in position_template which apparently reads 0 as closed and 100 as open
how can i switch these?
i get the current value with {{ value_json.body.slidePosition }}
eh, | float *-1 + 100 does the trick thank you all, very helpful 😡
you'll have to switch your set_position too
what? 😄
hm, you might be right
ooof
yep still did not do, it maybe because I was following a guide lol petro
what is that I tried a few edits with no luck (does it matter that these are HA imported hue scenes)?
No, you’re making a clerical error. Your template is correct but your doubling something.
Copy your configuration into the template editor. Not just the template and see what the output is.
This template listens for the following state changed events:
Entity: input_select.aj_room_scene
Just do what I asked and look at the output
https://pastebin.com/duLiuNg0 changed helper name and what I think was the issue
Nope, still same mistake
Paste that entire chunk into your template editor
And look at the fields where you template and the results of that field
https://pastebin.com/Raqj0NwY ah I think its right the last scene is listed, so trigger must not be working
Nope, not it
What field are you templating?
Type it in here so I know you know
This isn’t a trick question. I’m trying to gage what you know.
I was just typing I am old and only 4 months in still, I know some, but always get stuck when it comes to templating a fair bit, normally work it out but yes I am still a noob. but I presume the field is the condition value.
condition state lol I meant (which probably means i know nothing lol)
not really some more education is needed
probably my own fault for following a guide on this one lol
You shouldn’t be using templates if you can’t even identify a template in yaml
so have you figured out what your template is?
This is a very simple question
I know the template is the state.
no
{{ part or are you referring to what I wanted it to do
Ok, that's identifying the template
so what field is it in
this should be a 1 word answer.
it involves you looking to the left.
it's that simple.
you mean the type of code?
No.. what freaking yaml field is it in
well jinja (which I am trying to learn is not yaml)
what:
yaml:
field:
is:
it:
in:
it's not hard man
i'm trying to lead you to your problem and I can't even do that
it's entity_id
your template is in the entity_id field.
Ok, now that you know it's the entity_id field that the template is in. What is the result of that field in the last link you posted?
paste that result here.
ROFLMAO.... if you look over are previous private chats I was not this bad lol 😛
mabye I should of got some sleep after last nights night shift
so did you figure out the issue?
if not, paste the result of taht field from your last link.
no, paste just the reuslt of your template, which you now know is the result that you should see after the entity_id field
its changing the scene but under enter id if I roll the dial round
(in the results page)
but not actually changing it light wise
dude
just look at your field and past the result here. Stop looking in the wrong place. Stay with me,.
I'm trying to show you how to debug your stuff
by leading you down the path
and you aren't doing that, you're looking in the wrong spots
just do exactly as I ask and I'll lead you to the answer
ok so the original script shows the entity_id scene. part (template) the result shows what I just pasted
Yes. Paste the result of JUST the entity_id field in this chat
entity_id: scene.scene.front_bedroom_concentrate
ok, now, focus on that field
and it changes if I roll the dial
scene.scene lol
Do you at least see the process you should use when testing this stuff now?
its a dial that has 3 dial modes, normal toggle, brightness up and down and color temp and 3 taps and turns into scene selector
almost 3 dials in one
Im not massively familiar with template sensors - but I am trying to take two sensors and minus one from the other to give a result.
What have I overlooked here please
sensors:
- name: "Flow & Return Differential"
unit_of_measurement: "°C"
state: >
{% set flow = states('sensor.flow_temperature') | float %}
{% set return = states('sensor.return_temperature') | float %}
{{ (flow - return) | round(1, default=0) }}```
The only thing you have missed is a default value for your |float filters.
I took an example from the docs and changed the entity to match mine and changed the maths operations to suit my needs - but other than that - nothing changed. But it wont let me restart HA
What error are you getting?
its a config error - let me grab it
I guess there is nothiing wrong with the template, but rather with the yaml for the sensor itself
Oh hang on. You have half the old and half the new format
New format```
template:
- sensor:
-
name: "Flow & Return Differential"
unit_of_measurement: "°C"
state: >
{% set flow = states('sensor.flow_temperature') | float %}
{% set return = states('sensor.return_temperature') | float %}{{ (flow - return) | round(1, default=0) }}
-
so literally the top two lines ?
Yes
Also this goes in your configuration.yaml file, not sensors.yaml
yeah it was is the config - thanks - it seems to be restarting now
so i have some "older" sensors (templated) - but they still work - do I need to change them at all ?
No need right now, but the new format supports more attributes, like e.g. state_class, which allows it to be added to the long term statistics
Don't know if the legacy template will become depreciated in the future.
Hi all, is there a way how to pop the value from a list? To append value we can merge lists like {% set b = b + ['a'] %}, but how to remove the 'a'?
Hello folks, I'm having some trouble with universal media player rendering a template for it's state.. what I have works fine in the 'developer tools' but when I add it to my config the state always shows 'off'
Here is what I'm using if anyone can see why it wouldn't work..
basically, i'm aiming for the state to be 'playing' if the remote activity is Xbox, otherwise take the state from the actual media device i'm using
Something like this?
{% set list1 = [ 'a', 'b' ,'c'] %}
{% set list2 = [ 'a', 'd', 'e' ] %}
{{ (list1 + list2) | reject('eq', 'a') | list }}
state is not an attribute, you should use state_template and you should not put it under attributes:
ah jesus... i just realised it's state_template...
🤦♂️
I spent like an hour last night mucking around with the template trying to figure out why it didn't apply 🤣
Exactly what I was looking for! I started worrying, this function does not exist. Appreciate your help!
Check the pins for some links to more jinja information
Believe me I was in the topics and docu last two days. To be honest, from my perspective Jinja is pure disaster (functionality, readability, documentation) and am wondering how it could even survive. But thanks god for people like you. I don't know why is HASS using it but I assume there's a good reason, is there a topic about it? Please don't take it as an attack. Truly appreciate your help here
Jinja is easy to learn, read, and use. It's arguably easier than python. Jinja has been used since day 1 in home assistant.
there is no discussion about it's use
Yeah, I think (but not 100%) I've read your answer already in some topic, when someone else was questioning Jinja. And unfortunately I do not agree with you at all. But I still do accept that HASS developers can see benefit in it. Just wondering if there is any mention about it.
Well, I can't say I'm on petro's level, but I can handle the jinja templates quite well, without a programming background and about 1,5 year of tinkering around with them.
So I would agree that it is relatively easy to learn
it's a lightweight, object safe (i.e. won't break HA's internals), easy to learn, formatting language. It's perfect for the use in HA. What else would you want to use?
@mighty ledge I will not open this pandora box, just looking for answers and definitely trying to learn this thing even though it drives me crazy. Am pretty on same level as you are @marble jackal , I didn't have programming background but as a software consultant I start write some stuffs like a 1.5y ago and since I was able to write some pretty codes in JS, C and mainly in PYTHON, but putting together Jinja code takes me ages and together with yaml I have to use workaround on workarounds. So spending really days in documentation and topics to write something what I can have in python in few hours (@mighty ledge I bear in mind what was in that topic mentioned about python). So someone could probably ask me why I do not use python than, if I can. The answer is easy, I want to use HASS as it is with it's own features. BUt yeah I was really pretty close to rather write a component than bit more complex automation. But again, hopefully no one is taking this personally
I don’t understand how you see this as different than python. The syntax is identical if you avoid filters. The only thing that’s different is loop scope and using the word set.
Filters are used to avoid the loop scope issues and they create generators and are meant to be easy to read and understand. You’re filtering your list as you move further left.
To me, it seems like you don’t understand the basics of filtering using objects and that’s your problem with jinja.
Definitely agree with you here. I don't understand the basics of filtering. And yes I can't see enough similarities with python, e.g. my first question here today about using lists, which is being solved using filtering again. And no it's not easily readable as python is (my opinion) even JS is easier to read (again just my opinion). And I don't think am a silly person, so definitely trying to learn this and understand how it works, so possibly help to others in the future. But as mentioned above, Jinja is not well documented and also does not have very wide community. Whichever dev I asked if s/he knows jinja, I never got positive answer, just from people using HASS.
Jinja is used to serve up forms comprised of strings. It's a markup language designed to be object and memory safe. Every language has built-on language like this, this is pythons version.
you want to learn filters, and they are very easy to understand if you understand lambda in python and its 1000x easier to read than pythons lambda functions
just to compare some for loops...
python
for x in ['a', 'b', 'c']:
if x in y:
...
jinja
for x in ['a','b','c'] if x in y
or
for x in ['a','b','c'] | select('in', y)
which ones the easiest to read?
just take the time to learn filters and you'll see that they are WAY easier to read at a glance.
and typically less verbose
as well as more memory efficient because they use generators instead of lists
the only drawbacks to jinja are built in on purpose. I.e. make jinja object and memory safe. E.g. You can't create classes, you can't merge objects, etc
I is there a way to get fetch context.user_id in automation using templates from call_service events. All examples seem to use to_state.context but call_service events only seem to have to root context node. (not under data as they are in state_changed events.
@ashen hawk posted a code wall, it is moved here --> https://hastebin.com/afehirapet
can you show the event from the event viewer?
Nevermind, I just looked at it
I don't think you have access to it
unless it's just trigger.context
well, it could be trigger.event.context
seeing that it's at the root level of the event. That's probably it now that I think about it.
Thank you for putting effort to explain this, I will take a look on it properly. Just can't right now. And yes at glance this looks similar and easy (not the last solution), but still add jinja's bloat paranthesis, write longer code than just one straigh forward example and this thing becomes nasty, meanwhile python stays as you have written it.
Happy day to all, and thanks again for you interactions!
Trigger.context or trigger.event.context?
the latter
if you use filters properly, there isn't parenthesis bloat. Many many many examples on the forums over use parenthesis.
I purposely remove them all when I reply
order of operations is identical to python's order of operations
YEY! trigger.event.context.user_id worked!
pemdas
Thanks!
np
Hm. But now I need some black magic to "guess" based on time of this was done through the home-assistant or by other means. I have a sonos tts notification that says "Garage has been open for 30 minutes", I wanted it to say "Garage has been open for 30 minutes and it's X's fault". But I then have to check that the input_text field was updated approx 30 minutes + 10 seconds ago..... Wish me luck! 🙂
I do that by logging who opened the door originally
Cool.Care to share how?
Yup. I know.
unless you know exactly who opened it through the interface
context is only populated when the frontend is used
Well that I do know now. Since I update the "last_opened_by" input.text field that can be included in any input
My challenge is that there are multiple other ways to open the garage. All of them create the state "open/closed" because I have a door sensor. But that sensor has no idea what triggered it (its a curl call)
Hm. I can reset the text field on close. And if it's not updated.. Then it's done by other means. That might work. Yeye.
Yes, I created a sensor named: people_at_home
and it's basically a list of people at home
and if I don't know the context, I list out who it could be
using people_at_home
just create a group with all the people named group.people and then you can use that template sensor in your setup
the or and and ttributes lists out the people nicely in english
But I've found a way now. If i update the opened_by textfield to "system" when it's closed. So if its done outside it will be "system", unless someone actually fired the script.
Yah but there's no fun in that
So it will be the system's fault that the door is open?
I found that it's always the systems fault
hence why I made the people tracker
aka, it's one of these people who opened the door
but you have to store the list of people with the open event. Requiring another sensor. That's where I use MQTT
you can also use it to persist through shutdowns
Got a quick question, my mind doesn't seem to want to be able to figure this out.
I've got an iframe with a URL, and I want to change a portion of that URL with contents of an input_text state. How would I go about doing this?
I've tried doing things like this: .../file/clips/{{states['input_text.alert_clip_db_number'].state}}?mode=mjpeg... without any luck.
Using the Template Editor, it works. Does this just mean that iframe doesn't support templates? How does one get around this?
you can't template iframes
oof
What if I stored the entire URL in the input_text? Would I be able to just pull from that?
mjpeg
Not sure why I didn't think of that
That's how I used to do my cameras. Haha - thanks
Although, not sure how I'd incorporate a template into the mjpeg_url - putting it straight into the config yaml as a template doesn't work for sure.
There will never be a time where two input_text.alert_clip_db_number states are the same
I can't believe you can't template an iframe url. Hahaha. That's crazy
Are custom_widgets still a thing?
I've never heard of them before. Looks like there might have been a custom 'widget' that could help.
you can't template anything in the frontend except for markdown card. This should come as no surprise
you can use a custom card to template the iframe. Like the custom-template card
but it requires js templating
Is there a way to kind of debug the trigger object, or all variables/object accessible in an automation? For other objects like states and such i can of course use dev tools templating, but that does not work with the trigger object for example.
you can create a similar dictionary in the template editor
If you download the json file from the trace you can copy/paste it from a previous run
Ahh, didn't think of the trace, thanks!
Can anyone see what i'm doing wrong here? Trying to make a sensor with the amount of snow about to come..
{%- set snow = 0 -%}
{%- for weather in states.weather.home_hourly.attributes.forecast -%}
{%- if weather.condition.split('snow') -%}
{%- set snow = snow + weather.precipitation -%}
{{snow}} #Becomes the same as weather.precipitation
{%- endif -%}
{%- endfor -%}
{{snow}} #expecting accumulated for all hours, but becomes 0.
You need to use a namespace to use variables in and out of a for loop
Random example from history: #templates-archived message
ahhh, right, i think i've done that error before. Thanks, it was driving me mad.
It's not at all obvious
Nope. I work as a developer, so it was really illogical that it didn't work
fuck me, 104cm snow😩 Not considering probabilty and using the thumb rule of 1mm precipitation == 1cm snow
Palm trees and sunshine here, so good luck with that 🙂
Hah, thanks!
Also, is there a way to add to a variable in another way than var = var + var, like var += var?
I don't think so, but you're welcome to run a 1second test
There are more verbose ways
i tried the usual tricks i know, but those didn't work. well, x = x + y works, so.
hello, I have a question regarding how to pass two arrays in my script
sequence:
- service: icloud.play_sound
data:
account: !secret stefan_icloud_account
device_name: !secret stefan_icloud_device
- service: icloud.play_sound
data:
account: !secret anja_icloud_account
device_name: !secret anja_icloud_device
what I actually want to pass two variables of arrays for example first array [account1, account2, ..] and second [device_name1, device_name2,...] and to do for loop to match each pair and to trigger service: icloud.play_sound
I want to create script that is uniform regardless on how many devices I have
Do you always want to find all?
But anyway, you could probably do this:
# secrets.yaml
accounts: [ 'account1', 'account2', 'account3' ]
devices: ['device1', 'device2', 'device3' ]
# script
alias: Find Iphone
sequence:
- variables:
accounts: !secret accounts
device: !secret devices
- repeat:
count: "{{ accounts | count }}"
sequence:
- service: icloud.play_sound
data:
account: "{{ accounts[repeat.index -1] }}"
device_name: "{{ devices[repeat.index -1] }}"
Not completely sure if you can import a list like that from secrets.yaml. Otherwise just put "account1, account2, account3" in secrets.yaml (same for devices) and use accounts.split(', ') | count and accounts.split(', ')[repeat.index -1] (again the same for devices)
thanks @marble jackal I will try
I started with something like this:
sequence:
service: >
{% set data = [{'account':'stefan_icloud_account', 'device_name': 'stefan_icloud_device'}, {'account':'anja_icloud_account', 'device_name': 'anja_icloud_device'}] %}
{% for item in data%}
persistent_notification.create
data:
title: 'item.account'
message: "item.device_name"
{% endfor %}
this is just service persistent_notification, just to see if gonna to work but Im getting an error: Failed to call service script.find_iphone. Template rendered invalid service: persistent_notification.create data: title: 'item.account' message: "item.device_name" persistent_notification.create data: title: 'item.account' message: "item.device_name"
so, I believe that your approach is better, just for easier writing a variable data, I would like to be an complex array like this: [{'account':'stefan_icloud_account', 'device_name': 'stefan_icloud_device'}, {'account':'anja_icloud_account', 'device_name': 'anja_icloud_device'}]
you could use variables for that:
- variables:
data:
- account: stefan_icloud_account
device_name: stefan_icloud_device
- account: anja_icloud_account
device_name: anja_icloud_device
It will be the same dataset as you did, but more readable I guess
And then you can use the repeat:
- repeat:
count: "{{ data | count }}"
sequence:
- service: icloud.play_sound
data:
account: "{{ data[repeat.index -1].account }}"
device_name: "{{ data[repeat.index -1].device_name }}"
can you please post here an example of calling that script?
like this? ```service: icloud.play_sound
data:
- account: stefan_icloud_account
device_name: stefan_icloud_device - account: anja_icloud_account
device_name: anja_icloud_device```
No, just add the two code blocks together.
- variables:
data:
- account: stefan_icloud_account
device_name: stefan_icloud_device
- account: anja_icloud_account
device_name: anja_icloud_device
- repeat:
count: "{{ data | count }}"
sequence:
- service: icloud.play_sound
data:
account: "{{ data[repeat.index -1].account }}"
device_name: "{{ data[repeat.index -1].device_name }}"
because of the counted repeat, it will repeat the icloud.play_sound action 2 times
if you add more accounts/device_names to the variable, it will repeat it more times
yes I know, but this is in the script itself..I want to be able to pass only one set of account and device name
or two, three sets
How do you want to determine to whom it should be sent?
so I was thinking to pass some array in data section when Im executing the script, or multiple device_name/account statetemnt
based on what I put in my data variable (it can be key-value pair)
for example
{% set data = [{'account':'stefan_icloud_account', 'device_name': 'stefan_icloud_device'}, {'account':'anja_icloud_account', 'device_name': 'anja_icloud_device'}] %}
but also I can just send: [{'account':'stefan_icloud_account', 'device_name': 'stefan_icloud_device'}]
Just use what I posted above:
- service: script.find_iphone
data:
phones:
- account: stefan_icloud_account
device_name: stefan_icloud_device
- account: anja_icloud_account
device_name: anja_icloud_device
alias: Find Iphone
sequence:
- repeat:
count: "{{ phones | count }}"
sequence:
- service: icloud.play_sound
data:
account: "{{ phones[repeat.index -1].account }}"
device_name: "{{ phones[repeat.index -1].device_name }}"
But if you want you can also format the variable lin json like you did
- service: script.find_iphone
data:
phones: [{'account':'stefan_icloud_account', 'device_name': 'stefan_icloud_device'}, {'account':'anja_icloud_account', 'device_name': 'anja_icloud_device'}]
it works! thanks @marble jackal
Hi, I'm missing something stupid I think. I'm trying to setup a generic thermostat using a temp sensor and a switch to toggle a space heater.
I made a climate folder in my config and made a file name generic_thermostat.yaml in that folder.
I followed the template provided at https://www.home-assistant.io/integrations/generic_thermostat/#-----configuration-variables--
I saved my file and restarted my homeassistant core.
I expect now to see a thermostart card available named "climate.bedroom_heater" or something similar. But all I'm seeing is my current thermostat as an option.
I haven't used hastebin before, but here is this
Did you point the climate: entry to that folder?
I did not. Is there documentation I should look for to learn more about how to do that?
Hello - how can I make this work please? I think there are so many quote marks it might need escaping somewhere in the media_content_id piece as the 'sensor.next_pm_episode' part is not being rendered as text according to the HA check config tool. Thanks! https://pastebin.com/8bGVFbi6
It works in the template dev tools though… 🤔
'{"app_name": "bbcsounds", "media_id": "{{ states('sensor.next_pm_episode') }}"}'
use double quotes in states('sensor.next_pm_episode')
Thanks! So states("sensor……?
yep. Should work, since whatever in double curly brackets just gets interpreted as python code or something
tricky one: for a template switch, can you add a "wait" or "timeout" for sensing that the switch is actually OFF before HA moves the toggle?
my turn_off command is not instant on the source device, so i switch it off, the toggle goes off, then immediately goes back on, then after 1-2 seconds, it properly reads the state of the source device and goes back to the off position
That won't work, it will break up your template in parts
Thanks - it doesn’t throw a config check error anymore but doesn’t seem to actually play the media… any ideas what would work?
essentially i'd like a way to debounce this behavior.
I'm trying to get my bitcoin miner reporting into my HA
but it seems like the JSON is not quite reporting correctly
when I pull the API Straight I get this output
`{'STATUS': [{'STATUS': 'S', 'When': 1642820988, 'Code': 11, 'Msg': 'Summary', 'Description': 'cgminer 4.9.2'}], 'SUMMARY': [{'Elapsed': 19724, 'MHS av': 55402837.74, 'MHS 5s': 57494209.4, 'MHS 1m': 55588695.16, 'MHS 5m': 55549978.78, 'MHS 15m': 55444417.61, 'HS RT': 55549978.78, 'Found Blocks': 0, 'Getworks': 1300, 'Accepted': 7220, 'Rejected': 1, 'Hardware Errors': 44, 'Utility': 21.96, 'Discarded': 953550, 'Stale': 0, 'Get Failures': 0, 'Local Work': 134003269, 'Remote Failures': 0, 'Network Blocks': 27, 'Total MH': 1092764884270.0, 'Work Utility': 3023.31, 'Difficulty Accepted': 252398752.0, 'Difficulty Rejected': 40336.0, 'Difficulty Stale': 0.0, 'Best Share': 435993055, 'Temperature': 72.0, 'freq_avg': 847, 'Fan Speed In': 7110, 'Fan Speed Out': 7110, 'Voltage': 1230, 'Power': 3429, 'Power_RT': 3430, 'Device Hardware%': 0.0044, 'Device Rejected%': 4.0585, 'Pool Rejected%': 0.016, 'Pool Stale%': 0.0, 'Last getwork': 0, 'Uptime': 21109, 'Chip Data': 'HPND06-19102101 BINV04-192106B', 'Power Current': 248, 'Power Fanspeed': 8850, 'Error Code Count': 0, 'Factory Error Code Count': 0, 'Security Mode': 0, 'Liquid Cooling': False, 'Hash Stable': True, 'Hash Stable Cost Seconds': 2286, 'Hash Deviation%': 0.2697, 'Target Freq': 824, 'Target MHS': 54166464, 'Power Mode': 'Normal', 'Firmware Version': "'20210322.22.REL'", 'CB Platform': 'ALLWINNER_H3', 'CB Version': 'V8', 'MAC': 'C4:08:20:00:E9:F2', 'Factory GHS': 55347, 'Power Limit': 3500, 'Chip Temp Min': 0.0, 'Chip Temp Max': 0.0, 'Chip Temp Avg': 0.0}], 'id': 1}'
'''test'''
damnit
python3 whatminer.py | jq -R 'split(",")'
@zenith junco posted a code wall, it is moved here --> https://hastebin.com/poyevapuyi
@buoyant pine - Thank you for answering the question, but not quite understanding. can you help me with the python script to get it into HA?
'''import json
from whatsminer import WhatsminerAccessToken, WhatsminerAPI
token = WhatsminerAccessToken(ip_address="10.0.1.78")
summary_json = WhatsminerAPI.get_read_only_info(access_token=token, cmd="summary")
print(summary_json)'''
seems like something that would be perfect to update to push data to MQTT and run in a container
btw:
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
Don't forget you can edit your post rather than repeatedly posting the same thing.
For over 15 lines you must use a code share site such as https://www.codepile.net/ (pick YAML for the language) or https://paste.debian.net/ (pick YAML for the language).
@buoyant pine OK - how can I publish a dict into mqtt which I do have, and get publish the results to HA
sorry, not a full on coder but can read and write basic code
and I'll use the codepile from now on. than kyou
the point of me using that command was to show you how to do inline code
it's not three single quotes, it's three backticks
you could look into the paho mqtt python library for that. here's an example of it in use with a project of mine: https://github.com/Tediore/audioflow2mqtt
@buoyant pine can I pay you to format and get it into MQTT? I don't have time to screw with this but I need monitoring on my miner
Or is there a good resource for HA guys that are looking for some work?
$$
I can throw it together tomorrow or Sunday. You don't need to pay me
@buoyant pine How about I donate or do something to pay it forward? I know I can figure it out if I spend the weekend trying to get the formatting correct but at the end of the day I just and to see if a) the miner is working and b) if its overheating. I dont want to have to go down a rabbit hole
If you felt so inclined after I put it together, I do have a buy me a coffee link
Absolutely
Let me know what you need from me
And this seems like something that would be a great module for HA in general athough I dont know the users of whatsminer & HA together
and - I dont know what building a module entails so just tell me to shut up and appreciate the help 😄
Hello, I want to create a sensor which will tells me how many seconds are passed from last trigger to on
I have this {{as_timestamp(states.binary_sensor.bedroom_bed_left_motion.last_changed)
so, with combination with condition-state (triggered on), I think I will be able to know how many seconds passed away from last triggered on state
but I dont know how to cast to seconds, now, i get epoh linux time
{{ as_timestamp(now()) - as_timestamp(states.binary_sensor.bedroom_bed_left_motion.last_changed) }}
thanks!
That gives you seconds, but you also only want it if the state is on?
yes
I want to have a sensor which will be telling me how much secons gone from last trigger state to on
value_template: >
{% if is_state('binary_sensor.bedroom_bed_left_motion', 'on') %}
{{as_timestamp(states.binary_sensor.bedroom_bed_left_motion.last_changed) | timestamp_custom('%A %d-%b-%y, %H:%M:%S')}}
{% else %}
{{ states('sensor.bedroom_bed_left_motion_last_occured') }}
{% endif %}
Actually you probably don't want that first result in seconds. I just edited the post and added your template from the other channel.
Hi everybody!
I'm not sure where to post this, i'm sorry in advance if this is not the correct channel.
I have implemented ESC control for a brushless motor via a ESP8266 using ESPHome.
The values used to control the ESC from HA range from -50 (0%) to 0 (100%)
Is there a way i can clean up these values in order to show them on the lovelace dashboard in the proper % values?
Any pointers are much appreciated!
@obsidian lintel posted a code wall, it is moved here --> https://hastebin.com/alifusinik
I am trying to create a dummy light entity with hue options, I managed to get the brightness working and displaying on my floorplan. Color wise, it didnt work, can anyone advice? https://hastebin.com/alifusinik
You’re missing color templaate
Question on JSON
#WhatsMiner
- platform: command_line
name: WhatsMinerHank
command: "python3 whatminer.py"
value_template: '{{value_json.summary.temperature}}'
give me a unknown
value
It’s case sensitive
#WhatsMiner
- platform: command_line
name: WhatsMinerHank
json_attributes:- Temperature
- Power
command: "python3 whatminer.py"
value_template: '{{ value_json.SUMMARY }}'
So changed the calls to case sensitive
Does not appear to fix it
I have a template (https://pastebin.com/sUW1NRmX) to get the sum of all the consumption of smart plugs or lights. Each time I restart HA or Zigbee the value drops as some or all sensors all unavailable. Giving me a rather larger number of consumption which isn't correct. What I'm doing wrong ? Can this be resolved i a way?
Add an availability template so the sensor is only available when all source sensors are
Or add a statistics sensor to store the max value of your template sensor, and use that value in your template of the result is lower
Or both
@marble jackal could you please help me with an example?
I'm looking in to the statistics as it could always be that an consumption sensor is unavailable
How could I get the max value of
- platform: statistics
name: "Statistics Overall Consumption"
entity_id: sensor.overall_consumption
state_characteristic: mean
hi all! Can you please help me find a way to access a sensor's past value ? (I'd like to get the diff between the actual value and the last one)
thx!
this could probably help you:
https://community.home-assistant.io/t/min-and-max-value-of-the-last-24-hours-on-lovelace/133756/2
Hi everyone. I'm struggling with a recent idea I had. I have a Sonoff S31 (smart plug with power monitoring) that I've connected to my sump pump. I have a binary sensor template that I've created to track if the sump pump is "on" or "off" based on the power usage measured by the S31. This binary sensor is working just fine.
My new goal is to have a way to display (I'm assuming via a new template/entity) the last time that the sump pump was "on" based on this binary sensor's status. I'm building a display in my basement that would read various stats, but include something along the lines of "Sump Pump Last On: Jan 23 2022 8:00AM".
I've researched a few options, tried implementing them. Please take a look at my configuration.yaml code and see if I am close, or if you have any suggestions. Thank you!
https://www.toptal.com/developers/hastebin/wunovoteba.php
Also, I saw this recent advice from tom, which looked to be very close to what I am trying to do. https://discordapp.com/channels/330944238910963714/672223497736421388/934399119953371136
@next bane thanks
Is it somehow possible to template an entire script sequence? I have something which kinda works, but only for service calls.
I now use this:
- repeat:
count: "{{ action | count }}"
sequence:
- service: "{{ action[repeat.index -1].service }}"
target: "{{ action[repeat.index -1].get('target', {}) }}"
data: "{{ action[repeat.index -1].get('data', {}) }}"
I can use scripts as work around, since they can be called using a service call, but if somehow possible I would like to allow all types
Maybe everything below data, but not everything
Okay, I'll work with what I now have then 🙂
everything below service, target and data works
so basically all service calls work
Is there still a need for this? I can probably work on it later
If he doesn’t need it…..I 110% don’t need it. Just saying.
And it is Sunday….you should be busy pampering your better half
calibrated_esc_value:
value_template: '{{ (states.sensor.esc_entity.state|float +50)*2 }}'
calibrated_esc_value_better_if_min_max_available:
value_template: '{{ (states.sensor.esc_entity.state|float - states.sensor.esc_entity.attributes.min) * 100 / (states.sensor.esc_entity.attributes.max - states.sensor.esc_entity.attributes.min) }}'
That might do it.
The second option is more dynamic and allows for variance in the reported min/max of the entity (if it is reported in the attributes of the entity)
@buoyant pine Hey So I got it outputing in JSON instead of DICT
But - I still am getting unknown when I try get it into a template
import json
from whatsminer import WhatsminerAccessToken, WhatsminerAPI
token = WhatsminerAccessToken(ip_address="10.0.1.78")
summary_json = WhatsminerAPI.get_read_only_info(access_token=token, cmd="summary")
json_object = json.dumps(summary_json, indent = 4)
print(json_object)
Outputs to this
#WhatsMiner
- platform: command_line
name: whatsminerhank
json_attributes:
- Temperature
- Power
command: "python3 whatminer.py"
Is what I have in my configation.yaml
after the ticks hit enter, the ticks at the start and end of the code should be on their own line... don't repost the code just edit the post you made
I'm still doing it wrong 😦
The ticks are '`' the key is to the left of the number 1, you appear to be tying the single quote
Try adding:
value_template: "{{ value_json['STATUS']['STATUS'] }}"
Between json_attributes and command or after name I don't think the location matters
#WhatsMiner
- platform: command_line
name: whatsminerhank
json_attributes:
- Temperature
- Power
value_template: "{{ value_json['STATUS']['STATUS'] }}"
command: "python3 whatminer.py"
Still saying unknown
Testing after name, before json_att
Probably exceeds the state length limit
Check the log
Oh, nvm. Status, not summary
"{{ value_json['STATUS'][0]['STATUS'] }}"
@zenith junco
Still unknonw
#WhatsMiner
- platform: command_line
name: whatsminerhank
value_template: "{{ value_json['STATUS'][0]['STATUS'] }}"
json_attributes:
- Temperature
- Power
command: "python3 whatminer.py"
Check the log
Nothing is log as far as I can see. Searching for whatsminer
really need some logs
logger:
default: critical
logs:
homeassistant.components.http.ban: warning
homeassistant.components.sensor: debug
homeassistant.components.serial: debug
homeassistant.components.sensor.serial: debug
Can I crank up the logs on this?
your default is set to critical? that means you basically get no logs
k, fixing
Logger: homeassistant.components.command_line
Source: components/command_line/__init__.py:41
Integration: command_line (documentation, issues)
First occurred: 9:03:02 PM (2 occurrences)
Last logged: 9:04:03 PM
Command failed: python3 whatminer.py
use the absolute path of the file in the container
I have another file in the same location that works
##Niles Home Audio
- platform: command_line
name: NilesActive
command: "python3 pyserialtest.py znc,5"
I mean, I'll try the absolute path but its weird that one would work and one wouldn't
exec into the container and run the command
I'm trying to take a binary vibration sensor and turn it into my Dryer's status. But I want to delay the "Dryer Status" sensor from changing unless the vibration sensor has been in the Clear or Detected state for longer than a certain duration. Ican't figure out how to set this up in my config yaml
@real terrace Node Red works really well for doing that Kind of function
trigger-based template binary sensor with delay_off: https://www.home-assistant.io/integrations/template/#trigger-based-template-sensors
what kind of vibration sensor are you using
and yes, listen to Tediore - I'm mediocre at best 😄
@buoyant pine So you want me to do
docker exec -it container-name sh
and then run the shel command
?
/config # python3 whatminer.py
Traceback (most recent call last):
File "/config/whatminer.py", line 3, in <module>
from whatsminer import WhatsminerAccessToken, WhatsminerAPI
ModuleNotFoundError: No module named 'whatsminer'
/config #
or just do docker exec -it home-assistant python3 whatminer.py
well yeah, but you'd need to do that every time you upgrade the container
ick
which is why i suggested my solution 😄
what solution? Sorry Maybe I missed it
what we talked about the other day
making a container of it that pushes the data to MQTT
i said i'd make it
i was asking here if you still need it: #templates-archived message
Well I would owe you 🙂
you wouldn't; i do this stuff for fun
Yes, I saw that, but I figured I was making progress getting it into JSON
😄
I would very much appreciate a module that would publish to MQTT
i'll probably have some time tonight
Thank you!
hello, can you please tell me what is wrong with my script that it has rgb_color templating:
Im getting the eror:
[22870602721072] Error handling message: None for dictionary value @ data['rgb_color']. Got None
more precise question would be: is this legit:
["{{range(256)|random}}","{{range(256)|random}}","{{range(256)|random}}"]```
no, your numbers are in quotes
it expects a list of numbers, not a list of string numbers
you're confusing yourself by using the >
remove the quotes or remove the arrow and put it on the line above
Yes, I had earlier like this: rgb_color: > [{{range(256)|random}},{{range(256)|random}},{{range(256)|random}}]
but the same error message occurs
when I put this template into my template editor Im getting like this: [ 223, 178, 209 ]
that should work, are you sure you're looking at the most recent error?
could save 8 chars and probably a bit of processing time if you render the thing as one template instead of 3
hmm eventually I had a problem in other section of my script: rgb_color: "{{rgb}}"
and this is my input variable
description: 'If rgb random is False, sets wled light to provided rgb color'
example: '[0,255,0]' ```
I'm unsure if this is allowed, but I didn't see any responses to my question from over the weekend. Does anyone have a chance to take a look at this request for help? #templates-archived message
Sump Pump Last On Template
make a template sensor with a trigger for on. Otherwise templates will fail to resolve when everythings off even though there was something that was last on.
template:
- trigger:
- platform: state
entity_id: xyz.abc
to: "on"
sensor:
- name: Last on for xyz.abc
unique_id: last_on_for_xyz_abc
state: "{{ now() }}"
device_class: timestamp
it won't persist through shutdowns. If you want that, make an automation that sets an input_datetime
Okay, I will take a swing at it with this information. Will likely need to wait until after work hours on the east coast before I can start testing.
I feel like I am missing some understanding in how to define these templates... Is there a resource outside of then documentation (I feel like I've read over it a few times now) that you could refer me to?
I have no idea what you mean. The docs cover it all. If you don't understand something ask.
Okay, I'll review the internal docs again and follow up with any questions. Thanks for the help!
This sensor should stay "on" for 2 hours after it stops snowing or sleeting correct?
binary_sensor:
platform: template
sensors:
snowing:
friendly_name: Snowing
value_template: >-
{{ states('sensor.dark_sky_precip') in ['snow', 'sleet'] }}
delay_off:
minutes: 120
Yes, but I'm not 100% sure if delay_off accepts this format.
delay_off: "02:00:00" will for sure
It’s any format
Thanks, I will try that. I was basing it off of this example in the docs. https://www.home-assistant.io/integrations/template/#washing-machine-running
Is there something that could cause this to break? Earlier, sensor.dark_sky_precip changed from "snow" to "unknown" at 12:03 and the sensor turned off at 12:06
Hi i am trying to create a sensor which gives the remaining time of a running timer (set in an automation )
{{ (as_timestamp(state_attr('timer.leaving', 'remaining')) - as_timestamp(now())) | timestamp_custom('%Mm %Ss') }}
But this is throwing an error any help?
Define an error
TypeError: unsupported operand type(s) for -: 'NoneType' and 'float'
This works if you replace the timer with yours
{% set seconds = (as_datetime(state_attr('timer.vaatwasser_timer', 'finishes_at')) - now()).seconds %}
{% set hours = (seconds / 3600) | int %}
{% set minutes = ((seconds - hours * 3600) / 60) | int %}
{{ hours ~ 'h ' ~ minutes ~ 'm' }}
It gives this error TypeError: float() argument must be a string or a number, not 'NoneType'
Evening all, don't suppose anybody would mind point out something I'm failing at here
wait_template: "{{ state_attr('climate.heating_2', 'temperature') == (states('input_number.boost_target_temperature')) }}"
Both figures from state_attr('climate.heating_2', 'temperature') and ('input_number.boost_target_temperature')) are coming out at 24.9 but it's returning false...
Are they returned as strings or float?
@craggy rain posted a code wall, it is moved here --> https://hastebin.com/wizenelofe
I had a follow up question that was too much text/code. Please find it here when you have a chance: https://hastebin.com/wizenelofe
Hey guys, in my configuration.yaml I have "switch: !include switch.yaml" but when I try to edit my switch.yaml file to add a virtual switch I have the following on line 1 - platform: switch Property platform is not allowed
does anyone know why I would be getting that?
yes, you have switch: on teh first line and you should remove it
I don't have switch: on the first line, the first line is " - platform: switch"
ok, then I wonder what you're hoping to get from platform: switch
to create a virtual switch?
I have "switch: !include switch.yaml" in the configuration.yaml file to include the switch.yaml file so I shouldn't need the switch: on the first line
that is true
because the config is calling that file under the include command
Yes... ?
something like this... https://www.home-assistant.io/docs/configuration/splitting_configuration/
where it's saying the light switches are using the platform switch not template
then that says platform: template
that's for a light switch
if you're talking about this:
- platform: switch
name: "Patio Lights"
entity_id: switch.patio_lights
that's under light:
this is why I asked what a "virtual switch" is - it isn't really a thing
ok... what I was using before Home Assistant was Samsung Smartthings where I could create a virtual switch that could trigger something... is there no way for me to create a switch without having something physical to tie it to?
that's the template switch that I mentioned above
you can do whatever you want when it turns on and off
I've had HA for only a few weeks and know... not a whole lot about it.
that's just a thing that you can turn on and off and can trigger things
it's called a "toggle" in the UI
So if I wanted to have a button on the lovelace screen to trigger something in node red, the input boolean would be what I want?
a button generally has no state
you would just use a button card and do somethign in the action
ok, the button would toggle on/off or set a state, which in turn would trigger something in node red
ok, thanks for the help
@inner mesa, the input_boolean did the trick. Thanks for pointing it out.
hello. I have setup a statistics sensor. How do I round its value to an integer (its a mean value)?
do I need to make another sensor and use value_template?
hi friends. i can't figure out what i'm doing wrong here to exclude these under cabinet lights. everything else in this template is working correctly: {% if expand(states.light)| selectattr('state','eq','on')| rejectattr('attributes.type','eq','browser_mod' )|rejectattr('cabinet' in 'attributes.friendly_name') | list | count == 1 %} There is a light on {% elif expand(states.light)| selectattr('state','eq','on')| rejectattr('attributes.type','eq','browser_mod' )|rejectattr('cabinet' in 'attributes.friendly_name') | list | count > 1 %} There are {{ expand(states.light)| selectattr('state','eq','on')| rejectattr('attributes.type','eq','browser_mod' )|rejectattr('cabinet' in 'attributes.friendly_name') | list | count }} lights on {% else %} All lights are off {% endif %}
You're using rejectattr with two different forms, and only the first is correct
my first attempt was rejectattr('attributes.friendly_name','in','Under') - equally unsuccessful 😦
aha, thanks
https://jinja.palletsprojects.com/en/3.0.x/templates/#builtin-tests doesn't mention search anywhere
Good morning, I have a specific question trying to better understand the different use of {} and {{}} in automations.
I have read in the jinja docs that {} is for statements and {{}} for expressions.
I did however come across some instances where someone puts an if statement between {{}}. So now I'm a bit confused.
Hi! 😉
😉
Well, I'm not sure about the terminology here, but as I see it, you can write an if statement in a expression.
{{ 'hello' if is_state('person.you', 'home') else 'goodbye' }}
Is basically the same as:
{% if is_state('person.you', 'home') %}
hello
{% else %}
goodbye
{% endif %}
Depends a bit on how complicated your if/elif/else statement is, and how you are using the result on which one is more appropriate
And would this be a viable use?
- service: switch.turn_{{ 'on' if trigger.atribute == 'sunset' else 'off' }}
ah I'll have a look in templates in the dev tools
not sure what trigger.attribute should refer to, but it is a valid use
do you mean trigger.id?
the trigger is the sun platform
What do you have as trigger?
Please do note that the trigger data is only available in the automation itself, so you can not use that in
> templates
unless you copy it from a previous run of the automation (from the trace) and define it in the template checker
Just discovered that
alias: Buiten verlichting in de nacht
description: Zet de buitenlampen aan bij schemering en nacht
trigger:
- platform: sun
entity_id: sun.sun
atribute: sunset
- platform: sun
entity_id: sun.sun
atribute: sunrise
action:
service_template:
- service: switch.turn_{{ 'on' if trigger.atribute == 'sunset' else 'off' }}
target:
{% if state(light.tuin_schuur_251 == "off" %} - entity_id: light.tuin_schuur_251 {% endif %}
- entity_id: group.tuinlampen_lights
mode: single
if you change it to:
trigger:
- platform: sun
entity_id: sun.sun
atribute: sunset
id: "on"
- platform: sun
entity_id: sun.sun
atribute: sunrise
id: "off"
then I can use trigger.id ?
you can use:
action:
- service: switch.turn_{{ trigger.id }}
ah clean
service_template is depreciated a long time ago
and your template for target won't work like this
What are you trying to do there?
I want to check if a main switch is on or off. If off I need to turn it on first. In the lights group there is a light (Hue) that only works if the main power to it is on.
you can not turn on a group with the service switch.turn_on
do you also want to turn that switch off on sunrise?
that specific main switch? no.
btw your triggers are also incorrect. have a look at the docs https://www.home-assistant.io/docs/automation/trigger/#sun-trigger
You are mixing different trigger types
either use:
- platform: sun
event: sunset
ah sunset and sunrise are not attributes. They are events of sun (happening at certain timing of attributes of sun.sun)
or
- platform: state
entity_id: sun.sun
to: above_horizon
or
- platform: numeric_state
entity_id: sun.sun
attribute: elevation
above: 0
correct
elevation is an attribute
and the state of the entity sun.sun is either above_horizon or below_horizon
But, to go back to the action part. I think you could use this (after you fix the trigger):
- service: homeassistant.turn_{{ trigger.id }}
target:
entity_id: >
{% if trigger.id == 'on' %}
[ 'light.tuin_schuur_251', 'group.tuinlampen_lights' ]
{% else %}
[ 'group.tuinlampen_lights' ]
{% endif %}
messed up some quotes
note I'm using homeassistant.turn_on now, which can toggle everything which can be toggled
cool, was trying to search for how to turn on a group with different types of entities in it (Switches and lights)
But, you could avoid using templates at all by using choose https://www.home-assistant.io/docs/scripts/#choose-a-group-of-actions
But in that case we should move back to #automations-archived
indentation was also off, fixed that now
🙂
@merry furnace posted a code wall, it is moved here --> https://hastebin.com/imepefejox
Is there a question?
if you just put the timestamp device class senor in the UI, it will show you the relative time. If you don't like that format, you'll have to do what you did. But your quoting is wrong. Interior quotes should be ' and exterior quotes should be " or vice versa.
No, sorry, I saw that HassBot pushed my code to hastebin and then signed on with codepile to paste the code in that way. I think that's how I should have posted it?
well you didn't ask a question with the code
I have this template to get the next event from these calendars. Two of calendars do not have events so the start_time attribute is "None". This is causing an error with the min filter. I assume I need to use either is_number or is_numeric somewhere but not sure where.
value_template: >-
{% set event = [
(states.calendar.family_gmail_com.attributes.start_time) | as_timestamp,
(states.calendar.glen_meet_event_calendar.attributes.start_time) | as_timestamp,
(states.calendar.teamsnap.attributes.start_time) | as_timestamp,
(states.calendar.legacy_center_llc_calendar.attributes.start_time) | as_timestamp,
(states.calendar.total_sports_complex_calendar.attributes.start_time) | as_timestamp ] %}
{{ event | min | timestamp_custom ('%b %-d, %Y', false) }}
that is correct, if the calendar doesn't have any events, that attribute is not even present
oh
I should say that the array of values shows "None"
value_template: >-
[1643142600.0, None, 1643140800.0, None, None]
that is the output without the min filter
I don't know if that's a typed value or a string, but you can probably filter it with reject('eq', None)
(sorry, multitasking)
equals
gotcha
the same as '=='
One other question, another attribute for these calendars is "location" I would like to only include events in the array that have a location (not blank). Would that be a filter to include for each calendar?
yes
reject('eq', none) jinja doesn't like None
could be. they claimed success, though 🙂
I think I remember seeing something similar for true vs. True. I just play with it until it works
{{ [None, "foo"]|reject('eq', None)|list }} -> ["foo"]
🤷♂️
QED
There's something that causes it to fail somewhere
I've been purposely using none because of whatever it was
Ah
found it
it's not a valid test
none is
{{ None is none }} works
{{ none is None }} does not
the test is the 2nd item
so, I just use none everywhere
{{ [None, "foo"]|reject('is', None)|list }} will fail
good thing I didn't recommend that 🙂
although, is might not be a valid test for select
either way, I just use none everywhere
What would that filter to exclude events with a blank location attribute look like? This is still using my above template
selectattr('attributes.xyz', 'defined')
and that would just go as a filter on each calendar entity?
your template is bad, you should be using expand, not state objects. Then you could actually use filters properly
I'm guessing you copied/pasted this from someone else?
true, would be better to start with state objects and filter them
it may have been from you from a different template that you helped me with 😑
no, I don't use state objects as declared items
{% set event = [
'calendar.family_gmail_com',
'calendar.glen_meet_event_calendar',
'calendar.teamsnap',
'calendar.legacy_center_llc_calendar',
'calendar.total_sports_complex_calendar' ] %}
{{ expand(event) | selectattr('attributes.start_time', 'defined') | map(attribute='attributes.start_time') | map('as_timestamp') | min | timestamp_custom ('%b %-d, %Y', false) }}
@inner mesa would you rather have a new method selectstate('>', 45) or new tests that convert the comparision when running it. e.g. to make this work selectattr('state','>', 45)
i'm trying to think
or maybe a selectattrcast
selectattrcast('state', 'int', '>', 45)
I think the usage of "attribute" in Jinja is confusing
it should be selectprop, but they named it attr for some reason
yeah
anyways, I want to add this in because it keeps coming up, but I want it to work with datetimes or numbers, or any type
basically, states being a string is stupid and makes it hard to use filters when your trying to find numbers
or datetimes
I guess there's no other way to do a conversion like that without losing the rest of the object
right now there isn't
however, i'm going to add something that does this
free rein atm
I've been holding off adding it because I can't think of a clean way to do it
I like that it could be smart about what to cast the value to based on the incoming data type, but I'm not sure you have enough information to do that right
or I guess you're casting the incoming data type based on the value
is this still related my template or someting else?
ssshh, we're solving world peace
unrelated
haha, I figured. Thanks
you do typically
tests are basically 2 arguments
this and that
this and other
however you want to think of it
and you can type check both
so basically the definition of '==' is __eq__(self, other): where self is... well self, and other is the other object. And you can do isinstance(other, ...)
the only drawback to selectstate( is that it only works on state. If you have an attribute thats a string representation of a datetime, then it won't work.
anyways, if you come up with anything let me know, i've been asking people for ideas
yeah, I don't think adding n functions to handle n properties is the way
right
well, it could be 2
selectstate( and selectstateattr(
but yeah, less work = better
"selectstateattr" is so confusing
I'll think about it. I understand the problem and I don't see an existing solution that isn't gross
yep, that's why I haven't added it
it's goign to be as complicated as selectattr
basically.
I dint know if limiting it to casting types is the right call. Applying a filter, regardless of function, like map(), would be more general
the problem is map transforms what you're looking at
the goal is to transform the result but maintain the object
I understand, just as an analog for what we could do
i.e. filter based on an attribute, while comping the intended state, not the actual state
Point is that turning something into a float is just a function, as is multiply()
but that won't solve things like filtering out battery levels while you only care about the names of said batteries
which is currently only possible via namespace
same goes for min or max, lets say you want to get the min temperature in your house. So, try to get the min temperature from a series of sensors without creating 2 generators and outputting only the name
expand(states.climate) |
selectattr('state','eq','cool')| list | count
Is there a "not equal to" option for selectattr?
Thankss
Thanks for your advice, I've updated my code. This revision is a huge step forward, but problem is, now I'm getting the wrong time value for sump_pump_last_on_pretty. Would you pleas take a look when you have a chance? Also: I had to comment out the timestamp device_class... should I be using something else? Right now it is left blank. https://www.toptal.com/developers/hastebin/aviquselij.less
your conversion is wrong for the second time. You should be using as_timestamp(now()) | timestamp_custom....
or go straight strftime(.. with your timestamp
BTW, This also works
{{ as_datetime((as_datetime(state_attr('timer.vaatwasser_timer', 'finishes_at')) - now()).seconds).strftime('%Hh %Mm') }}
Evening all, don't suppose anybody would mind point out something I'm failing at here
wait_template: "{{ state_attr('climate.heating_2', 'temperature') == (states('input_number.boost_target_temperature')) }}"
Both figures from state_attr('climate.heating_2', 'temperature') and ('input_number.boost_target_temperature')) are coming out at 24.9 but it's returning false
I'm expecting if the two are equal it should be True but maybe I'm wrong..
Hello, how can I check which trigger is occurred from condition-event sunrise/sunset?
I tried something like this
I know how for example to check state (trigger.to_state.state) but I got confused with this event trigger
Just add ids to the trigger
Can you please just point me to docs or write a piece of code?
The attribute is probably a float and the state is a string.
The easiest thing to do would be to add |float to the states() call
Does it have a unit of measurement?
Hey guys. I am trying to setup a notification to inform me how many hours/minutes/secs has passed since the last triggered automation e.g. AC power loss.
AC Power Restored. Total Outage Time: {{ as_timestamp(now()) -as_timestamp(states.automation.alarm_ac_power_loss.last_changed) | timestamp_custom('%H:%M:%S') }}
I am getting this error though 😭 TypeError: unsupported operand type(s) for -: 'float' and 'str'
you need an extra set of parens
you're currently converting the second items into a string and then trying to subtract that from a timestamp
but if you really want the time for the last trigger, you should use that instead
{{ (as_timestamp(now()) - as_timestamp(states.automation.alarm_armed.attributes.last_triggered))| timestamp_custom('%H:%M:%S') }}
Is there an easy way to get the next Monday at any given time?
For example, right now that should refer to 2022-01-31
A week from today it should be 2022-02-06
something like this:
{{ (now() + timedelta(days=7-now().weekday())).strftime("%Y-%m-%d") }}
2022-02-06 is a Sunday, not a Monday
Whoops. You got what I meant though 🙂
thanks
What governs which day I target? Is that the -7?
hard to test with bad data 🙂
now().weekday() is the numeric representation of the day of the week with Monday as 0
Ah ok
So...if I wanted that to be a Tuesday instead of a Monday, I'd change that 7 to...a 6?
Right
every Tuesday:
{% set today=now()+timedelta(days=1) %}
{{ (today + timedelta(days=7-today.weekday()+1)).strftime("%Y-%m-%d") }}
Thanks. The values are showing now, but I am getting additional 7 hours 30 minutes on top of the actual differences? My TZ is UTC +8 which I've set in the configuration
the attribute is in UTC, now() is local
Okay...I think I understand. So to that would evaluate to the next Tuesday because days=1?
oh okay, so if that +1 was removed it would then be Monday?
again, Monday is 0, Tuesday is 1, Wednesday is 2
Gotcha
yes, compare with the previosu
I think I understand now...
So, why use now()+timedelta(days=1) instead of just now()?
the first line is just to simulate a given day
change the days=xx to whatever you want and watch the result change
it's just changing what "today" is
for the purpose of the experiment that you could run
Yeah, but wouldn't now() also be today
yes
like, why use timedelta at all?
For example, right now that should refer to 2022-01-31
A week from today it should be 2022-02-06
testing that
Ah ok
just trying to solve your problem 🙂
I think I see what you mean now 🙂
yeah, thanks - I was just thinking of it all wrong
😛
so if I changed that to say days=5 that would then cause the expression flip to the following monday?
🙂
that's why I gave you that
yeah
Ah okay. How do I get the attribute to use local time instead? or potentially adding offset to it?
thx
you can probably use utcnow() to have everything in UTC, but you can also review the large date/time section in the template docs
I think I understand now. I tried using utcnow(), but it gave me 23:53:38 😒
timestamp_custom('%H:%M:%S') }}``` = 13:57:05 which was my local time when it was triggered UTC +8
Since maybe the attributes is in UTC +8, so i thought I could use ```{{ now().astimezone() }}``` = my current local time. But it gave me the same result - additional 7h30mins
{{ as_local(states.automation.alarm_ac_power_loss.attributes.last_triggered).time() }}
Thanks guys. Got it sorted now
Thanks, I'll give it a go
So I gave this a go
'''{{state_attr('climate.heating_2','temperature' |float) == states('input_number.boost_target_temperature')|float}}'''
Ignore that formatting was trying to make it look nice in Discord, failed
{{state_attr('climate.heating_2','temperature' |float) == states('input_number.boost_target_temperature')|float}}
It still returns False
hello I would like to know if it is possible to condition the card display according to the connected user? I get there in a markdown card with an if user == "myuser" but impossible on a conditional card any idea? I try to create template sensor but not a success
The backend does not know who's logged in like that. This can only be done through custom elements
That's because the syntax is wrong
As with most things, I gave in and went with the flow and moved over to Zigbee2Mqtt instead
No point trying to reinvent the wheel if it's been mapped already I guess
your error was in your first state_attr, the ending ) is in the wrong spot, should be before the |
order of operations () are before filters are applied
I may well return to it anyway so I'll keep that in mind
Example of proper syntax: #automations-archived message
This binary sensor template periodically returns "unknown". I have a switch triggered by the state of this template that errors anytime that happens. What could cause this template to return "unknown" instead of on or off?
- platform: template
sensors:
snowing:
friendly_name: Snowing
value_template: >-
{{ states('sensor.dark_sky_precip') in ['snow', 'sleet'] }}
what would that look like?
Look at the bottom at the legacy template sensor docs
I can't directly link to it, because the anchor of the new sensor is the same, so it will go to that one
I found it but still not sure where that would go. Would I create an availability template for the dark_sky sensor?
The template would be something like
{{ not states('sensor.your_sensor') in ['unknown', 'unavailable'] }}
so like this? This means the binary sensor state will stay the same if the dark sky sensor goes to unavailable.
- platform: template
sensors:
snowing:
friendly_name: Snowing
value_template: >-
{{ states('sensor.dark_sky_precip') in ['snow', 'sleet'] }}
availability_template: >-
{{ not states('sensor.dark_sky_precip') in ['unknown', 'unavailable'] }}
Yep
so probably always a good idea to add these for sensors that determine state or a switch or other devices
Yep, I would also advise to have a look at the new format for template sensors, as you seem to be using the legacy format
I am trying to understand the availability template recommended above because I am not sure it solves my problem
When the dark sky sensor is snow or sleet, the binary sensors turns on. An automation is triggered by the state change of the binary sensor with an action switch.turn_{{ states('binary_sensor.snowing') }} The issue...presumably the dark sky sensor becomes unavailable (although this does not seem to be the case based on the history) and then the binary sensor becomes "unknown", the state change triggers the automation but throws an error because switch.turn_unknown is not a thing. How is the availability template fixing that?
you don't want the automation to trigger if it's going to result in an invalid action being executed
so whatever you have in the trigger needs to take that into account
template switch q: can i debounce a switch that needs a couple seconds to read the value_template?
toggle off --> value_template reading a power monitor -> switch turns itself back on -> 4s wait for wattage to drop -> switch turns itself off
not a fan of that
like "i want you to assume the device is OFF until at least 5 seconds pass, THEN read the value_template state"
won't delay_on or delay_off help with that?
Hello, recently I found out that frontend can convert datetime entity states into nice human readable strings like "in 5 minutes" or "1 hour ago". I wonder if there was a similar filter for templates. There is relative_time, but it only works for timestamps in the past.
i believe templates use jinja2 - so I'd check their docs
what is this sorcery you speak of
Anyone know how to go about filtering results from a REST sensor?
the REST sensor returns results that have a date field. I'm looking to only get results that are >= the current date...preferably just the first one
I'm also looking to get a bunch of different fields, but i dont know if that's possible
at this point, I'm starting to wonder if it would make sense to just write my own integration
Never mind, was thinking about a template sensor
Is it possible to filter values returned by sensors at all?
Currently, I have this:
- platform: rest
resource_template: "https://www.republicservices.com/api/v3/holidaySchedules/schedules?latitude={{ state_attr('zone.home', 'latitude') }}&longitude={{ state_attr('zone.home', 'longitude') }}"
name: 'trash_alerts'
value_template: "{{ value_json['data'][0] }}"
json_attributes_path: '$.data.[0]'
json_attributes:
- date
- description
- name
- specialNotes
The problem is - I end up with the following in state:
date: '2022-01-01T00:00:00.0000000Z'
description: Your pickup will be delayed by one day due to the holiday.
name: New Year's Day
specialNotes: ''
friendly_name: trash_alerts
Clearly that's not useful, because that date has already passed.
I need a way to somehow manipulate the return value
could i do it inside value_template?
What do you want it to be?
The next item in the list with a date that's after today
so...just a sec
Here's what the API returns:
[{
"date": "2022-01-01T00:00:00.0000000Z",
"description": "Your pickup will be delayed by one day due to the holiday.",
"name": "New Year's Day",
"phone": "508-832-9001",
"specialNotes": ""
},
{
"date": "2022-05-30T00:00:00.0000000Z",
"description": "Your pickup will be delayed by one day due to the holiday.",
"name": "Memorial Day",
"phone": "508-832-9001",
"specialNotes": "Service will be on a one day delay due to the Holiday this week. Please place your cans out by 7 A.M. the day after your normal scheduled pickup day. Happy Memorial Day from Republic Services."
}]
Right now it returns the first element becuase that's the first one. What it should do is filter that down somehow to find the one where date >= now()
can I do that in value_template?
I mean, I guess I can try it and see - but I want to know if I'm wasting my time before I spend 3 hours on something that just won't work or if there's a better way to do it
You should absolutely be able to do that
I mean...is that the "correct" recommended way to do this?
Basically, Trash night is every <insert day of the week here> - I want HA to show me a notification on that day, but also check in first with this API and see if there's an alert this week. If there is, then show the message from specialNotes
But the first part of that is obviously getting the data ingest right.
it's kinda horrendous, but it works:
{% set data = [{
"date": "2022-01-01T00:00:00.0000000Z",
"description": "Your pickup will be delayed by one day due to the holiday.",
"name": "New Year's Day",
"phone": "508-832-9001",
"specialNotes": ""
},
{
"date": "2022-05-30T00:00:00.0000000Z",
"description": "Your pickup will be delayed by one day due to the holiday.",
"name": "Memorial Day",
"phone": "508-832-9001",
"specialNotes": "Service will be on a one day delay due to the Holiday this week. Please place your cans out by 7 A.M. the day after your normal scheduled pickup day. Happy Memorial Day from Republic Services."
}]
%}
{% set date = data|map(attribute="date")|map('as_datetime')|select('gt', now())|list|first %}
{{ (data|selectattr('date', 'search', date.isoformat().split('+')[0])|first).specialNotes }}
Ah interesting, thanks
this is where petro's "transform within select" concept would work well
I ended up with something similar
{{ trash_json | selectattr("LOB", "equalto", "Residential") | selectattr("serviceImpacted", "equalto", true) | list }}
I didn't get quite as far as the date filtering
basically, find the date, and then index into the original data structure
could you enlighten me here?
it was a conversation in the last few days in this channel
Ah
because it's just a datetime at that point, not an structured object
Right
I mean, ideally, I'd still want the structured object so I can grab the specialNotes field because it sometimes contains useful info
Like "Please place your cans out by 7 A.M. the day after your normal scheduled pickup day."
yes, but I couldn't figure out how to do that in one expression because the date is a string
anyway, with that I'm going to bed
aw man. well here is what i thought of in the interim - use a boolean switch to take care of the instant on/off + buffer, then wait for a stable state on the power monitor and use that instead..
I did both but now after a reboot of deconz, both the statistics and the template state in an unavailable state/
https://pastebin.com/4yyBtBBz
The availability template is incorrect. You should not add the numbers there
But I don't think you should do both at the same time
either use this as the availability template:
https://www.codepile.net/pile/MObnDLOA
@small rock on second thought, you can combine the data of the statistics sensor, and the availability template like this
https://www.codepile.net/pile/qVwE1g5W
I'll give a go thanks!
@marble jackal I reloaded the config and it just remains unavailable
What is the result of both templates in
> templates
and what is the state of sensor.statistics_overall_consumption
unavailable
State template result in a value 2207, availability in false
then, that's the reason why the complete sensor is unavailalbe
remove the availalbility template, reload template entities, and check if that also changes the state of the statistics sensor
should I make a third sensor to be used in the statistics
I think the statistics sensor never got correct data so far
Yes, you can add it again
After a reload it works
after a restart it fails
If I add a secondary ccumulative sensor and add that to the sensor it works
I'll do it like that
Add it where?
If I'm not mistaken, the goal was to not let your sensor state be lower compared to a previous state
This won't prevent that
as, when the statistics sensor is not available, your float filter will default it to 0 and in that case, any result from the sum of device sensors will be higher
Yes that is true, the goal was indeed that never is lower. However it remains unavailable based on your codepile
when restarting HA that is
But now you achieved nothing compared with what you had 🙂
BTW, it just came to mind that when you remove one of the devices, or reset one of the sensors, you'll also have issues (as the sum will be lower). You will miss all energy until you reach the previous value again.
Any other idea then how I could manage that? As I use the sensor for the energy dashboard
Don't use it, just use the individual sensors 🙂
Add every item to the grid as net use and as individual device?
Well, the grid usage is intended to have your energy meter as input
But maybe you can ask in #energy-archived for advice on that
Hi, anyone know whats wrong with this? Soon as i add the ".round(1)" the card dissapears and no error showing.
label: '[[[ return states["sensor.openweathermap_temperature"].state.round(1) + "°C" + " • " + states["sensor.openweathermap_weather"].state]]]'
Well i have no idea, it was working before i added the round(1), have not realy knowledge about JS etc so i have no idea if this is the right way...
@marble jackal thanks for your help!
no problem, just thought of an alternative for the statistics sensor. You could create an automation to update an input_number if the value is higher compared to the current value of the input_sensor, and so create your own statistics max as comparison
But that value will be available when the source sensor is not
well step 1 would be to google round js...
I'm not trying to be an ass here, but I see you alot in here. Many of the questions can be solved with a simple search. I myself never knew JS prior to using HA... So I googled the way to do it and applied what I learned.
so the 2 things I would google based on what you already know is: 1. state is a string, and you want it to be a number. 2: You want to round that number.
So, search for convert string to number JS, and round JS
then apply what you found
Guessing about adding .round() at the end of your state is a recipe for disaster. Don't guess, find the answer. Apply the answer. When the application doesn't work, ask a question and post your code with your attempted application.
Done! https://www.codepile.net/pile/E89rExpA
One question: I had put the template on a single line with double quotes. HA turned this into multiple line. No issues there. However I was unfamiliar with the dash(-) behind the >
Why is it there?
hmm block chomping
- removes whitespace before the template
look up yaml rules regarding |, >, -
those characters are not templating characters, they are yaml characters
was just reading about it. They call it he a block chomping indicator apparently
To prevent a newline at the end
What could be an issue with such whitespace of new line?
well, there really isn't an issue in HA because HA by default removes leading and trailing whitespace on templates
so the - is pointless outside the markdown card
but everyone does it
it even automatically rewrites it in that style.
cool
Cool to be finally stepping in this templating. I'm trying to slowly convert all the scenes from Fibaro (lua) to HA
bytthe way in Fibaro I checked if something was already on before turning it on. It seems not necessary in HA. Is that assumption correct, or could I get into trouble that way later on?
I personally do that check. Choice is yours. The light will receive a turn on command if already on if you don't check and the light is on.
in the html guide it states that you con use
condition: not
conditions:
- condition: state
...```
Do you need to put that ``conditions:`` in there even if you only want to check against one condition?
Ah, whitespace control, I was also wondering the same about the dashes in jinja expressions, like eg {%- if foo == bar %-}
I guess my own answer should be yes, as I get an error if I leave the plural conditions statement out. Feels strange though.
yes, those also control whitespace
usually, you only need the {%- and you can forgo the -%}
yes
or you can just use templates
which is less verbose
If you create a condition and the condition is not met, does that mean that I will not find a log entry, or should i still see a log entry with a trace that tells me that the condition did not meet and the action is not taken? I would expect the latter.
log entires only appear if you hit them and you're using alias
otherwise the trace will show you when it failed.. by looking at the trace
Also, these are questions for #automations-archived not #templates-archived
ouch... sorry. Just getting back and forth between these two channels trying to build automations with templates in them.
So after my previous post about the conditions I tried to solve it with a template: https://www.codepile.net/pile/E89rExpA
But as soon as I did this the automation as a whole gets neglected.
So not sure where to go with that .. automations or templates 😔
Ah, so that will prevent
> template filling up with emptyness
your questions about conditions that don't contain templates go in #automations-archived . Anything with a template and the question is oriented about said template, go in #templates-archived . It's really simple. Is your question about the template? If yes, #templates-archived. Is your question about anything other than a template? If yes, not #templates-archived
Anyways, your template looks correct
Just keep in mind that those triggers will not occur unless they change from False to True
so if you're restarting, and they are already True, they will not turn further True and trigger.
{{ if state_attr('question' , '#templates') != True go #somehwereelse }}
TemplateSyntaxError: expected token 'end of print statement', got 'True'
damn even my joke results in errors 😉
strange.. as soon as I compare with this template if the state of the valve is already the same as the trigger.id, the whole automation works fine, but does not show a log item when i change the trigger state to above or below the compared value.
So if the template states the condition is not met, nothing happens (which is perfect) but also a log entry won't be written.
what do you mean "change the state"
in developer tools I change the state of the temperature sensor to a value above or below the trigger level
Again, you won't get log entries for things that aren't hit. Check the automation traces
Actually, do you even know about the trace?
you don't have a unique_id attached to that automation
so I'm guessing you don't know what traces are
Just now I understand what you meant. I found the clock item and the corresponding trace.
Thanks
true. I'm not sure what the unique_id is or how to use it. ...browsing the docs now...
I don't believe it's covered in the docs
if you use yaml, it's just something you learn in time
the automation editor automatically adds it
for you
otherwise just add id: some_long_unique_phrase to your automation at the same indentation as alias
-- i guess we are getting to much into automation stuff now -- 😉
we are
Hello, I'd like to receive a notification each time one of my Aqara temperature sensors stops working (for any reason). I'll detect that by checking if the temperature value did not change during the last 15 minutes. For this, i use this trigger code:
trigger:
- platform: template
value_template: "{{ as_timestamp( utcnow() ) | int > as_timestamp( states.sensor.meteo_room_temperature.last_changed ) | int + 15*60 }}"
But how can I do that for all my Aqara sensors without having one automation per sensor?
Thanks.
Following my question here, I'm wondering if that's achievable with a template in the trigger.
Let me try to explain.
Of course, I can use multiple entities as triggers like that:
- platform: numeric_state
entity_id:
- sensor.humidity1
- sensor.humidity2
above: '60'
That will trigger is the humidity value of any of my sensors is above 60. But I can't get how to pass a list of entities and then apply a value_template to each of them. If you have any idea, I'll be happy to try it. Thanks.
You mean something like this?
{%- set sensors = [ 'sensor.aqara_1', 'sensor.aqara_2', 'sensor.aqara_3' ] %}
{{ expand(sensors) | selectattr('last_changed', '<', now() - timedelta(minutes=15)) | list | count > 0 }}
I’ll try that and report tomorrow. Thank you very much.
@visual gust posted a code wall, it is moved here --> https://hastebin.com/nubodeyiru
hi.. hope this is the right place
created this template in configuration.yaml but can i add a icon to it?
sensor:
- platform: template
sensors:
weather_wind_dir:
friendly_name: Vind Retning
value_template: >
{% set dir = states('sensor.openweathermap_harboore_wind_bearing')|float %}
{% if 11.25 < dir <= 33.75 %} NNØ
{% elif 33.75 < dir <= 56.25 %} NØ
{% elif 56.25 < dir <= 78.75 %} ØNØ
{% elif 78.75 < dir <= 101.25 %} Ø
{% elif 101.25 < dir <= 123.75 %} ØSØ
{% elif 123.75 < dir <= 146.25 %} SØ
{% elif 146.25 < dir <= 168.75 %} SSØ
{% elif 168.75 < dir <= 191.25 %} S
{% elif 191.25 < dir <= 213.75 %} SSV
{% elif 213.75 < dir <= 236.25 %} SV
{% elif 236.25 < dir <= 258.75 %} VSV
{% elif 258.75 < dir <= 281.25 %} V
{% elif 281.25 < dir <= 303.75 %} VNV
{% elif 303.75 < dir <= 326.25 %} NV
{% elif 326.25 < dir <= 348.75 %} NNV
{% else %} N
{% endif %}
@visual gust posted a code wall, it is moved here --> https://hastebin.com/paperacogu
code wall 🤨
Yes, icon_template is described in the docs
icon_template: >
{% if is_state('sensor.openweathermap_harboore_wind_bearing', 'clear-day') %}
mdi:weather-windy
{% else %}
mdi:weather-windy
{% endif %}
but when i check the config it says invalid
but i guess it has to go in a different file than configuration
time to read docs
It goes right with the rest of the sensor definition. But yes, let the docs be your guide
@visual gust posted a code wall, it is moved here --> https://hastebin.com/utizifawav
Rule #6: Please do not post codewalls (text longer than 15 lines) - use sites such as https://www.codepile.net/ (pick YAML for the language) or https://paste.debian.net/ (pick YAML for the language).
Please take the time now to review all of the rules and references in #rules.
You're flooding the channel with unformatted code
i give up... this is what i have come up with from reading the docs and seen what other people report as working
https://pastebin.com/9CwR8yNT
basicly i want to permant change the icon to be the same one always