#templates-archived
1 messages Β· Page 58 of 1
do you get a value if you put this into developer-tools/template?
{{ state_attr('air_quality.laseregg_air_quality', 'Carbon_dioxide') }}
that's a good first step
omg, got it, i capitolized "C" in Carbon_dioxide because that is what it read on the attributes panel
lower case "c" worked
-> States tells you what it really is
can someone briefly explain why i needed to add "template" after the - platform line?
the original recommendation from Github convo was:
in Sensors.yaml
sensors:
sensedge_co2:
value_template: "{{ state_attr('air_quality.sensedge_air_quality', 'carbon_dioxide') }}"
device_class: carbon_dioxide
unit_of_measurement: ppm```
but that did not work for me
I just don't understand the difference in approach and how I got it to work
I'm trying to actually learn, not just make things work... which is new to me π
which?, learning, or not just mking things work?
learning... i usually am just satisfied making things work, following other people's content - but i'd like to understand what i'm actually doing here
I can dig it.
I think the answer to your question might be right in front of your nose, though - (YOU are the one creating the (templated) sensor, not loading the sensor from an integration/addon)
please use triple backticks when posting code for formatting
had to google that
sorry, still trying to figure that out
no problem
FYI what you have there is the legacy format. and you need platform: template because that's what the syntax requires:
https://www.home-assistant.io/integrations/template/#legacy-sensor-configuration-format
There's a new format and a legacy format for templates, and based on what you google for you'll find one, the other, or a broken mix of both.
Better to try to go to the official documentation than old forum posts
will discord not apply the triple backticks after the fact
in edit
or am i just doing it wrong
you can edit it
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.
Looks like you confused single quote for backtick, wrong character.
yep, thanks. got it
finally
so the format that I'm using that works, is old, and no longer recommended
sensors:
sensedge_co2:
value_template: "{{ state_attr('air_quality.laseregg_air_quality', 'carbon_dioxide') }}"
device_class: carbon_dioxide
unit_of_measurement: ppm```
hey guys, not sure if this is the right place but i want to make a script that takes some input data (2 numbers, a string and a bool) and then sets the value of input_numbers/input_string/input_bool to those values - how would i do that, and how would i call that in automation?
i just can't get my head around how to give something an external value and then have the script read that value
Do templates have access to all entity properties or only what's exposed through the "state" property?
What is an entity property?
I don't know what they're called in the UI, I just mean "property" in the Python sense
You cannot access them
interesting. So how do cards like the todo list card show them? Do they have special access beyond what templates provide?
there is a core websocket API that can give todo list items
ah ha, that's perfect, thanks so much!
How can I count a decrease of a sensor to one meter and an increase to another meter?
lights color_temp never used to be defined when the light was off - did the new update change this? all my lights now show up in the list when I do: {{ states.light|selectattr('attributes.color_temp', 'defined')|map(attribute='entity_id')|list }}
Hi all, does anyone know the problem that on the energy dashboard every day the whole value is written to the statistic every day at around 8pm and 6am?
I already postet this question in #energy-archived but they think it is a templating issue. Maybe somethink is wrong with it. Here my template that I use to calculate the entity
- sensor:
- name: pv_production_total
unique_id: "PVProductionTotal(kwh)"
state_class: 'total_increasing'
unit_of_measurement: 'kWh'
device_class: 'energy'
state: >
{% set l1 = states('sensor.victron_pvinverter_l1_energy_forward_total_20') | float %}
{% set l2 = states('sensor.victron_pvinverter_l2_energy_forward_total_20') | float %}
{% set l3 = states('sensor.victron_pvinverter_l3_energy_forward_total_20') | float %}
{{ (l1 + l2 + l3) | round(1, default=0) }}
Here is the ticket I opened but I think it is not a integration issue https://github.com/sfstar/hass-victron/issues/136
is there a way to convert days to Year, months, days
I have a sensor that returns a value in days (example, 800 days)
Is there a way of converting that to 2 years, 2 months, 9 days ?
yes, I created a macro for that
you'll need to convert the days to seconds though
its already converting to get days, I will adjust to make it seconds
{% set days = 800 %}
{% set seconds = 800 * 24 * 60 * 60 %}
{% from 'relative_time_plus.jinja' import relative_time_plus %}
{{ relative_time_plus(seconds, parts=3, compare_date=0, week=false) }}
This will give 2 years, 2 months and 10 days
seems to be a day difference with yours π
that's probaly because I compare it with first of January 1970
how do I add it via HACS?, Searching doesnt find it
no conversion to seconds needed
{% set days = 800 %}
{% from 'relative_time_plus.jinja' import relative_time_plus %}
{{ relative_time_plus(now() - timedelta(days=days), parts=3, week=false, time=false) }} # 800 days ago
result: 2 years, 2 months and 9 days
{{ relative_time_plus(now() + timedelta(days=days), parts=3, week=false, time=false) }} # 800 days from now
result: 2 years, 2 months and 7 days
you need to have experimental mode enabled in the HACS settings
@flat grail I converted your message into a file since it's above 15 lines :+1:
@quick prairie probably the value of your template is dropping to 0 at those times, then jumping back up to the accumulated/summed value. If you use the availability to instead make the sensor unavailable when that happens it will probably correct the issue. It could be that you're getting unusual values when some of your source sensors are returning data and others aren't, or they might be returning nothing overnight, or something like that; you'll need to look at the history of your sensors to see what's going on
@compact rune Thanks a lot for the help. I will try this option. Hopefully tomorrow the will be no more issues with it π
@flat grail FYI, I just updated the macro, and made the instructions for HACS more clear
I'm setting up a trigger-based sensor with a trigger with variables defined. Does this exist when the trigger is triggered, so that I can use it in the templates under the variables key? Or is it only available once we are evaluating the state? I've noticed that my trigger has stopped triggering and the only difference between my old version and this one is the use of "this"
this in a trigger based template sensor works the same as in an automation. It is created on trigger, and doesn't change anymore during the whole process of calculating the values in the sensor (both state and attributes)
just check the logs for issues
my bad -- I used states.this
well that's your problem
this.state
this is a state object (or at least it emulates one)
yeah -- evidently I'm not so great at this debugging business π
always check the logs, it's going to be your goto for issues
i used the UI to build a template sensor yesterday, but now its showing as unavailable
not sure what happened or how to fix it
check your log for errors and then fix the errors
i forced the template to have good data. still can't delete it
{% if 4 <= 700000 %}
0.021086
{% else %}
0.011943
{% endif %}
Hmm, it seems that this still gives me trouble: I get the following in the log: Template variable error: 'this' is undefined when rendering '{% set temp_hist_store = this.attributes.get('temp_history',{})%}
this is called by the template: temp_hist: >- {% set temp_hist_store = this.attributes.get('temp_history',{})%} {% if hour_solar in [7,14,21]%} {% set temp_prev = temp_hist_store.get('last_'~hour_solar,13.6)%} {% set temp_hist_store = dict(temp_hist_store,**{'previous_'~hour_solar: temp_prev,'last_'~hour_solar: T_curr})%} {% endif %} {{temp_hist_store}}
Full thing: https://dpaste.org/g7FsZ
Is it supposed to be this.state.attributes?
yeah the template UI editor is busted. how does one force delete one of those templateS? where is HA shoving them?
no, looks like this is not available in the trigger variables yet
put it in the action section
- trigger:
- platform: template
value_template: >-
{% set midnight = as_local(as_datetime(state_attr('sun.sun','next_midnight')))%}
{% set mins = ( now().minute == max([5,midnight.minute+1]) )%}
{% set new_day = (today_at('00:00:10') <= now() < today_at('00:01:00'))%}
{{mins or new_day}}
action:
- variables:
hour_local: ...
sensor:
- name: ...
any good ways to subtract two entites from each other?
sensor.solarpowertotal - sensor.home_energy_meter_electric_consumption_w
both are in watt units
"{{ ( states('sensor.solarpowertotal') | float | round(1)) - ( states('sensor.home_energy_meter_electric_consumption_w ') | float | round(1)) }}"
is what i've made so far but i'm getting an unknown when rendering template
{{ (states('sensor.solarpowertotal') | float - states('sensor.home_energy_meter_electric_consumption_w') | float) | round(1) }}
hm it seems to just be displaying the first value not the subtraction
first value being the solar power total
that means your second value is 0
ah it was cuz my second value was set to KW not W
thankyou!
I have a vibration sensor to indicate if my garage door is opening or closing. It takes 4 secs to go from fully open to fully closed. Is there a way to create a template to distinguish between opening and closing?
probably a toggle entity and have it triggered by the vibration sensor
only down side is that it could go out of sync if someone bumps the garage door hard enough
vibration detected -> toggle entity "on" "open"
vibration detected - > toggle entity "off" "closed"
again - i come along and bump your garage, now that sensor is screwed up
i would suggest a door sensor vs. vibration
I have both. I have a tilt sensor that indicates open or closed. I am trying to solve for opening and closing because there is a short time when the tilt becomes horizontal (on / open) but the door is still vibrating and same with closing
you'll have to build the logic based on the previous state
Hi all! Does anyone know of a way to display "days until the next week day (e.g., Saturday)"?
will it always be saturday of the following week?
{{ 5 - now().weekday() }}
or if you want it to work on sunday
{% set w = now().weekday() %}
{{ 5 - w if w <= 5 else 12 - w }}
Oh awesome, thanks!
the eq will change for every day
Never knew about weekday()
Or you could use the modulo operator to shorten the template:
{{ (5 - now().weekday()) % 7}}
That makes sense, but i think i will still run into this issue: door closed+no vibration --> starts to open so still closed+vibration --> mostly open so open+vibration --> open+no vibration. Seems like I have a current state and previous state
the vibration lasts 4 secs if that is useful
Trigger action? what is this magic you discuss? I missed this evidently! Thanks!
You didn't read the 2023.10 release notes properly
At least only a month behind! π
Can I set the state of a sensor when a different sensor state changes and have that be conditional on a third sensor?
To be fair VS Code didn't read the release notes either. It complains it's not good syntax. But it works!
this goes back to my garage door, I was thinking that I could create a template sensor that for example, get set to "opening" if the tilt sensor is "off" and the vibration sensor changes from "off" to "on" but not from "on" to "off". Is that possible?
It's not VSCode which is complaining, it's the HA extension, in which this is not added yet
Yes, but you have to build the logic from your trigger's previous state and next state
95% sure I already said that
you did, i am just confused on how to accomplish that
with a trigger based template sensor
the logic may be hard, but post what you've tried when you try something
will do, thanks
This is what I came up with: http://pastie.org/p/3Hjq6NNb9ognZpfsnYjOOo
I couldn't figure out how to get it in one. First looks at the state of the tilt when the vibration starts to set the motion status as opening or closing. Second, takes that sensors value when vibration is on ad if vibration is off uses the state of the tilt
Edit: It works!! I am open to ways to condense it, if possible
@compact rune I change the template
- sensor:
- name: pv_production_total
unique_id: "PVProductionTotal(kwh)"
state_class: 'total_increasing'
unit_of_measurement: 'kWh'
device_class: 'energy'
availability: 'yes'
state: >
{% set l1 = states('sensor.victron_pvinverter_l1_energy_forward_total_20') | float %}
{% set l2 = states('sensor.victron_pvinverter_l2_energy_forward_total_20') | float %}
{% set l3 = states('sensor.victron_pvinverter_l3_energy_forward_total_20') | float %}
{{ (l1 + l2 + l3) | round(1, default=0) }}```
but I still get the same error. Do I used it the wrong way? Any ideas
To format your text as code, enter three backticks on the first line, press Shift+Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks.
```yaml
example: here
```
Don't forget you can edit your post rather than repeatedly posting the same thing.
You need the availability template to actually do something, it's not a yes/no thing
You need to figure out what states of the underlying sensors create the problem and then make the template sensor unavailable when there would be an issue
Any help will be much appreciated - I'm stuck on a brain teaser and not even sure if it is possible. Also, unsure which channel to post this, but figuring this could be done in the microcontroller or using a template sensor, I decided to start here, but I belive it will probably best to implement on the microcontroller itself (ESPHome). I need to recognise patterns to determine different states. The for main patterns I'm prioritising to recognise is:```
The digital input drives HIGH following a status LED on a motor controller.
Gate Closed: LED OFF, Input Pulled low --> Easy, and done.
Gate Open: LED ON, Input Pulled High --> Easy, and done.
Now, this is where I get stuck,
Gate Opening: LED Flashing at an interval of 0,5s
Gate Closing: LED Flashing at an interval of 0,2s
Gate Loss of Mains: 2 Flashes per second, off for 1 second. Then repeat.
ESPHome has a discord, I would recommend going there. I think youβll have to measure the time between the input transitioning from low to high (rising edge trigger), and progress through a decision tree. E.g if it saw two edges in 0.2s then gate is closing. If it saw two edges in 0.5s then itβs either opening or loss of mains so you need to wait for two more edges and make a decision. If itβs been longer than 1s since the last edge, then check if the state is currently high or low and set it as open or closed, respectively. After the state of the sensor is set, the next rising edge would start the logic from the top of the decision tree.
trying to setup a notification automation to notify if WAN ip changes , but this notify does not give my IP address :
service: notify.mobile_phone
data_template:
title: Your External IP address has changed
message: Your new IP address is {{ states.sensor.router_extern_ip }}
outputs "Your new IP address is )>" ? something wrong with the template ?
I'd try states('sensor.router_extern_ip') instead of states.sensor.router_extern_ip as a first step. What you have is probably getting a state object rather than a string of the state.
Hi. Is it possible to pass a state object inside a variables statement? I am doing this in a trigger-based sensor action statement: - variables: temps: "{{states.sensor.inpo_praha_temperature_today_average_test}}"
and then trying to use it as {% set temp_hist_store = temps.attributes.get('temp_history',{})%}
which gives me an error ```
Template variable error: 'str object' has no attribute 'attributes' when rendering '{% set temps_hist_store = temps.attributes.get('temp_history',{})%
The sensor.inpo_praha_t... in the variables is actually the sensor I am calculating itself. I tried using "this" originally, but "this" doesn't seem to get defined until the main sensor part - -it's not defined in the trigger or the action parts
you seem to be right, this is not available in the action part as well
Hey all, I got a (guess) simple question, but not sure where to start. I have setup a template trigger sensor to get my daily calendar events for birthdays. Now that all works, and I get a new sensor with the amount of birthdays + the ones in there. It is possible that there are more celebrating on that day, so I get 1 or more records back from my 'scheduled_events' attribute. My goal is to show a template mushroom card with the names that are in the title of the calendar event.
How can I loop over those events, and get a certain attribute of it? My attributes I get from the sensor:
`scheduled_events:
- start: '2023-11-03'
end: '2023-11-04'
summary: Linde jarig - start: '2023-11-03'
end: '2023-11-04'
summary: Nardy jarig . Linde jarig`
I just want to loop through the events and take the summaries and put them together
So the output in the example above must be: Linde jarig, Nardy jarig . Linde jarig
{% for event in state_attr('sensor.xyz', 'scheduled_events') %}
{{ event.summary }}
{% endfor %}
@mighty ledge How simple can it be... Thanks a lot for your time
I came up with this. It works but is there a better/simpler way? http://pastie.org/p/3Hjq6NNb9ognZpfsnYjOOo
Hi how can i change this to show information "This is your week" To display this for 7 days and then start counting again. this is based on calendar events that repeats every 35 days.
The idea is to show remaining time and once it is my time to throw bins i can see for a week that is my turn
At this moment its only counting down and once the day hit its reseting and counting again for next turn
Your bin week in: {{ ((state_attr('calendar.michal', 'start_time') | as_timestamp - today_at('00:00') | as_timestamp) / 86400) | int }} Days
So just 'if that believes less than 7, display "this is the week"'?
It's just an if/then
sorry not sure how to do that ;/ i have done this from yt tutorial but wanted to edit this a little bit
there are great docs in the channel topic, but here:
{% set days = ((state_attr('calendar.michal', 'start_time') | as_timestamp - today_at('00:00') | as_timestamp) / 86400) | int %}
{{ iif(days > 7, 'Your bin week in: ' ~ days ~ ' Days', 'This is the week') }}
Is there an easy way without a loop to take 2 keys and add their values together from a list of dictionaries.
- name: 'santa'
place: 'mars'
- name: 'elf'
place: 'moon'
Output
- santa/mars
- elf/moon
not possible
Everyone knows that Santa lives on the moon. No idea about elves, maybe a big tree
Iβm trying to make a template trigger for an automation that fires off 5 minutes before an input_datetime. This is what I have currently but isnβt working:
{{ now() == today_at(states('input_datetime.work_mode_time')) - timedelta(minutes=5) }}
Is there a syntax error or will I need another component, like a sensor to calculate the offset, and use that value to trigger the automation when the current time matches?
now() is accurate in microseconds and it will update once per minute. It will never exactly match that other datetime
got it - the suggestion on the ha forums post I was looking at mentioned comparing with a >= comparison
That will work
@quick prairie I converted your message into a file since it's above 15 lines :+1:
If that resets twice a day, it is because your source sensors reset as well
But there must be some way to prevent this that the total value is not written into the entity. @compact rune said the availability option would be the right way to go but I donβt know how to write that.
well, he was wrong
that just makes the sensor go unavailable or not
your template already has the correct availability
So there is no way how to fix with HA functionality? So maybe the developer of the integration has to be fixing something?
no, if your state_class is set properly, then the resetting shouldn't matter
and your energy panel will output the correct info
i.e. in your case you probably want a state_class of total, and then you have to calculate last_reset based on when your sensors reset.
if you go w/ total_increasing it may also work as long as your sensor drops to 0
more than likely, you don't even need the template sensor, you just need to add all your sensors to the energy panel.
is it possible to translate state in a jinja template? i've seen some work about this by @craggy parrot but it's not yet merged. does it mean I need to do some | replace() to get weather state translated?
@still thistle Create a mapping with the translations
{% set translation =
{
'cloudy': 'foo',
'sunny: 'bar'
}
%}
{{ translation[states('weather.home')] | default('unknown') }}
Is there a way to get the todo items out of a todo in templating? I want to create some custom UI foir it using templating?
You can, but it's a chore. There is no translation method for the backend
ah, I see thefes show'd you the chore
not yet
coming soom β’οΈ
thank you @marble jackal i think it's cleaner than my replace
@thorny snow I converted your message into a file since it's above 15 lines :+1:
How can I list up the two lowest values from these 4?
{% set plat1tid = 3 %}
{% set plat1tid2 = 34 %}
{% set plat3tid = 12 %}
{% set plat3tid2 = 30 %}
{{name of the lowest value}}
{{name of the 2nd lowest value}}
{% set plat1tid = 3 %}
{% set plat1tid2 = 34 %}
{% set plat3tid = 12 %}
{% set plat3tid2 = 30 %}
{% set items = [plat1tid, plat1tid2, plat3tid, plat3tid2]|sort %}
{{ items[0] }}
{{ items[1] }}
Thanks! Not sure if im doing this right tho. I have a name for each value. How can I get the two lowest values including their names?
{% set plat1tid = 3 %}
{% set plat1tidNAME = name1 %}
{% set plat1tid2 = 34 %}
{% set plat1tid2NAME = name2 %}
{% set plat3tid = 12 %}
{% set plat3tidNAME = name3 %}
{% set plat3tid2 = 30 %}
{% set plat3tid2NAME = name4 %}
{{lowest value + its name}}
{{second lowest value + its name}}
Finished editing the post now btw
You need to create a mapping/dictionary to be able to do that. Or a list with mappings.
list w/ mappings
So either
{
'name1': 3,
'name2': 34,
'name3': 12,
'name4': 30
}
or
[
{ 'name': 'name1', 'value': 3 },
{ 'name': 'name2', 'value': 34 },
{ 'name': 'name3', 'value': 12 },
{ 'name': 'name4', 'value': 30 }
]
I agree the second will be best, but the first can work too
I'm writing a template to translate wattage from a sensor into a percentage value, and it's not working. Did I screw up the syntax? It just shows up as "unavailable"
{{ ((states('sensor.sonoff_blahblahblah_power')) * (100 / 27))-548 | round(1, default=0) }}
You need to convert the state to a number, as all states are strings
Oh, and you are only rounding 548 right now
Yes
boom, fixed and extra parenthesis fixed the rounding. Brilliant. Thanks, @marble jackal !
Why is this not appearing in home assistant? I saved it and restarted the configuration and there were no errors
template:
- sensor:
- name: "thermpwr_hourly"
unit_of_measurement: "kWh"
state: >
{{ [state_attr('climate.neviweb130_climate_kidroom1', 'hourly_kwh_count'), state_attr('climate.neviweb130_climate_basement', 'hourly_kwh_count'), state_attr('climate.neviweb130_climate_kidroom2', 'hourly_kwh_count'), state_attr('climate.neviweb130_climate_dining_room', 'hourly_kwh_count'), state_attr('climate.neviweb130_climate_living_room', 'hourly_kwh_count'), state_attr('climate.neviweb130_climate_parents_bedroom', 'hourly_kwh_count')] | map('float') | sum }}
Scam
@real fog please ban this user
<@&330946878646517761> ^
won't it ping all of them
That's the right thing to do with spammers.
Yep π
hi there π
I have a 3d printer, that runs klipper/moonraker. There is an integration that expose a bunch of stuff to HA and is really cool
One of the things that are passed along is the raw value of a pin on the microcontroller in the device, it happens to be connected to a bunch of LED strips.
It is shown as a number entity, that takes a (float) value between 0 and 100, but effectively, it's a dimmable light
I am trying to create a template that exposes as such, but I have difficulty reading the value and/or level of the actual number entity
@visual abyss I converted your message into a file since it's above 15 lines :+1:
For now it works one way only, I can set the value of the light, but if I change the value of the underlying number it does not update the state of the light
so, it only works one way (easier to show than to explain by text https://streamable.com/dexbg9)
I guess I am not sucessfully reading the number in level_template
playing with the template thing in the dev tools
state_attr('number.voron2_output_pin_caselight', 'value') is None somehow
Oh
I think I got it
Does that entity have such an attribute?
{{ states('number.voron2_output_pin_caselight') | float / 100 * 255}}
Yes
it's actually my first time writing one of those for myself... Looking at the docs and using the tab in the dev tools is actually useful... π
You'd be surprised how few people do those things
This machine is a giant box full of lights enclosed in acrylic, so it actually act a a lamp in the room... Hence why I want to be able to control it via HA too π
what the proper thing to put in a unqiue_id? a uuid as a string?
Yup, that works, I can now set stuff about it in the GUI
If anybody's curious, here's what I got working
@visual abyss I converted your message into a file since it's above 15 lines :+1:
This bit isn't doing what you think: value: "{{ brightness / 255 * 100 | int }}"
It's turning 100 into an int & truncating it, which it already is
Yes
make sense
Ah yes, it was still putting hte output values with a bunch of decimal points
Alright, I think I got it as good as I could, thanks @inner mesa !
Aaaaand now I can set it via HomeKit thanks to HomeBridge, perfect
that was the goal
Hi,
With Release 2023.11.1 - November 4
Template trigger.to_state.state don't working.
Can you give an example where it doesn't work. I use that for many automations without issues so far
to_state definitely works, it's an issue w/ the template
I'd wager that it's a template that grabs an attribute and the attribute is now None. That's breaking many things ATM
Now it's working fine I did not edit anything in the template.Thanks.
I have another question that I do not find a way to do: is it possible to restore the previously set brightness in turn_on on a template light like this one?
i have a blueprint that takes multiple light entities. i then alias the !input other_lights as other_lights . then i try to get their maximum brightness. this used to work, but in a recent HA upgrade it stopped working:
{{ expand(other_lights) | map(attribute="attributes.brightness", default =
0) | max > 30 }}```
I now get an error saying:
```Error: TypeError: '>' not supported between instances of 'NoneType' and 'int'```
is there a way to try this sort of syntax (using expand) in the template "Developer tool"? it seems to me like something is broken with expand but it's hard to test right now because i have to reload the Automations, and then trigger an automation using the blueprint.
The problem is that as of 2023.11, attributes they don't apply are now set to None if they don't apply rather being removed
so the default=0 is doing nothing because it's passing through a value of None
Yes. See this for a simple fix: #beta message
I don't know if map() can take a parameter that makes it also apply the default to None like default() does
Could be another option
But it's at least not documented
thanks so much for the referral. this saved me a ton of time. i was trying all sorts of stuff.
where do you find documentation for select selectattr etc?
See the links in the channel topic
Become a real Jinja2 Ninja! Don't worry my Genin, we are here to help! You can find general Jinja docs at https://jinja.palletsprojects.com/en/3.1.x/templates/, Home Assistant extensions at https://www.home-assistant.io/docs/configuration/templating/, and trigger variables at https://www.home-assistant.io/docs/automation/templating/
This channel is for support with Jinja templates. Some custom Lovelace cards support other types of templates, such as those written in JavaScript, and #frontend-archived is the right channel for that.
Please use http://pastie.org/, https://dpaste.org/, or https://paste.debian.net/ to share code or logs
thanks again, RobC.
First one
hi guys hopefuly very easy question how could i divide this binary sensor value by half? using templates but its not working for me yet:
`sensor:
- platform: statistics
name: "blabla"
entity_id: binary_sensor.c
state_characteristic: count
max_age:
hours: 24`
What did you try?
You can't do it in the definition you provided. You need to make another template sensor
looking there right now thanks
Hi all, is there any way to write a script to turn off all entities that contain a specific word within a certain domain? For example, I am trying to turn off all automations that contain the word "*heat" when I switch to summer mode:
sequence:
- service: automation.turn_off
data_template:
entity_id: >
{% for state in states.automation if 'heat' in state.name|lower %}
{{ state.entity_id }},
{% endfor %}
My code is wrong but I don't know what is wrong exactly? Any help?
Thank you!
@uneven lark I converted your message into a file since it's above 15 lines :+1:
New to this... any idea why I am getting this (trying to add bandwidth monitors per: https://community.home-assistant.io/t/snmp-bandwidth-monitor-using-statistics/96684/76)
- platform: template
sensors:
internet_in_mbps:
value_template: "{{ (state_attr('sensor.FGT_wan_in_stats_mean','change_rate')|float*8*(state_attr('sensor.FGT_wan_in_stats_mean', 'sampling_size')-1)/1000000)|round(2) }}"
unit_of_measurement: "MBps"
entity_id: sensor.FGT_wan_in_stats_mean //PROPERTY ENTITY_ID IS NOT ALLOWED
internet_out_mbps:
value_template: "{{ (state_attr('sensor.FGT_wan_out_stats_mean','change_rate')|float*8*(state_attr('sensor.UDMP_wan_out_stats_mean', 'sampling_size')-1)/1000000)|round(2) }}"
unit_of_measurement: "MBps"
entity_id: sensor.FGT_wan_out_stats_mean //PROPERTY ENTITY_ID IS NOT ALLOWED
specifically the /PROPERTY ENTITY_ID IS NOT ALLOWED
Because entity_id is not one of the allowed configuration variables for legacy format (or current format for that matter) template sensors (https://www.home-assistant.io/integrations/template#legacy-sensor-configuration-format)
Just remove those two lines.
I've seen it before, it's a legacy thing of the legacy format. Should not give errors, but it does nothing. However, this entity_id is faulty, as it includes capitals.
You should still remove the entire line though, as it doesn't do a thing
I would advice to create an input_boolean.summer_mode and check on the state of that in a condition of the automation
If you really want to turn them off, use the code below
sequence:
- service: automation.turn_off
data_template:
entity_id: >
{{
states.automation
| map(attribute='entity_id')
| select ('search', 'heat')
| list
}}
Nice!
@final parcel I converted your message into a file since it's above 15 lines :+1:
Platform: sql. - Not displaying sensor
@final parcel you need to create a list like ['item1','item2']
Time: >
{{ [ states('sensor.date') ~ 'T00:00:00+01:00',
today_at().isoformat()] }}
Play around with the template in developer tools until you get what you want
Thanks, what I am trying to do is a template sensor for apex card. I need to get today date - hours of a day and also tomorrow date plus hours of a day. π
You can add or subtract from datetimes with timedelta(hours=2)
thank you!
A string containing the ISO format of Yesterday at 21:00 for example:
{{ (today_at() - timedelta(hours=3)).isoformat }}
if I add 24 then I will have tomorrow. Great!
hmm but I am still getting error
- binary_sensor :
- name: "test"
state: yes
attributes:
datum: >-
{% set values = [states('sensor.date') ~ T00:00:00+01:00, states('sensor.date') ~ T01:00:00+01:00, states('sensor.date') ~ T02:00:00+01:00] %}
{{ values }}
Ok, maybe I shall try without template
ah!
But you should be trying that template in the dev tools template editor first, itβs much easier to debug there
you are right... but I am still not getting the list with the dashes... I am getting one row of: 5. listopadu 2023 v 00:00:00, 5. listopadu 2023 v 01:00:00, 5. listopadu 2023 v 02:00:00
In the template editor or that is what the sensor attributes returns?
If you delete everything in the template editor and only put in your template, the template editor will tell you result type: list
I did and the output is
[
"2023-11-05T00:00:00+01:00",
"2023-11-05T01:00:00+01:00",
"2023-11-05T02:00:00+01:00"
]
Yes that is a list
But if I go to the dev tools > states and look for the sensor it shows: datum: 2023-11-05T00:00:00+01:00, 2023-11-05T01:00:00+01:00, 2023-11-05T02:00:00+01:00 friendly_name: test
Which is not the list...
I would expect dashes between
Is this a template binary sensor?
Iβm not sure why it isnβt showing correct. try {{ values | list }}
Also take the dash out so it is datum: >
I took out the dash and nothing changed...
with list it is still the same also π¦
Iβm trying to find an example of another sensor that only has a list as an attribute. This might be how the frontend displays it.
If it is a list inside a dict it will show with the dashes:
{{ dict(vals=values)}}
I wish I could translate that to the regular language, I am not programmer π¦ just hobby
so how should put it into the config pls? π
just put {{ dict(vals=values)}} instead of {{ values }}?
Can I post you a screenshot to the message so you know how it displays now? It with dashes but on the top of the dates there si vals=
Yes
And yes to your second question
You can also do a list of dictionaries too, if you like that display better:
{% set values = [{'date':states('sensor.date') ~ 'T00:00:00+01:00'}, {'date':states('sensor.date') ~ 'T01:00:00+01:00'}, {'date':states('sensor.date') ~ 'T02:00:00+01:00'}] %}
{{ values}}
I canβt display screenshots in this channel
I post you a private message
Yes that is showing like it should, that is a dictionary with one key and a value that is a list
Thanks! I am getting closer....
It seems that the front end just shows a simple list as comma separated values, and thereβs nothing you can do about it. If you embed the list into a dictionary, or if each item in your list is a dictionary, then it shows with dashes
but I think I am gonna sleep and let it for future... because now I have name of dictionary and also name of that attribute
U just want to create same sensor as here for example https://github.com/RomRider/apexcharts-card#data_generator-option
I.. π
I have it almost!!! π
This worked like a charm. I love this way to create a list of entities based on search.
Thanks a million!
@karmic sapphire I converted your message into a file since it's above 15 lines :+1:
Seems it is beging to working however now I am not able to set date and time for tomorrow by {{ states('sensor.date') + timedelta(hours=24) ~ "T00:00:00+01:00" }} but I will leave it for tomorrow π
if all you want is to create a sensor with a list of values, you've already accomplished that. You don't need to worry about how the frontend displays the list. If you want to confirm it's a list, you can go into the template editor and write `{{ state_attr('binary_sensor.test','datum')[0] }} and it will show you the 1st (technically 0th) element of the list
the state of any sensor is a string. you can't add a timedelta to a string
hmmm but I will look at that tomorrow really π And many thanks! Its to late here π
if you really want to do it that way, you'd have to use {{ (as_datetime(states('sensor.date')) + timedelta(hours=24)).date() ~ "T00:00:00+01:00" }}
thanks!! Very much
Maybe I will find out using "for" how to write that more easy than specifying 48 hours per hour from current day midnight :). And thanks for helo. Much appreciated
play around with this tomorrow: {{ (today_at() + timedelta(hours=24)).isoformat() }}
A need really 24 hours of current day and 24 of tomorrow so I need to use probably date at first
Or I can do maybe for cycle just for changing the second numbers in that format π
sure. I may come up with something and post it for you to look at tomorrow.
Thanks! it is for purpose of Apex graph. This plugin gives me a spot electricity prices - https://github.com/rnovacek/homeassistant_cz_energy_spot_prices and I need to add to the graf the tarif I get in partucular hour. High and low depending on hour.
So I need to list of each hour for current and tomorrow hours and per each hour a need to assign the price of the tarrif
Good night
{% set ns = namespace(datelist=[]) %}
{% for i in range(0,48,1) %}
{%- set ns.datelist = ns.datelist + [(today_at()+timedelta(hours=i)).isoformat()] -%}
{% endfor %}
{{ ns.datelist }}
nvm, just wrote out a monster of a template to accomplish this
@small wasp I converted your message into a file since it's above 15 lines :+1:
then can easily work with the produced list of entities
Thanks! Btw could you explain me in more datil what is doing what? π
it's creating a range going from 0 to 47, and then takes last midnight and adds hour * number in range
and adds those in a list
doesn't look like something which would require a monster of a template
entities: >
{%- set ns = namespace(ret=[]) %}
{%- for key in ['device_id', 'area_id', 'entity_id'] %}
{%- set items = lights.get(key, []) %}
{%- if items %}
{%- set items = [ items ] if items is string else items %}
{%- set filt = key.split('_') | first %}
{%- set items = items if filt == 'entity' else items | map(filt ~ '_entities') | sum(start=[]) %}
{%- set ns.ret = ns.ret + [ items ] %}
{%- endif %}
{%- endfor %}
{{ ns.ret | sum(start=[]) }}
does the same thing
just need to add lights: !input xyz before that variable
assuming you're coming from a target selector
aka no monster template needed
that get's all entities
you'll need to add | select( 'search' , '^light' ) | list to the end
How would I use a camera entity to link to a url like this when clicking on it? http://192.168.1.34:9000/recipe/{{states.sensor.mealie_todays_meal_id.state}}
You need to use a card that supports templating in the tap action
got it, thanks
how do I multiply an input (trigger variable) duration by a constant? I want to time my lights out in a blueprint, and I've successfully gotten a blueprint working where I can input the timeout duration, but sometimes the automation doesn't work for some reason or another (zigbee network overloaded, etc), so I want to retry a few times, e.g. after (!input timeout_duration) 3 minutes, 2 * 3 minutes, 3 * 3 minutes, etc. I'm fine with doing it a fixed number of times, but I don't know how to do the for: '{{3 * timeout_duration}}' part
When I try with the above or any similar variant with pipes to int/float/multiply, I get an error (after trying to create a new automation with the blueprint; current automations are just, confusingly, "unavailble" with no more information): Message malformed: offset None should be format 'HH:MM', 'HH:MM:SS' or 'HH:MM:SS.F' for dictionary value @ data['for']
Edit: nevermind, it was a silly typo on a previous line.
Iβm trying to build a template to monitor all devices of a certain class with β{{ states.binary_sensor | selectattr('attributes.device_class', '==', 'moisture') | map(attribute = 'entity_id') | select('is_state', 'on') | list | length }}β however it only triggers on first sensor that is triggered, I plan to use this template with blueprint so I cannot make template sensors for each class, any suggestions?
your only option is to select all relevant entities in a selector, without the help of a template sensor it is not possible to do this dynamically
@tardy stirrup I converted your message into a file since it's above 15 lines :+1:
Hi, new to HA and programming in general. I'm trying to pull a buried attribute out of an integrated device. I created a sensor.yaml and have this code in there:
friendly_name: 'sensedge_co2'
value_template: "{{ state_attr('air_quality.laseregg_air_quality', 'carbon_dioxide') }}"
device_class: carbon_dioxide
unit_of_measurement: ppm```
I am getting the fallowing error: Invalid config for [sensor.template]: [friendly_name] is an invalid option for [sensor.template]. Check: sensor.template->friendly_name. (See ?, line ?).
I also have this code ahead of the template above, which may or may not be screwing something up?
monitored_feeds:
- type: five_minute
- type: current_hour_average```
Thanks!
no, your yaml code is wrong for the template sensor
here's how it should look https://www.home-assistant.io/integrations/template/#legacy-sensor-configuration-format
I also tried followign this format and it wouldn't work
- sensor:
- name: "Average temperature"
unit_of_measurement: "Β°C"
state: >
{% set bedroom = states('sensor.bedroom_temperature') | float %}
{% set kitchen = states('sensor.kitchen_temperature') | float %}```
Are you recommending I use the legacy format?
that's basically correct, but that falls under the template integration, so you can't place that in sensor.yaml
ah
no, I don't recommend you use that, but in your earlier posts you were using it, but it was not correct
right, it was working in my earlier post then stopped
so i'm tryign to update it
I'll need to read up on templating integration then, i'm not sure if that goes into config.yaml or gets its own
thanks!
This looks most like the legacy template sensor format, but it is wrong, and therefore not working. If it were correct it should be placed in sensor.yaml
- platform: template
friendly_name: 'sensedge_co2'
value_template: "{{ state_attr('air_quality.laseregg_air_quality', 'carbon_dioxide') }}"
device_class: carbon_dioxide
unit_of_measurement: ppm
This is correct YAML, but can't be placed in sensor.yaml. The way you have it now it should be placed direclty in configuration.yaml. However the template you have there doesn't ouput anything, it just sets two variables
template:
- sensor:
- name: "Average temperature"
unit_of_measurement: "Β°C"
state: >
{% set bedroom = states('sensor.bedroom_temperature') | float %}
{% set kitchen = states('sensor.kitchen_temperature') | float %}
you could create a separate templates.yaml for the 2nd one if you want
Sorry, I feel like these questions are terrible. I created a template.yaml and in config.yaml i included
template: !include.template.yaml
But now getting error: Error loading /config/configuration.yaml: could not determine a constructor for the tag '!include.template.yaml'
This is what is in my template.yaml:
- name: "sensedge_co2"
unit_of_measurement: "ppm"
state: >
{{ state_attr('air_quality.laseregg_air_quality', 'carbon_dioxide') }}```
You have a rogue period in that statement. Should be `template: !include template.yaml
ah, duh. thanks
my excuse: its dark and my eyes aren't working great right now (couldn't sleep)
thank you both!
There is new switch configuration for command_line for 2023.12 update, but command_line does not support these settings(port and resource): - platform: telnet switches: zm_trigger_terasa: resource: 192.168.1.20 port: 6802 command_on: '2|on+30|2|External Motion|External Motion' command_off: '2|off|2|External Motion|External Motion'
What to do now for these breaking change?
that's not a command line switch
i.e. there's nothing for you to change with that.
@rotund hazel ^
thanks , because I got warning
did you get a warning that said command_line?
if yes, then you need to find platform: command_line not the other platforms
no, warning for switch
post the warning because you're not providing the correct information
Consult the documentation to move your YAML configuration to integration key and restart Home Assistant to fix this issue.```
Right
notice how it says Command Line
therefor you need to search your switch configuration for platform: command_line
not platform: telnet which is not a command_line switch.
thank you
Is it possible to use the new template format when I want to create a template sensor from a different platform as template? like this on the legacy template format: http://pastie.org/p/0Uuh5OZWp4NB4Ry8qG76YS
you can't mix and match platforms
you have to make a waste_collection_sechule and a separate template
its working right now as the docs states, but my intention was to move, if possible to the new format
that was the reason to ask
throught he template: and no more sensor: platform
I need to learn a bit more with the templates
platform: template is different than platform: waste_collection_sechule
to get a better understanding
platform: template is the template integration
platform: waste_collection_sechule is the waste collection integration
you can't mix and match
okay. but this is not possible I guess, but I would like to know it for sure ^^;
Which is the best approach when I would like to split this platform into a seperate yaml file? it works with the sensor: platform = sensor: !include template-sensor.yaml
if you want to split them into separate files, you'd need to put them into a folder and your include would need to point to the folder. You'd used the merge list include.
sensor:
- platform: template
those can be moved to the new template sensor platform
sensor:
- platform: something_else
Those should be left where they are
I used different folder for now for template: with template/ and sensor: with sensor/
yes, that's how it should be
How can I make a template sensor for the chance of rain% and the humidity?
Could you be a little more specific about what you want the output to be? For instance, are you trying to determine the chance of rain based on humidity, etc?
I am trying to have a sensor that says "43%" humidity or "0%" chance of rain (two seperate sensors) to be used in a tts automation to tell me this information. But I need to seperate these values from my weather entity.
you don't need template entities, you can just template in your TTS automation
target:
entity_id: media_player.bedroom_display
data:
message: >
Good Morning, Itβs currently {{ states('sensor.weather_temperature') |
round(0, default=0) }} degrees and {{ states('sensor.weather_condition') |
default('N/A') }} in Salem today. Your bedroom is currently {{
states('sensor.aidans_bedroom_temperature') | round(0, default=0) }}
degrees. Today's high will be {{
states('sensor.weather_daytime_high_temperature') | round(0, default=0) }}
degrees with a low of {{ states('sensor.weather_overnight_low_temperature')
| round(0, default=0) }} degrees. You can expect a {{
states('sensor.weather_precipitation_probability') | round(0, default=0) }}%
chance of rain today.``` This is what I have but the entities other than sensor.weather_temperature don't exist.
They are attributes of your weather entity
Are they supposed to be visible in the ui?
they are visible in the UI if you use the weather card
or if you expand the weather attributes
regardless, to get an attribute from an entity, simply use state_attr
{{ state_attr('weather.home', 'humidity') }}
It looks like precipitation is only shown in the forecasts.
At least for the ones I have
Oh, I thought you were going to do it.
Anyway if there still is a forecast attribute @quiet creek will be able to take it from that (until March next year)
For a future proof solution a template sensor is needed
Unless there will be an alternative to get the forecast data in the time from now until March
@quiet creek I converted your message into a file since it's above 15 lines :+1:
did you actually check in devtools > states?
if you look at the screenshot Petro posted, none of these values you are now trying to extract are attributes of the weather entity
It looks like I don't have these availble to me, what weather integration has these values?
probably no weather entity will have them as attribute
but the precipitation will be in the forecast attribute
but not all weather integrations include today in daily forecast
Accuweather does
and also has precipitation_probability in the forecast
for the other two Accuweather provides temperature in the forecast for the highest temp of the day, and temp_low for the lowest
accuweather set to daily
to get them out:
{{ state_attr('weather.accuweather_daily', 'forecast')[0].precipitation_probability }}
but again, this will not work after March 2024
So, for now you can use something like that directly in your TTS message, no template sensor needed
after that:
template:
- trigger:
- platform: state
entity_id: weather.accuweather_daily
action:
- service: weather.get_forecast
data:
type: daily
target:
entity_id: "{{ trigger.entity_id }}"
response_variable: forecast
continue_on_error: true
- variables:
today: "{{ forecast.forecast[1] if forecast is defined else {} }}"
precipitation_probability: "{{ today.get('templow', none) }}"
temp_min: "{{ today.get('templow', none) }}"
temperature: "{{ today.get('temperature', none) }}"
sensor:
- name: Temperature High
unique_id: 858e8aa5-bed0-4920-a64d-0a659721887c
device_class: temperature
state_class: measurement
unit_of_measurement: Β°F
state: "{{ temp_min }}"
availability: "{{ temp_min is not none }}"
- name: Temperature Low
unique_id: ca25703a-5d27-4bb2-a811-62c4637dfe26
device_class: temperature
state_class: measurement
unit_of_measurement: Β°F
state: "{{ temperature }}"
availability: "{{ temperature is not none }}"
- name: Chance of rain
unique_id: c7f19a6e-7cfe-4c47-9eaa-f540861e2948
state_class: measurement
unit_of_measuremetn: "%"
state: "{{ precipitation_probability }}"
availability: "{{ precipitation_probability is not none }}"
You can use this trigger based template sensor to get the data out of your weather entity
Does this go in my config.yaml or my automation?
That is something for your config.yaml
will you accept a pull request to change this in Home Assistant repo?
I only ask because VS code says that the property action is not allowed
ignore it
I'm not one of the people reviewing and accepting PR's
Can anyone tell me how to change this template so that I get the last know value instead of 0 ?
- name: Import power # power from grid: positive if importing, else zero
unique_id: sg_import_power
unit_of_measurement: W
device_class: power
state_class: measurement
availability: "{{ not is_state('sensor.export_power_raw', 'unavailable') }}"
state: >-
{% if states('sensor.export_power_raw')|int < 0 %}
{{ states('sensor.export_power_raw')|int *-1 }}
{% else %}
0
{% endif %}
{{ this.state }}
thanks
@small wasp I converted your message into a file since it's above 15 lines :+1:
ugh
but yeah i was very happy to find out bitwise_and filter was a thing when & wasn't working
With the update to 2023.11 all lights which support brightness always have the attribute. So you could just check on that
would there ever be any case where a light supports brightness but not transitions though?
Ah sure, in that case it will go to brightness 1 immediately
actually testing this out, there's no way to differentiate in a template whether or not the null value returned by querying the brightness attribute is because of the light being off or because the light doesn't support brightness
My lights which don't support brightness simply don't have the attribute, whether they are on or off
right, but state_attr returns null regardless of if the light simply does not support brightess, or if it does and it's just currently off
Hi, I would like to compare the state from 3 entities and the entitiy with the lowest value should be put as the value from the template sensor. Is this possible?
nvm, the string representation "null" is the same but they aren't directly equal
for example this: {{ entities | expand | selectattr('attributes.brightness', 'defined') | map(attribute='entity_id') | list }}
will only list entities which support brightness
Yes, that's what I meant π
yeah i just got confused because the string representation was the same when i was initially testing it out
Hi, I wonder if anybody can help me with this sensor. I want the state to be TRUE after the media player being "paused" for 5 seconds. But in reality, it takes more or less 20 seconds for it to swicth. Is there something wrong in the template?
- name: Sonos Vardagsrum State
state: >
{{ (is_state('media_player.vardagsrum', 'paused')) and (now() > states.media_player.vardagsrum.last_changed + timedelta(seconds=5)) }}
```
You will be better off with a trigger template sensor. The state change of your example is dependent on a state change in media_player.vardagsrumor now() which only forces an update every minute
so now() is the crook here?
I have to read up on trigger based templates π
Yep to validate the extra 5 seconds the template relies on the update frequency of now() which is 1 minute to manage resources
many thanks for explaining
How can I get the sensor entitiy ID which has the lowest from three different entities? (Is that even possible?) Rest = 3, Bio = 6, Wert = 9 In this case, "Rest" is the lowest and an icon should be set accordently to "Rest" to the new template sensor
it's not to manage resources, it's to emulate using sensor.time, which is how we used to enforce a mintely update on template sensors.
the throttle on states and states.<domain> were put in place to manage resources
It's a rather complicated template
could just use a "combine the state of multiple sensors" helper entity
{% set ns = namespace(items=[]) %}
{% for e in ['sensor.a','sensor.b','sensor.c'] %}
{% set ns.items = ns.items + [{'e': e, 's': states(e) | float(None)}] %}
{% endfor %}
{{ ns.items | rejectattr('s', 'none') | sort(attribute='s') | map(attribute='e') | first | default }}
oh wait i didn't lie, a "combination" helper has an attribute to indicate its source
That it does, TIL
May I ask what is the "s" for? e is for the for loop
you don't need it, see what sebastian said
s and e are just labels I used to be lazy
ah okay, just asking because it provides me not the entity with lowest, but with the mid value
you didn't create the group with the setting set to minimum
I was refering to your code snipped. With the helper, it returns the lowest value indeed, but not the entity which has the lowest value
it has an attribute with the entity id of the one which has the lowest value
Hi, I wonder if anybody can help me with
it 100% returns the sensor with the lowest value.
it rejects sensors that do not have numerical results
Is it possible to create a template sensor that counts down to a specific date each month. And then starts over conting down to the same date next mont when it is reached ? I would like to know how many days are left until payday each month.
Yes
{% set t = today_at() %}
{% set date = t.replace(day=20) %}
{% if date < t %}
{% set next_month = date.month + 1 if date.month < 12 else 1 %}
{% set next_year = date.year if date.month < 12 else date.year + 1 %}
{% set date = date.replace(month=next_month, year=next_year) %}
{% endif %}
{{ (date - t).days }}
that's to the 20th of each month
@plucky depot ^
Thanks, would it be difficult do do the same thing to count down to a reaccuring event in the local calendar. And if that event is on an weekend it gives the countdown until the previous friday ?
My payday is the 25:th each month, but if the 25:th is on an saturday or sunday the payday is on the previos friday.
That's all possible but the code would be different
you'd have to replace t = today_at() with your calendar start_event attribute
as for the previous friday, that's not an easy task.
as you say, friendly_name is an attribute, and you would use state_attr(entity, 'friendly_name') to get it
icon is (typically) not an attribute, but something built into the entity in some way
Hello there people of #templates-archived. I have a remote MQTT device that I managed to get talking to the Mosquitto broker but I have spend too much time trying to make it work. Would somebody be interested in some quick PayPal beer-money to show me how to set that up?
Here's the template that I have found:
https://sequr.be/blog/2020/10/mqtt-templates-for-shelly-devices/#shelly-4pro
PN me your price
that tutorial and code is out of date by about 1 year at this point
find a different blog
shelly devices don't even need MQTT either, just use the shelly integration and avoid all the MQTT stuff
enable CoIoT, integrate, and you're done
it is remote. not within the LAN
I don't think that should make a difference
unless you don't have access to the device remotely
well it is remote and I have access through the Shelly Cloud so I can make changes in settings
would you be interested in lending a hand?
just bought you a coffee to show you I'm being serious
works for me, added you as friend here, ive set an alarm
i currently have a sensor that measures in kWatts, i would like to have this sensor in watts but i don't get it to work, tried this:
`sensor:
- platform: template
sensors:
elektricity_meter_watts:
friendly_name: "Huidig Verbruik In Watt"
unit_of_measurement: "Watts"
value_template: "{{ states('sensor.electricity_meter_energieverbruik') | float * 1000 }}"`
i figured it out, did it like this:
- platform: template sensors: huidig_verbruik_in_watt: friendly_name: "Huidig verbruik in Watt" unit_of_measurement: 'W' value_template: >- {% set t = states('sensor.electricity_meter_energieverbruik') | float %} {{ t * 1000 }}
There's no meaningful difference between the two
Your unit of measurement was probably the problem
works for me, added you as friend here,
The unit of measurement is different
Yeah, was looking at the template initially
oh wow... didn't know HA has integrated list of units
If I want to control the state of a switch based on comparison to some temperature values, would that be done with a template or something else?
I want to turn my radiator valves on and off when the set value (I guess I'll use some sort of helper to input that?) is the measured room temperature +/- 0.5 degrees or so
I basically want to replace the logic in my smart TRVs because they're detecting temperature at the radiator and it's rising too quickly compared to the room temperature so the radiators turn off too soon.
Yes that's something you can do with a template
That I'll start taking a look tomorrow, bed time!
hi guys, very quick question as I've already spent a while fighting this issue. How to create a template helper of boolean 'or' of group of binary sensors. Should it be {{ state.binary_sensor.sth1 or state.binary_sensor.sth2 }} or perhaps states('binary_sensor.sth1') or perhaps is_state('binary_sensor.sth1', 'on') OR ... ? I'm unable to solve that
is_state('binary_sensor.sth1', 'on') or is_state(...
You can also do, states('binary_sensor.sth1')|bool or states(...
I'll try that, llama told me to try that:
sensor:
- platform: template
sensors:
example_binary_sensor_or:
friendly_name: "Example Binary Sensor OR"
state: '{{ (states.binary_sensor1.state | boolean) | or(states.binary_sensor2.state | boolean) }}'
which looks similar to your second answer
No dont do that.
sure
See the waning box at the bottom of this section: https://www.home-assistant.io/docs/configuration/templating/#states
thank you! it does work
Is it possible to make a relative threshold helper? I want to use it for hysteresis in my temperature switch.
So I have an input number to set room temp, then a template sensor to get the value of the input into the threshold helper but that requires absolute values as far as I can tell.
How do I limit a json response for weather where itβs only daytime is_daytime: true?
@odd flare I converted your message into a file since it's above 15 lines :+1:
The one I currently have doesnβt differentiate between either true or false : {{ state_attr('weather.noaa_weather', 'forecast')[0]['temperature']}}
Why do I get an error when trying to do this?
{{ now() - (states('input_datetime.alarm_time') | as_datetime | as_local) }}
what do you mean "it requires absolute values"? Post the template
I'm using the UI, the threshold helper asks for a minimum and maximum value
use selectattr
post the error
I ended up writing a template, it seems to be working fine; the PSU in my server just died now so my home is back to being dumb π
AttributeError: 'NoneType' object has no attribute 'tzinfo'
input_datetime.alarm_time isn't a valid entity_id then
Or it's time-only
it is time only
true
im just trying to show time remaining on that time
then use today_at()
FYI remaining time on that will only update once per minute
replace | as_datetime | as_local with | today_at
thats okay, ill try that
Alarm Time: 06:00:00
Time Remaining: 1:23:41.836484```
should be just 23ish hours
if the alarm is tomorrow, then you need to account for that by adding a day
today_at returns todays date
secondly, you won't be subtracting it from now, now should be subtracted from it
if it's in the future
oh I see, thanks
It seems to me that referring to the calendar would just make it more complicated than necessary...
{% set today = today_at() %}
{% set this_25 = (today.replace(day=25)).date() %}
{% set next_25 = (today + timedelta(days=(31-today.day))).replace(day=25).date() %}
{% set uncorrected = this_25 if today.day < 26 else next_25 %}
{% set wd = uncorrected.isoweekday() %}
{% set corrected = uncorrected if wd < 6 else uncorrected - timedelta(days= (wd-5)) %}
{{ (corrected - today.date()).days }}
Iβm already doing that, did you the example I shared?
I need to select the temperature attribute but on when daytime = true
please read what I said
selectattr is not state_attr
notice the entire difference in words
based on your response, I have a feeling you won't know how to use it
| selectattr('is_daytime', 'eq', True) | map(attribute='temperature') | first | default
what is the format of this timestamp 21:50:27.951358 and how do I get it into hours minutes
You have to perform the math
timedeltas do not have a format function
if it's under 24 hours, you can use .seconds | timestamp_custom('%H:%M')
if it's over, you can still use timestamp_custom but you'll have to specify days
you'd use .total_seconds() | ... instead of seconds
I must be doing something wrong, here is the output
Time Remaining: 21:39:09.469205
Timeremain.seconds 14:39
timeremain.total_seconds 77949.469246```
code:
{%- set timeremain2 = timeremain.seconds | timestamp_custom('%H:%M') %}
{%- set timeremain3 = timeremain.total_seconds() %}
Time Remaining: {{ (states('input_datetime.alarm_time') | today_at) + timedelta(days=1) - now() }}
Timeremain.seconds {{timeremain2}}
timeremain.total_seconds {{timeremain3}}
you probably need to provide false to the timestamp_custom to let it know it's local
that works, perfect! thank you so much
I am confused on one more thing, why cant the input_datetime display the value with AM/PM?
I also tried as_timestamp(states('input_datetime.alarm_time')) | timestamp_custom('%I:%M %p')
because the state is always in 24hr format in local time, so HA knows what it can expect to work with
try
{{ today_at(states('input_datetime.alarm_time')).strftime('%I:%M %p') }}
you can't convert a time only string to a datetime timestamp
hah, was just going to say
that works!
{{ today_at(states('input_datetime.alarm_time')).strftime('%-I:%M %p') }} for true 12 hour time
@mighty ledge in my cheapest energy macro the user can input the number of hours, I now added a function wich basically copies the data and splits the hours in parts based on this number of hours (in case it is a float).
So if eg the input is 2.25 hours, I want it split in 4 parts, and if it is 2.8 hours in 5 pars.
I have now used this, but I wondered if there might be a more efficient way (h is the number of hours)
{%- set minutes = (h % 1 * 60) | round(0) -%}
{%- set minutes = [minutes, 60 - minutes] | max -%}
{%- set div_list = [60, 30, 20, 15, 12, 10] -%}
{%- set ns = namespace(d=60, wp=1) %}
{%- for div in div_list %}
{%- if div <= minutes and minutes % div < ns.d -%}
{%- set ns.d = minutes % div -%}
{%- set ns.wp = (60 / div) | int -%}
{%- endif -%}
{%- endfor -%}
{{ ns.wp }}
So you're just finding the remainder and getting the lowest common increment?
.25 -> 4
.2 -> 5?
.4 -> 5?
for fractions basically
I use this to make fractions IIRC
but I don't think it's "better"
{%- set fractions = {0.020833: '1/48', 0.041667: '1/24', 0.0625: '1/16', 0.083333: '1/12', 0.104167: '5/48', 0.125: '1/8', 0.145833: '7/48', 0.166667: '1/6', 0.1875: '3/16', 0.208333: '5/24', 0.229167: '11/48', 0.25: '1/4', 0.270833: '13/48', 0.291667: '7/24', 0.3125: '5/16', 0.333333: '1/3', 0.354167: '17/48', 0.375: '3/8', 0.395833: '19/48', 0.416667: '5/12', 0.4375: '7/16', 0.458333: '11/24', 0.479167: '23/48', 0.5: '1/2', 0.520833: '25/48', 0.541667: '13/24', 0.5625: '9/16', 0.583333: '7/12', 0.604167: '29/48', 0.625: '5/8', 0.645833: '31/48', 0.666667: '2/3', 0.6875: '11/16', 0.708333: '17/24', 0.729167: '35/48', 0.75: '3/4', 0.770833: '37/48', 0.791667: '19/24', 0.8125: '13/16', 0.833333: '5/6', 0.854167: '41/48', 0.875: '7/8', 0.895833: '43/48', 0.916667: '11/12', 0.9375: '15/16', 0.958333: '23/24', 0.979167: '47/48', 1.0: '1'} %}
{%- macro fraction(value, count=0) %}
{%- set out = fractions.get(value | round(6)) %}
{%- if out is not none %}
{{- out }}
{%- elif count <= 1 %}
{{- (value // 1) | int }}{{ ' & ' ~ fraction(value % 1, count + 1) if value % 1 else '' }}
{% else %}
{{- value }}
{%- endif %}
{%- endmacro %}
actually, I really need to update that cause it throws out shit on the regular
@fathom yew I converted your message into a file since it's above 15 lines :+1:
you have to build the list in jinja, you can't build the yaml
OK, so that is building the list and then outputing it using {{ listVariable }}?
But why is the template entirely removed during store & reload?
because segments require a valid value and it removes the invalid things when you view it in the UI
if you keep it yaml mode, it iwll persist
The params are also just a Yaml field in the UI.
@fathom yew I converted your message into a file since it's above 15 lines :+1:
Hmm, also not stored when I edit it in the YAML editor in the UI. π€
I'll edit the script on disk directly and see what it does β¦
OK, storing the script on disk makes it unable to be edited in the UI. I guess this is due to the usage of a template at all? At least, HA does not complain when reloading the scripts.yaml
because you didn't indent the field correctly
field: >
{{ ....
you have
field: >
{{
@mighty ledge many thanks, that did the trick. I was fiddling for 2 days on this noob issue. π
OK, so now fighting again with actually returning a list from a template.
Awesome, needed some namespace() fiddling, but it works now. π₯³
I'm trying to debug a template that isn't working... what's the best way to do the equivalent of a console.log or something in the Template editor?
nvm think i found it
just do {{ }}
hello everyone. Is it possible to create template light with scenes? I have smart IR-RF remote which works with Tuya. I'm using official Tuya integration and IR-RF remote not supported by Tuya integration. I can only use this with scenes in Home Assistant.
You should be able to use it with service calls.
So automatons scripts scenes and anything that has an action section.
This had never occurred to me before. I'm new at codes. Thanks a lot. I'll try it.
my novice head cant find the error:
https://hastebin.com/share/somoqiyuxo.php
Template error: as_timestamp got invalid input when boxuur renders None
do variables listen to eachother?
or are they only made independently?
you aren't providing a default
it's the 3rd from the bottom pin
and to check for none, if xyz is not none
if you properly check for none then you don't need the default
can you push me a liiiitle bit in the right direction? syntax wise?
i literally gave it to you
right here
is not is syntax?
yes
k ill try it
ugh....
trigger.to_state.attributes.pickup_start what does this renders when the attribute doesnt exist ? none? null? devtools says None
i just want to get it to run the {% else %} part lol. but now it jumps to the as_timestamp default of 0
Can anyone boast about the template they created? I need some suggestions, I want to add a widget on the watch that will show some information in an interesting way than just text, and on the phone in the widget
Is it possible to "template" a template sensor helper so I can reuse it with different entities in an automation?
I have a binary sensor template that does some calculations based on a few entities and I want to reuse it for different entities in different automations
I have a string that I'm scraping with multiscrape in the format "[54m 0s]" where the minutes and seconds vary. I want to convert the string to a time in seconds that I can use for automations and statistics. I have had zero luck creating a value_template that gives me anything other than Unavailable. Any one know what I need to do? It seems like it should be very simple.
Not like that. But you could write a script that takes parameters and returns a result
Hi all,
I have a template sensor showing a cost, however when it is at 0.10 or 0.20 etc. it only shows 0.1 / 0.2 but I really need it show the 0 like 0.10. Hope that makes some sense and someone can help. Thanks
Hi. I'd like to set up a sensor which would store the highest value of another sensor during the past hour. I'd like it to update once on the hour every hour. What's the best approach here?
Easy way is the HA Daily sensor - https://github.com/jeroenterheerdt/HADailySensor
This seems to do what I need -- but can it shorted the interval to 1 hour from 1 day?
Yes the integration calls it refresh interval and you choose that - see picture https://ibb.co/8ddqQsR
OK! the reset interval had me confused. Thanks! Saves me doing some template/statistics frankenstein!
Is there not an option for display precision in the entity settings?
Hmm it seems the daily sensor doesn't quite do what I want, but maybe I have misunderstood something. If I ask for max sensor with a refresh interval of 60 mins, then the value of the sensor will change only if the max in the last hour is larger than the max in the whole reset period, i.e. the day. I then thought I could get it to reset every 60 minutes manually, but in that case the sensor does not actually have a state until it updates and then immediately resets.
Hey, is it possible to integrate a template string in the entities card? Someone can assist me with a example?
i trid these currentlly
type: entities
entities:
- entity:
data_template: state: {{ as_timestamp(state_attr('calendar.feiertage', 'next_date')) | timestamp_custom('%d.%m.%Y') }} - entity: sensor.schulferien_beginn_ende_indays
- entity: switch.turoffner
name: TΓΌrΓΆffner
show_state: true
......
No, you can't use templates in an entity card
someone who can help me out with following:
i have a siemens_logo plc where i configured some binary sensors which works fine now
now i would like to declare some sensor values holding uninsigned words (according to the holding registers help in logo siemens). i am getting some values like 8192 and 8183 or 0. Don't actually know what to try else. i have tried (u)int8, (u)int16, floats, now last i tried some custom:
sensors: - name: pomp_timer_seconds_auto # VW12 slave: 255 address: 11 data_type: custom structure: ">h" count: 1
Anyone aware how to make a button for a denon receiver volume limit??
When looking at media_player state, there is an entry called entity_picture.....but I cannot for the life of me figure out how to view/use it. IP:8123/api/path/and/token gives 404 not found - is there a trick to this
@zealous nebula what do you want to do - enable and disable a volume limit?
Yeah ideally have three buttons one that sets it to -20 another -10 and lastly -5
service: media_player.volume_set
data:
volume_level: .82
target:
entity_id: media_player.denon
is there a better way to do this: {{ ( as_timestamp(now()) - as_timestamp(state_attr('binary_sensor.pc_status', 'last_changed')) |int(0) ) <= 40 and states('binary_sensor.pc_status', 'on') }}
just want to make it true when the sensor has been ON for 40 seconds
(that code doesn't really work too well)
Thats to set volume. What i an referring to is the actual volume limit
Let me post the pic hang on
Actually cant but its on web ip of denon audio and volume limit
I don't see a command for volume limit
I have an automation that checks the volume and if it is over 82 set it to 82 but that would only partially give you what you want
See this thread with a similar question #templates-archived message
hmm I don't want it to be a trigger template though - just a wait template
last_changed is not an attribute, so this won't work
You can have it in a wait template, but 40 seconds will not work, as the template will only update once per second
{{ now() - states.binary_sensor.pc_status.last_changed <= timedelta(seconds=40) }}
sorry I forgot to say it does have that attribute
- name: "PC Status"
icon: phu:laptop-windows
availability: "{{ not is_state('sensor.pc_smartplug_watts', 'unavailable') }}"
delay_off:
seconds: 20
state: "{{ states('sensor.pc_smartplug_watts')|float(0) > 6 }}"
attributes:
last_changed: '{{ now() }}'```
The first part of the comparison only increases though, so if it isn't true at the first time it's checked, it will only be true after a new state change
That attribute will just update every minute
oh I thought it updates every state change
No, attribute templates are not only rendered on time changes, but what's the use of adding data which is already available?
thats true - I didnt know it was
will {{ now() - states.binary_sensor.pc_status.last_changed <= timedelta(seconds=40) and states('binary_sensor.pc_status', 'on' }} work?
It will only be updated once per minute or on a state change of the binary sensor
But if your binary sensor was turned on like 2 minutes ago, this will only be true after it first turned off and then turns on again
Hi, I got a gas sensor that is "total_increasing" and representing the gasmeter in kWh. What template/helper could I use to calculate a current consumption (maby over the last 5 minues) based on this data.
{% set test = "100" %}
{% if is_state(test, "100") %}
True
{% else %}
False
{% endif %}
Why does this template return "False" ?
To my understanding this code sets variable "test" to "100" and then checks if that variable is "100".
It should return "True" right ?!
{% set test = 100 %}
{% if test == 100 %}
True
{% else %}
False
{% endif %}
I think a variable has no state, but a value
That seems to be right. Thanks a lot!
You can shorten that.
{% set test = 100 %}
{{ test == 100 }}
Does anybody know if mediaquery can be used in templates?
Templates don't know frontend stuff
@outer sand I converted your message into a file since it's above 15 lines :+1:
how can I get the id of the object (eg climate.kitchen) inside a template switch?
So I know which object called it
Basically I have a lots of generic_thermostats and they all call their own separate switch template to do turn the relavant TRV on, but it is not very DRY at the moment
So was trying to get the generic_thermostats to all call the same template switch and then evaluate within that or at least pass the id into a script
Thanks
I'm thinking you probably can't do that from a single switch. But if you had multiple switches configured in the same way, you could use this.entity_id to identify that switches name and either use that directly or pass that to a script to differentiate
Ha, actually that is not a bad idea at all, that would be better than what I have for sure - thank you!
oh god I found why it wasnt working \\ inside "\\" becomes "\"
and in template tab it works because its not inside ""
Just looking at this now, would this.entity_id get me switch.kitchen_radiator or just kitchen_radiator ?
the first
The second one is the object_id
Can somebody help me to test whether a sensor state is a timestamp xx:xx - I have a sensor that return a time or "Error: Not enough data within current selection" I only wanna use the timestamp
What would be the best approach to test a condition(ex: last_changed) at a certain time (ex: 17:00:00), to see if it's true or false?
{{(as_timestamp(now()))-(as_timestamp(states.binary_sensor.car_status.last_changed)) < 600}}
Should it be today_at(value)?
Hello. I'm trying to create "template light" with scenes and the on/off codes worked but I couldn't figure out how to set the brightness value. I have a Tuya smart remote and it is not supported by Home Assistant. So I can only use scenes.
Can anyone help me?
I recognize that from my cheapest_energy_hours macro, are you using that?
yes
The value_on_error setting is added for that
Let it return a datetime in the future if it errors
This is my snip so far
{% from 'cheapest_energy_hours.jinja' import cheapest_energy_hours %} {% set s = cheapest_energy_hours('sensor.energi_data_service', hours=5, look_ahead=false, time_key='hour', value_key='price', time_format='time24', include_tomorrow=false) %} {{ now().strftime('%H:%M') == s }}
whats wrong with this template trigger, it runs in automations, next alarm registers fine from my phone, yet it has never triggered
{{ states('sensor.pixel_8_pro_next_alarm') | as_timestamp > now().timestamp() + 3600 }}
to fish - I feel stupid π
Im using it in an automation to charge my car...I want it to tell me the next cheap time..and not "error....."
Your snippet returns true or false, not a time, nor this error
Unless you shared the wrong template
Im using this:
- sensor:
- name: "Billigste 3 timer i dag"
state: >
{% from 'cheapest_energy_hours.jinja' import cheapest_energy_hours %}
{{ cheapest_energy_hours('sensor.energi_data_service', hours=3, time_format='time24', look_ahead=true, time_key='hour', include_tomorrow=false, value_key='price') }}
So yeah, there aren't 3 hours left in the current day, what do you expect it to return?
Maybe "Ikke fΓΈr imorgen" (No until tomorrow)
Then use that for value_on_error
That's where that setting is for, to replace the errors the macro returns with something you want
Thanks π
value_on_error=Ikke fΓΈr imorgen ?
- sensor:
- name: "Billigste 3 timer i dag"
state: >
{% from 'cheapest_energy_hours.jinja' import cheapest_energy_hours %}
{{ cheapest_energy_hours('sensor.energi_data_service', hours=3, time_format='time24', look_ahead=true, time_key='hour', include_tomorrow=false, value_on_error=Ikke fΓΈr imorgen ,value_key='price') }}
Quotes around your message
- sensor:
- name: "Billigste 3 timer i dag"
state: >
{% from 'cheapest_energy_hours.jinja' import cheapest_energy_hours %}
{{ cheapest_energy_hours('sensor.energi_data_service', hours=3, time_format='time24', look_ahead=true, time_key='hour', include_tomorrow=false, value_on_error="Ikke fΓΈr imorgen", value_key='price') }}
That looks better
To format your text as code, enter three backticks on the first line, press Shift+Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks.
```yaml
example: here
```
Don't forget you can edit your post rather than repeatedly posting the same thing.
You want it to trigger one hour before your alarm?
That's not what this is doing
Alarm at 10:00
Now is 9:15
10:00 > 10:15 == false
Now is 8:15
10:00 > 9:15 == true
So it will be true until one hour before your alarm
Basically you should use < instead of >
yeah, now I feel stupid, thx
But I would use
{{ states('sensor.pixel_8_pro_next_alarm') | as_datetime - now() < timedelta(hours=1) }}
sometimes you just don't see it
Hello. I'm trying to create Template Light. I created input.number for brightness and it works fine but I don't know how to enable scene based on brightness value. Can you help please? I can share my codes.
- platform: template
lights:
dolap_isigi:
friendly_name: "Dolap IΕΔ±ΔΔ±"
level_template: "{{states('input_number.dolap_arkasi_isik_sensoru') | int}}"
turn_on:
scene: scene.lumina_osram_ac
turn_off:
scene: scene.lumina_osram_kapat
set_level:
service: input_number.set_value
data:
value: "{{ brightness }}"
entity_id: input_number.dolap_arkasi_isik_sensoru```
I'm new to this. Can you write a little more clearly?
It can be a whole sequence of actions, exactly the same as an action sequence in an automation, include stuff like choose and if and scene.apply
Which basically makes this a question for #automations-archived
Thank you very much.
Does anyone know how to view or use entity_picture present in things like media_player
Hi , I'm using "<area name> <device name> ..." as my naming convention for all my device and entities.
It used to be, that the GUI would hide the <area name> part, if it is identical to the area the device is located in. Eg: "Keller Steckdose" would display as "Steckdose" in the area view. (The same way as Homekit does it btw)
However, this is not the case anymore. Everything ist show with the complete names everywhere.
I did not (knowingly) change anything, nor do I know if there is any setting for this behaviour. Any ideas?
That had nothing to do with #templates-archived I would say it's more a topic for #general-archived
Sorry, I tried to post to frontend and misclicked...reposted to #general-archived
thanks
Hello!
I am struggling a little bit.
I have an aqara mini switch which did not work as I expected. But I am trying to make a template to make it work like a push button where the signal stays 'true' as long as I hold the button.
I have found the states of action is hold and release. Hold is 'true' for some milliseconds when I hold the button and then is 'false' immidiatly after, and then the action state for release is 'true' for the same amount of time again after I release the button.
So I would like to make a template that changes the value of a binary sensor to 'true' when Hold == 'true' and only change the state of the binary sensor to 'false' when the release state is 'true' again.
I have tried with this:
{% if is_state('sensor.mini_switch_action', 'hold') %}
true
{% elif is_state('sensor.mini_switch_action', 'release') %}
false
{% else %}
false
{% endif %}
But it didnt work
It seems like it works, but since hold is immidiatly
'false' right after it doesnt work
Can I make the template ignore the 'false' values of my sensors?
In the logbook for the state action it changes to "hold" when holding the button, then changes to something like null or nothing, it just says nothing in the logbook. Then changes to release when I release the button, and then changes to nothing again. Not sure if its a nill value, null value or just "". Any ideas?
Mini switch action
Mini switch action changed to release
Mini switch action
Mini switch action changed to hold
Oh, yeah I think thats what I need help for
Not sure how to filter out those
{{ is_state('sensor.mini_switch_action', 'hold') }} returns the same as this
Yeah I figured that out
make a trigger based template entity that only triggers on hold, release
I think thats what I am trying to do...
template:
- trigger:
- platform: state
entity_id: sensor.mini_switch_action
to:
- hold
- release
sensor:
- name: blah
state: "{{ trigger.to_state.state }}"
if you want that as a binary sensor to skip your logic...
template:
- trigger:
- id: "on"
platform: state
entity_id: sensor.mini_switch_action
to:
- hold
- id: "off"
platform: state
entity_id: sensor.mini_switch_action
to:
- release
binary_sensor:
- name: blah
state: "{{ trigger.id }}"
Thanks! This worked perfectly!
Okay, now I just need to also be able to toggle the lights with the same button, when I click the button the action is "single" - how can I manipulate the same binary sensor to go from off to on and back again using this action? And at the same time maintain the function with hold and release?
Seems weird that I have to program a button switch to work like a normal pushbutton
It seems it wont work since I allready filtered out the "null" value I didnt want, now I need it again
Not sure I should try another blueprint for this, but I am using "Single on/off/dim switch" blueprint which is based off a binary sensor.
So I got the hold/release to work, but not sure the blueprint works without a pulse of "On/Off" transition when just pressing the button. Now the pulse-signal is ignored and the sensor is only listening to the hold/release
template:
- trigger:
- id: "on"
platform: state
entity_id: sensor.mini_switch_action
to:
- hold
- id: "on"
platform: state
entity_id: sensor.mini_switch_action
to:
- single
- id: "off"
platform: state
entity_id: sensor.mini_switch_action
from:
- single
- id: "off"
platform: state
entity_id: sensor.mini_switch_action
to:
- release
binary_sensor:
- name: blah
state: "{{ trigger.id }}"
You're over thinking it
just look at your available triggers
yeah but the release state is not there when releasing a short press
then its just single, then nothing
So I can turn it on with single
but not off again
right, that's why your 'off' trigger uses from instead of to.
see what I wrote π
np
Okay, more problems. But not a template problem this time... Not sure, but the blueprint automation seems to crash my zigbee network
sounds like it should go in the trash then!
#blueprints-archived can help, but more than likely, you'll need to consult the blueprint owner
i have an input_select with some brightness settings for a lamp (20 40 60 80 100) i can cycle through with a button on the wall. Now if i manually set it to say low, but the last setting of input_select was bright, and then i press the button, it jumps from low to bright.
How can i template something smart in the automation which first checks the current brightness, and then selects the first higher input_select?
i was thinking setting the input_select first to the lowest, then do an until loop where it checks the next_input select with the current brightess, until satisfied. Then continue with the automation of actually switching brightness
but that doesnt look 'smart'
to follow up on my own question. I made something which works, but i feel im missing safety's, making the loop go beserk?
(input select has values 0 50 100 150 200 255)
what makes you feel it's going berserk?
Like the light is offline not giving britness values. Or any other reason I cannot see
check out the automation trace I guess
Hi everyone, I'm in desperate need of some guidance π I was sent here from #automations-archived but honestly have no clue where to start π
I'm trying to pre-heat my car based on driving time to my next calendar event.
I have my car connected
I have my calendar connect (google)
I have Waze Travel Time
I'm fairly new to this so excuse me if I'm saying anything that's fairly dumb haha.
What I'm trying to do is:
Get the location of the next calendar event (location attribute of calendar.kconsen_gmail_com)
Calculate the travel time through Waze using that location as destination and device_tracker.teslanl_location_tracker longitude and latitude attributes)
Get the start time of the next calendar event, subtract travel time from sensor.waze_travel_time and an extra 15 minutes
At the calculated time start - (travel+15) set climate.teslanl_hvac_climate_system to ON
The below template evaluates to "0.3", I'm expecting "0.30". I suppose Jinja2 removes the last zero by default, is there any way to force this to show? (round(3) evaulates to 0.297)
{% set fixed_tariff = states('select.energy_tariff_ex_moms') | float %}
{% set cost = hourly_usage * fixed_tariff %}
{{ cost | round(2) }}
### Evaluates to 0.3, expecting 0.30
you're generating a float, which has no concept of trailing zeros. 0.3 == 0.30 == 0.3000
If you want trailing zeros, you'll need to convert it to a string, and then do string manipulation to add extra zeros on the end.
or use the UI to select your sig figs
just need a unique_id
on the template sensor
@forest ferry I converted your message into a file since it's above 15 lines :+1:
this obviously works but am trying to replace the input_select by a variable (inputselect) defined in the button_card_templates
device: '[[[ return states[''input_select.ir_remote_ex''].state ]]]'
the correct syntax is the last one:
device: '[[[ return states[variable.inputselect].state ]]]'
Might be variables.inputselect. The docs have examples of both π https://github.com/custom-cards/button-card
thank you! it was indeed "[[[ return states[variables.inputselect].state ]]]"
Then there are several bad examples in the docs. BTW, this isn't JInja and belongs in #frontend-archived
ok thank you, still learning both HA and Discord .... the docs didn't have examples with nested variables within "return states" that's why I was struggling with syntax. Thanks again!
Hello , can someone help me to create a value template please ? this is for this entity with the possible incoming values
entiteit : alarm_control_panel.mqtt_alarm ,
Values :
DISARMED disarmed
NIGHT_MODE armed_night
ARMED armed_away
mqtt:
- alarm_control_panel:
state_topic: "homeassistant/alarm_control_panel/state"
command_topic: "home/alarm/set"
is there a way to put a template in a template? {{ is_state(states('input_text.tv_active_entity'), 'on') }} the input_text.tv_active_entity is media_player.living_room_tv_andriod_tv and the input text changes to what TV is active
I want to check the status of the TV
full condition code is from a repeat is currently:
until:
- condition: template
value_template: >-
{{ is_state('media_player.living_room_tv_kd_75x8500e', 'on') or
repeat.index == 120 }}```
why does it take 5-ish seconds to finish this automation?
https://hastebin.com/share/takadiguha.yaml
i added 4 cores xeon to the HA VM
for this loop, must be sufficient LOL
kWh Sensor -> kW Sensor
this should work
How can I check if my light brightness is over a certain value?
I cannot get this template to work
{{ is_state_attr('light.office_namron_dimmer', 'brightness', '249') }}
but this gives the value 250
{{ state_attr('light.office_namron_dimmer', 'brightness') }}
I got it, cant use '
But, it only checks if its the exact value
{{state_attr('light.office_namron_dimmer','brightness')|int(0) > 249}}
This should be true if bigger than 249
Hi, long time ago, I used {{ currency }} in my templates and it appears that it's no more available. I cannot find how to access the currency set in global settings in my templates now. Any idea? Thanks in advance.
You can set the device_class to monetary in a template sensor (and maybe set the unit_of_measurement, if it doesn't use the global settings currency - not 100% sure if it does by default)
I just wanted to know if this variable is still available somewhere as it used to be. If I understand well your response, it means that it's not the case anymore, right?
At least I'm not aware of such variable - fwiw
Thanks a lot
how can I get all properties of a sensor?
I want to see if there is a "last_changed" or "last_value" eg
Go to the developer tools - states section
sorry for the noobish question, where do I put "templates" ?
im trying to place this card on my dashboard
https://community.home-assistant.io/t/ipp-printer-sensors-with-custom-button-card/250719
the OP has two parts, a card (which I have), and a template, which I don't know where to put
this is something for #frontend-archived
it has javascript templates, which are not the topic of this channel
Thanks Jorg
hey...
i want to track the amount of time my boiler fires for hot water vs heating
i've a "boiler on" binary sensor - i'll call that binary_sensor.boiler_on, plus sensors for heating on (sensor.wiser_heating) + hot water on (sensor.wiser_hot_water).
So i want to track the time heating is on + boiler is firing as one history stat
And similarly, hot water on + boiler is firing as another history_stat.
And I can do that bit - binary sensor to combine the two being the key bit.
The bit i am stuck with - if hot water + heating are both on + boiler firing, I want to split the boiler firing time 50/50 between the hot water and heating history_stats ideally. But I can't see any way to do this....
Any suggestions ?
If I have a sensor that is triggered by state change, I can access the old state via trigger.from_state.state. But if I have a second trigger that is time_pattern I can't get the old state. Is that right?
and how would I solve this problem?
I want to calculate a difference
at least every 10minutes eg
what's the problem? If it triggers on the time patter there is only a current state
there is no difference
you need to give more info here
because there is no state change at your 10 minute period
ok one moment I try to give some code
the change would always be 0
- trigger:
- platform: state
entity_id: sensor.gasverbrauch_in_kwh
to: ~
sensor:
- name: Gas ZΓ€hlerstand Diff
unique_id: gas_zahlerstand_diff
unit_of_measurement: W
state_class: measurement
device_class: power
state: >
{% set diff_seconds = (now() - trigger.from_state.last_updated).total_seconds() %}
{% set to_value_kWh = (float(trigger.to_state.state)) - (float(trigger.from_state.state)) %}
{% set to_value = int(to_value_kWh*1000*(3600/diff_seconds)) %}
{{ to_value if to_value }}
this one would never shot 0W if the state does not change any more
so I need to get back every 10minutes or so to look if there was a change
would it work to just check if it was a state change?
right but what you aren't understanding is that if there is no state change, and you just get the state, then you're just getting the state.
there's no to-state, no from-state, only a current state
I get you petro
so I just need to check if the trigger was by state or by time?
and if it was by time I return "0"
right
Can I check which trigger it was?
trigger.platform == 'a'
oh great
or by giving them a trigger id
fyi to_value if to_value doesn't really make sense
that is right, I simplified it while testing π
{% if trigger.platform == "time_pattern" %}
{{ 0 }}```
like this?
yes sure
assuming you left that out for brevity
thanks to both of you....
are you trying to get an accurate rate of change?
I just try to get approx value (maby in percent) of how much the gasheater modulates
It can do 1kW-11kW and I want to see if I can visualize it with this sensor
I will see if this works π
keep in mind that HA suppresses state changes if the state doesn't change
so if you get multiple zeros in a row, then your sensor will not have a 'new' last_changed
@cerulean karma I converted your message into a file since it's above 15 lines :+1:
all of HA does this
so any time a sensor updates w/ the same value, it does not produce a state change event
So how to deal with that?
you don't, you're stuck with how the system works
you can add a random value that's insignificant
also just to let you know, there's a derivative integration which does this math for you
you say I could use a better/ready sensor instead if doing this?
not sure what you're saying there, but there's an integration which gets you the rate of change of any sensor, it's called derivative
hmm ok
@mighty ledge my cheapest energy macro has a whitespace issue. Apparantly I have 330 %} but only 227 -%} so 3 of them are wrong
any chance you know how to find them using a regex search in VSCode?
So I want to have the %} without a hyphen (and they don't have a space before them, already searched for that)
found one, only 2 left
hmm, found the last 2, but still the same issue
too late, but I think this would have helped: [^-]%}
tried that, but it no dice
ok it is a VSC related problem...didnt get that
thanks anyway!
sorry, work got busy
needs the } escaping maybe... [^-]%\}
(?<!-)(%})
(?<!-)(%}|{%|{{|}})(?!-) for all
I am trying to create an automation using some templates but not sure how to use nested variables in other variables properly in Home Assistant. I have a lock in Z2M and the payload into MQTT contains the "action_user" who generated the event and I need to get the PIN of that user from the payload and then run it against a list of users assigned to PIN to get me the "friendly name" of the user who unlocked the lock. Here is what I have but not sure how to get the nested variable done properly.
@dense swan I converted your message into a file since it's above 15 lines :+1:
I was wondering if anyone had some examples to point me to.
I don't know what you mean you want to split the firing time
@dense swan
do you know the pin?
or is action_user the person who did the action?
I know the MAPPING of PIN to user, I want to resolve that used pin to the "friendly name" of the user during the automation run
Yup
action_user = slot in lock
So to clarify, we use the action_user to get the pin they used?
nevermind, i'll work with that
action_user = slot the lock used so then get the PIN of that slot.
and then resolve that PIN against a hash to convert 1234 to User X
I didn't want to maintain a list of slots since it could differ on locks
{% set user = payload_json.action_user | string %}
{% set used_pin = payload_json.users[user].pin_code %}
{{ pin_codes_to_names.items() | selectattr('0', 'eq', used_pin) | map(attribute='1') | first | default }}
Hmm interesting
if you made your pin to code names differently the code would be easier
e.g.
{% set pin_codes_to_names = [
{'name': 'User X', 'code': "1234"},
{'name': 'User Y', 'code': "5678"},
] %}
would be.
{% set user = payload_json.action_user | string %}
{% set used_pin = payload_json.users[user].pin_code %}
{{ pin_codes_to_names | selectattr('code', 'eq', used_pin) | map(attribute='name') | first | default }}
would be easier to read
not to mention, if this is in an automation variable section... you can just use yaml
pin_codes_to_names:
- name: A
code: 1234
- name: B
code: 5678
but you'd have to ensure the code is an int or enforce it as a string
pin_codes_to_names:
- name: A
code: '1234'
- name: B
code: '5678'
Interesting.
here's an example of it in action
(give me a sec)
then i use the config variable later on in the variables section
https://github.com/Petro31/home-assistant-config/blob/615d1e344fcd40f72a40dc2a597df2e300ce2410/automation/buttons.yaml#L95C15-L95C15
I see, thanks! Let me play with it.
π
New question, is there an easy way in Jinja to multiply the values of 2 lists of equal length with each other?
So [ 1, 5, 3] and [ 4, 2, 2 ] will result in [ 4, 10, 6 ]
I now use a for loop for that
heh, no
numpy can do that really easily
so if you use pyscript you'll be able to do that
it'll just be np.array([ 1, 5, 3]) * np.array([ 4, 2, 2 ])
π
Yeah, I found that
It's for the cheapest energy macro, you can assign a weight if you eg want to find the best time to turn on the dishwasher which uses most energy in the first hour
I'll stick to it loop then
yeah, I'd just loop it w/ namespace
variables:
user: >
{{ trigger.payload_json['action_user'] | string }}
used_pin: >
{{ trigger.payload_json[user].pin_code }}
pin_codes_to_name:
- name: A
code: '1234'
- name: B
code: '5678'