#templates-archived
1 messages Β· Page 34 of 1
That's why I left it in π
yes I see tht now.... why is it identical in the top 3 without, and required in the bottom 3 though?
your other fix made a huge difference already:
too bad it doesn't yet move the recent event, in this case spring to the next time . maybe there's another fix possible for that. But, as that might involve the hour: the calculated hour is off . in NL, the time change happens as 02:00 AM. where the template says 3 +1..
I understood that this is an old way of creating a sensor, right?
- platform: template
sensors:
ventilation_level:
friendly_name: "Ventilation Current Setting"
value_template: >-
{% if states('sensor.shellyplug_s_3ce90ed7cdb6_power')| int(5) <= 6 %}
low
{% elif states('sensor.shellyplug_s_3ce90ed7cdb6_power')| int <= 20 %}
medium
{% else %}
high
{% endif %}
What do I replace the value_template part with in the new formatting?
new syntax I mean
{{as_timestamp([ns.spring,ns.fall]|min)|timestamp_custom('%A %-d %B %Y at %-H am')}}``` returns 'Sunday 26 March 2023 at 4 am'
Is it just "state: " and then my code?
yes, its state, but the whole template needs another syntax and place
Yeah, I got the rest. Like this right?
- name: "Ventilation Current Level"
unique_id: ventilation_level
state: >-
{% if states('sensor.shellyplug_s_3ce90ed7cdb6_power')| int(5) <= 8 %}
low
{% elif states('sensor.shellyplug_s_3ce90ed7cdb6_power')| int <= 26 %}
medium
{% else %}
high
{% endif %}
it should now go under the top level template: and then follow:https://www.home-assistant.io/integrations/template/#state-based-template-binary-sensors-buttons-numbers-selects-and-sensors
nested under sensor:
nope
template:
- sensor:
- name: Ventilation Current Level
unique_id: ventilation_level
state: >-
{% if states('sensor.shellyplug_s_3ce90ed7cdb6_power')| int(5) <= 8 %}
low
{% elif states('sensor.shellyplug_s_3ce90ed7cdb6_power')| int <= 26 %}
medium
{% else %}
high
{% endif %}```
yeah that's what I have π
I have a templates.yaml that already does the template: part
o well, in that case you're good π thought you said 'nested under sensor:' and meant toplevel sensor: there
Nah, nested under sensor (which is also nested already) haha Thanks for the help
you do have some strange |int'in there, on purpose?
otherwise do: state: > {% set power = states('sensor.shellyplug_s_3ce90ed7cdb6_power')| int(0) %} {% if power <= 8 %} low {% elif power <= 26 %} medium {% else %} high {% endif %}
Ahh that looks more efficient indeed, thanks!
I would add an availability and check for a numeric state of the source sensor there
Then you don't need the defaults for the int filter, and you won't get an incorrect low result
Another condition to do that, first checking for availability, or how would you go about it?
template:
- sensor:
- name: Ventilation Current Level
unique_id: ventilation_level
state: >-
{{ }}
availability: >-
{{ states('sensor.shellyplug_s_3ce90ed7cdb6_power') | is_number }}
Ah, and if it's not available it will just return "unavailable" ?
Yep
Cool, thanks
i believe i need some help with a template. i have an automation i fire before bed to slowly transition my lights off in my room. however when i wake up and turn my lights on they're still at that same super low brightness level. Is this something I should solve with templating?
#automations-archived message more information here if that helps
What's the difference between using >, | or >- ?
btw TheFes, if I change to {%- for i in range(400) %} in the template, the next event Spring is calculated correctly. Maybe some if/else can be set there? ({%- for i in range(372) %} is the minimum amount of days still setting 'next' spring correctly and calculates next fall as it were. Maybe I can simply leave it like that.
why is this not working
template:
- sensor:
- name: "Daily GoodWe Power"
unique_id: "daily_test"
state: >
{% if state_attr('sensor.pv_power')|float > 0 %}
{{ state_attr('sensor.pv_power') }}
{% else %}
0
{% endif %}
You aren't providing an attribute in either state_attr call
Seems like you're using state_attr() when you wanted states()
What are you using this for? I'm still struggling with tweaking my templates because of DST, but I'm not sure having an entity mentioning it would help me, haha
ty for directing me in the right direction i found it
Would is_number be the right check for this template? Maybe I should just if it exists instead?
{% set ns = namespace(times=[]) -%}
{%- set today = state_attr('sensor.energyprices','raw_today') -%}
{%- for hours in today if hours.values | is_number -%}
{%- set ns.times = ns.times + [as_local((hours.start)).strftime("%Y-%m-%d %H:%M:%S")] -%}
{%- endfor -%}
{%- set tomorrow = state_attr('sensor.energyprices','raw_today') -%}
{%- for hours in tomorrow if hours.values | is_number -%}
{%- set ns.times = ns.times + [as_local((hours.start)).strftime("%Y-%m-%d %H:%M:%S")] -%}
{%- endfor -%}
{{ ns.times }}
This is what the raw_today attributes look like:
- start: '2023-03-26T00:00:00+01:00'
end: '2023-03-26T01:00:00+01:00'
value: 0.11443 - start: '2023-03-26T01:00:00+01:00'
end: '2023-03-26T03:00:00+02:00'
value: 0.0968
In your previous post you posted that is was null
So in that case it was defined
Here: <#templates-archived message>
Hmm yeah, Something changed...
Hi folks - new to automations and templates and trying to figure out how to determine a different entity on the same device while handling a state change. For example, if I want to change the color of a thread bulb when it becomes a router - the event arrives on sensor.name_of_bulb_thread_status but I want to call a service on light.name_of_bulb. I can do it with some really ugly regex_replace string mangling - but I feel like there must be a more elegant way.
Plus if I could figure this out, I could generalize some of what I'm trying to do to an event trigger rather than a state trigger and not have to specify the entity_id for each thing I'm automating.
But from what I understand trigger variables only support limited templates.
But I am not proud of this
variables:
thisEntity: >-
{{
trigger.entity_id|
regex_replace(
find='sensor',replace='light',ignorecase=False) |
regex_replace(
find='_thread_status',replace='',ignorecase=False)
}}
And it's dependent on correctly and consistently naming entities.
Oooh - looks like the answer I want lies in device_id() and device_entities()
I was just typing that
Is there a hint on the best way to filter that list of entities to the one I want?
I just figured out I can get: ```
thisEntity: light.dining_room_chandelier_1_thread_status
thisDevice: 2b57d18174983d57fd19dddd5f0236ed
theseEntities:
- button.dining_room_chandelier_1_identify
- button.dining_room_chandelier_1_provision_preferred_thread_credentials
- sensor.dining_room_chandelier_1_thread_capabilities
- sensor.dining_room_chandelier_1_thread_status
- light.dining_room_chandelier_1
I feel like: ```
{{theseEntities|select('contains','light')}}
should work...
Or something
But I couldn't really find a list of select operators on the Jinja site - the only example with strings is 'equals'
And alas: <generator object select_or_reject at 0x7f4d5631b0>
How could I select the rooms timestamp_sensor value from these variables if the room binary_sensor is on?
variables:
rooms:
- name: kitchen
binary_sensor: binary_sensor.kitchen_cleaning
timestamp_sensor: input_datetime.kitchen_last_cleaned
- name: living_room
binary_sensor: binary_sensor.living_room_cleaning
timestamp_sensor: input_datetime.living_room_last_cleaned
on_rooms: '{{ rooms | map(attribute="binary_sensor")| select("is_state", "on") | list }}'
add |list
they're called "tests"
I expect that can overwrite the actual next change with the change of next year
{{ ["foo", "bar"]|select('contains', 'foo')|list }}
->
[
"foo"
]
Okay - is there a "safe" way to just assign that to a trigger variable I can use as an entity_id? I can't really test that part in the template playground.
Since it's a vector and not a string...
again, "tests"
more HA-specific tests are mentioned here: https://www.home-assistant.io/docs/configuration/templating/
I couldn't find a reference to 'contains' anywhere on that page - but it works.
Ooooh - I found it on the HA one - not the Jinja one... I see.
Thanks for your help - this is exactly what I needed.
The logbook says "x lights turned on" triggered by x automation. But I can't find any event/way to consume that in an automation. I can get whether a user called a service light.turn_on or off but there's no way to get that an automation triggered and turned a light on. Unless there is?
Ended up with a much cleaner: thisLight: >- {{ device_entities(device_id( trigger.entity_id)) | select('contains','light.') | first }}
Should't that be in to_state.context.parent_id ?
In a state_changed event...
How would I find the parent?
01GWEZQT2H3DXHGGVTFEC9YPHE
What does that tell me? Lol how do I find what that correlates to
If the parent_id is null then it's the first in the chain. Otherwise it was triggered by the parent.
I get that but how do I tie the parent to x automation? I see some people just simply checking if it's not null and user id is then it's an automation but I would want to know the specific automation.
What event are you handling? Because the automation running will trigger a state_changed on the automation itself: event_type: state_changed data: entity_id: automation.state_tester old_state: entity_id: automation.state_tester state: "on" attributes: last_triggered: "2023-03-26T18:21:03.838682+00:00" mode: single current: 0 id: "1679846836130" friendly_name: State Tester last_changed: "2023-03-26T18:14:16.990923+00:00" ...
I see. So I would just track state changed for a light let's say and also track state changed for automations or the automation itself. If the parent id matches them I know it's x automation?
You can test this in the developer->events tool. Just start listening to state_changed and then trigger it with the automation - and again without.
You will see all of the events.
Plus the order they arrived.
But be quick with the "stop listening" button. π
So depending on what you are trying to accomplish - you can trigger on state_changed and then use a condition to test that the entity is the automation you want? Not exactly sure what you are trying to do - but that would definitely work.
Yeah I'm trying to see if a specific automation turned lights on or did another do it.
How do I convert a timestamp (in numbers, like this: 1679864400) to a timestamp that HA can read?
I see how to tie them now. I tested it. checking state changed context id and the automation triggered context id.
I'm assuming it's not the right format because my automation can't set a datetime helper: Invalid datetime specified: 1679864400.0 for dictionary value @ data['datetime']. Got None
Ah found it! | as_datetime()
@floral shuttle different approach for the next changes:
{%- set n = now() %}
{%- set m = today_at().astimezone(utcnow().tzinfo) %}
{%- set t = n.hour - utcnow().hour + (0 if n.timetuple().tm_isdst else 1) %}
{%- set ns = namespace(spring='', autumn='') %}
{%- for i in range(1,750) %}
{%- set d1, d2 = n + timedelta(days=i-1), n + timedelta(days=i) %}
{%- set d1dst, d2dst = d1.timetuple().tm_isdst, d2.timetuple().tm_isdst %}
{%- if ns.spring and ns.autumn %}
{%- break %}
{%- else %}
{%- if d1dst > d2dst %}
{%- set ns.autumn = as_local(m + timedelta(days=i, hours=t)).isoformat() %}
{%- elif d1dst < d2dst %}
{%- set ns.spring = as_local(m + timedelta(days=i, hours=t)).isoformat() %}
{%- endif %}
{%- endif %}
{%- endfor %}
However, this relies on the loop break function which will be introduced in the next release
it stops the loop when both datetimes are found
Is there a way to get a list of all entity ids in a domain?
I would imagine something like domain_entities('sensor')
The OpenAI integration uses areas in a loop but as far as I can tell that isn't a built in function ? Am I wrong?
{%- for area in areas %}
{%- endfor %}
{{ states.sensor | map(attribute='entity_id') | list }}
don't trust any AI generated code
Okay, so shooting for the stars here - getting a list of the entity_ids of all the sensors that equal a specific state?
{{ states.sensor | selectattr('state', 'eq', 'your specific state') | map(attribute='entity_id') | list }}
'Click'
Hello !
I have this graph how can I get the temperature (it is a heating management module it does not provide a sensor to put it in a graph)
how could you list entities by domain for all domains
{% set pattern = '(\w+)\.(\w+)' %}
{{ states | map("regex_findall_index", pattern, 0) | map("first") | unique | list }}
is the best i have
cool! let me save that for next week... will see if I can find a way to incorporate the idea in the current template too. seems doable to compare the now() with the change time and iterate to the next... hmm
nice! always have to look up that regex syntax, to does not stick in my brains. using a tiny python script myself
btw, you dont list entities, only the used domains?
Okay, putting all this together - here's what I'm trying to do... The templates work in the playground - but the script engine hates something about this:
alias: ID Routers
sequence:
- variables:
routers: >-
{{ states.sensor | selectattr('state', 'eq', 'router') | map(attribute='entity_id') | list }}
- repeat:
for_each: routers
sequence:
- variables:
buttonID: >-
{{ device_entities(device_id(repeat.item.entity_id))|select('contains','identify')|first }}
- service: button.press
target: "{{ buttonID }}"
data: {}
mode: single
icon: mdi:router```
Message malformed: expected a dictionary for dictionary value @ data['sequence'][0]['variables']
oddly enough<, I now notice that the original template is borked too.... {%- set ns = namespace(previous=3,spring=none,fall=none) %} {%- set today = today_at().astimezone().replace(hour=ns.previous) %} {%- for i in range(365) %} {%- set day = (today + timedelta(days=i)).astimezone() %} {%- if ns.previous - day.hour == -1 %} {%- set ns.spring = today + timedelta(days=i) %} {%- elif ns.previous - day.hour == 1 %} {%- set ns.fall = today + timedelta(days=i) %} {%- endif %} {%- set ns.previous = day.hour %} {%- endfor %} {{([ns.spring,ns.fall]|min).isoformat()}} won't show because it canβt calculate ns.spring, hence causing a NoneType and erroring the |min. Now how this is possible? Never noticed that before
Your indentation is off for variables in both spots. Indent router and buttonID
Hey guys, I have a template sensor thatβs build on a sensor value, letβs call it sensor.important, My question is this, when my internet goes down, the sensor.important gets unavailable and my template sensor doesnβt have any value. Is it possible, to make the template sensor stay at the last known value, if sensor.important gets unavailable?
Yes it is.```
state: "{{ this.state if states('sensor.important') in ['unkown', 'unavailable'] else states('sensor.important') }}"
It can be simplified to this if the sensor is a numeric value normally:```
state: "{{ states('sensor.important') if states('sensor.important')|is_number else this.state }}"
Van Gogh's is there a way to render this correctly with jinja? It being sent to HA like this.
That's because the next ns.spring is on the 31st of March next year, which isn't within 365 days
And with that template you will also have an issue next year, as you will have two changes to dst in one 365 day period, which will cause the next change to be overwritten with that one of the next year
That's why I used the loop break
yes, as said, first thing when the beta arrives.... all in all it seems silly we have no straightforward way of looking up the next dst change date, and checking https://www.kalender-365.nl/zomertijd_en_wintertijd.html is so much easier π Was wondering though, other than checking for ==1 or ==-1, wouldn't there be an easier strategy to look for change in tm_isdst ?
you can do something similar now as well, just check if ns.springis already changed, and if that's the case, don't change it anymore
with your code:
{%- set ns = namespace(previous=3,spring=none,fall=none) %}
{%- set today = today_at().astimezone().replace(hour=ns.previous) %}
{%- for i in range(500) %}
{%- set day = (today + timedelta(days=i)).astimezone() %}
{%- if ns.previous - day.hour == -1 %}
{%- set ns.spring = today + timedelta(days=i) if ns.spring is none else ns.spring %}
{%- elif ns.previous - day.hour == 1 %}
{%- set ns.fall = today + timedelta(days=i) if ns.fall is none else ns.fall %}
{%- endif %}
{%- set ns.previous = day.hour %}
{%- endfor %}
{{([ns.spring,ns.fall]|min).isoformat()}}
uhm, let me phrase humanely: loop to find the first 3 tm_isdst changes, and list the first 2
yes, that works, also for the {%- set next = [ns.spring, ns.fall] | reject('<', now()) | min %} {%- set phrase = 'verliezen een uur' if next == ns.spring else 'krijgen een uur extra' %} {%- set clock = 'vooruit' if next == ns.spring else 'terug' %} {"spring": "{{ns.spring.isoformat()}}", "fall": "{{ns.fall.isoformat()}}", "event": "{{next.isoformat()}}", "days_to_event":{{(next-today).days}}, "phrase": "{{phrase}}", "clock":"{{clock}}"} attributes
any reason for the 500 days? I mean 372 works too
just took something large enough π
seems we never have to go beyond + 1 week
373 then? 366 + 7
yeah that is what I changed to yesterday....
so that template wont overwrite the next when there are 2 inside the that range? as in, it should pick the 'first' next..
indeed, because when ns.fall or ns.spring are already entered (so they are not none anymore) it will use the current value
{%- set ns.spring = today + timedelta(days=i) if ns.spring is none else ns.spring %}
great, I'll move to that for now then. thnks!
will update the post in the community with that
the thing the break would add is that you can actually stop the for loop when both are found
so you won't have to iterate over the remaining part of the range.
I see, yes, that could probably be a bit more efficient in that case. though, it doesnt update constantly, so maybe not a real huge issue. It's a nice refinement though
Omt: given the fact I need ```
{%- set ns = namespace(previous=3,spring=none,fall=none) %}
{%- set today = today_at().astimezone().replace(hour=ns.previous) %}
{%- for i in range(500) %}
{%- set day = (today + timedelta(days=i)).astimezone() %}
{%- if ns.previous - day.hour == -1 %}
{%- set ns.spring = today + timedelta(days=i) if ns.spring is none else ns.spring %}
{%- elif ns.previous - day.hour == 1 %}
{%- set ns.fall = today + timedelta(days=i) if ns.fall is none else ns.fall %}
{%- endif %}
{%- set ns.previous = day.hour %}
{%- endfor %}
yet another way to find Dst change date: last Sunday in March/October. might be easier? https://www.rijksoverheid.nl/onderwerpen/zomertijd-wintertijd/vraag-en-antwoord/klok-verzetten-nederland would save a lot of iterations in the loop...?
Your current approach is more generic and would also work for other countries, but if you know when it is, you can of course also use that
it is like that in all of the EU....https://eur-lex.europa.eu/legal-content/nl/TXT/?uri=CELEX%3A32000L0084 and has been for the last 22 years π
yeah, sure. I still hope it will change to not changing time at all though
+1 to that..
Thank you so much for this, i Will look into it tonight βΊοΈ
is this correct in that new template? (0 if n.timetuple().tm_isdst else 1) is that in fact the same as (0 if n.timetuple().tm_isdst == 1 else 1) ? so in fact a boolean with values 0/1
never realized we could change: mdi:{{(now().timetuple().tm_isdst == 1)|iif('update','history')}} to mdi:{{(now().timetuple().tm_isdst)|iif('update','history')}} ... clever!
0 is falsely so that works π
I did notice that that version is off by an hour, it was correct yesterday..
Any ideas why the automation editor doesn't like the regex_findall_index but the template editor takes it? As soon as I remove that the automation editor turns blue. Put it back and it's red.. I have used this exact regex_findall_index before in automations
entity_id: "number.{{ (sensor.split('_presence')[:1] | join('') if 'presence' in sensor else sensor.split('_illuminance')[:1] | join('')) | regex_findall_index('\.([^\.]+)$') + '_' + item }}"
ah the abominable hour....
Remember that whole bunch of extra crap I did in that template?
the DST template?
that was to account for that bullshit where is_dst just outputs wrong info
The template I've been using (which is very verbose) has been working for years at this point without an issue.
I get notifications 1 week before the event occurs and it's accurate to the second.
Yeah, I should not have tried to reinvent the wheel
I think I went through 3 iterations to get it working essentially
which spanned a year
It broke every DST shift
@half pendant I converted your message into a file since it's above 15 lines :+1:
i just realized my issue. Nevermind π
any thoughts on this?
where are you putting that field entity_id?
In a service call
Will that Nested loop even work?
I tried to set the item to sensor to avoid item confusion on the second loop.
I don't think nested for loops will work
but that nested for loop doesn't make sense
you're iterating over the same list
I'm trying to loop over the list of unavailable sensors. Then for each unavailable sensor do a number set value on the switch_entities.
I'm trying to avoid a large static dict
so just generate the list before hand
To map unavailable sensors to switch entities.
I guess I don't understand why you're iterating twice
you can do it all in 1 iteration if you're matching sensors to switches
but do it ahead of time in a variable
I wasn't sure how to make sure for each sensor it looped 4 times to execute number set value on each switch entity.
How could I do that dynamically?
I've got a universal media player where i need to overwrite the volume_set method with my custom script (that takes an input parameter "volume". How would i do that?
Did you read the link I posted?
in automations?
Yes
yeah. I managed to make the script! Thanks
ok, then what's the problem? Call the script passing your variable
I don't really understand what you're saying here
if you want to create dynamic lists, use namespace
{% set ns = namespace(items=[]) %}
... later in your for loop ...
{% set ns.items = ns.items + [ whatever you're adding to the list ] %}
yeah it was easier than i expected. Nevermind! Working great now ( i think haha)
That's how I would mate unavailable sensors to switch entities? So that when it loops over each unavailable sensor it executes 4 separate service calls? 1 for each switch_entity?
No, just add each service you want to execute to the list
then iterate the list in a single repeat
jinja will do your nested loop, namespace will store the information. Then later in yaml, use the list with your repeat
you can store a dictionary {'service': ..., 'data': {...}} then in your repeat.... repeat.item.service for whatever you put in service, and repeat.item.data for whatever you put in data
- repeat:
for_each: "{{ items }}"
sequence:
- service: "{{ repeat.item.service }}"
data: "{{ repeat.item.data }}"
I see now. The list items would contain the unavailable_sensors and service and data for each service?
You can store whatever you want.
How can identify WHICH automation changed a light?
I try to find that out; But the parent id is always different
- platform: event
event_type: call_service
event_data:
domain: light
action:
- service: system_log.write
data:
level: error
message: {{ context }} {{context.user_id }} {{context.parent_id}}```
(shortened for readability)
Iirc context.id or context.parent_id
But turning the light on two times results in 2 different context.id as well as 2 different context.parent_id for me
Check the ids in relation to automation ids
The mentioned filter logged outputs:
Context <homeassistant.core.Context object at 0x7fd556b0a1c0> Context.user_id None Context.parent_id 01GWHJ7WET1DBDMTAT9Q6544N0 Context.id 01GWHJ7WEW82MDYC7E86CA7KGY
Context <homeassistant.core.Context object at 0x7fd5580b7240> Context.user_id None Context.parent_id 01GWHJ9RXCF4EQZ400CY4K7Z26 Context.id 01GWHJ9RXE5J44595HCQBPN2A4
I fired it using the same action two times; so nothing keeps the same it seems
oh, from a different automation, the context.id from that RUN of an automation can be found in my log!
I'll test that when I get second thank you.
can anyone help me as to why this template throws anerror when writing an automation condition, but returns correctly in the template tool in dev tools
{{ state_attr('climate.hive_thermostat','hvac_action') == "idle" }}
the template is fine, but I can see issues with it if you actually put in in yaml
so we need the full yaml code for this condition
Are you 'testing' the condition and it fails there? If yes, last I remember testing template conditions was broken.
it's not anymore
just tested it, but the issue was the mixed usage of quotes inside of the template in combination with a single line notation
probably still doesn't work with variables passed to it though?
I don't use the UI, so i'm deferring to you
Yes, as @marble jackal notes, it was my bad use of quotation marks
I don't use it as well, I just tested it with {{ True }}
But I indeed see issues when using variables
It doesn't work, but at least it's clear why it doesn't
Any tips for this? I would like to gather the timestamp sensors to a list and then use them as targets in service action.
Any other method is ok also but that's what I had in mind.
{{ rooms | selectattr('binary_sensor', 'is_state', 'on') | map(attribute='timestamp_sensor') | list }}
Thanks! That was much easier than I thought. Maybe someday I
...I'll master the language
as soon as you do, we'll add something that makes it easier or more confusing
learning curve is steep and endless π
@final sun I converted your message into a file since it's above 15 lines :+1:
Can someone tell me why this doesn't work?
This is my error: Invalid time specified: "15:10:00" for dictionary value @ data['time']. Got None
Nvm I got it π
the result was already a string
Hi, i just got a zigbee switch remote or w.e u call it. It has 6 buttons and i want each button automated for to radio channel but i dont want 6 automations π is it possible somehow to vreate something like if button 1 presses then... etc..
@bitter sigil I converted your message into a file since it's above 15 lines :+1:
@bitter sigil I converted your message into a file since it's above 15 lines :+1:
Why does total_power_from_solar return 0, when the values of sensor.envoy_current_power_production = 3821 and sensor.envoy_current_power_consumption = 1026 ?
Can anyone tell me why this template sensor isn't working? I pasted a small portion of it here. When I examine sensor.psp_prices_tam, is is UNKNOWN. Trying to get this to work with the utility meter stuff. I am pretty sure this template is getting triggered, as I do see select.power_usage changing via my automations. I was hoping sensor.psp_prices_tam would equal .02 when 12AM occurred.
- trigger:
sensor:- name: "PSP Prices TAM"
unit_of_measurement: "$"
state: >
{% if is_state('select.power_usage', '12AM') %}
{{0.02}}
- name: "PSP Prices TAM"
because you're providing defaults of 2 for both. and 2 - 2 = 0
you're missing the end of your if statement
yeah, I have an end at the bottom, didn't include here cause I have 24 hours of if statements
how can we help you fix it if we can't see the whole template in your template sensor
Defaults of 2?
{% endif %} at the bottom
float(2) converts the state from a string to a number, if it can't convert it to a number, it will default to the value 2.
on startup, the values in your sensors will not be numbers, so it defaults to 2 for both
use an availability template to get past that
used this as well: state: >
{{ (states("sensor.envoy_current_power_production") | float | round(2)) - (states("sensor.envoy_current_power_consumption") | float | round(2)) }}
that will have the same problem
except it will error on startup
because you aren't providing a default
I am sorry. I am new to all this and I have no idea what an "availability template" is
I just need the number returned, so remove float and round?
it's just a field named availability that contains a template that will let HA know when the state is valid and should be calculated
I mean, not even this works: state: >
{{ states("sensor.envoy_current_power_consumption") }}
sensors:
- name: TotalPowerFromSolar
unique_id: total_power_from_solar
device_class: power
state_class: measurment
unit_of_measurement: "W"
state: >
{{ states("sensor.envoy_current_power_production") | float - states("sensor.envoy_current_power_consumption") | float }}
availability: >
{{ states("sensor.envoy_current_power_production") | is_number and states("sensor.envoy_current_power_consumption") | is_number }}
Should that return 1026 ?
this still returns 0
Are you sure you're looking at the correct entity?
I can share my screen if that would help, or go in voice chat if you got a couple of minutes to spare
can you take a screenshot of each entity you're pulling information from in the developer tools -> states page?
Open your Home Assistant instance and show your state developer tools
@bitter sigil 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.
well thats your problem
you aren't using the correct entity_ids
however you should still employ the availability template that I posted
just update the entity_ids
sensor.envoy_122103039899_current_power_consumption
that's your entity_id
availability: >
{{ states("sensor.envoy_122103039899_current_power_production") |
is_number and
states("sensor.envoy_122103039899_current_power_consumption") | is_number
}}
state: >
{{ states("sensor.envoy_122103039899_current_power_production") | float -
states("sensor.envoy_122103039899_current_power_consumption") | float }}
your template uses sensor.envoy_current_power_consumption
tthose are the ones I am using, I just removed the serial numer
ok then show a screenshot of sensor.totalpowerfromsolar
that is not on the developer Tools STATES page...
It is defined in the Card Configuration for the power-flow-card from HACS
This is its content:
@bitter sigil I converted your message into a file since it's above 15 lines :+1:
Then you didn't restart HA after adding it
uh wait, you're missng up how you can configure things
you can't put a template sensor inside your card configuration
And now I feel like an even bigger looser.... For this, just the "Quick reload" or a full restart of HA?
template sensors go in configuration.yaml
in the template section
it will then create an entity
you then use that entity in power-flow-card
I have no templates section in the yaml file
this is it...
Loads default set of integrations. Do not remove.
default_config:
Load frontend themes from the themes folder
frontend:
themes: !include_dir_merge_named themes
Text to speech
tts:
- platform: google_translate
automation: !include automations.yaml
script: !include scripts.yaml
scene: !include scenes.yaml
right, so you have to create it
so add a templates: !include templates.yaml to thhat file and then create a templates.yaml and put only the sensor info there?
sure you can do it that way
just make sure you add a - before sensor:
e.g.
- sensor:
- name: ...
unique_id: ...
wierd... I get an error...
Loads default set of integrations. Do not remove.
default_config:
Load frontend themes from the themes folder
frontend:
themes: !include_dir_merge_named themes
Text to speech
tts:
- platform: google_translate
automation: !include automations.yaml
script: !include scripts.yaml
scene: !include scenes.yaml
templates: !include templates.yaml
it's template:
ok, fixed that... Now in the template.yaml file that looks like this:
- sensor:
- name: TotalPowerFromSolar
unique_id: total_power_from_solar
device_class: power
state_class: measurment
unit_of_measurement: "W"
state: >
{{ states("sensor.envoy_122103039899_current_power_production") | float - states("sensor.envoy_122103039899_current_power_consumption") | float }}
availability: >
{{ states("sensor.envoy_122103039899_current_power_production") | is_number and states("sensor.envoy_122103039899_current_power_consumption") | is_number }}
- name: TotalPowerFromSolar
yep, restart and sensor.totalpowerfromsolar should appear
yeah, fixed a typo...
until you have at least 1 template sensor in your system
then when you have at least one, you can reload anytime you add a new one
but the first one you add, you need to restart
got the correct reading now, and the sensor appears in the STATES
can you point me to where these math definitions for floar and round and the likes are?
and things like is_number
it's in the topic
Become a real Jinja2 Ninja! Don't worry my Genin, we are here to help! You can find general Jinja docs at https://jinja.palletsprojects.com/en/3.1.x/templates/, Home Assistant extensions at https://www.home-assistant.io/docs/configuration/templating/, and trigger variables at https://www.home-assistant.io/docs/automation/templating/
This channel is for support with Jinja templates. Some custom Lovelace cards support other types of templates, such as those written in JavaScript, and #frontend-archived is the right channel for that.
Please use http://pastie.org/, https://dpaste.org/, or https://paste.debian.net/ to share code or logs
FYI the code in {% %} and {{ }} is jinja
I can talk in fortran and cobalt, but this is giving me a headache. Not the syntax, but the math/calculation parts of it.
You'll get used to it, it's just order of operation. And if you want, you can use parenthesis to make it easier for you to read
that documentation was the one I was looking for. Thank you kind Sir.
But is it possible to make sensor.important fall back to the last known value, if it gets unavailable? Value is numeric
@mighty ledge what does the availability: do? just checks that the sensor is online and returning a number? And if so, what happens if it is offline?
Then the template is unavailable
Can we default it to 0 instead of it becoming unavailable?
and you mean that particular sensor in the template file, not the whole template file correct?
Struggling to build this. Not sure how to get my list of sensors in. Then the list of entities for the number.set_value service and their corresponding values which is variabilized off the current item for efficiency.
How would I using namespace add all 4 switch_entities to each item in the list of unavailable_sensors https://dpaste.org/1Bau1
Or build the switch entity_id using something like this for each unavailable sensor
number.{{ (sensor.split('_presence')[:1] | join('') if 'presence' in sensor else sensor.split('_illuminance')[:1] | join('')) | regex_findall_index('\.([^\.]+)$') + '_' + item }}
post what you've tried
I realized the iifs probably wouldn't work how I set them up and eventually moved to using strings foo as placeholders just to see the outputs. But I have no idea how to get it exactly as I need. I have used namespace before but only for mapping data to pass to a script.
https://dpaste.org/r1PLE
Where does sensors come from? And why are you wrapping it in an array before appending it to an array?
Also, you have one %} too many
Improved formatting I believe: https://dpaste.org/0az41
You also have to explain what you mean by 'add'
and you're doing some redundant things in your variables
lets say binary_sensor.garage_presence_detector_presence_1 is unavailable
what do you expect the output to be
It was just me testing in template editor. Sensors would actually be unavailable_sensors https://dpaste.org/1Bau1
The garage would need to be filtered out and not be in the list to iterate over as there's no switch. That would be something I just get a notification for. That's why I sort of separated the 2. The purpose here is if for some reason any of my presence detectors (esp32s) or light sensor (esp32) is offline turn the accompanying switch light bars to red. If it's back online (determined in another loop after doing a button press on unavailable sensors that targets the corresponding restart entities) then switch the color back to blue for the accompanying switches
So it's set 4 entities per unavailable sensor that has a switch. target_switches. (2 are color entities and 2 are brightness) then later I would do the same thing except this time look for what's no longer unavailable and iterate over those reverting the color and brightness changes on those 4 entities.
Here's a novel idea: Why not create template sensors? And in the attributes just specify which switch is associated with it.
The other idea is a large static dict I was just wondering if there's a cleaner way
To avoid having a huge dict with each sensor mated to switch entities.
Ok, so pretend I said an entity that wouldn't be filtered out
When the naming conventions of the switch entities is known. Something like this would work for all 4 entities for all sensors.
number.{{ (sensor.split('_presence')[:1] | join('') if 'presence' in sensor else sensor.split('_illuminance')[:1] | join('')) | regex_findall_index('\.([^\.]+)$') + '_' + item }}"
what would you expect the output to be
because you keep saying switches but your template has number.
so I'm just trying to clarify wtf you're doing
Lol
These are inovelli switches the ZigBee blues
They have light bars on the side
If the esp32 that does presence is unavailable I would set the light bar to red which is 0 for color entities and brightness 100
Later on when it's available set back to 170 for color which is blue.
If it never becomes available again it stays red letting me know something is up.
That's the only reason I have switches. They aren't switch entities switch. but physically they are switches.
they are number entities?
Ok, so why do you have 4 number entities
4 number entities. 2 (color when binded lights are on and 1 for off)
2 for brightness (when binded lights are on and when they are off)
That's why the entities are
- switch_default_all_led_off_color
- switch_default_all_led_on_color
- switch_default_all_led_off_intensity
- switch_default_all_led_on_intensity
Disregard spacing ^
ok and what is the expected entity_id of switch_default_all_led_off_color if the presence entity_id is binary_sensor.kitchen_presence_detector_presence
Here was what I tested for one of the entities. Below the endfor is the output.
https://dpaste.org/6qfAj
Then the value would be calculated based off whether color was in the entity_id It's 0 else 100 (brightness)
binary_sensor.upstairs_bathroom_presense_detector_motion_sensor is spelled wrong
not really, i'll show you why in a sec
well, Just fix it tho
makes the regex easier
Fixing now.
I do have an else for splitting on _illuminance as one sensor could be sensor.office_illuminance_sensor
so what is switch_default_all_led_off_color going to do?
what is switch_default_all_led_on_color going to do?
service wise
Just a set value on the number entity. Color entities value would be 0 else 100 which is for the brightness entities.
else... meaning?
so this is just looking at unavailable things right?
or not
and what's your trigger
You're iterating over all these lists all the time, is that what you really want to do or is this going to be triggered by the presence detectors going unavailable & available
Just unavailable I would need to set a variable after restarting to see if any successfully restart as the list of available would change.
For example.
"{{ iif('color' in repeat.item, '0', '100') }}"
For unavailable.
For available.
"{{ iif('color' in repeat.item, '170', '70') }}" although now that I think about it I could just set all switches to 100 and only need to mess with the color entities.
The trigger would be one of them going unavailable. Or a couple of other binary sensors I have such as a delayed sensor when home assistant starts up then it would check for unavailable sensors.
binary_sensor.homeassistant_restart_delayed_trigger has a delay on it after the event start for home assistant. That way I could essentially check on a startup for anything that's already unavailable.
Is it bad to iterate all the time?
ok and what are you going to do with switch_default_all_led_off_intensity and switch_default_all_led_on_intensity when this unavailable list is populated?
Set to 100. If possible somehow to store memory save the previous value that way when it's available I would set it back to what it was before it was set to 100. But that's not a big deal.
so both are being set to 100?
So is this going to run every x minutes or seconds?
because you have unavailable/available yet your current code only looks for unavailable.
Yep both to 100. What I would do is first set all switches to red (0) and brightness (100) then attempt to restart the unavailable sensors.
entity_id: "button.restart_{{ trigger_object_id if trigger_object_id != 'null' else sensor_entity_object_id }}"
1 time per minute and stopping if the sensor becomes available.
Then I would iniitlaize a variable checking for available sensors and update those that are to blue.
To be more efficient it's possible could potentially check the difference between the initial unavailable and available and only target those entities.
I technically didn't need to trigger_object_id but the purpose for the else was in the event it wasn't a sensor that triggered the automation and instead was binary_sensor.homeassistant_restart_delayed_trigger
sorry pulled away for work
what's the entity_id of the button that you're pressing
No problem.
If it's an unavailable sensor of binary_sensor.master_bedroom_presence_detector_presence_1
Then the button entity is
button.restart_master_bedroom_presence_detector_presence_1
Awesome, is it possible to do a repeat while to attempt multiple restarts until index > 5 with a delay of a minute between each attempt per item or is that not possible?
it's going to try every loop to restart them once
limiting it to 5 will require a counter
Oh yeah. Lol π€¦ββοΈ
So when it becomes available we don't need a separate service call essentially to set the color back to 170 for example?
Nevermind read the code. I see that's handled too. This is awesome.. not something I would have come up with.
it does everything
Although if sensor.office_illuminance_sensor is unavailable what does it do? Would it still do a restart?
it'll do nothing
you had that filtered out for some reason
are you just trying to restart it?
if yes...
items: >
{% set ns = namespace(items=[], sources=[]) %}
{% for sensor in sensors %}
{% set target = sensor | regex_findall('(?:[a-z_]+\.)([a-z_]+)(?:_presence_detector[a-z_0-9]+)') | first | default %}
{% set unavailable = states(sensor) in ['unavailable', 'unknown'] %}
{% if unavailable %}
{% set ns.sources = ns.sources + [ sensor ] %}
{% endif %}
{% if target or target != 'garage' %}
{% for switch in switch_entities %}
{% if unavailable %}
{% set value = iif('color' in switch, 0, 100) %}
{% else %}
{% set value = iif('color' in switch, 170, 70) %}
{% endif %}
{% set ns.items = ns.items + [
{
'value': value,
'entity_id': 'number.' ~ target ~ '_' ~ switch
}
] %}
{% endfor %}
{% endif %}
{% endfor %}
{{ {'numbers': ns.items, 'unavailable': ns.sources} }}
Yeah just restart. Wondering how to gather a notification together for what's unavailable. Without sending one every minute lol.
make a separate automation
tbh, this is not how I would handle this
I'd just look for sensors that go unavailable
match the numbers (switches) and set the light until it becomes available again
Isn't that what the automation does now?
You'd get instant notifications that only happen once, and then you could limit it to 5 restarts.
no, you're checking every minute
instead of using the binary_sensor state changes as the trigger, you're running this minutely thing
I see. Well I just wanted to make sure if home assistant starts and there are sensors that were previously unavailable that I would attempt to restart all of them. Otherwise individual state changes to unavailable are fine. I was just trying to guard against issues that could be missed when home assistant starts
they should restore states
and you can guard by looking at to/from states
Interesting then I guess I don't need the trigger per minute. how would I achieve that then?
this is what I would have done
@silent vector
there's some typos in the numbers: >
'entity_id': 'number.' ~ location ~ '_' ~ switch
then you can follow the traces too
you can remove the {% if was_unavailable != unavailable %} if statement if you want the colors to update for each state change
otherwise it only does things when they go from available to unavailable
which might give it a chance to get out of sync on a restart
you could also remove the restart safeguards too
and it'll never get out of sync
because it will fire at restart
I see. Does the number set value run when unavailable and then when it's no longer unavailable run again to set the color/brightness back to available? Not sure how that work if the service call comes before the restart service call. How would it know it's available again to set the color/brightness back to available?
The automation will fire again
That automation runs in parallel
That means multiple copies of it run at the same time
So while the one is bailing because the restart works, the binary sensor will go available and the colors will be set
Oh that makes sense didn't notice that. Perfect then this does literally everything.
Yes
Learning so much about what's possible in Jinja over the last year from this channel.
What's this var? trigger line 86
There is no line 86?
that's the trigger object
Ah got it. Now that makes sense. When would it be none?
it's never none
however from_state will be none at startup
well, it just won't exist
shouldn't there be a small delay in the repeat? otherwise you'll just spam the button 5 times in 3 microseconds
Makess sense. Yeah I had a delay 1 per minute in my initial junk code I can add that right after the button service call
Just because esp32s take a bit to start back up too
Is it actually 3 microseconds between service calls/actions?
That is super fast. Pretty cool to know.
@sonic ember I converted your message into a file since it's above 15 lines :+1:
Any advice on fixing it? Is it a setting on my HA in terms of what's local, or is it a problem in my code? Or something else?
It's from @deep marsh 's awesome template π
what's it trying to do?
It loops through the list and stores the time with the lowest value
that's it?
{% set lowest = state_attr('sensor.energyprices','raw_today') | sort(attribute='value', reverse=true) | first %}
{{ lowest.time }}
{{ lowest.value * states('input_number.nextenergy_additional_electricitycosts') | float(0) }}
I pasted the wrong part of the code
{% set ns = namespace(times=[], prices=[], lowest_price=100, cheapest_time=now(), hour_counter=0) %}
{% set today = state_attr('sensor.energyprices','raw_today') %}
{% for hours in today -%}
{% if ns.hour_counter < hours_ahead -%}
{% set retrieved_time = as_timestamp(as_local(hours.start)) %}
{% if retrieved_time > current_time - 3600 %}
{% set retrieved_price = (hours.value | float(0) + states('input_number.nextenergy_additional_electricitycosts') | float(0)) %}
{% if retrieved_price < ns.lowest_price %}
{% set ns.cheapest_time = retrieved_time %}
{% set ns.lowest_price = retrieved_price %}
{% endif %}
{% set ns.hour_counter = ns.hour_counter + 1 %}
{% endif %}
{% endif %}
{% endfor %}
There's a part of the code before that which uses "hours_ahead" (a helper) to determine which part of the list to sort through
Sorry, forgot about that part, and your sort comment reminded me
π€·ββοΈ it's over complicated
you can just get the lowest object and then use it how you want to
I see how you do that, that's useful. But how would I integrate the part where it's not searching the whole list, just the list that is between now() and now()+ X hours
it searches the whole list
and you get the time
no clue why there is an hour counter
if you want the difference in time, just use math on the 2 dates
{% set lowest = state_attr('sensor.energyprices','raw_today') | sort(attribute='value', reverse=true) | first %}
{% set lowest_price = lowest.value * states('input_number.nextenergy_additional_electricitycosts') | float(0) %}
{% set hours_from_now = (now() - lowest.time | as_datetime).hours %}
So in simple terms, (to give context). My list has potentially for 48 entries of time + value for electricity prices. I want to know the lowest one in the next X hours, not the lowest one in the whole list. This is so I can say "I want to turn on an appliance during the cheapest time within the next 6 hours"
@celest tinsel I converted your message into a file since it's above 15 lines :+1:
{% set hour_threshold = 6 %}
{% set time_threshold = (now().replace(minute=0, second=0, microsecond=0) + timedelta(hours=6)).isoformat() %}
{% set lowest = state_attr('sensor.energyprices','raw_today') | rejectattr('start', '<', now().isoformat()) | rejectattr('start', '<=', time_threshold) | sort(attribute='value', reverse=true) | first %}
{% set lowest_price = lowest.value * states('input_number.nextenergy_additional_electricitycosts') | float(0) %}
{% set lowest_time = lowest.start | as_datetime %}
Oh that's a NICE piece of code!
Lemme test it in dev tools
Seems 'start' is a str, not datetime. I can't just add | datetime() after it right?
TypeError: '<' not supported between instances of 'datetime.datetime' and 'str'
Ok, found the filter that worked, but still get an empty list. It seems like it's not reading the value attribute right, can that be?
{% set hour_threshold = 24 %}
{% set time_threshold = (now().replace(minute=0, second=0, microsecond=0) + timedelta(hours=6)).isoformat() %}
{% set lowest = state_attr('sensor.energyprices','raw_today') | rejectattr('start', '<', now().isoformat()|as_datetime) | rejectattr('start', '<=', time_threshold|as_datetime) | sort(attribute='value', reverse=true) | first %}
{% set lowest_price = lowest.value * states('input_number.nextenergy_additional_electricitycosts') | float(0) %}
{% set lowest_time = lowest.start | as_datetime %}
ok, well you provided a list that showed them as strings
if they are datetimes, this is easier
@deep marsh yes I did! And it works perfectly, except for a 2 hour offset.
{% set hour_threshold = 24 %}
{% set time_threshold = now().replace(minute=0, second=0, microsecond=0) + timedelta(hours=hour_threshold) %}
{% set lowest = state_attr('sensor.energyprices','raw_today') | rejectattr('start', '>', now()) | rejectattr('start', '<=', time_threshold) | sort(attribute='value', reverse=true) | first %}
{% set lowest_price = lowest.value * states('input_number.nextenergy_additional_electricitycosts') | float(0) %}
{% set lowest_time = lowest.start %}
Never mind, I saw that you do not use the helper in the code above.
Sorry, just copied them from the Dev. Tools page, I didn't pay attention to what type of object they were
I will add it after playing with petro's code (instead of the "24" I have now. Your code works fine, but I also like learning new (and sometimes simpler) ways of doing it, like sorting the list this way.
You should avoid namespace if you can, as it creates new memory
Ah, so this is easier on the system resources?
if you run it alot yes, if you don't... it's not really a big deal
This will be run about 4 times a day max
But still, there's always more ways to do something π
There was a typo, fixed it above
Ah, thanks. I see how you fixed the str. issue. Still gives an empty list though. My troubleshooting tells me this rejectattr('start', '<=', time_threshold) the part that isn't working.
{% set hour_threshold = 24 %}
{% set time_threshold = now().replace(minute=0, second=0, microsecond=0) + timedelta(hours=hour_threshold) %}
{% set lowest = state_attr('sensor.energyprices','raw_today') | selectattr('start', '>', now()) | selectattr('start', '<=', time_threshold) | sort(attribute='value', reverse=true) | first %}
{% set lowest_price = lowest.value * states('input_number.nextenergy_additional_electricitycosts') | float(0) %}
{% set lowest_time = lowest.start %}
Yeah got it! Thanks!
Damn, I realise a problem... There are two namespaces of times, today and tomorrow, and I need to look for both. But I'll look through some documentation to figure that out. One way is to actually make one namespace that all the other templates use that contain both days data, but then I'm making a new namespace again... Will have to figure that out later, have a meeting in a bit.
Thanks for the assistance! And I learnt about lists a bit π
just add them together
{% set hour_threshold = 24 %}
{% set time_threshold = now().replace(minute=0, second=0, microsecond=0) + timedelta(hours=hour_threshold) %}
{% set items = state_attr('sensor.energyprices','raw_today') + state_attr('sensor.energyprices','raw_tomorrow') %}
{% set lowest = items | selectattr('start', '>', now()) | selectattr('start', '<=', time_threshold) | sort(attribute='value') | first %}
{% set lowest_price = lowest.value * states('input_number.nextenergy_additional_electricitycosts') | float(0) %}
{% set lowest_time = lowest.start %}
Adding them together and sorting the list doesn't work imho because you will have duplicate times this way. I looked into this as well when I created the code. But, there are multiple ways to Rome.
Since a recent update I get below error:
TemplateError('TypeError: can't multiply sequence by non-int of type 'float'') while processing template 'Template("{{ states('sensor.electricity_delivery_15m') * 4 | float }}")' for attribute '_attr_native_value' in entity 'sensor.electricity_delivery_power_15m_2'
It sounds Chinese for me. Could anyone please help me
you're multiplying a state, which is a string
as it's always been
you're turning "4" into a float
Where can I find basic to learn al these things? I've copy/paste this code. It worked before but since some updates, HA isn't happy with these lines.
that's what it sounded like
there are several links in the channel topic
states('sensor.electricity_delivery_15m')|float(0) * 4
it's never been okay to treat a state as a number - it's always been a string
They shouldn't have duplicate times because the date is included in the datetime objects
But sensor.electricity_delivery_15m isn't a state, it gives values
I don't want to discuss. You know much better!
Ah, then it's different than in my case.
I created this a couple of months ago already. Didn't look into it now, but the code that I've created works fine for me, so it's okay.
I'm sure it works, it just doesn't use the power of jinja
with generators & filters
meaning you're resolving all objects and ultimately many of them (calcs like that) could impact your system if it runs frequently
@inner mesa thanks, the error is gone, since I changed. Unfortunately have 2 more errors. 1 of them is:
```TemplateError('ValueError: Template error: float got invalid input 'unavailable' when rendering template '{{ (states('sensor.power_delivered') |float * 1000) - (states('sensor.power_returned') |float * 1000) }}' but no default was specified') while processing template 'Template("{{ (states('sensor.power_delivered') |float * 1000) - (states('sensor.power_returned') |float * 1000) }}")' for attribute '_attr_native_value' in entity 'sensor.power_distri'````
What does this mean? input 'unavailable' so sensor.power_delivered is not available?
no, it means that the sensor state is "unavailable", which can't be evaluated as a float
that has caused an error for a year or two
that is why I used float(0) in the example I gave you above
The state of ''sensor.power_delivered'' is 0.000
float got invalid input 'unavailable'
it definitely got "unavailable" for one of the sensors you're using
Thanks!
Changed
(states('sensor.power_delivered') |float * 1000) - (states('sensor.power_returned') |float * 1000) }}"
into
(states('sensor.power_delivered') |float(0) * 1000) - (states('sensor.power_returned') |float(0) * 1000) }}"
but have 2 more errors now
which are?
Hmmm. I hided the lines by command '#', restarted HA, no errors anymore. Removed the '#' and no errors anymore...
nice. oddly enough, I have to leave out the reverse=true to have this spit out the lowest over 2 days```
{% set lowest = state_attr('sensor.entsoe_avg_price','prices')
| sort(attribute='price') |first %}
{% set lowest_price = lowest.price | float(0) %}
{% set lowest_time = lowest.time %}
{{lowest}}
{{lowest_time}}
{{lowest.price}}``` maybe I missed something in the discussion above, if so nvm. Ill be reworking this to help create 'tomorrow' sensors tomorrow after some sleep. thxs for this
The reverse true should be missing, that was a mistake on my part
@mint prairie I converted your message into a file since it's above 15 lines :+1:
I'm trying to extract data from sensor attributes from the Habitica integration. The parts I need are the values for 'text:' in this example for the sensor. Is there some way to reference those values with a template? The hexadecimal codes aren't static. Every new item gets a unique number.
01234567-890a-bcde-f012-34567890abcd:
group:
completedBy: {}
assignedUsers: []
type: todo
value: -1
priority: 1
created_at: '2023-03-27T21:18:16.956Z'
text: Task 1
rereading that data set of start/end/value, I must admit I've never seen that... why on earth does that contain 'end'? if its created by a rest sensor, you should really change that, as now, you're storing 48 unnecessary KVP's in your memory.
a time/value combination suffices in all scenarios?
experimenting with this a it more, and not yet sure what the final result should be, but consider this template set please and see the final creation of a list of KVP's that are below the average price. How could I output the times of that list. Or, preferably select either the list of times, or the list of values.
result is in the form of [{'time': '2023-03-28 13:00:00+02:00', 'price': 0.08687}, {'time': '2023-03-28 14:00:00+02:00', 'price': 0.09}, {'time': '2023-03-28 12:00:00+02:00', 'price': 0.0913}, {'time': '2023-03-28 15:00:00+02:00', 'price': 0.09432}, {'time': '2023-03-29 23:00:00+02:00', 'price': 0.0948}, {'time': '2023-03-28 11:00:00+02:00', 'price': 0.09489}]
The nordpool integration does that as well, it provides a start and end datetime for each hour
looking for something like: a these times, your prices are below average etc etc
well, thats pretty superfluous ..
storing unique data under 2 identifiers within the same context might even be an issue....?
An issue for what?
DB sanity.
I don't see issues for that, they are individual list items with a price value and two datetimes
hmm. its just that searching a dictionary for what one would think is unique, a datetime, can now have 2 results. When I learned relational DB's that was a huge No. Admitted that ws some time ago.... and that is besides the functionality in the forst place. I mean, what use can those end times have?
btw, trying that time selector, can I use |string to make that work? I am aware I am evaluating 2 strings now, but given those consist of numbers only: {% set time_threshold = now().replace(minute=0, second=0, microsecond=0) %} {{time_threshold}} {% set prices = state_attr('sensor.entsoe_avg_price','prices') | selectattr('time', '<=', time_threshold|string) |sort(attribute='price')%} If I dont do that it errors with the infamous TypeError: '<=' not supported between instances of 'str' and 'datetime.datetime' discussed earier
where: {% set prices = state_attr('sensor.entsoe_avg_price','prices') | selectattr('time', '==', '2023-03-29 13:00:00+02:00') |sort(attribute='price')%} returns the correct value. so strings on both side of the operator
Quick question that I think is super simple...I'm wanting this to return an integer (a whole number), but I'm getting a decimal back. What am I doing wrong? {{60 / (states('sensor.sump_pump_2_pumpout_event_counter') | int(0))}} I have also tried {{60 / (states('sensor.sump_pump_2_pumpout_event_counter') | round(0))}}
I think it is something with the division? In testing with Developer Tools, the first line doesn't round but the second line does: ```{{ 3/14 | round(2) }}
{{ 12.3456 | round(2) }} ```
Got it: {{float(1440 / (states('sensor.sump_pump_2_pumpout_event_counter_24hr')) | int(0)) | round}} Not sure if this is the most elegant or efficient way, but it works...
you've got to think about the order of operations PEMDAS/BODMAS π
So was I trying to round a string or something?
if the final operation is |int, be sure you do that on the calculation result, and not on the final number in the calculation itself
{{ (3/14) | round(2) }} does what you want
where {{ 3/14 | round(2) }} would round 14 itself
Ohhhh
Now I see the order of operations connection
So I originally copied this from elsewhere and using a guess and test while trying to read the docs. What does the int(0)?
Another thing I don't understand about the syntax is sometimes the "operator" comes before and you put the "argument" enclosed in parenthesis (like with float in mine) and other times it comes after a pipe (like round in. mine). (Not sure if I'm using those terms correctly, hence the quotes). Is there a general rule I'm missing? Or can it work both ways?
see the pinned message for int(0) in default values https://community.home-assistant.io/t/updating-templates-with-the-new-default-values/346198
your second question regards either a filter ( used with the 'pipe' symbol |) or a function like the float() function you used above. Many of these are available in both methods, not all though.
Ah, filter vs. function, that's why it is different.
Using it as a function can avoid issues with order of operations
int(3/14, 0) for example
So to help me understand the thing that actually works... {{float(1440 / (states('sensor.sump_pump_2_pumpout_event_counter_24hr')) | int(0)) | round}}. What is this doing in plain English? It divides 1440 by the sensor state. Then converts that to a float? Then converts it to an integer? And then rounds it? If this is right, why is rounding needed, shouldn't the int filter take care of that?
guess the official docs explain the best: https://jinja.palletsprojects.com/en/latest/templates/#list-of-builtin-filters
LOL I was "reading" those and couldn't figure it out and came here. It's as if I'm copying and pasting a foreign language into a translation app and sometimes it says "error" and other times something intelligible comes out.
Probably doesn't help that it's 5am where I am and I've been up since 1:30 because I couldn't sleep.
But if I take out the float function it doesn't round it to zero decimals like I want.
Nevermind it does I think, if I use ( ) correctly.
{{(60 / (states('sensor.sump_pump_1_pumpout_event_counter')) | int(0)) | round}}
{{60 / (states('sensor.sump_pump_running_counter') | int(0))}} Those extra ( ) make all the difference.
Why is the int(0) needed? Why can't I just round it?
throw that into google and you get: Because the int function it is defined to truncate the floating point, not to round it. If you need to round a floating point number - use the round() function. A good way to remember it is that the int() function returns the integer component of a floating point number.
Any ideas what is wrong here?
https://dpaste.org/b7NJX
Message malformed: Unexpected value for condition: 'None'. Expected and, device, not, numeric_state, or, state, sun, template, time, trigger, zone @ data['action'][1]['if'][1]
But why do you have to truncate it first to round it? For example, this does not round the output {{(60 / (states('sensor.sump_pump_1_pumpout_event_counter')) | round(0))}}
I use HACS Afvalbeheer. Right now only 1 sensor thingy is shown as a calendar object, but there are sensors that show a date without being part of calendar.* How can I turn those sensor dates into a calendar object to be shown on the calendar? https://imgur.com/a/eqgi2lU
You'll have to format your thresholds as strings, both of them.
you have a wait for trigger in your if condition.
the if section only accepts templates or conditions, not actions.
Also the automation from yesterday worked just had to tweak some variables. repeat.value with repeat.item.value for example. Thanks for the massive assistance with that.
because your parenthesis aren't correct. And if you move the parenthesis, you need to ensure that it's a float when making your calculations.
{{ (60 / (states('sensor.sump_pump_1_pumpout_event_counter') | float) | round(0) }}
Secondly, that template will fail to render on startup. You'll need to pair this with an availability template or supply a default. Just keep in mind that your default cannot be 0 because then the equation will divide by zero which is impossible in math. That will also produce an error. So you'd have to supply a default that is not zero.
{{ (60 / (states('sensor.sump_pump_1_pumpout_event_counter') | float(1)) | round(0) }}
π€¦ββοΈ I didn't even realize that I had actions in the if
That's not possible right now without creating the calendars ahead of time. You'd have to manually create 3 additional calendars, then use an automation to create events from the sensors. If you just want to add them to your existing calendar, you can do that with your automation.
#automations-archived can help with that
Thanks for helping me get on the right track!
trying to make a template sensor (from two input_numbers) that platform time can trigger an automation from.. someone mind helping me?
platform: template sensors: alarm_time: value_template: "{{ states('input_number.alarm_clock_hour')|int() }}:{{ states('input_number.alarm_clock_minute')|int() }}"
resolves to correct time in this case 15:10
but i guess it needs to be converted to timestamp for automation to run?
Would an input_datetime not be much simpler than separate numbers for hour and minute? But yes if you want time trigger from a sensor, it must be device_class: timestamp.
managed to rewrite it to get timestamp (even though weirdly formated), testing it now.
correct hour/minute but 1900 january 1 π haha
today_at() function would probably be helpful.
trying to set a wake up routine out of inputnumber hour and inputnumber minute
alarm_time_fix_2: value_template: > {{ as_timestamp(strptime(states('sensor.alarm_time'),'%H:%M'))}}
GMT: Monday 1 January 1900 14:20:00
today_at(value)converts a string containing a military time format to a datetime object with todayβs date in your time zone.
{{ today_at(strptime(states('sensor.alarm_time'),'%H:%M'))}} gives ValueError: could not convert datetime to datetime: '1900-01-01 15:20:00'
you don't need strptime
today_at(states('sensor.alarm_time'))
(assuming alarm_time is "HH:MM")
I think you will also want:
alarm_time_fix_2:
device_class: timestamp
value_template: >
...
then it should be eligible for time trigger
it's not going to update every day
you'll need to use the new template entity format and provide triggers. 1 at midnight and 1 when sensor.alarm_time changes state.
I have a PR out to force today_at to resolve templates every minute, I think that will be added to 2023.4.x. But until then, it won't update unless you force updates.
by doing this
any link where i can read up on the new template entity format?
so if i set alarm now to like 06:30am tomorrow and go to bed.. its gonna be triggered from 06:30 today and not tomorrow
do i make an automation to reload the sensor somehow?
kk just tried thats exactly what happends
- platform: template
value_template: >-
{{ states("sensor.time") == (state_attr("input_datetime.wakeup_time","timestamp") | int | timestamp_custom("%H:%M", False)) }}```
Here's a time trigger I use for an alarm based on an input helper
current automation is like this
`alias: wakeupmode_is_on
trigger:
platform: time
at: sensor.alarm_time_fix
condition:
condition: time
weekday:
- mon
- tue
- wed
- thu
- fri
action:
- service: script.turn_on
entity_id: script.wakeupmode`
what is providing that sensor.alarm_time_fix?
you can also move that to a separate entity and do:```
- alias: Alarm Clock wD
id: alarm_clock_weekday
trigger:
platform: template
value_template: >
{{states('sensor.time') == states('sensor.alarmclock_wd_time')}}
using that template in an actual template sensor:```
template:
-
sensor:
- unique_id: alarmclock_wd_time
name: Alarmtime weekday
state: >
{% if is_state('input_boolean.alarmclock_wd_enabled','on') %}
{{state_attr('input_datetime.alarmclock_wd','timestamp')
|timestamp_custom('%H:%M',False)}}
{% else %} Not set
{% endif %}
- unique_id: alarmclock_wd_time
platform: template sensors: alarm_time_fix: device_class: timestamp value_template: > {{ today_at(states('sensor.alarm_time')) }}
platform: template sensors: alarm_time: value_template: "{{ states('input_number.alarm_clock_hour')|int() }}:{{ states('input_number.alarm_clock_minute')|int() }}"
Ahh seems a bit overcomplicated with the double template sensors
well alarm_time is set from input_numbers, alarm_time_fix was just a way to get automation to run
I see you didn't actually switch to the new template style
you don't need an automation
template:
- trigger:
- platform: time
at: "00:00"
- platform: state
entity_id:
- input_number.alarm_clock_hour
- input_number.alarm_clock_minute
sensor:
- name: alarm_time
device_class: timestamp
state: "{{ today_at(expand('input_number.alarm_clock_hour', 'input_number.alarm_clock_minute') | map(attribute='state') | map('int', 0) | map('string') | list | join(':')) }}"
this goes in configuration.yaml, not sensor.yaml
@dim jay That is the only template you need
uhm
Then just an automation watching for that trigger event?
no, no automation needed
WHat happens when that triggers tho lol
But isn't the whole point of having a time-based event to do something else?
Hence the automation bit anyways
Yeah, but that's not what he needed help with
he created an automation to update the entity, which isn't needed.
because it updates itself
Ahh I thought he was just trying to trigger an automation at a specific time
yes he can
with
trigger:
- platform: time
at: sensor.alarm_time
but he needs the template sensor first
Logger: homeassistant.config Source: config.py:868 First occurred: 16:08:29 (1 occurrences) Last logged: 16:08:29 Invalid config for [template]: expected a dictionary. Got [OrderedDict([('trigger', [OrderedDict([('platform', 'time'), ('at', '00:00')]), OrderedDict([('platform', 'state'), ('entity_id', ['input_number.alarm_clock_hour', 'input_number.alarm_clock_minute'])])]), ('sensor', [OrderedDict([('name', 'alarm_time_ts'), ('device_class', 'timestamp'), ('state', "{{ today_at(expand('input_number.alarm_clock_hour', 'input_number.alarm_clock_minute') | map(attribute='state') | map('int', 0) | map('string') | list | join(':')) }}")])])])]. (See /config/template/alarm_time.yaml, line 0).
you didn't copy it correctly.
copy that whole chunk and paste it into configuration.yaml, as-is
however it seems that you've tried to use an include based on that error
which you most likely set up incorrectly, so post what you tried
though I fail to see how in this case (setting an alarm time) this: #templates-archived message is simpler than #templates-archived message there are some crafty manipulations there, that have the beauty of simplicity..
expand -> map(state) -> map(int) -> map(string) | list | join . That is pretty cool indeed.
π€·ββοΈ it makes the triggers easy
because it's a timestamp sensor
I'm not sure why he decided to use 2 sliders instead of a input_datetime
which wouldn't require any of that
because im an idiot? π
might because of the Dashboard. I have them both..... some in my household prefer the slider, some prefer the datetime
or didnt know about input_datetime
simply create the input_datetime and use the following trigger
- platform: time
at: input_datetime.alarm_time
more like 'uninformed'
not knowing things doesn't make you an idiot
it's room for learning
so i add input_datetime: to configuration.yaml then create a variable like "alarm_time" and use that in my config?
you can create the input_datetime in the UI
just make sure it's a time only input datetime
no need to create a variable either
just create the datetime
also the plain input_datetime is a terrible UX on mobile. the sliders work much better
Yeah the input validation in HA makes me want to murder sometimes
Like my wife trying to change 06:00 to 05:45 it refuses to let you delete the whole value
God forbid you want to enter '0.01' into any numeric field in HA
You've literally got to type 0.1 and then insert the zero in between
Personally I would have loved to settle for that custom:time-picker-card, but hey, its custom, and I really try to stick to core as much as possible. So, still having doubts which interface to keep
I wouldn't sweat custom cards, they're like low-hanging fruit
All of the input validation in HA should be on field exit, not as you type haha
yeah, until they no longer are, and you have to go back to the raw building blocks of core.. tbh, these inputs should be getting some attention... other # though, we can only hope
kk all working now many thanks
now if kids complain about not waking up with all lights going off, music starting etc im not sure what to do
have a great evening π
Switching to a light-based alarm changed my wife's life, she was not a morning person and now she always wakes up for the alarm
Having a 10-minute fade in to full brightness is like magic for waking up
You just need a couple calls
First call to turn the lights on to 1%
Then a 2nd call to 100% brightness with a 10min duration
Figured as much. Doing it in a script with delays?
Naw, the light.turn_on call has a transition value
That's how long it'll take to to reach the value you're targeting
Something like ```service: light.turn_on
data:
transition: 600
brightness_pct: 100
target:
entity_id: light.nightstand_lights
You just need the first call to set to 1% with no transition so they start where you want, some lights will transition from the last state they were when on
One call may suffice however
Assuming that transition is supported by your hardware
Ha pretends to do it in that case but nothing occurs
I've seen people do 1% red with a fade to white full brightness
I always have my best bulbs in my nightstand for that very reason
Need some help turning pseudocode into an automation. I have solved this today with 4 different automations but that gets hard to maintain. Is there anyway to achieve this with an automation?
@half pendant I converted your message into a file since it's above 15 lines :+1:
Good evning π @mighty ledge you where so kind to help me a while ago. Can you meaby confirm a automation ? π
#automations-archived can help, and you don't need any templates
This seems to work brilliantly, thanks!!
Didn't manage to test it yesterday, but it worked now π
yeah there was a few rando issues that I adjusted
I was surprised that rejectattr didn't work but you used selectattr instead
can you explain why?
one rejects from the list, the other selects.
I think I had the logic backward based on what one I was using
i.e. I was removing what you wanted instead of keeping it
It's an integration (Nordpool) that provides this. I just installed the integration and used it as is. With some adjustments thanks to SmartHomeJunkie's videos
Ahh I see, so it would have worked if we swapped the < and >= but that would be less logical to read.
If I only have name: "string" it creates its own machine name right? For a template sensor? And if I put name and friendly_name it will do both? I'm trying to find a way to force the machine name in the code. Or do I change that in UI afterwards?
YES! It works π haha nice! Washing machine done and automated, including flexible time ranges π I'll have to write this up for others π Thanks @mighty ledge and @deep marsh !
Now the dishwasher, a new challenge π
Hi Guys, i'm planning on adding 6-8 mini displays around the house. I've built a custom dashboard for it and it works well - however, i'd like to make it one generic template that customizes based on the AREA of where the display is located - if it's in the kitchen, show the kitchen stuff.
I have pretty good naming conventions.
do you think this is doable? Or should i just build 6 dashboards and have each one default to a different one
what is the difference between "name:" and "friendly_name:"?
Nothing, just what the yaml requires
Templates wonβt help in that situation. All your displays would have the same info. You change one, the rest follow suit
I get this when viewing the energy dashboard: https://imgur.com/a/mkjpWwr but in the template file I have: - name: Total_Power_From_Grid_Today
friendly_name: Total Power From Grid Today
unique_id: total_power_from_grid_today
device_class: energy
state_class: total_increasing
it shows the name, not the friendly name. Can the "name:" have spaces? or should I use spaces inside quotes or double qoutes?
Yes it allows spaces
If I could grab the name then I could use sensor.(location)_temperature_sensor.temperature
so no need for friendly name at all? and what about using quotes?
Iβm on mobile but this would be the idea
Youβd have to use a custom card that allows templates in the front end. Built in cards do not allow templates.
I use mushroom cards mostly
But the challenge has been to grab the location of the client thatβs loading the dashboard
Well you canβt βget the locationβ. Youβd have to hardcode it
The backend has no concept of whoβs logged in
Or where they are logged in
It has the concept of devices, so I was hoping it could identify the device.
You donβt need quotes unless you have special characters in the name, like { or }
But you have me a good idea - maybe I create a user for each area
With the same name as the area
And each dashboard logs in as the user where the dashboard is
Yeah but thatβs still not going to translate into your template
Unless mushroom card exposes the logged in user as a variable in the templates namespace
At least now I know the jargon to look for a solution.
Since there are only a few, it might be easier to just build out 6 dashboards
Probably
I think you could also make use of the auto entities card
And possibly the layout card
Both custom
I believe user is available in those
Can't persistent session tokens be used for each area if you do a login to that area and not log off?
Or like with my HA on my phone, that it has is own entity, wouldn't each tablet have its own unique ID?
I'm new to this, but it seems that that is how geofencing works. so it would be the same principle for the tablets
Thatβs my thought - but Petro makes a good point that this might not be exposed as a variable to the front end. Iβll test this hot
@mighty ledge I have several template entities using integration_entities to guesstimate the power usage based on those which are available..
I never actually checked on them, but I guess I need to add now() (or as of 2023.4 relative_time or today_at) somewhere to make them actually reload
Or create groups π
Or just add a trigger to the template entity
Ah sure π
Having lots of fun over the past couple months moving my devices and automations from Homeseer to HA. I am starting to venture into tHavinghe world of templating. I have a need to collect on/off, time/duration, using the "history_stats" integration for a binary sensor that tracks each time outdoor brightness (lux) falls below 8500. I want to set the history_stats "start:" time based on sunset, modified by an offset (prior to). The "t_sunset_offset"code below provides the offset I am looking for. I am stumped on how to get the resulting H, M, S results, into the hour=, minute= second=, syntax of the "history_stats" integration. I appreciate any advice you can provide. TIA!... Don
t_sunset_offset: "{{ ((as_timestamp(state_attr('sun.sun', 'next_setting')) - 180*60) | timestamp_custom('%H,%M,%S')) }}"
{{ now().replace(hour=0, minute=0, second=0) }}
First example here shows that history stats can accept templates that render datetimes for the start: and end:.
https://www.home-assistant.io/integrations/history_stats/#examples
If I have a dictionary of lists with multiple indexes. Each index contains related information but one of the lists doesn't contain relational data meaning you couldn't select/map to get your answer otherwise you end up with a bunch of values for which there's no relationship as to what they are related to. The only answer I found was to loop through find the specific value and save the loop.index0. Then find the next value (the one that has nothing we can map/select on without losing relationship) by using the index position from the first value and ending the loop printing out the result.
Map select results in
foo
bar
santa
But I have 0 way of knowing was foo related to x or y or z?
Whereas my method results in foo because I was looking for x and x is related to foo.
Is there a cleaner way than doing a loop to set index value. then setting a var when the index matches and pulling the item out of the list?
DanielLeong#6388 Thanks for your reply, Daniel. I understand how to set the history_stats template up with static start times. In my case, I want to use the daily calculated sunset time available from sun.sun. I am not sure how to get the daily calculated sunset hour/minute/second as the history_stats "start:" time. Do you have any thoughts in this regard? Thanks
Super excited to this release! Great work to all involved! πππ
There's no need to provide the start time in terms of H,M,S. It can accept a datetime directly. {{ state_attr('sun.sun', 'next_setting') | as_datetime - timedelta(hours = 3) }} will give you the datetime you want, if I understand your offset rightly.
@rose scroll Ok! I believe I see where you are coming from. Makes sense now. Ill give it a go! Thanks!
hello, anyone has a way of calling youtube's API to check view count and subscriber count on one channel?
found it:
- platform: rest
name: 'CHANNEL Subscribers'
resource: https://www.googleapis.com/youtube/v3/channels?part=statistics&id=CHANNELID&key=APIKEY
method: GET
value_template: '{{ (value_json["items"][0].statistics.subscriberCount | int) }}'
scan_interval: 600
Hey petro. I'm working on a next version of this (for a different appliance), and looking for some documentation to see if I can figure it out myself. Any suggestion where to look for how to figure out the list sorting, etc?
In short, I want to find the lowest range of 3 hours (instead of just the lowest hour), but I don't mind finding the answer myself, helps me learn π
Thatβs not easy to do. Thereβs a post on the forums where I solved that for someone
I also recently wrote a macro for that with some additional options
I can figure it out with new namespaces, but from what I learnt here yesterday I'm trying to avoid that
Any tips how to find that forum post? (keywords?)
I don't think you can do this without a for loop
I could of course loop through the existing list, and then only store the starting time of the 3-hour timespan, that sounds feasible
Whatever I did gave you the window with the lowest cost with a variable window size
E.g. you could get the 2 3 or 4 hour window with the lowest overall total
Yea looks like it
This was what I did:
{%- macro cheapest_hours(hours, start, end, include_tomorrow) %}
{%- set today = state_attr('sensor.energy_price_brabander', 'raw_today') %}
{%- set tomorrow = state_attr('sensor.energy_price_brabander', 'raw_tomorrow') %}
{%- set time_key, value_key = 'time', 'total' %}
{%- set it = include_tomorrow | default(false) | bool(false) %}
{%- set s = today_at(start) if start is defined else today_at() -%}
{%- set e = (today_at(end) if end is defined else today_at() + timedelta(days=1)) + timedelta(days=1 if it else 0) %}
{%- set str = today[0][time_key] is string %}
{%- set s, e = s.isoformat() if str else s, e.isoformat() if str else e %}
{%- set values = (today + (tomorrow if it else [])) | selectattr(time_key, '>=', s) | selectattr(time_key, '<', e) | list %}
{%- set ns = namespace(value=none, time=none) %}
{%- for i in values[:values|length-(hours-1)] %}
{%- set ix = loop.index0 %}
{%- set v = values[ix:ix+hours] | map(attribute=value_key) | average %}
{%- if ns.value is none or v < ns.value %}
{%- set ns.value = v %}
{%- set ns.time = i[time_key] %}
{%- endif %}
{%- endfor %}
{{ ns.time }}
{%- endmacro %}
You can do {{ cheapest_hours(4, '14:00', '19:00', True) }} for example
Will look at that one tomorrow or this weekend. But also nice bit of code.
Is there a way I can use templates to pull out a specific months energy usage from a total_increasing entity?
I want to be able to send an email every month showing energy usage and costs for that month, for tax purposes
I'm hacking it at the moment with a utility meter that resets monthly, and sending the email at 11:59pm on the last day of the month before the meter resets
but it occurs to me there must be a more elegant way of achieving the same outcome
Templates can't access history, you're limited to integrations, like a SQL sensor, history_stats, statistics or utility_meter
hey guys, i want an automation to mute my tv when ads appear on youtube, and i've got most of it thought out and concept tested, but not all
i want a way to store specific attributes and compare them when things have changed - for example when watching youtube there's a media duration to say how long the media is, so if the media duration changes while the name of what's playing doesn't change, that means an ad has appeared, and would be a time to trigger the mute_tv script i have
how would i store the media duration of a video and then compare it to a new value when it changes?
Probably an input_text/input_number
ah, so i could store the media name/duration as an input helper and then compare against it? awesome, thanks!
yup, you can
wait, is this a bug? {% set dev_id = device_id('') %} {{device_entities(dev_id)}}
doesnt really matter whats in the quotes there, as long as it doesnt exist in the system, it lists over 2000 entities....
A Utility Meter is the easiest way to do this. No template needed. I don't understand why it needs a hack? Maybe I'm missing something?
you can of course send the data on the 1st of the next month, and use the previous_period attribute of the utility_meter
that's what I was thinking
Itβs only a bug if it lists devices without device_ids and you put letters in the quotes. An empty string will return all entities without devices
a, just wroteup this issue: https://github.com/home-assistant/core/issues/90573
yes, it also does it with {% set dev_id = device_id('thisdoesnotexist') %} {{device_entities(dev_id)|count}}
That's because all of those examples return null from device_id and you're using that as the input to device_entities
Ah, I did not notice that. Thanks
the device_id() crap hid it
Made note of that in the issue, @floral shuttle you should probably close that.
I noticd that, and what NSX says, it just seems very odd. Ive added a new reply there, hoping it makes things clearer on my part
I would say, if your scenario is looking to guard against a non-existent device, you should have a check on the return value of device_id and handle appropriately. device_entities can't know the whole scope of your problem, it just knows you're passing in none as the param to it.
It's expected because if you want to get a list of all entities without a device you provide device_entities(None).
been like that since day 1 and was part of the design
I thought it was an empty string with my first reply to you, which was me remembering incorrectly.
Either way, the functionality to get all entities without a device_id is expected
right, so summarizing: provide an existing device_id, and its lists the entities of that device_id, provide a non existing device_id (or an empty for that matter), and it returns all entities without a device
You're focusing on device_id as a function, but you wrote the issue up against device_entities
device_id('sdjflakjsdfl;sa') returns None
that's expected
device_entities(None) returns entities without devices
that's expected
Combining them is up to you, the user
Thats what I meant to summarize...
so if you don't want to get None devices
ok final question in this matter then: can we list all entities with devices too? as in the opposite of{{device_entities(None)|count}}
{% if device_id('sldfjalsdkjf') %}
{{ device_entities(device_id('akldjfl;ajsf;d')) }}
{% endif %}
Reject the ones with none
2 ways
Constructing it
{{ states | map(attribute='entity_id') | map('device_id') | reject('none') | unique | map('device_entities') | map(attribute='0') | unique | list }}
or rejecting none
rejecting none requires a generator in a generator
Or creating the list in a variable
er no ( to my comment)
that construction takes along time compared to the None version above
{{ states | rejectattr('entity_id', 'in', device_entities(none)) | map(attribute='entity_id') | list }}
Yeah, it's alot of generators
regardless, w/ states in the template, you're throttled to 1 update per minute
probably an error in the combining one
I wouldn't use that anyways, just use the rejecting one
I can take out the | map(attribute='0') | unique and the results remains the same
o dear never saw this before:.....
you're jumping to conclusions really now. lot of entities alright, but the system is fine
The timing for the 2 functions on my system is roughly .01 microseconds different
I have 1300 entities and a beefy computer
π€·ββοΈ
I'm assuming you're running on a non beefy computer with 4k entities based on above
i5 w/ 8gb ram
this is the template causing the delay:```
{{ states | map(attribute='entity_id')
| map('device_id')| map('device_entities') | list|count }}
going to get lots of dupes there
so better put the | map(attribute='0') | unique back in then....
might have made a typo before, this is what I am getting now
shows the templates better
if you really want to sum them use:
{{ states | map(attribute='entity_id') | map('device_id') | reject('none') | map('device_entities') | sum(start=[]) | unique | list }}
not what I posted before
Will it be the string 'none'?
no, you want to use that over reject('eq', none)
it's a built in test
'xxx' is none
Ah, right
You can also use select() in this case I guess
Unless there are device ids which would be falsely
what exactly does the sum template do? because it returns yet another outcome..
and that other outcome is closer to the truth
The sum(start=[]) adds the lists together to one list
the reject('none') is the problem in the summation template.
and the summation is wrong because of it
not sure what the problem is
I think there may be a problem with device_id
well, I've added the {{ states | rejectattr('entity_id', 'in' , device_entities(none)) | map(attribute='entity_id') | list|count }} to the issue tracker for reference, and closed.
if this is something else, it might need a separate issue
yes, that's the route I would go
there's something odd going on with device_id in map
I have a sensor that seems to report a time (when the washing machine will be done), how can i format that into a readable format that sasy in two hours or similar and use in the frontend?
What is the exact state of the entity?
First suggestion would be {{ relative_time(today_at(states('sensor.remaining_time'))) }}
Oh wait, relative time only works for datetimes in the past
this is how it reports the time 2023-03-31T15:36:50+00:00
Then as_datetime() instead of today_at()
No, that gives me the same result: {{relative_time(as_datetime(states('sensor.tvattmaskin_remaining_program_time')))}}
or not exactly the same 2023-03-31 15:36:51+00:00
feed it a timestamp, and use this
I use it for my alarm, and some other future timings π "Next alarm will be next monday, 3 april, in 2 days, 14 hours, and 27 minutes, at 06:20."
built on the amazing work by Petro
note I use this mainly in Dutch so the order/syntax of the date is a bit odd in English
i can try that, but it seems very complicated! Its weird though because if i visit the device page in HA it presents the time as "time left" and counts down if it's seconds
the UI takes datetimes and converts it to relative time for you
so if you leave it as 2023-03-31T15:36:50+00:00, the UI does the work
you change it, you have to do the work
what marius posted, is 'him doing the work'
i see. Altough it doesn't seem to work when i let the UI do the work. I'm using it in a mushroom template card however so maybe that's why i get the raw data?
that's because mushroom card doesn't have that work built in, anything made by custom authors will have custom results
Hi all, just got sent here with my problem and maybe you can help. I have a Aqara thermostat integrated with ZHA and would like to add a statistics graph based on set and measured temperature in a dashboard but can't access the actual temperatures in the statistics card configuration - any pointers?
yeah that's what i figured. Which makes getting "remaining time" into the frontent ui complicated
I would assume the normal mushroom cards output that correctly
it's the secondary info fields and template fields that wouldn't display it properly
yeah the normal mushroom entity card seem to handle it "as expected"
Yeah I just looked at the source and it does
so no "easy" way to get it into the template card then
same with secondary info
it's just template card that doesn't do it
no, there is no easy way. You have to calculate it
if it's in the past, you can use relative_time
luckily the integration exposes a progress sensor as well so all i have to do there is add % in the end π
Hello! I would like to convert a text sensor that I get from the charge level of my car into a numeric sensor.
I have an nspanel running with Esphome, and there is an error on the home page if the sensor returns, for example, "02:45".
does anyone have an idea how i could solve this? (I'm not a specialist...)
the best would be a conversion, for example, in numerical 2.45
That would be 2.75 hours
Yeah right! but for quick reading it would of course be easier.
I would say for quick reading 2:45 would work fine
this sensor from the car is somehow a timer or something. he counts down to zero. the nspanel with the blacky mas blueprint does not accept such a sensor on the homepage. That's why I thought of converting
All states are strings, why shouldn't it be able to display it
I don't know either, the nspanel doesn't open the homepage if this sensor is also to be displayed
if I remove this sensor, the display opens the homepage again
I don't know what kind of sensor it is. in the lovelace it is displayed like a clock or a timer or something. it shows how long it will take until the battery is fully charged.
the display is for example: "04:50 h".
and he actually means 4 hours 50 minutes
just can't be displayed on the homepage of the nspanel with esphome (and the blueprint).
is there any way to template a friendly_name using custom:auto-entities?
something like '{{entity.attributes.friendly_name}}'...
@oak ermine I converted your message into a file since it's above 15 lines :+1:
hi is there template for inverting the colour of a light? either in hs or in rgb I don't mind
these for example
hs_color: 30, 8
rgb_color: 255, 244, 234
for instance the inverse of red is cyan, etc
for rgb, the inverse is achieved by simply subtracting the value from the max value
255-x
I neeed a template to do this on the fly, cos the bulb changes colours 16 times a second
{% set r, g, b = state_attr('light.some_light', 'rgb_color') %}
{{ (255 - r, 255 - g, 255 - b) }}```
?
Hello, i'm having a heck of a time adding a serial sensor. I'm trying to read an arduino connected through USB. I've verified in the host OS that the serial command i'm looking for comes through. If i monitor the serial port, i recieve "{"red": "1"}". Here's what i have in config:
- platform: serial
name: "Remote_buttons"
serial_port: /dev/ttyACM0
baudrate: 9600
value_template: "{{ json_value.red }}"```
But when i look at the entity in HA, i just get status "unkown"
sorry, fell asleep. where do I put this?
just for the record, light.main is the one I want to invert, light.pulsar is the one I want to receive the inverted values
dunno, I don't know what you're doing nor do I have time to look into it. I suggest checking out the docs
the docs state we need a timestamp for that, to be able to use: entities: - entity: sensor.next_alarm_timestamp format: relative
so I went back to the template sensor I use, and noticed the device_class wasn't set. Adding device_class: timestamp errors though with File "/usr/src/homeassistant/homeassistant/util/dt.py", line 191, in parse_datetime return ciso8601.parse_datetime(dt_str) TypeError: argument must be str rendering the sensor unavailable.
i have a group with all my window sensors in it. i want to sent a notification to my mobile phone when iΒ΄m not at home and the group turns from off to on (window is opened). is there a way to see what window got opened?
{{ state_attr(trigger.to_state.entity_id, 'friendly_name') }} sends the friendly name of the group...
Just expand the group and select_attr to identify which members of the group has the state on?
that's outputting an integer. It needs to be a datetime
@quiet kite I converted your message into a file since it's above 15 lines :+1: