#templates-archived
1 messages ยท Page 40 of 1
value_template: >
{% set direction = ['N','NNE','NE','ENE','E','ESE','SE','SSE','S','SSW','SW','WSW','W','WNW','NW','NNW','N'] %}
{% set degree = state_attr('sensor.buoy', 'WDIR')|float (0) %}
{% set degree = state_attr('sensor.buoy', 'MWD')|float (0) %}
{{ direction[((degree+11.25)/22.5)|int] }}
it had nothign to do with that
it had everything to do with the fact that you used a unit_of_measurement with a non-numeric state
Is the unit of measure assumed?
Not understanding (what else is new). The exact same template works for my weather app. Doesn't work for my buoy reading
Where do I look?
did you use one when you created the sensor?
The states for the sensor does not
this is all your stuff
I did not create a unit of measure for either.
share the whole sensor that works and the one that doesn't
ny_harbor_wind_direction:
friendly_name: 'wind direction buoy'
value_template: >
{% set direction = ['N','NNE','NE','ENE','E','ESE','SE','SSE','S','SSW','SW','WSW','W','WNW','NW','NNW','N'] %}
{% set degree = state_attr('sensor.buoy', 'MWD')|float (0) %}
{{ direction[((degree+11.25)/22.5)|int] }}
Fails
wind_direction:
friendly_name: 'wind direction'
value_template: >
{% set direction = ['N','NNE','NE','ENE','E','ESE','SE','SSE','S','SSW','SW','WSW','W','WNW','NW','NNW','N'] %}
{% set degree = state_attr('weather.home', 'wind_bearing')|float (0) %}
{{ direction[((degree+11.25)/22.5)|int] }}
works
What does "fails" mean and are there any other attributes associated with either or those sensors that appear after value_template?
It means that the direction is wrong. It shows N no matter what the degrees are. I don't understand the question on other attributes associated with?
I did the troubleshooting steps I was given yesterday and the degrees show correctly
I fixed it. Had a duplicate sensor. Thanks for everyone's help.
should these two not show the same?
{{ states.binary_sensor.closet_motion_1_occupancy.last_changed }}
{{ state_attr('binary_sensor.closet_motion_1_occupancy','last_changed') }}
I know the latter one is the one that should be used, but...?
Only the first gives output, the second "null"
I think last changed is a "special" as it does not exist in the attributes list for the entity
Ok, but don't they both read the same data?
That is what I meant by special. state_attr only looks in the attributes table, but the last_changed is no an attribute, it is another item at the same level in the tree as the attributes.
Aha, got it, thanks ๐
Hi, in search of a template solution for this, I'd like to show the moon phase with left of it the previous phase and right of it the next phase. I can get the 'current' index from the list of 8 phases and with -1 and +1 this would work, except when current index =1 where I would need 8 as previous OR when current index = 8 where I would need index 1 as next. I can of course add an if curren= 1 then next = 1... but maybe there is something smarted..... I hope I made it clear?
this is that I have right now ['first_quarter', 'full_moon', 'last_quarter', 'new_moon', 'waning_crescent', 'waning_gibbous', 'waxing_crescent', 'waxing_gibbous']
{% set phases = states.sensor.moon_phase.attributes.options %}
{{ phases[states.sensor.moon_phase.attributes.options.index(states('sensor.moon_phase')) - 1] }}
{{ phases[states.sensor.moon_phase.attributes.options.index(states('sensor.moon_phase'))] }}
{{ phases[states.sensor.moon_phase.attributes.options.index(states('sensor.moon_phase')) +1 ] }}
which returns
new_moon
waning_crescent
waning_gibbous
as current index = 4 but how to deal when curren moon = waxing-gibbous or first_quarter
that will still work
it will work if it's the first, it won't work if it's the last
-1 chooses the last object
so when you're on the last item, you need to handle the last item only, because that's the only time it will go beyond the limit
{%- set phases = state_attr('sensor.moon_phase', 'options') %}
{%- for current in range(phases | length) %}
{%- set last = current - 1 %}
{%- set next = current + 1 if current + 1 < phases | length else 0 %}
{{ current }} {{ phases[last] }}
{{ current }} {{ phases[current] }}
{{ current }} {{ phases[next] }}
{%- endfor %}
ah... yes.... I should have know 'last' .. THANKS!
I don't have any more hair to spare... Please help with this. I am trying to set a date & time to a input_datetime helper. It seems to have some sort of cache, not overwriting when I want it to. Why? I had an "initial" value set in configurations.yaml, but that is commented out, and HA restated several times. This statement still won't update the helper...
- service: input_datetime.set_datetime
data:
entity_id: input_datetime.morning
date: >
{% set date = now().strftime('%Y-%m-%d') %}
{{ date }}
time: >
{% set delta = range(0,30) | random | int %}
{% set time = '05:45' | today_at %}
{% set morning = (time + timedelta(days=0,hours=0,minutes=delta)) %}
{{ as_datetime(morning.strftime(states('input_text.datetime_format'))) }}```
the last as_datetime was my last try, did nothing so removed again
What's the error? What's in states('input_text.datetime_format')
Last error was invalid time specified: 2023-05-18 05:54 for dictionary value @ data['time'] and contents of that helper is %Y-%m-%d %H:%M
So you're including a date in your time
You know there's a datetime field you can just set both at once? ๐
Yeah. I removed the last as_datetime()
- service: input_datetime.set_datetime
data:
datetime: >
{% set delta = range(0,30) | random | int %}
{% set time = '05:45' | today_at %}
{{ time + timedelta(days=0,hours=0,minutes=delta) }}
pays to read the docs ๐
Perhaps easier to do it all at once.. Will try that, thanks. Well I have read it and just thought this ought to work
and if it complains about it needing to be a string,
- service: input_datetime.set_datetime
data:
datetime: >
{% set delta = range(0,30) | random | int %}
{% set time = '05:45' | today_at %}
{{ (time + timedelta(days=0,hours=0,minutes=delta)).isoformat() }}
and it works fine in dev-tools... so not easy to find
if you want to set them separately... like you had above
- service: input_datetime.set_datetime
data:
entity_id: input_datetime.morning
date: >
{{ now().date() }}
time: >
{% set delta = range(0,30) | random | int %}
{% set time = '05:45' | today_at %}
{{ (time + timedelta(days=0,hours=0,minutes=delta)).time() }}
FYI Your range only does between 0 and 29 minutes
if you want 30 minutes, you need to change the 30 to 31
I tested the joint approach now first, it won't bite either... :/
post the error
I'm goign off memory
the first or second example should work. so if the one doesn't, the other will
no problem, will revert to what I had and try yours ๐
All of those examples work, so there's another problem if it's not working for you
Thanks for verify that ๐
I do believe you. Just stumped why it refuse to for me...
Well, does it come up w/ another error?
Yes, asked for an error quite a while ago
still using old initial values from configurations.yaml
You'll be getting an error somewhere
which is commented out...
this is what I ran with now
morning:
name: morning
has_date: true
has_time: true
# initial: "1900-01-01 07:00:00" ```
If yes, and config check is passing, but it's not reloading, then there's an error in your logs
that has nothing to do with the automatio
that's the intial values of the datetime, which will be stored regardless
what happens when you run the script or automation?
I would say so. It is part of the input_datetime helper definitions
there will be an error if it does not set
no?
well, it is... But if that is not supported, we may have found the issue...
so you're falsly thinking it's broken, when it's working as intended if the previous state was the initial
dude, are you running the automation?
yes or no?
Everytime it restarts, yes
Ok, look at the damn trace and look for errors.
I have...
Ok, then it will say something
post it here if you can't debug it
there will be errors in your logs or the trace will show you what it set
there's nothing else to this
don't look at the ending state if it'snot setting it
look at the trace
click on the service call and see what service data it sent
in the trace
this is debugging 101
You're making this really difficult for anyone to help
how can i create an automation that turns on a switch if a sensor is this numeric state + 20?
- You aren't posting errors
- You aren't sharing your code
- You're just saying "i messed it up i'll fix it" without posting what's messsed up.
that should be an option for a numeric condition
i was not able to find it
still not working ๐ฆ
POST YOUR FULL AUTOMATION
where can i define this? i see an above and under
not like a + 15
i do not need the above or under conditions defined so how does this work
you said, you only want to do something if your state is 20 above...
it always need to do something but it needs the current sensor data + 20
ah
now getting Invalid time specified: 2023-05-18 06:09 for dictionary value @ data['time']
FFS, Post your automation. You are messing up the yaml.
seriously man, you are so fucking frustrating to work with
ans how do you think I feel about this? I appriciate the help though
so for that, do you have a trigger? or is it always the same switch?
I don't care how you think. At this point you're not helping anyone help you. You're just saying "it doesn't work" while making basic mistakes at every turn. We can fix it in under 2 seconds if you JUST POSTED YOUR AUTOMATION.
which you aren't doing
but the trigger / automation is only allowed to execute if another temp sensor is this state + 20
ah ok, then you'll just need a simple template condition
fun shit. Thanks for nothing then
i m completly new to this template condition and nothing has worked so far here
Thanks for nothign??? You aren't posting the automation
why?
why?
why?
Literally makes no sense
"Hey I need help but I'm not going to share what's breaking"
"Thanks for not helping me"
Ok, what are the 2 sensors?
switch.dak_pomp_switch_0 can only be turned on when sensor.dak1_temperature is 20 degrees hotter then sensor.tank_onderin_temperature
Ok, then for the condition all you need is
- condition: template
value_template: "{{ states('sensor.dak1_temperature') | float(-20) + 20 > states('sensor.tank_onderin_temperature') | float(0) }}"
the float(0) and float(-20) are default values if the sensor's fail to work
if you want to be 100% sure it only works when both sensors are available...
- condition: template
value_template: >
{% set dak = states('sensor.dak1_temperature') %}
{% set tank = states('sensor.tank_onderin_temperature') %}
{% if dak | is_number and tank | is_number %}
{{ dak + 20 > tank }}
{% else %}
False
{% endif %}
that's a condition
use that as a condition in your automation that turns on the switch
Do you know how to make conditions in automations?
yes but not with yaml code
just select the template condition and paste the code only in the box
@steep raven I converted your message into a file since it's above 15 lines :+1:
the code is this part...
cant send screenshots here sadly
Yes, that's fine
Just keep in mind, you'll have odd behavior if you lose connection with 1 of the sensors
the second template I posted will not turn on the switch at all costs if 1 of the sensors is disconnected
food for thought
it does nothing ๐
shouldnt it be {{ tank + 20 > dak }}??
i changed it to this tho but still nothing
it would be {{ dak - 20 > tank }}
and this does what exactly?
sorry it's
{{ dak | float - 20 > tank | float }}
or you could add the 20 to tank, whatever floats your boat
how would this behave if one of the sensors doesnt report anything or something else then a number?
False
good
this here
{% if dak | is_number and tank | is_number %}
checks if they are both numbers before checking
if they aren't numbers (i.e. unavailable), then it just returns False
make sense?
the |float turns it into a number, all states are strings unless told otherwise
its kinda working
i pasted this code aswell for the turn off switch and made it {{ dak | float - 10 > tank | float }} but it turns off inmedtialy
make it a if then else instead of a condition
it will but it'll be more confusing to work with
that doesnt matter
๐
what matters is is its turning it off even always on change ๐
and not on dak is + 10 from tank onderin
so, wouldn't you want to turn it off when it's below 20?
you know what I mean on when +20, off else
unless you want it to stay on from 10 to 20
so
turning it on works now when its + 20
i want it to turn off when its only + 10
in a different automation
Ok, so...
with static numbers this worked great but as the day goes on the tank will warm up and then you are constantly adjusting manually xd
- condition: template
value_template: >
{% set dak = states('sensor.dak1_temperature') %}
{% set tank = states('sensor.tank_onderin_temperature') %}
{% if dak | is_number and tank | is_number %}
{{ dak | float - 10 < tank | float }}
{% else %}
False
{% endif %}
notice how I flipped the > to <
that's less than or greater than
it can be the same automation tho if possible but then how would i know / verifiy its off?
you can put conditions in a choose
so, choose: switch is off & > 20.... turn on, choose: switch is on & < 10 turn off
and then no default for the choose (to keep it whatever the state is)
but keep in mind, if one goes unavailable with the off, and it's on, it'll stay on
so you'd need to decide if you want to change that func
seems to work perfectly now with this on seperate automations ๐
personally, Id keep the logic how i described and just notify myself when those sensors go offline
if they are that important
can you add something it goes off ๐ if a sensor breaks or something
just make a normal automation separate from these
with a trigger for when the sensors go to 'unknown' or 'unavailable'
will try
no templates will be involved, so it should be pretty straight forward
state trigger, notification action
very short, very straight forward
Everything seems to work now as intended thank you ๐
No problem
I don't need the attitude. You're usually nice and helpful, but different today. Let's just leave it at that. If you are intrerested, it is a problem with my home assistant database..
There's no way it's an issue with your database.
that does not cause an automation service to fail
And I'd be nicer to you if you actually provided the information that was asked
but for some reason, you continue to not provide it
2 things requested multiple times were: Logs and full automation
things that were provided when requested: 0
Put yourself in another person shoes. If someone is taking the time out your day to help someone, and they aren't giving you the information you ask for, would you be happy to continue to help?
especially when you get nothing out of it?
No.
So, you don't listen, you don't provide information, you get pissed off helpers.
@mighty ledge idk is this is the right channel but can i embed like graphs from dashboards inside emails that home assistant sends via an automation?
I don't think anything like that exists. I would start in #integrations-archived. You may need to use something like graphina which is separate from HA.
i have now one that sends current sensor statusses but entire graphs would be awesome
Yes, and that's ultimately the problem. You'd need something to create the graph as an image.
BTW, I just discovered that the order of phases is incorrect in this attribute, just raised PR so I can make a nice card/function with it...the simple workaround is of course to determine these as a variable/list but...well ๐
I hope this is the correct place to ask this.
I've got a binary sensor that looks like this - it returns unknown.
platform: command_line
name: embysessionplayroom
command: "curl -H \"Content-Type: application/json\" -H \"X-Emby-Token: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\" -X GET \"http://ip:port/emby/Sessions\" | jq -r '.[] | select(.DeviceId==\"xxxxxxxxxxxxxxxxxxxxxxxxx\") | .Id'"
scan_interval: 4
But if i run the curl command in the terminal in HA without escape characters like this curl -H "Content-Type: application/json" -H "X-Emby-Token: xxxxxxxxxxxxxxxxxxxxxxxxxxxx" -X GET "http://ip:port/emby/Sessions" | jq -r '.[] | select(.DeviceId=="xxxxxxxxxxxxxxxxxxxxxxxxxxx") | .Id' i get the response i want.
What am i missing here?
the response has to return the pay_load on value
also keep in mind that it will be unknown at startup until it's polled
I don't understand, do I have to fetch everything first and then use value_template to get the result I want?
You can't with a binary sensor
Ooh
it's a binary sesnor, it has a value of on or off
Ah of course. I'll have to use something else
a normal comand_line sensor can pull the payload and do things with it
My bad, it works with a normal sensor. Thank you! ๐
np
How do i add items to a dictionary in a template?
you can't, but you can create a new dict based on the original. See this from a couple of days ago (last line): #templates-archived message
Im' trying to process some JSON data into a dictionary withy float keys ... i'll give that a look
Any way to get around:
SecurityError: access to attribute 'update' of 'dict' object is unsafe.
You canโt modify collections
But i can iterate through a collection and "convert" stuff and then make anew collection rightg?
you asked how to add a key to a dict, and the example shows that
You can only make new collections
specifically, it shows how to modify a key (which really just means remove the old one and add a new one)
Let me rephrase ๐
Given a dictionary of "string:"string and i want to convert it to float:string (where the keys are floats) is that doable
Yes but you need to create a new collection.
I asusme i can process | items and do ac onvert
This gives me pairs right?
{{ json_input | to_json | items }}
So I'm assuming i can apply a function to the key? is that correct
Youโd want from_json
{% set json_input = {"0":"#FEC4FF","10":"#D977DF","20":"#9545BC","30":"#4B379C","40":"#31B8DB","50":"#31DB8B","60":"#6ED228","70":"#FFFF28","80":"#F87E27","90":"#CF3927","100":"#A12527"} %}
{{ json_input | to_json | items }}
It doesnt work with from_json
Because your data isnโt a string
it's already a dict
Iโm on mobile but youโd need to iterate the items. Create a new list of key value pairs that have the transformed values. Then you create the dictionary using fromkeys
so going from dict -> items -> list gives me a set of tuples
modify the 1st entry of the tuple
reassemble to a dictionary
Namespace? like {% set new_list =}
interesting
584 creates a list in namespace
I've not seen that before
589 adds to the list
Youโll be adding a tuple with a key and a value
E.g. (key, value)
Yes, and alter the value there, then pass the namespace variable you created in 584 to from_keys (after the loop)
Thatโs the only path, so yes itโs the right path
Of course I'm going down this rabbit hole to make a totally obscure feature in a blueprint i have no idea if anybody will use ๐
Yep! Sounds about right
Trying to let people enter their own color array ... to render temp ranges on an awtrix clock
I've never used dict.from_keys() before. it's cool
It allows you to create a dict using all the no-no characters
{%- macro json_to_float_dict(json) -%}
{%- set ns = namespace(tuples=[]) %}
{%- for k,v in json_input | from_json | items -%}
{%- set key = k|float %}
{%- set ns.tuples = ns.tuples + [(key,v)] %}
{%- endfor %}
{{ dict.from_keys(ns.tuples) }}
{%- endmacro -%}
interestingly, the Python dict.fromkeys() seems less useful
I think fromkeys is old
you can only specify one value to be repeated
Thatโs nice if you want to create a quick dick with none in all values from a list
List of keys
not helpful at all with our limited Jinja support
Is it possible to calculate once and return all values with different attributes? Along the lines:
- sensor: unique_id: panel name: panel state: >- {% set degrees = 31 %} {% set radians = (pi/180) * degrees %} {{ degrees }} attributes: degrees: "{{ degrees }}" radians: "{{ radians }}"
Good question... i need to figure out how to add attributes to some of my stuff
I doubt it, but please do try
variable scope is to the template, typically
No, not possible
Well it is with a trigger sensor
you can set the state and then refer to the state in the attributes
is there a possibility to display the time formatted? I don't want it to look like this "2023-05-18T19:46:33. 161018+00:00", but May 18, 2023, 23:05
Can someone help a bit with this: https://gist.github.com/Bluscream/9589d638be2cec57e0046cd39982bf9e
Nobody is going to help with raw ChatGPT output
You may want to read #announcements message
It's hard to summarize it tbh but i can just copy and paste my initial request for chatgpt if that's what you want;
I have a homeassistant instance with the following devices:
- light.ceiling_light
- light.floodlight
- light.led_strip
I want you to create a config entry for input_select.lights_color that has the following options:
- Off: Should turn off all lights
- Bright: Should turn on all lights with cold white color and 100% brightness
- Red Bright: Should turn the floodlight off, ceiling_light and led_strip to 100% bright red
- Red Dark: Should turn floodlight and led_strip off, ceiling_light to 5% red
- White: Should turn the floodlight off, ceiling_light and led_strip to 100% bright warmwhite
I don't quite see the problem, the PSA says that i can't help other with AI, but doesn't say i can't use it to try and get help myself
What are you having problems with? That sounds like an automation you can make solely using the Automation UI if you wanted
it's a pain in the butt to split it into a lot of scripts 'n stuff tho. the way gpt proposed it looks really slick using service_template and data_template to get everything into one compact automation
You can get all of that in a single automation if you want... the problem with what it proposed is the fact that it doesn't work and is non-sense
to be clear, that is not what Rob wants. And there is way too much text in that link to expect anyone to help you with that, even if it was a reasonable request, which it is not
How can I see what the output is on a aqara fp2 sensor? It clear and detected. The aqaua app log shows someone is going away, someone is approaching. and other things. Ho can I find these in home assistant sensor?
Is there a way to see when an entity was last in X state?
For instance with a binary sensor want to basically say if device X didn't detect motion in the last 10 minutes
the easiest generic way to do that is to create a template binary_sensor that checks for that condition, and the use the last_updated property of that entity
but for your specific use case, it sounds like you just want an automation with a state trigger and a for: block
Shame that those things have been deprecated for years and you shouldn't be using them
Holy crap that's alot of text
it's using outdated functionality and making up functionality. Oof, that's why people who know better don't bother with chatgpt
Not sure what you mean exactly. Basically I have a binary sensor for if the washing machine is on or off. When it goes from on to off I send a notification saying it's done. I have all of this working already.
But I want to add a check to basically say if movement was detected in the laundry room in the last few minutes then don't send a notification because it was likely emptied already
How about a state condition on that automation to check for that? https://www.home-assistant.io/docs/scripts/conditions/#state-condition
Hmm possibly is there a way to say any state but on?
So something like if state is off, or unavailable, etc.
for greater then 5 mins send notification
You won't get something like that without coming up w/ a template sensor like Rob mentioned
Okay so how would you suggest I do it? I'm open to other ideas
Does it actually go unavailable where that's a case you need to handle?
Yeah it does quite frequently otherwise I wouldn't bother
It's a BLE sensor from UI
It's not usually for long periods of time more like it drops for a few seconds
an if then else can do that.
if with condition on, else... yadda yadda yadda
You can also make triggers using not_to
with for
there's about 100 different ways you can make this automation
If it were me, I'd make a template sensor that listens to the "on" state, that way you know what that particular sensor is representing and you can use that to filter out triggers you don't want to run the automation
and that way.... if your motion sensor flips to on... flips back to unavailable and then flips to off within the span of a minute, and then a minute later your trigger goes off, you won't get a notification
me too
in fact, that's what I did
but my washer is a dumb washer, so it's a bit more complicated
I had to time cycles to figure out when it's done
luckily, the final rinse cycle is exactly 10 minutes long, so I just key off that
i don't quite get what else he wants then tbh
Something strange suddenly, and I don't think I changed anything. In VSCode for each file I open, I now see:
Unable to load scheme from 'http://schemas.home-assistant.io/integration-template': No content.
Is something wrong with HA, or did something happen to my instance?
Basically says it as a notice on the first line of the file.
The plugin in the latest VSCode add-on version is broken
Restore your backup of the prior VSCode add on
Ah, so it's an add-on issue. Just have to wait then or restore indeed. Thanks
https://www.experte.de/dns-check?d=schemas.home-assistant.io that subdomain is not registered so your vscode can't reach it
Namespaces typically aren't in DNS necessarily
Is it a breaking change in terms of using VSCode, or just the checking of the template structure and colouring, etc.
It's just breaking schema validation
Ah, so risky in case I make a mistake ๐ Thanks
You can still use VSCode, but it won't scream at you if you don't follow the schema
Correct
Let me restore then, safer I think
Indeed, it's been broken for over a month at this point so a restore is the best option
you could always do CTRL+SHIFT+P -> Check config tho right?
Is there a simpler way to restore than copy-pasting the directory from my backup?
Settings -> System ->Backups... find the VSCode one
Ah yeah, thanks! 5.5.6 is the last working one, correct?
Yep
Thanks!
Man I wish all my utilities, phone provider, insurance, etc. etc. was open/community sourced
My washer is dumb too. I am just using a power monitoring outlet
So after usage drops below a few watts for 2 minutes I assume its done and send a notification
Thats been working great. I just want to avoid a notification if I go in before its done and take it out, or get their before the notification fires
Contact sensor is good for that as well
I don't know if this is the right place to ask, bug I'm having trouble using unique_id on a command_line sensor... I have the following:
sensor:
- platform: command_line
name: CPU Temperature
unique_id: rpi_cpu_temperature
command: 'cat /sys/class/thermal/thermal_zone0/temp'
unit_of_measurement: 'ยฐC'
value_template: '{{ value | multiply(0.001) | round(1) }}'
but when I restart HA, the id loads as sensor.cpu_temperature
Yes, that's what it will do
your entity_id is built off the name, not the unique_id
unique_id is for the UI to know what device is what so you can adjust it's settings in the UI
There's no way to set up an entity_id that differ froms the name in yaml without using customize.yaml
@gusty blaze By default, all of your devices will be visible and have a default icon determined by their domain. See customizing devices for how to change that.
I see, so to achieve what I want I'll have to set the name to RPi CPU Temperature and then customize the friendly_name to CPU Temperature... I think I got it, thanks
Yep
Hey, is it possible to give tem state an wildcard to track all calender entities?
{{ now().replace(second=0)|as_timestamp|int -(state_attr('calendar.xxxxxxxx_googlemail_com','start_time')|as_datetime - timedelta(days=1))|as_timestamp|int }}
no, you have to iterate all calendar entities
ok, thanks
i have 1 humidity sensor and i want it to turn on a switch 10 mins after it has been above 70% how can i do this?
With an #automations-archived
No template required
How?
Find out in #automations-archived
do you also have something to turn on a switch when theres more then 3kwh flowing back to the grid or can that also be done with a simple one?
My man, this is the templates channel. Please ask your questions in the #automations-archived channel.
hello I ahve this error: Message malformed: invalid template (TemplateSyntaxError: unexpected ')') for dictionary value @ data['sequence'][0]['if'][0]['value_template']
And Im trying to check if my variable coresponds to exact string
alias: New Script
fields:
command:
description: command type
example: mute-speakers
icon: mdi:desktop-classic
mode: parallel
max: 10
sequence:
- if:
- condition: template
value_template: >
{{ command) == 'mute-speakers'}}
then:
- alias: Mute Office Speakers
service: button.stefanpc_speaker_mute
You've got a ) after command
The error message even says that
hi guys
i genting some error in my sensor template
can someon help me
-
platform: template
sensors:
angulo_coletores_rebatido:
friendly_name: Angulo Coletores Rebatido
unit_of_measurement: "ยฐ"
value_template: >-{% set Azimute = states('sensor.azimute_solar') | float %} {% set Zenite = states('sensor.angulo_zenite') | float %} {% if (Azimute < (-90))%} {% set A = (Zenite + (90)) %} {% else %} {% endif %} {{A}}
A isnโt declared if azimuth is greater than -90
I am creating a template which shows the value of time left to charge in minutes , I would like to be shown like say "2 hours and 32 mins " . Is there any pre defined formula available ? or I need to use something like "/60" ?
@karmic elk You can try this: https://github.com/TheFes/relative-time-plus
use now() + timedelta(minutes= states('sensor.your_sensor_with_minutes_left') | int(0)) as input
Sure, I will try and let you know.
I have tried this , seems i am missing something here - https://imgur.com/a/QfRYIOs
I have added 2nd line for reference. As timedelta is zero when I add now() the result always current which we see from now()
@karmic elk You said the sensor displayed the number of minutes
It actually shows the time it's finished
In the case, just use the state of the sensor as input
my sincere apologies , You are correct I got confused with my own problem statement . https://imgur.com/a/Fsvs7QI the one you have is working . Can you help me understand what does int(0) does ? does the second count always going to be 00 on 6:35:00 ?
int(0) converts the part before it to an integer with 0 as it's default
But that's not what I meant, however as you are providing images of code, I can't really copy paste your input any correct it.
What I meant is you should use the state of the sensor as input of the macro
sorry , here is the code and result
{{state_attr('sensor.time_charge_complete','minutes_to_full_charge') }}
{{states('sensor.time_charge_complete')}}```
result
```2023-05-20 08:01:00.432890-07:00
380
2023-05-20T15:00:01+00:00```
You need to use the macro, as you did here
I have a template sensor that's supposed to use the value of my solar generation if it's available, and replace it with 0 if it's unavailable. It's not working, and I don't know enough about templates to understand why.
{% if states('sensor.solar_pac') != 'unavailable' %}
{{(float(states.sensor.solar_pac.state))}}
{% else %}
{{ 0 }}
{% endif %}
There is a lot of room for improvement, but basically it should work.
Did you test it in developer tools > templates?
Aaah, an error.. which one specifically?
I think it's to do with my inverter turning off when the sun is down
UndefinedError: 'None' has no attribute 'state'
if the inverter is off when HA starts, and there's nothing to pull the data from, then the entity isn't created. So there's no 'state'.
If that's the error, your sensor doesn't exist
yeah, not something I can overcome I guess
Check in developer tools > states
Yes, you can, by using states() like you did in the if statement
ah so instead of float, gotcha
ah
{% set s = states('sensor.solar_pac') %}
{{ s if s | is_number else 0 }}
much more elegant
thank you
I have a similar one, which is giving me a different error. I'm trying to have a sensor use the value of my HA Glow when the sun is down, and a CT clamp when the sun is up.
It seems my electricity supplier changed something on my meter, and now the pulse light isn't showing my imported energy anymore
it's flashing on bi-directional supply now
{{(float(states.sensor.power_sensor_live_power))}}
{% else %}
{{(float(states.sensor.house_power_consumption))}}
{% endif %}```
I'm getting TemplateSyntaxError: expected token 'end of statement block', got '='
I'm guessing I can't use sun.sun in that way
yeah, I've rewritten it
{% set esp32 = states('sensor.house_power_consumption') %}
{% set sun = states('sun.sun') %}
{% if sun == 'above_horizon' %}
{{d1}}
{% else %}
{{esp32}}
{% endif %}```
that looks like it's working
Is there a way to use template triggers in automations to emulate time pattern without using time pattern? Under certain conditions I would want the automation to trigger every minute and others not trigger. I can use a condition and a time pattern but I was not sure if it is better for performance to not trigger at all unless needed. Rather than triggering every minute only to hit a condition to stop the automation.
In any case, there'd still be the need to evaluate whether to trigger, whether it's through a template or time pattern. Without knowing what your actual condition is, it's hard to give a concrete answer. Condition is probably the easiest route, depending on how frequently it'll need to actually execute, you could have another automation to turn on/off this automation though, too.
Yeah that's something I thought about as well.
{{ (now().hour * 3600 + now().minute * 60 + now().second) % 75 == 0 }}
would this work as a trigger? It's not 1 time a minute but I'm curious.
Does anyone know if I can hardcode a template into a blueprint, so I can share my blueprint with others? The template has some logical converters so the vallues in the blueprint can be easily adjusted by a number input field.
This has to be transcoded to the automation after one published the automation
No, this will trigger each 4 minutes, as templates with now() are only rendered once per minute
Interesting. So just use now() and xyz for me to get a trigger when xyz is true?
is there a way I can:
a) make it only one decimal point
b) have it shown as "kB/s"
- name: "NAS Total Throughput"
availability: "{{ states('sensor.nas_download_throughput') | is_number }}"
icon: mdi:cached
device_class: data_rate
state: "{{ states('sensor.nas_upload_throughput')|float + states('sensor.nas_download_throughput') | float }}"```
Yes. |round(1) and add a unit_of_measurement
perfect! thanks
any reason why its showing as "scanning" even though its above 300 and below 1000?
Those statements aren't formatted properly
They don't make sense
1 < x < 2
Not what you gave
Just think about the syntax
sorry I am not following
isn't >= 10 < 300 greater than or equal to 10 but less than 300?
oh I see haha
I showed you the right syntax
Ahh that makes sense. Thanks for that
Having an issue with a template that used to work fine. Think something changed in the new versions and my code isn't compatible. This is the error:
Dishwasher - Set Start Time: Error executing script. Invalid data for call_service at pos 1: Invalid datetime specified: 2023-05-20 12:00:00+02:00 ## My Template for dictionary value @ data['datetime']
@sonic ember I converted your message into a file since it's above 15 lines :+1:
The error comes from s script in which you issue a service call
Not from a template sensor
This is the service call:
service: input_datetime.set_datetime
data:
datetime: "{{ states('sensor.nextenergy_cheapest_hour_dishwasher') }}"
target:
entity_id: input_datetime.dishwasher_auto_start_time
And this is the template that sets the "cheapest hour"
- name: "NextEnergy Cheapest Hour Dishwasher"
unique_id: 0f509f15-5e37-4366-920c-2e0981e16eda
icon: mdi:clock
state: >
{% set hour_threshold = states('input_number.dishwasher_hours_ahead') | int(0) - 5 %}
{% set time_threshold = now().replace(minute=0, second=0, microsecond=0) + timedelta(hours=hour_threshold) %}
{% set items = state_attr('sensor.energyprices','raw_today') + state_attr('sensor.energyprices','raw_tomorrow') %}
{% set lowest = items | selectattr('start', '>', now()) | selectattr('start', '<=', time_threshold) | sort(attribute='value') | first %}
{% set lowest_price = lowest.value * states('input_number.nextenergy_additional_electricitycosts') | float(0) %}
{% set cheapest_time = lowest.start %}
{{ cheapest_time }}
You've got a "comment" of ## My Template somewhere that got into the datetime value
I was wanting the AC to turn on to cool in a certain zone if an outside temp is higher than certain temp. I have a zoned system with 4 Thermostats and need HA to check if none of them are set to heat. I was wondering if this is the Template i need to use in an automation because the {{ is_state('climate.first_floor_thermostat', 'heat') }} template will only give me a false answer. The iif Template below seems to work in Developer tab Template i just needed some direction and advice.
{{ is_state('climate.first_floor_thermostat', 'heat') | iif('False', 'True')}}
{{ is_state('climate.basement_thermostat_2', 'heat') | iif('False', 'True') }}
{{ is_state('climate.master_bedroom_thermostat_4', 'heat') | iif('False', 'True') }}
{{ is_state('climate.second_floor_thermostat_3', 'heat') | iif('False', 'True') }}
Yeah that comment is at the beginning of the Template sensor I shared earlier
Sorry, accidental @ ๐
The error indicates that it's making it into the value from what I can tell
Lets see what happens if I remove it
Hi guys, i want in State only when is power more than 2W+, is it possible to do it?
- platform: history_stats name: Boiler Heating Time entity_id: sensor.boiler_power state: ">= 2" type: time start: "{{ now().replace(hour=0, minute=0, second=0) }}" end: "{{ now() }}"
You need to make a template binary_sensor for that, and then use it for history_stats
ok thx
Can someone tell me where I'm going wrong?
** - platform:
sensors:
boiler_heating:
friendly_name: Boiler Heating
icon_template: mdi:water-boiler
device_class: heat
value_template: >-
"{{ states('sensor.boiler_power')|float > 2 }}"**
Don't use quotes around your template if you use the multi line format
same problem
Invalid config for [binary_sensor]: string value is None for dictionary value @ data['platform']. Got None. (See /config/configuration.yaml, line 44).
Seems clear enough
after when i create this binary sensor
sorry I didn't see it platform: template
I've got a relatively basic question about templating yet again. I have the following and I'd like to make it more generic with the device name in the value_template and both entity_ids:
- platform: template
switches:
ac_toggle:
friendly_name: "Air Conditioning"
value_template: "{{ not is_state('climate.fujitsu_ac', 'off') }}"
turn_on:
service: climate.turn_on
target:
entity_id: climate.fujitsu_ac
turn_off:
service: climate.turn_off
target:
entity_id: climate.fujitsu_ac
possibly also the friendly_name
or, if there's a better way, I'm all ears. Weird that there's no climate.toggle
There's not much you can do here to make it more generic, unless you either add the object id in the entity id or friendly name
Ok, that's fine then - thanks
switch:
- platform: template
switches:
toggle_fujitsu_ac:
friendly_name: "Air Conditioning {{ this.entity_id.split('_')[1:] | join(' ') | title }}"
value_template: "{{ not is_state('climate.' ~ this.entity_id.split('_')[1:] | join('_'), 'off') }}"
turn_on:
service: climate.turn_on
target:
entity_id: climate.{{ this.entity_id.split('_')[1:] | join('_') }}
turn_off:
service: climate.turn_off
target:
entity_id: climate.{{ this.entity_id.split('_')[1:] | join('_') }}
I see what you mean. I think I'll just put in all 3, just in case I want to change things later
TemplateError('ValueError: Template error: float got invalid input 'unknown' when rendering template '{{ states('sensor.192.168.100.35_sound')|float > 150 }}' but no default was specified') while processing template 'Template<template=({{ states('sensor.192.168.100.35_sound')|float > 150 }}) renders=4>' for attribute '_state' in entity 'binary_sensor.bathroom_threshold'
what must I do
define a default for the float filter, or add an availability filter to your template sensor
if it's a template sensor
It canโt determine the state of your entity.
Only one . is allowed in an entity
Open your Home Assistant instance and show your state developer tools
wow didn't catch that, cheers
#voice-assistants-archived please
This is the template channel.
Hi. I have used the top one up until now because it gave me a value even when the light was turned off. This does no longer work and I have to resort to the lower notation which does not. Is there a way of achieving the same functionality?
{{ states.light.speaker_rgb.attributes.brightness }}
{{ state_attr('light.speaker_rgb', 'brightness')}}
That's not true
the first one would error out if the attribute didn't exist
that's never changed
that's why the first method is not suggested
@pastel moon ^
Well, now it does yes. But my code is unchanged since it did work... ๐ฆ Oh well, will have to find another way then. Thx
ther'es no well now it does, it's always been like that
literally
it's a dictionary, if the item doesn't exist, it will error
and lights from day 1 do not have the brightness attribute when off
so that code would have errored from day 1
Will not argue, so will check my backups. Something is not adding up, but agree that the first sounds unlikely.
Now it's a mystery. Backups from december show the same statement, and back then I know it did work. That aside then (I hear you), is there any way to mimic that behaviour?
ie to get the brightness level for a light?
you can default it to 0 when it's off
{{ state_attr('light.speaker_rgb', 'brightness') | default(0, true) }}
Thanks, that's an improvement, but I would need the last set level as baseline for a calculation...
not when it's off
If you need the last level you need to store it in an input_number, using an automation, or in a trigger based template sensor
Thanks, I'll have to modify it to use that then.
If you had that behavior in the past, this must have been a light that you manually created or a custom integration. If it was a built in integration, then post what integration that light came from
Philips HUE in this case, connected through Z2M. Can the code have been lingering and removed about last week in some update?
that would be an MQTT light
Ok
I've been using that for about a year now
and those have always had no brightness when the light is off
did you use auto discovery or did you use manual configuration?
It hasn't thrown an error at least
To include it? I really don't remember, it was a long time ago
Can you post the code you were using?
Auto I assume
Yes, give me a minute
This is what I've been running https://paste.debian.net/hidden/1a6468a4/
it is called by an automation to set some parameters, but brightness was read from the script itself
Are you 100% sure you've ran this when the lights are off?
this would have errored for years
there is countless forum posts about this
Absolutely. It is suppose to flash lights when for example the washing machine is done, which happens regardless of lights on or off
I don't see how this could have ever worked
I don't know now either... :/
That script can't be that old
you're using this.entity_id
that's maybe a year old now
Yes, I try to keep it reasonably updated...
I suppose I have to settle for a set default value then. It'll do the job. Nice with reading the brightness was it was never too bright. But not the end of the world...
The default @marble jackal mentioned makes it work, so happy with that. Thanks for having a look
I have an sensor attribute of "300" that is in seconds, so 5 minutes. I am trying to create a template that adds that attribute value to the state change of a switch. This template gives me the last state change of the switch: {{ as_timestamp(states.switch.bhyve_back_central_zone.last_changed) }}
{{ states.switch.bhyve_back_central_zone.last_changed + timedelta(seconds = state_attr('your_sensor', 'the_attribute')) }}
Thanks, had too add in the second ")" at the end but it other worked
hi all, im trying to create a sensor for imap_content but, im not sure where it place this code from the docs
https://www.home-assistant.io/integrations/imap/
it says i can use the " data in a template sensor."
its not accepting the word trigger when placing it in my templates.yaml in sensor.
Don't put template: in templates.yaml, just put the rest
you already presumably have template: in configuration.yaml
correct, but it does not accept the word trigger
this is what I'm pasting in my termplates.yaml w/o the word template and proper indentation:
http://pastie.org/p/3nfHrUYh9COkt2codrTWWS
maybe I have to place the sensor part in sensor.yaml?
its not accepting the word trigger when placing it in my templates.yaml in sensor.
What is not accepting it?
Template variable error: 'trigger' is undefined when rendering '{{ trigger.event.data['date'] }}'
Template variable error: 'trigger' is undefined when rendering '{{ trigger.event.data['headers']['Delivered-To'][0] }}'
Template variable error: 'trigger' is undefined when rendering '{{ trigger.event.data['headers']['Return-Path'][0] }}'
Template variable error: 'trigger' is undefined when rendering '{{ trigger.event.data['headers']['Received'][0] }}'
Template variable error: 'trigger' is undefined when rendering '{{ trigger.event.data['headers']['Received'][-1] }}'
where do you see that?
core logs
that doesn't make sense
You're looking at old logs or the wrong spot
Also seems odd to me that you have those logged errors without a timestamped line
you probably didn't have the trigger: part when it produced those logs
which leads me to believe you're looking in the wrong spot
where did you get those logs from?
what do you mean "in core"
core logs
from the UI?
ok, lets try again, here's what is in my template.yaml file
https://ibb.co/bP6PRJY
when I press refresh template enties
I get this error
the friendly_name above shows me that you're putting this in the wrong spot
The following integrations and platforms could not be set up:
template (Show logs)
Please check your config and logs.
log
Logger: homeassistant.config
Source: config.py:982
First occurred: 9:27:44 AM (2 occurrences)
Last logged: 9:51:18 AM
Invalid config for [template]: [trigger] is an invalid option for [template]. Check: template->sensor->31->trigger. (See /config/templates.yaml, line 1).
or the friendly_name above is not correct
ah ok, based on that error, your indentation is too indented
so as it turns out
you're incorrectly using friendly_name and you spaced it out wrong
and the binary_sensor: below says that you've messed up your indentation
the - trigger: should be at the same indentation level as - binary_sensor:
and because I have a feeling you're going to omit doing sensor... sensor needs to be the same indentation level as trigger, but without the dash.
I have no idea how you manage to do yaml
I'm trying to just look at your image and find out the spacing you have above and it doesn't match any standard practice, and it doesn't match what you have below on - binary_sensor:
Oh wait, I guess you're doing
- field:
- field:
sub_field:
if that's the case, then just copy/paste this.
- trigger:
- platform: event
event_type: "imap_content"
id: "custom_event"
sensor:
- name: imap_content
state: "{{ trigger.event.data['subject'] }}"
attributes:
Message: "{{ trigger.event.data['text'] }}"
Server: "{{ trigger.event.data['server'] }}"
Username: "{{ trigger.event.data['username'] }}"
Search: "{{ trigger.event.data['search'] }}"
Folder: "{{ trigger.event.data['folder'] }}"
Sender: "{{ trigger.event.data['sender'] }}"
Date: "{{ trigger.event.data['date'] }}"
Subject: "{{ trigger.event.data['subject'] }}"
To: "{{ trigger.event.data['headers']['Delivered-To'][0] }}"
Return_Path: "{{ trigger.event.data['headers']['Return-Path'][0] }}"
Received-first: "{{ trigger.event.data['headers']['Received'][0] }}"
Received-last: "{{ trigger.event.data['headers']['Received'][-1] }}"
got it! that was it, placing the above ^
thank you!
thank you @mighty ledge and @inner mesa
now would be a good time to study that and understand how YAML indentation works ๐
yes, I had the impression that only sensor or binary_sensor was allowed as primary (left most entries), but as I learned today, that is not he case ๐
@final abyss I converted your message into a file since it's above 15 lines :+1:
I want to use 2 input selects to output a value. 1 for meat type and 1 for cook temp. 1 selects Pig 1 selects Medium and i want a sensor outputting 160. My template skills are lacking.. Any ideas? (Json table to pick values from posted above)
{% set a = states('input_select.meat') %}
{% set b = states('input_select.temp') %}
{{ your_data.get(a, {}).get(b) }}
Thanks!
ok i have to be missing something completely obvious
value_template: "{% for device in json_data.devices %}{% if device.serial_num == 'xyz' %}{{ device.soc }}{% endif %}{% endfor %}"
The system cannot restart because the configuration is not valid: Invalid config for [rest]: template value should be a string for dictionary value
how long for chicken, medium rare?
what's device.soc output?
a number
no quoting issues
i assumed the error meant the template itself needed to be a string in the yaml
๐คทโโ๏ธ
works fine in the dev tools template editor too
works even better when i have it indented properly ๐
is there any way to get from trigger from_state how much that entity was in state on, and when its changed the state to ask something like '{{state.from_state.entity was more 10min}} then do something'
trigger.to_state.last_changed - trigger.from_state.last_changed
Is it possible if I have a list like this to grab 2 starting from the highest 3 digit value so 4.
Would return
foo003, foo004
{% set foo = ['foo001','foo002','foo003','foo004'] %}
The highest 3 digit value or the one you specify?
{% set foo = ['foo001','foo002','foo003','foo004'] %}
{{ (foo|sort)[-2:] }}
{% set foo = ['foo001','foo002','foo003','foo004'] %}
{% set input=4 %}
{% set index=foo.index('foo' ~ "%03d"|format(input)) %}
{{ foo[index-1:index+1]|join(', ') }}
Thank you that's really much simpler than I thought lol
Hi I am trying to create a sensor that can alert me of Power Outage. I am using a voltage sensor value for this. Whenever voltage becomes Unavailable. My sensor gives me a state that Utility Power is Unavailable. Issue is that logs are not appearing for state change. Only history bar is showing up. I can't trigger an automation using it's states as well. Following is my code:
- sensor:
- name: "Utility Power"
state: >
{% if is_state('sensor.ground_floor_channel_1_voltage', 'unavailable') %}
Unavailable
{% else %}
Available
{% endif %}```
Tnx, but I ened also to know which exact state? because this entitiy can have multiple states not just on and off states?
I want to say I want to measure only trigger.from_state where state was "on"
I wan to to know duration how long was my entity in state "on" before went to state "off"
The 'history bar' showing up is normal. Why can't you trigger an automaton based on it?
It does not acknowledge Available state as trigger in automation. I don;t know why but whenever i try to trigger it upon state change from Unavailable to Available. and vice versa The Automation never triggers.
you can type whatever you want
I am thinking as it is a template sensor and not a binary sensor. That's why it's causing these issues
no
Unavailable and Available are just strings
there should be no problem using them in a trigger
shouldn't need to, but won't hurt
in any case, your problem doesn't seem to be with the template sensor, but with an automation
s long as the state of the sensor is reflecting properly in
-> States
here is the trigger inside an automation. It has never triggered.
trigger:
- platform: state
entity_id:
- sensor.utility_power
from: unavailable
to: Available
condition: []
action:
unavailable and Unavailable aren't the same
Here is another automation that was created moths ago. Never triggered. In this Unavailable is with capital U.
trigger:
- platform: state
entity_id:
- sensor.utility_power
to: Unavailable
from: Available
attribute: current
condition: []
action:
sorry for that i have tried without attribute as well. Never worked.
I can't fight a strawman
without the attribute line, it should work just fine
try it now
both of what you've posted have clear issues
It was my last hope finding something that might work that i added this redundant line attribute. Believe me i have tried without attribute as well.
again, I don't know what to say
it's not redundant, it's just wrong
that attribute won't ever be either of those values
I know it's wrong but i have tried the correct as well.
ok. I have no more feedback, then
Btw can you tell me how can I alter this Utility_Power sensor so it can give me state change logs as well. Right now it's only showing history bar. Thanks for the input.
Not directly. SQL sensor or a trigger template sensor, depending on your scenario
There are some stats integrations as well, depending on what you need
hi guys, am trying to do a rest sensor from this template but it doesn't show up correctly https://pastebin.com/H7rncqi6
this what the data looks like, I dunno if I have the template down correctlyhttps://imgur.com/a/wriijDe
the sensor does update when the proximity sensor is actioned but the state is always "detected" (on, basically)
Can you share that data in its original/raw form as text/JSON?
Yes. The template looks correct if you want to get the 8 in this case
hmm forgot to say I have it as a binary sensor
don't mind how it looks like. either the 8 or off is fine by me
on would be 0 (cm) - i.e. when the prox sensor is actioned
I switched it to a regular sensor and it went through. Thanks!
Currently I have:
- name: "Kitchen Motion Hybrid Sensor"
device_class: motion
state: "{{ is_state('binary_sensor.kitchen_motion_sensor', 'on') and is_state('binary_sensor.kitchen_motion_sensor_mmwave', 'on') }}"```
but was wondering how I can do
is_state('binary_sensor.kitchen_motion_sensor', 'on') THEN is_state('binary_sensor.kitchen_motion_sensor_mmwave', 'on')
so it never triggers if the MMwave senses it first
{% set motion = is_state('binary_sensor.kitchen_motion_sensor', 'on') %}
{% set mmwave = is_state('binary_sensor.kitchen_motion_sensor_mmwave', 'on') %}
{% if motion %}
{{ mmwave }}
{% else %}
{{ motion }}
{% endif %}
amazing! thanks
@inner mesa you were right about my clear mistakes in the code.
Actually I was trying to edit in visual editor in the past. It was showing up as Unavailable in visual editor but in yaml it was showing up as unavailable. From now on I will confirm yaml.
Hi,
im using a custom DHL integration for package tracking. It creates for every package a new entity named "dhl.12345"
I want to create a automation that notifys me for every new state of new packages.
How can i create this automation that finds the individual entitys every time new? (something like auto entity card but for the backend)
@cloud valley I converted your message into a file since it's above 15 lines :+1:
@cloud valley I converted your message into a file since it's above 15 lines :+1:
How do I need to setup the template I need to get the automation to work the way I want it to work.
As the trigger only needs to look at the
"ResponseText": "Lights ON room X"
```c
portion of the received MQTT payload from the device
As when I have 1 template setup I can create multiple templates based on the same template. as the MQTT payload received by the device is always the same.
It is also the same when sending data to the device.
did you start with an MQTT trigger? https://www.home-assistant.io/docs/automation/trigger/#mqtt-trigger
I am using the GUI to create a automation. I have not dived deep enough into using scripts and such
Yes I start with a MQTT trigger
How would this work in the GUI for automations?
As that is what I am getting confused on.
Please post some example entities and their states, otherwise we'll be guessing here
and it will most likely be multiple automations or a template sensor
Do you mean like:
@cloud valley I converted your message into a file since it's above 15 lines :+1:
They are Tuya switches, controlled trough the Local_tuya addon.
for the switch I am testing it there are 2 states:
- type: turn_off
- type: turn_on
For the moment there will be multiple automations.
Where the voice command response of the device will dictate what room/switch will be controlled.
"ResponseText": "Lights ON room X"
Since this looks to be the easiest to implement/expand on.
As when I have it working for 1 switch with 2 states, it should work for other switches as well {curtain switch}
thats the entity: dhl.0034043469005055xxxx
the state is in german โDie Sendung wurde erfolgreich zugestellt.โ Means something like, the package got delivered.
the idea is to notify me about every new package that comes into the system when it changes to โDie Sendung wurde erfolgreich zugestellt.โ (when the package got delivered) with adding every package manually
Wait, it doestn let me copy properly ๐ฆ
no problem mate, i figured it out, just dont know if its perfectly
@icy jay I converted your message into a file since it's above 15 lines :+1:
thats it: https://pastebin.com/Tpb7Tb0v
hello and a nice good evening
i have problems with two entities from my huawei inverter from my solar system
the inverter provides one sonsor each for grid inport and grid export.
But the data of the sensor are total kwh values
but I need current and daily values in w/kw and kwh
I have read that you can do this with sensor templates.
Unfortunately, I have no idea at all about programming and although I have now searched and read several days on different sites, I could not solve my problem.
I have then tried to adjust the sensors via the helper, but also get no accurate values.
Can someone help me here?
The sensors are as follows:
total kwh import: sensor.power_meter_consumption
total kwh export: sensor.power_meter_exported
hi all, I would like to create a true condition using this template of an attribute sensor
- condition: template
value_template: >-
{{ 'true' if state_attr('imap_content', 'Sender',
'Wifes Name') else 'false' }}
it does not seem to like the above.
Just use {{ is_state_attr('imap_content', 'Sender','Wifes Name') }} ... but your entity ID is wrong anyway
So that alone won't work
Is it sensor.imap_content?
You can use a state condition if you're just comparing against an attribute string, too: https://www.home-assistant.io/docs/scripts/conditions/#state-condition
So then the template route for that is {{ is_state_attr('sensor.imap_content', 'Sender','Wifes Name') }} , if Sender is the attribute name on that entity
Hi
i need a template as a condition in an automation, that checks if there is no entity in the system with a specified domain. How can i do this?
I have some time-throttled devices that sometimes get stuck at an old value. Here is the YAML
- platform: filter
name: "Garasje - Easee 1: Effekt_Filtered [W]"
entity_id: sensor.garasje_easee1_effekt_live
unique_id: sensor.garasje_easee1_effekt_filtered
filters:
- filter: time_throttle
window_size: "00:02"
Here is a picture of the stuck devices:
https://imgur.com/a/BbL4sR6
or maybe a sensor that checks if a domain is in the system
You want if there's zero entities within a given domain?
exactly
Thanks!
And if i want to count them?
remove the equality and it'll give you the total number of matching entities
perfect!
Thanks a lot ๐
Is there a way to evaluate a template, to test the output?
thanks
Is there a clean way to ensure a list exists in it's entirety in another list.
{% set fooey = ['foo002','foo003','foo004',
'foo001'] %}
{% set bar = ['foo002','bar003','foo004',
'foo001'] %}
Bar must be a full match with fooey but not == meaning if fooey was this it should still work as long as every item of bar was in fooey
{% set fooey = ['foo002','foo003','foo004',
'foo001','foo005','foo006'] %}
I feel like you're asking about interview questions in real time ๐
Hope you get the job!
๐๐๐
No lol but it is work related
Trying to make sure 1 list is in another
But not ==
The answer is to start with the subset list, reject items that are 'in' the larger list, and check the length of the resulting list for == 0
Oh yeah ๐คฆโโ๏ธ if Petro was here I wouldn't hear the end of me not thinking of using reject lol
Iโm here silently judging
Lol it's been a long day of troubleshooting issues I completely forgot about that method.
I hope I got the job
Lol no it's not an interview ๐๐. We use Ansible for automating infrastructure
hi, how to create a condition where I want the condition to fail because door was opened within the last 3 minutes of when the a trigger was triggered
if door was opened in the last 3 minutes, do not proceed
state: off
for: 3 minutes
``` ?
oh yeah, that would work!
thanks
- condition: state
for:
hours: 0
minutes: 2
seconds: 0
entity_id:
- binary_sensor.shed_door
- binary_sensor.gate_front_door_side
- binary_sensor.gate_garage_side
- binary_sensor.back_door
state: "off"
๐
Ok, I have this automation that I only want firing no sooner than every 30 minutes between sunrise and sunset:
- condition: template
value_template: >-
{{(as_timestamp(now()) - as_timestamp(state_attr("automation.bird_feeder",
"last_triggered") | default(0)) | int > 1800 )}}
now, if I wanted to add another condition that I don't want it firing more than 5 times a day, any idea how I can set that condition up?
Add a counter and reset the counter at midnight.
I keep on geting this error: https://1drv.ms/i/s!ApzByAh_w4hMgaAu8E61timggxcsOQ?e=FfZGeV
How do i figure out which "thing" is causing my error?
Is that a picture of some text? I didn't bother past the login
Just post the text from the error please
Unable to copy and paste the text
Use a proper SSH client, get the log from the logs site in web interface or use something like samba to grab them
Could you please tell me how I can use the GUI for the template/check I want for my MQTT device?
since I get confused between the GUI and how to set it up script wise.
As I do not know where to put it, and the way it looks in the guide is different than how the jaml code looks in the automations portion
I have now tried to solve my problem differently
I have combined my 3 phases via the helpers into one sensor.
have this sensor then used, also works almost...
only has the sensor reversed values ๐ฆ current that flows into the network is displayed as import...
have then searched again on the internet and came across a template that swaps the values.
have adapted this to my sensor but now get the following error
cant insert a picture :(, thats my tamplate
template
sensors:
sensor.3_phasen_in_out:
value_template: >-
{{ is_state('binary_sensor.sensor.3_phasen_in_out', 'off') }}
friendly_name: sensor.3_phasen_in_out-inverted
device_class: lock
on line 3 there is an error "can not read a block mapping entry; a multiline key may not be an implicit key" unfortunately I do not understand the error :/
@scenic siren To format your text as code, enter three backticks on the first line, press Shift+Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks.
```yaml
example: here
```
Don't forget you can edit your post rather than repeatedly posting the same thing.
You are mixing the new format and the legacy format
Or maybe not, but in that case platform: template seems to be missing
Not clear because of missing code tags
thank you, i did not know how to do that :/
i understood that if i use platform: template then i need an extra template file. but for now would just like to have it in the yaml configuration
You need to remove the sensor. part from sensor.3_phasen_in_out
No, you don't need an extra file for that
The code you have now belongs under sensor:
sensor:
- platform: template
sensors:
3_phasen_in_out:
value_template: >-
{{ is_state('binary_sensor.sensor.3_phasen_in_out', 'off') }}
friendly_name: sensor.3_phasen_in_out-inverted
device_class: lock
Why device class lock?
And why not at binary sensor?
Unfortunately, I cannot answer these questions.
I have no idea about programming at all.
I'm just looking for a few days desperately a solution to adapt my sonsor.
on the search I have found a template which swaps the values and have simply entered my sensor :/
my inverter has only one sensor each for grid import and grid export in total kwh data
i thought i could get a current value with the 3 phases ๐
this actually works, only that the values are swapped.
therefore the template
thank you for your help.
I have deletet the
device_class: lock
at the end, now i don't get any error anymore.
when i wanted to use the new sensor, i could not because it shows that the sensor has no unique id.
i'm sorry to bother you with such trivialities, i just don't understand the whole thing.
just a quick one, trying to figure out a template for echo dots (because I want to use them in conditional) and want the template sensor to show a state if the say media_player.echo stat is standby or paused
I know now how to do one if state is return, but what if I want to use 2 of the states device can be in
Do you mean if-then with more than 2 possibilities?
{% if some_test %}
{{ x }}
{% elif another_test %}
{{ y }}
{% elif ... %}
...
{% else %}
{{ z }}
{% endif %}
basically yes, echo dots are either in standby or paused when you say stop, I want my conditional card to show calendar when echo is in either of them stats
@cursive ice I converted your message into a file since it's above 15 lines :+1:
that obviously failed
Oh...it's because if you list multiple conditions in a conditional card, it will display only if all conditions are true.
Your intent is to implement the or logic in a template sensor, then use the state of that sensor for the conditional card?
{{ states('media_player.xxx') in ['standby', 'paused'] }}
Pop that in the value_template of a template binary sensor.
there we go, thank you
sensors:
echo_dot_clock_state:
friendly_name: 'echo dot clock state'
value_template: >
{% set state = states('media_player.echo_dot_clock') %}
{{ 'standby' if state == "paused", "paused" else playing }} ```
ok that was wrong lol, not to hopeful for me
ah, ok, my mistake was already thinking I can adjust something I already had for another sensor.
If you really need the state to be a specific string instead of true/false, you can check out immediate if:
https://www.home-assistant.io/docs/configuration/templating/#immediate-if-iif
But I think you just need a binary sensor.
I only tried that as I have quite a few sensors done that way for example - platform: template sensors: washing_machine_current_course: friendly_name: 'Washing Machine Current Course' value_template: > {% set current_course = states('sensor.front_load_washer_current_course') %} {{ 'Program set' if current_course == "-" else current_course }}
I thought just adapting that to fit this would work lol
You can theoretically implement it as a sensor. But your adaptation didn't go far enough. == tests if one value is identical to another. What you want is in, which tests if one value is among a list [...] of values.
Hey. Was redirected here from #automations-archived, need to create a condition in an automation to only run when triggered by a user and not run when trigger by script.
I tried to use a template condition:
condition:
- condition: template
value_template: "{{ context.user_id != None }}"
But when I test the condition, I get this error: In 'template' condition: UndefinedError: 'context' is undefined. Either I'm using context incorrectly or it isnt defined in conditions block?
Is it possible the context is not defined because its just a test?
I test by pressing the 3 dots and then pressing test
done and working with
- platform: template
sensors:
echo_dot_clock_state:
friendly_name: 'echo dot clock state'
value_template: >
{% set state = states('media_player.echo_dot_clock') %}
{{ 'standby' if state in ["paused", "paused"] else playing }} ```
thank you
Pretty sure you mean ['paused','standby'] and 'playing'?
yes your correct its paused, standby else playing
You canโt text that condition that way, you have to run the automation to test it
I see
The condition should be good yeah? Since the user_id will be none if a script causes automation to run
Then add a unique_id to your config.
Check the docs, the legacy format you are using is at the bottom
hello
after you have helped me with the template, i have read further in the help to solve the problem and have also managed it for now.
the code is now:
sensor:
- platform: template
sensors:
3_phasen_in_out:
value_template: >-
{{ is_state('binary_sensor.sensor.3_phasen_in_out', 'off') }}
friendly_name: sensor.3_phasen_in_out-inverted
device_class: energy
unique_id: 'Test grid Sensor'
```now i can select the sensor and use it in the integration.
But now there is a new problem.
the output value of the sensor is false?
You can't test those templates in the GUI because the variables don't exist
Yes, what did you expect the output to be?
Um, I see the same error in traces when the automation runs
You'll see all variables that exist in the automation
so just click on the topmost trace element to see changed variables for the whole thing?
(topmost is trigger)
my thought was, since my inverter only outputs total kwh values, to create a current value with the three phases.
I would like to have current values for grid export and grid import.
so i put the three sensors of the phases together via a helper.
this also works, but the values are interpreted incorrectly.
if i now consume electricity this is displayed as grid export, if i export electricity this is displayed as grid consumption.
therefore my idea to swap the sensor values over the template
thank you
I had to use trigger.to_state.context
{% set stuff = [{'hostname': 'foo001', 'ip_address':'1.1.1.1' }, { 'hostname': 'foo00', 'ip_address':'1.1.1.2' }] %}
{{ tst | random }}
Is there a way to remove a random n of items from a list of dicts?
Let's say there were 4 lists of dicts and I wanted to remove 2. It would remove 2 in a random order not necessarily the first or last items in the list of dicts.
Select one random item, reject that. Repeat that
Hm so use a loop essentially?
Yes, or just repeat the steps
@scenic siren I converted your message into a file since it's above 15 lines :+1:
hiya guys, need a bit of help with this. I'm trying to convert uptime to a more human readable information from IPP integration. So as some of you might already know that although the uptime entity (once it's enabled) showed the right information(in minutes). when it's queried via dev tools, it is showing in date and time format (of when the printer was initially switched on). HA seems to be doing its own calculation by subtracting now() with it's payload = time in minutes. I'm trying to set a simple automation just to send me an alert if uptime is more than certain minutes, but due to my lack of knowledge of template, even after reading the documentations along with some other articles I found, I still couldn't make the head or tail of this. Would anyone please help me to show me an example that I can do to get the info I need?
{{states('sensor.epson_et_3750_series_uptime') }}
currently that template gives out--> 2023-05-24T13:53:56+00:00
Try {{ now() | as_timestamp - states('sensor.epson...uptime') | as_timestamp > xx }}
Where xx is the time threshold in terms of seconds
Thanks @rose scroll - the result is still showing as this --> 2023-05-24T15:01:26+00:00, I just copied pasted it into template editor. am I meant to add anything else?
Ah, when I trimmed it down to just {{ now() | as_timestamp}}, the result is this --> 1684940828.728487
Umm...the result should be true or false, not another timestamp.
{{ (now() - states('sensor.epson_et_3750_series_uptime') | as_datetime).total_seconds() / 60 > 10 }}
for 10 minutes
'greater than 10 minutes'*
ahhhhhhh
now we are getting somewhere
Thanks @mighty ledge , I think I starting to understand how this works
you can use as_timestamp too but it get's hairy when you do or don't have a TZ attached
I'm now getting true or false
so I just avoid it
thanks both!
just keep in mind that the value can go negative if your sensor for some reason is set to a value in the future
ok ok
but that would be the sensor messing up
it'll be false, so it shouldn't impact the tempalte
How would I need to set it up then to do what I want it to do?
It would be something like:
1: MQTT signal comes in
2 check if payload contains = X:
"ResponseText": "Lights ON room X"
3.1 If payload contains = X go to step 4
3.2 If payload does not contain X= do nothing
4 activate: switch_1_on / Switch_1_off
With an MQTT trigger for the topic and an if: or choose: based on the payload
I think I linked this earlier: https://www.home-assistant.io/docs/automation/templating/#mqtt
Yeah, just make an automation using the links posted by rob
Your template would just be {{ 'X' in trigger.payload }}
The rest is #automations-archived
In this case, like {{ 'c' in trigger.payload_json.Data.ResponseText }}
Soo I need to enable templating first, then create a automation trough the GUI?
or do I need to make it trough a template
you don't "enable" templating, you just use a template where it's accepted
And how do I do that?
type things?
there are examples in the docs: https://www.home-assistant.io/docs/scripts/#choose-a-group-of-actions
Do you know how to make an automation?
choose the right things in the UI
Because thatโs step 1
A automation trough the GUI?
Yes I know how
Ok, then you should know how to create a trigger then
And a condition
Youโd use an mqtt topic trigger
I have a empty template as a condition, I get stuck on how I need to have it do what I want it to do
this one, based on the JSON response that you posted earlier: #templates-archived message
or I guess petro's would work if you just want a string search in the entire raw JSON ๐
Thank you this looks to be working.
ok so I've got a bunch of trigger-based binary sensor templates, and their conditional icons aren't working.
@fallow gulch I converted your message into a file since it's above 15 lines :+1:
this is from my templates.yaml ^^
I'm getting the 'else' icon even if the sensor is in its 'on' state
But only some of the time. The "Kitchen" one below was working fine for a little while yesterday, now it's back to the outline icon whether its off or on
Do the id's need to be unique to each instance of trigger?
Use the trigger id to define the icon too...
{{ iif(trigger.id == 'on', 'mdi:food', 'mdi:food-outline') }}
I think that's worked. I had to trigger them all to get the icons to refresh, but I gather this was expected behaviour.
thank you!
must be missing the obvious, but just about the only template sensor in my config I can not control the precision of is this:```
template:
-
sensor:
- unique_id: length_of_day_factor
name: Length of day # factor for circadian light calculation'
icon: mdi:altimeter
state: >
{% set daylength = states('sensor.astral_daylight')|float %}
{{((daylength*-0.0063616)+0.11131)}}```
- unique_id: length_of_day_factor
and it really needs it....:
right, I wasnt aware that would be a prerequisite.... (I now notice I can take out all the parenthesis too btw, its a legacy template I didnt revisit for some time now)
why wouldnt' that be?
you can't set a precision on a string
unit of measurement controls everything about sensors
been like that since day 1
that's why the graphs aren't numerical when you don't have a UOM
correct, and I had this before:```
{% set daylength = ((as_timestamp(state_attr('sun.sun','next_setting')) -
as_timestamp(state_attr('sun.sun','next_rising'))) /
3600) + 24 %}
{{((daylength*-0.0063616)+0.11131)|round(5)}}
yep, still a string, and you rounded it yourself
Bet ya if you showed the history, it wouldn't be numerical
given the fact this is a factor, and not some time unit, do we have an appropriate UOM for that? or device_class for that matter: https://developers.home-assistant.io/docs/core/entity/sensor
seems a hack to me doing that.... but, I did now, and still cant set it in the ui:
how is that a hack? It's unitless...
what's no unit? An empty string
clear your cache and refresh the page
you may also need to restart
so I understand correctly: having that template without unit makes it a string (like all templates) but setting an empty unit on it makes it a number? (or at least an entity with a configurable precision.)
and no clearing cache or restart didnt fix that
You're giving it "no units"
Make sure yaml is actually putting the UOM
if not, make it a space " "
a yes I'll try that. btw this is what it is showing in dev tools now
Try adding a stateclass
and adding the space there helps!
nice
yep, much better
heck what is with all these rabbit gifs on each post
oops, sorry too big, ill delete that
it's fine
thx Petro, 1 issue down
is there more than 1 issue?
there's always more issues ๐ I've just finished another icon template rest writeup https://github.com/home-assistant/core/issues/93527
having trouble following your issue there
oh apparently icon can be templated
color me surprised
yes, me too, it's complex: 1- rest does not hot reload, 2- it throws errors, and 3- the icon template is not always used
@thorny cargo I converted your message into a file since it's above 15 lines :+1:
Ive added that summary ;-0
@thorny cargo look at your select.nachttisch_rechts_gradient_scene entity in developer tools -> states, and find the actual name of the attribute you're trying to use.
I can see a list of options there of which i want to randomly choose?
right, options
so look at your code...
what attribute are you trying to get?
hint, it's not option...
Why is it not an option?
What else?
I want to choose an option from the list of options randomly?
right the list of options
not option
I guess you aren't getting what I'm saying... you're missing the s on your attribute.
Thank you. I just got it right before you said it.
Got another question. I got a hue tap dial switch. Is it possible to dim only the last controlled light?
you'd have to build that system if it's not already built by the tap dial
input text or a template sensor
@grand walrus I converted your message into a file since it's above 15 lines :+1: