#templates-archived

1 messages Β· Page 34 of 1

floral shuttle
#

how odd.

#

check this:

marble jackal
#

That's why I left it in πŸ™‚

floral shuttle
#

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..

sonic ember
#

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

floral shuttle
#
{{as_timestamp([ns.spring,ns.fall]|min)|timestamp_custom('%A %-d %B %Y at %-H am')}}``` returns 'Sunday 26 March 2023 at 4 am'
sonic ember
#

Is it just "state: " and then my code?

floral shuttle
#

yes, its state, but the whole template needs another syntax and place

sonic ember
#

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 %}
floral shuttle
sonic ember
#

nested under sensor:

floral shuttle
#

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 %}```
sonic ember
#

yeah that's what I have πŸ™‚

#

I have a templates.yaml that already does the template: part

floral shuttle
#

o well, in that case you're good πŸ˜‰ thought you said 'nested under sensor:' and meant toplevel sensor: there

sonic ember
#

Nah, nested under sensor (which is also nested already) haha Thanks for the help

floral shuttle
#

you do have some strange |int'in there, on purpose?

sonic ember
#

No, funny indeed I have 2 different INT

#

hmmm.

floral shuttle
#

otherwise do: state: > {% set power = states('sensor.shellyplug_s_3ce90ed7cdb6_power')| int(0) %} {% if power <= 8 %} low {% elif power <= 26 %} medium {% else %} high {% endif %}

sonic ember
#

Ahh that looks more efficient indeed, thanks!

marble jackal
#

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

sonic ember
#

Another condition to do that, first checking for availability, or how would you go about it?

marble jackal
#
template:
  - sensor:
      - name: Ventilation Current Level
        unique_id: ventilation_level
        state: >-
          {{ }}
        availability: >-
          {{ states('sensor.shellyplug_s_3ce90ed7cdb6_power') | is_number }}
sonic ember
#

Ah, and if it's not available it will just return "unavailable" ?

marble jackal
#

Yep

sonic ember
#

Cool, thanks

dull burrow
#

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?

sonic ember
floral shuttle
#

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.

spark sundial
#

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 %}
inner mesa
#

You aren't providing an attribute in either state_attr call

#

Seems like you're using state_attr() when you wanted states()

spark sundial
#

ok lets see

#

it still dont show it

#

its saying not avalible

sonic ember
# floral shuttle

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

spark sundial
sonic ember
#

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
marble jackal
#

In your previous post you posted that is was null

#

So in that case it was defined

sonic ember
#

Hmm yeah, Something changed...

hardy basin
#

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()

marble jackal
#

I was just typing that

hardy basin
#

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
hardy basin
#

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>

halcyon fulcrum
#

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 }}'
inner mesa
#

they're called "tests"

marble jackal
inner mesa
#
{{ ["foo", "bar"]|select('contains', 'foo')|list }}

->

[
  "foo"
]
hardy basin
# inner mesa they're called "tests"

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...

inner mesa
#

you just want the first one?

#

[0]

#

or |first

hardy basin
#

|first is what I needed.

#

So where is the list of select operators?

inner mesa
#

again, "tests"

hardy basin
#

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.

silent vector
#

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?

hardy basin
#

Ended up with a much cleaner: thisLight: >- {{ device_entities(device_id( trigger.entity_id)) | select('contains','light.') | first }}

hardy basin
#

In a state_changed event...

silent vector
#

How would I find the parent?

#

01GWEZQT2H3DXHGGVTFEC9YPHE

#

What does that tell me? Lol how do I find what that correlates to

hardy basin
#

If the parent_id is null then it's the first in the chain. Otherwise it was triggered by the parent.

silent vector
#

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.

hardy basin
#

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" ...

silent vector
#

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?

hardy basin
#

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.

silent vector
#

Yeah I'm trying to see if a specific automation turned lights on or did another do it.

sonic ember
#

How do I convert a timestamp (in numbers, like this: 1679864400) to a timestamp that HA can read?

silent vector
#

I see how to tie them now. I tested it. checking state changed context id and the automation triggered context id.

sonic ember
#

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()

marble jackal
#

@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

hardy basin
#

Is there a way to get a list of all entity ids in a domain?

#

I would imagine something like domain_entities('sensor')

rich dust
#

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 %}
marble jackal
hardy basin
marble jackal
#

{{ states.sensor | selectattr('state', 'eq', 'your specific state') | map(attribute='entity_id') | list }}

hardy basin
#

'Click'

cold crag
#

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)

astral pebble
#

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

floral shuttle
floral shuttle
#

btw, you dont list entities, only the used domains?

hardy basin
#
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']

floral shuttle
#

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

silent vector
spice crow
#

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?

fossil venture
#

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 }}"

rich dust
#

Van Gogh&#39;s is there a way to render this correctly with jinja? It being sent to HA like this.

marble jackal
#

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

floral shuttle
#

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 ?

marble jackal
#

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()}}
floral shuttle
#

uhm, let me phrase humanely: loop to find the first 3 tm_isdst changes, and list the first 2

floral shuttle
# marble jackal with your code: ```py {%- set ns = namespace(previous=3,spring=none,fa...

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

marble jackal
#

just took something large enough πŸ™‚

floral shuttle
#

seems we never have to go beyond + 1 week

marble jackal
#

373 then? 366 + 7

floral shuttle
#

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..

marble jackal
#

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 %}

floral shuttle
#

great, I'll move to that for now then. thnks!

#

will update the post in the community with that

marble jackal
#

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.

floral shuttle
#

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 %}

marble jackal
#

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

floral shuttle
marble jackal
#

yeah, sure. I still hope it will change to not changing time at all though

floral shuttle
#

+1 to that..

spice crow
floral shuttle
#

never realized we could change: mdi:{{(now().timetuple().tm_isdst == 1)|iif('update','history')}} to mdi:{{(now().timetuple().tm_isdst)|iif('update','history')}} ... clever!

marble jackal
#

0 is falsely so that works πŸ™‚

#

I did notice that that version is off by an hour, it was correct yesterday..

silent vector
#

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 }}"
floral shuttle
#

ah the abominable hour....

mighty ledge
#

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.

marble jackal
#

Yeah, I should not have tried to reinvent the wheel

mighty ledge
#

I think I went through 3 iterations to get it working essentially

#

which spanned a year

#

It broke every DST shift

plain magnetBOT
#

@half pendant I converted your message into a file since it's above 15 lines :+1:

half pendant
#

i just realized my issue. Nevermind πŸ™‚

mighty ledge
silent vector
#

In a service call

mighty ledge
#

inside target or outside?

#

@silent vector ^

silent vector
#

Will that Nested loop even work?

#

I tried to set the item to sensor to avoid item confusion on the second loop.

mighty ledge
#

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

silent vector
#

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

mighty ledge
#

so just generate the list before hand

silent vector
#

To map unavailable sensors to switch entities.

mighty ledge
#

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

silent vector
#

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?

half pendant
#

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?

mighty ledge
half pendant
#

in automations?

mighty ledge
#

Yes

half pendant
#

yeah. I managed to make the script! Thanks

mighty ledge
#

ok, then what's the problem? Call the script passing your variable

mighty ledge
#

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 ] %}
half pendant
silent vector
#

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?

mighty ledge
#

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 }}"
silent vector
#

I see now. The list items would contain the unavailable_sensors and service and data for each service?

mighty ledge
#

You can store whatever you want.

dry ether
#

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)

mighty ledge
dry ether
mighty ledge
#

Check the ids in relation to automation ids

dry ether
#

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!

silent vector
thorny snow
#

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" }}

marble jackal
#

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

mighty ledge
marble jackal
#

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

mighty ledge
#

I don't use the UI, so i'm deferring to you

thorny snow
#

Yes, as @marble jackal notes, it was my bad use of quotation marks

marble jackal
#

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

halcyon fulcrum
#

Any other method is ok also but that's what I had in mind.

mighty ledge
halcyon fulcrum
#

Thanks! That was much easier than I thought. Maybe someday I

#

...I'll master the language

mighty ledge
#

as soon as you do, we'll add something that makes it easier or more confusing

halcyon fulcrum
#

learning curve is steep and endless πŸ˜„

plain magnetBOT
final sun
#

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 πŸ‘

marble jackal
#

the result was already a string

swift gull
#

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..

plain magnetBOT
#

@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:

bitter sigil
#

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 ?

ionic valley
#

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}}
mighty ledge
mighty ledge
ionic valley
#

yeah, I have an end at the bottom, didn't include here cause I have 24 hours of if statements

mighty ledge
#

how can we help you fix it if we can't see the whole template in your template sensor

ionic valley
#

{% endif %} at the bottom

mighty ledge
# bitter sigil Defaults of 2?

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

bitter sigil
#

used this as well: state: >
{{ (states("sensor.envoy_current_power_production") | float | round(2)) - (states("sensor.envoy_current_power_consumption") | float | round(2)) }}

mighty ledge
#

that will have the same problem

#

except it will error on startup

#

because you aren't providing a default

bitter sigil
#

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?

mighty ledge
#

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

bitter sigil
#

I mean, not even this works: state: >
{{ states("sensor.envoy_current_power_consumption") }}

mighty ledge
#
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 }}
bitter sigil
#

Should that return 1026 ?

mighty ledge
#

Are you sure you're looking at the correct entity?

bitter sigil
#

I can share my screen if that would help, or go in voice chat if you got a couple of minutes to spare

mighty ledge
#

can you take a screenshot of each entity you're pulling information from in the developer tools -> states page?

plain magnetBOT
#

@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.

mighty ledge
#

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

bitter sigil
#

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 }}

mighty ledge
#

your template uses sensor.envoy_current_power_consumption

bitter sigil
#

tthose are the ones I am using, I just removed the serial numer

mighty ledge
#

ok then show a screenshot of sensor.totalpowerfromsolar

bitter sigil
#

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:

plain magnetBOT
#

@bitter sigil I converted your message into a file since it's above 15 lines :+1:

mighty ledge
#

uh wait, you're missng up how you can configure things

#

you can't put a template sensor inside your card configuration

bitter sigil
#

And now I feel like an even bigger looser.... For this, just the "Quick reload" or a full restart of HA?

mighty ledge
#

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

bitter sigil
#

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

mighty ledge
#

right, so you have to create it

bitter sigil
#

so add a templates: !include templates.yaml to thhat file and then create a templates.yaml and put only the sensor info there?

mighty ledge
#

sure you can do it that way

#

just make sure you add a - before sensor:

#

e.g.

#
- sensor:
  - name: ...
    unique_id: ...
bitter sigil
#

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

mighty ledge
#

it's template:

bitter sigil
#

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 }}
mighty ledge
#

yep, restart and sensor.totalpowerfromsolar should appear

bitter sigil
#

again full restart or just the yaml?

#

ok, my bad...

mighty ledge
#

just restart HA

#

you don't need to reboot

#

reloading yaml will not work

bitter sigil
#

yeah, fixed a typo...

mighty ledge
#

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

bitter sigil
#

got the correct reading now, and the sensor appears in the STATES

mighty ledge
#

alright, then you should be good from here

#

that was the hard part

bitter sigil
#

can you point me to where these math definitions for floar and round and the likes are?

#

and things like is_number

mighty ledge
#

it's in the topic

plain magnetBOT
#
The topic of this channel is:

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

mighty ledge
#

FYI the code in {% %} and {{ }} is jinja

bitter sigil
#

I can talk in fortran and cobalt, but this is giving me a headache. Not the syntax, but the math/calculation parts of it.

mighty ledge
#

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

bitter sigil
#

that documentation was the one I was looking for. Thank you kind Sir.

spice crow
bitter sigil
#

@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?

mighty ledge
#

Then the template is unavailable

bitter sigil
#

Can we default it to 0 instead of it becoming unavailable?

bitter sigil
silent vector
silent vector
silent vector
#

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

silent seal
#

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

mighty ledge
#

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

silent vector
mighty ledge
#

you also aren't using trigger_object_id anywhere

#

so notsure what thats for

silent vector
#

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.

silent seal
#

Here's a novel idea: Why not create template sensors? And in the attributes just specify which switch is associated with it.

silent vector
#

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.

mighty ledge
silent vector
#

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 }}"

mighty ledge
#

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

silent vector
#

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.

mighty ledge
#

they are number entities?

mighty ledge
#

Ok, so why do you have 4 number entities

silent vector
#

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 ^

mighty ledge
#

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

silent vector
#

Then the value would be calculated based off whether color was in the entity_id It's 0 else 100 (brightness)

mighty ledge
#

binary_sensor.upstairs_bathroom_presense_detector_motion_sensor is spelled wrong

silent vector
#

Is it lol.

#

Oops

#

It is

#

That would wreck this

mighty ledge
#

not really, i'll show you why in a sec

#

well, Just fix it tho

#

makes the regex easier

silent vector
#

Fixing now.

#

I do have an else for splitting on _illuminance as one sensor could be sensor.office_illuminance_sensor

mighty ledge
#

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

silent vector
#

Just a set value on the number entity. Color entities value would be 0 else 100 which is for the brightness entities.

mighty ledge
#

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

silent vector
#

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?

mighty ledge
#

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?

silent vector
#

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.

mighty ledge
#

so both are being set to 100?

mighty ledge
#

because you have unavailable/available yet your current code only looks for unavailable.

silent vector
#

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

mighty ledge
#

what's the entity_id of the button that you're pressing

silent vector
mighty ledge
#

Ok, here's the whole automation

#

@silent vector

#

should just work

silent vector
#

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?

mighty ledge
#

it's going to try every loop to restart them once

#

limiting it to 5 will require a counter

silent vector
#

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.

mighty ledge
#

it does everything

silent vector
#

Although if sensor.office_illuminance_sensor is unavailable what does it do? Would it still do a restart?

mighty ledge
#

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} }}
silent vector
#

Yeah just restart. Wondering how to gather a notification together for what's unavailable. Without sending one every minute lol.

mighty ledge
#

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

silent vector
mighty ledge
#

You'd get instant notifications that only happen once, and then you could limit it to 5 restarts.

mighty ledge
#

instead of using the binary_sensor state changes as the trigger, you're running this minutely thing

silent vector
#

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

mighty ledge
#

and you can guard by looking at to/from states

silent vector
mighty ledge
#

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

silent vector
#

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?

mighty ledge
#

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

silent vector
#

Oh that makes sense didn't notice that. Perfect then this does literally everything.

mighty ledge
#

Yes

silent vector
#

Learning so much about what's possible in Jinja over the last year from this channel.

#

What's this var? trigger line 86

mighty ledge
#

There is no line 86?

inner mesa
silent vector
#

Lol 18*

#

I pasted this into my code editor

mighty ledge
#

that's the trigger object

silent vector
#

Ah got it. Now that makes sense. When would it be none?

mighty ledge
#

it's never none

#

however from_state will be none at startup

#

well, it just won't exist

marble jackal
#

shouldn't there be a small delay in the repeat? otherwise you'll just spam the button 5 times in 3 microseconds

mighty ledge
#

yes there should

#

delay after

#

not before

silent vector
#

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

silent vector
mighty ledge
#

no

#

HA is asynchronous, so it can be smaller

silent vector
#

That is super fast. Pretty cool to know.

plain magnetBOT
#

@sonic ember I converted your message into a file since it's above 15 lines :+1:

sonic ember
#

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 πŸ™‚

sonic ember
#

It loops through the list and stores the time with the lowest value

mighty ledge
#

that's it?

sonic ember
#

Yep, pretty much

#

Oops

mighty ledge
#
{% 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) }}
sonic ember
#

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

mighty ledge
#

πŸ€·β€β™‚οΈ it's over complicated

#

you can just get the lowest object and then use it how you want to

sonic ember
#

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

mighty ledge
#

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 %}
sonic ember
#

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"

plain magnetBOT
#

@celest tinsel I converted your message into a file since it's above 15 lines :+1:

mighty ledge
#
{% 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 %}
sonic ember
#

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 %}
mighty ledge
#

why'd you put as_datetime in the time_threshold

#

your times are strings

sonic ember
#

Apparently my dates are datetimes

#

I got the TypeError without that

mighty ledge
#

ok, well you provided a list that showed them as strings

#

if they are datetimes, this is easier

sonic ember
#

@deep marsh yes I did! And it works perfectly, except for a 2 hour offset.

mighty ledge
#
{% 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 %}
deep marsh
#

Never mind, I saw that you do not use the helper in the code above.

sonic ember
sonic ember
mighty ledge
#

You should avoid namespace if you can, as it creates new memory

sonic ember
#

Ah, so this is easier on the system resources?

mighty ledge
#

if you run it alot yes, if you don't... it's not really a big deal

sonic ember
#

This will be run about 4 times a day max

#

But still, there's always more ways to do something πŸ™‚

mighty ledge
#

There was a typo, fixed it above

sonic ember
#

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.

mighty ledge
# sonic ember Ok, found the filter that worked, but still get an empty list. It seems like it'...
{% 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 %}
sonic ember
#

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 πŸ™‚

mighty ledge
#

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 %}
deep marsh
#

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.

cinder lotus
#

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

inner mesa
#

you're multiplying a state, which is a string

#

as it's always been

#

you're turning "4" into a float

cinder lotus
#

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.

inner mesa
#

that's what it sounded like

#

there are several links in the channel topic

#

states('sensor.electricity_delivery_15m')|float(0) * 4

inner mesa
#

it's never been okay to treat a state as a number - it's always been a string

mighty ledge
cinder lotus
#

But sensor.electricity_delivery_15m isn't a state, it gives values

inner mesa
#

it is a state

#

clearly

#

and states are strings

cinder lotus
#

I don't want to discuss. You know much better!

deep marsh
mighty ledge
#

You have duplicate times?

#

or were you just looking at the TOD?

deep marsh
#

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.

mighty ledge
#

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

cinder lotus
#

@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?

inner mesa
#

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

cinder lotus
#

The state of ''sensor.power_delivered'' is 0.000

inner mesa
#

float got invalid input 'unavailable'

#

it definitely got "unavailable" for one of the sensors you're using

cinder lotus
#

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

marble jackal
#

which are?

cinder lotus
#

Hmmm. I hided the lines by command '#', restarted HA, no errors anymore. Removed the '#' and no errors anymore...

floral shuttle
# mighty ledge ``` {% set hour_threshold = 24 %} {% set time_threshold = now().replace(minute=0...

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

mighty ledge
plain magnetBOT
#

@mint prairie I converted your message into a file since it's above 15 lines :+1:

mint prairie
#

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
floral shuttle
#

a time/value combination suffices in all scenarios?

floral shuttle
#

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}]

marble jackal
floral shuttle
#

looking for something like: a these times, your prices are below average etc etc

floral shuttle
#

storing unique data under 2 identifiers within the same context might even be an issue....?

marble jackal
#

An issue for what?

floral shuttle
#

DB sanity.

marble jackal
#

I don't see issues for that, they are individual list items with a price value and two datetimes

floral shuttle
#

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?

floral shuttle
# mighty ledge ``` {% set hour_threshold = 6 %} {% set time_threshold = (now().replace(minute=0...

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

sage sluice
#

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...

floral shuttle
#

you've got to think about the order of operations PEMDAS/BODMAS πŸ˜‰

sage sluice
#

So was I trying to round a string or something?

floral shuttle
#

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

sage sluice
#

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?

floral shuttle
#

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.

sage sluice
#

Ah, filter vs. function, that's why it is different.

marble jackal
#

Using it as a function can avoid issues with order of operations

#

