#templates-archived
1 messages ยท Page 19 of 1
cause I made a booboo
and i'm being dumb
over complicating
{% set currentPrice = states('sensor.electricity_price_total') | float %}
{% set gridFees = states('input_number.electricity_grid_fees') | float %}
{% set threshold = 0 %}
{% set onRate = 0.6 %}
{% set alwayOnBelow = 1 %}
{% set neverOnAbove = 6 %}
{% set ts = (now() - timedelta(hours=1)).replace(microsecond=0).isoformat("#", "milliseconds") %}
{% set today = state_attr('sensor.tibber_prices', 'today') | default([]) %}
{% set tomorrow = state_attr('sensor.tibber_prices', 'tomorrow') | default([]) %}
{% set items = (today + tomorrow) | rejectattr('startsAt', 'lt', ts) | list %}
{% set prices = items
| rejectattr('total', 'none')
| map(attribute='total')
| sort
%}
{% set threshold = prices | select(prices | count * onRate) | first | default(0) + gridFees %}
{% set threshold = min(neverOnAbove,max(alwayOnBelow,threshold)) %}
{% set heater = items
| rejectattr('startsAt', 'lt', ts)
%}
{% set ns = namespace(vars = []) %}
{% for item in heater %}
{% if item.total + gridFees < threshold %}
{% set ns.vars = ns.vars + [{'value': 1, 'startsAt': item.startsAt}] %}
{% else %}
{% set ns.vars = ns.vars + [{'value': 0, 'startsAt': item.startsAt}] %}
{% endif %}
{% endfor %}
{{ ns.vars }}
hmmm wait
TemplateRuntimeError: No test named 28.799999999999997.
hehe ๐
what's the point of the last namespace
you just want a list of items that are below your threshold?
also, the gridfee addition can also be removed for just the threshold because you're adding it in both places
it's a moot calculation
True, I just copied another sensor I have. This one is used to mark when the heater will run on an ApexChart
Like this, the faded area is from this sensor: https://imgur.com/XbiJFwI
ok
{% set currentPrice = states('sensor.electricity_price_total') | float %}
{% set threshold = 0 %}
{% set onRate = 0.6 %}
{% set alwayOnBelow = 1 %}
{% set neverOnAbove = 6 %}
{% set ts = (now() - timedelta(hours=1)).replace(microsecond=0).isoformat("#", "milliseconds") %}
{% set today = state_attr('sensor.tibber_prices', 'today') | default([]) %}
{% set tomorrow = state_attr('sensor.tibber_prices', 'tomorrow') | default([]) %}
{% set items = (today + tomorrow)
| rejectattr('startsAt', 'lt', ts)
| rejectattr('total', 'none')
| sort(attribute='total')
| list
%}
{% set index = (items | count * onRate) | int %}
{% set threshold = items[index].total if index < items | count else 0 %}
{% set threshold = min(neverOnAbove,max(alwayOnBelow,threshold)) %}
{% set ns = namespace(vars = []) %}
{% for item in items %}
{% set value = iif(item.total < threshold, 1, 0) %}
{% set ns.vars = ns.vars + [{'value': value, 'startsAt': item.startsAt}] %}
{% endfor %}
{{ ns.vars }}
wait
fixing
prices I presume ๐
there
index undefined
UndefinedError: 'prices' is undefined
yeah try again
Boom!
man, i'm getting worse at coding without an IDE
That code is for sure more compact than what I managed to whip up, thanks again ๐
it's not really about being compact, it's about using looping over and over
you want to minimize loops
you need to have 2 because you're calculating the threshold
@proud cradle I converted your message into a file since it's above 15 lines :+1:
I'm trying to convert your code to the sensor I just posted above but I don't understand why I'm not allowed to map a value?
I get the entire array in items, with all properties. I just need total.
UndefinedError: 'float object' has no attribute 'total'
when you map it, it changes the object
what are you tying to change? You shouldn't need to map it
It takes the current price and compares with the threshold to see if the heater should run or not right now
So simple version of the first sensor
just binary on/off
post what you're trying
{% set currentPrice = states('sensor.electricity_price_total') | float %}
{% set gridFees = states('input_number.electricity_grid_fees') | float %}
{% set threshold = 0 %}
{% set onRate = 0.6 %}
{% set neverOnAbove = 6 %}
{% set alwayOnBelow = 1 %}
{% set prices = (state_attr('sensor.tibber_prices','today') + state_attr('sensor.tibber_prices','tomorrow'))
| rejectattr('total', 'in', [None])
| rejectattr('startsAt', 'lt', (now().timestamp() - 3600) | timestamp_custom('%Y-%m-%dT%H:%M:%S.000%z'))
| map(attribute='total')
| sort
%}
{% set threshold = prices[(prices | count * onRate) | int] + gridFees %}
{% set threshold = min(neverOnAbove,max(alwayOnBelow,threshold)) %}
{{ (threshold > currentPrice) and (currentPrice < neverOnAbove) }}
That's the original, I just wanted to replace the loop with yours
{% set currentPrice = states('sensor.electricity_price_total') | float %}
{% set threshold = 0 %}
{% set onRate = 0.6 %}
{% set alwayOnBelow = 1 %}
{% set neverOnAbove = 6 %}
{% set ts = (now() - timedelta(hours=1)).replace(microsecond=0).isoformat("#", "milliseconds") %}
{% set today = state_attr('sensor.tibber_prices', 'today') | default([]) %}
{% set tomorrow = state_attr('sensor.tibber_prices', 'tomorrow') | default([]) %}
{% set items = (today + tomorrow)
| rejectattr('startsAt', 'lt', ts)
| rejectattr('total', 'none')
| sort(attribute='total')
| list
%}
{% set index = (items | count * onRate) | int %}
{% set threshold = items[index].total if index < items | count else 0 %}
{% set threshold = min(neverOnAbove,max(alwayOnBelow,threshold)) %}
{{ threshold < currentPrice < neverOnAbove }}
Has anyone an idea to to prevent resets of "total_increasing" sensors`?
is this problem specific to energy? until the templare-sensor went deprecated for mqtt-devices it was a template
but ok, i'll post it there
i have no idea what your'etalking about
none of those have been deprecated
can you point out the deprecation you're referring to @raw pumice
set threshold = items[index].total if index < items | count else 0
What does this actually do, you have a value infront of a if statement?
Is that if reversed so you define the true part before and else after?
It's does the same as:
{% if index < items %}
{% set threshold = items[index].total %}
{% else %}
{% set threshold = 0 %}
{% endif %}
But if first checks the if statement, and then performs the part in front of it
That's not confusing at all ๐คช
Well, you can just read it, and it tells you what it does ๐
$x == 1>0 ? true : false;
Php is soooo readable ๐
e.g. threshold = (index < items) ? items[index].total : 0;
it's a bit like iif(), but in that case both the true and else part will be rendered, so that will throw an error if there are not enough items
@proud cradle read it left to right
like a sentence, it'll make sense.
that's python
it's meant to be read outloud
something if condition else something_else
I think there is an issue in the recection part of your code @mighty ledge , it seams like it keeps values older than now?
I just altered your last code
which didn't filter out anything older than now
it only chose things older than now
so if you only want things greater than now, change the lt to gt
It still returns 48 elements?
This is for example returned
{'total': 4.0352, 'startsAt': '2022-12-05T08:00:00.000+01:00', 'level': 'NORMAL'}
The items array needs to contain only values => now
ok, then change the selectattr to >=
I just copied what you had
FYI
and you had, lt which is less than
or maybe you're referring to your new sensor? anways, simply change the lt to >=
Yeah the binary sensor
But something is going on. The original code (pasted above) {{ prices | count }} == 33
While the new code returns 48 (items | count)
Today + Tomorrow in total will be 48 hours (items)
So the reject part can't be working
add the gridfees back, maybe it's making a difference
I forgot we added the hour, so it should still be 'lt'
Found the issue
Was isoformat("#", "milliseconds")
Should be to work isoformat("T", "milliseconds")
๐
Hi guys, I have a dashboard with three camera's on it. I want to have one camera enable based on a switch setting. I've created a jinja2 template but I'm unable to get proper placement of my code. Thanks in advance for helping me out!
- title: Home
cards:
- type: picture-entity
entity: camera.meadow
- type: picture-entity
entity: camera.driveway
{% if is_state('switch.camera-monitoring','on') %}
- type: picture-entity
entity: camera.garden
{% endif %}```
e.g.
field: >
{{ in the field }}
not
{% .. %}
field: ...
{% .. %}
Is only for entities, right?
- title: Home
cards:
- type: picture-entity
entity: camera.meadow
- type: picture-entity
entity: camera.driveway
- type: conditional
conditions:
- entity: switch.camera-monitoring
state: "on"
card:
type: picture-entity
entity: camera.garden
Great !! thanks for your help guys on such short notice!
Sorry for wrong placement.
What sensor is this? What is its purpose? It's quite complicated, really.What sensor is this? What is its purpose? It's quite complicated, really.
what's it matter? it's not meant for you
I tried the trigger based template sensor you suggested, and it seems to work nicely, thanks! I would need a little help on how to proceed. Do I have an ever growing list of changes attributes for all sensors that had a state change?
Silly question, sorry. Since it is a python dict, there cannot be duplicate keywords, thus the list is limited to the number of entities listed in the trigger, right?
Yes
When I expand this, I get the state, and a list of all attributes recursively (list of changes and friendly_name), can I use selectattr() the get the changes dict only?
[<template TemplateState(<state sensor.nominal_change_history_2=OK; changes=binary_sensor.1_119_allapot_dbz=2022-12-05T13:03:24.343802+00:00, binary_sensor.1_134_allapot_dbz=2022-12-05T14:12:41.669503+00:00, friendly_name=Nominal Change History @ 2022-12-05T18:14:12.817490+01:00>)>]
Just use state_attr('sensor.last_nominal_change', 'changes')
Great, I did not know it works without expand! Thanks!
Is it possible to use a jinja macro() to set the state of template sensors?
This fails validation stating that a "%" can't start any token.
template:
sensor:
{% macro icon( id ) -%}
{# Do a bunch of macro stuff #}
{%- endmacro %}
- name: 'Openweather Icon'
state: >
{{ icon( state_attr('sensor.openweather_report', 'current').weather[0]['id'] ) }}
{% set changes = state_attr('sensor.last_nominal_change', 'changes') %}
{{ dict(changes.items() | sort(attribute='1')) }}
Not like this, the macro will not be available under the state key
you can use it within a template block, but that usually makes macros less useful ๐
Hmmm, the macro is a really long if, elif block, basically a case statement. I don't want to repeat it for each day/hour...
I made something like this: {% set chg = state_attr('sensor.last_nominal_change','changes')| dictsort(false, 'value', reverse=true) | list %}
look at YAML anchors
OK, I have some of those I'll review. Thanks
How do i create a for loop for each device_tracker
need to change the layout of my auto entity card for my vpn on off switch.
states
{% for device in states.device_tracker %}
got it
I cant get my regular expression to work using regex_findall_index only .* gets results
the regex i should use is ^192.168.5.(1[5-9]\d|2[0-4]\d)$
aha
not use index
Trying to create a "weekend" sensor that is "on" from 5PM Friday until 5PM Sunday every week. Thoughts on how to do this?
EDIT: or maybe an automation that turns a boolean on and off at the desired times is better
Re from #integrations-archived: i want to make multiple custom entities (like a light) where i can set custom HTTP requests for certain actions without the need of buttons
Use the new schedule. helper
The GUI is a bit buggy but for me, but it seems to still work even if its confusing what hours are included
OK this makes me feel a bit daft. I put these in to the template tool, 3 numbers to 1 dec pl but when I add them together I get many decimal places. I know I can round the output but I don't understand why this is happening?
{{ states('sensor.air_con_energy_monitor_channel_b_power') | float(default=0)}}
{{ states('sensor.air_con_energy_monitor_channel_c_power') | float(default=0)}}
{{ states('sensor.air_con_energy_monitor_channel_a_power') | float(default=0) + states('sensor.air_con_energy_monitor_channel_b_power') | float(default=0) + states('sensor.air_con_energy_monitor_channel_c_power') | float(default=0)}}
26.2
-16.1
4.8
14.899999999999999
good enough for me.
So, I just upgraded through several versions of HomeAssistant, and suddenly, my timestamp template sensors have gone from working perfectly, to all showing "Unknown".
The value templates work fine on the dev tools > template tab, so I'm not sure what's going wrong with the sensors.
e.g. {{ strptime(state_attr('switch.rainmachine_normal_watering_plan', 'next_run'), "%Y-%m-%dT%H:%M:%S") }} returns 2022-12-07 02:00:00 as expected. But this just returns "Unknown"```sensor:
- platform: template
sensors:
normal_watering_plan_nextrun:
friendly_name: 'Normal Watering Plan Next Run'
value_template: >
{{ strptime(state_attr('switch.rainmachine_normal_watering_plan', 'next_run'), "%Y-%m-%dT%H:%M:%S") }}
device_class: timestamp```
And converting the sensor from the legacy format to the new format didn't fix it. Still returns "Unknown"
@low kernel I converted your message into a file since it's above 15 lines :+1:
Service Template help
I would get rid of the strptime() and just use the attribute as-is
That doesn't actually fix it either
Add |as_datetime?
Seems like anything with the device_class of timestamp is borked
- sensor:
- unique_id: doorbell_last_rung
name: 'Doorbell Last Rung'
state: "{{ states('input_datetime.doorbell_last_rung') }}"
device_class: timestamp```
It says it accepts a datetime or ISO8601 string
Even a simple one like that returns Unknown, though the template returns a date if you check it from the Template tab of Dev Tools
Trying now. Waiting for HomeAssistant to restart...
you can just reload template entities
Either way, didn't fix it
this works fine:
- sensor:
- name: since_last_changed
state: "{{ now() }}"
device_class: timestamp
as does:
- name: since_last_changed
state: "{{ state_attr('automation.kitchen_remote_fr_lights', 'last_triggered') }}"
device_class: timestamp
- name: since_last_changed
state: "{{ states('button.water_heater_leak_detected_ping') }}"
device_class: timestamp
๐คท
That does indeed work
all of those work fine
Ok, so why don't my other ones work...
{{ now() }} returns 2022-12-05 22:29:00.029220-08:00
{{ states('input_datetime.doorbell_last_rung') }} returns 2022-12-05 21:15:22
Is some kind of conversion required now, that wasn't required in the older versions of HA?
Just one more thing: if I use your trigger based template sensor, can I define more triggers and more sensors? I need to differentiate between two types of changes in my set of binary_sensors: from on to off and from off to on. I defined two, but i cannot get it working. (I put the on and off in corresponding not_from and not_to fields.
Yup, adding .000000-08:00 to the end suddenly makes it output an actual date into the sensor
I'm assuming there's a better way of doing this than hard-coding decimal seconds and time zone...
Any idea what that would be?
Nope, its built to only log the last nominal change, it doesn't differentiate between the state, besides unknown and unavailable.
It is created to have a persistent version of last_updated for nominal changes
{{ states('input_datetime.doorbell_last_rung') | as_datetime | as_local }}
Do note that that converts it into a datetime object, not to a string
Already tried that. Unfortunately, no dice
Forgot to add as_local for the timezone
Thaaaat did it
Worked for every sensor except normal_watering_plan_nextrun. For some reason, the entire entity vanished...
name: 'Normal Watering Plan Next Run'
state: >
{{ strptime(state_attr('switch.rainmachine_normal_watering_plan', 'next_run'), "%Y-%m-%dT%H:%M:%S")|as_datetime|as_local }}
device_class: timestamp```
Not sure what's going wrong there
strptime is somewhat required, because the Rainmachine sprinkler system uses an odd date/time format
The raw value for next_run is formatted like this: 2022-12-07T02:00:00
Yeah, now that entity is borked. "Entity not available" error
Oh, it's because HomeAssistant isn't using the unique_id as the entity ID... that's odd
Aight, that's another post-upgrade issue off the list. Time to get solar monitoring working again.
That's correct, the unique_id is only used as a unique id, the entity_id is derived from the name.
{{ '2022-12-07T02:00:00' | as_datetime | as_local }} works fine for me BTW, so I guess it was the entity_id issue which caused some the template not to work
Yeah, it was making a new entity every time I reloaded. What happened to the ability to set a fixed entity_id in yaml?
I need to differentiate between state changes. Can I do it in the trigger template sensor, or shall I in anoher sensor?
if it is just for one binary sensor, you can create two input_datetimes (one for on and one for off) and create an automation to write the datetime to that input_datetime
You mean like instead of changes:, I'll need to do changes_on: and changes_off:?
No, I was not referring to the template sensor here. If you only need this for one binary_sensor, you could just forget about the template sensor and do it in an automation
If you would store all states in that template sensor, it would turn into a long list quite soon if you would add a power sensor for example
as they change state very often
It is meant for binary_sensors only, and a limited number, I'm not planning to extend it now.
The state changes are alltogether few dozens a day.
Well, you could change the template sensor so it indeed stores changes_on and changes_off
But the sensor I created is a generic one, intended for all kinds of entities, so also those which change very often
it is just not intended for your use case, so you'll need to amend it for that
Ok, so provided I have some tens of binary sensors, only binary, and I need to check for off and on changes and start automations on that, would you recommend your template sensor? Is it worth a try?
that could work
You are great! Thanks a million!
oh, you should indent line 15 with one space
Can i gdt any tips for this?
Hi! Iโm trying to achieve COP calculation and would like someone to look into it with fresh ideas. Did a forum post in community- https://community.home-assistant.io/t/heating-cop-calculation/498679
Anyone got a script for unmutting phone, setting volume to max and sounding a noise? i have a script that does the noise but not sure if there's the ability to do the former, lost my phone and pretty sure it's on full mute so if the script is working i'm not hearing the result
hello. i was trying to use
{{ 'call' in state_attr('calendar.work', 'message') | lower }}
to look for the word "call" in a calendar event, the issue is that I have more than 1 calendar event on the day, so it only sees the most recent. is there a way to look at the other active calendar events?
that won't work
you just converted the enter message from the calendar to lowercase
and then you check for the word Call which has an uppercase character
so Call will never be in that message, as it only has lowercase characters
ignore that, i copied the wrong one. let me edit it
i was playing around and copied the wrong one here
but anyway, my issue still is there. i want to look at all active calendar events today for the word, but 'message' only contains the most recent to come in. is there any solution apart from making a separate calendar just for my 1 thing i want to look for?
Hey all - I am trying to write a template that checks if a timer.finished event (for timer.hvac_fan) has fired within the last hour - any guidance/assistance?
You need to have that data then
what you can do is create a trigger based template sensor, which triggers on that event, and logs the time
You can also check the last_changed object of the timer entity, and check if it is not active, but that will not be reliable after a restart of HA
Thanks - I resorted to a helper input_boolean to solve for my need. When the timer.finished event fires, the helper is set to true, and reset as appropriate for my need.
help pls
each device is unique
i need something simple where i can specify each action myself
pseudo yaml:
custom_device:
type: "light"
name: "LED Strip"
control_scheme: "http/get"
actions:
on: "http://automater.pi/api/ir/?device=led_strip&action=on"
off: "http://automater.pi/api/ir/?device=led_strip&action=off"
fade: "http://automater.pi/api/ir/?device=led_strip&action=fade"
flash: "http://automater.pi/api/ir/?device=led_strip&action=flash"
colors:
blu: "http://automater.pi/api/ir/?device=led_strip&action=blue"
red: "http://automater.pi/api/ir/?device=led_strip&action=red"
white: "http://automater.pi/api/ir/?device=led_strip&action=white"
pink: "http://automater.pi/api/ir/?device=led_strip&action=pink"
use shell commands
shell_command:
led_action: curl http://automater.pi/api/ir/?device=led_strip&action={{ action }}
then call with
service: shell_command.led_action
data:
action: "on"
@spice current
You have to make the template light using those commands
Also, without something to 'get the state', none of that will work
wdym by template light, sorry im not deep into yaml stuff
i just want it to force it and assume the last "sent action" to be the state until another action is applied
so caching the state in HASS instead of the device
That will take alot of work
and noone has done this before?
you'll need helpers to store all the 'states'
plenty have, it's just different every time
wdym its different? The whole thing could even have a simple UI
lights are complicated
where you select what to create (switch, light, etc); which features it has and how to "call" these features
it's different for every 'fake' light. https://www.home-assistant.io/integrations/light.template/
you may think it's simple, it is not.
there is no UI
you'll have to learn yaml
yeah i just meant UI would be nice and would make the whole "dumb device to smart device" convertion a lot easier and faster
will this handle the "caching"?
you have to cache it yourself
there is nothing that does what you want that will work out of the box
when was the first version of HASS released, just curious
~2014ish
dang almost 9 years and noone thought of making this easier
because we don't need to, we do yaml ๐
this UI push is new.
so you're in the minority
i like how the ui works for automations/scripts and the tuya local thingy
I doubt these will make it into the UI anytime soon, so you'll just have to pull up your boot straps
how do i tell the template that my light doesnt support dynamic brightness values but just up and down
is there any way to do something like ['sensor.temprature1','sensor.temprature1'] | state_attr("friendly_name") ?
as in "get the friendly_name from each entity"?
{{ expand(['sensor.temperature1','sensor.temperature1'])|selectattr('attributes.friendly_name', 'defined')|map(attribute='attributes.friendly_name')|list }}
uh neat! thank you.
what about calculating with temperature and current_temperature like this:
((state_attr('climate.wohnzimmer', 'current_temperature') - state_attr('climate.wohnzimmer', 'temperature'))*2)|round / 2,
for each entity?
I'm trying to get the highest delta between room temp and set room temp - see also https://community.home-assistant.io/t/get-highest-climate-set-current-temperature-delta/498945
Hello all. I have a sensor that gives the drive time to a location at any given time. How can I make a dynamic notification that fires at an offset before a given time where that offset is defined by the traffic sensor?
I'm not sure why exactly this is wrong, though I know it's not much to go off: Invalid config for [template]: expected dictionary for dictionary value @ data['sensors']. Got [OrderedDict([('name', '{{ items.c1.name }}'), ('state', '{{ items.c1.value or this.state if this.state is defined else none }}')])].
{{ ( (states('sensor.ble_temperature_a4c138328d38') | float >+ (state_attr('climate.smart_thermostat_3','temperature') | float)) and
( (as_timestamp(now())- as_timestamp(states.sensor.ble_temperature_a4c138328d38.last_changed) | timestamp_custom('%H') <= 10 ) ) }} I dictated this code to artificial intelligence ๐ What I wanted: If the sensor taken from the Ble_ temperature sensor is higher than the smart_thermostat temperature value for 10 minutes, the command was on. I need this code. By following the temperature, I am trying to synchronise the temperature of the boiler simultaneously. If there is a mistake, I would be very happy if you make corrections.
Share the entire config of the template sensor using this template
Please use a code share site to share code or logs, for example:
- http://pastie.org/ (select YAML for the language)
- https://dpaste.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.
Don't trust that AI, this doesn't make sense at all
What you want can't be done in a single template, because you are comparing numeric states
Create a template binary sensor using {{ states('sensor.ble_temperature_a4c138328d38') | float > (state_attr('climate.smart_thermostat_3','temperature') | float }} and then check if that binary sensor is on for 10 minutes
It's sensor: not sensors:
I'll give it a try
Thank you very much, I thought and practiced the same thing...I was wondering if there was a better method
No, because last_changed will update on every state change, and the comparison can be true before and after the state change
But the 10 minutes will be reset then, when they shouldn't
Can you explain the last sentence a bit more? Could the system created with binary sensor also be faulty?
Seems like I'm at a loss, here, maybe you can help: I'm trying to extract a value from an attribute and I can't find it in the docs:
Max. temps will be {{ state_attr('sensor.pws_forecast', 'calendarDayTemperatureMax') }} ยฐC.
returns:
Max. temps will be [4, 2, 1, 0, -1, -2] ยฐC.
How can I get to the individual values of that array?
Well assume the state of the sensor is 15 and the state of the climate entity is 10. So sensor > climate is true. It stays like this for 9 minutes, but then the sensor changes to 14.
The statement is still true, but since the sensor changed state, last_changed will have that new datetime and there is no way anymore to determine how long the statement has been true
As the result of the statement itself did not change, a binary sensor using that statement would also not have been changed, so that one will still show the correct time the statement became true (unless you do a reboot in the meantime)
{{ state_attr('sensor.pws_forecast', 'calendarDayTemperatureMax') | join(', ') }}
Does a tool exist to parse home assistant yaml such that I can see what the output of my code is? That way I'm not just blindly making changes and hitting the restart button over and over
show your template developer tools
Like that you mean?
BTW, you don't need to restart for most changes, you can reload parts of your configuration here
show your server controls
No, I want to see the output of the variables portion of the paste I sent earlier
The bottom line is that I can't seem to formulate the correct output to create my sensors
Not sure there is anything for that, bit template sensors can be reloaded from the link I sent, do no need for reboots
I have attempted to reload there with no change, but I will try using it again
Well that's because it is a trigger based template sensor, which will only update when triggered
That's fair, it should be updating every 10 seconds
Does that packs attribute change every 10 seconds?
If it has the same value as the previous one, it won't trigger
Usually, yes, within a millivolt or so. I mean, I have a ton of errors right now
Let me compile them into one pastie
The first one is easy, there is no str filter, there is a string filter though
Maybe that will fix it all
Well, that certainly did change things. Doesn't seem to accept that module is defined as "1", though
The point of all this anchoring and use of variables is to reduce about 1800 lines of yaml down to roughly 40
Thank you for your detailed explanation. It is not something very sensitive. Ble sensor updates every 15 seconds. I don't think it will be too much of a problem. I will test it tonight. The purpose of wanting this sensor: my house is an American kitchen. The kitchen and living room are one, the house heats up when the food is cooked, to which degree the house rises (even if the thermostat is at a lower temperature) is to ensure that the thermostat is fixed to that temperature and does not go lower. the aim is not to lose the heat of the heated house.
If the sensor updates that frequent, tool you'll never reach the 10 minutes if you don't use the binary sensor
Btw, if you would put this trigger in an automation, you will be able to see the entire result in the trace of the automation
I already used binary sensor
I need to delete the 63 unnamed sensors all this testing has created
Add a unique_id to prevent that
Alright, it's 10PM and I have to be in a few hours. Still need to delete all those unnamed sensors somehow, and for some reason I still get Template variable warning: 'module' is undefined when rendering '{{ trigger.to_state.attributes.packs | selectattr('module', 'eq', module|string) | first | default({}) }}' though from that code I would gather that module was defined right after variables
module should be 1 according to the code you shared
euhm 0 decimals , is
|float * 1000, round 0 }}
??
aah ty !!
Does anyone know a good example for setting up a 'smart' presence sensor. I can do a simple 'or is_state', but have two issues (1) some of the motion sensors turn on immediately, but take ~45 minutes to turn off and (2) I need to mix ANDs and ORs
This is my pseudo code, but I don't know how to do the 'on' recently, or the AND:
@timber cobalt I converted your message into a file since it's above 15 lines :+1:
How about just assuming no one is home when your alarm is armed_away, and otherwise assume someone is home? If your presence sensors don't go off for 45 minutes, that's a problem in your approach above
Doesn't the AND obviate the need for all the ORs? (assuming you set the alarm when you leave)
If someone leaves and forgets to arm, still want the house to go through and shut off lights etc.
The issue with the presence sensor not going off for 45 minutes is that it's a motion detector that's connected to the alarm system. It's a bad sensor, but useful for the step up.
Regarding the 'AND' I assumed nesting logic like I did above wouldn't actually work. I couldn't find any example that did it.
I ended up just using helpers. This seems to work. The last step is basically your suggestion, but ANDed with the other detection methods. So: If armed away = not there. If armed home = home. If system unarmed = check for activity. Just seems more wordy than I'd expected.
@timber cobalt I converted your message into a file since it's above 15 lines :+1:
Does HA support the jinja {% include %} feature?
https://jinja.palletsprojects.com/en/3.1.x/templates/#include
With yaml &anchors not seeming to work for jinja code, I'm trying to use the jinja {% include 'file' %} in a template sensor as:
state: |-
{% include '/config/test.yaml' %}
{% if state_attr('sensor.openweather_report', 'current').weather[0]['id'] is defined %}
{{ set_icon( "state_attr('sensor.openweather_report', 'current').weather[0]['id']" ) }}
{% endif %}
Here is the error:
[homeassistant.helpers.template_entity] TemplateError('TypeError: no loader for this environment specified') while processing template 'Template("{% include '/config/test.yaml' %}")' for attribute '_attr_native_value' in entity 'sensor.openweather_icon'
Seems not
Nope, also tried that
Btw, if it would work you should include a jinja (.j2) file, not a yaml file
Yes, it's not yaml. Thanks for that. I'm writing up an Issue
I don't think it's an issue, I would suggest to write a feature request
Fair enough
Looks like a PR to add jinja include and import was created, but rejected in 2020. Use scripts, write a python script, or write a custom component was the suggestion. https://github.com/home-assistant/core/pull/42244
Yikes!
Just applied 2022.12 and ALL my Zigbee2MQTT entities have changed their unique IDs from what they were to a _2 variant of the original name.....restart didn't fix it.....I've got 500+ entities so I don't really want to delete the old names and then rename the _2 ones back to default......
Any ideas on how to fix that?
Needless to say everything is now broken.....
That didn't happen to me on the betas. I'd recommend using your backup and rolling back
But I also suspect more than templates are broken. So it might be worth using #general-archived for now ๐
Didn't even notice the wrong channel was selected....sigh ๐ฆ
Dear all, is there a simple way to throttle the templates from publishing so much into the MariaDB?
I've got some simple calculus templates for power to create various device power groups and they generate some obscene numbers of datapoints over a week
yes, give them a trigger
I have a 10-day DB purge and these 4 entities generate 750k points each, with the closes second having less than 300k
- sensor:
- name: Net power meter
state_class: measurement
device_class: power
unit_of_measurement: W
unique_id: net_power_meter
state: >
{{ (states('sensor.electricity_meter_power_active_phase_1') | float | round(4) + states('sensor.electricity_meter_power_active_phase_2') | float | round(4) + states('sensor.electricity_meter_power_active_phase_3') | float | round(4)) | int }}
availability: "{{ states('sensor.electricity_meter_power_active_phase_1') | is_number and states('sensor.electricity_meter_power_active_phase_2') | is_number and states('sensor.electricity_meter_power_active_phase_3') | is_number }}"
I went through the documentation and I must admit I was stuck with triggers
How would one look like for a sensor such as this one?
when do you want it to evaluate?
Previously, there used to be a fixed timer update_interval:
the use a time_pattern trigger
But it seems it's no longer possible
If I'd like it to update at 1 or 2 Hz
Yes, I've read this twice, but can't understand the term 'match' in the documentation.
With the time pattern trigger, you can match if the hour, minute or second of the current time matches a specific value. You can prefix the value with a / to match whenever the value is divisible by that number. You can specify * to match any value (when using the web interface this is required, the fields cannot be left empty).
"You can specify * to match any value" this is particularly confusing in light of the examples given.
Could you give an example of a trigger for every two seconds?
I'll try to incorporate it into my code and post it back, to make sure it makes sense.
the third example there is what you want, but it just uses minutes
trigger:
- platform: time_pattern
seconds: "/2"
This is the operative phrase:
You can prefix the value with a / to match whenever the value is divisible by that number.
So the full sensor would look like this:
- trigger:
- platform: time_pattern
seconds: "/2"
sensor:
- name: Net power meter
state_class: measurement
device_class: power
unit_of_measurement: W
unique_id: net_power_meter
state: >
{{ (states('sensor.electricity_meter_power_active_phase_1') | float | round(4) + states('sensor.electricity_meter_power_active_phase_2') | float | round(4) + states('sensor.electricity_meter_power_active_phase_3') | float | round(4)) | int }}
availability: "{{ states('sensor.electricity_meter_power_active_phase_1') | is_number and states('sensor.electricity_meter_power_active_phase_2') | is_number and states('sensor.electricity_meter_power_active_phase_3') | is_number }}"
Correct?
I'd like to create an automation to turn on Christmas lights. But, I'd like it to only run on certain days of the year (essentially... December and Jan), and when it's dark enough...
So...
Trigger: it's dark
Condition: month is in (dec, Jan)
Action: Turn on
But, i don't see a option to have a date or month as a condition. My guess is: templates to the rescue.
I am however... Terrible at templates. Anybody have a suggestion? Maybe... Know of some good contextually relevant reading?
Thanks for pointing me in the correct direction Rob! Appreciate it!
@inner mesa would you mind having a look? โ๏ธ
I tested the trigger-based template sensor for a few days, what I figured was that it does not work reliably. Now I have this code (only the sensor part, I omitted the trigger), it complains about 'str' cannot have isoformat():
sensor: unique_id: nominal_occsy_chg_hist name: Nominal Occupancy Change History state: "OK" attributes: changes_on: > {% set current = this.attributes.get('changes_on', {}) %} {% set new = {trigger.entity_id: trigger.to_state.last_changed.isoformat() | as_local} if trigger.to_state.state == 'on' else {} %} {{ dict(current, **new) }} changes_off: > {% set current = this.attributes.get('changes_off', {}) %} {% set new = {trigger.entity_id: trigger.to_state.last_changed.isoformat() | as_local} if trigger.to_state.state == 'off' else {} %} {{ dict(current, **new) }}
When I remove the isoformat(), I get this: ValueError: dictionary update sequence element #0 has length 1; 2 is required
I assume you still have the trigger in right?
@thorny snow I converted your message into a file since it's above 15 lines :+1:
ah, I see what's wrong
the | as_local filter is applied on the isoformat string of the datetime
which doesn't work
this should work
changes_on: >
{% set current = this.attributes.get('changes_on', {}) %}
{% set new = {trigger.entity_id: as_local(trigger.to_state.last_changed).isoformat()} if trigger.to_state.state == 'on' else {} %}
{{ dict(current, **new) }}
changes_off: >
{% set current = this.attributes.get('changes_off', {}) %}
{% set new = {trigger.entity_id: as_local(trigger.to_state.last_changed).isoformat()} if trigger.to_state.state == 'off' else {} %}
{{ dict(current, **new) }}
BTW use 3 backticks for code blocks of multiple lines
It works again, thanks!
@thorny snow I've changed mine as well, the state now shows the number of entites stored instead of just "OK"
https://github.com/TheFes/HA-configuration/blob/main/include/template/trigger/last_changed.yaml
Hmm, what do you currently have as values for these attributes
changes_on and changes_off
I wanted to upload a small image about that. How can I upload an image?
you can use imgur, but it would help for testing if I have it in text
Please use a code share site to share code or logs, for example:
- http://pastie.org/ (select YAML for the language)
- https://dpaste.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.
All right. So, right now state: 3, content is five items:
changes_on: binary_sensor.1_121_allapot_dbz: '2022-12-08T11:05:48.912156+01:00' changes_off: binary_sensor.1_121_allapot_dbz: '2022-12-08T11:05:18.254059+01:00' binary_sensor.1_117_allapot_dbz: '2022-12-08T11:03:28.438085+01:00' binary_sensor.1_122_allapot_dbz: '2022-12-08T11:09:52.853203+01:00' binary_sensor.1_128_allapot_dbz: '2022-12-08T12:07:38.643283+01:00' friendly_name: Nominal Occupancy Change History
"value_template": "{% if value_json == 101 %} 100 {% elif value_json == 255 %} 0 {% else %} value_json {% endif %} | int"
why does it not convert to int?
i've also tried to pipe each value, but says '55' is not a number
if I remove the template it works, but gives errors for the odd values (101 and 255)
It counts the unique entities in both lists combined, so there are actually 4 (as 121 is listed in both)
apparantly value_json doesn't return a number, but a string
the entire payload is just a number, it works for another sensor to convert number to strings
I placed it inside too, no help
"value_template": "{% if value_json == 101 %} 100 | int {% elif value_json == 255 %} 0 | int {% else %} value_json | int {% endif %}"
no, 100 is already an int
it is value_json which is not already an int, you need to convert that
100|int is still 100
so no harm
value_json|int ==> string
it does not work...
but "101" is not 101
"value_template": "{% if value_json == 0 %} Scurt circuit {% elif value_json == 1 %} Normal {% elif value_json == 2 %} Incendiu {% elif value_json == 3 %} Sabotaj {% elif value_json == 4 %} Panicฤ {% elif value_json == 5 %} Deconectat {% else %} Necunoscut {% endif %}",
this works flowlesly
why does not work when I want an INT out, not a string?
then in this case value_json is an integer
it is always just a number
in both cases
{% elif value_json == 1 %} Normal
"Normal" is a string
so I expect
{% if value_json == 101 %} 100
100 to be a string too
You are not providing any information what value_json is, and where it comes from. Remember that you are the one asking for help, and crystal balls are in short supply
no, you are defining it to be 100
value_json is a number only, raw payload is "101" (no quotes)
100 is a integer
I can't post screenshots
if you want it to be a string, you need to define it as '100'
so it is hard to see
or 100 | string
If value_json in this template: "{% if value_json == 101 %} 100 {% elif value_json == 255 %} 0 {% else %} value_json {% endif %} is always an integer, the result will also always be an integer
either 100, 0 or value_json itself
if the result is not an integer, then value_json was not an integer
that's my problem, it says it's a string... I control the payload is just a number, no quotes no nothing
Well, it's not a complicated template, and there are only three outputs possible. Either 0, which is an integer, or 100, which is an integer, or value_json, which according to you is an integer
that's what I say
So, if HA complains that the result is not an integer, it must be from another part in your configuration, or value_json is not an integer
one sec, I deleted my config, was done by hand, now I do it via code
Logger: homeassistant.components.mqtt.number
Source: components/mqtt/number.py:208
Integration: MQTT (documentation, issues)
First occurred: 3:19:29 PM (3 occurrences)
Last logged: 3:19:30 PM
Payload '55' is not a Number
Payload '255' is not a Number
both values are numbers on the MQTT message
they are not strings
can you post the full action?
then post the configuration of your MQTT number and take a screenshot of the topic in question in MQTT explorer
I am not allowed to add images here
you should not post images of configuration code
and if needed you can upload an image to imgur, and post the link
@glacial bridge I converted your message into a file since it's above 15 lines :+1:
Please use a code share site to share code or logs, for example:
- http://pastie.org/ (select YAML for the language)
- https://dpaste.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.
does this help?
I'm not sure if message was delivered, it says it was converted to a file
share your images with imager
@glacial bridge
anyways, I see your issue
value_template: >-
{% if value_json == 101 %} 100 {% elif value_json == 255 %} 0 {% else %}
{{ value }}{% endif %}
will try
ah crap, should have seen that.. shouldn't it be {{ value_json }} though?
doesn't matter
oh okay
the typing resolver will take care of it
ah okay, both value and value_json are valid, but the 2nd is converted to json
yeah
no reason to convert to json when you don't have to, however that variable exists in the namespace so I don't think it matters which one you use because both are prepopulated
ah, clear.. I clearly don't use these kind of configs ๐
but anyway, the message that it was still not working suddenly disappeared
now it works out of the blue with the same payload
same template
I just deleted the whole device from ha and rediscovered
wtf?
Your old template would only work when the value is 101 or 255, it wouldn't work with any other value
you need to update your template to what I wrote
well, the problem with your earlier version was that you were returning the string value_json and not the value in the variable
it's my template that works
it will fail
value_template = "{% if value_json == 101 %} 100 {% elif value_json == 255 %} 0 {% else %} value_json {% endif %}",
this works... now
this is what you need to use
It won't
trust me it does
you're literally returning the string value_json instead of the variable
I can see the slider moving
that will do what I just said, return the string "value_json" unless the payload is 101 or 255
value_json is int because of pre-parsing
ok, then how does it work?
since I can post numbers and see the slider moving in the dashboard
It would work in something like this {{ 0 if value_json == 255 else 100 if value_json == 101 else value_json }}
right, but the way you have it currently, it will not work.
then I'm imagining the slider moves with the payload?
๐คทโโ๏ธ your template is wrong, here look:
no, it is probably using the config you had before
reload MQTT from devtools > yaml
Notice how it says 'value'
does it still work then?
now, look when I put brackets
hey, look, proof that your template's wrong. Who would have thought
Most likely what's happening is that you're working off an old discovered topic and your current one hasn't been used. Send the discovery info again and It will stop working.
oh well... just checked, it works... even after removing and rediscovering, so I will leave it as is
when I delete the device, the respective MQTT discovery topics get deleted as well on the server
so it was a clean discovery
just don't come crying here for help when it fails, because it will
that template is wrong.
๐
This returns 4, which is what I would expect from it
{% set on = {
'binary_sensor.1_121_allapot_dbz': '2022-12-08T11:05:48.912156+01:00' } %}
{% set off = {
'binary_sensor.1_121_allapot_dbz': '2022-12-08T11:05:18.254059+01:00',
'binary_sensor.1_117_allapot_dbz': '2022-12-08T11:03:28.438085+01:00',
'binary_sensor.1_122_allapot_dbz': '2022-12-08T11:09:52.853203+01:00',
'binary_sensor.1_128_allapot_dbz': '2022-12-08T12:07:38.643283+01:00' } %}
{{ (off.keys() | list + on.keys() | list) | unique | list | count }}
it should not return 3 though
I've just checked it at a later stage, and it seems ok. At the beginning, there was some hiccup, no idea why.
Is there any change on the | default filter in jinja? I'm getting a curius error on the template editor for this:
{{ [] | default(['0'], true) | average }}
ValueError: Template error: average got invalid input '(['0'],)' when rendering template '{{ [] | default(['0'], true) | average }}' but no default was specified
{{ [] | default([0]) | average}}
The , true wasn't there for an empty case? this was working in .11
oh sorry I had a string
no, the true does nothing in that case
the default you're supplying is the [0]
this does not corelate to adding defaults to floats
or ints
this is a separate function/filter
ValueError: Template error: average got invalid input '([],)' when rendering template '{{ [] | default([0]) | average}}' but no default was specified
It needs the ', true'
my fault was that I was given a string to pass to the average that needed a number
Is it possible to write the tag_id (of an NFC Tag i read inside HA) into an "helper" to be able to Store it as "Last readed Tag" and compare it with current Tag?
it's not going to pass because default isn't being used when your input is []
@frank gale if you're trying to avoid empty list errors use this
{{ ([] or [0]) | average }}
default can be used with empty lists with ', true' argument, i'm not having any issues
Yeah, that should be possible.
if you use it on the template you wrote above it will render ok
you will get 0 as average
then your error is that you're using ['0'] instead of [0]
yes I wrote it already petro ๐
sorry, bouncing between work and here
no problem! thanks for sorrying ๐
Sadly i only See the Event Trigger, but nothing i could read Like "state_attr" or anything else
why is that stopping you then?
you can trigger off events
I Trigger an Automation with tag read, but i need to Store and compare the UID inside an helper within that Automation:
I need i as helper to start/Pause/resume Playback of Audio Like Spotify or mp3/ogg
See what rob posted
you don't need it as an attribute, the information is passed via trigger objects
I Just checked the Link, but as soon as i add {{ trigger. }} Into the Template Editor, i only get error "UndefinedError: 'trigger' is undefined"
So i dont know how to get the UID once i read an Tag
you can only use it in automations or trigger based sensors, where are youtrying to use it?
Dev-Tools / Template
To Test the result
yeah you can't do that, it doesn't have a trigger
you have to test it in an automation
So i need to Debug it somehow to See the correct trigger Part to See where the UID is listed
you can listen to events in the event page on developer tools
No, you listen to the events in
-> Events
you can view your traces of an automation as well
many tools to do this
you can even view a different automation that uses scanned tag events to get the shape as it will have a trace with that info
event_type: tag_scanned
data:
tag_id: E0040350********
device_id: a761e58243837915de***********
origin: LOCAL
time_fired: "2022-12-08T20:13:51.107420+00:00"
context:
id: 01GKSNYY4***********
parent_id: null
user_id: null
Thats what i get, but i think iam to stupid to get it somehow inside {{ }}
I need the "tag_id" saved in an input_text
trigger.event.data.tag_id
Inside the traces IT seems to Work, But the input_text do not change
service: input_text.set_value
target:
entity_id: input_text.tag_uid
data:
value_template: "{{ trigger.event.data.tag_id }}"
Can someone help with this?
example from the docs: https://www.home-assistant.io/integrations/input_text/#automation-examples
๐ value not value_template
Thanks that worked
I have this sensor for yesterday with:
end: '{{ now().replace(hour=0).replace(minute=0).replace(second=0) }}'
duration:
hours: 24```
It gets reset (somehow it calculates a new value) each time I restart HA. Is this expected behaviour?
Not an anwer to your question, but for that template you can also use "{{ today_at() }}"
and you can do all those replaces in one go, if you do want to use them "{{ now().replace(hour=0, minute=0, second=0) }}"
In what kind of sensor are you using this config?
hi, I'm trying to make alexa announce the remaining time on my washing machine.
the "message:" block should get a string value, but when I enter {{ states(sensor.washing_machine_remaining_time }} I get a notification that "template value should be string for dictionary value..."
the sensor value is string when i put the same command in the developer section.
any ideas how to make this work?
what is the actual code of the service call in which you used this template
Please use a code share site to share code or logs, for example:
- http://pastie.org/ (select YAML for the language)
- https://dpaste.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.
Yep, just as I expected. Rule #1 of templating, surround your template with quotes if you use the single line notation
message: "{{ states('sensor.remaining_time}}"
thanks ๐ตโ๐ซ
What would this look like with the template updated code?
sensors:
wetemp:
friendly_name: "temperature_outside"
unit_of_measurement: 'ยฐC'
value_template: "{{ state_attr('weather.accuweather_house', 'temperature') }}"
I heard that's a little outdated and should be template: - sensor: and not -platform: template sensors:
But trying to replicate it makes the code break all the time lol
Like the ID would be temperature_outside and the name Temperature: Outside which is also something I cannot replicate properly
To format your text as code, enter three backticks on the first line, press 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.
Apologies, properly edited. That's the best attempt - the one I am using at and "works".
But considering I am currently messing / fixing some stuff, thought would be a good timing to updae to the new format and not use the old one
Can't seem to pull it off tho
I can produce it for you, but I would like you to show what you tried to do, so I can tell you were it is going wrong
first of all, you know this new code can not be placed in something like sensor.yaml right?
I ended with this mess:
- sensor:
- name: "Temperatura Fora Teste"
unique_id: temperatura_fora
unit_of_measurement: 'ยฐC'
value_template: "{{ state_attr('weather.accuweather_house', 'temperature') }}"
But it gives synthax error when I post it on HA VSC
I am putting in configuration.yaml, which is the right place to, right?
At least that's the place I had the old (and current) one.
unique_id is indented too far
template:
- sensor:
- name: "Temperatura Fora Teste"
unique_id: temperatura_fora
unit_of_measurement: 'ยฐC'
state: "{{ state_attr('weather.accuweather_house', 'temperature') }}"
this should work
but if you place it where it was, it might break everyting coming after it, if there are more sensors belonging under the sensor: key, they will not work anymore
there are two different integrations here, the old template sensors are using the sensor: integration, and should be under that key
the new format uses the template: integration, which should be a separate section in your configuration.yaml
I appreciate your help, I just tried to use that code and it's giving two errors:
- in the name line it's giving - Missing property state
- in the value template it's giving - property value_template is not allowed.
I've added it in a different place of configuration.yaml to avoid errors, but still getting them. But I understand what you meant.
change value_template to state
Was testing it out before saying anything, it did work! Thank you so much @marble jackal!
Think now with this as base I will be able to create the others I intended. Have a wonderful day man.
I'm creating a frost warning, and quickly getting out of my templating depth.
so far I have this:
{{ state_attr('weather.dark_sky', 'forecast')[1]['temperature'] <=2}}
Though I've realised I need the output to tell me wether any of the forecasted temperatures in the next 16 hours are equal to or below 2ยบC, not just for the next hour (dark sky provides hourly temp forecasts) which I have currently ([1]).
Am I right in thinking substituting [1] for [1-16] would do what I require? or am I doing something I do not intend/is there abetter way to achieve my goal?
Thanks in advance for any assistance.
{{ state_attr('weather.dark_sky', 'forecast')[:15] | map(attribute='temperature') | min <= 2 }}
That will use the first 16 items, and takes the lowest value out of them to compare (counting starts at 0)
fantastic thank you!
Hello. How can I get a full list of my addons and integrations with a template?
as far a I know you can't. You can get the entities of an integration, but there doesn't seem to be a way to get the intgration of an entity
for add_ons you could use update entities
{{ states.update | selectattr('attributes.entity_picture', 'defined') | selectattr('attributes.entity_picture', 'search', '/addon') | map(attribute='name') | map('replace', ' Update', '') | list }} for add-on
Is it possible to create big random numbers with a template? I need random numbers with exactly 20 digits. The random integration can't handle such big numbers.
Maybe you could use a template and append multiple random numbers together?
Then you could also just cutoff any excess using something like {{ states('sensor.random_number')[:20] }}
I'm beginning to see your problem as I try this out myself...
19 digits seem to be the magic barrier. ๐
oh, of course it would be something like that. lol
I was trying to get it to treat it like a string, but since it's only numbers, it seems to ignore my attempts.
20 will be very hard to do
i believe that's outside the integers range
Yep
the max value you can do with an integer is 15 characters
so... 999999999999999
and the max range for selecting a random number is 100000
@marsh cairn what do you actually need this for?
hmmm, what you could do is...
@wheat junco I converted your message into a file since it's above 15 lines :+1:
{% set ns = namespace(items=[]) %}
{% for i in range(20) %}
{% set ns.items = ns.items + [ '0123456789' | random ] %}
{% endfor %}
a {{ ns.items | join }}
you'd have to put a letter in front of it to avoid errors in python to keep it a string.
Nice. Maybe he can use it.
I'll give it a try. Thank you!
- platform: average
name: "Daily average outside temperature yesterday"
unique_id: "daily_average_outside_temperature_yesterday"
entities:
- sensor.fasada_temperature
- sensor.aqara_temperature_1
end: "{{ now().replace(hour=0, minute=0, second=0) }}"
duration:
hours: 24 ```
sorry for late reply... you think its the sensors fault?
Looks like you are using this custom component https://github.com/Limych/ha-average
Yes
You could also try this:
- platform: average
name: "Daily average outside temperature yesterday"
unique_id: "daily_average_outside_temperature_yesterday"
entities:
- sensor.fasada_temperature
- sensor.aqara_temperature_1
start: "{{ today_at() - timedelta(days=1) }}"
end: "{{ today_at() }}"
Will that reset at 0:00:00?
The start will be yesterday at 00:00, the end will be today at 00:00
Ok I will try, thanks !
Hi all. I'm looking to make a template that checks if there is an event at any point during the day that contains a certain word. I know how to check to see if the next event contains that word, but not if it exists at any point during the day. How would I go about that, while also not having things like an all-day event throw it off?
Still recalculating on HA restart... Once it was also stuck on "unavailable" from the start. I guess this is some kind of a bug in this sensor?
Could be, maybe create an issue for it
It does have correct start/end in attributes: https://ibb.co/T1dh4Kg
Its calculating value for next interval
Is one of the two sources unavailable?
Not at the time of checking
You think it may be that it starts this sensor before those temperature sensors become available?
That would most likely be the case I think. One is a Hue, another is Zigbee(deconz)
It does not update its state after. Only after restart and at midnight.
I cant seem to find an official way of doing a sensor like this, even if its ugly?
Your screenshot states count sources: 2 and available sources: 1, so that's why I asked
As it is data from yesterday it should not really matter which comes online first
I see. Other "today" sensor has 2 out of 2. Maybe that is the bug
Im pretty sure now this is where the bug is coming from. Is it possible to make this sensor wait for those 2 to become available? It probably wont recalculate with 2 out of 2 before midnight.
Because rarely the whole sensor is "unavailable" (probably then its 0 out of 2) but couldnt seem to exactly reproduce it, because I cant restart HA everytime I want.
I wouldnt in a million years figure that out, I have so many sensors just for this central heating, thats why Im doing everything from scratch before I iron all bugs like these out.
I made 2 more average sensors, 1 for each of those actual temperature sensors. I restarted only once since and count/min/max values match to one of them! Will restart more times after midnight in 19mins. Thanks !!
How do I group multiple phones to get notifications at once?
Hi, I have a sensor that totalizes the number of hours one of my lights is on (history_stats), this however is only showing for as long as my recorder has states (10d at present). How can I move the daily total into long term statistics? I have setup sensors for total/total_increasing/measurement but they also show the values intra-day...I only want the total of the day tracked. ```
- name: "PC Game On LT1"
unique_id: PC_Game_On_LT1
state_class: total_increasing
state: "{{ states('sensor.pc_game_on') |float(0) }}"
It needs an unit_of_measurement to be added to long term statistics
so that would be hours then I guess...thx
Hello, I have a template sensor with 12 attributes which all store a list.
On the date 1.1. now all entrys on all 12 attributes should be deleted (or set to an empty list aka [])
How can I do that?
You need to convert it to a trigger based template sensor then
ah ok, yes I am sitting right now on it
can you define an action in a "trigger template sensor" based on which trigger triggered, if I have 2 triggers? aka how in automations you can use trigger ids?
would this work correctly?:
monthly_tally_1: >-
{%if trigger.idx == 1%}
{{[]}}
{%else%}
...
{%endif%}```
I tested it right now, and the attribute still has all his entrys in that list.
What did you use as trigger?
- platform: state
from: "0.0"
not_to: "0"
entity_id: input_number.number1
id: "0"
- platform: state
from: "12"
to: "1"
entity_id: sensor.month
id: "1"```
these are my 2 triggers
why does this capitalize the first letter of every word except the first word?
{{ (states|selectattr('entity_id', 'search', 'node_status')|selectattr('state', 'in', 'alive, unavailable, unknown')| map(attribute='object_id')|list|replace('[', '')|replace(']', '')|replace('_node_status', '')|replace('_', ' ')|title ) }}
is it possible to template a header image url?
Try it like this:
{{ states | selectattr('entity_id', 'search', 'node_status') | selectattr('state', 'in', ['alive', 'unavailable', 'unknown']) | map(attribute='object_id') | map('replace', '_node_status', '') | map('replace', '_', ' ') | map('title') | join(', ') }}
I was about to migrate all my legacy templates to "the modern format". But it seems that you can't specify a friendly_name in the modern template: format.
You define a name: which then is converted to an entity name. On most sensors, I don't want that since I may have several entities with same "display name". Also, the conversion of Swedish characters creates confusing entity names sometimes.
This means I will end up using the name for entity name and then use customize.yaml (which is not recommended and supposed to be phased out) for every template sensor. This is somewhat confusing. Is this really the preferred way or am I missing something?
Tbh I haven't bothered switching to the new format since the legacy format still works
name specifies the friendly name, and is used for the entity_id
If you add a unique_id you can change both in the GUI
You can also not provide a name and add a friendly_name attribute
The unique_id will then be used for the entity_id, but (if I'm not mistaken here) the object_id will start with template_
Anyway, no need to use customize if you add a unique_id
I sure can change the "display name" in the GUI, but when you have like a hundred templates, it's much faster in YAML.
I think it's strange you can't specify them both separately. I, for example, always use English entity names (for easy sharing examples), but Swedish friendly names.
Well, I guess I'll stick with the old format them. Thanks for explaining.
Or:
You can also not provide a
nameand add afriendly_nameattribute
I can? the modern templatedoesn't accept friendly_name
If it does, everything is fine ๐
Adding a friendly_name before was exactly the same as providing a friendly_name attribute
You can add whatever attributes you want
is there a way to break or return nothing in a template? So I can make nested ifs easier to read?
Well, ok. You are correct. But it doesn't fill the need. An attribute created that way doesn't "act like a friendly name". It is not what is shown in the GUI.
- name: "altandorr_battery_level_tmpl_test"
unique_id: whatever_unique
state: "{{ (states('sensor.altandorr_battery_level') | round (0, default=-1)) }}"
attributes:
friendly_name: "Magnetsensor pรฅ altandรถrr TEST" ```
You sure?
Gives me:
friendly_name: altandorr_battery_level_tmpl_test icon: mdi:battery unit_of_measurement: % device_class: battery
So either I am doing something very wrong , or I just found a bug
(the device_classcomes from customize_global)
I'll restart just in case I messed something up..
Same thing. It's like HA overrides my manually created attribute
Hmm.. I tried to create a completely new template sensor.
- name: "Template Test Sensor Name"
unique_id: unique_id_on_my_template_test_sensor
state: "Template Test Sensor STATE"
attributes:
friendly_name: "Template Test Sensor Friendly Name"
Gives me: https://ibb.co/pZhHxhN
So friendly_name is not used and name becomes entity_name
unique_id is not used in the GUI at all
maybe that's why TheFes said
You can also not provide a name and add a friendly_name attribute
Yeah. I just thought you said the opposite ๐
unique_id isn't ever "used" in the UI, but it allows you change the name and entity_id in the UI
well, I thought it would
I wish you were right ๐
without a name:
then you can change the entity_id to be whatever you want, but you'd have to do it in the UI
Yep. But with 100+ templates, I think I'll wait until the modern template gets more options/settings - or the legacy template stops working (which ever comes first)
I suppose the thinking is that you have to enter it somewhere, so just do it in the UI along with every other entity
awesome. Thanks !!!!!
Give me customize.yaml or give me death
With unique_id and friendly_name attribute:
sensor:
- unique_id: this_is_a_test
state: "test"
attributes:
friendly_name "Hello earthlings"
Whatโs the best approach to setting an iconโs color for 30 seconds after a sensor is triggered?
{% if is_state('binary_sensor.kitchen_motion','off') %}
green
{% else %}
red
{% endif %}
Thatโs what Iโm using now. I just want it to stay red for 30 seconds before going back to green. To simulate the motion cool down period
This looks like there's a working template that waits 20 mins before doing something... perhaps you could reverse engineer it into a working solution for you...
https://community.home-assistant.io/t/wait-for-20-minutes-syntax-for-wait-template-in-visual-mode/324394/4
Thanks! Totally new to HA syntax. I think Iโm on the right path.
Are you utilizing the developer tools template tool?
I have found it to be helpful as I fumble through the templates... haha
might also look into timers:
https://www.home-assistant.io/integrations/timer/
Thanks! Jinja, that's what I couldn't find yet in terms of the syntax being used
Become a real Jinja2 Ninja! Don't worry my Genin, we are here to help! You can find general Jinja docs at https://jinja.palletsprojects.com/en/3.1.x/templates/, Home Assistant extensions at https://www.home-assistant.io/docs/configuration/templating/, and trigger variables at https://www.home-assistant.io/docs/automation/templating/
This channel is for support with Jinja templates. Some custom Lovelace cards support other types of templates, such as those written in JavaScript, and #frontend-archived is the right channel for that.
Please use http://pastie.org/, https://dpaste.org/, or https://paste.debian.net/ to share code or logs
Thanks, your example sure works. Good to know! ๐
I like the concept of gathering all types of templates together, but I think the modern template need some work to become a bit more logical. But maybe that's just me.
Do note it adds template_ before the unique_id
Ugh. Hate that I've been smashing about without knowing about the Dev tool!
Yep! That's fine really, I use domain.entity_name_tmpl as naming convention today, so a search & replace in Scripts & Automations should do it.
Just need to do some scripting to convert the code to the new format. Perfect task for a Saturday night ๐
{% set stateNow = (states.binary_sensor.kitchen_motion.state) %}
{% set timeThreshold = (now() - ls < timedelta(seconds=10)) %}
{% if (stateNow == 'on' and timeThreshold == True) %}
orange
{% elif (stateNow == 'on' and timeThreshold == False ) %}
red
{% else %}
green
{% endif %}```
^ this is working well ๐
Can we reference the last time an action was performed? "toggled"?
Asking, as I'd like to apply this same logic to a garage door, to show a visual feedback that the action is being performed. But, with a single binary sensor for on/off, my logic fails to update the icon when an action is performed to close the door.
That is the last_changed object
But, my last_changed logic fails, since the door has been "open" for a while
So, my mental rough logic would be: if the door is open, and last changed is greater than 30 seconds, AND you just performed an action, then color = orange
The last_changed would only be updated once the door is actually closed and the sensor is updated again to off
What do you mean with "just performed an action"?
Double tap to perform the toggle action
Ohhh. I'm an idiot I think.
I have a door sensor, but also switch
I see only a motion sensor in that template, the is no reference to any button press action
So I just need to include the switch in my logic
I'm using a mushroom card
Let me paste in my whole code
Yes, and you should also now that templates with now() are rendered once per minute (on the minute) so it will probably stay orange somewhere between 10 seconds and a minute
Depending on the time of the button press
Of note, "kitchen_motion"... is the garage door sensor
Of course it is ๐
That's helpful. I was noticing some delays. Any alternative for fast updates?
๐ I blame... only myself ๐
A trigger based template sensor triggering on a state change of the garage door sensor and an auto_off of 10 seconds
Then you can use that binary sensor and don't have to rely on last_changed or now()
Ok. I'm going to attempt to digest that ๐
Forgive my noobishness: "trigger based template sensor". Meaning something I'm creating within this specific template and self-referencing? Or something I'm created outside of this template based on the state change, that I am then referencing within this template?
Ah, so Automation -> Trigger: Template Trigger?
template:
- trigger:
- platform: state
entity_id: binary_sensor.kitchen_motion
from: "off"
to: "on"
binary_sensor:
- unique_id: cooldown_garage_door_sensor
name: Cooldown garage door
state: "{{ true }}"
auto_off: "00:00:10"
This will create binary_sensor.cooldown_garage_door which will stay on for 10 seconds after the kitchen motion sensor turns on
Amazing. Much easier to use
And similar format for creating a binary_sensor from a switch vs. another binary_sensor as well?
Yes, just change the trigger to the switch entity
And give it a different unique_id and name
And don't repeat the template: line in your configuration
And, potentially dump question, I'm just adding this to the code for the card before I make any references to cooldown_garage_door_sensor
This code needs to be added to configuration.yaml, not to your dashboard code
Roger that.
Man, thanks for being so responsive!
Would modifications to the template section of the configuration.yaml require a restart? Or does one of the reloadable subsections cover that?
the one that says "template entities"
Is that list of reloadables dynamic? I don't have Template Entities, so wondering if I need to restart and then I'll see it?
then you don't have one yet
Gotcha
you need to have at least one, and yes, it's dynamic
Hum. This doesn't appear to be working however. As the state change of the binary_sensor.kitchen_motion isn't updating the state of the cooldown_garage_door_sensor
The entity is binary_sensor.cooldown_garage_door
And the kitchen motion sensor has changed from off to on?
Yup
Would the default state of the binary_sensor.cooldown_garage_door be off?
In the dev tools, I can see the state changing for the kitchen motion sensor, but the cooldown is staying on
It would start at unknown after first creation, then after the first time it has been triggered it should turn on, and after 10 seconds it should turn off
So a full restart, it should show as unknown?
No, triggered based template sensors retain their state after restart or reload
Gotcha.
Setting the state manually to off, it's staying off after the kitchen motion triggers
I see what's wrong
The - before binary_sensor should not have been there
With it it indeed basically creates a binary sensor which is always on
I removed it in my code above
Sweet! That's working now
This is much superior to the time based method, and, will be super helpful for future stuff!
Nice ๐๐ผ
Note to self for future garage door setups: Have two contact sensors for open and closed. ๐
Also, in just generally chatting with my brother about what I'm fiddling with, he sent me this: https://twitter.com/memenetes/status/1600898397279502336
(YAML meme)
Hello, need a bit of assistance, trying to make a battery level gauge, found what seems a good way to do it(i only have voltage).
Found a page that kinda explains one way to do it. https://community.home-assistant.io/t/help-to-convert-battery-voltage-to-percentage/432579
But i got stuck with the values and don't know what they are 312.5 and 406.25 If anybody could explain those two values would be greatly appreciated
can someone please give me a hint why my mqtt sensor do not work anymore since Home Assistant 2022.12.0?
they are all configured like:
@noble pawn I converted your message into a file since it's above 15 lines :+1:
hello, wise men (and women)... got a template question.
I have a input_select named remote, with values: remote.living_room & remote.bedroom
and 2 apple TVs. Living_room & Bedroom
I am trying to send commands, to the selected apple tv
With mqtt.dump i get this data
edi/cmd/telinit,{"args": "4", "user": "tioan", "replyTo": "edi.msg.edish.send.21204", "touchedByExchangeTopicBridge": "True"}
How can i use the args value, in this example 4 as an value_template for an mqtt text sensor?
like this:
- state_topic: "HomeAssistant/rtlsdr/event/234"
name: Outside_Humidity
unit_of_measurement: "%"
icon: mdi:water-percent
value_template: "{{ value_json.humidity }}"
your value_template would look like:
value_template: "{{ value_json.args }}"
did that help ?
i will try it
Apple TV selector
Works, thank you
glad to be of service
what is wrong with this? :
service: remote.send_command
data:
device_template: "{{ input_text.remote }}"
Without seeing more (or if there is history above since I just logged on), I would say it should be formatted like this, no?
service: remote.send_command
target:
entity_id: remote.tv_room
data:
command:
- PowerOn
- Mute
device: Receiver
delay_secs: 0.6
I am trying to use a template to choose between 2 appleTVs
so I. don't need 2 sets of scripts
Sorry. I've not tried that, so I'll bow out. I can only reference what's listed here (https://www.home-assistant.io/integrations/apple_tv/). Depending on what value "{{ input_text.remote }}" hold, you should be able to substitute it on the examples they list. Without seeing more, I'm not sure.
yeah, that's what I'm working from
what does "{{ input_text.remote }}" contain?
remote.Living_room or remote.bedroom
Okay, so the line that says entity_id: should look like this I would say: entity_id: "{{ input_text.remote }}" since it contains the remote entity.
service: remote.send_command
target:
device_id: "{{ input_text.remote }}"
data:
device: "{{ input_text.remote }}"
hold_secs: 1.5
command:
- home_hold
- select
I think you need to keep the device_id: line and remove the device: line listed below that.
RobC, yes!
I'll bow out. Thanks @inner mesa
thanks cbhiii
Did you the docs?
yes, but I am confused
service: remote.send_command
target:
device_id: "{{ states.input_text.remote }}"
data:
hold_secs: 1.5
command:
- home_hold
- select
better?
i am reading
service: remote.send_command
target:
entity_id: "{{ states.input_text.remote.state }}"
data:
hold_secs: 1.5
command:
- home_hold
- select
Now read the big warning box
that got it, thanks @inner mesa
https://photos.app.goo.gl/7Kdoci42AuUvwU9TA
How do you do a platform correctly? Iv been messing with it and it still only puts a value of unknown when I check it's state, I have it a name after platform once but then was complaing I was initializing it twice idk
alright so here is whats stumping me
`template:
- sensor:
- name: Office HVAC Activity
state: "{{ state_attr('climate.office', 'hvac_action') }}"
- name: Office HVAC Activity
- sensor:
- name: Kitchen HVAC Activity
state: "{{ state_attr('climate.kitchen', 'hvac_action') }}"
- name: Kitchen HVAC Activity
- sensor:
- name: Dining Room HVAC Activity
state: "{{ state_attr('climate.dining_room', 'hvac_action') }}"
- name: Dining Room HVAC Activity
- platform:
name: office heating Today
entity_id: sensor.office_hvac_activity
state: 'heating'
type: time
start: '{{ now().replace(hour=0).replace(minute=0).replace(second=0) }}'
end: '{{ now() }}'`
im trying to count how long heating is on
and i had that after platform
it complained
yes i said i removed that
and that was wrong
il send you the error that makes
why?
no, don't
it's just wrong
don't put it under template:. It belongs under sensor:
docs are here: https://www.home-assistant.io/integrations/history_stats/
mhmmmmmmmmmmmmmmmmmmmmmmmm ok let me try that
blindly copying from the forum is bad
come on now that was completely blind, i tried to find info and other examples of platform being used
*wasnt
i thought history stats was just the name that i could then call on
still getting error Invalid config for [template]: [platform] is an invalid option for [template]. Check: template->sensor->0->platform. (See /config/configuration.yaml, line 30).
@keen holly I converted your message into a file since it's above 15 lines :+1:
thats the new code now
don't put it under template:. It belongs under sensor:
like in the docs
docs are here: https://www.home-assistant.io/integrations/history_stats/
i didn't think i could just say sensor outside of template in there ok let me try that
even copy and pasting in the example it gets mad
so its def not my spacing
` duplicated mapping key (41:1)
38 | start: "{{ now().replace(ho ...
39 | end: "{{ now() }}"
40 |
41 | sensor:
------^
42 | - platform: history_stats
43 | name: office heating Today `
@keen holly I converted your message into a file since it's above 15 lines :+1:
For Mushroom Template Card whatโs the syntax for referencing the selected entity in following fields? To get the Name?
Figured it out: {{ device_attr(entity,'name') }}
That's the name of the devices
Which could be different from the name of the entity
{{ states[entity].name }} will give you the name of the entity.
Or {{ state_attr(entity, 'friendly_name') }}
Because entity != device?
Correct, some entities, like helpers and groups won't even have a device
The device is more like the physical object, like a washing machine. Several entities can belong to a device, like s switch to turn it on and off, a sensor to indicate the state, a timer to set a delayed start etc
Your new template binary_sensors won't have a device either
Hello all, I need some assistance with a quick template. I have a template which gets the warning details for weather; however I want to put each warning on a separate line. Currently it displays them all after each other. Here is the code
{%- for state in state_attr('sensor.highett_warnings', 'warnings') -%}
{{state.phase | upper}} - {{ state.short_title}}
{% endfor %}
Hello, I have a fan tamplate and so far so good. Now i'm trying to make 3 preset speeds but cant get it working. Any suggestions? Here is my code:
https://pastebin.com/wfZn00Y3
I found a way to get the entity_name I want AND the display name, without using customize, but it requires creating them first and renaming them afterwards. However, it works to rename them in YAML.
1: Create the template sensor with the future entity_name you want (sensor.test_sensor) as name and prepare the display name you want for fast search and replace:
- unique_id: test_sensor
name: test_sensor
# name: 'The Display Name you really want'
state: ""
2: This creates the sensor with the entity name I want (sensor.test_sensor). Now reload.
3: Change the name to the display name you want
4. Reload and profit.
This way you don't get the leading 'template_' and you can still avoid the GUI.
If you prepare a separate file with all the templates you create, you can now search and replace all ' name' with '# name' and all ' # name' with ' name' and copy them all at once.
Hi,
why this template doesn't work?
entity: light.christmas_lights
icon: |-
{% if is_state('light.christmas_lights, 'on') %}
none
{% else %}
mdi:pine-tree
{% endif %}```
I cannot change icon dependent on state
try icon_template:
i think it has to be a "_template" to accept a template
doesn't work. Its then show attribute icon permanentaly
Than i am sry ๐ฆ than you have to wait for a pro
thanks for the effort
@velvet sigil only mushroom template cards can use templates
another approach which doesn't need you to change anything after creation is:
- sensor:
- unique_id: some_test_sensor
name: "{{ 'initial_object_id' if this.state == 'unknown' else 'Totally different name' }}"
state: "OK"
I have just tried template too, doesn't work
primary: Christmas light
entity: light.christmas_lights
secondary: ''
icon: |-
{% if is_state('light.christmas_lights, 'on') %}
none
{% else %}
mdi:pine-tree
{% endif %}```
what doesn't work? What is the result here?
and what is your goal? It looks like you don't want an icon when the light is on
exactly
try: icon: "{{ 'mdi:pine-tree' if is_state(entity, 'off') }}"
with the template you are currently using, your result will be the string "none"
not the special empty thingy none
in both "on" and "off" states no icon is displyed
I have tried like this
primary: Christmas lights
secondary: ''
icon: "{{ ''mdipine-tree'' if is_state(entity, ''off'') }}"
entity: light.christmas_lights```
no icon is displayed in both cases
fixed it , doesn't work aswell
works fine here
how come
type: custom:mushroom-template-card
primary: Christmas lights
secondary: ''
icon: '{{ ''mdi:pine-tree'' if is_state(entity, ''off'') }}'
entity: input_boolean.test
Is here any mistake I cannot see ?!
primary: Christmas lights
secondary: ''
icon: '{{ ''mdi:pine-tree'' if is_state(light.christmas_lights, ''off'') }}'
entity: light.christmas_lights```
you need to add quotes around light.christmas_lights
in the template
but as you specified it as entity, you can use the variable like I did
done thank you, fixed everything. now it works
Hello Everyone,
i'm new here and stuck at a sensor-template which i didn't get to run
Is there someone who can help me?
I try to get a sensor from a sensor attribute
Sure, share the template sensor config
how is the trick to put code in readable form?
@buoyant pine
sensor:
- platform: template
sensors:
sensor_pricelevel:
friendly_name: PriceLevel
entity_id:
- sensor.electricity_price_myhome
value_template: "{{ state_attr('sensor.electricity_price_myhome', 'price_level' }}"
To format your text as code, enter three backticks on the first line, press 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.
But the problem is you're missing a closing parenthesis in the template and everything below sensor_pricelevel: needs to be indented two spaces
Also, you don't need
entity_id:
- sensor.electricity_price_myhome
sensor is from the integration of Tibber (if this helps)
That's not really relevant, no
hmmm
i have the entity now but it's unavailable
You should use the new (since quite while) way of templating
i'm happy to but i don't know how
template:
- sensor:
- name: sensor_pricelevel
unit_of_measurement: "ยฐC"
state: "{{ state_attr('sensor.electricity_price_myhome', 'price_level' }}"
To be fair, the legacy version still works and doesn't have a deprecation announcement
But yeah, it definitely makes sense to use the new format for any new sensors
I'm not migrating my old ones unless they deprecate that format
never touch a running system ๐
This needs a closing parenthesis like I mentioned earlier though
yeah... I now see it too
template:
- sensor:
- name: sensor_pricelevel
unit_of_measurement: "โฌ"
state: "{{ state_attr('sensor.electricity_price_myhome', 'price_level') }}"
name can have spaces and stuff btw
and where we're talking abount a clean way to config....
i would like to have this in a extra file to keep config.yaml as clean as possible
in your configyaml put this
template: !include template.yaml
and the template.yaml should then start alike this
- sensor:
- name: "Gas Usage"
unique_id: Gas_Main
unit_of_measurement:
with 2 spaces
@heavy crown are you sure with the )?
i would put it behing "myhome'"
here: myhome'),
i can ignore the 2 spaces in front of "- sensor"?
- sensor:
- name: sensor_pricelevel
unit_of_measurement: "โฌ"
state: "{{ state_attr('sensor.electricity_price_myhome', 'price_level') }}"
and there i need the "unique_id"?
that's why i don't like yaml ๐
unique ID is optional. It just lets you change settings for the entity in the UI
I use the unique id so I can delete it via the gui...I play around alot
and as @buoyant pine said...settings
i can do this via GUI?
it makes so much fun to me to work with yaml, but i can live with working with gui only
(contains slightly sarcasm)
No, you can't create template sensors in the UI
How can i add a screenshot here?
Better get used to it.. the more complex stuff require yaml
although the devs DO work on improving the GUI
e.g. they just moved scrape to GUI
ss not allowed
Use imgur or similar to post images
i really like the gui of HA
I'm currently switching from OH
okay, then in this way:
It works!
@heavy crown @buoyant pine Thank you for your help!
viper539 Please use imgur or other image sharing web sites, and share the link here.
Image posting is blocked in most channels to discourage people from sharing text as images. Sharing text as images assumes that everybody sees the world as you do, which isn't the case. Some people are colour blind, or have visual impairment that means they can't make sense of an image of text.
@frail scarab ^
Does anyone how I can template my today's Google Calender events?
{% for cal_events in expand(states.myCALNAME) %} {{ as_timestamp(cal_events.attributes.start_time) | timestamp_custom('%H:%M') }}, {{ cal_events.attributes.message }} {%- endfor -%}
Does not work. (only one event)
generic_thermostat: How to get the target_temp as sensor_value to show in a the mini-graph-card?
events? You can't get todays events from a calendar entity. You can only get the next event
if it's an attribute of the climate entity, use the state_attr function and put it in a template sensor.
Ah thanks, so there is no way to get all the events ( I see them in my calander view though ) Thanks a lot
no
can i set a variable as the friendly name of this sensor via:
{% set name = this.get('friendly_name')%}
or is the syntax off or is there another way?
It's either this.name or this.attributes.friendly_name
ok thank you ๐
You can use get() if you're unsure if it exists at all
is there a this.attribute.name?
when I am inside of an attribute template? or can I get the name of the attribute I am currently inside anyway?