#templates-archived
1 messages · Page 52 of 1
Hi have anyone a template for a zha entity_id device list
#zigbee-archived message
you claim there the template doesn't work. What do you mean with that? The template works fine for me (using another integration, because I don't use ZHA)
"i need entity_idand friendly_name ...."
entity_id: {{b}}
friendly_name: {{state_attr(b, 'friendly_name')}}
Do you want the name of the Device or the friendly name of the Entity?
i've been staring at this for days. i'm trying to get my alarm on my phone to trigger... anything honestly. I've got the sensor entity for next alarm and I'm trying to use this template:
platform: template
value_template: >-
{{now().strftime('%a %h %d %H:%M %Z %Y') ==
(((state_attr('sensor.pixel_5a_next_alarm', 'Time in Milliseconds') | int /
1000) ) | timestamp_custom('%a %h %d %H:%M %Z %Y'))}}
I think it's because it's only updating by the minute (that's what the template editor suggests)
but adding :%S to the end of those values doesn't seem to fix it
I think you are trying to do this the wrong way. Do you have a sensor which contains the time of the next alarm? If so you should be able to trigger something based on the time of the sensor in an Automation.
platform: time
at: input_datetime.alarm_time
Is what i use to turn on the radio in the morning. Which is based on my calendar events.
every second is fine if you are using the date time unless you reguarly set your alarm less than one second before you want it to go off.
I ended up calculating a "seconds until alarm" value in a template sensor, because it seemed the easy way to be able to start things (like "sunrise simulation" lighting) a fixed duration prior to the alarm
unit_of_measurement: "seconds"
state: "{{ (as_local(as_datetime(states('sensor.xq_at52_next_alarm'))) - now()).total_seconds() }}"```
Means I can do "numeric state below 1800" as the trigger. Hasn't failed me yet.
In that case I would suggest to just create a template sensor with device_class: timestamp which has a datetime 30 minutes prior to your alarm sensor
I have a couple of automations with different offsets; heating/cooling gets adjusted at -1h, bedroom lighting at -30m, other house lights at 0m
okay, mkaes sense then
Yeah it's definitely ugly, but it's a nice one-size-fits-all solution
I would add an availability template for when no alarm is set (you will get errors otherwise) and exclude it from you recorder
@vagrant zephyr I converted your message into a file since it's above 15 lines :+1:
hi, i have a template sensor that is returning a float value, but when i view the device history in home assistant , it shows up as a bar chart of the numeric values (as if it was a string value), not a histogram / statistics graph like i want to see, is there something extra i have to do to this sensor to get it treated as a numeric value?
command_line today was error:
homeassistant.components.command_line.utils
['Command failed (with return code 1): cat /sys/class/thermal/thermal_zone2/temp']
|--> 08:32:24 Mon, 28-Aug
command_line.yaml:
#Nhiệt độ CPU máy chủ Hass
- sensor:
name: "cpu_temperature"
command: "cat /sys/class/thermal/thermal_zone2/temp"
unit_of_measurement: "°C"
value_template: '{{ value | multiply(0.001) | round(2) }}'
I use Intel NUC.
Thanks
Hi, I have got a energy sensor (reading values from a tasmota power smartmeter) that sometimes (ever 10+ days, so very rare) writes "unknown" instead of a value into the DB. The Sensor is total_increasing and so the next valid value leads to a jump from 0 (unknown) to ~6600 (which is the actual value). How could I take care that there only get valid values into the DB?
`- sensor:
- name: Strom Zählerstand
unique_id: strom_zahlerstand
unit_of_measurement: kWh
state_class: total_increasing
device_class: energy
state: >
{% if is_number(states('sensor.tasmota_mt681_total_in')) %}
{{ float(states('sensor.tasmota_mt681_total_in')) }}
{% else %}
{{ float(states('sensor.strom_zahlerstand')) }}
{% endif %}`
I would use a trigger based template sensor:
- trigger:
- platform: state
entity_id: sensor.tasmota_mt681_total_in
to: ~
sensor:
- name: Strom Zählerstand
unique_id: strom_zahlerstand
unit_of_measurement: kWh
state_class: total_increasing
device_class: energy
state: >
{% set to = trigger.to_state.state %}
{{ to if to | is_number else this.state }}
hey that looks great, I will try that directly
thanks 🙂
It needs an initial state change from the source sensor to get a first value after you changed it
It seems so work fine
And what is the important point of this template that there will be no bad values any more?
...as said this occurs only every 10+ days. So I need to wait a few weeks to be sure it works as I am hoping
Thanks a lot
{% set a= integration_entities('zha') %}
{% for b in a %}
entity_id: {{b}}
friendly_name: {{state_attr(b, 'friendly_name')}}
{% endfor%}
{{ to if to | is_number else this.state }}
That part checks if the new value is a number (which unknown is not) and if that is not the case, it will return the current state of the template sensor (this.state)
ok fine, thanks
Don't know why I didn't try this earlier. Thank you
@marble jackal the use of this.state is new to me, is the use of it right in this template? I just used {{ 0 }} in the else statement...
`- sensor:
- name: "Absolute Luftfeuchtigkeit oben"
unique_id: "AbsoluteHumidityOben"
unit_of_measurement: "g/m^3"
state_class: "measurement"
state: >
{% if is_number(states('sensor.temperature_humidity_sensor_2f20_temperature')) and is_number(states('sensor.temperature_humidity_sensor_2f20_humidity')) %}
{{ ( 1000*e**(19.016-(4064.95/(float(states('sensor.temperature_humidity_sensor_2f20_temperature'))+236.25)))100/(461.66(float(states('sensor.temperature_humidity_sensor_2f20_temperature'))+273.15)) * float(states('sensor.temperature_humidity_sensor_2f20_humidity'))/100 | float) | round (1) }}
{% else %}
{{ this.state }}
{% endif %}`
this.state refers to the state at the moment the template is rendered (for trigger based template sensors the moment of the trigger)
looks fine this way
ok thanks 🙂
Hey could someone pleas help me figure out what i am missing? I have the following sensor:
last_soil_humidity: value_template: > {% if has_value('sensor.diymoresoildht11_analog_range1') %} states('sensor.diymoresoildht11_analog_range1') {% else %} states('sensor.last_soil_humidity') {% endif %}
and my frontend shows it as a string :/
So my history is saying my value is states('sensor.diymoresoildht11_analog_range1')
these lines need to honor pin 2
states('sensor.last_soil_humidity')
states('sensor.diymoresoildht11_analog_range1')
Sorry but what does "honor pin 2" mean?
Oh wow sorry I am new to discord - now I see that I'm missing {{ }}. THX!
yah, sorry, was away from pc. That's what I was referring to.
Derive Three-Phase Motor State
Can I generate attributes in a template sensor dynamically using a loop? I have a rest sensor with attributes that could change on the fly. I would use a template sensor to summarize the data.
It's a flight price API
anybody have trouble with command_line cpu_temperature on Intel NUC?
@crimson lichen I converted your message into a file since it's above 15 lines :+1:
Not that attributes itself, but you can create a dynamic dict in an attribute
needing to set an input_datetime programmatically, I noticed that {{as_timestamp(state_attr('script.slapen_select','last_triggered'),0) |timestamp_custom('%H:%M',default = none)}} does not set the correct year 😉 what would be the best format to do that? Testing {{as_timestamp(state_attr('script.slapen_select','last_triggered'),0) |timestamp_custom('%Y-%m-%d %X',default = none)}} gives the right format, but not sure if this is only in template editor. Seems so terribly verbose/hacked/complex...
to get the idea:```
trigger:
platform: state
entity_id: script.slapen_select
action:
service: input_datetime.set_datetime
target:
entity_id: input_datetime.sleeptime_today
data:
time: >
{{as_timestamp(state_attr('script.slapen_select','last_triggered'),0)
|timestamp_custom('%H:%M',default = none)}}
aargh, now seeing this copied automation only uses the time: option. I guess the timstamp option woukld be more complete.... {{as_timestamp(state_attr('script.slapen_select','last_triggered')|as_local)}}
yep, this seems to work alright, (without the as_local):
action:
service: input_datetime.set_datetime
target:
entity_id: input_datetime.sleeptime_today
data:
timestamp: >
{{as_timestamp(state_attr('script.slapen_select','last_triggered'))}}```
why not use the datetime option:
action:
service: input_datetime.set_datetime
target:
entity_id: input_datetime.sleeptime_today
data:
datetime: >
{{ state_attr('script.slapen_select','last_triggered') }}
that attriubute contains a full datetime object
indeed, why not!. I had missed that too... 😊 much better.
How might I do that? Here's an example of the data I want to summarize.
https://dpaste.org/XzTvi
template:
- sensor:
- [ ... ]
attributes:
flight_summary: >
{{ create dict here based on data rest sensor }}
Perfect I was thinking about something like that. Is there a way to track history of an attribute? I would make another attribute that selects the lowest price for example.
I have a very annoying tuya light that claims to only support hs color mode.
In reality, what it really supports is rgb and white with a color interlock.
The result is that HA and everything that relies on it cannot turn the light to its white LEDs through the GUI or voice interfaces (at least through Alexa or homekit).
This means I can request the light turns white, but it will just engage the RGB LEDs in a 255,255,255 state.
Today I realised that I can call a service, light.turn_on with an RGBW value of 0, 0, 0, 255 and to my delight the LEDs in question interpret this well enough to turn off the RGBs and turn on the white LEDs. It's curious that it accepts an RGBW value at all with an interlock though. Setting any of the other three values to anything but 0 will result in the RGB lights coming on and the white turning off. I attempted and confirmed that specifying white: true does not work.
Anyway, to my question. After discovering a way to trigger the white mode with the RGBW value, I wondered if I can wrap the bulb in a Light Template. I specifically want to recreate it with relevant services and specify the specific supported_color_modes: ['rgb', 'white']. I've been looking at the docs here: https://www.home-assistant.io/integrations/light.template but I don't see any mention of specifying supported color modes, so figured I'd ask if this is a use case that makes sense for template lights 🙂
you can't add supported modes without changing actual code
Your best option is to create a template light and try to provide all the information you'd like, with templates
...so, the thing I'm asking then. That'll be a yes?
Yes, but you don't define what it supports
you define what's available for the light by filling out the yaml
that will in essence change "what color modes are supported"
i.e. you're trying to change something that's automatically created by the configuration
Goodo, I'd wondered if that would be the case. It says that the other default values are "optimistic" which made me worry it was just going to tell the lovelace card to show all possible elements whether appropriate or not 😅
you do not want optimistic
looking at the docs, it's not supported for light templaets anyways
ah well, never mind then. For now I've just stuck an extra button under the cards in question that activates white mode. Normally it's never a problem but every now and then a 3 year old charges into my garden office and screams "'lexa, make lights purple!" and I'm stuck on RGB until I figure it out.
personally, I avoid TUYA products because of these types of reasons
They don't have a API that devices adhere to
Me too, this is one of my earliest devices that I just haven't managed to sort yet. I've managed to flash or hack most of them but I can't seem to get that libra ESPHome solution to flash on this stupid chip. That may be my poor soldering skills to be honest though, it just doesn't seem to want to connect.
I also find it really weird that there's all this fear over 5G and huawei spying on us, but never a peep about the endless tuya devices folk are plugging into their homes. I swear if things ever did go to shit with China, they could just overload our power grids by turning all our smart plugs and lights on at once 😅
never even heard of this huawei thing
I'll have to look it up
luckily I don't have any of those devices, however I do have like 304298349823 cheap chinese chip DIY projects
Oh yes, pretty much all the world's 5G infrastructure (masts, dongles, routers) for a long time could only be set up using Huawei equipment. I believe when Trump was in power and was rilling them up he sought a ban on Huawei 5G equipment, I'm not sure if it happened in the end but it seems it was taken seriously enough that even here in the UK the parliament discussed banning it too and several other countries were concerned about it. Seemingly there's a fear china can listen in to 5G network traffic. Something they deny of course and I don't know if any evidence was ever shown, but being proprietry equipment it seems it was enough to get NSA and GCHQ worried about it.
It just always seemed odd to me that they considered that a threat without any real evidence to prove it, but not the fact that these cheapy tuya smart devices we're all installing require server side control by a Chinese company and those most certainly aren't hiding anything about it.
Yep, the logic is not there...and then to know that those that spy on the 'western' world are esp. the USA and UK 🙂
Oh wow, seems a ban was indeed enforced here in the UK too. Apparently all 5G public networks have to strip out Huawei hardware by the end of 2027. https://www.gov.uk/government/news/huawei-legal-notices-issued
All to protect local interests
I spy better than you spy
anyhow...not for this thread
The new modem my 5G provider sent out recently got rid of my old Huawei one and is a Zyxel one. The bottom says they're based in Denmark. Most odd. But yes, not really the forum for this 😅
Does anyone know if we can get history of attributes of a sensor and use that data in templates?
no
Is there a workaround to achieve this? Backstory is I'm tracking flight prices and I would like to know when the price is the lowest in the last x days and then I would send a notification for example.
I would create a few statistics sensors to grab the minimum value over X, Y, Z days and then probably have some automations around those.
Nodered can do it.
This one, for instance, tells me my off-peak electric rate by giving me the minimum value in the last 24 hours:
unique_id: off_peak_electric_rate
name: "Off-peak electric rate"
entity_id: sensor.octopus_energy_electricity_current_rate
precision: 3
state_characteristic: value_min
max_age:
hours: 24```
I have never used nodered. I might go down the statistics sensor or history sensor route. I was trying to avoid creating a bunch of sensors but it's better than nothing so I can know I am getting the best price. The beauty of ha is I can do this myself with a free API rather than paying some company to tell me the best price lol.
Sounds like you're just trying to recreate SkyScanner and they don't exactly charge a subscription 😅
I'm using kiwi API.
I've been using it less and less lately as automations improve, but when I want to do some complex coding operation or operating on arbitrary sets of history data i think it's still my favorite option.
Good to know.
you'd have to use SQL sensor
if the api gives you a list of past flights, then you can just use a normal template
There's an SQL sensor? How have I not known about this?! Oh this opens up so many doors 😄
there is
For some reason I thought Skyscanner wasn't free.
Ooo i found the doc page. Exciting!
I only use it for database size
Yeah it doesn't give a list of past prices but if Skyscanner does I'll look into that
How would I do this with getting the attributes of a sensor rather than state?
you'd have to come up with the query
I have some input_boolean sensors(lets say A, B and C), and I want to set a template sensor based on these rules: if A and B set sensor S = 'partial', if A and C set S = 'partial', if A B and C set S = 'total', how can I do it? But I have around 10 input_boolean sensor, so basically S will be 'total' only when all of them are set
it is 'total' only when all are on, when one or more are off it is partial, when all are off it is 'off'
well. it would bbe nice when it is partial to show the entity frieldy name that is on, but I am not sure if there is a fancy way to show them in a card
'on' I assume it is 'total'
{% set booleans = ['input_booean.1', 'input_booean.2', 'input_booean.3', 'input_booean.4'] %}
{% set cnt = booleans | map('states') | map('bool', False) | reject('false') | list | length %}
{% if cnt == 0 %}off
{% elif cnt == booleans | length %}on
{% else %}partial
{% endif %}
why not just use select('eq', 'on') after mapping it to state?
sure
what does the reject('false') do exactly?
it rejects the items which have value False from a list
ah get it, thaks
ok, I tested it and it works, but I notice a small issue, since not all input_boolean sensors are updated in sync, it will pass from off to partial and then total or from total to partial and then off, is there a way to add a sort of delay to make sure that all input sensors are updated? they are in max 1 second
Hey! I'm trying to add a graph of electricity prices to a notification triggered by an automation:
{% set prices = (states.sensor.nordpool_ee.attributes.raw_today +
states.sensor.nordpool_ee.attributes.raw_tomorrow)
| selectattr('start', 'gt', now()) | list %}
{% set labels = prices | map(attribute='start') | list %}
{% set data = prices | map(attribute='value') | list %}
https://quickchart.io/chart?c={type:'bar',data:{labels:{{labels}},datasets:[{label:'Price',data:{{data}}}]}}
I'm struggling to figure out how to format the date, so that I can have nice labels for my chart. Is there a filter to run an arbitrary python command, such as strftime on each element in a list, or a built-in filter formatting date somehow? Ideally, I'd like to do something like this
{% set labels = prices | map(attribute='start') | map('strftime', '%a %H:%M') | list %}
to get labels like Tue 23:00, Wed 00:00, Wed 01:00 etc..
I've also thought about creating a separate list by iterating over the prices and storing the values in a list, but HA does not allow appending elements to a list >.< https://github.com/home-assistant/core/issues/33678
Rubber duck debugging ftw. As I was typing "does not allow appending elements to a LIST", I figured that I can append to a string 😄
This works:
states.sensor.nordpool_ee.attributes.raw_tomorrow)
| selectattr('start', 'gt', now()) | list %}
{% set data = prices | map(attribute='value') | list %}
{% set labels = namespace(value='') %}
{% for state in prices -%}
{% set labels.value = labels.value + "'" + state.start.strftime('%a %H:%M') + "'," %}
{%- endfor %}
https://quickchart.io/chart?c={type:'bar',data:{labels:[{{labels.value}}],datasets:[{label:'Price',data:{{data}}}]}}
Here's how it looks: https://quickchart.io/chart?c={type:'bar',data:{labels:['Tue 23:00','Wed 00:00','Wed 01:00','Wed 02:00','Wed 03:00','Wed 04:00','Wed 05:00','Wed 06:00','Wed 07:00','Wed 08:00','Wed 09:00','Wed 10:00','Wed 11:00','Wed 12:00','Wed 13:00','Wed 14:00','Wed 15:00','Wed 16:00','Wed 17:00','Wed 18:00','Wed 19:00','Wed 20:00','Wed 21:00','Wed 22:00','Wed 23:00',],datasets:[{label:'Price',data:[0.0541, 0.054, 0.0948, 0.0805, 0.0805, 0.0805, 0.0948, 0.1169, 0.1526, 0.173, 0.204, 0.1941, 0.192, 0.1669, 0.1765, 0.1765, 0.1913, 0.1764, 0.1981, 0.1718, 0.1729, 0.2187, 0.2094, 0.1613, 0.1399]}]}}
Is there a way to change a light. Entity to either a fan or switch? I know there’s a helper to change a switch to those but I’m not sure how to go the other way around.
@vagrant zephyr I converted your message into a file since it's above 15 lines :+1:
the problem is that states are always strings and you're doing ascii math
this:
states('sensor.jordan_phone_battery_level') < "85" needs to be states('sensor.jordan_phone_battery_level')|float < 85
and by putting that first, you'll never hit the second case
you need to flip the order of the first two
you can also not repeat yourself so much..
nest the "if" statement for charging or not, set a variable for the battery_level
Thank you I'll try that, wasn't sure what float meant wheb seeing it being used
anyways, if you ever come over to this channel, the proper way to get /<minutes> via a template trigger that works with all intervals is...
{{ ((now() - '2023-08-30T00:00:00' | as_datetime).total_seconds() // 60) % states('input_number.aquaponics_cycle_interval') | int == 0 }}
but keep in mind that it will not work with an 1/minute. No template sensor will do that because of how templates are designed
I thought it was using the minutes of the hour.. guess I was wrong 🙂
you an also use any date in place of '2023-08-30T00:00:00' to get your desired minutely repeating
But it does make it more reliable than I thought it was
Your template does, but the problem is when you us /7 lets say, passing the hour will not work
you'll have a hiccup
modulos?
I also learned how to work work dictionaries in Python, which is a breeze compared to jinja
yes, jinja sucks for dicts
it's all because jinja is designed to not create new memory, it just want's to traverse existing memory
No I thought /7 would just trigger at X:07, X:14 etc, same every hour
It will
but then between 56 and 7 will be more than /7
that's an 11 minute gap
if you truly want /7, then you have to use an always increasing number
0 is also devisable by 7
yeah, still same principle, you'll have a 4 minute gap, point is, it's not actually /7 when you use now().minute
No, okay, I understand that
if you want to be really lazy you can use timestamp, but you can't alter the seed date
{{ (now().timestamp() // 60) % ... }}
But with the paint pattern trigger, will it use the minutes since 1970/1/1 00:00 UTC?
With an uptime sensor you could really replicate the time_pattern trigger behavior then
Yep, well within reason
can't go below 2 minutes 😕
you could with a template entity that uses a time_pattern trigger.
a 1 minute increment would always be true with a template
You can do a trigger on a 1 second time pattern and use the input_number as a condition if you need more than a 1-minute resolution
right, essentially the same as a template entity w/ trigger, but it wouldn't have extra traces in the automation editor for each 'failed' condition
But that gets a little excessive to have an automation triggering every second imo
that shouldn't matter tho if your lowest increment is 5
also, tinkerer's idea of an automation that schedules the next time might be another way to go
the downside is that it might get wonky after a restart
Right. I scaled back the input_number to only go up to 30 so that I wouldn't have to worry about wonky intervals that go over an hour.
as long as 60 is divisible by the increment, you should be good. Truncating it at 30 makes 25 the only wonky one. It'll trigger at 0, 25, 50, and then 0 again
all the other increments start and end at 60
Here's what I've gotten so far, and it seems to be working just fine. I only need it to run every 30 minutes at most, anyways. Anything lower would be a special case. https://github.com/Apocrathia/home-assistant-config/blob/master/packages/projects/aquaponics.yaml
Hello beautiful people, I think this is a Template question. I have created a ESPHome IR Remote Climate device but would now like to use a Xiaomi temperature sensor in conjunction with it. I have seen 1 way and that is to link the Xiaomi sensor to the ESP device with BLE but that's not an option here. So, Is there a way to create a thermostat using both these items together?
unfortunately, there is no "template climate" integration
You can however use generic thermostat integration which might get you what you want without templates
anyone know how to use wildcard?
was going to do an automation on the first of every month
{{ now().date() == "x-x-01" }}
now().day == 1
that was easy, thanks
I'm unsure what to use for the "controller data"
I'm not sure what youmean?
I'm guessing somehow I need to get the Generic Thermostat to talk to/send commands using the climate.officeir_office_ac entity I have created
if you already have a climate entity, why do you want a second climate entity?
sounds like you just want an automation?
Beacause I need a temperature reading tied to it for setpoints
ah ok, yes that would be generic thermostat, but it proabaly isn't what you want
and I don't think what you want exists
😦
anyways, read the documentation I linked, it covers how to set up generic thermostat, but make sure you read what it's meant to do
Yeah I have used it before and it works fine for things like broadlink ir using smartir etc but as you said it doesn't look it supports ESPHome IR Remote Climate
could be worth me making a feature request
if the behavior does what you want, you can make scripts
Way above my pay grade LOL
if you can use generic theromostat, you can make a script
it's all through the UI
and any templating issues can be solved here
make a script, use that in generic thermostat
is this the right way?
{% if now().day == 1 %} {% endif %}
in a conditional template?
thanks
Do you mean a template condition? https://www.home-assistant.io/docs/scripts/conditions/#template-condition
{{ now().day == 1 }}
so to trigger an automation on the first its as simple as this?
`trigger:
- platform: time
at: "00:00:01"
condition: - condition: template
value_template: "{{ now().day == 1 }}"`
Or just use a template trigger:
trigger:
- platform: template
value_template: "{{ now().day == 1 }}"
There's no need to trigger every day just to check if it's the first.
Isn't that going to run the template once per minute forever? I feel like maybe time trigger might be more efficient?
No his was a time not time_pattern trigger
I know but you're proposing a template trigger, with now(), which I think will be executed once per minute.
Yep, you're right 🤦♂️
I moved all those kind of things to calendar event triggers
It’s negligible tho
The template listener is going to run regardless how many times it runs the template
If it was doing heavy math I’d avoid the template trigger
After I understood that the threshold helper cannot do this, I have been directed here towards creating a template for a binary sensor that works like a threshold sensor, where the upper limit can be set via a slider or a +/- field in the dashboard (like a numeric input helper) - the problem is....I have zero clue how to even approach this, and code is very hard for me, so I am grateful for any hints or code snippets that can help me
Secondly, I wanted to ask if this template sensor is universal, just like a helper that I can add to any automation, or if I need to code it separately in all my automations
Threshold is a binary sensor, so you will want a Template binary sensor (https://www.home-assistant.io/integrations/template#state-based-template-binary-sensors-buttons-numbers-selects-and-sensors) . If you can share a more specific description of what you want to do it will be easier to help you. Once it is configured and loaded, you will have a binary sensor entity that can be used in automations just like any other binary sensor.
Thank you!
Well essentially I want it to turn on when a certain temperature is exceeded on a sensor (sensor.temp_bedroom_temperature), and turn off when the temp of the sensor drops under the 'threshold' (Fan Set Temp). Now the actual threshold value I want to be able to set it from the dashboard, either as a scale (22-29 degrees C for example) or as a number with +/- signs. I noticed that a very simple implementation is having a numeric input helper (input_number.fan_set_temp_bedroom) to do that
Does this level of detail help more?
We need to know how you want the output to be mapped. Is the goal to have it turn "on" as it crosses the upper limit then "off" only after it crosses the lower? Or should it only be "on" between the two set points?
Oh, that is simple - I only want the upper limit - so it should turn on if the value is higher than the input value - in that respect I don't even care about the threshold - if it is higher than the input_number then be 'on', otherwise be 'off'
The most basic configuration for that is:
template:
- binary_sensor:
- name: Bedroom Fan Threshold
state: |
{{states('input_number.fan_set_temp_bedroom')|float <
states('sensor.temp_bedroom_temperature')|float}}
Edit: Fixed typo. Thanks Rob
whoa!! thank you! @haughty breach - just so I understand better...even if input_number is a number it has a "state"?
All entities have a state
Trying to translate this in something I understand, please correct me if I am wrong:
Create a binary sensor template named Bedroom Fan Threshold
The state of which is a ....value template? where the state of input_number < sensor temp bedroom - I am guessing the < means that it turns "on" if the sensor number is higher than the input
thank you kindly @haughty breach and @inner mesa
hi again. so i wanted to create a template to display the state of a sensor a month ago. and thanks to your help i got it to work, this is what i got so far:
{% if now().day == 1 %} {{ states('sensor.day_02') }} {% endif %} ... {% if now().day == 30 %} {{ states('sensor.day_31') }} {% endif %} {% if now().day == 31 %} {{ states('sensor.day_01') }} {% endif %}
but i realized this is not going to work for certain motnhs..?
is it possible to combine now()day and now()month in some way?
thanks!
What about something like:
{% set d_num = (now() - timedelta(days=30)).day %}
{% if d_num in range(1,10) %}
{{ states('sensor.day_0'~d_num|string)}}
{% else %}
{{ states('sensor.day_'~d_num|string)}}
{% endif %}
{{ states('sensor.day_' ~ ('%02.f' | format(now().day))) }}
timedelta() is the key, along with a format-string, but maybe this is solving the wrong problem. Why is the data in 30 sensors
Because SQL is hard... 
Dude it ain't too hard. Maybe restart your problem. Maybe the hive-mind can suggest better solution.
Oh you're not the OP ignore 😉
can use a SQL sensor to pull accurate values from states. Magic!
But OP @summer salmon hasn't answered why his data is so screwey
i agree with you guys, im new at this i have no clue what i am doing
take a step back - explain why your data may be in ~30 separate sensors?
then maybe we can suggest a good solution
where did the data come from?
now this is just embarrasing lol
i dunno, i have always stored my data in seperate sensors ike this and never had any issues so have not really seen a reason to not do it.
but thanks for your advice i'll read up on sql and get my shit togetger
We're happy to help, no need to be embarassed.
In the meantime here is code that incorporates both timedelta and the format string and should work for you
{{ ('sensor.day_' ~ ('%02.f' | format((now() - timedelta(days=30)).day))) }}
There’s probably a more elegant way tho
{{ 'sensor.day_%02d' % (now() - timedelta(days=30)).day }}
@summer salmon where does your data come from? how do you store it? interested
@summer salmon if your data is in sensor.day_01 to 31 (day of month) and you want to retreive the one for 30 days ago, a one-line sensor is:
{{ states('sensor.day_%02d' % (now() - timedelta(days=30)).day) }}
thanks guys, its appreciated.
i store ny data in utility meters with calibrate.utility meter service calls with automations. i have always known this is not the correct way to do it, but its beginner friendly and as i said... i never had any problems actually.
you guys rock by the way
Not sure I understand. Screenshots? I never used the service on utility_meter fwiw
since you are curious it all started with me making a sensor to calculate the cost per day of diffrent devices, my electricity price changes every hour (no peak price, its actually 24 different prices per day)
so i did
{ (states('sensor.kwh_last_period')|float(0) * states('sensor.elec_price_last_period')|float(0)) | round(3)}}
and stored that data in 24 diffrent sensors. and added them together with a helper. maybe it sounds weird but it was really easy, even for me lol
Do you want help "fixing" that? Or want to solve with the data you have?
im only doing this cause i think its fun, i want to learn as much as possible. your more than welcome to send me a DM with your thoughts, i sadly have to run to work now. and as you might presume i dont work with anything computer related lol
(with current data) I would probably try and implement it using a SQL sensor, or maybe via REST API to access history...
If you know that only one record per day is added to the sensors data, you can fetch the 30th-to-last value with something like
SELECT * FROM states
WHERE metadata_id = (SELECT metadata_id FROM states_meta where entity_id = 'sun.sun')
ORDER BY state_id DESC
LIMIT 30, 1
Hi Guys, I have a quick tile setup on my android phone that opens and closes my garage door. But it's only a momentary switch so guess back to off after half a sec. It's there a way to have the quick tile state be based off a door sensor I have on the garage door?
Dumb templating question- trying to pull calendar events from multiple calendars into a single sensor. Following the logic in this thread but since I have multiple calendar.list_events services, I wind up with duplicate nested attibutes:
https://community.home-assistant.io/t/how-to-list-multiple-calendar-event-in-a-template/349139/39?u=skelso
My event data winds up looking like:
`data:
scheduled events:
- events:
- start:
summary
- start:
- events:
- start:
summary
- start:
- events:
- start:
summary
I want:data:
scheduled events:
- start:
- events:
- start:
summary - start:
summary - start:
summary`
- start:
@summer salmon (phew!) I've got a solution for you. It involves using a SQL sensor to query the state table in the DB.
It finds the right sensor to use by using DATE_SUB functions in SQL plus DATE_FORMAT('sensor.day_%d')
Then selects the first value that's at least the right age...
TLDR: add the following to the bottom of your configuration.yaml and restart HA
sql:
- name: Old Data
query: >
SELECT states.* FROM states
INNER JOIN states_meta ON states.metadata_id = states_meta.metadata_id
WHERE states_meta.entity_id = DATE_FORMAT(DATE_SUB(NOW(), INTERVAL 1 MONTH), 'sensor.day_%d')
AND last_updated_ts < UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 1 MONTH))
ORDER BY state_id DESC
LIMIT 1
column: "state"
tested on mariadb, but I assume sqllite will be the same...
hmm, maybe it isn't. let me know which DB you have.
The sensor-select part will be something like
strftime('sensor.day_%d', date('now', '-1 month'))
and the date filter will be something like
AND last_updated_ts <= strftime('%s', 'now', '-1 month')
Hi all, is there an easy way to print out the list of enabled entities for a given integration?
I was thinking of putting it in the template editor to print out all my Shelly entities that are enabled. I am switching away from the community integration and back into native, but wouldn't want to break all my dashboards and automations, so would like to keep track of the names.
I came across the general template, though struggle with adjusting it to print out just specific integration entities:
{% for state in states -%}
{{ state.entity_id }}
{% endfor %}
???
Nevermind!! Found this {{ integration_entities('smartthings') }}
It could only use an enabled entity filtration
Currently it spits out all.
Wow thats amazing. Cant Thank you enoigh! Will take a more detailed look at this when i get home!
Trying to figure out whats wrong with this automation. I'm fairly certain it's something in the current_volume section. https://dpaste.org/61yZB
Error while executing automation automation.office_dial_rotate: TypeError: can only concatenate str (not "float") to str
@half pendant My guess is this: new_volume: "{{ max(0, min(current_volume + (volume_change | float), 1)) }}"
BTW there is nothing secret about device id's they are just randomly generated by HA when you integrate them
same with the numbers for entity id in the device stuff as of last month
The error caused by you placing quotes around the templates in the current_volume variable
you are outputting a string with the template, not the result of the template
@half pendant I converted your message into a file since it's above 15 lines :+1:
yes, I just explained why
So it should be current_volume: |- {% if state_attr('media_player.homepod_mini', 'volume_level') == 0 %} {{states('input_number.office_tv_last_volume_level') | float}} {% else %} {{ state_attr('media_player.homepod_mini', 'volume_level') | float }} {% endif %}
correct
are you sure the volume_level is still reported when the device is off?
Google devices don't
the homepods are never off. They are always on. I had an issue with the apple tv not reporting volume level sometimes so i switched to the hompods (they are all connected). The issue i had there was that sometimes the homepods would report volume_level = 0 even though it wasn't, so the volume level would get superlow when i tried to lower it. To offset that i'm now saving away the latest volume level and using that if the homepods are reporting 0
I have a bunch of entities starting with sensor.tgtg_ and I want to create a 'template sensor with the count of the sensors above 0 as the state, and in an attribute a list of all the sensors above 0'. Help? 🙂 I've tried with {{ states.sensor | selectattr('entity_id', 'search', 'sensor.tgtg_') | map(attribute='state') | map('float', 0) | sum }}
and that seems to do the first part, but I'm not sure how to get the sensors above 0 in an attribute.
that's not a count of the entities, that's the sum of their state
I thought that's what you meant yesterday. 🙂
End goal is to trigger if one of those entities has state above 0
But I see that you wrote 'count'... 😛
Yest, I understand the goal, but I said you need a template with the count as it's state
you are also writing that in your text above
{{ states.sensor | selectattr('entityid', 'search', '^sensor.tgtg') | map(attribute='state') | select('is_number') | map('float') | select('>', 0) | list | count }}
It was almost copy paste of your answer yesterday 😄
this will give a count of the sensors which are reporting a number, and not equal to 0
can they be negative?
okay, in that case the code above will give you the count
for the entities:
{{ states.sensor | selectattr('entityid', 'search', '^sensor.tgtg') | selectattr('state', 'is_number') | selectattr('state', '!=', '0') | map(attribute='entity_id') | list }}
to be sure you are using the same data, you could use the same for the count, and just add | count
what are you trying to do anyway?
maybe this will help
first part is the template sensor, second part is an automation which sends out notifications when there is a box available, and you can click to go directly to to app on the selected box (assuming you also use Android)
oh it also uses my variables template sensor
I want to be notified with details about each entity the moment that entity has state > 0. Getting notifications about TooGoodTooGo 🙂
(Sorry for the late response)
Funny. Thanks. I'll check it out. My previous automation also took me straight to the box. 🙂
hello. I have a sensor that displays power in real time(watts), that goes negative when discharging batteries, and positive when charging. I want to make 2 new template sensors, one that only counts negative values, and one that only counts positive values, Both sensors need to output positive numbers of Kwh with riemann integral. How would i go about to make that sensor in configuration ?
i came up with this one to read only negative values on my sensor. But it does not work.
- sensor:
- name: "Testningnegativ"
unit_of_measurement: "W"
state_class: measurement
device_class: power
state: >
{% if states('sensor.not_connected_battery_power') | float(0) =< 0 %}
{% set gridout = (states('sensor.not_connected_battery_power') *-1) %}
{% else %}
{% set gridout = 0 %}
{% endif %}
{{ gridout }}
attributes:
last_reset: '1970-01-01T00:00:00+00:00'
stolen from some random place since i have no idea how to code
the one called positive is working as intended, looking like this,
- sensor:
- name: "Testningpositiv"
unit_of_measurement: "W"
state_class: measurement
device_class: power
state: >
{% if states('sensor.not_connected_battery_power') | float(0) >= 0 %}
{% set gridin = states('sensor.not_connected_battery_power') | float(0) %}
{% else %}
{% set gridin = 0 %}
{% endif %}
{{ gridin }}
attributes:
last_reset: '1970-01-01T00:00:00+00:00'
- name: "Testningpositiv"
- sensor:
- name: Positive
device_class: power
unit_of_measurement: W
state_class: measurement
state: >
{% set value = states('sensor.not_connected_battery_power') | float %}
{{ value if value >= 0 else 0 }}
availability: "{{ states('sensor.not_connected_battery_power') | is_number }}"
- name: Negative
device_class: power
unit_of_measurement: W
state_class: measurement
state: >
{% set value = states('sensor.not_connected_battery_power') | float %}
{{ value | abs if value < 0 else 0 }}
availability: "{{ states('sensor.not_connected_battery_power') | is_number }}"
did you write this just now? i would like to understand what i am even doing. but i guess that is up to my betters.
i pressed copy on the box. but i'll look if i misplaced it
make sure that -sensor line lines up with all your other templates as well
i cannot get it to work for some reason
take a look at your correct template sensor
tried moving forward name from the same line at sensor aswell
so i have found out. this isnt the first time i had issues
it works now
thank you very much.
now im just going to put these template sensors in a riemann and get kwh out of them
Whats the easiest way to notify two devices (without duplicate automation) when using your example? Also, the attribute is no longer 'Item URL' but 'item_url' btw.
make a notification group and use that instead
Oooh.. that's neat. Thanks.
How i can do a LIKE instead ewual in automation: {{ trigger.calendar_event.summary == "M9" }}
You can test if the summery contains M9
but what do you mean with LIKE? Is N9 like M9? or M10?
Like M9
what doe you mean with like?
Ok, on my calendar, i have different appointement for hockey my younger kids mentionned M9 into the appointement and my oldest one M11. I would like to trigger 20 min before appointement contain M9
How’d it go?
{{ "M9" in trigger.calendar_event.summary }}
{{ trigger.calendar_event.summary is search("M9|M11") }} or this to check on both in one go
Anyone able to point me in the direction of capturing the last zha_event from a device? Wanting to build a template sensor for the last fired event from an IKEA 5-button remote.
Assuming you updated to the last release, why not just use the logbook for the events? 🙂
https://www.home-assistant.io/blog/2023/08/02/release-20238/#introducing-the-event-entity
This might also be of interest: https://community.home-assistant.io/t/tracking-of-lock-entry/608204/5
The Event entity looks perfect - but it doesn't look like ZHA has been updated to include them yet (or at least not the IKEA set of devices). Will have to look at other suggestions for now.
{{ state_attr('input_device.keyboard','cat') }}
😆
Hey all, I have 5 sensors, sensor.test_mon, sensor.test_tue, etc. I need to use these in a card and would like to know if I can template the day in the sensor, e.g.
{{ states('sensor.test_{{now().strftime("a")' }}
this obviously does not work
{{ states('sensor.test_' + now().strftime('%a')|lower) }}
There are actually 7 days in the week, so this will still error two days per week (with 5 sensors)
Hello! I've a JSON list that's being returned froma restful call similar to this (only it's >255 characters:
[
"Dog",
"Cat",
"Fish",
"Rabbit",
"Lizzard",
"Iquana",
"Mouse"
]
I'm trying to pull the data from this into a sensor (so that I can then feed it into the selection choices on an input_select helper.
because of the result length, I need to put this data into an attribute instead of the state, but I can't seem to find any examples that start with a list without keys and such.
Just make it the value of a key
Thanks, I've been trying to do that most of the day, lol
rest:
- resource: http://192.168.255.10/api/
sensor:
name: Shop
value_template: "OK"
json_attributes:
-pets: {{value}}
scan_interval: 120
am I close?
You need a space before pets and quotes around the template
You probably also need {{ value_json|from_json }}
Parses, but no attribute.
I don't think you can do this in a rest sensor
you can only provide a dict key as attribute, which you don't have
I have something in a commandline sensor, but it feels dirty. 🙂
json_attributes string | list (optional)
A list of keys to extract values from a JSON dictionary result and then set as sensor attributes. If the endpoint returns XML with the text/xml, application/xml or application/xhtml+xml content type, it will automatically be converted to JSON according to this specification
Oh, well that's unfortunate
Oh, you're right
My mistake
I dislike that
It is a bit annoying if there are no dictionaries in the json
I was hoping there was a way to injet a dict
Too restrictive
oh well, I appreciate you guys taking a look at it!
I suggest making a feature request to make REST attributes more like a template sensor
You can try the multiscrape addon which allows for templates in the attributes
im trying to run a test script to let lights change colors as a sort of party lights. I have them in sync now with a shared variable as delay. but i would like to run the loop with each light his own random delay. This still runs in sync.....
i expect light 1 to blink with 1sec interval, the second with 5
but they both change color at 5sec
or do i need a loop per light in a main loop?
I'm trying to get the value of a numeric helper in the trigger of an automation. I want to set the "minutes" value to the value of the numeric helper.
@tawny sedge I converted your message into a file since it's above 15 lines :+1:
This YAML is invalid. What am I doing wrong with the syntax in the "minutes"?
This is the error "Message malformed: expected float for dictionary value @ data['for']['minutes']"
I'm guessing it's not possible to use templates with device triggers/conditions/actions. You'll want to use a state trigger
That's indeed the case
thanks for pushing me, noticed i really needed to learn this.
i kinda wondered why my history was only 10 days, had recorder setup all wrong. and apparently was not even using mariadb. i learned alot, thank you
There is no need to use MariaDB. The default SQL database has improved to the point that there is little advantage now.
if there is advantage why should i not use it? strange thinking
Simplicity. Why run up a seperate container if it is not needed? I use it because I also host my Kodi databases in MariaDB.
If it wasn't for that and that I have a lot of LTS data stored there (hard to move back) I'd use the default DB.
i dont know about you, but i kind of enjoy spinning those containers up lol.
i get your point though
Thank you SO much! That’s exactly what I needed.
How do you renable a template sensor you had set a unique id and disabled via ui? It just vanished from the states list
Settings - Devices & Services - Entities: There is a triangular symbol below the
. You can select to show hidden/disabled entities there.
You can find it now and enable its visible or enabled setting.
ty, first time doing that
I have a lot of temperature sensors feeding into automations through templating, and using the min, max of said sensors. Is there a way to only use the data if it has updated in the past X minutes? I have a very klugey setup currently, and I feel like it could be a lot better.
{% set my_min = 400 %}{%- if states('input_boolean.use_probe_1') == "on" -%}{% set my_min = ([states('sensor.igrill_probe_1') | int(400), my_min | int(400)] | min) %}{%- endif -%}{%- if states('input_boolean.use_probe_2') == "on" -%}{% set my_min = ([states('sensor.igrill_probe_2') | int(400), my_min | int(400)] | min) %}{%- endif -%}{%- if states('input_boolean.use_probe_3') == "on" -%}{% set my_min =([states('sensor.igrill_probe_3') | int(400), my_min | int(400)] | min) %}{%- endif -%}```
the 400 is in there because they "should never be that high" (aka something is on fire so nothing really matters anymore)
currently I'm using a seperate input boolean per input to "toggle it" off and on
From the state object of the entity/entities you can use a filter like:
| selectattr('last_changed', 'gt', now()-timedelta(minutes=2))
The purpose of the booleans is effectively to disable the other sensors from being used in the measurements (ala, I don't care about probe 2 right now so don't include it in the math). If I could use the last updated attributes it'd work without the boolean
To find the lowest state value of those that have changed within the last 2 minutes you could use something like:
{{ states.sensor | selectattr('entity_id', 'search', 'igrill_probe')
| selectattr('entity_id', 'has_value')
| selectattr('last_changed', 'gt', now()-timedelta(minutes=2))
| map(attribute='state') | map('int') | min }}
ohhh, I'll have to give that a try. That'd help a ton! Thank you!
Earlier I wrote some JavaScript that uses a single LET variable instead of a bunch of IF statements to return an icon for use in a custom:button-card. It even has a part to catch a undefined variable.
So then I set out to make the same thing in Python/Jinja for use in a Mushroom Template Card. It took a while to get it to return the matching variable but I must have spent the last two hours trying to catch the undefined variable. Tried all kinds of different stuff to try to make it work...
The whole time: I was trying to call the WRONG MDI ICON! Was trying to return mdi:question when it is really mdi:help (which returns a question mark.)
...code snippet...
{% set icon = conditions[weather_condition] %}
{% if icon is not undefined %}
{{ icon }}
{% else %}
mdi:help
{% endif %}```
Is there something special I need to do for this work?
{% if state_attr('climate.badezimmer_eg', 'preset_mode') ==
'week_program_1' %}
green
{% else %}
red
{% endif %}```
Assuming you're trying to use that in a frontend card. It depends on the card you're trying to use it on. If it is a stock card, chances are it won't work as they're generally not able to be templated.
I am trying to use button-card.
The documention shows a different syntax though:
if (entity.state < 60) return 'lime';
if (entity.state >= 60 && entity.state < 80) return 'orange';
else return 'red';
]]]```
Yes, you should follow the docs
Alright ty. I was hoping I didn't have to learn a new syntax 😅
The custom:button-card uses JavaScript while most templating is in Jinja. Head over to #frontend-archivedas your question is more frontend-based.
Any ideas?
Will try this, thank you!
I want to track a 240v breaker by using a CT in one leg (to track one phase), to get estimated consumtion I would need to multiply total active energy output by two
This should work to create the template sensor
- name: "Bomba de Casa Total"
state: "{{ states('sensor.shellypro3em400_e05a1b339cec_phase_c_total_active_energy') | float(0) * 2}}"
unit_of_measurement: 'kWh'
device_class: energy
My question is, how can I list it as individual device in energy dashboard I dont see it there
Works beautifully- is there any way to add an attribute listing which calendar it came from?
Also should I add an automation to keep refreshing data?
You need to replace the last template in the script with something like:
{% set ns = namespace(alt_events=[]) %}
{% for e in agenda1.events %}
{% set ns.alt_events = ns.alt_events + [dict(e, **{"calendar": "Calendar A"})] %}
{% endfor%}
{% for e in agenda2.events %}
{% set ns.alt_events = ns.alt_events + [dict(e, **{"calendar": "Calendar B"})] %}
{% endfor%}
{{ns.alt_events}}
If you use VSCode it will show the mdi, so if it doesn't show it's not a valid mdi (at least with the add-on, maybe it uses some mdi extension for that)
@normal notch I converted your message into a file since it's above 15 lines :+1:
@normal notch this is not a valid template
value_template: "{{ camera_type }} == 'Driveway'"
Move the ending curly brackets to just between the single and double quote
When do template images update? Mine only seem to update when home assistant is restarted.
Depends on the template used to get the image. If it is not using anything which causes it to reload on state change like states() you might want to add something like a trigger
Yeah I'm not. Just a web url that does not change. Thanks for the tip. I'll change them to triggered template images.
I've used a triggered template image with triggers for HA start, templates reload, entity state change and a time pattern trigger for pulling an image from our weather service.
These are cloud cover images, they only update every hour so I'll use a time pattern trigger for that.
But with that time pattern trigger alone you will get that image 1h after HA start or a template reload. Before that the image will not be available. That's why I added the templates reload and HA start triggers too
That way it is immediately available and gets actualised in a timely pattern
No, will get it every hour. Every time the hour is divisible by 1 (and the seconds == 0). Also I've just been reading the site information and it actually only updates every 3 hours. So 1 hour should be plenty.
Yes, but you will see it the first time after an hour (edit: at the next load time)
So you are saying they are not restored?
That's great, many thanks! 🙂
Not in my experience.
Ah. Ok then. Thanks for the tip.
Every reload of templates in the dev tools or HA restart kills those
The untriggered ones reloaded on restart so I assumed the triggered ones would too.
- triggger:
- platform: homeassistant
event: start
- platform: event
event_type: event_template_reloaded
- platform: time_pattern
minutes: "/15"
image: ......```
was my approach
Pretty much what I have now. Thanks.
If that's the case, I'd consider that a bug. Trigger based template entities should restore after a restart or template reload
Do you know if templates can be used to define what entity to use? As an example, I was trying to do this to decide what camera to snapshot from:
entity_id: camera.{{camera_type | lower }}_camera_sub```
But it does not seem to wokr unfortunately
Actually the docs only say that triggered template binary sensors and sensors are restored. So it would have to be a feature request.
It specifically says "The state of other trigger-based template entities is not restored."
Quote your single line templates. ```
target:
entity_id: "camera.{{camera_type | lower }}_camera_sub"
Gave that a go but it didn't seem to work, but will try again incase I mis-typed. Thanks! 🙂
Use the developer tools template editor to check
Just set the value of camera_type first, ```
{% set camera_type = "Driveway" %}
"camera.{{camera_type | lower }}_camera_sub"
Will give it a quick shot, thanks! Dev tools did seem to work though... two tics
Ah it works! Perhaps I had mis-typed it before, as it did not generate an image before. Thanks!!! 🙂
Oh, oops..
I need some help! I am trying to merge/append two dicts together. Any ideas?
Does dict(dictionary_1, **dictionary_2) do the trick?
Can anyone see anything wrong with this?
- name: "[Motion] Sensors"
state: |-
{% set sensors = states.binary_sensor|default([], true) | selectattr('entity_id', 'defined') | selectattr('state', 'defined') | selectattr('attributes', 'defined') | selectattr('attributes.device_class', 'defined') | rejectattr('state', 'eq', 'unavailable') | selectattr('attributes.device_class', 'eq', 'motion') | sort(attribute='last_updated', reverse = True) | sort(attribute='state', reverse = True) | list %}
{{ sensors }}
it works in the template under development tools
It should get a list of all valid motion sensors and sort them in order of latest update and on state before offstate
but when i create it under sensors.yaml which i include in my configuration.yaml it just comes up as unavailable
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.
Found the issue "State max length is 255 characters."
guess this {{state_attr('sensor.daylight_savings_times','dst_changed_today') == true or state_attr('sensor.daylight_savings_times','dst_change_tomorrow') == true}} could be written as {{state_attr('sensor.daylight_savings_times','dst_changed_today') or state_attr('sensor.daylight_savings_times','dst_change_tomorrow')}} too
or would that cause some edge case issue at change (not sure what could go wrong, but just to be sure..)
only potential issue i can see is if the result is undefined but then it should resolve to false so therefor it would be the same as == true
so it should be functionally the same
but if you're worried about potential issues i'd do state_attr('blah')|bool
that way it will always resolve to an actual boolean
Wouldn't is_state_attr make more sense?
yeah, thx. been using this binary since forever, and never had an issue with it being unavailable, so guess that wont be required. trimming down on yaml characters....
yes, could also have been done
fwiw, I am testing these:```
dst_change_tomorrow: >
{% set dt = now() + timedelta(days=1) %}
{{now().astimezone().tzinfo != dt.astimezone().tzinfo}}
dst_changed_today: >
{% set dt = now() + timedelta(days=-1) %}
{{now().astimezone().tzinfo != dt.astimezone().tzinfo}}
im guessing there is no easy way to make
timestamp_custom('%A, %-d %B')
display in swedish?
and yeah, if i change general language settings in HA, it might change, but i for sure dont want to do that.
Uhm, that will display 2023-09-02 There is nothing to translate in that
sorry pasted wrong thing 😉
edited post
kinda weird that even if i do TTS google translate with swedish, it will still say friday instead of fredag.
A quick and dirty workaround might be something like this (for today's name of day in Swedish - at least I hope it is correct 😆 ):
{% set weekday = weekdays[now().weekday()] %}
{{ weekday }}```
hahahah yeah that worked!
but only for {{ weekday }}
guess i have to rewrite the whole thing to make it work around that
You just need to replace the now().weekday() by something that counts the weekday from 0 to 6.
that is indeed very cool and interesting. thanks!
but thing is, i did this looong template based around dates (from calendar)
so everything is built upon |timestamp_custom('%A, %-d %B')
that gives me Friday 22 September
which does not seem to want to be translated.
its not really a big deal, i can probably live with it
im gonna assume this is because i did it wrong from the beginning.
Hi, whats going on here then? i have written a template that works fine in the template tool but shows as unavailable once loaded?
trying to think how i can show the issue
by sharing the template
there must be some kind of of limit to how many lines can be output it works with 5 but not 6.. ill share the code 2 sec
states can't be more than 255 characters
Your are probably exceeding the 255 limit for a state. Use Attributes or multiple sensors.
was waiting to see the response from a Mod and a Padawan writing at the same time. 😆
we all share a hive mind
think ill split it into 3 sensors
Or... Put it in an attribute
That could work.. i want to show it on a markdown card but you can show attributes there cant you?
yes
If you are using a Markdown card, why not simply use a Template Macro and include that when you need it.
You already have the code to build it.
cos i dont know what im doing lol
I was going to ask if you wrote that 🙂
Or if it's only for the card, just use the template in the card
I did but im no expert
well blow me .. pasted it into a markdown card and its perfect
thank you xoxox
I find using the template macros useful as you can document what you have done with comments and if you delete the card any code still exists for reuse later. https://www.home-assistant.io/docs/configuration/templating/#reusing-templates
Hi All, i have a KG measurement. Is there any way to round to the nearest half KG? e.g. 10.0, 10.5, 11.0
A nice way, or a horrible way? Because the time-honoured method is output=round(input*2)/2
Should be able to throw that into a template sensor
Thanks!
Hey everyone, I'd like to create a template that gets the last 5 minutes of a sensor's data from recorder integration and uses that to generate an average. I'm having trouble figuring out how to do that.
a SQL sensor makes more sense for that
Use the statistics integration
thanks guys, I'm stuck in the old influxdb style way of doing things
need to get used to thinking in this new way
works perfect thanks everyone
''' - condition: state
entity_id: switch.shelly_test
state: "off"
for:
hours: 0
minutes: 5
seconds: 0'''
is there a change to check this automation condition as a template?
chance
An equivalent template would be:
{{ is_state('switch.shelly_test', 'off') and
states.switch.shelly_test.last_changed <= now() - timedelta(minutes=5)}}
great, thanks @haughty breach
can I read user profile settings inside a template? I want to get the language the user has set
nope, templates don't know anything about the frontend
rip, my family is gonna have to cope with English titles then (or I could add a separate "setting" for that)
Well
with some cards which accept templates, there is a user variable, which contains the username
you can use that in the card directly
@mossy compass eg
type: markdown
contents: >
{{ 'Bananas' if user in [ 'Dad', 'Mom', 'Little brother'] else 'Oranges' }}
Is there a way to say how long the previous state was for location? I am using a location notification blueprint, and I want the notification text to say how long the person was at the location they are leaving.
If you use a state trigger on the person entity, you can compare the last_changed of the from_state and the to_state to see how long it was in that state
I'm trying to get the current item + next item in this list.
example output
84 00
But I am getting
UndefinedError: there is no next item
https://dpaste.org/CXWVj
that's because in your last iteration there is no next item
{{ loop.nextitem | default("") }} will resolve that
Makes sense thank you.
Would this be the place to ask for scrape sensor help? As in getting the right data from the html
Or maybe use state-switch with user?
Is there any good way of implementing an area filter onto the occupied_sensors? i know you can put the entity_id into area_id() but don't think that would work well for the below scenario
{% set area = 'bedroom' %}
{% set occupied_sensors = states.binary_sensor|default([], true) | selectattr('entity_id', 'defined') | selectattr('state', 'defined') | selectattr('attributes', 'defined') | selectattr('attributes.device_class', 'defined') | selectattr('attributes.device_class', 'eq', 'motion') | selectattr('state', 'eq', 'on') | list %}
I would start with area_entities('kitchen')
looks like i can do | selectattr('entity_id', 'in', area_entities(area))
that's one way, yes. or you just start with that instead of states.binary_sensor
in other words, start with the list of entities that you care about (are in that area) and filter from there
area_entities(area)|expand|xxxx
ah yeah, that would certainly be a nice optimization, only just ran across area_entities before your answer didn't realise it returned a list of entity states for the area
Will do it that way, thanks
hi everyone i have a door lock sensor that shows locked/unlocked but it doesnt expose a door lock entity, it just logs this in the device logbook. [VeriLock Translator fired Notification CC 'notification' event 'Access Control': 'Manual lock operation']
how can i create a template sensor for these devices to show locked/unlocked status?
I assume the Verilock Translator is a zwave device? See https://www.home-assistant.io/integrations/zwave_js/#events
Operate the lock in all the various ways (manually, with keypad, via remote, etc) and note the events that are fired. Do the same for unlocking. Then you can ask a more detailed question about how to create a template that evaluates to on when those events are received.
its zwave correct. it doesnt actuate the lock, its only a locked/unlocked sensor. I have the events isolated but my question is about creating the template
is there a way to create a "lock" template sensor that will show locked/unlocked based on an automation I create triggered by the events?
Here is something that could get you started; you don’t need an automation; this sensor will update when it sees the event:
template:
- trigger:
- platform: event
event_type: zwave_js_notification
event_data:
device_id: your_device_id
label: Access Control
sensor:
- name: "Front Door Lock Event"
state: "{{ trigger.event.data.event_label }}"
unique_id: front_door_lock_event
You could modify that with a template lock that doesn’t do anything, or you could use a template binary sensor
Sorry, I was wrong, it looks like a trigger-based lock doesn’t exist. You’d have to make it a trigger-based binary sensor
so i got this...
template:
- trigger:
- platform: event
event_type: zwave_js_notification
event_data:
domain: zwave_js
node_id: 219
command_class: 113
command_class_name: Notification
event_label: Door Unlock
type: 6
event: 1
event_label: Manual unlock operation
sensor: - name: "Sunroom Door Unlocked"
state: "{{ trigger.event.data.event_label }}"
unique_id: sunroom_door_lock_event
- platform: event
but how do i do the lock vs unlock?
there are 2 separate events and i
Maybe this?
template:
- trigger:
- platform: event
event_type: zwave_js_notification
event_data:
domain: zwave_js
node_id: 219
command_class: 113
command_class_name: Notification
event_label: Unlocked
type: 6
event: 1
event_label: Manual unlock operation
sensor: - name: "Sunroom Door Unlocked"
state: "{{ trigger.event.data.event_label }}"
unique_id: sunroom_door_lock
- platform: event
Can you provide the detail on what the lock event is? For your template (the code after the state key) you’ll want something that evaluates to on or true when the lock event is received, and then evaluates to off or false in all other cases
And you want this sensor updated (you want the template code re-evaluated) on both Locked and Unlocked events, so you need to remove the things in the trigger that would only match one of those events
@lucid thicket I converted your message into a file since it's above 15 lines :+1:
yep here are the events
@waxen lance I converted your message into a file since it's above 15 lines :+1:
@waxen lance I converted your message into a file since it's above 15 lines :+1:
That would be event: 1 or event: 2
here's two different ways to do it, hopefully this helps you understand what is possible with a trigger-based template sensor: https://paste.debian.net/1291092/
Also, for future reference, help with template sensors should be under #integrations-archived and if you're having issues with the code for the state, then this is the right place
by the way, in that debian paste, you'll have to either delete one of the two options (both the trigger and the binary_sensor sections) or else make the name and unique_id actually unique between them
And I used device_id in the trigger because that ID is unique to that lock. The nodes could get reused if the lock is removed and a different device is added. But the device_id will be new & unique each time a device joins the zwave network.
{% set monitored_entities = ['sensor.hue_toilet_motion_sensor_battery',
'light.diningroom',
'light.office1'] %}
{% set no_entities = 0 %}
{%- for monitored_entity in monitored_entities -%}
{%- if states(monitored_entity) in ['unavailable', 'unknown'] -%}
{% set no_entities = no_entities + 1 %}
{%- endif -%}
{%- endfor -%}
{{ no_entities }}
there are two entities which are unavailable and unknow. why do i get out 0, not 2?
Because of the scope of the for loop
Your changes in the for loop exist only there, you need to define a namespace
{% set monitored_entities = ['sensor.hue_toilet_motion_sensor_battery',
'light.diningroom',
'light.office1'] %}
{% set ns = namespace(no_entities = 0) %}
{%- for monitored_entity in monitored_entities -%}
{%- if states(monitored_entity) in ['unavailable', 'unknown'] -%}
{% set ns.no_entities = ns.no_entities + 1 %}
{%- endif -%}
{%- endfor -%}
{{ ns.no_entities }}
But you can easily do this without a for loop
{{ monitored_entities | map('states') | select('in', ['unavailable', 'unknown']) | list | count }}
thanks
Hi again! I'm trying to get the energy consumption of a device today. How could I do that with a template? It should be possible given that the Energy tab has no issue getting that data.
Use that, no templates involved
But I'm not looking for an utility meter?
This is for a single device
track consumptions of various utilities (e.g., energy, gas, water, heating).
oh I see, thanks
Create a utility meter based on the energy sensor of that single device
How does the energy tab get that data anyway?
is it something I can't take advantage of as it needs to be an internal integration?
It uses the long term statistics in which the hourly deltas of each sensor are stored
It basically sums up all those hourly deltas for the selected period
It doesn't create entities or sensor values for those totals
Is there a way I could take advantage of the long term stats for my templates or is this only for integrations?
Anyway using utility meter worked fine, thanks!
The only way to access LTS would be with an SQL sensor.
Thanks, that's too complex for me so I'll just stick to using a utility meter.
It seems to be working just fine, but I'll resort to SQL sensor if I need to
Hi! I just noticed something weird with regex_replace and service input_text.set_value.. If I look at the template result in the template dev tools, I get the correct result:
Template: {{ states('input_text.ios_reminders_handlelisten') | regex_replace(find='((Klesvaskemiddel)(\\n)?)', replace='', ignorecase=True) }}
Result: Something\nThis\nThat
When I try to use this with input_text.set_value, it ignores the match of \n
Result: Something\n\nThis\nThat
Any ideas? 🙂
How might I achieve this output list from these 2 separate lists?
I am essentially saying every 4 items in main_list reset cycle list back to 0. Which is why bob is foo. I assume I might need a nested loop but I wasn't sure if there's a cleaner way.
Why is adam skipped
Because eve is missing
Oh Adam is skipped because I fudged up
Adam is now not skipped https://dpaste.org/Z0sx8
what about bob?
I removed it as I wanted to keep the example clear
Essentially every number of items in cycle_list in this example 4 items reset back to the first item in cycle_list when we get the output.
That's why Chris at position 5 is foo and if I added Bob back at position 6 then Bob would be santa
We should just continue discussing your name choices and ignore your question 🙂
It was pretty funny the Adam and eve one lol
This is just something complex that I am not sure of the right way to approach in jinja
Nevermind I figured out something for this lol.
Does it look something like:
{% set ns = namespace(zipped=[]) %}
{% for item in main_list %}
{% set ns.zipped = ns.zipped + [ item ~ ': ' ~ cycle_list[loop.index0] | default('foo') ] %}
{% endfor %}
{{ ns.zipped }}
Looks like this and disregard names lol
{% set main_list = ['goo','fuy','udur','dhdh','shhd','eueh'] %}
{% set cycle_list = ['pr1','pr2','pr3','pr4'] %}
{% set ns = namespace(zipped=[]) %}
{% for item in main_list %}
{% set ns.zipped = ns.zipped + [ item ~ ': ' ~ loop.cycle(*cycle_list) ] %}
{% endfor %}
{{ ns.zipped }}
This slight difference achieves the reset I was looking for
now we have the actions in trigger templates I finally started out using the response_variable and tried to template that into a useful entity... followed the weather forecast example successfully. but, how can we test this response_variable in eg dev tools?
also asked in the Petition thread in the community so forgive my double ask.
got the answer from theFes in https://community.home-assistant.io/t/petition-dont-delete-the-forecast-attribute/609298/176, all clear now: run the service in dev tools services and see the data in the response field presented nicely below.
what is the correct way to print the state of a input_boolean in a template?
{{ states('input_boolean.your_input_boolean') }}
hm thats what I tried
{{ states('input_boolean.luftentfeuchter_status') }} -> TypeError: float() argument must be a string or a real number, not 'NoneType'
oh damn you are right
I thought it should at least print it since I put it in first line
thank...again 🙂
@cerulean karma I converted your message into a file since it's above 15 lines :+1:
is there a chance to create a endlessloop when missing the condition?
I change the input_boolean which is the trigger on change at the same time
Would HA prevent me from creating such a loop?
I don't think you need an infinite loop. You are just trying to sync the input_boolean with the switch right?
yes
Then the above automation is sufficient, the chance that you toggle the input boolean and the switch changes at the exact same ms is almost zero
yes the automation seems to work fine, I just came to my question when thinking about it....What would HA do if I create a automation with trigger: on change and action: toggle
Yeah you could use input_boolean.toggle instead of the if/then/elseaction, but that is more something for #automations-archived
yes sure....
you could simplify your automtion (with the use of a small template)
alias: Luftentfeuchter_Status_setzen
trigger:
- platform: state
entity_id:
- switch.shelly_luftentfeuchter
- input_boolean.luftentfeuchter_status
not_to: "unavailable"
condition:
- condition: template
value_template: >-
{{ states('input_boolean.luftentfeuchter_status') != states('switch.shelly_luftentfeuchter') }}
action:
- service: homeassistant.turn_{{ trigger.to_state.state }}"
target:
entity_id: >
{{ [ 'input_boolean.luftentfeuchter_status', 'input_boolean.luftentfeuchter_status' ] | reject('eq', trigger.entity_id) | list }}
mode: single
that looks much better 🙂
hm but it works not as expected...If I change the input_boolean it should change back automatically
simple said: it should be a excact copy of the switch
and when I change it manually it should change back
background is that I have a "readonly" switch
alias: Luftentfeuchter_Status_setzen
trigger:
- platform: state
entity_id:
- switch.shelly_luftentfeuchter
- input_boolean.luftentfeuchter_status
not_to: "unavailable"
condition:
- condition: template
value_template: >-
{{ states('input_boolean.luftentfeuchter_status') != states('switch.shelly_luftentfeuchter') }}
action:
- service: input_boolean.turn_{{ states('switch.shelly_luftentfeuchter') }}
target:
entity_id: input_boolean.luftentfeuchter_status
mode: single
that should do what you want
this does the same as your automation
it copies the state of your switch to that of the input_boolean
but what if I manually change the input_boolean to the wrong state?
It seems not to correct it again
it triggers the automation, and sets it to the state of the switch again
I completly copied the code but it does seems not to do the same as my automation
situaton: swith is on, boolean is on
you then toggle the boolean, this will trigger the automation. Your condition will pass, as the states differ.
The action will perform input_boolean.turn_on as the state of the switch is on
wait
there were some double quotes which shouldn't be there
removed it
at the end of the service call
Executed: 7. September 2023 um 12:09:03
Error: Template rendered invalid service: input_boolean.turn_off"
service: input_boolean.turn_{{ states('switch.shelly_luftentfeuchter') }}"
target:
entity_id: input_boolean.luftentfeuchter_status
yes, remove those double quotes after }}
not sure why you'd want to do this though
I want to show the state in a entity card without giving the posibility to change it with a "quick" click
so I add the input_boolean into the list of the entity_card to visualize the state but have it "readonly"
So you have a toggle which doesn't toggle? Why not just create a template binary sensor out of it
Yes I have a not working toggle 🙂
don't really understand what you mean with the binary sens
I think I got it now....will try that
@marble jackal You are right again, I really like that... 🙂
@supple ginkgo I converted your message into a file since it's above 15 lines :+1:
What did you already try?
Tried using: intent_uri: "google.navigation:q={{ states('input_text.navigate_to') }}"
And a series of other similar strings... I know the variable/helper is working as I can reference that if I send it stright to a notification, Ithink the issue is when I'm trying to use it as part of the intent_uri line...
I see no reason why that would not resolve the template to the actual state
what does it show if you test it in devtools > template
The command works in the sense that it starts google maps on my phone and starts the navigation even, but instread of passing the address from the variable the query box on navigation shows the variable name/string...
not sure what you mean there, can you upload a picture to imgur and share the link
Oh, now thats interesting... in the DevTools -> Servcies, when I use the exact same YAML it works exactly as I would expect....
Now when I create a script with that code in, it works, it just won't work when I use a button to call the service.... Thanks for the pointers @marble jackal, I have a workaround now. 🙂
How can I check if a state of a select option is chosen?
{% if is_state('input_select.trockner_status', 'trocknet') %}
blue
{% else if is_state('input_select.trockner_status', 'fertig') %}
green
{% endif }```
does not work
I think jinja needs elif not else if. else if is showing me syntax errors in template devtool, have you tried using that?
Also you need a %} at the end
So there's now a new integration with the "google assistant" where you can send google assistant commands like: "turn on kitchen light" or "turn off office light" and that does work for me preaty well (it has some latency, but overall it works).
However, i'm trying to also send some shopping items to my shopping list that is listed in google keep.
When i say the following command to one of my google nests / displays, it works well:
Add something to the shopping list
So i tried to send the same command using the new google assistant service but that doesn't work.
I don't know why.
service: google_assistant_sdk.send_text_command
data:
command: add something to the Shopping List
Is there a way to mimic a device selector in the template editor to say see all devices wiht a manufactor that equals something?
I'm trying to debug.
It looks like i can take a device id and get an attr from it but nto sure if i can see all the attributes on specific device and/or itterate through every single device
You can't do that, as it is linked to a specific account. There is a custom component which allows that, and a PR to add it to the core one.
PS, this is totally unrelated to templates and should have been asked in #integrations-archived
I saw this message on the forums and it intrigued me about how you can create a sensor of all automations that are currently in progress and Tinkerer mentioned coming here to see how. I've created dozens of template entities, but am curious what this might look like. I never was interested in this before, but as it always goes in home automation - you see something new and you just have to have it even if you don't really need it 🙂
Anyone know how I can determine the count and names of automations in progress at any one point in time - using the "current" - with a template sensor or the like (trying to make sure my RPI is not overwhwlemed and concerned when I see CPU spikes that I am not expecting...)?
@remote perch I didn't see your message above and I guess I followed you from the forum lol
Automations have a current attribute which shows how many instances of that automation are running
So basically your want to list or count those which are above 0
Would this be the best place to post about custom:button-card templating ?
ok, thanks!
Working on trying to create a template for a light based pomodoro timer I'm trying to set up. The goal is to have the card either display "Off" or the current duration of the timer, but using the following code:
Off
{% else %}
{{ state_attr('timer.30_minutes','remaining') }}
{%endif%}```
It displays the duration of the timer, not the remaining time. Any suggestions for me?
the true remaining time for a timer is not in the state machine, it can't be retrieved with a template. At best you can subtract the finishes_at time from now(), but that only updates once per minute.
remaining only updates when it is paused.
The entities card will however display the live remaining time for a timer, if you want to use that.
hey, since 2023.9.0 all my templates are gone. also: vscode doesn't work anymore
both are unrelated to this channel.
If the whole template integration is broken, that's something for #integrations-archived, VSCode is something for #add-ons-archived (assuming you are referring to the add-on)
This channel is for help with the actual jinja code
oh ok never mind
goodmorning. When ever i turn off ALL lights in the house in one go, sometimes something stays on. Is it because the zigbeenetwork get flooded with commands? Im thinking of looping through all lights that are on, and turn them off with a little interval.
So from some automation i have i found this:
['light.voortuin_wand']) | selectattr('state', 'eq', 'on') |
map(attribute='entity_id') | list }}```
How can i loop this like a `for each`
just use that as the input for the for_each
ill have a go at it. ill search for for_each
found it thx. step 1 is to exclude some rooms.
are all your lights zigbee?
no, some are wifi
| selectattr ( 'domain' , 'eq' , 'light' )
| selectattr('state', 'eq', 'on')
| map ( attribute = 'entity_id' )
| list }}```
i cant add keuken to the area_entities
because of my lack of knowlegde in synta 😉
I would put all the lights you want to turn off in a zigbee group, and turn that group off
the zigbee relays through 2 sets of ikea gui10... and i hate them
they need resetting sometimes
you can't add multiple areas to area_entities
anyway.... i prefer to turn them off one by one... with 1sec intervals. Is kinda fancy as well
you can do expand(area_entities('woonkamer') + area_entities('keuken'))
that looks good!
but you don't need to expand them anyway
....hehe
(area_entities('woonkamer') + area_entities('keuken')) | select('search', '^light.') | select('is_state', 'on') | list
as soon as your template is correct, this is something for #automations-archived
{% set x = "AAA" %}
{%- for i in range(1, 10) -%}
{% set x = "BBB" %}
{% endfor %}
{{ x }}
why is x still "AAA"?
does the for loop change the context?
because of scope
the changes done inside the for loop are done there, the variable outside the scope is unaffected. The x in your loop is basically a diffent x then the one outside it.
you need to define a namespace to have access to them outside the loop
{% set x = namespace(value="AAA") %}
{%- for i in range(1, 10) -%}
{% set x.value = "BBB" %}
{% endfor %}
{{ x.value }}
oh thought I create a global var whem putting it on top
no, jinja works different here compared to python
Is there a way to get locale-specific formatting of dates in templates? Like day-names in norwegian?
No
You have to fully template it
I mean "Yes", but it's not simple like using strftime
@vagrant monolith I converted your message into a file since it's above 15 lines :+1:
or, don't use a target selector as they are the hardest to work with when trying to get an entity list
How can I use that to just contain the ones in my "entities" field?
>
{%- 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=[]) }}
You have to use all 3 templates in that post
your selector is mapped to a variable named lights
e.g.
variables:
lights: !input light_target
device: ...
area: ...
entities: ...
then, use "{{ entities }}" for your snapshot entities template.
Failed to call service script.flash_house. Entity IDs cannot be None for dictionary value @ data['snapshot_entities']. Got None
@vagrant monolith I converted your message into a file since it's above 15 lines :+1:
you're spacing isn't correct
also, you don't have quotes around your entities template
So it sayd object objcet now
@vagrant monolith I converted your message into a file since it's above 15 lines :+1:
@vagrant monolith I converted your message into a file since it's above 15 lines :+1:
You're doing htis in all yaml right? No UI?
if you choose to use the UI for this, you cannot switch to UI mode
only view it in yaml mode
aside from that, it will work.
Yes I view in in yaml only yes
Then just run it and it should work
if it doesn't, post the full json trace here using a share site
@vagrant monolith Please use a code share site to share code or logs, for example:
- https://dpaste.org/ (select YAML for the language, and consider picking a longer expiry)
- http://pastie.org/ (select YAML for the language)
- https://paste.debian.net/ (you guessed it, select YAML as the language)
Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.
color:
- 224
- 27
- 36
repeat: 1
entities:
entity_id:
- light.axel_bedroom_window
- light.axel_bedroom_bed
- light.axel_bedroom_wardrobe
This doesnt work
How do I find traces?
Go to the scripts page, and view the trace
Any pointers on how, do you need to use some mapping or some such thing?
You can just use my macro lib
I'll have a look. and give you a PR for Norwegian 🙂
released, thanks 🙂
Hi, i am trying to make a switch to mount my synology crypto folder by ssh, but i always get the log command failed.
The keyless ssh login works from the homeassist terminal and the command also works after logging in.
But when i try to test the command from HA terminal, i get ash: synoshare: command not found.
The command is: ssh -i /config/.ssh/diskstation_rsa -o 'StrictHostKeyChecking=no' -q root@192.168.178.69 'synoshare --enc_mount \"crypto\" _PASSWORD_'
(I also tried simple commands like MyHostName with the same result)
anyone spots why below doesn't work? {% set state = states('sensor.pir_living_illuminance_lux') %} {% set low = states('input_number.light_threshold_dark') %} {% set high = states('input_number.light_threshold_daylight') %} {% if is_number(state) and state > high %} daylight {% elif state < low %} dark {% else %} in between {% endif %}
it alternates between daylight & dark, also when the value is clearly between
All states are strings
You're checking if it's a number, but not actually converting it into one before the comparison
Add |float(0) (or whatever default you want) to each of the first three lines, and you can get rid of the is_number check
doh. thanks Rob
Is there any way of using the chosen entity_id in a script for the data value? Ex: using the input_number.set_value service
service: input_number.set_value data: entity_id: input_number.{{ states('sensor.pick_the_good_input_number_to_play_with') }} value: >- {% set number = entity_id.state |int + states('number.dynamicincrement') |int %} {{ number }}
Would appreciate if someone can point me in the right direction
you have to build the entity_id again and then use the states() function in your value template
Hello, since the update 2023.9. One of my template is triggered twice where previously it was triggered only one time
the trigger is very simple
- trigger:
- platform: state
entity_id: binary_sensor.grid_calculation
to: "on"
that's not a template
and this binary_sensor.grid_calculation is having an auto-off after 120 sec.
till now I never had issue with the calculation
@final lark I converted your message into a file since it's above 15 lines :+1:
in in my template.yaml
regardless, if it's triggering twice, it's not a template issue
keep in mind, this channel is about templates, not the template integration or triggers
but they added action block in the release, not link to that ?
oh ok , I got it
anyways, nothing with the new action section changed triggers
so your issue is with binary_sensor.grid_calculation
ok. but something change 🙂
I doubt it
thank you petro for the notice
I bet you that your binary_sensor is going on -> unavailable -> on
so, verify that your binary sensor is working properly
nope it's on or off (only the first time after loading it's unavailable)
well thatw ould cause an extra trigger
condition is to: "on"
yes, but if it goes from unavailabe to on, it will trigger
yes indeed.
if it goes any state to on it will trigger
and there are 4 possible states: off, unknown, unavailable, and on
on -> on will not trigger
all the rest will
@final lark I converted your message into a file since it's above 15 lines :+1:
I know that petro.
that's not the full template integration
that's part of it
right but how can we debug it without the trigger
@final lark I converted your message into a file since it's above 15 lines :+1:
it also has no safety built into it
Everything was running since 2 months
I just update to 2023.9 from 2023.8.4
then value received now is twice the value.
example: delta is 0.2 and at the moment is binary is on , I see 0.2 +0.2
where before it was 0.2
and are there errors in your logs? None of your to_states/from_states have proper defaults applied to the float conversions
Yes, I get nothing changed, but nothing changed with HA in regards to triggers
I'm trying to lead you to the real problem instead of focusing on what you think is the problem
my assumption was, mhh they introduce action block then may be it goes twice due to that
the binary is very simple case here with auto_off
so it's on by the template and auto off ... nothing more than that
it's not that simple, you have no safety built into that
and your trigger is a state change trigger
which could be unavailable to a value
when it raised to on ; calculation is passing twice ... I have put a count-in on it , I'm waiting some sun 🙂
it depends on how sensor.filtered_electricity_meter behaves at startup, or in general
you have 0 unavaiable safty built into all your templates. Meaning it all those can go unavailable.
the value is fine there
Well, the create an issue and provide proof that it’s triggering twice
yes, I will do some template to simulate the case
from now... I'm suspect something wrong but I cannot point where exactly.
I’m 100% sure nothing is wrong.
But I’ll let you do you
It’s all the same trigger code everywhere. Literally.
You’d see this issue in automations. And the pr to add actions was small, and does not touch triggers.
ok . I need to leave , my wife is waiting me ... 😉 thank you already for the small chat petro for helping me
Thanks for the hint. What do you mean by building the entity_id again? Can't you use template inside template? ex: {% set entity_id: input_number.{{ states('sensor.pick_the_good_input_number_to_play_with') }} %} wouldn't work
today I learned something new about using the ChatGPT prompts, turns out if I simply use this prompt, the quote is the always the same (this is part of a morning greet automation that runs when I enter the office):
- service: conversation.process
data:
agent_id: [redacted]
text: tell me a random quote
response_variable: quote
so, I have to add something variable to it like date, time, temperature. If I use date or time, would it be something like this?
text: tell me a random quote {{ now }}
im not sure, its a paid plan so I hope they are not doing that
she was very polite, but this was the responce to that above:
speech: >-
Apologies for the confusion, but it seems there's been an error in
your request. If you're looking for a random quote, here's one for
you:
"Life is what happens when you're busy making other plans." - John
Lennon
I've heard the John Lennon quote like 20 times already 🙂
using {{ now }} in the template editor, gives an output of <function now at 0x7f120eeac0>
maybe I have to convert it actual date
now()
ahh ok, that didn't work either, but the responce was a bit better
speech: >-
I'm sorry, but as an AI, I don't have the ability to predict or
generate specific quotes for future dates. I can provide a general
motivational quote if you'd like. Here's one:
"Believe you can and you're halfway there." - Theodore Roosevelt
if I change the prompt to "provide me a general motivational quote" this so far is working
Also, someone mentioned upping the temperature.
ok, this robot needs a bit of training
ok, its back to repeating Roosevelt
He didn't say how to finish the other half
ok this seems to work, I did it 6 times and it gave me 6 different quotes every time, not a template solution though
generate a beautiful quote...
ill post the quote last trace for you RobC
Here is your AI generated quote of the day Life is like a camera. Just
focus on what's important, capture the good times, develop from the
negatives, and if things don't work out, just take another shot.
😀
Maybe I can template the word beautiful to randomly pick other adjectives
beautiful, calming, mathematical, scientific, political,
Etc.
And the word is picked at random
generate a {{ [ "motivational", "scientific", "calming", "mathematical", "political", "religious","beautiful"] | random }} quote...
How's my syntax here?
Try it in
-> Templates
thanks, Rob. This works
- service: conversation.process
data:
agent_id: [redacted]
text: >-
generate a {{ [ "motivational", "scientific", "calming", "mathematical",
"political", "religious", "beautiful" ] | random }} quote...
response_variable: quote
Hey, I have a template sensor with round(1) but it shows me the value with a . instead of a ,
what can I do about this?
{{ states('sensor.balkonkraftwerk_efficiency') | float | round(1) }} %
All other values are shown with ,
If you put it on your dashboard, it will show a comma
You might need to have a unit of measurement for that though
Hi all! I want to set a input datetime with date NOW + 30 days. But i dont know how, The example below works with a entity + 30 days. but i want to use like "now()" somehow 🙂 anyone knows how? 😄
{{ (state_attr('input_datetime.dishwasher_last_clean_date', 'timestamp') + 2592000) | timestamp_custom('%Y-%m-%d')}}
and
{{ (states('input_datetime.dishwasher_last_clean_date') | as_datetime + timedelta(days=30)).isoformat() }}
I'm having quite the struggle formatting to add a thousands separator comma. I know I can use state measurement number and the UI would add it but this is a template with a lot of attributes I would rather not make a sensor per attribute.
"{:,.2f}"
"{0:,.2f}"
'{0:,}'
'{:,}'
{{ '{:,.2f}' | format('225344') }}
All get me TypeError: not all arguments converted during string formatting
no its shown with the . sadly
Did you add a unit_of_measurement
unit_of_measurement is %
ooh sweet! Thank you TheFes
Hello @mighty ledge
from the issue of yesterday, it's triggered one time but the template is processing twice the data.
I created an automation with the same trigger as in the template integration and as action write in system logs.
So it's sure that is not triggered twice but the issue of calculation and the template itself is for sure doing twice the work.
Each time the trigger is it, the counting attribute is having +2
I could use a little help with something I'm attempting to do. I have entities that display unavailable at times and I'd prefer them simply list a value of 0 at those times. I referred to this (https://community.home-assistant.io/t/set-value-to-0-if-entity-is-not-available/327424) forum post, however my dashboard still displays the unavailable value. The template code belongs in my config file under the other templates, no?
What's your code?
I figured it out. Thanks though!
Anyone have any ideas?
{{ '{:,.2f}'.format(225344) }}
Note that it expects a number, not a string
And format is a Python method, not a filter
I tried this but it outputs a list?
Oh ok then I actually had it right earlier 🤦♂️ I was thrown off by the list
Thank you both
In some configurations of others i see a state trigger -> to: ~ I cannot find anything in the documantation about trigger to "tilde". Can someone explain or give directions where i can find info in the documentation?
Ahh, already found my answer....#automations-archived message
It was published here, though it does seem to be missing from the trigger documentation 🤔
https://www.home-assistant.io/blog/2021/12/11/release-202112/#triggering-on-any-but-only-state-changes
Basically it's the same thing as to: , which is documented. I believe it's just a feature of YAML syntax, that an empty value, ~, null, Null, and NULL are all accepted as the same thing.
(also I see this is not a templates question)
Trying to create my first template by reading the temperature of a weather entity. I have the following, and I have loaded all yamls, but when look up dev tools states, I do not see the template.
- platform: template
sensors:
weather_temp:
friendly_name: "Weather Temperature"
unit_of_measurement: 'degrees'
value_template: "{{ state_attr('weather.local_weather', 'temperature') }}"
IIRC if it's your very first template, you need to do a reboot, and not just a yaml hot reload
In the future you can do yaml reload for changes or additions of new templates. It's just that when you have none, the platform is not even loaded, so it doesn't know how to do reload.
Hope this is the correct channel to post this apologise if not. I have a Zigbee double socket that I control with the following Yaml using the Value_template but I guess I need a condition as when I operate one switch it affects the other as they both have the same value of 'Power' but there is another value of 'Endpoint' which is either 1 or 2.
@red pebble I converted your message into a file since it's above 15 lines :+1:
any way to convert existing template sensors (edited in yaml) into the new UI-driven ones?
I can see the new sensor created in /config/.storage/core.entity_registry and core.config_entries....
Also, is there any way to get a multi-line template editor in the UI (for those new templates)?
Also, is there any way to export/import these?
Copy paste
Pretty sure you can just hit return to get more lines
Not currently, but blueprints are a future thought
Hmmm I’ve got about 30 of the things. Not sure I’d bother
Sensor goes to 'Unknown' because the host is offline
Command failed (with return code 255): ssh -i /config/.ssh/brendyn -o 'StrictHostKeyChecking=no' pizza@192.168.51.25 "type interactive.txt"
When the whole point is to show the host is offline
I use a avlue template if yes, true, else false
Why is it ignoring my template?
Good Morning
is this the right way (especially the last line) to make sure, that the sensory will have a valid value? No matter if there is a unknown/unavailable sensor before?
@cerulean karma I converted your message into a file since it's above 15 lines :+1:
Or is there something like a try...catch that you should use?
What is best practice or best working way to manual manipulate/correct data of a trigger template? If I do it via developer tools or via python hack services or custom integrations, which can set values to sensors, it is returning back to the old value after HA restart. As far as I tried until now.
The way I'm currently using is another trigger (template reload) and then a value temporarily assignment in changing the template. Then reload. And then reverting back to the wanted template and reloading again. Then it ofc stays.
But I wonder if there is an easier/better way.
You want to manipulate the state of a trigger based template sensor?
Yes
I would use an event trigger, and send a custom event in your automation
What's the use case here?
Correct wrong data because of HA bug. 😂
Okay, but you want to use the state of a sensor unless it's faulty?
After I correct it it is not faulty anymore at the moment.
I have no automation here. Then perhaps my current way is faster. I only thought there is a value box or way, where I can directly set it to a new value and where it stays after reboot.
You can also send the event in devtools, or just use an input_number
Is the correction consistent (like dividing by 10,100,... or addition/substraction)?
No. One time value change.
Yes. But then I have to change my trigger template sensor as well. Then I can stay with changing the template to direct assignment of the right value once and then returning back to the real template. But ofc thanks for your idea. I will use it if this will happen more often in one sensor.
Background: It is about https://github.com/home-assistant/core/issues/100096 where I have now a wrong sum because of the (fixed but not rolled out) bug.
data:
message: >-
{{ states('sensor.mobiel_xxx_last_notification','android.text') }}```
When i template the state with dev tools, its the full long text. But when i use it in this write-to-file-service, its get cut to a certain amount of chars. Didnt count but maybe 255 chars?
so im using an attribute which can contain more then 255 chars. So its something the service-call chops up to 255
What is the best way to change the values from a devicetracker from athome+away to on+off?
do I really have to create binarysensors for each?
probably but why do you need them to be on/off?
I use them to represent the state of Laptop/PC,... in a custom:mushroom-entity-card.
and if the Laptop is powered on the card says "At home"
does the card support templating?
{{ states.sensor | selectattr('entity_id', 'search', 'tgtg') | map(attribute='state') | map('int', 0) | list | sum }} beschikbaar
{%else%}
geen TGTG
{%endif%}```
NOW: This does a count(adds) all states of all selected entities, whenever they are non zero. for example 21 is the output from 4 entities.
WISH: Output the amount of entities which has it state non zero. So i don want 21. but 4.
do i? lol
yes you do