int(3/14, 0) for example

sage sluice
#

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?

floral shuttle
sage sluice
#

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.

marble jackal
#

The float function is not needed there

#

The result will be a float

sage sluice
#

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?

floral shuttle
#

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.

silent vector
#

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]
sage sluice
#

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))}}

slender laurel
#

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

mighty ledge
mighty ledge
#

the if section only accepts templates or conditions, not actions.

silent vector
#

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.

mighty ledge
# sage sluice But why do you have to truncate it first to round it? For example, this does not...

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) }}
silent vector
mighty ledge
slender laurel
dim jay
#

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?

lofty mason
#

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.

dim jay
#

managed to rewrite it to get timestamp (even though weirdly formated), testing it now.

#

correct hour/minute but 1900 january 1 πŸ˜„ haha

lofty mason
#

today_at() function would probably be helpful.

dim jay
#

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

lofty mason
#

today_at(value) converts a string containing a military time format to a datetime object with today’s date in your time zone.

dim jay
#

{{ today_at(strptime(states('sensor.alarm_time'),'%H:%M'))}} gives ValueError: could not convert datetime to datetime: '1900-01-01 15:20:00'

lofty mason
#

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

dim jay
#

cool

#

gonna test it

mighty ledge
#

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.

dim jay
#

how to do force an update?

#

how do i*

dim jay
#

any link where i can read up on the new template entity format?

plain magnetBOT
dim jay
#

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

spark flame
#
  - 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

