#templates-archived
1 messages Β· Page 54 of 1
currently reported value is 129
value_json returns 129 directly? Then you don't need .svalue1.
Does it return 129 as a number or string?
Also, 129 is not one of the numbers defined in your if statements.
yes sorry its a typo, corrected now π
If you remove .svalue do you still get an error?
@fierce hawk I converted your message into a file since it's above 15 lines :+1:
It says there that you have to provide command_topic: before it will parse the yaml validly.
It is required for an MQTT select, as per the docs.
FYI value_json will not resolve if it just returns a number. You'll have to use value. Also, if value_json does resolve and it has keys like svalue, you'll have to make sure to check the value type when making if statements. 129 is not the same as "129". You can see this directly in the JSON for the topic. No quotes means you check without quotes.
@fierce hawk I converted your message into a file since it's above 15 lines :+1:
There are missing % in front of each many }
it works π or at least it doesn't throw me an error!
thanks a lot
Ok so now it parses the value Level1, Level2 or Level3 instead of 129, 130 and 131 when I select the dropdown.
I assume this is because we need now a command_template
I've tried this:
command_template: >
{% if value == Level1 %} 129
{% elif value == Level2 %} 130
{% elif value == Level3 %} 131
{% endif %}
It doesn't work but I don't think I am too far; I tried to re[p;ace value by state but doesn't work either
You need quotes around your strings i.e. {% if value == "Level1" %} 129
that won't necessarily work
yes it will correct the problem on that template, but we still need to see the values in the topics
Im trying to send an image in discord but seems I dont have the option?
just copy/paste the value
the value are just
129
130
131
images are discuraged because we don't want pictures of text, we want the text
so the full topic value is just 129?
yes
then value_template and commadn_template will be opposite
@fierce hawk I converted your message into a file since it's above 15 lines :+1:
command_template: >
{% if value == 'Level1' %}129
{% elif value == 'Level2' %}130
{% elif value == 'Level3' %}131
{% else %}?????
{% endif %}
You need a command for the off selection
assuming it's zero
{% if value == 'Level1' %}129
{% elif value == 'Level2' %}130
{% elif value == 'Level3' %}131
{% else %}0
{% endif %}
then reverse it for the value_template
{% if value == '129' %}Level1
{% elif value == '130' %}Level2
{% elif value == '131' %}Level3
{% else %}Off
{% endif %}
ok, should it be ' or " ?
doesn't matter
it works π
one thing I noticed is that the state is "unknown" under the dev tools/state
select.ccei_pump_speed -> unkown
I'd expect to be the reported value??
well, that depends on your state_topic
that's why I've been asking for you to copy/paste the values from your topics here
because right now, I have no idea if what you're saying is correct
what is the best way to share this? the way I checked the values are on MQTT explorer
topic: anteavs_C049EFEC7950/u8_w/filt_speed/info/reported
value history
129
130
...
if that's the case, it should just work on startup if the topic has one of those values in it
Hey guys. I'm at a loss on template fans. Can somebody explain to me what I'm missing in this setup? I can run a script that cycles through a set of scenes, where each scene controls a speed of a 3 speed fan. So, I have scene.dining_room_fan_all_off, all the way to scene.dining_room_fan_high_on. If I cycle through the scenes, everything works as expected. I want to make a template fan that comes on, when any of the fan speeds come on. I also want the template fan to show 4 presets or speeds, off all the way to high. I've set this example of a template fan up, but it doesn't work as expected. What am I missing?
scripts don't have states
so your preset mode template isn't correct
and your set_preset_mode service doesn't do anything
that should be calling the scenes, assuming that's what you want to run
I have no idea what to use as a turn on and turn off entity, or how I'd write the set_preset_mode.
Am I allowed to have more than 1 entity in the set pre set mode?
set_preset_mode is just an action section, exactly like the automation action section
So, I should be turning on the scenes that correspond to the fan speeds?
but you aren't using the preset_mode variable
Yes, it should be turning on the script that coresponds with the preset_mode
or scene
Do I need a script for every scene/speed or can 1 script that cycles through the scenes/speeds work?
you can do whatever you want it to do
that's the beauty, if you can dream it up, you can do it
it's a full action section
that means you can write multiple actions
What about the preset mode template, am I describing it correctly, or if not how would I?
This template does cylce throught the speeds fine, but I can't pick a set speed. I can only cycle.
You said scripts don't have states, but when I put {{ states('script.dining_room_fan_control') }} into the developer tool template, I get whatever the scene the script is on at the time. I thought that I could then describe the preset mode template, as each different scene of the script as a preset.
I'm sure templates are easy for guys like you, but I can't understand things like this, unless I get specific questions answered, or have directly similar examples.
Scripts are either off or on, and the latter only if they're currently running and waiting for something. At no time is the state of a script a scene
I have a ... aesthetical problem right now: This is my morning routine template: https://www.pastiebin.com/650c29e60ed40 and this the current output: https://www.pastiebin.com/650c2a2878563 today there is nothing on Google Calender and thus is does not show any appointment. My problem is that there are double spaces between a few of the outputs and these ugly newlines are not needed, too. What did I do wrong here?
you have spaces outside of the templated values
I do? I tried to get rid of any trailing and leading spaces. What for example do you mean?
von {{ states('sensor.openweathermap_forecast_precipitation_probability') }} Pr has a space before the value and a space after the value, if the value is empty you get 1+1 spaces
if you're referring to the whitespace, i.e. carriage returns. add -'s to your template. See pin #2
that is true, but the values are not empty by normal circumstances.
For example line 4. This line is passed nicely and then the output has two spaces instead of one before it continues with the line 7 rainy condition output. And the line 31 part seems to create newlines even.
petro answered the newlines issue
He did? I just fixed the second whitespace thx to him now, that for sure.
I know what a pin is, be assured about that. ^^ That pin talks about whitespaces and not about newlines. Anyways, after throwing around some - I managed to find the culprit for that and made things look almost good, still after the first line it starts with indentation... Current template: https://www.pastiebin.com/650c30f8e7c17 and output: https://www.pastiebin.com/650c311068455
I mean I know why it's there I guess, but if I remove the spaces from for example line 7 it starts to tell me in File Editor that I am doing bad things. Template Editor is happy though.
that indentation is because you have it indented in the template editor
whitespace in coding means spaces, carriage returns, regular returns, and tabs.
@wicked kiln you can remove a lot of repetition in the weather part if you do it more like this: https://dpaste.org/eXfr7
Any way to have state_arr check for multiple values?
{{ state_attr('deez.nuts', 'attr') in ['foo', 'bar'] }}
Yesss, @buoyant pine thank you.
True that... It's only there. So all fine for now, but your solution is interesting, too. Will tinker a bit with it. Thx to all
IMAP Content Template sensor
I'm having an issue with this template. I've discovered the nature of the issue...I'm just too new at templates to know how to fix it.
"val":{{- state_attr({{ light_entity }}, 'brightness') -}}
{{light_entity}} is defined elsewhere and works in all other calls within the script, but the 2 sets of {{ }} are throwing an exception
I was getting confused because other places I needed to use quotes around the double braced variable, but because this is a function it just needs the variable (not the value contained in the variable) ...right?
I'm confused as to why this works in Dev Tools but not when I create a binary template sensor helper with a Motion device class. Entity's state doesn't change even though the template returns properly in Dev Tools. Ideas?
{% set motion = 'binary_sensor.bathroom_motion_detector_on_off' %}
{% set occupancy = 'binary_sensor.bathroom_motion_detector_occupancy' %}
{% if is_state(motion, 'on') or is_state(occupancy, 'on') %}
Detected
{% else %}
Clear
{% endif %}```
binary sensors should always return on or off, not detected/clear.
so the device class handles the Detected/Clear, right?
Yes, it's just a frontend translation.
The sensor is on if the template evaluates as True, yes, on, enable or a positive number. Any other value will render it as off. The actual appearance in the frontend (Open/Closed, Detected/Clear etc) depends on the sensorβs device_class value
https://www.home-assistant.io/integrations/template/#state
changing to on/off is literally all it took to work. π€¦ββοΈ
You can just directly return the result of the test, it will be treated as on or off by yaml. Will save you some keystrokes.
{{ is_state('binary_sensor.bathroom...off', 'on') or is_state('binary_sensor.bathroom...occupancy','on') }}
Followed your suggestion but kept the variables. yaml {% set motion = 'binary_sensor.office_motion_detector_on_off' %} {% set occupancy = 'binary_sensor.office_motion_detector_occupancy' %} {{ is_state(motion, 'on') or is_state(occupancy, 'on') }}
Hi there,
I have a question regarding the brightness_scale on mqtt light.
I currently have a light where you can change the brighness but its on 3 levels instead of %
- 0 = 25%
- 1 = 50%
- 2 = 75%
- 3 = 100%
I have done the code below but doesn't seems to work: or maybe I should use a different slider?
light:
- name: "CCEI WEX30 PoolLight"
device:
identifiers: "C4DEE2D4C3B0"
manufacturer: "CCEI"
name: "Tild"
model: "V1"
hw_version: "1"
sw_version: "2.80"
unique_id: CCEI_WEX30_Light
state_topic: "tild_C4DEE2D4C3B0/u8_w/light_state/info/reported"
command_topic: "tild_C4DEE2D4C3B0/u8_w/light_state/info/desired"
# brightness: true
brightness_scale: 3
brightness_state_topic: "tild_C4DEE2D4C3B0/u8_w/light_bright/info/reported"
brightness_value_template: >
{% if value == 0 %} 0%
{% elif value == 1 %} 25%
{% elif value == 2 %} 50%
{% elif value == 3 %} 100%
{% endif %}
brightness_command_topic: "tild_C4DEE2D4C3B0/u8_w/light_bright/info/desired"
brightness_command_template: >
{% if value == "0%" %} 0
{% elif value == "25%" %} 1
{% elif value == "50%" %} 2
{% elif value == "100%" %} 3
{% endif %}
payload_on: "1"
payload_off: "0"
brightness_value_template should return a number, you are now returning a string
besides that, you've set the brightness_scale to 3, so 3 is now your maximum brightness value
I must admit I don't have a lot of experience with mqtt lights, but to me it looks like you don't need the brightness_value_template at all
for the brightness_command_template you might need to round the value, don't know if it will send a floating point number
you are completly right, i dont need the brightness_value_template at all
it works π thanks
What's the difference between from_keys in home assistant and fromkeys in native python when working with tuples ?
from_keys in home assistant works with tuples while native fromkeys does not.
Hello alltogether. May someone help me to get an automation working?
What i want to achieve: i have 11 room thermostats. every room has its own external thermostat. if 3 of the actual set temperatures are below 1 degree of the actual measured room sensors, i want to set the heater to on, because then i need enough thermal energy
from_keys and fromkeys are both python functions, you can read about them in python
First of all, the state of a climate entity is not the temperature, the actual temperature and the set temp are in the attributes.
But also your template itself is a compilation of several different templates, and some random strings stating template
it should return either true or false
- platform: state
entity_id:
- climate.tcv_badezimmer
attribute: current_temperature
For some reason all I can find is fromkeys for python.
trigger:
- platform: state
entity_id:- sensor.average_temperature_badezimmer
- sensor.average_temperature_buro
- sensor.average_temperature_dusche
- sensor.average_temperature_flur_anbau
- sensor.average_temperature_kinderzimmer_1_west
- sensor.average_temperature_kinderzimmer_2
- sensor.average_temperature_kuche
- sensor.average_temperature_schlafzimmer
- sensor.average_temperature_wohnzimmer
- platform: state
entity_id:- climate.tcv_badezimmer
- climate.tcv_buero
- climate.tcv_dusche
- climate.tcv_flur_anbau
- climate.tcv_kinderzimmer_1_west
- climate.tcv_kinderzimmer_2
- climate.tcv_kueche
- climate.tcv_schlafzimmer_ost
- climate.tcv_schlafzimmer_west
- climate.tcv_wohnzimmer_nord
- climate.tcv_wohnzimmer_sued
attribute: temperature
This should do it i think?
because average sensor is already a temperature which changes states
value_template: "{{ state_attr('climate.tcv_badezimmer','temperature') }}"
this should do it
Well, is this right here? "{{ state_attr('climate.tcv_badezimmer','temperature') }} <=1 {{ states('sensor.average_temperature_badezimmer','temperature') }}
"19.0 <=1 20.8
you are still creating 2 different templates with a string in between
test you templates in developer tools > templates, but I guess you want something like:
{{ state_attr('climate.tcv_badezimmer','temperature') <= states('sensor.average_temperature_badezimmer') | float }}
it should output true or false. Not something like 19.0 <=1 20.8
but how do i tell it,compare 1`?
{{ state_attr('climate.tcv_badezimmer','temperature') - states('sensor.average_temperature_badezimmer') | float <= 1 }}
something like that
subtract them, and compare the result with 1
or move stuff around {{ state_attr() + 1 <= states() | float }}
Thank you π
And if you want to test whether at least 3 of your thermostats pass that test, you can simply do {{ (state_attr('climate.xxx', 'temperature') - states('sensor.aaa') | float <= 1) + (state_attr('climate.yyy', 'temperature') - states('sensor.aaa') | float <= 1) + ... + (state_attr('climate.zzz', 'temperature') - states('sensor.aaa') | float <= 1) >= 3 }}
Because {{ true + true }} yields 2 π
Thanks π
I will try now, change from true to false worked by changing target temperature π
I just want to save unneccesary gas at winter
π
boiler should heat, if heat is needed, not the whole day
Can you provide a link to from_keys because I can't find it anywhere even python docs.
it seems to work π
{{ state_attr('climate.tcv_badezimmer','temperature') + 1 <= states('sensor.average_temperature_badezimmer') | float +
state_attr('climate.tcv_buero','temperature') + 1 <= states('sensor.average_temperature_buro') | float +
state_attr('climate.tcv_dusche','temperature') + 1 <= states('sensor.average_temperature_dusche') | float +
state_attr('climate.tcv_flur_anbau','temperature') + 1 <= states('sensor.average_temperature_flur_anbau') | float +
state_attr('climate.tcv_kinderzimmer_1_west','temperature') + 1 <= states('sensor.average_temperature_kinderzimmer_1_ost') | float +
state_attr('climate.tcv_kinderzimmer_2','temperature') + 1 <= states('sensor.average_temperature_kinderzimmer_2') | float +
state_attr('climate.tcv_kueche','temperature') + 1 <= states('sensor.average_temperature_kuche') | float +
state_attr('climate.tcv_schlafzimmer_ost','temperature') + 1 <= states('sensor.average_temperature_schlafzimmer') | float +
state_attr('climate.tcv_schlafzimmer_west','temperature') + 1 <= states('sensor.average_temperature_schlafzimmer') | float +
state_attr('climate.tcv_wohnzimmer_nord','temperature') + 1 <= states('sensor.average_temperature_wohnzimmer') | float +
state_attr('climate.tcv_wohnzimmer_sued','temperature') + 1 <= states('sensor.average_temperature_wohnzimmer') >= 3 }}
Anyone can help me out with the FAN template to control my type-D ventilation? I have a smart plug to turn then vent on and of, and a "shelly 2PM" to set the fan to MID and HI
Off : smart plug turned OFF
low : smart plug ON, S1 & S2 shelly OFF.
mid: smart plug ON, S1 ON& S2 shelly OFF.
hi: smart plug ON, S1 & S2 shelly ON.
Or Node-red, also good,I have read some posts, but still not really clear to me.
Lol, man, I was trying to assist you with a simple automation and that's what you came up with!
FYI that can be drastically simplified if you just shared the automation like I asked π
well, apparently you did, but it didn't ping me?? wtf
fucking discord
Well, i just didnt know how to do, it was work in progress π
give me a moment
might require you to check for -1 to -3
instead of 1 to 3
your template makes no sense
fyi
you're adding the value "True" which is equivalent to 1 to all your temperature differences then evaluating that against the number 2
No, I mean this mess:
what do you think it's doing?
I thought it is looking for every thermostat and its temperature sensor if the difference is higher then 1 degree. if 3 or more of these pairs are with that difference, then my heater will be set on
but it shows me true and false
yeah, that doesn't mean it's correct
hm :\
I pasted a working automation that literally does what you want
it didn't have the other trigger though
but you don't really need the other trigger
i try yours π
you want heat_cool mode, so you'll have to alter that service call
and as I said, if the temperature is below the average, then you'd want to account for that instead of what I had
@mighty ledge your automation does not trigger
i changed the service call to the right one
i have set 4 thermostats to 23 degrees, room temps are aroun 20 degrees, automation was not triggered
it'll only trigger when the temperature changes
yeah, but thats the thing: if room temperature is 19 degree, room temp thermostat is set to 19 degree. someone changes thermostat to 20 degree, then it should be count as 1. if some other rooms are also set higher, then that should also count and if 3 thermostats are set 1 degree higher, or temp in 3 rooms falls below 1 degree, heater should start heating π
that was what i meant with compare
π
so you have all these climate devices that don't run thermostats? They just give you a temperature?
no. i have actually 11 rooms thermostats. every rooms has its own, external room sensor. each thermostat will be actualzed every 15 minutes for the external temp. i have a gas boiler which only should heat, when enough heat is needed
these are danfoss ally thermostats. but if u measure the temperature directly at the heat, you will get extremely inaccurate room temperatues
at the radiator i mean not heat
these thermostats support external sensors. they measure the room temp at the middle of the room, far away from the radiator.
thats why i meaned that we need to compare the actual set temp of the room thermostat and the room sensor, then it works
that was why this -> {{ state_attr('climate.tcv_badezimmer','temperature') + 1 <= states('sensor.average_temperature_badezimmer') | float
the average sensor is middled by a custom sensor of the external room sensor by 5 minutes. if a door gets opened or a window, the thermostat should not immediately react to that
Any idea where I can find the from_keys python docs?
@petro thank you very much π it seems to work π
I think it's almost the same as the Jinja from_keys method
Petro said from_keys was python. But I think it's jinja? I can't find documentation for jinja either
Is it possible to have a sensor of device_class duration to only show days in the front end?
Don't believe this is customizable with any of the default cards.
You could do it with a template in Markdown card if that works for you
Hey, I'm trying to make a custom weather template, is there a field for the full week forecast?
because this forecast_daily_template: "{{ state_attr('weather.my_region', 'forecast') }}"does not work, I'm not sure what the template is expecting
(weather.my_region) is an entity coming from accuweather
The forecast attribute is depreciated and not used anymore by some weather integrations. You have to get the forecast by a service call
Does this work in devtools > template
yes, but it returns a list
Because if it does, it should work for the template weather
That's expected, a list with one forecast per item
What exactly do you mean with not working here
Invalid config for [weather.template]: [forecast_daily_template] is an invalid option for [weather.template]. Check: weather.template->forecast_daily_template. (See ?, line ?).
Are you on HA 2023.9?
Ancient
That specific key is added in 2023.9
forecast_template should work
it works indeed, thanks for the help
@brave vine I converted your message into a file since it's above 15 lines :+1:
You need to put your template into
-> Template and see what errors it shows. Not sure what you expected when you send a string representing a datetime into the float filter.
{% set LEDOn = states('input_datetime.light_s_on') | as_datetime %}
{% set Length = states('input_number.light_schedule') | float %}
{{ ( LEDOn + timedelta(minutes=Length) ) | as_timestamp | timestamp_custom("%H:%M:%S", True) }}
Or another way:
{% set LEDOn = states('input_datetime.light_s_on') | as_timestamp %}
{% set Length = states('input_number.light_schedule') | float * 60 %}
{{ ( LEDOn + Length ) | timestamp_custom("%H:%M:%S", True) }}
Thanks for the reply @lucid thicket, still fairly new to home assistant, not the most proficient at reading the docs, Iβve been trying to research online but couldnβt see much that would help in my case here, appreciate the comment
Sure. The template editor is extremely useful when trying to get this stuff correct. Just start small and as you get each line correct you can add more lines of code.
@heavy minnow I converted your message into a file since it's above 15 lines :+1:
- platform: history_stats
name: Bedroom AC today Uptime
entity_id: switch.window_ac_wall_switch_bedroom
state: "on"
type: time
start: >
{% if now().hour >= 18 %}
{{ today_at("18:00") }}
{% else %}
{{ today_at("18:00") - timedelta(days=1) }}
{% endif %}
duration:
hours: 24
alternative
start: >
{% set t = today_at('18:00') %}
{% set d = 0 if now() > t else 1 %}
{{ t - timedelta(days=d) }}
Same result π
Just gave these two a try and neither seem to work either.
First one comes back with error "TypeError: unsupported operand type(s) for +: 'NoneType' and 'datetime.timedelta'"
Second comes back with error "ValueError: Template error: as_timestamp got invalid input '01:00:00' when rendering template '{% set LEDOn = states('input_datetime.light_s_on') | as_timestamp %} {% set Length = states('input_number.light_schedule') | float * 60 %} {{ ( LEDOn + Length ) | timestamp_custom("%H:%M:%S", True) }}' but no default was specified"
Gave it another go myself but just cant figre it out at all.. this is such a pain π€£
It doesnt seem to be using the input_datetime as needed
your datetime only has a time
replace the first line with {% set LEDOn = today_at(states('input_datetime.light_s_on')) | as_timestamp %}
Thank you @inner mesa, although still having an issue with this, it has improved for sure, but the time is now 1 hour behind (ive taken away the + 18 hour input nunber), but the input_datetime is not showing as 00:00 if I set it to 1:00, any ideas ?
I'm not following
Original problem here
so ive got an input_datetime to select when the lights will turn on and a input_number for how long the lights are on for, essentially im trying to figure out the time the lights will turn off (if that makes sense?)
you should use the first bit of code provided by mekaneck that uses a datetime object
I don't understand the problem that you described above
but the input_datetime is not showing as 00:00 if I set it to 1:00
using the below;
{% set LEDOn = today_at(states('input_datetime.light_s_on')) | as_timestamp %}
input_datetime is set to 1:00 but the code shows 00:00, so its an hour behind
okay, I think you said the opposite above
sorry.. im confusing myself here too lol... but yes, the code pulls back a value which is an hour behind
what is the input_number set to?
input_number is currently set to 18
{% set LEDOn = today_at(states('input_datetime.light_s_on')) | as_timestamp %}
{% set Length = states('input_number.light_schedule') | float * 60 %}
{{ ( LEDOn + Length ) | timestamp_custom('%H:%M', False) }}
returns 03:18, which, working correctly should be 18:00
why did you add False?
Hmm, didnt see that one, thats now been changed π
Is there a way with a rest sensor to just pass the entire response into the attributes field? I tried
json_attributes:
- "{{ value_json }}"
GitHubs API spits out an array with no Json keys to go off of.
And the problem is that you need to mulitply by 3600
if you specify hours
Nope, it needs to be a dictionary key
Thank you Rob, Appreciate the help! I dont meen to be a pain, still fairly new to HA π
Dang. Not sure how else to get this into the attributes field when it's just a giant list response.
It's that. Can see the example response is just a list
The multiscrape custom integration supports templates in attributes
I think the issue is just wether or not it's possible to dump the rest API response into an attribute. When there's no keys to go off of?
Here's a sample API response
https://dpaste.org/LnWO9
Attributes support lists and dicts. I donβt see why that entire output couldnβt be stored in an attribute, at least with multiscrape. I donβt know the limitations of the rest sensor.
I'll look into it thank you
quick though to y'all smart peeps... when templating an entity_id for a target in a script, if the template returns more than one entity, how do I write the jinja so it doesnt error with invalid entity_ids?
target:
entity_id: >-
{%for entity in (state_attr('media_player.mrp_helper','entity_id'))%}
{%if is_state(('input_boolean.' ~ entity.split('.')[1]),'on')%}
{{entity}}{%endif%}{%endfor%}
[3:19 PM]
above checks if correlating input boolean is on, then returns the id
[3:19 PM]
works in templater, doesnt work in script
[3:20 PM]
thoughts?
oop sorry about the timestamps, I am asking in automations as well
Please do not cross post
fair. i figured i would check here as I didnt get any kind of response in the other chan; sorry
ahh .. on the for line
correct?
or with the entity
wait .. i think I remember reading something somewhere about join?
You can either use a namespace and put the entity_ids in a list and output that.
Or use the group members and create a separate list to check on the input boolean states out of that list
With the second option you don't even need a for loop
Fes, I'll be honest; I'm not that familiar with Jinja. I'm coming from google and VB from about 15 years ago
It's new, and for a dude my age, painful to learn and keep up... but I'm tryin
I'll see what I can do, but I appreciate the pointers from you both
unless you can example me up faster than google, and I can take a gander (I'm good at dissecting, not creating from scratch)
target:
entity_id: >-
{% set ns = namespace(list=[]) %}
{% for entity in (state_attr('media_player.mrp_helper','entity_id')) %}
{% if is_state(('input_boolean.' ~ entity.split('.')[1]),'on') %}
{% set ns.list = ns.list + [entity] %}
{% endif %}
{% endfor %}
{{ ns.list }}
That's option 1
ok ... so defining ns as a list and then adding them. then return the ns
that, I understand
(namespaces are new. Ill have to google up on them)
i wasnt aware you could define them as lists
{% set mp = state_attr('media_player.mrp_helper','entity_id') %}
{% set bool_on = mp | map('replace', 'media_player.', 'input_boolean.') | select('is_state', 'on') | map('replace', 'input_boolean.', 'media_player.') | list %}
{{ mp | select('in', bool_on) | list }}
That should also work
literally just choked on my coffee. holy cow
ahh ok I see what its doing, though
remapping the domain to and from input_boolean
selecting the ones in the list that are on, then exporting as list
dang
I dont think I would have found the 2nd option very easily with google
thanks, Fes. 6 of one, half dozen of the other... I can dig it
Thanks a lot, I'll give it a try
You too
Hello. How could I combine two sensors for the same period of time but 24 hours apart? I have a sensor counting how long my AC ran during the previous day (using History Stats), and I have a different sensor counting how long the AC has run today so far. If itβs only 3PM so far today, I want to compare todayβs usage with yesterdayβs usage up until only 3PM, so I can figure out if Iβm using more or less by the same time of the current day. Iβm not sure if this would end up needing to be an elaborate template sensor, or if something exists built-in like a helper or integration that I may have missed trying. Iβm looking for any suggestions or a direction to go. Thank you.
You need a SQL sensor https://www.home-assistant.io/integrations/sql/#state-of-an-entity-x-time-ago
alright ... one more for ya, Rob or Fes;
entity_id: >-
{% set ib = trigger.entity_id %}
{% set mp = ib | map('replace', 'input_boolean.', 'media_player.') | list %}
{{ mp | list }}
this would, from what I think I understand would replace the 'input_boolean.' with 'media_player.' and then output as a list.
but, it splits the whole thing into seperates:
valid entity IDs: ['i', 'n', 'p', 'u', 't', '_', 'b', 'o', 'o', 'l', 'e', 'a', 'n', ...]
what am I missing, here?
so i've also tried this:
{{ trigger.entity_id | map('replace', 'input_boolean.', 'media_player.') | list }}
same result
Oh, you're iterating over the entity_id from the start...
Why do you want a list of one item?
media player
if you just want to replace the domain, {{ trigger.entity_id|replace('input_boolean', 'media_player') }}
long story short, its for an automation that will only involve one entity at a time
alright, if you say so
{{ [trigger.entity_id|replace('input_boolean', 'media_player')] }}
that's what makes a list
identical results:
{{ ['foo']|replace('foo', 'bar') }}
{{ ['foo'|replace('foo', 'bar')] }}
['bar']
remember how i said that learning new languages is painful??
so jinja basically allows you to turn a string into an array just by adding brackets.
yep. makes sense to me!
smh
it's not turning a string into an array, it's creating a list with the only item being that string
well, true,
the string is unchanged, aside from the replace
there are really only two types of data structures in Jinja - lists and dicts. lists are [xxxx, yyyy] and dicts are {'foo': 'bar'}. That's pretty much it
Much appreciated. I wonder how I've never run across this integration before. Thanks!
Wouldnβt it be easier to use two history_stats sensor and a template sensor?
@torpid mural I converted your message into a file since it's above 15 lines :+1:
@static dune I converted your message into a file since it's above 15 lines :+1:
Unless there is a consistent way to tell apart the true lights from the light strips/light groups (eg. something in the attributes), it may be easier to just explicitly reject them from the list by entity_id.
@static dune Instead of including explicit entity_id's in the template as Daniel suggest, you could create a lights group with all lights you want excluded in it, then exclude all members of that group in the template by adding |rejectattr('entity_id', 'in', expand('light.ledstrips')). Advantage is you wouldn't have to edit the template if something in your setup changes.
Hi All, have a question about templates being new to HA. I have a number of climate entities which I want to create a sensor entities for each. I've played in the Dev tools template part of HA and was able to return something I wanted but now curious how do I create it as an entity I can use? Is it in the configuration yaml?
This is the code I used in the template area in Developer Tools:
friendly_name: Master Bedroom Temperature
unit_of_measurement: 'Β°C'
value_template: "{{ state_attr('climate.master_bedroom', 'current_temperature') }}"
guest_king_temperature:
friendly_name: Guest King Temperature
unit_of_measurement: 'Β°C'
value_template: "{{ state_attr('climate.guest_king', 'current_temperature') }}"```
Yes, you do that in configuration.yaml, unless you've segmented your configuration.yaml into separate files by specifing sensor: !include sensor.yaml in your configuration.yaml -as many people do when their configuration.yaml grows to large-, then you do it in sensor.yaml.
Thanks @torpid mural I prefer the separation route so will create a sensor.yaml!
To save you some time: do leave 2 spaces before every line in that sensors.yaml. And do not repeat the sensor: inside that sensor.yaml file.
Does this look right for the include yaml @torpid mural ?:
master_bedroom_temperature:
friendly_name: Master Bedroom Temperature
unit_of_measurement: 'Β°C'
value_template: "{{ state_attr('climate.master_bedroom', 'current_temperature') }}"
platform: template
guest_king_temperature:
friendly_name: Guest King Temperature
unit_of_measurement: 'Β°C'
value_template: "{{ state_attr('climate.guest_king', 'current_temperature') }}"```
Almost. Do mind the 2 leading spaces. It behaves like you copy-pasted the contents of the sensor.yaml into the configuration.yaml at the position of the include ! statement. i.e. it would need to be indented to be under the sensor: heading. Plus, you never repeat the - platform: template, you just specify more sensors after teh sensors: heading.```
-
platform: template
sensors:
master_bedroom_temperature:
friendly_name: Master Bedroom Temperature
unit_of_measurement: 'Β°C'
value_template: "{{ state_attr('climate.master_bedroom', 'current_temperature') }}"guest_king_temperature:
friendly_name: Guest King Temperature
unit_of_measurement: 'Β°C'
value_template: "{{ state_attr('climate.guest_king', 'current_temperature') }}"```
One more tip, if you want to be able to view, edit, or show history for your new template entities from your front-end, do add a unique_id: attribute to your entities.
@halcyon kindle Good luck, have to go offline now.
This won't work, you are comparing entity_ids. with complete state objects. You can use the entity_id attribute of the group
ok, thanks. Can you give me an example please?
|rejectattr('entity_id', 'in', state_attr('light.ledstrips', 'entity_id'))
Is there a way to make state_attr('light.ledstrips', 'entity_id') return an empty list when light.ledstrips doesn't exist? i.e. make the statement filter out nothing when the group doesn't exist instead of giving an error message?
|rejectattr('entity_id', 'in', state_attr('light.ledstrips', 'entity_id') or []) would this be a correct way of achieving it? (It works when I test it, but does it have any unwanted side effects or something like that?)
I am currently using two different history stats sensors, but I don't see how to take the current day's sensor and subtract it from a partial total of yesterday's sensor. (e.g. 3pm today amount minus (-) the amount from 3pm yesterday (not the total for yesterday).
Anyone have a suggestion for my question on how to create a template sensor that records total hypothetical compensation for energy generated by my solar panels?
What's the formula to calculate the hypothetical compensation?
it's the sum of all compensations over time I would have received had I returned all energy generated by my solar installation into the grid. i.e. it's the running total of all price/kWh * number of kWh generated. I put the names of my sensors in the message that was turned into a text.
Is price/kWh a constant?
To mimic how the energy dashboard records costs and compensations. I would do the same for the total of hypothetical costs of my usage.
It is an input_number at the moment, so it may change over time.
I don't use any energy dashboard stuff in my setup, but it sounds like you want to find an integral. Have you looked into the Riemann Sum Integral integration?
Yes, I know about the Integration integration. This works only if the price is a constant a.f.a.i.k.. What I think I need is however a repetitive calculation of price * usage at time t added to any previous results. This is how the energy dashboard stores the costs and compensations for the actual energy returned to and taken from the grid. If I can get the same information for the total energy produced and total energy consumed, I can calculate the difference between those costs and compensations and it'll show me exactly when I break even plus what the gain/loss is.
Thank you!
Do include the correction given by TheFez though!
At any point in time, you can use a template sensor to calculate price * usage, then integrate over the value of that template sensor?
Though again, I don't have experience with this application.
I'll have an another look. Any further suggestions are still welcome though π
I would personally make it a variable then
{% set reject_list = state_attr('light.some_group', 'entity_id') or [] %}
Assuming you want to calculate the difference at the current time, as opposed to any arbitrary time, it should be possible. The magic isnβt in the template sensor, itβs in the setup of yesterdayβs history_stats sensor
- platform: history_stats
name: Yesterday AC run duration at this time
unique_id: 0a50bbea-73f2-401a-a260-7e9576812e0a
entity_id: binary_sensor.ac_state
state: "on"
type: time
start: "{{ today_at('00:00') - timedelta(days=1) }}"
end: "{{ now() - timedelta(days=1) }}"
if you want yesterdays info, you'd want
start: "{{ today_at('00:00') - timedelta(days=1) }}"
end: "{{ today_at('00:00') }}"
They are looking to compare the on-time of yesterday up to the current time, to today at the current time.
If it is 3 pm, how much longer has the AC been on today compared to the amount it was on yesterday up until 3pm yesterday
So that example was the yesterday sensor, but it canβt be the whole day
The goal would be to look at the "final sensor" at 3PM to see if I'm using more or less cooling than the previous day for the current time. And then again at 4PM let's say or some other time period (like a 3 hour block) if each time period needs to be calculated individually. In a perfect world the sensor would show + or - the number of hours different (since the history stat sensors are in hours) between yesterday and today.
The example I pasted would be the AC on-time from yesterday at midnight until this time yesterday.
The sensor might look like this over time if I was using more AC than the previous day:
12PM value: -0.12h
1PM value: -0.05h
2PM value: 0.11h
3PM value: 0.23h
Yes, you just need a history stats sensor to calculate the usage today, and then a template sensor to subtract the two. It should do exactly as you want, it will continuously calculate the difference
I'm trying to avoid using the total for the previous day. The total at midnight on the previous day will not show me if at 3PM on both days (previous and current) if I'm ahead or behind in similar usage.
Letβs say it is 10:15am right now. The example I pasted will give you a sensor that shows the AC on time from 0:00 yesterday until 10:15 yesterday. And 15 minutes from now, that same sensor will show the AC usage from 0:00 yesterday until 10:30 yesterday
Okay, I now see what you did there. Let me create that and play with it. Thanks for your time and help with this.
Why is that? Does that perform better?
because it's easier to read
ok.
@mighty ledge Thanks again for your automation. It seems to work good. I tried to update to set gas boiler on and off with two automations now. For some reason, they will be triggered, even if they should not. May you take a look at them?
https://paste.debian.net/1292992/ heater on automation
https://paste.debian.net/1292993/ heater off automation
from my understanding, i have made the condition AND and OR - it should not execute now
hm. something seems to be wrong with the changes iΒ΄ve made π But i think iΒ΄ve got it. I had to multiply by -1.
{% if average is not none and temperature is not none and (average - temperature) * -1 >= 2 %} - that does it
you probably want abs(average - temperature) >= 2 instead
ah okay, that returns also a positive ?
Thank you π
but technically its same i think? just better to read?
no, yours won't work if average is larger than temperature
does that matter?
because is just want to check just in one direction
with abs it would check then in both directions for >=2 ?
because that i dont want
ok π
How do I reference a template I specified? I have:
- platform: template
sensors:
all_lights_count:
friendly_name: 'all_lights_count'
icon_template: mdi:lightbulb-group
value_template: "{{ expand('light.all_lights') | selectattr('state','eq','on') | list | count }}"
I defined the group all_lights in groups.yaml. How can I reference this template, specifically to get the count of all lights that are on?
if you defined all_lights in groups.yaml, it won't be called light.all_lights
it would be group.all_lights
what do you mean by "reference"?
are you asking where to put that block of text?
if you want to create a light group, you'll have to use something like light: !include lights.yaml in configuration.yaml and put your group in that yaml. Instead, you can create a Helper > Group > Light group and accomplish the same thing, but it could be more convenient when adding/removing lights from the group since you can do it through the UI instead of yaml.
or that
Yeah, sorry I noticed the group.all_lights but i'm looking to then add them to a card to display the lights currently on. Specifically I'm looking to add the card:
type: custom:mushroom-chips-card
chips:
- type: weather
entity: weather.forecast_home
show_conditions: true
show_temperature: true
- type: entity
entity: lock.lock_frontdoor
- type: entity
entity: lights.all_lights
alignment: center
The group should still work though, right? It just won't have the added "light capabilities".
Provided your template works properly, you should now have a sensor called sensor.all_lights_count. Put that as the entity.
And, technically, you don't need the template sensor (unless you plan on using it for other automation purposes), but you can use a template card as the chip. I have some stuff that I can show you, but it looks like your question is more for #frontend-archived.
Hey guys. I've been trying for several days to get something going. Can somebody give me a hand? I've got some old mechanical ceiling fans. They changed speeds with the old pull chain. The only way that I could figure out how to make them smart was to use a 3 relay switch, to set relay 1 and 2 to be low, set relay 2 and 3 to be medium and all 3 relays to be high. I had to set it up like this, because this is the way the capacitors are wired to the fan motor. That all works like clockwork in my UI. The problem comes with voice control. I only have fan speeds, but not a fan as a whole. I made a fan group of the speeds, but I never figured out how to make it behave as a single fan with different speeds. If somebody could explain how to create a fan out of the speeds, maybe I could get an understanding of how to make a template fan with all of the speeds. When I try to make a template fan with presets, I don't know how to use the correct format to turn it on and off, or how to set the presets.
This would be a job for a script I think. Have the template fan's speed reference an input_number, then have an automation trigger on changes to that input_number that executes the script. In the script, have a dictionary that maps values of the input_number to states of the relays and then set the relay states appropriately.
Something like:
variables:
fan.fan1:
0:
switch.relay1: off
switch.relay2: off
switch.relay3: off
1:
switch.relay1: on
switch relay2: on
switch.relay3: off
...
The script would call switch.turn_on or switch.turn_off based on the combination of entity_id's of the fan, switch and speed. Then in the automation, you would call the script and pass it the appropriate fan, switch and speed values.
I just set mine on "high" and use a fan speed smart switch. I hope that's okay.
The template fan is definitely the way to go, you could use a script to simplify the definition some, but you'd basically just be turning in the percentage values (https://www.home-assistant.io/integrations/fan.template/#converting-from-speeds-to-percentage) into service calls that translates to turning on the appropriate relays.
If you share what you've tried, it'll be easier to guide you in the right direction, though
@median mason I converted your message into a file since it's above 15 lines :+1:
if they show up as switches, daniels method would be the easiest to handle. I can help you with the template, just let me know the relay info.
Hi there! hope you all had a good weekend.
I am having a lamp where you can change the color. To change the color, its a MQTT message where you send a code (between 0 and 15).
I'd like to have a card to select the desired color.
I found custom:rgb-light-card completly serves purposes, and in that card you can call a service/script.
I am able to create a script to call a particular color, but instead of creating 16 scripts I'd like to create 1 script and just parses the payload value in the entity yaml?
Do you know if this is feasible?
Example, instead of having a script.blue and script.white I'd like to have a script.light and when clicking on blue i'd like to send payload '1' and clicking on white sending payload '2'
yes, but you'd need to supply us with a color to value list
That's the color/pattern and payload code
Warm = 0
Cold = 1
Blue = 2
Lagoon = 3
Cyan = 4
Purple = 5
Magenta = 6
Pink = 7
Red = 8
Orange = 9
Green = 10
Pop = 11
Rainbow = 12
Modern = 13
Techno = 14
Horizon= 15
and what service do you use to change the color?
service: script.ccei_light_color
and in there I am publishing to this topic : tild_C4DEE2D4C3B0/u8_w/light_code/info/desired
can you please post that script?
@fierce hawk I converted your message into a file since it's above 15 lines :+1:
service: script.change_mqtt_color
data:
color: green
it will also work via the UI
maybe just to make it a bit more fool proof, use:
selected: >
{{ colors.get(color | lower, 0) }}
oh, and I think the paload should be {{ selected }}, not {{ color }}
yah, there's ways to make it better, the goal was to just have it work with a selector
I edited the paste, if it didn't take via the link then I'll have to post the link again
looks like it didn't take
that looks better!
odd, my old link which is still open in a tab didn't push the changes trhough when I edited it an hour ago
oh, it does, but apparently it changes the link
wtf is the point of editing then....
-1 point for dpaste
not much, it shows the change history
that other site, which changed to being paid, was better in that respect. It even had a party mode you could enable and then everybody with the link could edit it
but I already forgot the url
probably one of the ad driven ones
Thank you! I'll work a little on Daniel's method first and see what I can come up with.
I appreciate the help man! I'll work on this.
I've created my input number with 4 settings, 0 to 3. I'm now making a script that has triggers of the input number changing to specific numbers. I gave each trigger an id, but when I try to make a choose action for the trigger id's, HA says that no triggers have id's set. I saved the script after setting the id's. Is this a bug, or is there something else I'm not doing?
I was able to do the triggered by in yaml.
trigger id's like that can only be used in the automation that created them
also, you don't need input helpers, that's why I was offering to help you with the template
Ok, I've got this below. How would I set up a template fan from this?
fan.dining_room_fan_medium(switch.dining_room_fan_speed_2 and switch.dining_room_fan_speed_3)
fan.dining_room_fan_high(switch.dining_room_fan_speed_1, switch.dining_room_fan_speed_2 and switch.dining_room_fan_speed_3)```
- sensor:
- name: "Battery Charge Only"
unique_id: "battery_charge_only"
unit_of_measurement: "W"
device_class: power
state_class: measurement
state: >-
{% set batterypower = states('sensor.battery_charge_discharge_power') | float %}
{% if batterypower > (0)}
{{ batterypower * 1 }}
{% else %}
{{ 0 }}
{% endif %}
why does my template sensor not work?
i want sensor.battery_charge_only to have the positive values from sensor.battery_charge_discharge_power
{% if batterypower > (0)}
You're missing the closing % in this line
some unnecessary math in there, too π
but if the value goes negative, the if isn't unnecessary
you could replace that whole block with this:
{{ [0, states('sensor.battery_charge_discharge_power')|float(0)]|max }}
what do you mean with set a default for float?
like I just added
can be reduced 1 character if...
{{ max(0, states('sensor.battery_charge_discharge_power')|float(0)) }}
Hello Petro, i actualized the automations for heater on and off. I also added some negated checks at the heater off section. All work, i cant find a problem. Bute may you take a look at it? I am not really sure, if negation (is not) is the right thing at that place.
@buoyant pine I thought you'd laugh at that π€£
oh wow you guys are amazing. why does this work? like max(0, sensor.... does only count values until the max is reached?
if it's negative, then 0 is higher than the negative value
ah it is "take the higher value"
so this clears up why min also works π
i am amazed. really
where is this written down? is there a sheet with all "*math"
There are some links in the channel topic
heater on https://paste.debian.net/1293060/ heater offhttps://paste.debian.net/1293061/
wow also learned where the channel topic is. nice
Not sure what you're asking here. Sorry
You helped me with the automation for heater on π i added now 3 checks - 2, 3 or 5 sensors below specified temperature. i made a second automation if 7 sensors are above specified temperature. to avoid some misleading behaviour, i copied the 3 "heater on" checks negated to heater off automation. if one of these 3 heater on are still used, then automation off should not be fired.
How can I create a list of floats out of a list of TemplateState objects so I can sum the values?
| rejectattr('attributes.device_class', 'undefined')
| selectattr('attributes.device_class', 'eq', 'power')
| rejectattr('attributes.unit_of_measurement', 'undefined')
| selectattr('attributes.unit_of_measurement', 'in', ['W', 'kW'])
| map(attribute='state')
| list()
%}
{{ watts|sum }}```
results in "TypeError: unsupported operand type(s) for +: 'int' and 'str'" because state is of type str, but I can't find how to make it into floats...
Neither one of those is quite right. When I turn it on it goes straight to high and neither low or medium works. Also, the on off button never says on.
Great! thank you. One final follow up question: can I conditionally divide the float value by 1000 if unit_of_measurement eq 'kW'?
| rejectattr('attributes.device_class', 'undefined')
| selectattr('attributes.device_class', 'eq', 'power')
| rejectattr('attributes.unit_of_measurement', 'undefined')
| selectattr('attributes.unit_of_measurement', 'in', ['W', 'kW'])
| rejectattr('entity_id', 'in', area_entities('energie'))
| rejectattr('state', 'in', ['unknown', 'unavailable'])
| map(attribute='state')
| map('float')
| list()
%}{{ "%.2f"|format(watts|sum) }}```
not that I can think of. I would split it up into two sets and unconditionally divide the ones in kWh
OK Thank you
you can collect the everything up to taht check in a variable to avoid repeating yourself
or make a macro
@torpid mural I converted your message into a file since it's above 15 lines :+1:
you could further break some of that out to reduce repetition, but meh
Which state transition doesn't work? Off to speed 1/2/3, speed 1/2/3 to off and/or any speed to any other speed?
Trying to round to nearest 0.5 using round(1, "half", default). but automation will not safe and highlight it red in service: climate.set_temperature data: temperature: "{{ (state_attr('climate.hallway','temperature'))|float|round(1, "half", default)) }}" target: entity_id: climate.hallway
you have an extra )
this also won't save "{{ state_attr('climate.hallway','temperature')|float|round(1, "half", default) }}" it will pass in dev tools.
you have " both inside and out
Sorry what do you mean?
I haven't reviewed the arguments for round, but try round(1, 'half', default)
that
you can't surround the template in " and also use it inside
I see. I'm was just using example from https://www.home-assistant.io/docs/configuration/templating/. I was able to save it now. Thanks
that only has the function call. You have to consider the context in which you're using it
Right. That make sense.
Are your switches momentary switches or do they persist, i.e. when you turn on switch 1 does switch 1 stay on?
Good morning everybody.
I'm now receiving this warning several times, what's wrong?
Thanks
"this warning"
what warning?
Template variable warning: 'homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'last_reset' when rendering '{{ ( as_timestamp( now() ) - as_timestamp( states.sensor.energy_tostadeira_monthly_total.attributes.last_reset ) ) | timestamp_custom("%d") }}'
- platform: template
sensors:
## Dias
monthly_energy_cicle_days_tostadeira:
friendly_name: 'Dias em consumo'
unit_of_measurement: "dias"
value_template: >-
{{ ( as_timestamp( now() ) - as_timestamp( states.sensor.energy_tostadeira_monthly_total.attributes.last_reset ) ) | timestamp_custom("%d") }}
Your template does not work, because there is no attribute last_reset present
And how can I remove the warning? Because the correct value appears in HA
Most probably this occurs after a restart when the sensor is not available
My guess would be, that this attribute is created after the first render attempts. I'd try an availability template.
- platform: template
sensors:
## Dias
monthly_energy_cicle_days_tostadeira:
friendly_name: 'Dias em consumo'
unit_of_measurement: "dias"`
availability_template: "{{ state_attr('sensor.energy_tostadeira_monthly_total', 'last_reset') != none }}"
value_template: >-
{{ ( as_timestamp( now() ) - as_timestamp(state_attr('sensor.energy_tostadeira_monthly_total', 'last_reset')) ) | timestamp_custom("%d") }}```
edit: see below
I would use state_attr()in the value template as well π
I'll try it and let you know if it works.
It may be when it restarts, but sometimes it still takes a while to appear.
I have a template that creates a binary_sensor like this:
- trigger: - platform: state entity_id: binary_sensor.alarm_sensordi0006 to: "on" id: "on" - platform: state entity_id: binary_sensor.alarm_sensordi0003 to: "on" id: "on" binary_sensor: - name: bla_bla state: "{{ trigger.id }}"
instead of repeat all the platrom multiple times, can I add more entity_id in the same platform?
You can use yaml anchors
how?
well, if you're trying to repeat code for different sensors, then you'd use anchors
if you just want mutliple entity_ids in the same trigger going to that single bla_bla sensor, then you'd just list out the sensors in 1 trigger
they are already in one trigger, but in multiple "platform"
in this example I have only 2, but in others I have 4/5, so I want to avoid to retrite platform 4/5 times
right, so just list out the entities
ah, you mean the sensor that can trigger, yes then
list how? under entity_id: comma separated?
or can I add multiple entity_id in the same trigger?
what is your actual goal here
you can add multiple entities in one trigger
- platform: state
entity_id:
- ...1
- ...2
- trigger:
- platform: state
entity_id:
- binary_sensor.alarm_sensordi0006
- binary_sensor.alarm_sensordi0003
to: "on"
id: "on"
binary_sensor:
- name: bla_bla
state: "{{ trigger.id }}"
ah ok, thanks
how can i stringify the actual entity so i can use a regex pipe on it?
they are by default in OR?
triggers are always OR
i can use friendly_name but that regex is more hard for me to obtain hehe
print the sensor.blabla@xxx@bla so i can regex xxx
from what? you have to give more context here
sensor.tgtg_backwerk_amersfoort_verrassingspakket
yes, that's an entity_id
ok, that is a string π
and that's already a string
which part of it is "the shop"
as it is Dutch, my guess is he want's to have backwerk
I have two set of keys and want to use a BLE tracker for each set but if one set goes away I want it to be reflected under a single entity I can use with user presence. Today I have my iPhone with the iOS companion but the ble keys are a fall back if the app stops working. Could I use a template to create a single entity to be used in the user's devices page for my user?
tgtg_{shop}_{city)_{box type}
surprise package
Can I create a device_tracker entity using templates?
what's a suprise package π€£
well, shops can make boxes with stuff they can't sell otherwise, and then sell it as a surprise package
like bakery which will put 3 breads, 6 donuts, and a package of cookies in a bag and then sell it for 10 euros as a surprise package
you can make an automation that uses device_tracker.see to update a device tracker, not sure if it will create one from scratch
backwerk is actually a bakery
I would assume it does create one from scratch
Hmm. ok. let me try that.
I don't know why we don't have a template device_tracker integration
I'd wager that this service does it?
I was hoping you did but the service would create the device_tracker entity but does it "live" across restarts?
as a sidebar, worse case you can create a template sensor that has lat/lon attributes that essentialy works like a device_tracker when paired with a person
@acoustic arch
Guess this should work {{ 'sensor.tgtg_{shop}_{city)_{box type}'.split('_')[1] }}
im back. You can buy for a couple of euros a suprise bag worth around 15euros of stuff almost over date
I am just trying to determine if at least one set of keys is gone so it triggers the automation I have of home = 0
just plop the sensor on a person in the person UI area
backwerk is the shop yes
mmmm. not sure how this works. I trying to dynamicly TTS the shopname only, when im home
@mighty ledge that works but if one set is home and one is gone it sets the user home. I was tired of swapping BLE track across keys so got a second one.
example:
{{ "sensor.tgtg_boni_amersfoort_magic_box" | regex_findall_index('(?<=\_)(.*?)(?=\_)') }}
but the first part would be the trigger_entity name? havent looked at it yet
You are asking a very specific question. To know how to do this, we need to know more context. But I already said that
yes, if you trigger on that sensor changing state, you can get that from the trigger variables
thats great to hear. a lead to the solution
im farming the forum, regex sites and you guys atm lol
But your regex thing returns the same as my split solution
not sure why you need regex at all tbh
split and remove what you don't want and then combine using spaces
it'll be faster than regex
Well, I provided something, which you dismissed as mmmm. not sure how this works.
but it splits the entity_id on the _ and then takes the 2nd part
because im not sure how to proceed with that solution in an automation
the same as with your regex solution
post the automation...
it doesnt exist yet
i only have the non TTS version going. But once home i want the TTS version. Saves me picking up the phone because it makes a sound π
it does become a bit more complicated if the shop has more than one word though
or if the trigger doesn't have the entity_id key
like bakery on the corner
bakkerij op de hoek
friendly_name: TGTG Bakkerij Groenendijk - Euterpeplein, Amersfoort (Verrassingspakket)
like this one
remove TGTG, select until -
yes
It's the name of the app (Too Good To Go)
TooGoodToGo
if you use the friendly name regex_findall("TGTG ([a-zA-Z ]+) - ")
or
regex_findall("TGTG (.*) - ")
both seem to work (I have the same integration installed)
Yeah, the .* is like a "greedy find everything"
so it's saying find everything between TGTG and -
the [a-zA-Z ] will only find letters and spaces, so it might not work if you have those fancy letters in your names of things
the result of the findall will be the name
{{ "TGTG Bakkerij Groenendijk - Euterpeplein, Amersfoort (Verrassingspakket)" | regex_findall("TGTG (.*) - ") | first | default }}
So assuming you are using a state trigger @acoustic arch you can use trigger.to_state.attributes.friendly_name | regex_findall("TGTG (.*) - ")
maybe even trigger.to_state.name | regex_findall("TGTG (.*) - ")
{{state_attr('sensor.tgtg_bakkerij_groenendijk_euterpeplein_amersfoort_brood_box', 'friendly_name') | regex_findall("TGTG (.*) - ")}}
this gives me ['Bakkerij Groenendijk']
and {{ state_attr('sensor.tgtg_bakkerij_groenendijk_euterpeplein_amersfoort_brood_box', 'friendly_name') | regex_findall("TGTG (.*) - ") | first | default }} gives me Bakkerij Groenendijk
so without ['']
which for TTS is what i want
so yes. this is correct
i think i have all the pieces to make this TTS automation work
thanks a lot. you guys are gold
im gonna try building the TTS automation
@sudden wraith I converted your message into a file since it's above 15 lines :+1:
@sudden wraith @marble jackal created a macro that does those calculations for you if you're interested.
It can do a lot more than just return the cheapest hour. If your dishwasher has a 3 hour program for example, it can find the cheapest consecutive block of 3 hours.
And if you have a power sensor, you can even find the best start time based on the power usage of a previous run.
Oh, that's exactly the thing I wanted.
I was just experimenting with cheapest hour first because I don't know jinja at all.
Sounds like we think alike, because next step for me was to measure power draw to see when it makes the most sense. π
You just made my life a lot easier π
Anyone have the template for 'tomorrow' ? eg 2023-09-27
(now() + timedelta(days=1)).date()
thanks π
im having a hard time implimenting a conditional statement to this template sensor, what am I missing?
@karmic sapphire I converted your message into a file since it's above 15 lines :+1:
conditions aren't supported there
That's not a thing... add the condition to the template
attributes:
changes: >
{% set current = this.attributes.get('changes', {}) %}
{% if is_states('input_boolean.server_boot_complete'. 'on') %}
{% set new = {trigger.entity_id: trigger.to_state.last_changed.isoformat()} %}
{{ dict(current, **new) }}
{% else %}{{ current }}{% endif %}
I've had a feature request open for that for quite a while
ah thank you!
oooooooooooooooooooh contraire, new action field allows conditions!
No clue if it stops the state from updating, been on my list to look at
I woudl assume it does
not supported there, where they had it
and this part is a critical piece:
No clue if it stops the state from updating, been on my list to look at
Yes it is
I wouldn't expect a condition failing in the action to stop the state from being updated, just to stop execution of further steps in the action
π€·ββοΈ I think of it in terms of returned data from service calls
no returned data, it wouldn't update
depends on the intention of the OP for that condition
alanporter would know better, he made the change
the way the docs read, it sounds like you're just providing data that you can use in the state, but it doesn't have any direct effect on the state
action list (optional)
Define actions to be executed when the trigger fires. Optional. Variables set by the action script are available when evaluating entity templates. This can be used to interact with anything via services, in particular services with response data. See action documentation.
π€·ββοΈ
I think TheFes tested conditons in the action block during beta, but they had no effect on the sensor update...
@marble jackal ^?
You could grab the state from the current sensor without it being a circular reference.
and essentially treat it like "no update"
good evening. i have a shot question for which i didnt find an answer: if i have a numeric state at an automation set to below 17. what will happen if outside temperature goes to -1?
- condition: numeric_state
entity_id: sensor.outdoor_temperature
below: 17
or does this better work?
- condition: numeric_state
entity_id: sensor.outdoor_temperature
above: -20
below: 17
@thorn harness that is a question for #automations-archived
ok π
@haughty breach @mighty ledge the condition in that example had an effect on the state, as I was setting a variable used in the state template after the condition. But the state template was rendered on each trigger
Thanks
Oh you just posted that π€£
I just got back from a meeting and though you posted that an hour ago
No, I didn't notice your ping before
Was translating some intents to Dutch π
But I also tested if variables from the action part could be used in the availability template during the beta
That wasn't the case then, but it was changed somewhere after my tests
Sounds intense
Hello
I'm struggling a little bit with a template from a multiscrape output.
Any chance of getting some help?
I'm managed to get the data and to truncate it, but now the value I want is at the end of my string....and the quesiton is how do I extract that.....?
Long story short - I get a blob from a multiscrape fetch....and then I do this to it:
value_template: '{{ value.split(","conditions":")[0]}}'
Which gives me this:
jQuery22409170868888429933_1695760092404({"build_code":"005-s1-bt0.bwa0.bwg0.bwd0.bpop0.bst0-m0","client":{"base_url":"https://s3.amazonaws.com/tempest.cdn/assets/better-forecast/v9/"},"current_conditions":{"air_density":1.23,"air_temperature":7.0,"brightness":14478
What I want is the "14478" off the end.....but...this can be any number so it is not fixed length....I must basically take everything from the right up to, but not including the ":"
This seems like a simple problem but I am a little stumped.
π¦
it looks like you're trying to manually parse JSON π
I don't know what the %7D and %7B are there, but you should try {{ value_json.brightness }}
oh, I see - that's { }
what a mess.
That seems simple.....
it looks like it's URL-encoded JSON
How do I formnat that into value_template: ?
like I showed you
ok, that's a giant block of JSON
value_template: '{{ value_json.brightness }}'
Yes...it is mega ugly.....
you just need to pretty-print the JSON (any online formatter can do it) and it will be more clear
So if I do it simple as above, the log gives me:
Template variable error: 'value_json' is undefined when rendering '{{ value_json.brightness }}'
You need to set value_json with your JSON at the beginning of template
OK...conceptually yes - tell it you have json, then tell it to parse and extract the tag value i want
This is my multipscrape yaml:
- name: Tempest Scraper
resource: https://swd.weatherflow.com/swd/rest/better_forecast?callback=jQuery22409170868888429933_1695760092404&api_key=a8f5dbda-af0a-4b57-99b9-f10baa88f27b&build=76&lat=-41.17002&lon=174.83538&station_id=34978&units_temp=c&units_wind=kph&units_pressure=hpa&units_distance=km&units_precip=mm&units_other=metric&units_direction=kph&_=1695760092405
scan_interval: 120
log_response: true
timeout: 20
sensor:
- unique_id: public_light_level
name: 'Public Light Level (lux)'
#state_class: measurement
value_template: "{{ value_json.brightness }}"
#unit_of_measurement: 'lux'
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.
Maybe that custom component doesn't accept value_json but just value
Maybe....using value on it's own doesn't work (Template variable warning: 'str object' has no attribute 'brightness' when rendering '{{ value.brightness }}')
According to this (https://github.com/danieldotnl/ha-multiscrape/issues/234) it should work
Hmmm....maybe harder.....
They seem to have a multiscrape section and then some sort of extra sensor section...thought it is unclear to me how these releate to each other....
It's not proper json.....I can't even prettify it....it's actually multiple bits smushed together.....
So on that basis a simnple json_value will not work.....so back to text extracttion.....
So sad....
Why not split the string again on : then index the last item [-1]?
value_template: '{{ value.split(",\"conditions\":")[0].split(":")[-1]}}'
That worked!
I'm so excited I just about wet myself!
Sometimes string manipulation is just simpler π
Yes!
I'm so stoked! At least I can stop my lights from going bananas now.....
Now I need to find a few more data sources, and then aggregate them somehow...but that's a separate problem!
Just be aware that if for some reason the format of your result doesn't remain consistent (eg. If ,"conditions": somehow appears before :14478 sometimes), the above would not work.
if you remove the whole callback=jQuery... (up through the & right before the API key) you get back actual JSON, which you could probably put through |from_json in the template, and then you could do .current_conditions.brightness off of the output of that, I think
that callback is for jsonp (https://en.wikipedia.org/wiki/JSONP) which luckily isn't used much anymore but some stuff still supports it. Luckily, that API supports not using it, which should make your life easier π
Iβm just following along for fun, but you are absolutely correct. How did you know that API supported not using jsonp?
The following works as expected:
- name: Tempest Scraper
resource: https://swd.weatherflow.com/swd/rest/better_forecast?api_key=a8f5dbda-af0a-4b57-99b9-f10baa88f27b&build=76&lat=-41.17002&lon=174.83538&station_id=34978&units_temp=c&units_wind=kph&units_pressure=hpa&units_distance=km&units_precip=mm&units_other=metric&units_direction=kph&_=1695760092405
scan_interval: 120
log_response: true
timeout: 20
sensor:
- unique_id: public_light_level
name: 'Public Light Level (lux)'
state_class: measurement
value_template: "{{ value_json.current_conditions.brightness }}"
unit_of_measurement: 'lux'
@silent grove it is definitely preferred to make the output actual JSON, then index into it with keys. You should also consider getting a new api_key heh.
Oh....that is super sexy.....and they both work so now I have two methods....I'm sure I will find other things to scrape in the future where both of these will be used again!
Thsanks for your help everyone - much appreciated!
Heh, I didn't know it supported it, just tried removing the argument and it worked, so I figured I'd pass it along here π
Can anybody tell me why the first template is false here???
is it supposed to be fan_helper or helper_fan?
it's supposed to be that. Did you notice the 2nd template?
I noticed that one line has fan_helper_2, the other has helper_fan_2
Oh damn! I must be really tired!
I looked at that for several minutes and didn't see it...smh
Hi all... I have an MQTT binary sensor that needs to get its state from two different MQTT topics, is this possible? Thanks π
make a template sensor from 2 mqtt sensors
thanks for the reply... so the template sensor can get its state from multiple MQTT binary sensors?
yes
you can even make a binary_sensor group
without needing a template binary_sensor
ah, ok... I did see something about binary_sensor group when I was searching for an answer, I will check into that, thanks
Hi folks, I see we can now do templates in UI and I was wondering if to set an attributed for a sensor using templates in UI is done with Jinja2 ?
I'm looking to move this:
template:
- sensor:
- name: yellow_bin_days
state: >-
{{ min(((state_attr('calendar.recycling_collection','start_time') | as_timestamp - today_at('00:00') | as_timestamp) /86400) | int,2) }}
attributes:
days: >-
{{ ((state_attr('calendar.recycling_collection','start_time') | as_timestamp - today_at('00:00') | as_timestamp) /86400) | int}}
No, attributes cannot be set up using the UI.
I just read the changelog. My bad, should have read the fking manual properly π
Other more advanced fields, like attributes, are unavailable from the UI. You will still have to set those up in YAML.
I can't seem to get the attribute to work:
- platform: state
entity_id: sensor.home_switch_action
not_from:
- unavailable
- unknown
- none
- ""
sensor:
- name: Home Switch
icon: hue:button
state: >
{% set action = states('sensor.home_switch_action') %}
{{ trigger.from_state.state if action == "" else action }}
attributes:
last_triggered: '{{ trigger.event.time_fired }}'```
is there a way to show the last triggered as the last time the state changed but not_from: unavailable, unknown, none and ""
as there is no 'time_fired' for the sensor sensor.home_switch_action
is last_triggered: '{{ now() }}' what you're looking for?
I think it is! thank you π
I'm trying to build a url_path for a tap_action on a config-template-card, but seem to be running into a wall. The syntax
http://example.com:9925/recipe/{{ states('sensor.mealie_todays_meal').lower()|replace(' ','-') }}
is working for me in a markdown card, but when I try to move it over to the url_path in the config-template-card it chokes and rather than going to the intended site, it opens the same dashboard in HA with that URL appended and without resolving the value of sensor.mealie_todays_meal.
Can anybody point me in the right direction? I've been beating my head against this for a day or so and just haven't had any luck.
I don't use that card, but it looks like it uses JavaScript for templating and not Jinja.
...it's right there. Right in the first sentence of the Github.
I quit, I'm gonna go back to thinking Google Home is the best smarthome ever.
Thanks @rose scroll XD
Haha...but you're not far from making it work! Just need some translating to JS.
lol that's easier said than done for me, but at least I have a basis for google-fu
Or if you like Jinja, just set up a template sensor that takes that template as it's state and then reference that template sensor's state in your custom template card.
That'll allow you to render the url in Jinja and use minimal JS.
It worked! Thank you!
hmm trying to convert bytes to Gb
{{ ((float(states('sensor.routerdevice_b_received')) / 1000000000) | round(2)) }}
gives a very low value of 0.09 while it should be more near 4 GB ?
Hello everyone, i'm veeery new to HA, i'm using AirCon extension to control an air conditioner, and some of the AC commands are not available in the HA UI, like "quiet mode", the extension and HA are using MQTT, how can I customise the HA UI to integrate additional functions ? i tried adding a custom climate section to the configuration.yaml with the same name as the device but it creates a second device...hiiints ? TY
what is the AirCon extension?
deiger/aircon on github
since quiet mode isn't part of the mqtt climate entity its best to incorporate it as an additional switch under the same device
Can you please point me to some yaml doing something similar ? I can code but Iβm very unfamiliar with this environment
do you have yaml that shows how to turn on quiet mode?
Hi all. I have a problem since the last update 2023.9.3 in one of my template. I have the follwing error "state_attr is not defined". Do you have the same problem ? Below the code which was working before :
let input = states[variables.retain] === undefined || states[variables.retain].state === 'unavailable' ? time(Date.now() - Date.parse(state_attr[script.set_values_when_chlrore_pressed].last_triggered)) : time(Date.now() - Date.parse(states[variables.retain].state)), unit = ' '; return circle(state, input, unit);
seems like you just need to call to the device on it's command topic with the property and the value
t_fan_mute
I think it's up to you to figure out what topic it goes to as the docs don't cover it
oh nm, they are listed shittily in those docs
{mqtt_topic}/{property_name}/command
{mqtt_topic}/{property_name}/status
So you should be able to make an MQTT switch out of that
weird that it doesnt get discovered already since its supported by the script
I didn't look but I would expect it to be automatically made into a switch, so yeah it is weird
how do i add a series of input numbers, have a piece of yaml 5 input number fields
it's basically an on/off toggle
can i add it in yaml
state_attr typically isn't available in JS templates.
what custom card is that?
hm but it's strage as it was working yesterday. It's a custom:button-card
then that's impossible
So I will get the value before the JS template
custom button card has never had state_attr
unless that's something new in the 4.0 version
attributes are accessed states['entity_id'].attributes.<attribute>
well in the custom button card I check the attribute of an input select
- type: custom:button-card entity: input_select.chlore_state name: Chlore triggers_update: input_select.chlore_state template: - base_task - icon_pool - circle
tehre's alot of other issues i'm noticing with that template as well
Are you sure the script just alwasy did the 'else' statement in that?
JS will not resolve code in if statements if it doesn't go that path
meaning you can have syntax errors and it won't know until it runs that 'limb'
I see. Ok I will use a different method to input the correct value in my JS template
let input = states[variables.retain] === undefined || states[variables.retain].state === 'unavailable'
? time(Date.now() - Date.parse(states['script.set_values_when_chlrore_pressed'].attributes.last_triggered))
: time(Date.now() - Date.parse(states[variables.retain].state)),
unit = ' ';
return circle(state, input, unit);
It works. Thx a lot
not sure what you mean here
no got it, wanted to add a few input_numbers , can be done in configuration.yaml ty
copy / paste π
kib/sec to gb = / 1000000000
I'm trying to save a video as part of an automation. If I check my logs I get a "Can't write motion_detect_video/garage1.mp4, no access to path!" error. Any ideas? Doing a google there seems to be some very old information about whitelisting directories but I can't see where to put this in the configuration.yaml file.
actually I changed to an existing folder config/www/videos
that would just be /local/videos
Hello, is there any way to create a log list of who closed or opened the garage door and when? I currently have a template created in homeassistant that turns on the relay in half a second to open the gate. Unfortunately, when I enter the gate entity created in the template, it does not show me who opened or closed it. And I write that the gate was opened by state 1...
Hello, I was wondering it is possible to have a template that if the Value is above 1.00 for 5 min, then it becomes True? below what I have so far
{{ states('sensor.pressure_1')|float > 1.00 or states('sensor.pressure_2')|float > 1.00 }}
<was about to say...>
I would create a trigger-based template binary_sensor for each with a numeric_state state trigger and a for: "00:05:00 block
then use the states of those template binary_sensors
Thanks @inner mesa I will give it a go
even easier:
template:
- binary_sensor:
- name: "Pressure 1 High"
state: "{{ states('sensor.pressure_1')|float > 1.00 }}"
delay_on: "00:05:00"
- name: "Pressure 2 High"
state: "{{ states('sensor.pressure_2')|float > 1.00 }}"
delay_on: "00:05"00"
is there a preferred way to set a template sensor as "unknown" ?
via a template preferably
yes I meant what do I set it to
Do you really mean unknown or unavailable?
I specifically want unknown rather than unavailable
You can set it to whatever you want to if the sensor class allows
this would be for a temperature device class
perfect, that works. I set it to render to none and dev tools > states is now showing it as unknown
thank you
I only just saw this ( Thanks RobC), in the mean time I came up with this as I wanted in one Sensor overall
{{ states('sensor.pressure_1')|float > 1.00 delay_on: "00:02:00" }} or {{ states('sensor.pressure_2')|float > 1.00 delay_on: "00:02:00" }}
Getting >> TemplateSyntaxError: expected token 'end of print statement', got 'delay_on'
might just have to stick with what you come up with @inner mesa
yeah, that's quite the mishmash of stuff
you can still combine into one sensor, e.g. :
template:
- binary_sensor:
- name: "Pressure 1 or 2 High"
state: >
{{ states('sensor.pressure_1')|float > 1.00
or states('sensor.pressure_2')|float > 1.00 }}
delay_on: "00:05:00"
When 2023.9 dropped, I created a Template binary sensor - It works but I don't seem to be able to find a way to actually view the template I used. Any ideas ?
created it in the UI?
yes
yes. thats where I created it but how do I view the template I created it with ?
you want to change/view the template you used for that sensor?
yes, just view at this point
perfect, thats what I was looking for - thanks
you can also click the cog icon and go to template options
ah yeah, i see it now. I think my initial problem was that the helper I first looked at wasn't actually based on a template π user error !
That would make things difficult
In my defence <grin> I'd created an automation (which did include a template) which toggled a binary sensor (and that's the helper I was trying to understand)
Any idea what's happening here. I'm getting this API response which means somehow the template is in the rest string this worked until now with a different end point but same template
{'message': 'Invalid stack identifier route variable', 'details': 'strconv.Atoi: parsing "{{ states.sensor.portainer_stack_list.attributes[\'data\'] | select(\'search\',\'zwave\') | map(attribute=\'id\') | first }}": invalid syntax'}
rest sensor resource
https://192.168.4.46:9443/api/stacks/{{ states.sensor.portainer_stack_list.attributes['data'] | select('search','zwave') | map(attribute='id') | first }}/images_status"
I guess somehow I have been using resource with a template but I actually should have been using resource_template. Fixed my issue.
@solemn ore I converted your message into a file since it's above 15 lines :+1:
@solemn ore expand "expands" groups into their grouped entities.
That makes sense! Doh!
Iβve managed to get it to list all of the entities now, just trying to work out filtering on the light domain and then thatβs all good! Thanks for clearing that up. I think I looked at so much documentation it didnβt quite register!
You can avoid using expand
{{ area_entities('your area') | select('is_state', 'on') | select('search', '^light.') | list }}
That should include the group as well
Legend! Thank you, the search test was exactly what I was looking for!
@tight thicket I converted your message into a file since it's above 15 lines :+1:
is there to make that if the state of this trigger sensor is "unknown" that it shows 0? that way the second trigger kicks in? https://hastebin.com/share/oyinapovef.java
this sensor used to work but the last 2 days it has been showing 'unknown'
Why not just remove unknown from not_from? It seems like your variable available in the state: template will handle the unknown state for you.
What is making sensor.outside_home_feels_like_temperature go to unknown?
no idea - it hasn't gone unknown - it just went to that when restarting HA
its it because states('sensor.outside_min_temp') | is_number isnt a number?
@sacred sparrow -- is not a number is a float?
@languid pendant I converted your message into a file since it's above 15 lines :+1:
https://www.home-assistant.io/integrations/script/#variables Its not defined in the script
I dont think need to define a default; it should pass the variable regardless
even with the variable declared and a default given, the error is still the same
I linked the wrong section, intended to link to fields, but here's an example that shows both sides of it: https://www.home-assistant.io/integrations/script/#passing-variables-to-scripts, you don't need a variables map in the service call, it's directly in data
I dont think I worded it correctly; the variable, 'ac_alarm' needs to be sent to the script with data: variables: ac_alarm: 'this is the variable' ... then the script uses that ac_alarm variable content ... the problem is that the script reports that the variable has not been defined, when it is.
specific err is : Template variable warning: 'ac_alarm' is undefined when rendering '{{ ['media_player.'~ac_alarm~'_kodi_mini'] }}
so the script isnt accepting the variable, even though it was presented
I'm saying that it should be called like this
service: script.ac_on
data:
ac_alarm: room
hrm
strange. it works, but im not sure i understand why. I have another script that works, that I put variables: xxx: yyy in and it still works
but this one is not
inconsistent... head scratcher
thanks though
In your other script, that should work as long as you reference those variables as variables.xxx
strangely enough, I dont, which is why I was having a hard time
If it is inside the script, you define variables with the variables: block. If you call a script via a service, you pass variables into that script with the data: block
hi. what's the right way to test if the sun is below the horizon and it's at some point between the sunset and 3 am, i.e. I want the template to reject the morning times of darkness. Is there an easy way to achieve this?
There is no easy way to retrieve the previous sunset, but you could check if the sun is below the horizon and if it's like between 15:00 and 03:00
Which can be done with two separate conditions without the need for templates
My real trigger is more complicated so I'd rather have a template if poss -- my problem right now that if I test now()<today_at("3:00") it doesn't do the evening
With a template it would be something like
{{ is_state('sun.sun', 'below_horizon') and not today_at('03:00') < now() < today_at('15:00') }}
aha negating -- that's smart instead of going crazy with ors
Not so crazy
{{ is_state('sun.sun', 'below_horizon') and (now() < today_at('03:00') or now() > today_at('15:00')) }}
Is there a more efficient way of getting the friendly name of a bunch of sensors than this
{{ expand(states.sensor) | select('search','stack_image_status') | selectattr('state','eq','outdated') | list }}
Also from that how would I get the friendly name when the template output is this
https://dpaste.org/tYAWy
having some trouble ...trying to do this simple equation (| x - y |) / ((x - y) / 2)) * 100
where x is sensor.x and y is sensor.y
any help is appreciated
what did you try?
im getting nothing π i think the ( ) is making me confused
tried nothing?
yes ive tried just putting the sensor data there but im not sure if using int or float is the way to go? im far from an expert at this π₯Ί
What is that supposed to do, exactly? Because to me it looks like that's going to result in
- divide-by-zero error if
x==y - -200 if
x<y - 200 if
x>y
trying to do % difference between sensor.x and sensor.y
And - looking at the || which I assume you're shorthanding abs() as - you don't care which is higher?
You don't need to expand states.sensor, it already contains the full state objects. And you can use map() to list the names
Isn't that just calculated with (x - y) / y
Hi π! Is there a bitwise right shift or some equivalent to struct.pack available in Jinja?
I've never heard of a bitwise right shift operation before...interesting concept. What are you using it for?
I believe in HA templates, struct.pack is possibly directly available: https://www.home-assistant.io/docs/configuration/templating/#functions-and-filters-to-process-raw-data
Thanks! @rose scroll I want to deconstruct an integer to have a list of bytes (integers 0-255 in this case). So eg. [(num & 0xffff) >> 8, num & 0xff]
Goodmorning, I'm struggling with adding a template in the service part of an automation.
In the first part of the automation I write entries into an input_text with a template, which works well.
Then I try to call a service input_boolean.turn_on, but only when the input_text is filled.
{% if is_state('input_text.battery_notification_text', '') %}
input_boolean.turn_off
target:
entity_id: input_boolean.battery_notification
{% else %}
input_boolean.turn_on
target:
entity_id: input_boolean.battery_notification
{% endif %}```
I tried different spacings but to no avail yet.
Is this use within this service not allowed perhaps?
-- edit -- just changed it to service_template, but still an error stating Template rendered invalid service
You should only template the service call itself, not the service data
Ha. Thanks for answering, I was just going to try that.
And service_template has been depreciated for years now, you can just use service
{% if is_state('input_text.battery_notification_text', '') %}
input_boolean.turn_off
{% else %}
input_boolean.turn_on
{% endif %}
target:
entity_id: input_boolean.battery_notification```
Ah ok, I removed all template statements from data in my old code, but saw template being used somehwere on the forum so I thought I should try. I will remove it again.
Indentation looks off, target: should be indented the same as service:
Yes that works! Thanks a lot. Have been struggling for a few hours now.
Is it possible to create a timer entity that sets its duration based on the state of an input_number?
The docs say:yaml timer: test: duration: "00:00:30" so I'm wondering if something like this will work: yaml timer: test: duration: '{{states.input_number.test.state | int }}'
The goal is to be able to adjust the duration of the timer via the frontend but be able to use a slider.
use
alternatively, you can
duration: >
{{states(input_number.test) | int }}
No, as shown in the docs, the duration must be an integer or "HH:MM:SS".
Unfortunately, duration wants to be in "HH:MM" or "HH:MM:SS" format. Trying this but not working yaml {{ "'00:" + states("input_number.test_timer_duration") + "'" }}
I don't think that is templatable at all.
Currently, you can alter duration via script with a templated value after the entity is set up.
@haughty breach you can also specify a digit. It does not 'have' to be in that format. 00:01:00 -or- 60
Yes, I said above you can use an integer...
for seconds
IIRC the configured duration will set the max for what you can set it to via script
It does. That's the error that I'm getting when checking yaml.
@slate fossil -- youre not templating that correctly. use
{{ states('input_number.test_timer_duration')|int }}
That is a valid form of template
single quotes.
states.foo.state gives you the same as states("foo") , with some subtle differences. the latter is encouraged, but the former is not incorrect.
I got that. That didn't work. Working past that now. The bigger issue is probably like karwosts said and the duration is not templatable.
@slate fossil
duration:
minutes: >-
{{ states(trigger.entity_id | replace('input_boolean.','input_number.'))|int }}
this is taken directly from one of my automations.
That's an automation. I'm trying to make an entity.
Probably safe to say duration is not templatable for the entity. This yaml timer: test_timer: duration: > {{'00:01'}} name: "Test Timer" icon: mdi:timer restore: truereturns Invalid config for [timer]: offset {{ '00:01' }} should be format 'HH:MM', 'HH:MM:SS' or 'HH:MM:SS.F' for dictionary value @ data['timer']['test_timer']['duration']. Got "{{'00:01'}}\n".
oh. youre putting it in a config? yeah I dont think you can template config yaml at all
perhaps not as a timer:, but I wonder if I can put it in template: with a trigger / platform: state π€
which, to be honest -- is unfortunate. I'd love to be able to template my configs for my alarm clock package. have it dynamically create the entities based on helper memberships
Yeah. That's kind of what I'm trying to go for.
I get it. I've searched high and low. The only way I found a way to get it that way is to make a 'template' and put it in the templater in dev tools to make it spit out the yaml
if you can figure out the template: idea, please share. I'd buy you a beer for that one lol
that's not gonna work at all
is this not more or less what you want, or am I understanding this wrong?
https://community.home-assistant.io/t/dynamic-timer-with-input-number/516826
I created a template: that stores the last_changed values of certain entities and it survives restarting.
You need to set the timer using a service call
Okay. I see what they did there. Instead of trying to force the duration within the entity, the automation sets it upon triggering. That could work just as good.
Then you can use your template
Added duration: to timer.start in my automation. yaml service: timer.start data: duration: "{{ states.input_number.test_timer_duration.state | int(0) * 60 }}" target: entity_id: timer.automation_auto_office_lightsNow, I can use a slider to adjust the duration. The time remaining appears on the custom:button-card on my dashboard and actually counts down in real-time.#frontend-archived message
FYI I think there's some plan to eventually remove duration from timer.start
I don't quite understand what state that's in but it seemed contentious
I'm confused. How would the duration of a timer end up being set?
then how the heck would you set the duration at all? seems silly
you can use
data:
duration:
minutes: "{{ states.input_number.test_timer_duration.state | int }}"
for this
duration will accept seconds, minutes, hours
Yeah. I was just thinking about that figuring it would work but, I believe the default is in seconds so I just let the template do some math and save a line.
touche. yes, default is seconds. It'll even accept milliseconds. I have to use that for my announcements script
ope. maybe. I might be wrong. I am using -delay in the script
believe you need to use timer.change
that'd be a pain IMO ... just adds more lines to stuff
Do you mean they're talking about removing the duration from the timer.start service call, and not the actual entity?
Yes, no duration in timer.start service.
I sure hope that someone has some sense and 'votes that off the island' Good Idea Fairies'... I tell ya.
ugh. this is an awful idea.
actually I can't tell. that might have been walked back or partially walked back, I can't find the thread
Looks like that appears in a beta but was reverted. https://github.com/home-assistant/core/pull/99613
I imagine a change like that would break a lot of stuff...
so maybe don't worry about it for now.
+1 @slate fossil ... but I'm hopin I shouldnt have to worry about it ever
Even still, I'd imagine a change that drastic would take years to actually come to fruition so that users would have time to accommodate
6 months is the deprecation time.
Kind of makes me wonder what would be next. Removing, for example, color_temp from light.turn_on and have to rely on a light.change service?
I'm trying to wrap my head around your cheapest-energy-hours macro @marble jackal, but I'm not entirely sure how to use it. What I want is, when event happens, I want to pick the cheapest three hours before 14:00 the next day, and then have it start my device then. Are there any examples that could help with that?
That's been reversed
That was supposed to be part of 2023.8, but has been completely reversed
Temporarily, or permanently?
Permanently
cool, thanks for the update.
Shew.
