#templates-archived
1 messages ยท Page 49 of 1
they just added somethign like that
there's a config_entry_changed event, or something like that
again, requires a config entry
my automation is triggered by entity_registry_updated -- i didn't think the integration was in the event data, but let me tripple check thanks for the reminder
event_type: entity_registry_updated
data:
action: create
entity_id: switch.cloud_alexa
origin: LOCAL
time_fired: '2023-07-28T15:46:02.152994+00:00'
context:
id: 01H6EJV9S8H3246CPWYM9MK519
parent_id: null
user_id: null
i'm not sure what the context is... but the data dict doesn't have what i need
oh, yeah, that ๐
so.. that'd also be a sweet solution - if the event just had a bit more info
oh man, here's the solution:
{% set entity_id = "device_tracker.pihole" %}
{% set integration_name = "unifi" %}
{{ entity_id in integration_entities(integration_name) }}
thanks for your help and encouragement @inner mesa
yes, if you already know the integration
I was looking for a more general solution, rather than solving your problem ๐
yeah, maybe i didn't give enough context! i just want to know if new entities are coming from a specific integration
given an entity_id, what integration did it come from?
Thanks this will help
Hi all,
Could someone please assist in understanding why a template sensor becomes NaN after many hours of normal performance. This is coupled with the fact that when I restart templates while they are NaN state, they come back up as normal
@undone jungle I converted your message into a file since it's above 15 lines :+1:
@undone jungle I converted your message into a file since it's above 15 lines :+1:
`Ventilation power recovery
10 hours ago
Unavailable
Ventilation energy efficiency
11 hours ago
Unavailable
`
What do you mean it goes NaN
the value is NaN or the entity is unavailable
NotANumber
yes I know that
but NaN can only be produced by python when the math fails to calculate
so, is the actual state NaN or is it unavailable?
Sorry - Entity is currenly unavailable,
It sometimes showed up as entity is not a numerical output (or something to this effect).
Then you need to revaluate your availability template
The problem is that as per template tester, I don't.
It seems to work there just fine while at the same exact time on the dashboard it's
https://i.imgur.com/yikKMbS.png
The only way you can get a non real number w/ those templates is if it falls into the else case, which you don't have
I agree, but what is strange is that the template tester is working just fine while at the same time the entity is unavailable
I.e. is_state('binary_sensor.ventilation_bypass', 'on') and is_state('binary_sensor.fan_operational', 'off')
All the availability criterions are met
once it goes unavaialbe, it won't come back with that error
so fix your else statements
that error will also cause the entity to go unavailable
so, it's either your avail template or that missing else clause
and you're saying that the availibility is correct, so it's your else clause
that will also remove the errors in your logs
Would you mind having a look at it. I don't think I am missing a combination of conditions.
you are, i just explained what you're mssing
if this case happens is_state('binary_sensor.ventilation_bypass', 'on') and is_state('binary_sensor.fan_operational', 'off')
you will supply the template sensor with no value
that's just 1 that I found
I'm sure there's others
just put an else statement with a default output for those cases
But that combination is impossible. It can't have an open bypass while the unit is off.
The bypass would not have the power to open, so it must be getting some false states then.
HA is async, and templates resolve quickly, A momentary state change could be happening
that's why you always CYA
Yep that looks correct
You can probably get rid of all those other elifs because they all just output 0
I'll consider it, but I also like seeing the logic as I read through the templates
Even if its a bit cluttered.
Thank for help @mighty ledge, but that unfortunately is not it. With else the entities are still unavailable in HA, even after template entity restart, but the template is returned correct values in the tester.
Can you post your actual config and not an image of it please
Please see one
And here is the second one
I want it with your changes
Aaa..sorry. Just added the else. Give me a sec
@undone jungle I converted your message into a file since it's above 15 lines :+1:
Also, how are you including those
@undone jungle I converted your message into a file since it's above 15 lines :+1:
this part isn't going to help:
and states('sensor.incoming_air_temperature')
it's probably always true
Theyโre in the wrong section if they are in sensor
and yeah, they're templates
I just did a test and changed one of the is_state statements from (name of the sensor, on) to the same without a space in front of on and the sensors returned
template:
sensor:
- etc.
template:
sensor:
- etc.
When I change this back and forth now, it makes no difference now, but it just made the sensor appear as normal without issue a moment ago, when I changed it first.
I don't get it. I've done this now three days in a row, where I think I see a small typo, which is an additional space, or something, and that is why these two sensors stop working. I change it and the sensors are back. 10 hour later they are unavailable again, and persist as unavailable, even though they work in the template tester just fine.
I did absolutely nothing to make it become unavailable, but it does and then doesn't recover. If I make mostly any small change, save the file and restart templates, it's back up again.
It happens only for these two templates.
The only things that would cause that is source sensors going unavailable or you populating the state with an empty value by not having an esle clause
nothing else
No such issues with all other input entities that feed these calculations:
https://i.imgur.com/O6dBZ1J.png
They are all present.
then it's the else clause
I've added the else state now and let's see tomorrow.
Could you please confirm the else is where it should be in both sensors?
yep, looks good
personally, I think your templates need to be reworked
the way you code makes it hard to read
also, i'm not sure why you have this in your availability template is_state('binary_sensor.fan_operational', 'on')
I am very much selftaught and without any formal training, so whatever I pick up as bits and pieces I incorporate... kind of like Orc Whaaa! ๐
This is the main fan of the ventilation unit. If it's not ON all the values will be complete nonsense, since stale air will be left in the unit and any recovery or temperature data is of no use.
ok, then what's the point of checking it in your state template
that's what I mean by "the way you code"
you're making it unecessarily complicated
it makes it harder to read and harder to follow
your code should only highlight the paths you care about
e.g.
{% set strumienN = states('sensor.air_supply_flow') | float %}
{% set tcz = states('sensor.incoming_air_temperature') | float %}
{% set tn = states('sensor.room_supply_temperature') | float %}
{% if is_state('binary_sensor.ventilation_bypass', 'off') and is_state('switch.open_windows', 'off') %}
{% if tcz < tn %}
{{ (((tn - tcz) * strumienN * 1200) / 3600) | round(2) }}
{% else %}
{{ ((((tn - tcz) * strumienN * 1200) / 3600) * -1) | round(2) }}
{% endif %}
{% else %}
0
{% endif %}
much easier to read and understand what's happening
Fair point, I won't lie, this looks much simpler. Won't removing all the additional information (such as the fact temperature comes as float,etc.) make it much less robust?
Can't you just use | abs instead of the nested if?
{% set strumienN = states('sensor.air_supply_flow') | float %}
{% set tcz = states('sensor.incoming_air_temperature') | float %}
{% set tn = states('sensor.room_supply_temperature') | float %}
{% if is_state('binary_sensor.ventilation_bypass', 'off') and is_state('switch.open_windows', 'off') %}
{{ (((tn - tcz) * strumienN * 1200) / 3600) | abs | round(2) }}
{% else %}
0
{% endif %}
not really.
Yep, didn't pick up on that ๐คฃ
make's it so you don't need the variables either then.
I am sorry I don't understand which way you are going.
Need to look this over when in front of a monitor but indeed sound like this could be further simplifying things. If the outside temperature differential is the only determinant which later gets converted to a positive output., then using an absolute number should be enough
can anyone see anything wrong with this? https://pastebin.com/sdKJ86Ew
the switch isnt showing up in entities
I've looked at that but the templating seems to be slightly different when included
same with the other stuff that's included in the other files doesn't match that type they show in the configuration example but the other stuff works
It needs to be in switch with platform template, not in template
ah, so if i wanted to include it would basically be?
switch:
- platform: template
switches: !incldue blah;
will give that a try, thanks
bah discord messed up the syntax
yeah that got the dev tools seeing it when i did check config, thanks
Template loop detected while processing event: <Event state_changed[L].. that is new to me: {% set period = states('input_number.lightning_strikes_period')|float %} {% set ns = namespace(count=0) %} {% from 'lightning.jinja' import strikes %} {%- for s in strikes().split(',')|reject('eq','') if states[s].last_updated > now() - timedelta(hours=period) -%} {% set ns.count = ns.count + 1 %} {%- endfor %} {{ns.count}}
and when entered in dev tools template does not tjhrow an error
unless its the attribute to coin the phrase: {% set period = states('input_number.lightning_strikes_period')|float %} {% if this.state|int(default=0) != 0 %} {% from 'lightning.jinja' import strikes %} {%- for s in strikes().split(',')|reject('eq','') if states[s].last_updated > now() - timedelta(hours=period) -%} {{'Inslagen om: ' if loop.first}} {{-as_local(states[s].last_updated).strftime('%H:%M')}}{{', ' if not loop.last}} {%- endfor %} {% else %} Geen inslagen de afgelopen {{period}} uur {% endif %}
but that shows a correct list of times too, so I am at a loss really what to check for that Warning to go away
So 'return' isn't valid here. Is there a way that doesn't involve fetching from states() 6 times?
value_template: >
{%
set aqi = states('sensor.air_quality_index')|float(0)
if (aqi >= 300) return "darkred"
if (aqi > 200) return "purple"
if (aqi > 150) return "red"
if (aqi > 100) return "orange"
if (aqi > 50) return "yellow"
return "green"
%}
And am I the only one who has Studio Code Server get stuck in some mode where it thinks hitting enter means 'find next' instead of insert newline? I wind up having to switch to something else in sidebar and back to get out of it.
Can't get it to accept this either.
value_template: >
{{
set aqi = states('sensor.air_quality_index')|float(0)
"darkred" if (aqi >= 300) else
"purple" if (aqi > 200) else
"red" if (aqi > 150) else
"orange" if (aqi > 100) else
"yellow" if (aqi > 50) else
"green"
}}
You're confusing JS and Jinja
You need to write valid Jinja
value_template: >
{% set aqi = states('sensor.air_quality_index')|float(0) %}
{% if (aqi >= 300)%} darkred
{% elif (aqi > 200) %} purple
....
I read that it was not possible to set a variable inside a block and have it show up outside the block.
That's the same block...
The first %} doesn't end the block introduced by the first {% ?
No, the next YAML key would start a new "block"
Oh. Wasn't clear from what I read exactly what a block was so I made a wrong assumption.
HA has a template editor where you can play around with stuff: https://my.home-assistant.io/redirect/developer_template/
its definitely not new. I can guarentee lighting strikes macro is touching the entity that your templates reside in. I've definetly helped you with a loop detection before.
Also, devtools doesn't show warnings, there is probably a warning in the log though
Hello template gods, does anyone have an automation based on their sensor.mobile_app_next_alarm entity? My template for it recently started getting triggered everytime I plug in my phone to charge
Keep getting startled everytime I go to bed from the music ๐
Sadly we're not mind readers (any more anyway, not after the last time we tried). Please share the YAML and any errors so we can see what you've done.
๐
I was writing the yaml! You're too fast
{{now().strftime('%a %h %d %H:%M %Z %Y') == (((state_attr('sensor.thanasis_next_alarm', 'Time in Milliseconds') | int / 1000) ) | timestamp_custom('%a %h %d %H:%M %Z %Y'))}}
took this from somewhere obviously. I'n not good enough with (time) templates
I'm waiting for my barber appointment btw, so if I stop responding it was my turn
I don't see an obvious reason why this would trigger when you start charging your phone
Also somehow my entity in HA and my actuall alarm has a 1h difference ๐ฅ
see just plugged it now
That's because of timezones, one is probably in UTC
Hi is there any solution to iterate through the whole media_player domain without creating a group by hand?
Is your next alarm at that time?
Is that a template sensor, or just the sensor provided by the companion app
Sure, start with states.media_player
now that is the time I plugged the phone in, and every time I plug in the phone it changes to the now time
and now it changes back
only that my alarm is at 7:15 instead
๐
try explaining that hahaha
but template looks OK right? so the problem is with the mobile app integration, not a template issue
So the companion app sensor changes to the current time when you start charging and then changes back
That's indeed something for #android-archived
Or file a bug report
Template does what it should do
Yeah that is what I meant, test in dev tools, check the log. It must have been a specific situation because thereโs no trouble now
i tried and get back <template DomainStates('media_player')> what do i need to do when i have to list all?
In fact it it happened once.
What do you want to list?
got it ๐ {% for item in states.media_player %}
{% if item.state | lower == 'playing'%}
{% if 'Emby' in item.attributes.friendly_name %}
{{item.attributes.friendly_name}}
{% endif %}
{% endif %}
{% endfor %}
thank you ๐
well it won't because it cant be put into a template loop because you're not inside the sensor and referencing itself
the template editor will never have a loop detection warning because it's not inside a template sensor, so no loop can happen
that, but turn the order around (or the operator) ? or.. o well, I always start with the smallest value and an < operator:```
{% set temp = states('sensor.buienradar_temperature')|float(0) %}
{% if temp < -20 %} black
{% elif temp < -15 %} navy
{% elif temp < -10 %} darkblue
Is there a reason you're not just using a Time trigger based on the sensor itself?
that's rather new, many people don't know about it
{{ states.media_player | selectattr('state', 'eq', 'playing') | selectattr('name', 'contains', 'Emby') | map(attribute='name') | join('\n') }}
This should do the same without the need for a loop
looks nice ๐ is it possible to select the media_title also?
if have now {% for item in states.media_player %}
{% if item.state | lower == 'playing'%}
{% if 'Emby' in item.attributes.friendly_name %}
{{item.attributes.media_title}} auf {{item.attributes.friendly_name}}
{% endif %}
{% endif %}
{% endfor %}
Petro is right. Back when I made the automation that didn't exist. Clever though I'll change it to that
Thanks for the hint
Still need to workout the issue with the time changing when I plug the phone though. SO weird! Aha! Package: com.miui.securitycenter
okay thank you ๐
24 hours later and here we are again, with the else statement:
First it was non-numerical and a minute later unavailable
If I make any change in the syntax, save the file and reboot templates, it will be back up.
Even if this change is completely inconsequential and changed back will work just fine as well
can you post the errors from the logs
non-numerical means it will never come back
also post the history of all input devices at that moment in time
There isn't anything in the logs concerning this entity, nor can I find anything related to templates
... that's impossible if you're saying 'non-numerical'
so you aren't telling the truth about one thing or the other
There is a modbus error, and these are mostly values from modbus (i.e. HVAC unit via modbus):
Logger: homeassistant.components.modbus.base_platform
Source: components/modbus/base_platform.py:350
Integration: Modbus (documentation, issues)
First occurred: 21:14:51 (147 occurrences)
Last logged: 21:22:03
Unexpected response from modbus device slave 11 register 4224, got 0x a
where are you getting this 'non numerical' crap from?
that's what I want to see
I don't want to see your version of that message, I want to see the message
Instead of the 'entity is currently unavailable' it was the non-numerical for a minute before - on the dashboard where a gauge card should be.
my man
don't look at the UI for states
use history
that's a message from that particular gauge
Do me a favor, go to your history, throttle the time to 10 minutes before and 10 minutes after the event
select all 5 entities that make up the template sensor and the entity itself
and post that image
Both gaps are HA reboots
After the second there is a brief lack of response from the 'operation' binary sensor, but this should be captured by else, I suppose.
I only see 2 values? Didn't the template have 3?
Efficiency is the output, two temperatures are inputs. There may be a flow as well, let me see
can you post which template we are talking about right now
with your current config
@undone jungle I converted your message into a file since it's above 15 lines :+1:
I'll correct the graph with the additional variable, just a sec
thanks
That is all of them
After the unit boots up, the values are streaming but the template doesn't come back up.
This started on 2023.07, or at least never happened before very recently
It looks like as if the 'fan.operation' sensor being off or unavailable as the unit boots up brings the template down and it never recovers.
well, like i said before, I don't know why you have that in unavailable
personally, I'd just have 0 when the fan was off
and I wouldn't care about the state of the ventialtion bypass either
all that matters is that you have numbers for your values, the template can cover the rest.
you also don't really have a safety net in your code
if t1 and t3 are the same value, you'll divide by zero
that will cause an error
this is what I would use
- name: Ventilation energy efficiency
unique_id: recu_energy_efficiency
icon: mdi:percent
device_class: percent
unit_of_measurement: %
state: >
{% set t1 = states('sensor.incoming_air_temperature') | float %}
{% set t2 = states('sensor.room_supply_temperature') | float %}
{% set t3 = states('sensor.room_exhaust_temperature') | float %}
{% if is_state('binary_sensor.ventilation_bypass', 'off') and is_state('binary_sensor.fan_operational', 'on') and is_state('switch.open_windows', 'off') and t1 != t3 %}
{% set output = (t2 - t1) / (t3 - t1) * 100 %}
{{ ([ 0, output, 100] | sort)[1] | round(2) }}
{% else %}
0
{% endif %}
availability: >
{{ [
'sensor.incoming_air_temperature',
'sensor.room_supply_temperature',
'sensor.room_exhaust_temperature'
] | map('states') | select('is_number') | list | length == 3 }}
there should be no risk of failures with that.
Thank you, I'll review and come back with questions, if you don't mind!
and you could simplify the first 3 lines to
{% set t1, t2, t3 = [ 'sensor.incoming_air_temperature', 'sensor.room_supply_temperature', 'sensor.room_exhaust_temperature' ] | map('states') | map('float') | list %}
- Won't the above go to zero every time the t1 = t3 which is bound to happen as the night/day cycle progresses? This will result in some efficiency and a zero in between, with the same being true for the other template for power.
yes
but it's simple math man
that makes your denomiator 0
you can't divide by 0
that's a math rule
can't get around that
I know that right now there would be a divide by zero error, technically, but it doesn't show up in the date, for some reason. Hence, even though through ignorance, that is preferable
no it's not preferable
dividing by zero will make that error
see the red error?
that means your entity would not come back
if you want a rock solid template, you account for everything, you don't ingore things because you like them a certain way
I am not disagreeing with you, but this specific failure mode just doesn't happen for some reason. Either they never synch perfectly and jump over an identical temp somehow or IDK.
well, you should account for it regardless
I'll try it out, though if accounting for it means having additional zeros messing up other calculations, I'll have to look for another way. I am very sorry if it sounds as if I don't appreciate your input. That is not the case - just trying to be pragmatic about down the line information storage.
I think you're over thinking it
You are probably right! I often do.
That's just the way I am... lol
you're having problems, but you're not willing to account for them and you're making your templates extremely hard to manage and read
I think you're thinking he's overthinking it
too much thinking going on
I believe there isn't device_class: percent. It's giving an error
I've found fixed the other which is % must be in parentheses.
@undone jungle I converted your message into a file since it's above 15 lines :+1:
@undone jungle I converted your message into a file since it's above 15 lines :+1:
I've also added device_class: power here after I posted, for the long term statistics
Let's see what happens over the next 24h
๐ค
There is one last issue I'll have to resolve which is what happens when the unit is turned off via the software switch.
This means the temperatures will still be reported, but this will be stale air that will produce nonsense values for both power and efficiency.
I'll probably modify the availability to include it somehow, though it's risky once again, that it will get confused when HA is rebooting and modbus is not yet up....
Template friends - can I get a sanity check? Traces gives me the following error: Choose: Option 2 executed
Stopped because an error was encountered at July 29, 2023 at 6:11:11 PM (runtime: 0.03 seconds)
not a valid value for dictionary value @ data['entity_id']
@edgy flume I converted your message into a file since it's above 15 lines :+1:
Sorry - slow in copy-pasting
let me know if you'd like to see the script too - but the script is working fine (I get its notifications without issues)
media_player doesn't appear to be defined
the service media_player or the variable playing_media_players?
playing_media_players: >-
{{ expand('media_player') | selectattr('state', 'eq', 'playing') |
rejectattr('entity_id', 'eq', 'media_player.office') |
map(attribute='entity_id') | list }}
That
You're right. Ah - okay now I'm all confused - I wonder if it was supposed to expand the speaker groups I created under helpers for the script.
Did you write that?
No, I'm getting help from the unthinkable.
I did write the script though, with help from here.
Good luck
Thanks.
Good morning everyone
any chance of modifying my template to show me the device name instead of id?
{{ integration_entities('tasmota') | map('device_id') | unique | list }}
I was thinking of wrapping device_attr around it but it does not seem to work for a list)
{{ device_attr(integration_entities('tasmota') | map('device_id') | unique | list, name_by_user) }}
{{ integration_entities('insteon')|map('device_attr', 'name')|list }}
So simple! Thank you ๐
I am trying to only list those devices that are available and played with has_value. Cannot seem to get it right though.
{% if has_value(integration_entities('tasmota')) %}
{{ integration_entities('tasmota') | map('device_attr', 'name') | unique | list | count }}
{% endif %}
Returns AttributeError: 'list' object has no attribute 'lower'
Of course a one-line would be nicer, but I couldn't get that to work ({{ has_value(integration_entities('tasmota')... either ๐ฆ
Also no luck with
{{ integration_entities('tasmota') | rejectattr('state', 'in', ['unavailable', 'unknown']) | map('device_attr', 'name') | unique | list | count }}
UndefinedError: 'str object' has no attribute 'state'
Nope
{% set devices = integration_entities('tasmota') | map('device_attr', 'name') | unique %}
{{ devices | rejectattr('state', 'in', ['unknown', 'unavailable']) | list }}
{{ is_state_attr('sensor.dwd_weather_warnings_stadt_xxxxxx_current_warning_level', 'warning_1_parameters')['gusts'] | replace('<', '') | replace('[km/h]', '') > 59 }}
why this template are not working, someone can help?
You are comparing a number to a string
can you assit me? dont know how i can change these
i need it as a trigger in an automatisation
{{ integration_entities('tasmota') | select('has_value') | map('device_attr', 'name') | unique | list | count }}
You need to look at what to use where, you are mixing filters to be used on state objects with filters to be used on entity_ids
Ah, I understand. I thought that in the quoted trial code I was checking and rejecting the state of the entity belonging to tasmota.
integration_entities() returns entity ids, not state objects
I created a template trigger from event data, how can I make sensors out of these? https://pastebin.com/WUTpNuM6
yeah, I tried that but get this error: Invalid config for [template]: [sensor] is an invalid option for [template]. Check: template->sensor.
sensor is under id at same level of platform
what I pasted is the content of templates.yaml that I include with template: !include templates.yaml
without "sensor" it works, or better I dont get any arror, if I add sensor after each id: , I start to get that error
sensor is under id at same level of platform
There is no sensor, nor platform in that code you shared
template expects a list, you're providing a dictionary. You should start with a hyphen.
That will also allow you to put sensor on the and level as trigger, where it belongs
nut if I put on the same level of "trigger" how can I create multiple sensor per platform?
I need onw per each patform
there's an example in teh docs
yes, but the example is with one entry under trigger, if I have more and I need a sensor for each?
how the indention would be?
template:
- trigger:
- platform: event
sensor:
- name: trigger based sensor 1
- name: trigger based sensor 2
- trigger:
- platform: event
sensor:
- name: trigger based sensor 3
- sensor:
- name: state based sensor 1
like the example
yes, this is a sensor for the same event, I have multipl events under the same trigger
so I need to create a sensor per event
not multiple sensor for the same event
ah, I can have multiple trigger
then use the ids you created
ok, makes sense, thanks
Yes, because it is a list
right
and how can I print out somewhere the content of this? trigger.event_data.args[0] , I don't know what it contains so I can't be sure that I am assigning the right value to the sensor
can I print it in dev tool somewhat
Listen to the event in devtools > events
- Just make it the state
- Make an automation that uses
persistent_notification.create
https://pastebin.com/WUTpNuM6 , I did some parsing here, but I need to know the content of trigger.event_data.args[0] now
but if you simply look at the event in
-> Events, you get the whole structure
ok
in the trigger I filtered out a lot of not needed things
then do one of the things I suggested
how?
trigger.event gives the whole event
- platform: event
event_type: dahua_event_received
event_data:
name: Dahua
Code: CrossLineDetection
action: Start
data:
Object:
ObjectType: Human
This will most likely not trigger from my experience. Best to do the test in the state template
uhm, how if the sensor/entity is not created yet?
events don't requires entities
in the state templace I can print out the content of a sensor/entity, but how can I print the content of my trigger.event_data
what I built here https://pastebin.com/WUTpNuM6 is a selection of what I need from a raw event that I see in the event dev tool, so now I have my filtered data in trigger.event_data.args[0], correct?
how can I show it?
sorry, i just jumped in here
If your dahua creates events, then you have to listen to the events and build your triggers off them
this is what I am trying to do
ok, well, you've yet to post your event
you've only posted what you think it looks like
this is an example
I just need to create a sensor/entity out of these kind of events
the vent structure is the same, they change just a couple of fields
well, from what I can tell your triggers are wrong
unless you have a camera named dahua
but you have name: dahua in all of those, but the name is garage.
seems like your indentations are correct, so if you have a dahua camera then it would work
yes, it is
well, the name is not dahua, but in this event is "garage"
and I have others too, but the strucutre is the same
so, the name in my trigger probably is wrong, I have to create it for each cameras, with the right name?
that is fine, I can do it, but now, from what I have, how can I add the sensor creation there?
you can just omit values
you don't need to have it rigidly find the event data
you can have it trigger off any event and then you perform actions using the event data in your messages
yes, but I need to create a sensor per camera
yes, so changing the name it should
yes, correct
first thing now: how can I test that my trigger is correct?
second how can I build a sensor out of it?
by making the camera create the event
by making a template sensor that uses the trigger as the 'trigger', and you pull the data into the state.
robc already linked the docs for making the trigger based sensors
but I need to know if the content in my trigger is correct, not the raw event, is there a way??
why do you need to know that
make an automation if you want to see it happen live with a gui
to know if my trigger is parsing the data correctly
looking back these suggestions were already given to you
I will check that, and what about the content of trigger.event_data.args[0], can I print it somewhere?
so, either listen to the events, or make an automation that shows the 'trigger'
... my man, did you gloss over what the fes said?
you meand this? "trigger.event gives the whole event" ?
what I dont unerstand is where can I get it, is there a "trigger console"? ๐
Sorry, rob said it, not thefes
there is no trigger console
anyways, rob detailed what to do
right here
ok, I will re-read all the msg carefully and try it, thanks all anyway
Automations are more easy to debug, you can create an automation with the same trigger and maybe just delay: 0 as the action and see the whole event in the trace
yep, I will try this method
Or send it in a notification as Rob proposed
thanks
I've got a template sensor that calculates distance between two entities and it only shows the history bar, not a statistic graph
how can I change the type of the sensor?
Add a unit_of_measurement
Documented, but not necessarily obvious
hi again, so I followed your suggestion, so I created the automation with action persistent_notification.create, but probably the trigger is not correct and the notification never happen, so now I am trying to debug the trigger itself, but I don't see any log about that to throubleshouting
even the sensor has been created, but of course it never been updated, probably for the same reason
So what's your trigger
this is the template for the trigger sensor https://pastebin.com/aRtWY74j , this is the automation https://pastebin.com/6VmfvseF and this is the raw data get from event listener https://pastebin.com/WZwMx3bG
(the raw event contains name: Garage, but I also have name: Giardino)
it seems that the trigger is not catching the event, but no logs to confirm this
It won't work like this, you can't provide partial information of a key from the event_data in the trigger
You need to provide the whole value
So it's better to check on it in a condition (in case of an automation) or in the state template in case of a template sensor
what do you mean with the whole value? I added the fields that I need to filter, the rest of data in the whole event is not important for me
I probably dont even need all of them, just the name, the ObjectType and the action, for filtering what I need
Your trigger will now fire when data exactly matches:
Object:
ObjectType: Human
It will never do that as the data key contains a lot more information
So you need to check on the ObjectType after the trigger, not in the trigger
can you please provide an example? I dont get it, I need the trigger when ObjectType is "Human", this field can also contain different values yes, but I just need when it is = 'Human'
trigger:
- platform: event
event_type: dahua_event_received
event_data:
name: Giardino
Code: CrossLineDetection
action: Start
id: giardino_human
condition:
- "{{ trigger.event.data.data.Object.ObjectType == 'Human' }}"
action:
service: persistent_notification.create
data:
message: "my giardino human test"
title: "dahua human giardino"
this is odd, I was not aware that I need to filter for ALL the possible fields under data to make it works, I was thinking that it is possible to filter also for only the fields that I want
@marble jackal no notifications, no errors, nothing is happening
Check your trace to see if it triggered
where?
one of the sensor that is generated by the dahua integration triggered, so the event happened
In the automation trace section.
ah ok, let migrate it to the UI editable one
you don't need to, just add id: alkdjflaksjdflkjlskjfd
no trace found, it means that the trigger is not catching the event?
That would be correct
keep in mind, Ive never seen your events have the name that matches your trigger
your events are all Garage
let me get one with the exact name
Also, you have CrossLineDetection or CrossRegionDetection
The only thing that seems correct is Start
Your trigger is CrossLineDetection and your event was CrossRegionDetection
it's gotta match exactly.
if you want both, it needs to be in the condition.
or you have to duplicate your trigger.
you can't
so I have to create another trigger for it?
...
what I meant how can I check something like: Code: CrossRegionDetection | CrossLineDetection ?
my guy
I really think you don't read my responses
let me copy and paste what I wrote again that answers that question
If you want to create your template sensors with the object detection & logic applied to all cameras, I suggest an automation with a custom event.
uhm, I was thinking to use something like this in the state: under template sensor {{ trigger.event.data.data.Object.ObjectType == 'Human' and trigger.event.data.data.action == 'Start' }}
but the logic will be more complex if I need to check for 'Stop' too
can you please provide an example of an automation with custom event?
alias: Dahua Camera Event Translator
id: Dahua_Camera_Event_Translator
mode: parallel
max: 25
trigger:
- platform: event
event_type: dahua_event_received
action:
- event: dahua_translated_event
data:
name: "{{ trigger.event.data.name }}"
detection: "{{ trigger.event.data.Code in ['CrossLineDetection', 'CrossRegionDetection'] }}"
type: "{{ trigger.event.data.data.Object.ObjectType }}"
action: "{{ trigger.event.data.action }}"
That will create a custom event that just has the data you care about.
then your triggers will be
I think I can remove Code: CrossLineDetection from the trigger, right?
hold on a sec
then your trigger will be:
- platform: event
event_type: dahua_translated_event
data:
name: ...
detection: True
type: ...
action: ...
That automation will work for all cameras and all events
and the new sensors?
and the new sensors will use the translated event as the trigger
you just have to fill the sensor triggers out with the information you want to capture
ah ok, in the template for platfrom event that I created
[homeassistant.components.automation] Automation with alias 'Dahua Camera Event Translator' could not be validated and has been disabled: extra keys not allowed @ data['action'][0]['data']. Got {'name': '{{ trigger.event.data.name }}', 'detection': "{{ trigger.event.data.Code in ['CrossLineDetection', 'CrossRegionDetection'] }}", 'type': '{{ trigger.event.data.data.Object.ObjectType }}', 'action': '{{ trigger.event.data.action }}'}
data needs to be event_data
this is what I added in my automations.yaml file https://pastebin.com/JdHxBjrB that I include with automation: !include automations.yaml
oops, my b
thanks
Hello, I need some help writing a template condition that compares two attributes from the same sensor
basically, I have a "climate.bedroom_TRV" entity that lists the TRV's operating modes if called directly and "set_temperature" and "current_temperature" as attributes and I don't know how to tell the template to use the attributes instead of just the direct value
I have zero knowledge of templating or yaml and I'm trying to use what I can find online
this is a template I have that seems like it should do what I need, but I have no idea how to add "state_attr" in it
{{ states('climate.bedroom_trv') | float < states('climate.bedroom_trv') | float + 1 }}
I suggest reading that section in the docs
so, whould this be correct then?
{{ state_attr('climate.bedroom_trv', 'current_temperature') | float < state_attr('climate.bedroom_trv', 'temperature') | float + 1 }}
I need it to compare "current_temperature" with "temperature" and only act if the difference between the two is larger than 1 degree
Can an area somehow be used as an entity? I want to add an area's lights to a history card. Or must I rework that somehow?
No, you can't use an area light that. You would need to create a group with group.set to create a dynamic group based on area_entities()
Should be fine. You probably don't need the |float there, but it won't hurt
"current_temperature" can list values along the lines of 25.1 degrees, so I figured that adding the |float should help with the decimals
it doesn't do anything with that
it's only needed if you want to turn a string into a float
Ok, thanks. Will try to make something work with groups then ๐
so the info I found was wrong. Can you please link me to the correct documentation?
not sure what you're looking for
that's just the way it is - if you have a string that represents a numeric value and you want a float, use |float, preferably with a default like |float(0)
If you already have a float, you don't need it. Since attributes can retain their native type (unlike states, which will always be strings), numeric values in attributes are probably already the proper type
I see. Thank you for the explanation.
Final question then, how can I eliminate the decimal point from the value?
use |int to just truncate/chop it off or |round(x), wehre x is the number of decimal places to round to
Something like this? {{ expand(area_entities('kitchen')) | selectattr('domain', 'eq', 'light')|map(attribute='entity_id')|list }}
or can it be done more efficient?
that's a lot of work for just {{ area_entities('kitchen') }} ๐
Agreed
ah, you just want lights
Yes, there is a bit of filtering, so not total waste I hope
{{ area_entities('kitchen')|select('match', 'light.')|list }}
Oh, much neater, thanks ๐
So to create a globing group, would I list my areas ans then loop them through this line to get the entities?
that already provides a list
True, but for one area only. I'd like to end up with one large group with all area's lights
is that different from all lights?
Hm. Shouldn't be, youre right. Then I can just filter on state to see which is on or not
๐คท
{{ areas()|map('area_entities')|list }}
you really want this:
{{ areas()|map('area_entities')|sum(start=[])|select('match', 'light.')|list }}
Perfect! Was just trying to cut the pieces together. Haven't seen sum before... ๐
Very nice, thanks! ๐
what is the jinja solution for checking that a value is not 'undefined' before passing it to float? For instance:
{% set total = states('sensor.that_is_sometimes_unavailable') | float %} gets errors when that sensor isn't available, and I'd like to handle that to prevent the errors
if you want to ensure that total has a value, use |float(0), or whatever default you want
it really depends on the behavior you want if it's not available
if i have {{ states('binary_sensor.windows_11_aaron_p600s') }} , is there a way to get the value of its previous state?
No, templates only have access to the current state
well im using it in an automation so that doesnt matter i guess, how do i?
i was trying to update a Helper when the state changes because the last changed time of the state changing obviously resets when i reboot and i wanted to not show that
Soooo...
I have sensor.home_general_forecast which has a array (forecasts) of dictionary structure under it {start_time, end_time, per_kwh}
I kinda need to do this (not real code)
state_attr('sensor.home_general_forecast', 'forecasts') | filter(start_time > today@15:00 && end_time < tomorrow@7:00) | min(per_kwh)
any tips? ๐
Does anyone has experience how to create a "virtual" device in HA that you can assign some "real" enities to? Here is the use case: I have several plugs that I would like to aggregate under one main device
You add them to a group
Sounds good - How do I create a group then?
Settings > Devices > Helpers > Add group
keep in mind that grouped devices in the UI need to be all the same domain
so if they are sensors, then you'd make a sensor group... etc
Makes sense ๐ Thanks much for the advice
But beside groups I guess there is no actual way of creating a "virtual device" right? I just thougt it would be nice to click on a device to see all plugs assigned to it and then switch them seperately (now itยดs just on and off for all)
you are creating a virtual device
but it doesn't have the name 'virutal device'
Well it doesnยดt show up in devices ...
it's an entity
It jhust would be nice to have sth. like that: https://ibb.co/0tNxbJz
Instead of navigating device pages, why not make a dashboard with the layout you want to see?
You can make an entities card w/ all the switches grouped together that you'd like
Yes, that would be an option - anyway, not quite the same as an virtual device but I guess the group will do then
Itยดs a little sad that when using the "Remote Home Assistant" integration, only single entities are getting synched but not the actual device#
Hello everyone
I'm trying to find out how to setup a fan template, so I've got a IR fan and it generates 4 scenes on home assistant (Fan_off, Fan_1, Fan_2, Fan_3)
Anyone has a template to help setup so that those 4 scenes works as a single fan template?
Thanks so much for the help
scenes? are you sure about that?
yeah, the IR blaster that i have at the moment creates the ir comands like scenes instead of buttons or something else.
How do i get the selected option of an input_select in a template
it shows unknown if i use states
it's the state
oh the input select must be recreated. sigh
Hi all, so if I wanted to TTS a response from openai conversation, is this how to do it?
http://pastie.org/p/477wSekkOUhESWWFmEZBly
I have a feeling I need to use the responce variable somewhere, but not sure where
maybe it should be
message: >-
{% if ('quote.response.response_type == action_done') %}
Your Quote of the day is {{ quote.response.speech.plain.speech }}
{% else %}
No quote today.
{% endif %}
Hello! I am new to HomeAssistant and I just made the Cast to my Google Nest Hub working but I have a problem when casting the dashboard to the nest hub. I have a custom card and it have some value_template with some functions to process the time value, but on the casting display, the functions seems to not work. Any ideea how I can fix this?
Does anyone know if i can filter a list of entities by domain (eg. light), this template seems to pick up everything in the area:
{% set lights_on = expand(area_entities('office')) %}
{{ lights_on | selectattr('state', 'eq', 'on') | list | count > 0 }}
{% set lights_on = expand(area_entities('office')| select('match', 'light')) %}
{{ lights_on | selectattr('state', 'eq', 'on') | list | count > 0 }}
{{ area_entities('office') | select('match', '^light.') | select('is_state','on') | list | count > 0 }}
Ahhh nice, love a one liner - thanks! ๐
ok, this seems to be working
data:
agent_id: [redacted]
text: quote of the day
response_variable: quote
- service: tts.speak
data:
cache: false
media_player_entity_id: media_player.
message: |-
{% if ('quote.response.response_type == action_done') %}
Here is your AI quote of the day {{quote.response.speech.plain.speech | trim | replace('\"','')}}
{% else %}
No quote today.
{% endif %} ```
i found I had to add the | trim | replace('\"','') not sure what that means
no...
You'll never get no quote today with that code
if you check your automation, you'll be able to see the response data and then you can fix this {% if ('quote.response.response_type == action_done') %}
but that part is wrong, you're basically saying if True, which is always true. because it's a populated string
oh, ok, that whole "if" part was to take care of the case where there is an error, and that would be reflect by this:
response_type: error
but is the response if successful, it would be this:
response_type: action_done
so, it will not recognize if the response_type: error as written?
Hey guys I used to have a template working, however I had to restart my home assistant from a backup and the template no longer works
{{ now() - state_attr('automation.roborock_clean_if_tv_turns_off', 'last_triggered') > timedelta(hours=12) }}
Testing to see if an automation hasn't run for last 12 hours or more
I get this error "In 'template' condition: TypeError: unsupported operand type(s) for -: 'datetime.datetime' and 'NoneType'"
well, you wrapeed the statement in quotes, so it's just a string not a statement
'quote.response.response_type == action_done' -> quote.response.response_type == 'action_done'
thank you!
Your automation hasn't triggered yet, so there is no datetime in the attribute
d -> s
line 1, position 39, d -> s
๐
I put it in our language
Hehe
{% set last_trigger = state_attr('automation.roborock_clean_if_tv_turns_off', 'last_triggered') %}
{{ last_trigger is none or (now() - last_trigger > timedelta(hours=12)) }}
you could do
If you are using this in automation.roborock_clean_if_tv_turns_off you can use this.attributes.last_triggered
{{ now() - (last_trigger or now()) > timedelta(hours=12) }}
Could that possibly give a negative timedelta of a few milliseconds?
probably
It will still not exceed 12 hours
Maybe I'll add another macro called this_minute()
which will be exactly on the minute
and a this_second()
or something like that
this_hour()
or today_at('now')
๐คทโโ๏ธ
time needs to be easier
Thanks both of you!
I have some Zigbee bulbs that are 2700K-6500K, but claim over Zigbee to be 2000K to 6536K. So when Adaptive Lighting tries to control them, the colors come out all wrong.
Does anyone know how to make a template that remaps them? The doc just says how to set the min and max, but my interpretation of that is if I set the limit to 2700, it will cap the value HA asks for to 2700K, resulting in a mystery actual color temperature, rather than remapping it.
https://www.home-assistant.io/integrations/light.template/
Y=mx + b
Just realized this won't work, it has to return true if last_triggered is none. Otherwise it will never trigger
Yes, something like that will work
Also, the light template seems to have a way to set what the value is read as, but not what it's written as.
There's also this, but is this saying that you need to make not only a template, but also an input_number entity, to use the template?
https://www.home-assistant.io/integrations/light.template/
set_temperature:
service: input_number.set_value
data:
value: "{{ color_temp }}"
entity_id: input_number.temperature_input
The input number is optional, it's just showing that you can do anything you want when something calls the set_temperature service on the template light
So if adaptive lighting calls set_temperature on your template light, you can turn around and then call set temperature on your real light, but you can use some transform function to send a different temperature.
The wiki could really use a more useful remapping (say, brightness or color temperature) example. That huge example just gives errors when I paste it in the dev tool, even if I chop out a bunch.
ValueError: Template error: int got invalid input 'on' when rendering template 'ceiling_light_adj:
friendly_name: "Ceiling Light"
temperature_template: "{{states('light.ceiling_light_1', 'color_temperature') | int}}"
set_temperature:
service: input_number.set_value
data:
value: "{{ color_temp }}"' but no default was specified
"Umm, what?" is all I can get out of that.
{{states('light.ceiling_light_1', 'color_temperature') | int}} <- this isn't a valid template
should be state_attr(), not states()
also, ctrl-space or whatever gives no suggestions in the template tool.
state_attr('light.ceiling_light_1', what do I do here?)
Maybe I should file a bug about having a built-in feature to fix up lights that lie. I have three different Zigbee light things that all have the same problem, from two brands.
provide the attribute
And one of them isn't even a strip controller where it makes sense for them not to know what LEDs you connect to it.
Okay, what attribute? I don't know what the attribute is called.
That was just a wild guess.
alright
If I look at the light in HA, the only attributes it shows are "off with transition" and "off brightness". And a color and-or color temperature picker, but that's not an attribute.
@fluid radish I converted your message into a file since it's above 15 lines :+1:
Huh, if I use the attribute name color_temp instead of color_temperature, the error changes: UndefinedError: 'color_temp' is undefined
are you looking in
-> States?
@fluid radish I converted your message into a file since it's above 15 lines :+1:
Thanks, I thought that data used to be directly on the light's details.
This seems to work for reading the scale:
temperature_template: "{{(370-153)/(500-15) * (state_attr('light.ceiling_light_1', 'color_temp') | int - 500) + 370 }}"
Is there a way to generalize and reuse a template for more than one light without copying and pasting a bunch?
Or maybe there's a way to make a ZHA quirk instead to avoid having to template it.
you can make a macro, but the code to import and use it would probably be just as wordy as copying and pasting
If I want to use "the requested color temperature" as the input for this, how would I do it?
set_temperature:
service: input_number.set_value
data:
value: "{{ color_temp }}"
entity_id: input_number.temperature_input
I see, the template debug tool can't handle template light format.
It would be helpful for the wiki to have an example that just straight passes through every attribute, rather than confusingly doing stuff with random scripts and named entities.
I think I'm getting it, though.
Do you have to specify to pass through things like brightness, if you're directly calling another light.turn_on from the turn_on section?
ValueError: Template error: int got invalid input 'None' when rendering template '{{(370-153)/(500-153) * (state_attr('light.ceiling_light_1', 'color_temp') | int - 500) + 370 }}' but no default was specified
it sounds like you tried to get the color temperature of a light that's off
and didn't provide a default
What would even be reasonable as a default?
And actually, the base light is currently on.
@fluid radish I converted your message into a file since it's above 15 lines :+1:
That's a few revisions later, still trying to get it working.
Template variable warning: 'transition' is undefined when rendering '{{ transition }}'```
I got toggling and color temperature to work, but not yet the level.
is there a way to copy all the attributes from an entity to the templated entity? I'm changing the state to add an invisible whitespace so the trailing 0 doesn't get eaten in the UI
#general-archived message
Thanks @soft breach
Yes these sensors from HA app i know. I have assigned assignable names to my sensors. Additionally I have device_tracker over ping
I have only one AP on every etage. For me, it would be more important to know if everyone in the household is home.
And the AP can change then yes, so no special AP
I have tried this with the ping variant. But when the users are asleep in flight mode, the presence is no longer guaranteed
brightness and transition are not available in the turn_on action section.
Typically, you have to store brightness and transition in a helper entity and use those values.
or you omit them from that service
@fallen linden I converted your message into a file since it's above 15 lines :+1:
@fallen linden you have to share your full xml, otherwise we can't help. Both of those examples appear to only show a section of the XML.
how do I upload it as a file? It says the length is too long
i put it up at Pastebin in the link above
value_json.status.outlets.outlet[0].state
if AOF is off and AON is on...
value_json.status.outlets.outlet[0].state == 'AON'
That will give me either AON or AOF how do i change that into a booleon value
So if i read the whole XML into HA with
sensor:
- platform: http
name: Raw XML Data
resource: http://10.11.1.195/cgi-bin/status.xml
method: GET
content_type: 'text/xml'
value_template: '{{ value }}'
how do create a sensor that will read value_json.status.outlets.outlet[0].state and give me a True or False or 0 or 1 or on or off or what ever?
exactly what I just wrote
I am sorry i am not understanding...
your value template... just copy/paste what I wrote
i thought value_json.status.outlets.outlet[0].state will just give me AON or AOF... not a booleon value
this
it's that simple
so in my yaml i just put
platform: http
name: Raw XML Data
resource: http://10.11.1.195/cgi-bin/status.xml
method: GET
content_type: 'text/xml'
value_template: '{{ value }}'
value_json.status.outlets.outlet[0].state == 'AON'
no... dude, where did you put your template before?
in your working sensor
hint, check pin 1 2
i dont have a template for this... i dont know how to make the template
i was thinking something like this but it does not work...
platform: template
sensors:
aquarium_freshwater_mid:
friendly_name: "Aquarium Freshwater Mid"
value_template: >-
{% set ns = {'ns': 'http://www.w3.org/2005/Atom'} %}
{% set xml = state_attr('sensor.raw_xml_data', 'value')|parse_xml %}
{% set value = xml.xpath('//ns:status/ns:outlets/ns:outlet[66]/ns:state/text()', namespaces=ns) %}
{% if value[0] == 'AON' %}
on
{% else %}
off
{% endif %}s
Ok, so you're saying this template did you didn't create?
So, if that works and is correct
and I told you your new template is value_json.status.outlets.outlet[0].state == 'AON', where do you think it should go in your new sensor?
it does not work
did you try the template I wrote, are you grabbing the correct outlet?
the template I wrote looks at outlet 1
you have liek 40 outlets there
the 0 in the template means outlet 1
so, you have to count to what outlet you want and put the number there
well, the number minus 1
so outlet 40 would be 39
SO something like
- platform: rest
name: Aquarium Temperature Test
resource: http://10.11.1.195/cgi-bin/status.xml
value_template: "{{ value_json.status.outlets.outlet[66].state }}"
force_update: true
This would give me AOF or AON?
oh ok... so that just changes it to Bool??? i did not know that... i thought i would have to do a if statement or somthing
let me try it
that's a normal if statement
or test
{% if (statement) %}
do something
{% else %}
do other
{% endif %}
statement just needs to resolve true/false, so in this case we don't need the if
because x == y will return true or false
same with x > y or x < y or x != y etc
would it be safe to replace {{expand('group.lights_outside_total_device_power') |selectattr('state','is_number') |map(attribute='state') |map('float')|sum}} with {{expand('group.lights_outside_total_device_power') |map(attribute='state') |select('is_number') |map('float')|sum}} consider both output and efficiency?
changing the order of selects
I don't think it matters
thx. my eyes have a preference for the shorter version, but I wasnt sure if selecting the numbers 1 step later would impact the evaluation
they are generators so it's almost the same
if not exactly the same
the resulting output is only provided if the information is chosen
for each generator
it's a hard concept to grasp but, if something is being filtered out, the order really doesn't matter because it's not resolving that item during the process and the number of loops is still the same
with things like sort and unique, it will matter because they return lists, not generators
yes, I think I can understand that... very clear explanation btw thx
the only thing in your template that outputs a list is expand
have another one, triggered by TheFes's changing his version template with some new possibilities in the version template. - unique_id: ha_dev_update_available_not_skipped state: > {{states('binary_sensor.ha_dev_update_available') == 'on' and 'dev' in state_attr('update.home_assistant_core_update','latest_version') and state_attr('update.home_assistant_core_update','latest_version') != state_attr('update.home_assistant_core_update','skipped_version')}} seems a bit complex with those different integrations (supervisor en Version), but I can find a way to use only those update entities
idea: ignore a dev update and still be notified for the next update
Sorry, I haven't dove into understanding how the version function works
no worries, this works, maybe if Martijn returns he can have a look
This shows the contents of the version object https://github.com/ludeeus/awesomeversion
While sharing the link I now understand why ludeeus is promoting it ๐
but is it really awesome????
because he's a poet...
Maybe I'll deploy awesome version on my production lines here for version control
it's on pypi
thats external to HA? or used in the version integration? trying to find a way to check the Version services and its entities, and link that to update entities (whishing those 2 were integrated somehow)
Yes, it's external to HA
but it's built into HA
i.e. any application can use it if they choose
btw there's a very confusing ux on that because clicking any of those 4 services brings on to a huge overview, and the selected service. which was the reason for my template in the first place
anyways, this is not for #templates-archived, sorry. Just the related cause
Hello, how can I create a sensor which will show me the minand max outdoor temperature of the day from 0-24?
So exactly for one day of the week
use history stats or the statistics integration, not templates
But of course, that would be even better. Do you have an example for me from which I can learn?
I'm having some issues with a restful sensor - it worked a dream before but seems to have stopped pulling data. Is this thread the best place to post it?
Doesn't seem related to a template
Check the logs, probably post in #integrations-archived
well, if the data shape changed, it would be a template change
I had a few rest endpoints do that on me
pissed me off to say the least
where would I find these logs?
settings sytem logs
ah yeah ok, nothing in there that indicates they're not working
they show a value, but it's a few days old
tried restarting, but the values don't seem to refresh and i've looked at the page it's pulling data from and all still seems to be there
go directly to the endpoint and see if the data is the same
no, the data is different
- platform: rest
name: "Vanguard: US Equity"
resource: https://www.vanguardinvestor.co.uk/api/funds/vanguard-us-equity-index-fund-gbp-acc
value_template: >-
{{ value_json.navPrice.value }}
then verify that your endpoint is correct in your configuration. Also, something like that would have an error associated with it
hmmm ok, i'll keep looking then, no errors in the logs
Your template still works based on that endpoint, so it's not the template
Thanks. I have already been to this page. I just wonder how I can capture the day period. Because this value, shows me yes always 24 hours back and not a day of the week?
max_age:
hours: 24
You can't with that integration, you can with the SQL integration, but you'll need to come up with the query.
There is no other option?
no
Weird, then why does the wiki say this?
Defines an action to run when the light is turned on. May receive variables brightness and/or transition.
because it may recieve them
that doesn't mean it exists at all times
if you call a light.turn_on service without defining those, ti does not have them
You can track the daily max or min using trigger-based template sensors https://gist.github.com/Didgeridrew/6627b5f88f5ed8f9a380fb245d5fe67a, but this won't give you access to previous values like a SQL sensor would.
Oh thanks thats a fine idea
I will test it - I will let you know the next few days
Is Minimum value only this
{{ [source, current] | min }}
@inner mesa Would this look like a start? ```
- platform: template
sensors:
fade_duration_left:
friendly_name: Fade Duration Left
value_template: "{{ now() - states('input_datetime.fade_start') }}"```
To format your text as code, enter three backticks on the first line, press Shift+Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks.
```yaml
example: here
```
Don't forget you can edit your post rather than repeatedly posting the same thing.
didn't I? I always do, will fix
I'm not Rob, but some comments
- all states are strings, you need to convert it to a datetime
- that datetime needs to be timezone aware, so use
as_localon it - the result will be a timedelta, I would suggest to convert it to seconds and use
state_class: durationin combination withunit_of_measurement: s
Oh. there's even a class for it! Thanks for the suggestions, will try to update accordingly
I'm not Rob
Few are ๐
Ok, so broke it down to this; {% set duration = (now()|as_local) - (states('input_datetime.fade_transition_time_start')|as_datetime|as_local) %} {{ duration.seconds }}
it counts up though... ๐
yah, no that won't work
you need to know the duration before the calc
so if you set the duration to 600 seconds, it would be....
Oh gosh, I'm sorry. I wrongly tagged RobC before...
Ah, I'll give it back to Petro, as he seems to know the background
{% set duration = 600 %}
{% set calc = now() - states('input_datetime.fade_transition_time_start')|as_datetime|as_local %}
{{ (duration - calc.total_seconds()) / duration * 100 }}
Ty though! ๐
@marble jackal <#automations-archived message>
Ah, a completion percentage so it seems
that is correct
Ah, I actually scrolled back, but the question was in another channel ๐
True... It evolved into a template more than anything...
This surely counts down, thanks! I will play a bit with it and see if I can manage to make stop at 0 and other tricks... ๐
what would the difference be between .total_seconds() and .seconds? Its the latter rounding? Answer was: Yes. ๐
Total seconds gives you the total seconds. Seconds only give you the seconds for under 24 hours
And (less important) seconds gives an integer, total_seconds() a floating point number
Thanks! Yes, I noticed they were in fact int and float at least... ๐ Thanks for the help for now, will continue on this later!
I have a template sensor that I have created for my washing machine based on the power state. One this i want to do is add a "delay" between state changes. Before going off or standby I would like a certain amount of time to pass. Is there a way to do that?
Here is my code: https://pastebin.com/NWbFsM3y
Convert it to the new format and make it trigger based
Then you can use numeric state triggers and hold the state
could you point me to an example? this was my first attempt at a template
There are examples in the docs. In your case I would use 3 numeric state triggers, add a trigger id which represents the intended state and just refer to the trigger id in your template
Well maybe a state trigger for the off trigger
template:
- trigger:
- platform: state
entity_id: sensor.washing_machine_power
to: "0"
for:
minutes: 3
id: "off"
sensor:
- unique_id: sensor_washing_machine_status
name: Washing Machine Status
state: "{{ trigger.id }}"
This is the gist of it, you need to add the other 2 triggers
Thanks I will give this a try
does this look sane ? https://paste.debian.net/1287734/
You'll need a namespace to get previous_tier_limit and total_cost out of the loop.
ok I'll need to read some more then, it works in python so just trying to copy it over best I can
Didgeridrew: did I use it correctly ? https://paste.debian.net/1287738/
shit I made an error in that one, but it's just a rate error
How do you deal with a variable that may or may not exist? If it exists, I want to forward it.
You can use a choose statement to see if the the variable is defined and perform the action (using it) if it is
What would that look like? Currently, it looks like this:
set_level:
service: light.turn_on
target:
entity_id: light.ceiling_light_1
data:
brightness: "{{ brightness | int }}"
transition: "{{ transition | float }}"
You can put a whole script in the set_level key. So everything that automation actions can do (multiple actions) can go under that field.
This is where I landed https://paste.debian.net/1287748/
that's a helluva lot cleaner than my bullish attempt
now that I think about it, it's been about 3 years since I did any templating
did something change in how the template engine treats states that are formated as lists?
for the given state ('update.home_assistant_core_update', '2023.7.3', 'skip')
i used to be able to do {{states.input_text.ha_update_check.state.split('', '')[0]}}
to get the first entry
but now that returns ('update.home_assistant_core_update' so in order to get update.home_assistant_core_update, i have to do {{(states.input_text.ha_update_check.state|regex_replace('\(|\)|\s|\'','')).split(',')[0]}}
Nothing changed there. States have always been strings, and the string ('update.home_assistant_core_update', '2023.7.3', 'skip') will be treated like you describe
The quotes and parenthesis are part of the string
Furthermore, your state is not formatted as a list but as a tuple
I don't know how to write a script, and I don't know everything that automation actions can do.
To add to my comment above, if you would format it as a list (with [ and ]) and use double quotes around the items, you could use from_json to do what you want to do
It may be a convoluted question, so please bare with me.
The UPS integration (NUT) is outpuitting an incorrect parameter for one of the voltage sensors, since it's giving out a multiplier for the actual voltage and not the voltage itself. It's 2.25V when full, even though it should be 2.25 * 36V = 81V
Is there a way to customize the entity to give it the correct output, as opposed to using a template to create another entity with the correct voltage.
No, you can't change the output of the actual sensor. That has to be changed in the integration itself
The unfortunate part of it is that it's not even the integration. It's how the manufacturer did the firmware, so that ain't changing.
Their software probably knows it's a multiplier and not a voltage, while NUT is simply pulling the variable without contesting it.
FYI thatโs an issue with your hardware or nut itself. My unit outputs voltage properly. Id write up an issue against nut itself. ( not the addon or integration)
Having looked at documentation, that is a very common problem with the majority of UPS providers, since many of them are based on the same or very similar controllers and firmware.
I've compared two drivers for the same device and one reports the value as incorrect number of cells with a V and the other driver multiplies this just fine.
So definitely a NUT issue, is what I am saying
Not HA related - though I am still more likely to fix it on HA end with a template, since NUT is a jungle of inefficiency and conflict..
yes it is
Hey,
id like to create a template sensor, that is on if theres any calendar event in the next 48h.
The calendar entity doesnt have any start attributes, they only appear when the event is right now
Some ideas?
You can use the calendar service to get the upcoming events as list and then loop the list in a template to show them.
data:
duration:
hours: 48
minutes: 0
seconds: 0
target:
entity_id: calendar.family
https://www.home-assistant.io/integrations/calendar/#service-calendarlist_events
You might need to use an automation to populate count.
That works fine, thx!
Only have to figure out now, how to do the template, but google will have a answer for this, hopefully
@tired sandal I converted your message into a file since it's above 15 lines :+1:
(most likely the variables section) - all I have to go on is: " Error rendering variables: AttributeError: 'NoneType' object has no attribute 'tzinfo' " in the logs
scratch that - looks like my rest sensor is failing to grab the API data
Given an array of dictionaries that I want to filter, is there a reason to use selectattr('serviceImpacted', '==', true) vs selectattr('serviceImpacted', 'eq', true) ?
no, they're identical
from the Jinja docs:
jinja-tests.eq(a, b, /)
Same as a == b.Aliases:
==, equalto
so if I'm trying to make a manual sensor, I just had a thought.... is there a way to make it record which month it's for using a template or would I have to do that from my input helper?
this is basically the template I have to do the rate calculations https://paste.debian.net/1287748/
Hi Al, what am i doing wrong here? sensor.powershop_daily_charge = $1.03 and im trying to create a another sensor that is $1.03 / 1000. Im slowly getting there with the syntax, but i just need a bit of help with this one ๐
- sensor:
- name: "Powershop Supply Charge NZD Wh"
unit_of_measurement: "NZD"
state: >-
{{ states('sensor.powershop_daily_charge') * 1000 | float | round(3) }}
Opps.. sorry: Yes, I need $1.03 * 1000
sensor:
- platform: template
sensors:
powershop_supply_charge_nzd_wh:
friendly_name: "Powershop Supply Charge NZD Wh"
unit_of_measurement: "NZD"
value_template: "{{ (states('sensor.powershop_daily_charge') | float * 1000) | round(3) }}"
should work
Yep - i got to the same place now as well. It does actually work, but i also get this error message: homeassistant.exceptions.TemplateError: ValueError: Template error: float got invalid input 'unavailable' when rendering template '{{ (states('sensor.powershop_daily_charge') | float * 1000) | round(3) }}' but no default was specified
2023-08-04 11:55:12.682 ERROR (MainThread) [homeassistant.helpers.template_entity] TemplateError('ValueError: Template error: float got invalid input 'unavailable' when rendering template '{{ (states('sensor.powershop_daily_charge') | float * 1000) | round(3) }}' but no default was specified') while processing template 'Template<template=({{ (states('sensor.powershop_daily_charge') | float * 1000) | round(3) }}) renders=4>' for attribute '_attr_native_value' in entity 'sensor.powershop_supply_charge_nzd_wh'
You should specify a default for your float filters
And ideally fix your sensors, which are apparently unavailable
Thanks for that - have set the default now. The other sensor is a multiscrape based one, so i think whats happening is that they are unavailable whilst the scrape process is happening, as a second or so later powershop_supply_charge_nzd_wh updates with the correct value.
Hey all. Looking for some help as my google skills have failed. Using the custom button card, trying to set the icon/card color based on the value of a binary sensor state. I read it couldn't be done using normal templating and trying "java" from what the page said. Any advice? I can paste the few lines if needed.
Just seeing some of that, went looking for something else. I'll read that and try and come back if i'm still stuck.
I copied and pasted from the docs the bit of code that applied, replaced with my binary sensor, changed the return values, and the code is accepted but does nothing.
color:
- - - if (binary_sensor.ac = 'on') return "red"; else return "gray";```
sorry, I forgot how to paste code in here. been a bit.
To format your text as code, enter three backticks on the first line, press Shift+Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks.
```yaml
example: here
```
Don't forget you can edit your post rather than repeatedly posting the same thing.
HA reformatted it on me. It's not what I saved into it.
i'll redo it and share before I save this time
that's not the problem
first, I don't see where it says that the "color" supports templates
second, binary_sensor.ac isn't the way to test a state
here's a more complicated example of mine:
- type: custom:button-card
entity: sensor.occupancy
state:
- value: "[[[ return states['automation.away_timer'].state === 'on'; ]]]"
operator: 'template'
name: "[[[ return parseInt(states['input_number.away'].state) + 's'; ]]]"
icon: "mdi:timer"
color: yellow
- value: "[[[ return parseInt(states['input_number.away'].state) === 0; ]]]"
operator: 'template'
name: "Away"
icon: "mdi:home-export-outline"
color: "red"
- operator: 'default'
color: green
name: "Home"
icon: "mdi:home"
tap_action:
action: call-service
service: script.home
the main point is that you should use the "state:" block
I do actually ... That was going to be in the new code I would have pasted after redoing it. Forgot to paste proper the first time.
or you can do it this way:
- type: custom:button-card
entity: sensor.mbath_water_temp
name: Water Temp
icon: mdi:water
show_state: true
show_units: true
template: badge_template_desktop
styles:
icon:
- color: >
[[[
if (states['input_boolean.heat_water'].state === 'on')
return 'red';
else
return 'green';
]]]
tap_action:
action: call-service
service: homeassistant.toggle
Gonna try that now .... Would that work for the card color as well?
that does it! thank you!
what is wrong with this guys:
- name: "ElliottsDoerSensor"
state: >
{{ states('binary_sensor.elliotts_vaerelse_dor_dorsensor_contact') | replace("on", "ร
ben",1) | replace("Unavaliable", "")) | replace("off", "Lukket", 1) }}
What does it return
could use a little help solving a 'problem'.. Partner has bought an Electric car and we are looking for a way to easly collect a running total of how much electric we are using (using the actual cost) so we know how much of the electric bill is their share. We've hooked up a Zigbee plug that can generate a running total but there a few.. oddities with it we need to work around and we anrt sure how to turn that Kw usage count into a pound value for 'electric used'
So the issues are.. A) It already has a running total in it, and we cnat figure out how to reset it, B) every so often it seems to freak out and send (what we think) are its 'lifetime usage' totals as an actual usage amount to Zigbee which confuses the utter heck out of HA. Like reporting a device used 300Khw in a day. I dont know if there is a way to smooth out or.. filter results that would clearly be wrong (say if the previous total is.. 30kwh higher than the last one, thats almost certinally going to be impossibly wrong)
Can someone help me fix this one, not sure what i've done wrong.
data:
volume_level: {{ states('input_number.office_apple_tv_current_volume_level') | float + 0.1 }}
target:
entity_id: media_player.kontor
What's the error?
Error running action: expected float for dictionary value @ data['volume_level']. Got None
No quotes around the template
great thank you!
It dosn't show up at all...after ive put it in config an rebootet
there should be errors in your logs then
โโโ
Logger: homeassistant.config
Source: config.py:864
First occurred: 10:39:36 (2 occurrences)
Last logged: 10:39:36
Invalid config for [template]: invalid template (TemplateSyntaxError: unexpected ')') for dictionary value @ data['sensor'][6]['state']. Got '{{ states('binary_sensor.elliotts_vaerelse_dor_dorsensor_contact') | replace("on", "ร
ben",1) | replace("Unavaliable", "")) | replace("off", "Lukket", 1) }}\n'. (See /config/configuration.yaml, line 51).
Invalid config for [template]: [platform] is an invalid option for [template]. Check: template->platform. (See /config/configuration.yaml, line 85).
โโโ
Yep, your yaml is incorrect
you'll have to post your config that you attempted
- name: "ElliottsDoerSensor"
state: >
{{ states('binary_sensor.elliotts_vaerelse_dor_dorsensor_contact') | replace("on", "ร
ben",1) | replace("Unavaliable", "")) | replace("off", "Lukket", 1) }}
That's fine
where you're placing it and how you're placing is not
meaning you have to post your entire config for it.
No it's not fine
I don't understand?
The is an ) too much in it
yah, just saw that
In the replace for unavailable
but the error is poitning at platform key
which means he's doing something wrong with his yaml
Ohhh ๐คญ
normally syntax errors will result in a "but got none"
What is also wrong ?
The second one seems to be that you are using the legacy format under the template integration
In other words?
error 1
Invalid config for [template]: invalid template (TemplateSyntaxError: unexpected ')') for dictionary value @ data['sensor'][6]['state']. Got '{{ states(\'binary_sensor.elliotts_vaerelse_dor_dorsensor_contact\') | replace("on", "ร
ben",1) | replace("Unavaliable", "")) | replace("off", "Lukket", 1) }}\n'. (See /config/configuration.yaml, line 51).
error 2
Invalid config for [template]: [platform] is an invalid option for [template]. Check: template->platform. (See /config/configuration.yaml, line 85).
mark, can you please just post your configuration
for the love of god
just post it, we will show you the errors
The second error is related to another sensor
Yes, but that will cause the whole template integration to fail to load
Hurry up and wait
Hoping someone can point me in the right direction here... I'm noticing that UI elements are rendering differently on different devices (https://i.imgur.com/dEQrOCR.jpg).
What can I change to help either eliminate or reduce this effect for a more consistent look across devices?
#frontend-archived can help with that.
Hello all,
I am in the process of implementing a small sensor to count my battery devices where the battery level is < X%.
The coding works in principle, but I would be interested if there is a cleaner or more elegant way to implement this?
- name: count_battery_low
unique_id: count_battery_low
state: >
{% set devices = [
states.sensor.shortcut_button_office_battery,
states.sensor.shortcut_button_living_room_battery,
] %}
{{ devices | selectattr('state', '<', '51') | list | count }}
well, your code doesn't actually work. It just appears to work
๐
any battery devices in the single digits between 6 and 9 will not show up in that template
oh and devices with 100% battery will show up as low too
{% set ns = namespace(items=[]) %}
{% for device in [
states.sensor.shortcut_button_office_battery,
states.sensor.shortcut_button_living_room_battery,
] if device.state | is_number %}
{% if device.state | float < 51 %}
{% set ns.items = ns.items + [ device ] %}
{% endif %}
{% endfor %}
{{ ns.items | count }}
okay, i thougt it was not so bad
I would say.. many things to learn ๐
Thx petro - i will look into your code and try to understand it
Couldnt find out how to do this exactly. Some ideas?
I need a sensor thats on when theres a calendar event in the next 48hrs
The calendar entity should have a start_time attribute, you can use that for you template
Example:
message: Sinterklaasavond
all_day: true
start_time: '2023-12-05 00:00:00'
end_time: '2023-12-06 00:00:00'
It only has the start time when the event is right noe, before it doenst have start or end time
Well, as you can see my event is 4 months from now, and I have a start time attribute
Did you check in developer tools > states
Yep i did, this is the output:
offset_reached: false
friendly_name: Familie
@marble jackal if i call the service, i get 2 events on august 15th and 16th, but in dev tools the calendar has only these 2 attributes above
If i do the samr with a local calendar, i get start_time and the rest. But not with the icloud calendar. The attributes just show up if the event is right now
Okay, if the response of the service call does include them, then use that
Yes thats it what i meant, i dont know how to do this :/
But still thanks for your response, ill find a way somehow
Well, I guess best might be to create an automation on a time pattern trigger, maybe once per hour
Then issue the service call and use the response to add the first start time to an input datetime
I would need to test that myself, and I'm on mobile so I can't do that now
i think it would be enough if i count the given events and if theres just > 0 then turn a input bool on
but the count is the problem for me
thanks for your time!
I need help for some replacement thingy... I want to display a name and method of unlocking... but if a user with id 11 in the lock locks in i takes the text from user 1, twice..
- name: "HoveddoerAabnet"
state: >
{{ states('sensor.hoveddor_last_unlock_user')
| replace("Unavaliable", "")
| replace('1', 'Mark - Pinkode')
| replace('0', 'Maria - Fingeraftryk')
| replace('11', 'Thea - Fingeraftryk')
}}
So if user 11 locks in the sensor value is Mark - PinkodeMark - Pinkode - but should be Thea - Fingeraftryk
{% set mapping = { '1': 'Mark', '0': 'Maria', '11': 'Thea' } %}
{{ mapping[states('sensor.your_sensor')] | default() }}
That's what I would do, you could also first do the replace for 11 before you do the replace for 1
Since there might be other things colliding, im gonna try yours ๐
Hi all ๐ Any1 know how to solve this?:
This one works.
{{ is_state_attr('input_datetime.maste_ut_kl', 'hour', 2 ) }}
But i want to show false/true of hour is above 8 or not. But i only get syntax error ๐
{{ is_state_attr('input_datetime.maste_ut_kl', 'hour', > 8 ) }}
Yay! thank you Rob!
Does anyone know if there is a way to include the word and during a joining of strings? Ie if it is two strings being joined it would just say 'word1 AND word2' but it its more than 2 being joined it would be 'word1, word2 AND word3'
trying to incorporate some natural language into a tts action
{{ your_strings[:-1] | join(', ') ~ ' and ' ~ your_strings[-1] if your_strings | count > 2 else your_strings | join(' and ') }}
Hi,
i want to create a template sensor that counts the events given by the following service, does somebody know how to do this?
data:
duration:
hours: 48
minutes: 0
seconds: 0
target:
entity_id: calendar.familie ```
Try {{ response.events | count > 0 }}
@wanton girder I converted your message into a file since it's above 15 lines :+1:
The id remains the same wether it is fingerprint or pincode
But how do i put this all into a template sensor?
You can't directly, because you need to issue the service call. That's why I proposed an automation on a time pattern
You can toggle an input boolean based on the template result
Or send an event in the automation and use that in a trigger based template sensor
Okay, so call the service in a automation and then a template with {{ respone.events | count > 0 }}
but how do i toggle the bool on that result?
Sorry, im just not that into templating
I get this:
Error: Script requires 'response_variable' for response data for service call calendar.list_events
@wanton girder I converted your message into a file since it's above 15 lines :+1:
have this binary: {{is_state('person.me','home') or is_state('person.she','home')}} . figured id rewrite that to {{'person.me' or 'person.she' in state_attr('zone.home','persons')}} which has some unexpectd result.... it lists who is in that attribute, instead of true/false.
if I use only one, {{'person.me' in state_attr('zone.home','persons')}} it does true/false..
@marble jackal could you please help me doing this? Im cant get behind how to do this
Thanks mate!
Something like this
action:
- service: calendar.list_events
data:
duration:
hours: 48
target:
entity_id: calendar.m_m
response_variable: response
- if: "{{ response.events | count > 0 }}"
then:
- service: input_boolean.turn_on
target:
entity_id: input_boolean.test
else:
- service: input_boolean.turn_off
target:
entity_id: input_boolean.test
That actually works perfectly, thank you vers much!
Ill try to get behind the code and help myself the next time
the โreapone_variable: responseโ was the thing i didnt had, now its working
a yes, silly me. thx.