dim jay
#

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`
spark flame
#

what is providing that sensor.alarm_time_fix?

floral shuttle
#

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 %}
dim jay
#

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() }}"

spark flame
#

Ahh seems a bit overcomplicated with the double template sensors

dim jay
#

well alarm_time is set from input_numbers, alarm_time_fix was just a way to get automation to run

mighty ledge
#

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

dim jay
#

uhm

spark flame
#

Then just an automation watching for that trigger event?

mighty ledge
#

no, no automation needed

spark flame
#

WHat happens when that triggers tho lol

mighty ledge
#

the template updates

#

it's a template sensor

spark flame
#

But isn't the whole point of having a time-based event to do something else?

#

Hence the automation bit anyways

mighty ledge
#

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

spark flame
#

Ahh I thought he was just trying to trigger an automation at a specific time

mighty ledge
#

yes he can

#

with

#
trigger:
- platform: time
  at: sensor.alarm_time
#

but he needs the template sensor first

dim jay
#

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).

mighty ledge
#

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

dim jay
#

think i got it now

#

i use folders to not clutter my configuration.yaml

floral shuttle
#

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.

mighty ledge
#

πŸ€·β€β™‚οΈ 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

dim jay
#

because im an idiot? πŸ™‚

floral shuttle
#

might because of the Dashboard. I have them both..... some in my household prefer the slider, some prefer the datetime

dim jay
#

or didnt know about input_datetime

mighty ledge
#

simply create the input_datetime and use the following trigger

- platform: time
  at: input_datetime.alarm_time
mighty ledge
#

not knowing things doesn't make you an idiot

#

it's room for learning

dim jay
#

so i add input_datetime: to configuration.yaml then create a variable like "alarm_time" and use that in my config?

mighty ledge
#

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

floral shuttle
spark flame
#

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

floral shuttle
#

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

spark flame
#

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

floral shuttle
#

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

dim jay
#

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 πŸ™‚

spark flame
#

Having a 10-minute fade in to full brightness is like magic for waking up

dim jay
#

Please share code how you faded that

#

Seems awzm

spark flame
#

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

dim jay
#

Figured as much. Doing it in a script with delays?

spark flame
#

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

mighty ledge
#

Assuming that transition is supported by your hardware

spark flame
#

That too

#

Some lights are terrible at 1%

mighty ledge
#

Ha pretends to do it in that case but nothing occurs

spark flame
#

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

half pendant
#

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?

plain magnetBOT
#

@half pendant I converted your message into a file since it's above 15 lines :+1:

silent reef
#

Good evning πŸ™‚ @mighty ledge you where so kind to help me a while ago. Can you meaby confirm a automation ? πŸ™‚

mighty ledge
sonic ember
sonic ember
mighty ledge
sonic ember
#

I was surprised that rejectattr didn't work but you used selectattr instead

#

can you explain why?

mighty ledge
#

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

sonic ember
sonic ember
#

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 πŸ™‚

eternal hazel
#

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

bitter sigil
#

what is the difference between "name:" and "friendly_name:"?

mighty ledge
#

Nothing, just what the yaml requires

mighty ledge
bitter sigil
#

it shows the name, not the friendly name. Can the "name:" have spaces? or should I use spaces inside quotes or double qoutes?

eternal hazel
bitter sigil
#

so no need for friendly name at all? and what about using quotes?

eternal hazel
mighty ledge
eternal hazel
#

But the challenge has been to grab the location of the client that’s loading the dashboard

mighty ledge
#

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

eternal hazel
mighty ledge
eternal hazel
#

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

mighty ledge
#

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

eternal hazel
#

Since there are only a few, it might be easier to just build out 6 dashboards

mighty ledge
#

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

bitter sigil
#

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

eternal hazel
marble jackal
#

@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 πŸ™‚

mighty ledge
marble jackal
#

Ah sure πŸ™‚

drowsy grove
#

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) }}

rose scroll
silent vector
#

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?

drowsy grove
#

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

hollow girder
#

Super excited to this release! Great work to all involved! πŸ˜πŸ˜ŠπŸ˜ƒ

rose scroll
drowsy grove
#

@rose scroll Ok! I believe I see where you are coming from. Makes sense now. Ill give it a go! Thanks!

fervent ravine
#

hello, anyone has a way of calling youtube's API to check view count and subscriber count on one channel?

fervent ravine
sonic ember
mighty ledge
marble jackal
#

I also recently wrote a macro for that with some additional options

sonic ember
#

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?)

marble jackal
#

I don't think you can do this without a for loop

sonic ember
#

I could of course loop through the existing list, and then only store the starting time of the 3-hour timespan, that sounds feasible

marble jackal
#

Jep

#

That's what I did

mighty ledge
#

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

sonic ember
#

I'll see what I can find on the forums, and otherwise I'll go looping πŸ™‚

mighty ledge
#

Yea looks like it

marble jackal
#

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

sonic ember
#

Will look at that one tomorrow or this weekend. But also nice bit of code.

fallow gulch
#

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

obtuse zephyr
clear mist
#

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?

obtuse zephyr
#

Probably an input_text/input_number

clear mist
#

ah, so i could store the media name/duration as an input helper and then compare against it? awesome, thanks!

obtuse zephyr
#

yup, you can

clear mist
#

that sounds perfect

#

thanks for that

floral shuttle
#

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....

sonic ember
marble jackal
#

you can of course send the data on the 1st of the next month, and use the previous_period attribute of the utility_meter

sonic ember
#

that's what I was thinking

mighty ledge
floral shuttle
#

yes, it also does it with {% set dev_id = device_id('thisdoesnotexist') %} {{device_entities(dev_id)|count}}

obtuse zephyr
mighty ledge
#

the device_id() crap hid it

#

Made note of that in the issue, @floral shuttle you should probably close that.

floral shuttle
#

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

obtuse zephyr
#

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.

mighty ledge
#

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

floral shuttle
#

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

mighty ledge
#

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

floral shuttle
#

Thats what I meant to summarize...

mighty ledge
#

so if you don't want to get None devices

floral shuttle
#

ok final question in this matter then: can we list all entities with devices too? as in the opposite of{{device_entities(None)|count}}

mighty ledge
#
{% if device_id('sldfjalsdkjf') %}
  {{ device_entities(device_id('akldjfl;ajsf;d')) }}
{% endif %}
marble jackal
#

Reject the ones with none

mighty ledge
#

or rejecting none

#

rejecting none requires a generator in a generator

marble jackal
#

Or creating the list in a variable

mighty ledge
#

er no ( to my comment)

floral shuttle
#

that construction takes along time compared to the None version above

mighty ledge
#
{{ states | rejectattr('entity_id', 'in', device_entities(none)) | map(attribute='entity_id') | list }}
mighty ledge
#

regardless, w/ states in the template, you're throttled to 1 update per minute

floral shuttle
#

those last 2 templates don't do the same btw

mighty ledge
#

probably an error in the combining one

#

I wouldn't use that anyways, just use the rejecting one

floral shuttle
#

I can take out the | map(attribute='0') | unique and the results remains the same

#

o dear never saw this before:.....

mighty ledge
#

you have a slow system

#

and alot of entities

#

downside of using cheap hardware

floral shuttle
#

you're jumping to conclusions really now. lot of entities alright, but the system is fine

mighty ledge
#

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

floral shuttle
#

this is the template causing the delay:```
{{ states | map(attribute='entity_id')
| map('device_id')| map('device_entities') | list|count }}

