#templates-archived
1 messages · Page 61 of 1
calendar get_events migration and understanding what i'm doing
Can someone point me to where I can find all available functions in templates and what each does in hass?
The are links in je topic description
Oh, I hoped there where more organised and cleaner docs on that somewhere. But I guess those will do too.
I'm setting up a state-switch card that uses a template. I have confirmed that the media player's source is currently HEOS 3 - Aux In, but it's returning Other. What am I missing? {% set source = state_attr('media_player.kitchen.heos', 'source') %} {% if source == 'HEOS3 - Aux In' or source == 'Kitchen Aux In' %} Aux {% else %} Other {% endif %}
this is not a valid entity_id: media_player.kitchen.heos
The HA logs probably mentioned that
Yeah stupid typo on my part
@stiff plank I converted your message into a file since it's above 15 lines :+1:
Can someone show how to exclude every but the last 5 symbols - eg 11:11
Hi all... I'm using decluttering card. I want to pass either a temperature sensor or a message to a card. How do I check in the template whether the passed variable has a value?
Something like this (but this doesn't work)
{% if [[temperature_sensor]] != null %}
Temperature
{% else %}
Message
{% endif %}
If you have a string you can use slicing {{"abcdefg 11:11"[-5:]}}
I'm using scrape an get a text and timestamp- I only want the timestamp
Think I need something along these lines
Anyone ?
Why isn’t didgeridrew’s suggestion working for you?
You can enter
{{ value[-5:] }} in the 'Value Template' section in the sensor in the UI
@stiff plank
#integrations-archived message
Hello, how would a template light look like that is a pure dummy, does nothing but supports everything. It will be used in automations.
How would I go about creating a sensor that allows me to switch between N other sensors? For instance, I have 4 temperature sensors from ESPHome devices and I want to be able to choose one of those to "be" this sensor (so I can use it as the sensor target for the ESPHome Thermostat)
Add the demo integration.
You’ll get every domain, as a fake entity
But i need several lights, not just one.
Is that possible with the demo integration?
can someone give me a hint on how i need to write a template to get from
"{'weather.mycity': {'forecast': [{'datetime': '2023-12-10T00:00:00Z'}]}}
to
"{'forecast': [{'datetime': '2023-12-10T00:00:00Z'}]}"
I guess you are referring to the service response change for weather forecasts?
Instead of response.forecast it's now response['weather.your_weather'].forecast
ok but how do i strip the ['weather.your_weather']
i have some other things that rely on the prevoiuse format
Depends on what those other things are
We can help you better if you share your code
ok sure, I'm parsing the weather forcast to create a long string which i use on an esphome with a attached epaper display to show the weather.
originally i was using the forecast entity, when that went away i created a template sensor which was updated hourly, and used that in turn to again create the string
my assumption was that it would be easiest to manipulate the template sensor using forecastS in a way that is has the same format as the previous version which was using forecast (singular)
Hi folks, was hoping some one could help me with this. I want a template binary sensor that is on if numeric value (of another sensor) is below x and off if above y. notice that is 2 seperate numerical values it needs to evaluate against. If it is between those 2 values it should keep its existing state. Any help would be greatly appreciated.
Hi there. I'm running HA Container on Podman, and today I updated from 2023.8.x all the way to 2023.12.1. It looks like there was a behavior change (or I'm just not remembering right); the built-in YAML editor has started expanding shorthand template conditions to full on condition: template / value_template clauses. This just makes my stuff harder to read. But I like using the built-in editor. Is there a way I can make it stop doing that?
Yes I think that is new behavior, and no you cannot control it (short of not using the visual editor).
What's the rationale for this change? It's just making all my scripts more unwieldy.
There were bugs in how the visual editor processed the shorthand templates, it was difficult to handle them, so it is converted to a standardized format.
Hmm. That's interesting. At least it seems to only do the conversion when I load up a script in the visual editor. If I change them back to shorthands, it won't re-expand them when I hit save.
yes the expansion would occur as part of loading in visual mode.
Is it possible to have the default view for scripts be the YAML view? Would that sidestep this behavior?
No it's not possible, but I suppose it would work if that was possible.
That's a bummer. Okay, thank you.
This can be simplified here and there, but you need to share the sensor in which you store the forecast
Do you only use the forecast for this sensor? Because you can als create this sensor with the response without the need to store it in an attribute
so basically. the template sensor was featuring the forecast for the next days and the other template sensor was creating the string wich I was using vor visualization on the epaper display
Yeah, but you can do that in one sensor, without the need to store the entire forecast
Firstly, entity_ids are always lowercase
I know i just redacted the actual city 🙂
Okay
You just need to change the last line to
forecast: "{{ MYCITY_forecast_waveshare['weather.MYCITY'].forecast }}"
Which was what I already said here #templates-archived message
OH GREAT, sorry i did't get ist where to change in the first place!
that helped, thanks a LOT!
you are defing the variable weather twice here, the first one will be overwritten by the second
this does what you did, but then without the need to store the forecast as an attribute
https://dpaste.org/hXCgb
thanks!
whoops, misplaced a quote, replaced the link
what's the easiest way to check if a calendar event happened yesterday in a templated sensor?
You can only access that by using a service call:
service: calendar.get_events
data:
start_date_time: "{{ today_at() - timedelta(days=1) }}"
duration:
hours: 24
minutes: 0
seconds: 0
target:
entity_id: calendar.your calendar
response_variable: yesterday
if you use that in a trigger based template sensor, you access it in your template
How can I make a condition that checks for an entity not existing? 🙂
{{ states.sensor.foo is none }}
having trouble with a template in a service call. in dev tools this works fine:
service: climate.set_temperature data: temperature: "{{ state_attr('climate.aircon_test' , 'temperature')|float | round(0) + 1 }}" target: entity_id: climate.aircon_test
but when i call climate.set_temperature from a chip card tap action it says expected float for dictionary value @ data temperature
service call is written as
tap_action: action: call-service service: climate.set_temperature data: temperature: "{{ state_attr('climate.aircon_test' , 'temperature')|float | round(0) + 1 }}" target: entity_id: climate.aircon_test
You can't use templates in calls like that. Make a script that does that and call the script instead
this is really a #frontend-archived thing
got it thanks. didn't realize we couldnt template in a front end call. thought my template was problematic
how do we guard a value to be in the index of a list? eg {% set bft = 16 %} {% set colors = ['lightblue','paleturquoise','aquamarine','greenyellow','lime', 'mediumspringgreen','yellowgreen','navy','gold','orange', 'tomato','orangered','maroon'] %} {{colors[bft] }};
using that with an actual entity ofc, with possible values 0-12. so the list is length 13.
I did try this {{colors[bft] if bft <= colors|length else 'grey'}} but still get
list object has no element 13
which is correct, but it doesnt move to the else on 13, if I go beynd that the else does kick in.
aarrgh.. typo.. <= {{colors[bft] if bft < colors|length else 'grey'}} works ok.. never mind me, sorry
Ya, when checking indexes, < is correct
is there a function/filter for median?
or do I need to do something like:
{% set list = [2.3, 2.5, 2.1] %}
{{ (list | sort)[(list | count / 2) | round(0, 'floor') | int] }}
I´d still be looking for a template light, that is just a dummy light and does nothing, so I can put automations between it and my physical light.
can't you just use an input boolean?
no one will write that out for you because it will require about 10 different input helpers
which is why I suggest using the demo platform.
Not to mention, it will be a very hard and large template entity
okay, I'll settle for this for median then
{% set list = [2.3, 2.5, 2.1, 2.4] %}
{% if list | count is odd %}
{{ (list | sort)[(list | count / 2) | round(0, 'floor') | int] }}
{% else %}
{% set mid = (list | count / 2) | int %}
{{ (list | sort)[mid-1:mid+1] | average | round(2) }}
{% endif %}
Just make a macro
I don't see a median filter
should be easy enough tho
should be a filter & func
I think it's better to use median for my combined template weather instead of the average
so that's why I was looking for it
But I wanted to share it on the forums as a package, so I don't want to make it more complicated with an additional custom template.
Really? Why can I not just put a template light in my config with no function?
Because the function needs to work in order for it to have the function
I tried the demo platfrom but couldnt find out how to control the number of lights.
what do you want it to support? only on and off, or also brightness, color_temp, color etc?
i.e. if you want to have brightness, you need an input_boolean that represents your brightness
if you want effect list, you need an input_select that reflects your effects
Thank you. That´s too much work then for my dozens of lights i need.
if you want color, you need 3 input numbers that reflect RGB
if you want white color, you need an input number that reflects your white value
Yeah, got it.
hopefully now, you can see why no one wants to help 😉
and all of that for each light (if you want to be able to set them different from each other)
only on/off is simple 🙂
Do you know how I can config the demo platform? Doesnt seem to be possible, is it?
and even then, you need an input_boolean for the on/off
yes sure 🙂
you can't, w/ the demo integration you just get a few demo lights & entities
Can the template light not store information on its own?
No
light when i define turn_on:
self.turn_on or something like that
no
There must be a solution to my flashing problem.
well, you never asked that question, you asked about template lights
that's why we have a macro
The XY problem is asking about your attempted solution rather than your actual problem.
What´s a macro?
what I used above
the xy problem
it's so common that we have a bot message for it
it's when users don't explain the real problem, they ask some random ass question that has nothign to do with the real issue, when they could have asked about the real issue instead
I did ask the real question in general yesterday.
you can use template lights for that, but use the values from the actual light
Template lights wont' solve that problem
if you're saying alexa turn on lights to 1% and the lights flash 100% then 1%, that will always happen
yes
as the hardware is doing that.
let me guess TUYA devices?
we had that discussion yesterday
It´s not about the hardware
It´s hue devices.
Let me explain further.
I have hue devices and they don't do that, so...
I have an automation that turns on a light to the desired brightness (and other things) whenever it is turned on. So the light will always receive two light.turn_on. First without payload, second with payload.
After a certain time I want my lights to turn on at 1% brightness for example.
So if I say to Alexa. Turn on light.
you can template the entire data field to include or not include brightness in the first light.turn_on
It should turn on at 1%.
you don't need 2 light.turn ons
How do I avoid the first one, when it is done via Alexa or UI button?
alexa only sends 1 light.turn_on call
your automation is doing 2
unless you set up some janky solution in alexa
Yes, but I would need to modify that light.turn_on call from alexa which i cant?
So my automation is waiting for the light.turn_on without payload and then sends another one with the right brightness.
.... why
What would you suggest to solve it?
Can I modify the light.turn_on from alexa or UI?
I mean, if it is a physical button, it´s easy. I directly call my automation instead of turning on the light. So only one light.turn_on with brightness is issued.
Please explain why you're intercepting a light.turn_on service
To turn on the light to a brightness when no brightness was specificied.
but why, please explain why you are doing this
Specify a brightness
For example to turn it on at 1% brightness when the user just turned it on.
"I'm doing this because I want the birghtness at 4am to be xyz"
Different brightnesses at different times.
Amongst other things.
And when the prior brightness was larger than the new one, the light will flash.
That would be a template light that you expose to alexa
if you want light settings per time of day
There we go with template lights again for every light.
keep in mind, that will still not work for physical button clicks
but not a dummy light, you need to base it on the actual light
there'sn o way to intercept that
Yeah, then my template light idea was not too off.
unless you have smart buttons (like a shelly in detached mode). You can then use the button press to toggle the template light as well
I only have smart buttons. I dont use light switches that cut electricity anymore.
And for buttons there is no problem already.
But instead of programming template lights for every physical light, i´d rather write my own addon or integraton that automatically creates template lights for the real one and links them already.
you can create one, and use anchors for the others
Anchors?
What´s that?
"{{ this.entity_id }}" since when is this possible?
dunno, a year maybe?
I suppose they try to set the brightness with a single light.turn_on call in an automation, write template lights or live with it
But there is absolutely no way to stop/manipulate the first light.turn_on call?
I use adaptive lighting to intercept those calls and let that decide the brightness needed
Or the Flux integration
My scheme is the following right now. I have 3 automations for every light. One auto on which handles stuff that turns on a light automatically light motion, doors, etc. This one calls the on automation which turns on a light to the desired settings like brightness, etc. Then i have an auto off automation which turns off a light based on motion, time, etc. That´s how it´s done?
Ok, I have some questions about adaptive lightning and flux:
- Can they set the brightness and temperature of lights to desired values at certain times?
- Can they put lights which are already on to the desired values with custom transition time like 10 seconds?
- When lights should not be changed under certain circumstance (e.g. they are currently red to notify me of something), can I specify they shouln´t be modified in those circumstances?
- How do those integrations intercept the turn_on call?
I have very precise requirements for different lights to what values they should be set at different times.
None of what you described requires intercepting the service call
the only time you'd need to intercept the service call is from a physical switch
all the other times, you program it to handle the light
What about Alexa and UI turning the light on at 8:05 pm when the brightness from 8 pm onwards should be at 1%?
you can make a script that gets a brightness from a look up table. Make the script accept any light entity. Have all your automations call that script
why the hell is alexa doing that
HA is for automations
alexa is for voice control
I mean voice control via Alexa.
that's the only circumstance that you'd need a template light
literally
all the other ones, you program into your automations
And buttons in the HA UI?
automation
But how? The buttons directly issuse the turn_on command
no, you can make a script and have the button call the script
that's what tap_action is for
So I wouldnt have my real lights in the UI anymore but instead buttons that start my automation?
no... you change the tap action
from toggle, to call-service
and instead call a script that turns on or off the light w/ the desired intensity
there's about 800 ways to do this without intercepting the turn_on action
Where/how can I do that?
have you ever built a script?
See above
No, you have a script.
- in the UI you assign that script to the
tap_action - with outside control you will control a template light in alexa that in turn triggers an automation in HA with the same script to control the real lights
I have built scripts before, but I still dont get how i would link the buttons in UI for my lights? What is the difference between a script and an automation that just has actions?
the action section of an automation is just a script
please take 5 minutes to read about tap_action
So i can always use automations instead of scripts?
there's nothing to understand if you read about tap_action
But for that template light I would still need the complex template light with all its helpers?
I feellike you're overloading your brain
because now you're completely mixing things up
we stated multiple times that you don't need the helpers w/ the template light for what you want to do, after you explained what you wanted to do
Oh I think I get it.
I have a template light which always controls the real light directly except for a turn on command without payload?
right
And in the UI and Alexa I put my template lights instead of my real ones?
sure if that's what you want
Then i dont even need tap actions do I?
nope
Nice
and for not having to do it for every light I can use anchors?
I dont even need to check if the payload is empty. I could just always call my on automation for the real light when the turn_on for the template light is issued.
you can use anchors to cut down the yaml, yes
Where can I find the doc for those anchors?
yaml anchors are documented all across the internet
theya re not an HA thing
they are a yaml thing
ok
thx
Still a lot of work for a little flash
Is there a way to determine whether it was alexa who issued the turn_on?
If you give alexa a unique user, you can use the context object to figure out if it was her or not.
otherwise, no
probably not
cleaning up my log, I have this warning on startup.
Error in 'choose[0]' evaluation: In 'template' condition: TypeError: argument of type 'NoneType' is not iterable
Most of my choose templates are like trigger.id == 'foo' which would cause this right? This would be something like 'bla' in variable
what about a template entity?
it needs to be a trigger based template entity with an action section then, as otherwise it can't use choose
but I searched on choose in VSCode in my whole config
I'll try again..
regarding the median function/filter.. I'm looking in core/homeassistant/helpers/template.py
would it be as simple as:
def median(value):
"""Take the median value"""
return statistics.median(value)
statistics is already imported.
Oh, and add
self.filters["median"] = median
oh and self.globals["median"] = median
yes, I already understood the tests are the tricky part in HA PR's 😛
Jup that was the easy part haha, tests can be awful 😛
Why does this:
"{{states.light.flur.state}}" work, but this:
"{{states.light.flur.brightness}}" doesnt?
because brightness is an attribute
states.light.flur.attributes.brightness
or use the states method
state_attr('light.flur', 'brightness')
this doesnt work, this gives "on"
but no the brightness
typo
whats preferable? state_attr or states?
states.light.flur.attributes.brightness
and
state_attr('light.flur', 'brightness')
is the same, isnt it?
one uses the state object, one accesses the attribute from the state object safely
so which should i use?
always use the states method or state_attr method
avoid state objects unless you know how to code
states.light.flur.attributes.brightness is preferable then?
{{ state_attr('light.example', 'attribute') }} for an attribute```
- "You can do anything in templates"
- "Jinja uses various delimiters in the template strings.
{% %}..." - "you need to use a namespace if you're planning modify a variable..."
- "I see a lot of folks ask for how to know, of a group, who was th..."
- "To count lights which are on, and exclude light groups, note tha..."
- "Jinja (Template) Built-ins jinja.palletsprojects.com/en..."
- "Distinguishing Yaml from Jinja (templates) community.ho..."
- "Confused about the 2022.2 breaking
defaultchange? c..." - "Understanding types to parse JSON community.home-assist..."
- "@689168555861737485 Here's a template that looks up a friendly..."
whoops, I meant
Become a real Jinja2 Ninja! Don't worry my Genin, we are here to help! You can find general Jinja docs at https://jinja.palletsprojects.com/en/3.1.x/templates/, Home Assistant extensions at https://www.home-assistant.io/docs/configuration/templating/, and trigger variables at https://www.home-assistant.io/docs/automation/templating/
This channel is for support with Jinja templates. Some custom Lovelace cards support other types of templates, such as those written in JavaScript, and #frontend-archived is the right channel for that.
Please use http://pastie.org/, https://dpaste.org/, or https://paste.debian.net/ to share code or logs
Why is this worse than?
This looks more like what i´m used from programming tho.
*used to
Since it avoids using strings.
Do i have to restart HA for every template light change?
@thorny cargo I converted your message into a file since it's above 15 lines :+1:
if you just added the light for the first time, you have to restart
if you make changes to an existing light template, you can reload template entities
Invalid config for 'light.template' at configuration.yaml, line 69: some but not all values in the same group of inclusion 'effect' 'lights->dummy_flur-><effect>', got None, please check the docs at https://www.home-assistant.io/integrations/template
Why is that?
you need effect_template most likely
you have a template for the list, a action for the effect, but you don't have what the current effect is
Nice, works like a charm
Have I got everything then in my template?
The bar for my color temperature doesnt work. It sets the temperature but no controller is shown
Why does my dummy not get the temperature of my real light?
temperature_template: "{{state_attr('light.flur', 'color_temp')}}"
Should be fine, shouldnt it?
Yep
The controller bar for temperature of my dummy is still missing even though i addes min and max mireds to my template light.
Seems like the dummy cant get the temperatue of my real light.
You are just "pulling" the temperature as current state. You likely haven't the set_temperature service call.
Setting temperature works.
What doesnt work is that the dummy shows the current temperature.
Have you looked into the Dev tools, if your template shows the expected output?
Light is probably off 🤷
No, it´s on
What do the states in the Dev tools say?
<template TemplateState(<state light.dummy_flur=on; min_color_temp_kelvin=2000, max_color_temp_kelvin=6535, min_mireds=153, max_mireds=500, effect_list=['blink', 'breathe', 'okay', 'channel_change', 'candle', 'fireplace', 'colorloop', 'finish_effect', 'stop_effect', 'stop_hue_effect'], supported_color_modes=[<ColorMode.COLOR_TEMP: 'color_temp'>, <ColorMode.HS: 'hs'>], color_mode=hs, brightness=255, color_temp_kelvin=None, color_temp=None, hs_color=(28.391, 65.659), rgb_color=(255, 166, 87), xy_color=(0.526, 0.387), effect=None, friendly_name=Dummy Flur, supported_features=36 @ 2023-12-11T16:45:09.538803+01:00>)>
and that are those of the real one:
<template TemplateState(<state light.flur=on; min_color_temp_kelvin=2000, max_color_temp_kelvin=6535, min_mireds=153, max_mireds=500, effect_list=['blink', 'breathe', 'okay', 'channel_change', 'candle', 'fireplace', 'colorloop', 'finish_effect', 'stop_effect', 'stop_hue_effect'], supported_color_modes=['color_temp', 'xy'], color_mode=color_temp, brightness=255, color_temp_kelvin=4291, color_temp=233, hs_color=(26.727, 29.841), rgb_color=(255, 212, 178), xy_color=(0.405, 0.36), effect=None, friendly_name=Flur, supported_features=44 @ 2023-12-11T16:45:09.537201+01:00>)>
And why are you using another template now? We have been talking about {{state_attr('light.flur', 'color_temp')}}
It depends on the color mode your light is in. Color mode hs doesn't provide color_temp,
Regardless of the mode my light is in, the dummy cant show a temperature since it cant switch to temperature mode.
How would I use anchors to use my code for a list of light names?
Color temperature doesn't exist in Hue/Saturation
Yeah and the template light cannot switch to temperature mode, thus never has a temperature.
But it can still set it.
To get the state a workaround might be to use hs_template instead of temperature_template
I already got hs_template. Removing temperature_template doesnt change anything.
Can I use my template light code for mulitple lights?
Question does some1 have a template to set a state of a entity to sleeping?
in this case my entity 🙂
Hi All… any idea how to go about sorting this error in my logs?
2023-12-12 12:17:27.913 WARNING (MainThread) [homeassistant.helpers.template] Template variable warning: 'dict object' has no attribute 'motionDetectorStatus' when rendering '{{ value_json.motionDetectorStatus }}'
You don’t set entity states, states are updated by devices
Do you have that template in your system?
I dont think so… nothing in the config.yaml file anyway.
Plus all my “helper” based motion groups seem to be OK as well. I literally dont know where the error is coming from. 🙂
Mqtt then, discovery
I currently have a simple binary sensor template helper made:
{{ states('sensor.living_room_cube_sensor_angle_x')|float > 85 }}
How do i add more entity's to this? So the binary sensor only turns on during multiple entity values being correct? And is it possible to make this between two values instead of currently >85?
Or would something like this work?
{{ states('sensor.living_room_cube_sensor_angle_x')|float < 90 }}
{{ states('sensor.living_room_cube_sensor_angle_y')|float > 80 }}
{{ states('sensor.living_room_cube_sensor_angle_y')|float > 90 }}
{{ states('sensor.living_room_cube_sensor_angle_z')|float > 80 }}
{{ states('sensor.living_room_cube_sensor_angle_z')|float > 90 }}```
thanks!
I would do it like this:
{% set x = states('sensor.living_room_cube_sensor_angle_x') | float(0) %}
{% set y = states('sensor.living_room_cube_sensor_angle_y') | float(0) %}
{% set z = states('sensor.living_room_cube_sensor_angle_z') | float(0) %}
{{ [x, y, z] | select('>', 80) | select('<', 90) | list | count == 3 }}
you need one true or false. Not 6 true or false
I assume they all need to be true (so x, y and z should be between 80 and 90)
Hi, I have a MQTT sensor and the integrated MQTT broker. I now implemented the sensor. which works. I also would like to use the availablity, because after a HA start the sensor is still unavilale. but I have a block here where Im stuck. Can someone enlighten me? http://pastie.org/p/5XcCy8BjGEam9cN2d3yafk
thanks for the response! i need each sensor to be a different value, your template makes it for all sensors the same value
that's becasue I used your example
so x, y and z need to be between different values in order to activate the binary sensor.
ah i see, my bad then.
in that case:
{% set x = states('sensor.living_room_cube_sensor_angle_x') | float(0) %}
{% set y = states('sensor.living_room_cube_sensor_angle_y') | float(0) %}
{% set z = states('sensor.living_room_cube_sensor_angle_z') | float(0) %}
{{ 80 < x < 90 and 60 < y < 70 and 50 < z < 95 }}
looks weird, that it starts with a value, then x, then the secondary value. thanks a lot though! don't understand how it works but as long as it does^^
works perfect, just tested^^ gonna make some nice HA-p0rn from this 😄
it basically states that x should be between the 2 values
you could also do it in 6 seperate steps if that's more readable for you:
{{ x > 80 and x < 90 and y > 60 and y < 70 and z > 50 and z <95 }}
does this work with minusses? so if -5 to 5? i created one if the sensor is upside down or top (the z changes from ~ 90 to ~ -90, but now both top and bottom binary sensors are activated.
no
if you want it to work with minuses, add | abs to each value
As a sidebar, i'm 99.999999% sure a blueprint for this device already exists
is it the xiaomi magic cube? In that case, yes
It's gotta be
I don't know any other device that has cube in the name that reports angles
it's a vibration sensor, the aqara's.
{% set x = (states('sensor.living_room_cube_sensor_angle_y') | float | abs) %}
{% set x = (states('sensor.living_room_cube_sensor_angle_z') | float | abs) %}
{{ -5 < x < 5 and -5 < y < 5 and -85 < z < -95 }}```
Unfortunately not working 😦
whoops, already see why pasting it here.
🏗️
-85 < z < -95
You'll never get negative values anymore
what do you mean?
changed this to x y z at the start of the lines, didn't make it work.
if you add abs your values will always be positive
70 will remain 70, but -70 will become 70 as well
and even when you would still get negative values, -85 < z < -95 will never be true. A value can not be above -85 and below -95 at the same time
if you use abs, remove all the negative signs in your last line
abs is absolute value
i.e. always postive number
but that makes it not work at all.
it should, the value is negative in order to make the binary sensor work.
dude
z2m reports the current z-axis is -90.
if your values are always positive because use ABS, then how will x ever be -?
yes, and you converted that to 90 because you used the abs filter
so it can't work with minuses? it didn't work before i added abs, and now neither, because of abs then, as i understand it.
and yeah, not great at math and code.
you added abs where you declare x, y and z
that will mean you will not have negative values anymore
{% set x = (states('sensor.living_room_cube_sensor_angle_x') | float | abs) %}
{% set x = (states('sensor.living_room_cube_sensor_angle_y') | float | abs) %}
{% set x = (states('sensor.living_room_cube_sensor_angle_z') | float | abs) %}
{{ 0 < x < 5 and 0 < y < 5 and 85 < z < 95 }}
-80 will be considered the same as 80
that will work with both postive and negative numbers
yeah i understand that now, thanks. learning something new every day 😄
but converts negative to positive because of abs. therefore if the sensor reports on z-axis -90, that template wont actually work.
or?
that template will work, because -90 will be converted to 90 by the abs filter, and 90 is between 85 and 95
But that's not good. Because the sensor can report between 85-95 when its facing up. It reports -85 till -95 when facing downwards ^^
If i would then use the template and understanding correctly, both binary sensors would turn on.
Both the binary helper set for upwards facing, as the one for facing downwards with negative z value.
we don't know of any binary sensors, we only know of this particular template you are asking questions about. We don't know what you are trying to achieve
The XY problem is asking about your attempted solution rather than your actual problem.
so, it might be helpful if you would describe your problem, and what you are trying to achieve
the device/sensor reports x y z values on different entity's. when its facing down, its z sensor is reporting 90 degrees. so the value 90. when its facing down, its reporting -90 on the same z axis. on both situations i want to make a action for it.
as stated before, you should look into the blueprint
it's an automation thats already set up for you, you just fill out the fields
That's not an answer to my question. But anyway, you don't have to use abs, if you want to be able to see if the device is upside down, don't use it
thanks you too! ❤️
pretty sure you didn't understand his repsonse
Still trying to help here
i got it figured out by removing the abs, and swapping the minus and positive numbers in Z (and the x and y sensors)
yes, that was what i was trying to suggest 🙂
sorry for being stopid quite some times.
@jolly cradle I converted your message into a file since it's above 15 lines :+1:
I've written a message and I got a reply that it got converted to a file. is anyone able to see the file/message?
it was over 15 lines long.
@limpid stratus I converted your message into a file since it's above 15 lines :+1:
@restive swift I converted your message into a file since it's above 15 lines :+1:
@limpid stratus remove - sensor: above the 2nd sensor. It isn't placed under the trigger now, so it can't access the variable with the forecast
Hi, I have a MQTT sensor with the integrated MQTT broker. I now implemented the sensor. which works. But after HA start it is (of course) unavailable. I would like to change that, I have a block here where Im stuck. Can someone enlighten me? http://pastie.org/p/55cyGv924LRsiyeCFV0Hms Thanks 🙂
Is there some way I can rate limit this template so that it doesn't change its state more often than a given interval?
{% if now().minute >= 40 and (((states('sensor.amsleser_houruse') | float / (now().minute)) * 60) | round(2)) > 4 %}
{{ True }}
{% else %}
{{ False }}
{% endif %}
Hi,
ive been using a automation to list calendar events and turn a input boolean on or off if there are events or not. This work until the service changed from „list events“ to „get events“
@icy jay I converted your message into a file since it's above 15 lines :+1:
- service: calendar.get_events
data:
duration:
hours: 120
minutes: 0
seconds: 0
response_variable: response3
target:
entity_id: calendar.db
conditions:
- condition: template
value_template: "{{ response1.events | count > 0 }}"
- condition: template
value_template: "{{ response2.events | count > 0 }}"
- condition: template
value_template: "{{ response3.events | count > 0 }}"
then:
- service: input_boolean.turn_on
target:
entity_id: input_boolean.kalenderanzeige
data: {}
Any ideas why this wont work anymore?
Thats what the 2023.12 change says:
The output of this newer service changed slightly, as it now returns a mapping of entity IDs to lists of events instead of a list of events.
That solved it:
{{ response2['calendar.ics'].events | count > 0 }}
I have a bunch of template sensors in my template.yaml file, and I need to create a float variable to be used in each sensor to calculate energy cost, how can I define this variable?
this is an example of sensor that I have:
- sensor: - name: Frigo yearly cost unit_of_measurement: "€" state: "{{ (float(states('sensor.frigo_consumi_yearly')) * float(0.35)) | round(2) }}"
I want to replace 0.35 with a variable so I can just change it instead of changing the value in each sensor every time
hi! is |has_value supposed to work on binary_sensors? If not what's the proper thing to do? I want to set up an availability template based on some binary_sensors having a known state
By putting it as a state template in a trigger based sensor, but why would you want that?
Yes, that should work
Use an input number
BUt this is what I get in 2023.12.1, in the template devtool:
{{states('binary_sensor.sealed_salon' )}}
{{states('binary_sensor.sealed_salon')|has_value}}
output:
off
False
You know you have two different entity ids there right?
yeah that was a stupi typo/ it's the same
You need to use it on the entity id
Not on the state
{{ 'binary_sensor.sealed_salon' | has_value }}
oh i see -- that's a bit funny. Ok indeed it works
price_per_kwh: name: price per kw/h initial: 0.35 min: 1 max: 10
something like this? it works also with float?
It's not is_value, it's has_value
You can define it in the GUI as well, under helpers
You need to use it in the same way as your sensor value, so het the state and convert it to a float
in the helper I cant find the initial value when I create a "number" helper
but if it is defined as number, it is integer? if so how can I set a 0.35 value? if it is a string than I can cast to float when I use it
nevermind, they are float already https://www.home-assistant.io/integrations/input_number/#initial
All states are strings, so also the state of an input_number will be a string
Why do you want to set an initial value?
I will use the initial value to set the price per kw/h
I need a variable that I can update manually on needs
it is not a calculated value in HA itself
I understand that, but I don't think you understand what the initial setting does.
That will set it back to 0.35 on every restart of HA
While otherwise it will just restore the previous state
yeah, I will change the initial value if I need to change the cost per kwh, or there is a better way to do it?
min/max is something that I dont need
I am doing like this now:
price_per_kwh: name: price per kW/h initial: 0.35 min: 0 max: 10 unit_of_measurement: "€/kWh"
- sensor: - name: Totale total cost unit_of_measurement: "€" state: "{{ (float(states('sensor.totale_consumi')) * float(states('input_number.price_per_kwh')) | round(2) }}"
but I think something is wrong
You don't need the initial value, you can just change the value on your dashbord or in the entity settings
ok, so you suggest to create it with "number" helper? but I only see max and min, where exactly I can set the value?
ah ok, after the creation and using steps of 0.01
Yes
ok, so now if I try to use it I get Invalid config for 'template' at templates.yaml, line 135: invalid template (TemplateSyntaxError: unexpected '}', expected ')') for dictionary value 'sensor->0->state', got "{{ (float(states('sensor.totale_consumi')) * (states('input_number.price_per_kwh')) | round(2) }}"
- sensor: - name: Totale total cost unit_of_measurement: "€" state: "{{ (float(states('sensor.totale_consumi')) * float(states('input_number.price_per_kwh')) | round(2) }}"
oh, missing )
weird that the HA config checker did not discovered it
e.g. of using float and round properly:
{{ (states('sensor.totale_consumi') | float * states('input_number.price_per_kwh') | float) | round(2) }}
config check only looks at yaml
ah
it does not look at anything in the yaml fields
I don't like this syntax, but I see that it less prone to errors
that's the intended way to use jinja
you can even do...
{{ states('sensor.totale_consumi') | multiply(states('input_number.price_per_kwh') | float) | round(2) }}
Hi there!
I would like to change the color of a light based on some sensor state;
Short story is we are having multiple tarriff for electricity and I would like to change color of a light based on the current tarriff.
The sensor I have is: sensor.current_price with those states: "Bleu, Blanc, Rouge, inconnu"
I'd like the light to be blue when state is bleu, white when state is blanc etc...
What would be the best implementation?
an automation, not using templates, using the choose action/sequence with state conditions that lead to light.turn_on actions using the accompanied color
if you aren't afraid of templates, there are template solutions to this problem
@fierce hawk ^
@honest wing I converted your message into a file since it's above 15 lines :+1:
wrong channel, sorry
tap_action:
action: call-service
service: button.press
data:
entity_id: button.gencel_doruk_restart
yea I also just realized it #frontend-archived message
I was so blind! Thanks anyways!
Question is it possible with a template to change a state from person. to another state ?
i can do it with the developer tools
No, templates do not offer a way to set states
is there another way to achieve this?
You should focus on the device_trackers that are assigned to the person
how do you mean that ?
its my phone + Smartwatch
i would like that this would say Sleeping
https://i.imgur.com/sVd0pS3.png
instead of home
and when my automations detect that some stuff will trigger, like my curtains who close
and some devices cant trigger stuff anymore
ha didnt knew the HASS app also tracked battery state
Seems like you really want a template sensor or input_text
Is it possible to use a template to reuse the options from an input_select helper, as the valid options for a scripts field.
I'm trying to do this but I'm surely missing something as this isn't working as the definition for the script field.
option: selector: select: options: "{{ state_attr('input_select.sitting_room_activity', 'options') }}" name: option required: true
could you explain to me how i could make it ?
And ping me because that would make it allot easyer to find for me for tomorrow 🙂
Anyone know a good way to strip the leading zero off a sunrise time? {{ (states('sensor.sun_next_rising') | as_timestamp | timestamp_local | string)[11:16] }} will give me 07:30
- name: 'HOME power total'
unique_id: home_power_total
device:
identifiers: energymon3
name: "ENERGYMON3"
model: "Sonoff Basic"
manufacturer: "Tasmota"
device_class: power
state_class: measurement
suggested_display_precision: 0
unit_of_measurement: "W"
state_topic: tele/ENERGYMON3/SENSOR
force_update: true
value_template: "{{ value_json.ENERGY.Power[0] }}"
based on the above template, I would expect that changing "W" to "kW" would divide the value by 1000 and show "kW" as a suffix; but It multiplies by 1000 and stays in watts... what am I missing?
{{ (states('sensor.sun_next_rising') | as_datetime | as_local).strftime('%-H:%M') }}
Thanks, that worked! Is there an easy way to get this as 12h time as well?
Sweet 🙂
weird. seems like It didn't want to change/process units unless I changed the entity_id; now works....
I'm looping thru an array in the attributes. I'd like to use a filter for the time comparison but comparing a str to date is bad. Is this unpossible with a filter? Can I change the component to define types on the attributes?
example:
{% for ass in state_attr('sensor.infinite_campus_assignments', 'assignment') | selectattr('missing', 'equalto', true)| sort(attribute='duedate') -%}
{% if as_datetime(ass.duedate)> now() - timedelta(days=14 ) %}
{{ ass.assignmentname }}
due date: {{ ass.duedate }}
{% endif %}
{%- endfor %}
if the property in the component was date time I assume this would work..selectattr('duedate', 'lt', two_weeks_ago)
@timber cliff How is the datetime string formatted? If it's an isoformat datetime string in either UTC or your local time, you can easily create a string to compare with
Can I shorten this somehow? {% set precipitation = state_attr('sensor.weatherman_data_tag','wm_precipitation_0') %} {% set precipitation_unit = state_attr('weather.forecast_home','precipitation_unit') %} {% if precipitation == 0 %} '' {% elif precipitation > 1 %} {{ precipitation | round | string + ' ' + precipitation_unit}} {% else %} {{ precipitation | string + ' ' + precipitation_unit}} {% endif %}
{% if precipitation > 0 %}
{{ precipitation | round(0 if precipitation > 1 else 2) ~ ' ' ~ precipitation_unit}}
{% endif %}
no need for the string filter if you use ~ to join the parts
or use
{% if precipitation > 0 %}
{{ [precipitation | round(0 if precipitation > 1 else 2), precipitation_unit] | join(' ') }}
{% endif %}
Hmm. Any idea why this is not recording the time of the first opening for the day? https://community.home-assistant.io/t/sensor-for-first-time-binary-sensor-is-tripped-each-day/654827/2?u=tom_l
has_value needs to be applied on an entity_id, not an a state
so has_value(this.state) will always be false
template:
- trigger:
- platform: state
entity_id: binary_sensor.your_sensor_here
to: 'on'
sensor:
- name: Sensor Daily First On Time
state: >
{% set opened = states[trigger.entity_id].last_changed %}
{% if as_datetime(this.state) is not none and as_datetime(this.state).date() != opened.date() %}
{{ opened }}
{% else %}
{{ this.state }}
{% endif %}
device_class: timestamp
that should work I think
yes, that is done by the date comparison
Yep I see that now. Thanks.
if the date of the current state is the same as the date of opened, it will return the current state
Yeah. This bit: as_datetime(this.state).date() != opened.date() I just saw my attempt using .day was missing and jumped to the wrong conclusion.
Counting down until they ask me to format the datetime as they want...
incoming in 3... 2...
0.5...
the person who requested this last time the door was opened sensor to request for a different format for the datetime
I have an automation that does that
makes a mqtt device and plops in door information
who opened the door, when it opened, when it closed, etc
I should probably turn that into a blueprint
how do you know who opened it?
you can infer that information, or you can pull it from the context (if they used the UI)
e.g. the sensor displays "Mike or Lindsay", if my wife or I are home
so, one of use must have opened the door
ah sure
That stops working if you also have a kids without device trackers 😉
TheFes, 4yo or 2yo opened the door
just cut off thier hands
jk
but yes, we don't have kids, so it's pretty easy for us
I use a template to detect if guests are home via devices connected to my guest vlan
on a more serious note about stopping your 2 and 4 year old from opening the door, you can get those spinning plastic things that don't allow them to spin the door knob
@radiant vine I converted your message into a file since it's above 15 lines :+1:
That went well... anyway if somebody could help i would be glad 🙂
Probably had some strange indentation problem there.
Yea tänks. I got it fixed
Hello! I could need some help with a template.
speech_engine:
mode: queued
sequence:
- variables:
media_player: !include players.yaml
[ truncated ]
- service: input_number.set_value
target:
entity_id: input_number.media_player_volume
data:
value: "{{ state_attr(media_player, 'volume_level') }}"
The set_value does not set the value. But in dev-tools-->templates (and the template below is the above players.yaml):
{% if player == 'office' %}
{% set media_player = 'media_player.office' %}
[ truncated ]
{% endif %}
{{ media_player }}
{{ state_attr(media_player, 'volume_level') }}
returns:
media_player.office
0.37
it's since I used this that it doesn't work. Before, while testing, I hardcoded "media_player.office" instead of the variable media_player
data:
value: "{{ state_attr(media_player, 'volume_level') }}"
roughly 40 lines of IFs. But this has been working for 4 years and still does. I recently implemented the volume control
@wintry bay I converted your message into a file since it's above 15 lines :+1:
if it's a list, state_attr(media_player, 'volume_level') won't work
{% set media_player = 'media_player.hallway, media_player.living_room, media_player.office' %}
that will be resolved as a list
true! but that currenty is not active because the IFs falls in another case
returns:
media_player.office
0.37
it returns both the media player and the level?
I don't see that include showing a number anywhere
the long code returns the media player. The numebr comes from "{{ state_attr(media_player, 'volume_level') }}"
I copied both of them in Dev tools -> templates
is there an error in your logs?
not about this :/
Then it should be working
i can also copy the script
You're most likely looking in the wrong spot or the path the script is taking isn't what you expect
yeah, it should :/ but doesn't, and I thought it's my eyes failing somewhere
view the trace
the logbook doesn't save any trace for this script. There is an input boolean that I use for testing, this triggers a test message. It helps me while writing the templates and the scripts used - but the whole speech system doesn't leave any trace if you mean the tree-like tool that shows the debug trace of anything
so it's the boolean that produces the list?
ok this is awesome!
no, the boolean that i was toggling was running a different speech pipeline. The "testing" one uses another which is the one I'm working on
the templates and all is correct - i was just calling the wrong script that started the speech engine
about the list: that is a condition that 100% won't work, but it's also on IF that is never triggered. It is a residue from when I was using Alexa as media player
but thanks! really!
Does anyone know if theres a way to use area_entities in a template sensor, so that when entities are added or removed to a given area, the template sensor itself dynamically picks up on the change?
Today I added various power entities into my living room and expected my template sensor that iterates through them and totals their power together, to reflect the new entities but it seems that the area_entities doesn't listen for changes in the entities in the area.
Rebooting HA of course made it then pick up the changes.
Interesting, I hadn't thought about that. It's not based on entities, so there's no tie-in to the state machine
I thought that there was an event for when an entity is added, and there still may be, but I don't see it documented here: https://www.home-assistant.io/docs/configuration/events/
Yeah I had been trying to optimize all of my custom template sensors and had previously being recommended to use the area_entities, which did work great, but yeah it seem to have this slight downside. Whether its by design or not I guess is the question. Its not a big deal but I guess it might surprise people when it doesn't pick up on changes to the area of some entities.
Would it require some sort of like 'area entities changed' event.
Right, just "entity added" isn't enough. And it's not in the state machine, so isn't represented in a state_changed event
Ahhh ok, got it.
you know.. as much as I hate large language models.. Bing is actually 'okay' at writing template code...
Or at least, writing it enough so you can kinda bodge it
.. generally
Hi
some help please with a sensor template.
I want to swop the sign of a energy value that is coming in from my inverter > states('sensor.sunsynk_battery_power'))
it comes in as a negative when charging the battery and as a positive when its depleting the power.
{{ (states('sensor.sunsynk_battery_power') | float | abs) }} - This would just make it always positive.. but not when its positive .. to negative.
multiply with -1
Yeah I was just thinking that 😄
{{ states('sensor.sunsynk_battery_power') | float * -1 }}
gets flashbacks of square roots, imaginary numbers..
I could use a hand actually with some template code that I cant seem to make work. I need to read the value from an array and return that that time -2 hours. (which I have working) BUT it needs a second check that if the event start time is after 4pm then the resulting time should be 2 hours before 4pm. {% set event = state_attr('event.octopus_energy_octoplus_saving_session_events', 'joined_events')[-1]['start'] %} {% set timestamp = as_timestamp(event) %} {% set two_hours_prior = timestamp - 2*60*60 %} {{ two_hours_prior | timestamp_custom('%H:%M', true) }} {{ 'true' if now().strftime('%H:%M') == two_hours_ago else 'false' }}
do you really need the string true and false? Is this for a binary sensor?
Its for a trigger template so I think it does? (It needs to return true/false was my understanding)
it will retrun true or false if you just do
{{ now().strftime('%H:%M') == two_hours_ago }}
it will actually retrun a boolean value then, not a string
and you our returning both a time string and true or false
I think you intended to do this:
{% set event = state_attr('event.octopus_energy_octoplus_saving_session_events', 'joined_events')[-1]['start'] %}
{% set timestamp = as_timestamp(event) %}
{% set two_hours_prior = timestamp - 2*60*60 %}
{% set two_hours_ago = two_hours_prior | timestamp_custom('%H:%M', true) %}
{{ 'true' if now().strftime('%H:%M') == two_hours_ago else 'false' }}
you never defined the variable two_hours_age, you just outputted what it should be
I would do it like this though:
{% set event = state_attr('event.octopus_energy_octoplus_saving_session_events', 'joined_events')[-1]['start'] %}
{% set two_hours_ago = (event | as_datetime | as_local).strftime('%H:%M') %}
{{ now().strftime('%H:%M') == two_hours_ago }}
test that in devtools > templates first, it could be that the value is already a datetime, and then it will retrun an error
Is this not only going to change the value from pos to neg?
no, multiplying with -1 will turn positive values negative, and negative values positive
you can easily try for yourself using a calculator
Hm.. give me a sec to go over this as Im not sure I understand 😄
Ahh right right I see
Yeah it complains that the value is already a datetime and not a float 🙂
remove the as_datetime filter then
{% set event = state_attr('event.octopus_energy_octoplus_saving_session_events', 'joined_events')[-1]['start'] %}
{% set two_hours_ago = ((event | as_local) - timedelta(hours=2)).strftime('%H:%M') %}
{{ now().strftime('%H:%M') == two_hours_ago }}
Yeah that produces a 'false' result which should be correct 🙂
Just as well, I thought that was working when it clearly wasnt haha. Now for the next bit to check if its before 4pm and do something different if it is 😄
Thanks , 🙏 , and to get the value rounded to no digits just add? round(0)
yes, but make sure not to round only -1
{{ states('sensor.sunsynk_battery_power') | float * -1 }} round(0)
no, the round filter needs to be inlcuded in your template, so within the curly brackets
{{ states('sensor.sunsynk_battery_power') | float * -1 round(0) }}
no.. you have to declare a filter by using the pipe | character, just like you do for the float filter
oh that would round the -1
and that
Thanks , all working.
So, just looking at this Im actually a bit confused as wouldnt this amke 'two_hours_ago' just.. be equal to the event time?
🙂
Hi everyone,
trying to extract the first two letters of the first word and first two of the second word of the area_name. But I am guessing that I have to write my idea differently:
@dry narwhal I converted your message into a file since it's above 15 lines :+1:
was doing like 10 other things, but I .. think this code does what I want? (its hard to tell) ```TEST:
{% set event = state_attr('event.octopus_energy_octoplus_saving_session_events', 'joined_events')[-1]['start'] %}
{% set two_hours_ago = ((event | as_local) - timedelta(hours=2)).strftime('%H:%M') %}
{% set cutoff = (today_at('14:00') | as_local).strftime('%H:%M') %}
{% if two_hours_ago >= cutoff %}
Window is after the Cutoff
{{ now().strftime('%H:%M') == cutoff }}
{% else %}
Window is before the Cutoff
{{ now().strftime('%H:%M') == two_hours_ago }}
{% endif %}```
Fixed it myself. Will post once I have ensured it won't throw an error when only one word
So it should read the avlue of the saving session, and check what the time is 2 hours before that point, if the resulting time after 2pm, it should return 'true' if the time is actually just 2pm. If the result is BEFORE 2pm it should return true at.. whatever time is 2 hours before... ... if that makes sense
(i.e. if the trigger time in 'event' was 6pm, it should return true if the actual time is 2pm, If the 'event' was at 3pm, it should return true at 1pm)
My head hurts haha.
Mine did too after reading it 😄
Unfortunately I cannot help. But looking forward to reading how you get on 🙂
My fixed code is:
@dry narwhal I converted your message into a file since it's above 15 lines :+1:
(Just if someone is looking for something similar 🙂 )
@dry narwhal why are you using that first for loop
you can just do:
{% for item in states.climate | selectattr('entity_id', 'search', 'eq3', ignorecase=True) -%}
{% set a_name = area_name(item.entity_id) %}
{% set name_split = a_name.split() %}
{{
{
"type": "thermostat",
"entity": item.entity_id,
"name": name_split[0][:2] + name_split[1][:2] if name_split | length > 1 else a_name[:4]
}
}},
{%- endfor %}
Why doesn't this work anymore? 🤔
{%- set seendevices = namespace(entities=[]) -%}
{%- for device in states.device_tracker -%}
{%- if(device.attributes | length) == 2 and device.state == "home" -%}
{%- set seendevices.entities = seendevices.entities + [device.entity_id] -%}
{% endif %}
{%- endfor -%}
i have ping device trackers which i need to count
i see ping devices, with 2 attributes and state "home" in my entities list
seendevices.entities however is empty
there's most likely more or less attributes
you should be using integration_entities('ping') anyways
🐌
@arctic sorrel please put the sonic run emoji on the previous snail emoji. Thanks.
my ping entities have 6 attributes
Yes, now that they moved to the UI, the number of attributes most likely changed
round_trip_time_avg: 1.058
round_trip_time_max: 1.698
round_trip_time_mdev: ""
round_trip_time_min: 0.418
device_class: connectivity
friendly_name: Server
integration_entities('ping') wasn't a thing also when I did this afaik
thanks, got it to work with that
I'm still waiting for tinkerer to put the sonic emoji on the snail emoji
device.state is empty though
this worked before
{{ integration_entities('ping') | select('is_state', 'home') | list }}
it's not a state object, before you had state objects
saying things like "this worked before" when you aren't understanding why it worked before doesn't help the convo
anyways, this is what you can use now.
I'm just baffled
it's not baffeling, you used a really odd way to figure out the state objects were from the ping integration
where is my breaking change announcement about device.state 😡 🤬
true
the number of attributes changed
which broke your bad template
ping was listed as a breaking change
anyways, use the template above, it's easier now
my ui still only shows source and ipattributes
entity list shows friendly_name being added
clear your cache and refresh the page, those are most likely the old unused yaml entities
ping was moved from yaml to the UI
and the dev tools -> states page and entity lists use caching for speed, which sometimes missleads users
can confirm
device.state is not why no entities were found
it's the check on 2 attributes
the ping entities which are moved to the GUI have more attributes
I am working on an automation that notifys me when a door is opened. I am sure i can do this with templating but not sure how to get the variable for it. I want to have the notification tell me which binary sensor was triggered in the message i.e "your {{ back_door }} was just opened" while there being several different triggers.
well... It worked? lol
trigger:
- platform: state
entity_id:
- binary_sensor.door_1
- binary_sensor.door_2
to: "on"
action:
- service: notify.something
data:
message: "{{ trigger.to_state.name }} just openend"
outstanding thank you very much @marble jackal .
ok
{% elif state_attr('climate.fancoil_studio', 'current_temperature') | float > state_attr('climate.fancoil_studio', 'temperature') | float + 0.2 %}
warm
{% elif state_attr('climate.fancoil_studio', 'current_temperature') | float < state_attr('climate.fancoil_studio', 'temperature') | float - 0.2 %}
cold
{% endif %}```
mm i'm trying to figure out how to make a template that compares 2 values and i'm at the point where the first if is es: 22.5 it returns ok, if 22.2 returns cold and 22.8 warm.. how can i make so that between 22.3 and 22.7 is still resulting ok in the first if?
{% set current = state_attr('climate.fancoil_studio', 'current_temperature') %}
{% set set_temp = state_attr('climate.fancoil_studio', 'temperature') %}
{% set cold = set_temp - 0.5 %}
{% set warm = set_temp + 0.5 %}
{% if current > warm %}
warm
{% elif current < cold %}
cold
{% else $}
ok
{% endif %}
wow this works in the template sensor perfectly, thanks!
had to fix the typo in else part
Okay, I'm presumably getting something easy wrong, but I'm blanking. I'm trying to make a template binary sensor just blindly follow the state of a binary helper variable, and it's just not showing up as an entity, and I don't seem to get an error log.
`
- binary_sensor:
- name: "Wasmachine loopt"
unique_id: "SensorWasherRunning"
device_class: power
state: >
{{ states('input_boolean.washer_running') }}`
- name: "Wasmachine loopt"
The code in the {{}} successfully returns on or off in the devtools template page.
(and the template binary sensor right above, in the same file, with the same indentation, does show up and has done so for many months.)
ooooh. Bloody hell. It appears to be a naming conflict.
I would advice to use more unique unique_ids.
I always use a UUID. You can generate then using https://www.uuidgenerator.net/
It should be fine as long as you don't create a second sensorwasherrunning in the template integration
I dislike UUIDs, but it certainly seems like it would work better.
Yeah, I’m still not sure what exactly is going on, but it seems like starting it with template or sensor is a no-no.
well, under the hood that unique_id is already prepended w/ template
“template.”, right?
Yeah, I don’t really understand why it wouldn’t like that. But in the interests of making my life easier I might just move on to UUIDs because I don’t really care what it is.
not sure, it doesn't really matter. It's only to make it unique under the hood in the system
In the visual code studio add on you can generate them with a right click of your mouse
I did also notice that in the unique ID to entity name transition it seems to translate my CamelCase into camel_case, so it’s doing weird stuff.
that part of the HA extension?
Oh, good, that’s useful, cause I am using that.
Don't know for sure, maybe it's even built in VSCode 🤷♂️
what's the shortcut combo?
Could you explain further?
Just a input text and let the automation set the text sleeping in it or awake and trigger stuff from it
Think this would be a template question?
I have a Aquara Dual Relay Zigbee device. I have it paired to Home assistant with a third party zigbee controller. If I had it paired using one of aquara's zigbee hubs, there would be an option to change the relay to a "pulse" mode vs a hard on/off relay. Since I dont own an aquara hub I am not able to change this...
I currently have it wired into my garage door and it works, but I have to toggle the switch twice in home assistant to make it operate. (Switching to pulse mode, would normally fix this)
Is there a way I can change the type of device in home assistant to a button vs a switch, or essentially make it open and close with press in home assistant. Basically using software, make it "pulse"
Please DO reply to this and or mention me if your able to help. 🙂
Should I log a feature request or bug report on this one do you think?
Template button integration would be a good fit for this. Confusingly it is not a template question, as no templates are actually required. So #integrations-archived would have been a better fit, ```
template:
- button:
- unique_id: "garage_door_button"
name: "Garage Door"
icon: "mdi:garage"
press:- service: switch.turn_on
target:
entity_id: switch.your_switch_here - delay: 1
- service: switch.turn_off
target:
entity_id: switch.your_switch_here
- service: switch.turn_on
- unique_id: "garage_door_button"
It's a new feature
OK cheers. Is that something a layman like myself should log, or should it come from someone with a bit more knowledge and power 🙂
Nobody else will do it
If you have a feature request for the frontend you can open one here, for Home Assistant itself please post on the forum. All other feature requests should be made to the developer of that custom card/component.
Just post on the forum
Can anyone help me modify the template below? I'd like to adjust the template so that it only picks from four specific colors rather than the entire RGB spectrum.
data:
rgb_color:
- "{{ range(255)|random }}"
- "{{ range(255)|random }}"
- "{{ range(255)|random }}"
target:
device_id:
- 472d84c9d68d751c9b5f51ae2ad7036b
- f823e6ed66629c44c7ba41a6f622c1e0```
I considered swapping rgb_color: with color_name: but wasn't able to discern the proper syntax for a list of colors (red, green, blue, orange).
Can you do something like the following?
data:
rgb_color: >
{{ [[100, 200, 150], [255, 255, 255], [1, 1, 1], [255, 0, 0]] | random }}
target:
device_id:
- 472d84c9d68d751c9b5f51ae2ad7036b
- f823e6ed66629c44c7ba41a6f622c1e0```
Also as a side note, get in the habit of never using device id’s whenever you can avoid it
Funny you should mention the device id. That’s actually the way HA converted the initial UI action into yaml.
Yeah it does that now to make device replacement easier. Unfortunately it completely obscures the entity id.
Oddly enough, this didn't have any effect.
I did manage to cobble together this template color_name: "{{ ('blue','green','red','white')|random }}" which is pretty close and working. I'm going to keep playing with the RGB angle since it would be nice to have the full flexibility of RGB.
Ha! This ultimately works. No idea why. rgb_color: "{{ [[255, 0, 0], [0, 255, 0], [0, 0, 255]] | random }}"
And there it is
If I was looking for the time of day it was first triggered (rather than number of minutes or hours ago), would I pipe ( | ) an as_local in the line where the opened variable is set?
Hello, I have a JSON from a REST API (grocy api in particular, with list of all products in my stock)
I'd like to create a sensor that has, in its attributes, the list of all the products
the JSON is in the form of
[{"name":...},{"name":...},{"name":...},{"name":...}]
it's an array
how can I add all the products as attributes of the sensor?
with value_template: "{{ value_json | length }}" I get the count of them properly
I would need something like
json_attributes_path: "$"
json_attributes:
- amount
- name
- expiry
etc...
json_attributes: >-
{% for x in (value_json|from_json) %}
{{ x.amount }}
{% endfor %}
This doesn't seem to work
You can't
Only by putting the names in yourself, you can't use a template for that
json_attributes: >-
what you mena jq?
The attributes in a rest sensor can't be templates
The only thing you can determine is the dictionary which contains the attributes
Just FYI there is a grocy custom integration. https://github.com/custom-components/grocy
Hi! i would like to trigger an automation 30 minutes before my phone alarm goes off. I have tried this:
- platform: template
value_template "{{ states('sensor.time') == (state_attr('sensor.sm_a546b_next_alarm', 'timestamp') - 30*60)|timestamp_custom('%H:%M', false) }}"```
I do not know anything about templates and found this on a forum. Im using the right sensor. But nothing triggers.
Could someone help me with this? \:)
what does {{ state_attr('sensor.sm_a546b_next_alarm', 'timestamp') }} return in
-> Templates?
Does anyone have any idea why this is returning '93ABD9' when the input boolean is off?
{% if is_state ('input_boolean.stove_enabled', "on") + states ('sensor.flue_sensor_stove_flue_temp') |float <= 190 %} #93ABD9
{% elif is_state ('input_boolean.stove_enabled', "on") + states ('sensor.flue_sensor_stove_flue_temp') |float <= 375 %} #D47428
{% elif is_state ('input_boolean.stove_enabled', "on") + states ('sensor.flue_sensor_stove_flue_temp') |float <= 600 %} #EF0F0F
{% elif is_state ('input_boolean.stove_enabled', "off") -%} white
{% else %} white
{% endif %}
you're adding a boolean to a float?
this kinda thing makes no sense:
is_state ('input_boolean.stove_enabled', "on") + states ('sensor.flue_sensor_stove_flue_temp') |float <= 190
I guess you want and where you have +
RobC thank you.. I have literally been pulling my hair out for two hours with this
null
in the states tab Sensor.sm_a546b_next_alarm has these attributes Local Time: Sun Dec 17 01:00:00 GMT+01:00 2023 Package: com.sec.android.app.clockpackage Time in Milliseconds: 1702771200000 device_class: timestamp icon: mdi:alarm friendly_name: SM-A546B Next alarm
oooh wait so timestamp is not there
feel free to debug that kind of stuff on your own 🙂
Hey all! I just installed the LCARS theme / templates and I have a quetion -- I seem to have lost the 3 dot menu in the upper right corner, replaces with the text UNKNOWN. If I siwtch back to the default or other theme ( non lacrs ) it comes back
Any suggestions ?
I think it's this extension https://marketplace.visualstudio.com/items?itemName=netcorext.uuid-generator
Which comes with the add-on
I was thinking of making a jinja macro for this https://community.home-assistant.io/t/a-better-mold-sensor/656916?u=tom_l and the state template seems eaisly doable, but how would I deal with the availability template?
In
, {{ state_attr('sensor.arcadia_christian_church', 'stream') }} currently returns true.
How do I convert that to properly be used in a button card? This does not work - I always get grey
type: custom:button-card
entity: sensor.arcadia_christian_church
triggers_update: sensor.arcadia_christian_church.stream
state:
- value: 'true'
color: rgb(255,0,0)
- value: 'false'
color: rgb(55, 55, 55)
It's probably a boolean value, not a string. Remove the quotes around true and false
I've tried that, still no dice.
Oh wait, you are checking on the entity state, not on that attribute value
Yeah... How do I check the attribute value from the
template in the card?
Do I need to build some sort of helper sensor and make the comparison on that in the card?
If I add show_state: true to the card, it gives me the name of the current stream.
which makes sense that 'true' or true isn't ever going to match that...
That's a question for #frontend-archived
Created a template helper that looks at that state, Set the button-card to look at the helper state instead. Took a few more tries to realize that it was returning 'True', not true or 'true', but it's working now.
Hello everyone. I need help with a sensor and im prettry new to this homeassistant. 🙂
- name: "Elpris ekskl elafgift"
unique_id: elpris_ekskl_elafgift
state: {% set elafgift = (0.86120) %}{% set elpris_ekskl_elafgift = (states('sensor.elpriser_inkl_afgifter')|float) - elafgift %}{{ elpris_ekskl_elafgift }}
unit_of_measurement: DKK/kWh
Thanks for letting me rubberduck, @marble jackal
here i try to substract 0.86120 from my sensor "sensor.elpriser_inkl_afgifter"
it works when im trying it in Developer tools -> Template
but not when im putting it in my template file
when i try to start homeassistant after adding it I ger the following error: "found character '%' that cannot start any token"
What am I doing wrong? 🙂
need quotation marks around the template
To avoid my template turning into a huge mess, is it possible to define a custom function myself with a return value?
I need to look at the weather conditions reported by my weather service, and map these to weather icons in HA. It will use substring matching since the local weather service has tons of variants, and I only need to use maybe 5 icons in HA.
Do I need to reload HA between modifying my file on disk to keep working on the macro?
Also, I'm not clear on where exactly to do the from include in my automation yaml.
you do the from every time you start new jinja
to reload macros, call the reload template macro service call
Hmm. Would this be correct?
...
- type: icon
value: >-
{% from 'weather_icon.jinja' import weather_icon %}{{ weather_icon(state_attr('weather.gatineau_hourly_forecast', 'forecast')[0]['condition']) }}
x: 160
...
that's one way
@marble kestrel I converted your message into a file since it's above 15 lines :+1:
I'm trying to set up a template sensor. It's supposed to map zha_events for a specific zigbee device. However, I can't even get the simple event listener from the documentation page to work: https://www.home-assistant.io/integrations/template/#turning-an-event-into-a-trigger-based-binary-sensor
Awesome, macros are working 🙂 thanks!
so i got the most stopid question of the day....
In the following topic, first reply, a user gives instructions how to create a dummy light....but where the heck do i enter that template in order to create this dummy entity? 😅
https://community.home-assistant.io/t/create-a-virtual-dimmer-or-light-template-for-alexa/74025
hello template masters! i am trying to make sense of my self build mqtt sensors by having them push their measurements over a shared topic instead of having the device id included there. This should result in something of a payload like this {"hw_id":"<emac>", "sn_ix":"<index>", "celsius":<measurement>, ...}
Based on the string supplied in hw_id id like it to reference a device and sn_ix a sensor entity displaying the measurement
could anyone help me figuring out what i need to setup to do this? I am already able to grab the measurement through a value template, but i cant seem to find what needs to be done to be selective about the data origin
it goes in the light section
light section? all i know is entity's, devices, helpers.
light:
in configuration.yaml or something? 🤔
Not really sure what you're asking
thanks, that did the trick ❤️
currently i have an mqtt sensor like this
https://xgob.in/26wj4vgd
this will receive an update with the data from any payload and therfore no sensor specifically
the payload however includes fields to identify which esp and sensor it is from which i would like to use to assign the data to the correct sensor entity
When using numeric state as a trigger with sun.sun, can the below be a template? e.g.```
below: "{{ states('input_number.lights_sun_elevation') }}"
When reloading I get an error in the logs saying it expected a float. I have tried with this and get the same error:```
below: "{{ states('input_number.lights_sun_elevation') | float }}"
How can I format a value of an entity which is a datetime as string to a custom time format?
I've tried already with "|asdatetime" and then "timestap_custom("%-H:%M", default=0), but the default (empty) is shown.
Wiothout the default I get a hint, the input value is invalid.
Try this?
{{ states('input_datetime.test_datetime') | as_timestamp | timestamp_custom("%-H:%M")}}
Input value is still invalid (I've did the timestamp converstion before)
ValueError: Template error: timestamp_custom got invalid input '1702854941.0' when rendering template
Got it, have to convert as_timestamp to float, then I can pass it to rimestamp_custom.
You can’t template the above: and below: thresholds, but you can specify an entity that has a numeric value as its state
The docs have an example of this:
https://www.home-assistant.io/docs/automation/trigger/#numeric-state-trigger
You can make a set of template entities that usess the state topic and fall back on their previous state.
template:
- trigger:
- platform: mqtt
topic: temperature-probe
sensor:
- name: x
state: >
{{ trigger.payload_json.celsius | round(1) if trigger.payload_json.hw_id == 'x' else this.state | default }}
That seems rather smart!
I suppose this would effectively not trigger an update on the recorder for that entity?
it shouldn't
but that's the route I'd take for the most part
not sure how good the code is, but it should work
Is there an easy way to replace only the last occurence of a character in a string? I've got a template that returns a list of entity friendly names separated by a comma. The last comma should be replaced with an " and".
Currently: A, B, C, D
Wanted: A, B, C and D
reverse and replace once?
{{ "A, B, C, D" | reverse | replace(",","dna ",1) | reverse}}
Oh, thats smart 😄 Thank you
I asked chatgpt in the meantime because I remembered that existed and it came up with this
| regex_replace(',([^,]+)$',' und\1')
I have no idea what's going on there. It works but I might change to your solution simply because I understand it 😄
yeah regex can get quite complicated.
Hm, is there. a way to pull the array value for several different enties and check an array and return a count on how many are true?
I hvae several 'climate.wiser_roomname' and want to create ac ount of how many of those have the value 'is_heating:true'?
{{ states.climate | selectattr('attributes.is_heating', 'eq', True) | list | count }}
haha, your so good at this petro 😄
Long live the Oxford Comma!
It's for an automation that notifies me on one of my Sonos speakers that at least one of the windows is still open when I open the door to leave my apartment. I tried it without the "and" and it just sounds super weird to me 😄
The 'and' is fine, it's the lack of that crucial comma 🙂
Is there a way to check the state of an entity 3 seconds ago? this is my starting point
{{ (now() - states.binary_sensor.office_pmth_presence.state=='off') }}
No
i was thingking something like this
{{ (now() - states.binary_sensor.office_pmth_presence.state=='off').total_seconds() < 3 }}
but that wont work
Templates have no access to historical state
It works with last changed
this works as a true false
{{ (now() - states.binary_sensor.office_pmth_presence.last_changed).total_seconds() < 3 }}
I have a temp sensor that becomes unavailable for exactly 10 minutes then it comes online again. How can I make something that it always shows the last known temperature
You can make a template sensor that just updates when the source sensor has valid values
That sounds like a good plan, are there some instructions that I can follow?
this.state can be used to represent the current state: https://www.home-assistant.io/integrations/template/#template-and-action-variables
I’ve tried it but it’s really hard for someone without any knowledge
template:
- sensor:
- name: Holly Weight
unique_id: holly_weight
state: >-
{% set weight = states('sensor.litter_robot_4_pet_weight')|float %}
{{ weight if weight > 13 else this.state }}
now you have some knowledge
afternoon guys!
I have a template sensor entity, but I'm having a hard time to list on attribute (one item per line)
{% set unavailable = expand(area_entities('Balcony'))
| selectattr('state', 'eq', 'unavailable')
| list
| map(attribute='name')
| join('\n') %}
{{unavailable}}
It seems the linebreak is stripped out when rendering inside attributes , is there a workaround for this?
Thank you!
Hi, I'm willing to learn HA and reading a lot using Google, but all suggestions do not work for me. That's why I#m trying to get an answer here.
Having an entity card with several entities.
Now I want to change the icon color upon the value, i.e. battery is low. I've tried this what I found
type: entities
entities:
- entity: sensor.working_room_battery
name: Natterie
icon: mdi:battery
style: |
:host {
--paper-item-icon-color: red;
color: red;
}
But getting "Der Schlüssel „entities.3.style“ wird vom visuellen Editor nicht erwartet oder nicht unterstützt." which means, "style" is not supported.
Had to look up what the Oxford comma is exactly 😅 looks like I misunderstood. Luckily the Oxford comma isn't a thing in German 😉
The fight could lead to armed conflict
There's a book that touches on it: https://en.wikipedia.org/wiki/Eats,_Shoots_&_Leaves?wprov=sfti1
OK, trying to make a template light based on the example at https://www.home-assistant.io/integrations/light.template/#make-a-global-light-entity-for-a-multi-segment-wled-light but I'm getting this error when I try to set effect to "none": Failed to call service light/turn_on. string value is None for dictionary value @ data['effect']
Does anyone know of a template method that can combine multiple climates as one? Or to create a single climate entity that will relay commands from itself to two others? I created a climate group which presents as a "group.climates_example" entity and isn't good for my needs.
My use case: I have two minisplits hooked up to the same heatpump, two broadlinks, one for each. Both broadlinks with their sensors are using smartIR (https://github.com/smartHomeHub/SmartIR) to give me two climate entities.
Because there's only a single heat pump, my minisplit modes need to be synced with one another. Again, the climate group is fine for issuing synced commands to both devices via automation, but since it's not a "climate.example" entity, I can't use it with my preferred Simple Thermostat (https://github.com/nervetattoo/simple-thermostat) card on the dashboard.
As an alternate solution, I was going to ditch the climate group altogether and control only one climate entity via both manual dashboard control and automation, then have a separate automation set Climate 2 to the same attributes as Climate 1 whenever it changes. The problem I ran into there is that I cannot use a float template as an input to set temperature. The automation rejects the following and won't save it.
service: climate.set_temperature
data:
temperature: {{state_attr('climate.example_1', 'temperature') | float}}
target:
entity_id: climate.example_2
Any Ideas?
quotes around the template?
Thanks, that did what I needed... man, sometimes you stare at something so long and lose sight of the simple solutions, and just need another head to make a comment.
@cerulean oyster I converted your message into a file since it's above 15 lines :+1:
Hi.
Im trying to create a template in the "new" helper menue, but i cant get it to react as i do in the dev-tool->template
{% if is_state("binary_sensor.frient_a_s_wiszb_138_binary_input", "on") -%}
Open
{%- else -%}
Closed
{%- endif %}
It does not update when status is changed to ON
or am i maby doing the whole thing wrong?
why are you doing this when you already have a binary sensor
just change the device_class of the binary sensor to opening or door
or change the "display as"
and your states in the UI will be open/closed
If you were creating a binary template, it wanted the result to be on/off, not "Open" or "Closed".
Yeah... i figured it out, i over complicated a easy thing. thank you both
can someone please tell me, why a variable, that i set in a for loop, is again empty after the for loop?
put them in your sensor/notify.events/notify_events.yaml file
loop scope, jinja does not allow that. You need to use namespace() to store values that you want to use outside the loop.
how?
chances are, you don't even need a loop either
i need a loop for one task, but the second could be replaced, if someone tell me how to properly remove a item from a list
can you post your code?
let me tiedy it up again
The link under my post
I already saw your post and replied to you. I was talking to Lanea with that comment
duplicate key is displayed
I see that, put your code into the file
sensor/notify.events/notify_events.yaml
that's where all your sensors should go
if you want them to be separate, you have to use a different method
@final axle I converted your message into a file since it's above 15 lines :+1:
ok, so
this should output the 'input_text.music_follow', a active tracker list, without the trackers of the user how press a button
{% set ns = namespace(output=[]) %}
....
inside for loop
....
{% set ns.output = ns.output + [ item ] %}
then finally outside the loop
{{ ns.output }}
FYI, there's some other things you can change. e.g.
{% set matching_users = (states.person | selectattr('attributes.user_id','==', "81f3967ff55f4c94afe6e52400d538d1") | list) %}
{% if matching_users | length > 0 %}
{% set user = matching_users | first %}
can change to
{% set user = states.person | selectattr('attributes.user_id','==', "81f3967ff55f4c94afe6e52400d538d1") | list | first | default %}
which will default user to None if there is no element in the list
that's what default does
this work great thx
or you can do this
{% set user = states.person | selectattr('attributes.user_id','==', "81f3967ff55f4c94afe6e52400d538d1") | list | first | default('system') %}
which also removes the {% set user = None %} and the {% set user = "system" %} without the if check
you can even default it to something that resembles a state object to make the rest of your code work
lastly, your whole for loop can be turned into a 1 liner
{{ state_attr(user.entity_id, 'device_trackers') | select('is_state_attr', 'source_type', 'espresense') | list }}
@final axle ^
but a person could have more then one tracker
Yes, that list gets them all
just for you to understand, in the automation, the user id is replaced by a variable
Yes I understand that
state_attr(user.entity_id, 'device_trackers') returns a list of entity_ids
| select('is_state_attr', 'source_type', 'espresense')
filters the list of entity_ids
to only ones that are from espresense
i cant share the automation yaml here, let me upload it to pasebin
But that is an integration
No it's not, that is a file that contains a series of platforms.
the sensor section supports more than 1 integration
you just decided to put it all into 1 separate file
Trust me, put the sensor in that file, it will work
@mighty ledge here you can now see the complete automation as it is right now
Yes, I see that but the code doesn't need a loop is what I'm saying
if you want, you can revise it and re upload it
because i plan to make it public in the future when everything works
all it looks like it's doing is putting a list of entity_id's into an input text
when done, this automation should implement a follow me function for music based on snapcast and espresence
yep, this will be the active trackers list for follow me function
Ok, sit tight
i have two buttons, where a user can add its espresence device trackers or remove it
when they are in the list, the music will follow these trackers
@final axle
trigger:
- platform: event
event_type: call_service
event_data:
domain: input_button
service: press
service_data:
entity_id: input_button.folge_mir
id: "1"
- platform: event
event_type: call_service
event_data:
domain: input_button
service: press
service_data:
entity_id: input_button.folge_mir_nicht
id: "2"
action:
- variables:
triggering_entity: >
{{ trigger.event.data.service_data.entity_id }}
user_id: >
{{ context.user_id }}
user: >
{{ states.person | selectattr('attributes.user_id','eq', user_id) | first | default }}
entity_ids: >
{{ state_attr(user.entity_id | default, 'device_trackers') | select('is_state_attr', 'source_type', 'espresense') | list }}
condition: []
action:
- service: input_text.set_value
target:
entity_id: input_text.music_follow
data:
value: "{{ entity_ids }}"
@mighty ledge tthe background is this manual
https://github.com/MaxxKra/Abfallerinnerung
You aren't listening to my responses and you're talking past me. Take the sensor you put in configuration.yaml, and put it in the file sensor/notify.events/notify_events.yaml. If you aren't unwilling to do that, then there's nothing you can do to make the sensors you want to add work with your current setup with sensor: !include sensor/notify.events/notify_events.yaml.
You either have to change your !include, or add the sensor to your file
there's no in betweens.
home assistant dont like this....
what does it say?
Oh, nevermind, see what I did
hold on
it dont let me save...
alias: Musik folgen
description: ""
trigger:
- platform: event
event_type: call_service
event_data:
domain: input_button
service: press
service_data:
entity_id: input_button.folge_mir
id: "1"
- platform: event
event_type: call_service
event_data:
domain: input_button
service: press
service_data:
entity_id: input_button.folge_mir_nicht
id: "2"
condition: []
action:
- variables:
triggering_entity: >
{{ trigger.event.data.service_data.entity_id }}
user_id: >
{{ context.user_id }}
user: >
{{ states.person | selectattr('attributes.user_id','eq', user_id) | first | default }}
entity_ids: >
{{ state_attr(user.entity_id | default, 'device_trackers') | select('is_state_attr', 'source_type', 'espresense') | list }}
- service: input_text.set_value
target:
entity_id: input_text.music_follow
data:
value: "{{ entity_ids or 'system' }}"
Had to edit it again, try copying it now
it does nothing....
is there a reason you're using an event for pressing the button?
because then i get the user id of the user who presses it
triggering_entity: input_button.folge_mir
user_id: 81f3967ff55f4c94afe6e52400d538d1
user: >-
<template TemplateState(<state person.lanea_lucy=home; editable=True,
id=lanea_lucy, latitude=52.107986, longitude=9.253258, gps_accuracy=100,
source=device_tracker.sm_f936b, user_id=81f3967ff55f4c94afe6e52400d538d1,
device_trackers=['device_tracker.sm_f936b', 'device_tracker.lanea_z_fold4'],
friendly_name=Lanea Lucy @ 2023-12-19T20:42:03.002445+01:00>)>
entity_ids: []
alias: Musik folgen
description: ""
trigger:
- platform: state
entity_id:
- input_button.folge_mir
- input_button.folge_mir_nicht
condition: []
action:
- variables:
triggering_entity: >
{{ trigger.entity_id }}
user_id: >
{{ context.user_id }}
user: >
{{ states.person | selectattr('attributes.user_id','eq', user_id) | first | default }}
entity_ids: >
{{ state_attr(user.entity_id | default, 'device_trackers') | select('is_state_attr', 'source_type', 'espresense') | list }}
- service: input_text.set_value
target:
entity_id: input_text.music_follow
data:
value: "{{ entity_ids or 'system' }}"
Ah, hold on, can't serialize the satates object.
alias: Musik folgen
description: ""
trigger:
- platform: state
entity_id:
- input_button.folge_mir
- input_button.folge_mir_nicht
condition: []
action:
- variables:
triggering_entity: >
{{ trigger.entity_id }}
user_id: >
{{ context.user_id }}
user: >
{{ states.person | selectattr('attributes.user_id','eq', user_id) | map(attribute='entity_id') | first | default }}
entity_ids: >
{{ state_attr(user, 'device_trackers') | select('is_state_attr', 'source_type', 'espresense') | list }}
- service: input_text.set_value
target:
entity_id: input_text.music_follow
data:
value: "{{ entity_ids or 'system' }}"
That should work
i dont need system, but one button (folge_mir) need to add the trackers and the other button (folge_mir_nicht) needs to remove the trackers again from the list
thats what i try to do
so 1 button adds, the other removes?