obtuse zephyr
#

going to get lots of dupes there

floral shuttle
#

so better put the | map(attribute='0') | unique back in then....

mighty ledge
#

No

#

don't use the summation one

#

the result still isn't matching

floral shuttle
#

might have made a typo before, this is what I am getting now

#

shows the templates better

mighty ledge
#

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

marble jackal
#

Will it be the string 'none'?

mighty ledge
#

no, you want to use that over reject('eq', none)

#

it's a built in test

#

'xxx' is none

marble jackal
#

Ah, right

#

You can also use select() in this case I guess

#

Unless there are device ids which would be falsely

mighty ledge
#

There's something going on for sure

#

the summation and rejection should match

floral shuttle
#

what exactly does the sum template do? because it returns yet another outcome..

mighty ledge
#

and that other outcome is closer to the truth

floral shuttle
marble jackal
#

The sum(start=[]) adds the lists together to one list

mighty ledge
#

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

floral shuttle
#

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

mighty ledge
#

yes, that's the route I would go

#

there's something odd going on with device_id in map

half pendant
#

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?

marble jackal
#

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

half pendant
#

this is how it reports the time 2023-03-31T15:36:50+00:00

marble jackal
#

Then as_datetime() instead of today_at()

half pendant
#

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

floral shuttle
#

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

half pendant
#

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

mighty ledge
#

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'

half pendant
#

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?

mighty ledge
#

that's because mushroom card doesn't have that work built in, anything made by custom authors will have custom results

eternal blaze
#

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?

half pendant
mighty ledge
#

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

half pendant
#

yeah the normal mushroom entity card seem to handle it "as expected"

mighty ledge
#

Yeah I just looked at the source and it does

half pendant
#

so no "easy" way to get it into the template card then

mighty ledge
#

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

half pendant
#

luckily the integration exposes a progress sensor as well so all i have to do there is add % in the end πŸ™‚

random crescent
#

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

inner mesa
#

If that's a time, 2:45 isn't 2.45

#

If it's 2 hours and 45 mins

marble jackal
#

That would be 2.75 hours

random crescent
#

Yeah right! but for quick reading it would of course be easier.

marble jackal
#

I would say for quick reading 2:45 would work fine

random crescent
#

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

marble jackal
#

All states are strings, why shouldn't it be able to display it

random crescent
#

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).

sonic vigil
#

is there any way to template a friendly_name using custom:auto-entities?
something like '{{entity.attributes.friendly_name}}'...

plain magnetBOT
stuck remnant
#

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

exotic grail
#
{% set r, g, b = state_attr('light.some_light', 'rgb_color') %}
{{ (255 - r, 255 - g, 255 - b) }}```
#

?

weak lake
#

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"
stuck remnant
#

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

exotic grail
#

dunno, I don't know what you're doing nor do I have time to look into it. I suggest checking out the docs

floral shuttle
# mighty ledge the UI takes datetimes and converts it to relative time for you

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.

sonic vigil
#

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...

rose scroll
mighty ledge
plain magnetBOT