#templates-archived

1 messages ยท Page 19 of 1

proud cradle
#

It's the today & tomorrow selection that somehow goes to default

mighty ledge
#

cause I made a booboo

#

and i'm being dumb

#

over complicating

#
          {% set currentPrice = states('sensor.electricity_price_total') | float %}
          {% set gridFees = states('input_number.electricity_grid_fees') | float %}
          {% set threshold = 0 %}
          {% set onRate = 0.6 %}
          {% set alwayOnBelow = 1 %}
          {% set neverOnAbove = 6 %}
          {% set ts = (now() - timedelta(hours=1)).replace(microsecond=0).isoformat("#", "milliseconds") %}
          {% set today = state_attr('sensor.tibber_prices', 'today') | default([]) %}
          {% set tomorrow = state_attr('sensor.tibber_prices', 'tomorrow') | default([]) %}
          {% set items = (today + tomorrow) | rejectattr('startsAt', 'lt', ts) | list %}
          {% set prices = items
              | rejectattr('total', 'none')
              | map(attribute='total')
              | sort
          %}
          {% set threshold = prices | select(prices | count * onRate) | first | default(0) + gridFees %}
          {% set threshold = min(neverOnAbove,max(alwayOnBelow,threshold)) %}
          {% set heater = items
              | rejectattr('startsAt', 'lt', ts)
          %}
          {% set ns = namespace(vars = []) %}
          {% for item in heater %}
            {% if item.total + gridFees < threshold %}
              {% set ns.vars = ns.vars + [{'value': 1, 'startsAt': item.startsAt}] %}
            {% else %}
              {% set ns.vars = ns.vars + [{'value': 0, 'startsAt': item.startsAt}] %}
            {% endif %}
          {% endfor %}
          {{ ns.vars }}
#

hmmm wait

proud cradle
#

TemplateRuntimeError: No test named 28.799999999999997.

mighty ledge
#

yes

#

sorry, brainfarting here give me a moment

proud cradle
#

hehe ๐Ÿ™‚

mighty ledge
#

what's the point of the last namespace

#

you just want a list of items that are below your threshold?

#

also, the gridfee addition can also be removed for just the threshold because you're adding it in both places

#

it's a moot calculation

proud cradle
#

True, I just copied another sensor I have. This one is used to mark when the heater will run on an ApexChart

mighty ledge
#

ok

#
          {% set currentPrice = states('sensor.electricity_price_total') | float %}
          {% set threshold = 0 %}
          {% set onRate = 0.6 %}
          {% set alwayOnBelow = 1 %}
          {% set neverOnAbove = 6 %}
          {% set ts = (now() - timedelta(hours=1)).replace(microsecond=0).isoformat("#", "milliseconds") %}
          {% set today = state_attr('sensor.tibber_prices', 'today') | default([]) %}
          {% set tomorrow = state_attr('sensor.tibber_prices', 'tomorrow') | default([]) %}
          {% set items = (today + tomorrow) 
              | rejectattr('startsAt', 'lt', ts)
              | rejectattr('total', 'none')
              | sort(attribute='total')
              | list
          %}
          {% set index = (items | count * onRate) | int %}
          {% set threshold = items[index].total if index < items | count else 0 %}
          {% set threshold = min(neverOnAbove,max(alwayOnBelow,threshold)) %}
          {% set ns = namespace(vars = []) %}
          {% for item in items %}
            {% set value = iif(item.total < threshold, 1, 0) %}
            {% set ns.vars = ns.vars + [{'value': value, 'startsAt': item.startsAt}] %}
          {% endfor %}
          {{ ns.vars }}
#

wait

#

fixing

proud cradle
#

prices I presume ๐Ÿ™‚

mighty ledge
#

there

proud cradle
#

index undefined

mighty ledge
#

ah shit, i deleted that line

#

try again

proud cradle
#

UndefinedError: 'prices' is undefined

mighty ledge
#

yeah try again

proud cradle
#

Boom!

mighty ledge
#

man, i'm getting worse at coding without an IDE

proud cradle
#

That code is for sure more compact than what I managed to whip up, thanks again ๐Ÿ™‚

mighty ledge
#

it's not really about being compact, it's about using looping over and over

#

you want to minimize loops

#

you need to have 2 because you're calculating the threshold

plain magnetBOT
proud cradle
#

I'm trying to convert your code to the sensor I just posted above but I don't understand why I'm not allowed to map a value?

#

I get the entire array in items, with all properties. I just need total.

#

UndefinedError: 'float object' has no attribute 'total'

mighty ledge
#

when you map it, it changes the object

#

what are you tying to change? You shouldn't need to map it

proud cradle
#

It takes the current price and compares with the threshold to see if the heater should run or not right now

#

So simple version of the first sensor

#

just binary on/off

mighty ledge
#

post what you're trying

proud cradle
#
        {% set currentPrice = states('sensor.electricity_price_total') | float %}
        {% set gridFees = states('input_number.electricity_grid_fees') | float %}
        {% set threshold = 0 %}
        {% set onRate = 0.6 %}
        {% set neverOnAbove = 6 %}
        {% set alwayOnBelow = 1 %}
        {% set prices = (state_attr('sensor.tibber_prices','today') + state_attr('sensor.tibber_prices','tomorrow'))
            | rejectattr('total', 'in', [None])
            | rejectattr('startsAt', 'lt', (now().timestamp() - 3600) | timestamp_custom('%Y-%m-%dT%H:%M:%S.000%z'))
            | map(attribute='total')
            | sort
        %}
        {% set threshold = prices[(prices | count * onRate) | int] + gridFees %}
        {% set threshold = min(neverOnAbove,max(alwayOnBelow,threshold)) %}
        {{ (threshold > currentPrice) and (currentPrice < neverOnAbove) }}
#

That's the original, I just wanted to replace the loop with yours

mighty ledge
#
          {% set currentPrice = states('sensor.electricity_price_total') | float %}
          {% set threshold = 0 %}
          {% set onRate = 0.6 %}
          {% set alwayOnBelow = 1 %}
          {% set neverOnAbove = 6 %}
          {% set ts = (now() - timedelta(hours=1)).replace(microsecond=0).isoformat("#", "milliseconds") %}
          {% set today = state_attr('sensor.tibber_prices', 'today') | default([]) %}
          {% set tomorrow = state_attr('sensor.tibber_prices', 'tomorrow') | default([]) %}
          {% set items = (today + tomorrow) 
              | rejectattr('startsAt', 'lt', ts)
              | rejectattr('total', 'none')
              | sort(attribute='total')
              | list
          %}
          {% set index = (items | count * onRate) | int %}
          {% set threshold = items[index].total if index < items | count else 0 %}
          {% set threshold = min(neverOnAbove,max(alwayOnBelow,threshold)) %}
          {{ threshold < currentPrice < neverOnAbove }}
raw pumice
#

Has anyone an idea to to prevent resets of "total_increasing" sensors`?

raw pumice
#

is this problem specific to energy? until the templare-sensor went deprecated for mqtt-devices it was a template

#

but ok, i'll post it there

mighty ledge
#

i have no idea what your'etalking about

#

none of those have been deprecated

#

can you point out the deprecation you're referring to @raw pumice

proud cradle
#

set threshold = items[index].total if index < items | count else 0
What does this actually do, you have a value infront of a if statement?

#

Is that if reversed so you define the true part before and else after?

marble jackal
#

It's does the same as:

{% if index < items %}
  {% set threshold = items[index].total %}
{% else %}
  {% set threshold = 0 %}
{% endif %}
#

But if first checks the if statement, and then performs the part in front of it

mighty ledge
#

ya, that

#

in-line if statement

proud cradle
#

That's not confusing at all ๐Ÿคช

mighty ledge
#

lol, it's not if you learn it ๐Ÿ˜‰

#

every language has an inline if statement

marble jackal
#

Well, you can just read it, and it tells you what it does ๐Ÿ™‚

mighty ledge
#

pythons is pretty readable

#

other languages, not so much

proud cradle
#

$x == 1>0 ? true : false;
Php is soooo readable ๐Ÿ™‚

mighty ledge
#

e.g. threshold = (index < items) ? items[index].total : 0;

marble jackal
#

it's a bit like iif(), but in that case both the true and else part will be rendered, so that will throw an error if there are not enough items

mighty ledge
#

@proud cradle read it left to right

#

like a sentence, it'll make sense.

#

that's python

#

it's meant to be read outloud

#

something if condition else something_else

proud cradle
#

I think there is an issue in the recection part of your code @mighty ledge , it seams like it keeps values older than now?

mighty ledge
#

I just altered your last code

#

which didn't filter out anything older than now

#

it only chose things older than now

#

so if you only want things greater than now, change the lt to gt

proud cradle
#

It still returns 48 elements?

#

This is for example returned
{'total': 4.0352, 'startsAt': '2022-12-05T08:00:00.000+01:00', 'level': 'NORMAL'}

#

The items array needs to contain only values => now

mighty ledge
#

ok, then change the selectattr to >=

#

I just copied what you had

#

FYI

#

and you had, lt which is less than

#

or maybe you're referring to your new sensor? anways, simply change the lt to >=

proud cradle
#

Yeah the binary sensor

#

But something is going on. The original code (pasted above) {{ prices | count }} == 33

While the new code returns 48 (items | count)

#

Today + Tomorrow in total will be 48 hours (items)

#

So the reject part can't be working

mighty ledge
#

add the gridfees back, maybe it's making a difference

#

I forgot we added the hour, so it should still be 'lt'

proud cradle
#

Found the issue

#

Was isoformat("#", "milliseconds")
Should be to work isoformat("T", "milliseconds")

mighty ledge
#

๐Ÿ‘

atomic sedge
#

Hi guys, I have a dashboard with three camera's on it. I want to have one camera enable based on a switch setting. I've created a jinja2 template but I'm unable to get proper placement of my code. Thanks in advance for helping me out!

#
  - title: Home
    cards:  
      - type: picture-entity
        entity: camera.meadow
      - type: picture-entity
        entity: camera.driveway
      {% if is_state('switch.camera-monitoring','on') %}
      - type: picture-entity
        entity: camera.garden
      {% endif %}```
mighty ledge
#

you can't template like that

#

templates only go in fields

#

not around fields

marble jackal
#

conditional card ๐Ÿ™‚

mighty ledge
#

e.g.

field: >
  {{ in the field }}

not

{% .. %}
  field: ...
{% .. %}
atomic sedge
marble jackal
#
  - title: Home
    cards:  
      - type: picture-entity
        entity: camera.meadow
      - type: picture-entity
        entity: camera.driveway
      - type: conditional
        conditions:
          - entity: switch.camera-monitoring
            state: "on"
        card:
          type: picture-entity
          entity: camera.garden
atomic sedge
atomic sedge
shell fractal
#

What sensor is this? What is its purpose? It's quite complicated, really.What sensor is this? What is its purpose? It's quite complicated, really.

mighty ledge
thorny snow
#

I tried the trigger based template sensor you suggested, and it seems to work nicely, thanks! I would need a little help on how to proceed. Do I have an ever growing list of changes attributes for all sensors that had a state change?

thorny snow
#

Silly question, sorry. Since it is a python dict, there cannot be duplicate keywords, thus the list is limited to the number of entities listed in the trigger, right?

thorny snow
#

When I expand this, I get the state, and a list of all attributes recursively (list of changes and friendly_name), can I use selectattr() the get the changes dict only?
[<template TemplateState(<state sensor.nominal_change_history_2=OK; changes=binary_sensor.1_119_allapot_dbz=2022-12-05T13:03:24.343802+00:00, binary_sensor.1_134_allapot_dbz=2022-12-05T14:12:41.669503+00:00, friendly_name=Nominal Change History @ 2022-12-05T18:14:12.817490+01:00>)>]

marble jackal
#

Just use state_attr('sensor.last_nominal_change', 'changes')

thorny snow
dusty hawk
#

Is it possible to use a jinja macro() to set the state of template sensors?
This fails validation stating that a "%" can't start any token.

template:
  sensor:
    {% macro icon( id ) -%}
       {# Do a bunch of macro stuff #}
    {%- endmacro %}
    - name: 'Openweather Icon'
      state: >
         {{ icon( state_attr('sensor.openweather_report', 'current').weather[0]['id'] ) }}    
marble jackal
marble jackal
inner mesa
#

you can use it within a template block, but that usually makes macros less useful ๐Ÿ™‚

dusty hawk
#

Hmmm, the macro is a really long if, elif block, basically a case statement. I don't want to repeat it for each day/hour...

thorny snow
inner mesa
#

look at YAML anchors

dusty hawk
#

OK, I have some of those I'll review. Thanks

cosmic hamlet
#

How do i create a for loop for each device_tracker

#

need to change the layout of my auto entity card for my vpn on off switch.

#

states

#

{% for device in states.device_tracker %}

#

got it

cosmic hamlet
#

I cant get my regular expression to work using regex_findall_index only .* gets results

#

the regex i should use is ^192.168.5.(1[5-9]\d|2[0-4]\d)$

#

aha

#

not use index

spiral imp
#

Trying to create a "weekend" sensor that is "on" from 5PM Friday until 5PM Sunday every week. Thoughts on how to do this?
EDIT: or maybe an automation that turns a boolean on and off at the desired times is better

spice current
lime pasture
#

The GUI is a bit buggy but for me, but it seems to still work even if its confusing what hours are included

sick ice
#

OK this makes me feel a bit daft. I put these in to the template tool, 3 numbers to 1 dec pl but when I add them together I get many decimal places. I know I can round the output but I don't understand why this is happening?

{{ states('sensor.air_con_energy_monitor_channel_b_power') | float(default=0)}}
{{ states('sensor.air_con_energy_monitor_channel_c_power') | float(default=0)}}
{{ states('sensor.air_con_energy_monitor_channel_a_power') | float(default=0) + states('sensor.air_con_energy_monitor_channel_b_power') | float(default=0) + states('sensor.air_con_energy_monitor_channel_c_power') | float(default=0)}}

26.2
-16.1
4.8
14.899999999999999

inner mesa
#

that's the way computers work

#

you can round at the end

sick ice
next elm
#

So, I just upgraded through several versions of HomeAssistant, and suddenly, my timestamp template sensors have gone from working perfectly, to all showing "Unknown".
The value templates work fine on the dev tools > template tab, so I'm not sure what's going wrong with the sensors.

#

e.g. {{ strptime(state_attr('switch.rainmachine_normal_watering_plan', 'next_run'), "%Y-%m-%dT%H:%M:%S") }} returns 2022-12-07 02:00:00 as expected. But this just returns "Unknown"```sensor:

  • platform: template
    sensors:
    normal_watering_plan_nextrun:
    friendly_name: 'Normal Watering Plan Next Run'
    value_template: >
    {{ strptime(state_attr('switch.rainmachine_normal_watering_plan', 'next_run'), "%Y-%m-%dT%H:%M:%S") }}
    device_class: timestamp```
next elm
#

And converting the sensor from the legacy format to the new format didn't fix it. Still returns "Unknown"

plain magnetBOT
low kernel
#

Service Template help

inner mesa
next elm
#

That doesn't actually fix it either

inner mesa
#

Add |as_datetime?

next elm
#

Seems like anything with the device_class of timestamp is borked

#
  - sensor:
    - unique_id: doorbell_last_rung
      name: 'Doorbell Last Rung'
      state: "{{ states('input_datetime.doorbell_last_rung') }}"
      device_class: timestamp```
inner mesa
#

It says it accepts a datetime or ISO8601 string

next elm
#

Even a simple one like that returns Unknown, though the template returns a date if you check it from the Template tab of Dev Tools

next elm
inner mesa
#

you can just reload template entities

next elm
#

Either way, didn't fix it

inner mesa
#

this works fine:

- sensor:

  - name: since_last_changed
    state: "{{ now() }}"
    device_class: timestamp
#

as does:

  - name: since_last_changed
    state: "{{ state_attr('automation.kitchen_remote_fr_lights', 'last_triggered') }}"
    device_class: timestamp
#
  - name: since_last_changed
    state: "{{ states('button.water_heater_leak_detected_ping') }}"
    device_class: timestamp
#

๐Ÿคท

inner mesa
#

all of those work fine

next elm
#

Ok, so why don't my other ones work...

#

{{ now() }} returns 2022-12-05 22:29:00.029220-08:00
{{ states('input_datetime.doorbell_last_rung') }} returns 2022-12-05 21:15:22

#

Is some kind of conversion required now, that wasn't required in the older versions of HA?

thorny snow
next elm
#

Yup, adding .000000-08:00 to the end suddenly makes it output an actual date into the sensor

#

I'm assuming there's a better way of doing this than hard-coding decimal seconds and time zone...

#

Any idea what that would be?

marble jackal
marble jackal
next elm
#

Already tried that. Unfortunately, no dice

marble jackal
#

Forgot to add as_local for the timezone

next elm
#

Thaaaat did it

#

Worked for every sensor except normal_watering_plan_nextrun. For some reason, the entire entity vanished...

#
      name: 'Normal Watering Plan Next Run'
      state: >
        {{ strptime(state_attr('switch.rainmachine_normal_watering_plan', 'next_run'), "%Y-%m-%dT%H:%M:%S")|as_datetime|as_local }}
      device_class: timestamp```
#

Not sure what's going wrong there

#

strptime is somewhat required, because the Rainmachine sprinkler system uses an odd date/time format

#

The raw value for next_run is formatted like this: 2022-12-07T02:00:00

#

Yeah, now that entity is borked. "Entity not available" error

#

Oh, it's because HomeAssistant isn't using the unique_id as the entity ID... that's odd

#

Aight, that's another post-upgrade issue off the list. Time to get solar monitoring working again.

marble jackal
#

{{ '2022-12-07T02:00:00' | as_datetime | as_local }} works fine for me BTW, so I guess it was the entity_id issue which caused some the template not to work

next elm
#

Yeah, it was making a new entity every time I reloaded. What happened to the ability to set a fixed entity_id in yaml?

thorny snow
marble jackal
#

if it is just for one binary sensor, you can create two input_datetimes (one for on and one for off) and create an automation to write the datetime to that input_datetime

thorny snow
marble jackal
#

No, I was not referring to the template sensor here. If you only need this for one binary_sensor, you could just forget about the template sensor and do it in an automation

#

If you would store all states in that template sensor, it would turn into a long list quite soon if you would add a power sensor for example

#

as they change state very often

thorny snow
#

It is meant for binary_sensors only, and a limited number, I'm not planning to extend it now.

#

The state changes are alltogether few dozens a day.

marble jackal
#

Well, you could change the template sensor so it indeed stores changes_on and changes_off

#

But the sensor I created is a generic one, intended for all kinds of entities, so also those which change very often

#

it is just not intended for your use case, so you'll need to amend it for that

thorny snow
#

Ok, so provided I have some tens of binary sensors, only binary, and I need to check for off and on changes and start automations on that, would you recommend your template sensor? Is it worth a try?

marble jackal
#

that could work

thorny snow
#

You are great! Thanks a million!

marble jackal
#

oh, you should indent line 15 with one space

acoustic jungle
rare linden
#

Anyone got a script for unmutting phone, setting volume to max and sounding a noise? i have a script that does the noise but not sure if there's the ability to do the former, lost my phone and pretty sure it's on full mute so if the script is working i'm not hearing the result

silent flicker
#

hello. i was trying to use

{{ 'call' in state_attr('calendar.work', 'message') | lower }}

to look for the word "call" in a calendar event, the issue is that I have more than 1 calendar event on the day, so it only sees the most recent. is there a way to look at the other active calendar events?

marble jackal
#

that won't work

#

you just converted the enter message from the calendar to lowercase

#

and then you check for the word Call which has an uppercase character

#

so Call will never be in that message, as it only has lowercase characters

silent flicker
#

ignore that, i copied the wrong one. let me edit it

#

i was playing around and copied the wrong one here

#

but anyway, my issue still is there. i want to look at all active calendar events today for the word, but 'message' only contains the most recent to come in. is there any solution apart from making a separate calendar just for my 1 thing i want to look for?

zealous bough
#

Hey all - I am trying to write a template that checks if a timer.finished event (for timer.hvac_fan) has fired within the last hour - any guidance/assistance?

marble jackal
#

You need to have that data then

#

what you can do is create a trigger based template sensor, which triggers on that event, and logs the time

#

You can also check the last_changed object of the timer entity, and check if it is not active, but that will not be reliable after a restart of HA

zealous bough
#

Thanks - I resorted to a helper input_boolean to solve for my need. When the timer.finished event fires, the helper is set to true, and reset as appropriate for my need.

mighty ledge
#

going to need more info

#

like example commands, what's changing for each light, etc

spice current
#

each device is unique

#

i need something simple where i can specify each action myself

#

pseudo yaml:

custom_device:
   type: "light"
   name: "LED Strip"
   control_scheme: "http/get"
   actions:
      on: "http://automater.pi/api/ir/?device=led_strip&action=on"
      off: "http://automater.pi/api/ir/?device=led_strip&action=off"
      fade: "http://automater.pi/api/ir/?device=led_strip&action=fade"
      flash: "http://automater.pi/api/ir/?device=led_strip&action=flash"
      colors:
          blu: "http://automater.pi/api/ir/?device=led_strip&action=blue"
          red: "http://automater.pi/api/ir/?device=led_strip&action=red"
          white: "http://automater.pi/api/ir/?device=led_strip&action=white"
          pink: "http://automater.pi/api/ir/?device=led_strip&action=pink"
mighty ledge
#

use shell commands

#
shell_command:
  led_action: curl http://automater.pi/api/ir/?device=led_strip&action={{ action }}

then call with

service: shell_command.led_action
data:
  action: "on"
#

@spice current

spice current
#

will this show as a light in google home

#

with color wheel, brightness slider etc

mighty ledge
#

You have to make the template light using those commands

#

Also, without something to 'get the state', none of that will work

spice current
#

wdym by template light, sorry im not deep into yaml stuff

spice current
#

so caching the state in HASS instead of the device

mighty ledge
#

That will take alot of work

spice current
#

and noone has done this before?

mighty ledge
#

you'll need helpers to store all the 'states'

#

plenty have, it's just different every time

spice current
#

wdym its different? The whole thing could even have a simple UI

mighty ledge
#

lights are complicated

spice current
#

where you select what to create (switch, light, etc); which features it has and how to "call" these features

mighty ledge
#

you may think it's simple, it is not.

#

there is no UI

#

you'll have to learn yaml

spice current
spice current
mighty ledge
#

you have to cache it yourself

#

there is nothing that does what you want that will work out of the box

spice current
#

when was the first version of HASS released, just curious

mighty ledge
#

~2014ish

spice current
#

dang almost 9 years and noone thought of making this easier

mighty ledge
#

because we don't need to, we do yaml ๐Ÿ˜‰

#

this UI push is new.

#

so you're in the minority

spice current
#

i like how the ui works for automations/scripts and the tuya local thingy

mighty ledge
#

I doubt these will make it into the UI anytime soon, so you'll just have to pull up your boot straps

spice current
#

how do i tell the template that my light doesnt support dynamic brightness values but just up and down

meager ember
#

is there any way to do something like ['sensor.temprature1','sensor.temprature1'] | state_attr("friendly_name") ?

inner mesa
#

as in "get the friendly_name from each entity"?

#

{{ expand(['sensor.temperature1','sensor.temperature1'])|selectattr('attributes.friendly_name', 'defined')|map(attribute='attributes.friendly_name')|list }}

meager ember
ancient lynx
#

Hello all. I have a sensor that gives the drive time to a location at any given time. How can I make a dynamic notification that fires at an offset before a given time where that offset is defined by the traffic sensor?

karmic oar
#

I'm not sure why exactly this is wrong, though I know it's not much to go off: Invalid config for [template]: expected dictionary for dictionary value @ data['sensors']. Got [OrderedDict([('name', '{{ items.c1.name }}'), ('state', '{{ items.c1.value or this.state if this.state is defined else none }}')])].

shell fractal
#

{{ ( (states('sensor.ble_temperature_a4c138328d38') | float >+ (state_attr('climate.smart_thermostat_3','temperature') | float)) and
( (as_timestamp(now())- as_timestamp(states.sensor.ble_temperature_a4c138328d38.last_changed) | timestamp_custom('%H') <= 10 ) ) }} I dictated this code to artificial intelligence ๐Ÿ™‚ What I wanted: If the sensor taken from the Ble_ temperature sensor is higher than the smart_thermostat temperature value for 10 minutes, the command was on. I need this code. By following the temperature, I am trying to synchronise the temperature of the boiler simultaneously. If there is a mistake, I would be very happy if you make corrections.

marble jackal
plain magnetBOT
#

Please use a code share site to share code or logs, for example:

Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.

marble jackal
#

What you want can't be done in a single template, because you are comparing numeric states

karmic oar
#

That's the config in template.yaml

marble jackal
#

Create a template binary sensor using {{ states('sensor.ble_temperature_a4c138328d38') | float > (state_attr('climate.smart_thermostat_3','temperature') | float }} and then check if that binary sensor is on for 10 minutes

marble jackal
karmic oar
#

I'll give it a try

shell fractal
marble jackal
#

No, because last_changed will update on every state change, and the comparison can be true before and after the state change

#

But the 10 minutes will be reset then, when they shouldn't

shell fractal
leaden onyx
#

Seems like I'm at a loss, here, maybe you can help: I'm trying to extract a value from an attribute and I can't find it in the docs:
Max. temps will be {{ state_attr('sensor.pws_forecast', 'calendarDayTemperatureMax') }} ยฐC.
returns:
Max. temps will be [4, 2, 1, 0, -1, -2] ยฐC.
How can I get to the individual values of that array?

marble jackal
# shell fractal Can you explain the last sentence a bit more? Could the system created with bina...

Well assume the state of the sensor is 15 and the state of the climate entity is 10. So sensor > climate is true. It stays like this for 9 minutes, but then the sensor changes to 14.
The statement is still true, but since the sensor changed state, last_changed will have that new datetime and there is no way anymore to determine how long the statement has been true
As the result of the statement itself did not change, a binary sensor using that statement would also not have been changed, so that one will still show the correct time the statement became true (unless you do a reboot in the meantime)

marble jackal
karmic oar
#

Does a tool exist to parse home assistant yaml such that I can see what the output of my code is? That way I'm not just blindly making changes and hitting the restart button over and over

plain magnetBOT
marble jackal
#

Like that you mean?

#

BTW, you don't need to restart for most changes, you can reload parts of your configuration here

plain magnetBOT
karmic oar
#

No, I want to see the output of the variables portion of the paste I sent earlier

#

The bottom line is that I can't seem to formulate the correct output to create my sensors

marble jackal
#

Not sure there is anything for that, bit template sensors can be reloaded from the link I sent, do no need for reboots

karmic oar
#

I have attempted to reload there with no change, but I will try using it again

marble jackal
#

Well that's because it is a trigger based template sensor, which will only update when triggered

karmic oar
#

That's fair, it should be updating every 10 seconds

marble jackal
#

Does that packs attribute change every 10 seconds?

#

If it has the same value as the previous one, it won't trigger

karmic oar
#

Usually, yes, within a millivolt or so. I mean, I have a ton of errors right now

#

Let me compile them into one pastie

marble jackal
#

The first one is easy, there is no str filter, there is a string filter though

karmic oar
#

Maybe that will fix it all

#

Well, that certainly did change things. Doesn't seem to accept that module is defined as "1", though

#

The point of all this anchoring and use of variables is to reduce about 1800 lines of yaml down to roughly 40

shell fractal
# marble jackal Well assume the state of the sensor is 15 and the state of the climate entity is...

Thank you for your detailed explanation. It is not something very sensitive. Ble sensor updates every 15 seconds. I don't think it will be too much of a problem. I will test it tonight. The purpose of wanting this sensor: my house is an American kitchen. The kitchen and living room are one, the house heats up when the food is cooked, to which degree the house rises (even if the thermostat is at a lower temperature) is to ensure that the thermostat is fixed to that temperature and does not go lower. the aim is not to lose the heat of the heated house.

marble jackal
#

If the sensor updates that frequent, tool you'll never reach the 10 minutes if you don't use the binary sensor

marble jackal
karmic oar
#

I need to delete the 63 unnamed sensors all this testing has created

marble jackal
#

Add a unique_id to prevent that

karmic oar
#

Alright, it's 10PM and I have to be in a few hours. Still need to delete all those unnamed sensors somehow, and for some reason I still get Template variable warning: 'module' is undefined when rendering '{{ trigger.to_state.attributes.packs | selectattr('module', 'eq', module|string) | first | default({}) }}' though from that code I would gather that module was defined right after variables

marble jackal
#

module should be 1 according to the code you shared

north locust
#

euhm 0 decimals , is

|float * 1000, round 0 }}

??

mighty ledge
#

no

#

( ... | float * 1000) | round(0)

north locust
#

aah ty !!

timber cobalt
#

Does anyone know a good example for setting up a 'smart' presence sensor. I can do a simple 'or is_state', but have two issues (1) some of the motion sensors turn on immediately, but take ~45 minutes to turn off and (2) I need to mix ANDs and ORs

#

This is my pseudo code, but I don't know how to do the 'on' recently, or the AND:

plain magnetBOT
dusty hawk
#

How about just assuming no one is home when your alarm is armed_away, and otherwise assume someone is home? If your presence sensors don't go off for 45 minutes, that's a problem in your approach above

#

Doesn't the AND obviate the need for all the ORs? (assuming you set the alarm when you leave)

timber cobalt
#

If someone leaves and forgets to arm, still want the house to go through and shut off lights etc.

#

The issue with the presence sensor not going off for 45 minutes is that it's a motion detector that's connected to the alarm system. It's a bad sensor, but useful for the step up.

#

Regarding the 'AND' I assumed nesting logic like I did above wouldn't actually work. I couldn't find any example that did it.

#

I ended up just using helpers. This seems to work. The last step is basically your suggestion, but ANDed with the other detection methods. So: If armed away = not there. If armed home = home. If system unarmed = check for activity. Just seems more wordy than I'd expected.

plain magnetBOT
dusty hawk
#

Does HA support the jinja {% include %} feature?
https://jinja.palletsprojects.com/en/3.1.x/templates/#include
With yaml &anchors not seeming to work for jinja code, I'm trying to use the jinja {% include 'file' %} in a template sensor as:

state: |-
 {% include '/config/test.yaml' %}
 {% if state_attr('sensor.openweather_report', 'current').weather[0]['id'] is defined %}
   {{ set_icon( "state_attr('sensor.openweather_report', 'current').weather[0]['id']" ) }}
 {% endif %}

Here is the error:
[homeassistant.helpers.template_entity] TemplateError('TypeError: no loader for this environment specified') while processing template 'Template("{% include '/config/test.yaml' %}")' for attribute '_attr_native_value' in entity 'sensor.openweather_icon'

inner mesa
#

Seems not

marble jackal
#

Nope, also tried that

#

Btw, if it would work you should include a jinja (.j2) file, not a yaml file

dusty hawk
#

Yes, it's not yaml. Thanks for that. I'm writing up an Issue

marble jackal
#

I don't think it's an issue, I would suggest to write a feature request

dusty hawk
#

Fair enough

dusty hawk
silent grove
#

Yikes!

#

Just applied 2022.12 and ALL my Zigbee2MQTT entities have changed their unique IDs from what they were to a _2 variant of the original name.....restart didn't fix it.....I've got 500+ entities so I don't really want to delete the old names and then rename the _2 ones back to default......

#

Any ideas on how to fix that?

#

Needless to say everything is now broken.....

silent seal
#

That didn't happen to me on the betas. I'd recommend using your backup and rolling back

#

But I also suspect more than templates are broken. So it might be worth using #general-archived for now ๐Ÿ™‚

silent grove
undone jungle
#

Dear all, is there a simple way to throttle the templates from publishing so much into the MariaDB?

#

I've got some simple calculus templates for power to create various device power groups and they generate some obscene numbers of datapoints over a week

inner mesa
#

yes, give them a trigger

undone jungle
#

I have a 10-day DB purge and these 4 entities generate 750k points each, with the closes second having less than 300k

#
  - sensor:
      - name: Net power meter
        state_class: measurement
        device_class: power
        unit_of_measurement: W
        unique_id: net_power_meter
        state: >
          {{ (states('sensor.electricity_meter_power_active_phase_1') | float | round(4) + states('sensor.electricity_meter_power_active_phase_2') | float | round(4) + states('sensor.electricity_meter_power_active_phase_3') | float | round(4)) | int }}
        availability: "{{ states('sensor.electricity_meter_power_active_phase_1') | is_number and states('sensor.electricity_meter_power_active_phase_2') | is_number and states('sensor.electricity_meter_power_active_phase_3') | is_number }}"
undone jungle
#

How would one look like for a sensor such as this one?

inner mesa
#

when do you want it to evaluate?

undone jungle
#

Previously, there used to be a fixed timer update_interval:

inner mesa
#

the use a time_pattern trigger

undone jungle
#

But it seems it's no longer possible

inner mesa
#

the triggers are the same everywhree

undone jungle
#

If I'd like it to update at 1 or 2 Hz

undone jungle
#

Yes, I've read this twice, but can't understand the term 'match' in the documentation.

#

With the time pattern trigger, you can match if the hour, minute or second of the current time matches a specific value. You can prefix the value with a / to match whenever the value is divisible by that number. You can specify * to match any value (when using the web interface this is required, the fields cannot be left empty).

#

"You can specify * to match any value" this is particularly confusing in light of the examples given.

#

Could you give an example of a trigger for every two seconds?

#

I'll try to incorporate it into my code and post it back, to make sure it makes sense.

inner mesa
#

the third example there is what you want, but it just uses minutes

#
  trigger:
    - platform: time_pattern
      seconds: "/2"
#

This is the operative phrase:

You can prefix the value with a / to match whenever the value is divisible by that number.

undone jungle
#

So the full sensor would look like this:

   - trigger:
      - platform: time_pattern
        seconds: "/2"
     sensor:
      - name: Net power meter
        state_class: measurement
        device_class: power
        unit_of_measurement: W
        unique_id: net_power_meter
        state: >
          {{ (states('sensor.electricity_meter_power_active_phase_1') | float | round(4) + states('sensor.electricity_meter_power_active_phase_2') | float | round(4) + states('sensor.electricity_meter_power_active_phase_3') | float | round(4)) | int }}
        availability: "{{ states('sensor.electricity_meter_power_active_phase_1') | is_number and states('sensor.electricity_meter_power_active_phase_2') | is_number and states('sensor.electricity_meter_power_active_phase_3') | is_number }}"
#

Correct?

tacit sun
#

I'd like to create an automation to turn on Christmas lights. But, I'd like it to only run on certain days of the year (essentially... December and Jan), and when it's dark enough...

So...
Trigger: it's dark
Condition: month is in (dec, Jan)
Action: Turn on

But, i don't see a option to have a date or month as a condition. My guess is: templates to the rescue.

I am however... Terrible at templates. Anybody have a suggestion? Maybe... Know of some good contextually relevant reading?

inner mesa
#

99% of problems have been solved and documented on the forum

tacit sun
undone jungle
#

@inner mesa would you mind having a look? โ˜๏ธ

thorny snow
# marble jackal http://pastie.org/p/1M7iT11YDU79XXGNtQsxJz

I tested the trigger-based template sensor for a few days, what I figured was that it does not work reliably. Now I have this code (only the sensor part, I omitted the trigger), it complains about 'str' cannot have isoformat():
sensor: unique_id: nominal_occsy_chg_hist name: Nominal Occupancy Change History state: "OK" attributes: changes_on: > {% set current = this.attributes.get('changes_on', {}) %} {% set new = {trigger.entity_id: trigger.to_state.last_changed.isoformat() | as_local} if trigger.to_state.state == 'on' else {} %} {{ dict(current, **new) }} changes_off: > {% set current = this.attributes.get('changes_off', {}) %} {% set new = {trigger.entity_id: trigger.to_state.last_changed.isoformat() | as_local} if trigger.to_state.state == 'off' else {} %} {{ dict(current, **new) }}

#

When I remove the isoformat(), I get this: ValueError: dictionary update sequence element #0 has length 1; 2 is required

marble jackal
#

I assume you still have the trigger in right?

plain magnetBOT
marble jackal
#

ah, I see what's wrong

#

the | as_local filter is applied on the isoformat string of the datetime

#

which doesn't work

#

this should work

        changes_on: >
          {% set current = this.attributes.get('changes_on', {}) %}
          {% set new = {trigger.entity_id: as_local(trigger.to_state.last_changed).isoformat()} if trigger.to_state.state == 'on' else {} %}
          {{ dict(current, **new) }}
        changes_off: >
          {% set current = this.attributes.get('changes_off', {}) %}
          {% set new = {trigger.entity_id: as_local(trigger.to_state.last_changed).isoformat()} if trigger.to_state.state == 'off' else {} %}
          {{ dict(current, **new) }}
#

BTW use 3 backticks for code blocks of multiple lines

thorny snow
#

It works again, thanks!

marble jackal
thorny snow
#

It's becoming five star...

#

For me that state shows one entity less than stored.

marble jackal
#

Hmm, what do you currently have as values for these attributes

#

changes_on and changes_off

thorny snow
#

I wanted to upload a small image about that. How can I upload an image?

marble jackal
#

you can use imgur, but it would help for testing if I have it in text

plain magnetBOT
#

Please use a code share site to share code or logs, for example:

Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.

thorny snow
#

All right. So, right now state: 3, content is five items:
changes_on: binary_sensor.1_121_allapot_dbz: '2022-12-08T11:05:48.912156+01:00' changes_off: binary_sensor.1_121_allapot_dbz: '2022-12-08T11:05:18.254059+01:00' binary_sensor.1_117_allapot_dbz: '2022-12-08T11:03:28.438085+01:00' binary_sensor.1_122_allapot_dbz: '2022-12-08T11:09:52.853203+01:00' binary_sensor.1_128_allapot_dbz: '2022-12-08T12:07:38.643283+01:00' friendly_name: Nominal Occupancy Change History

glacial bridge
#

"value_template": "{% if value_json == 101 %} 100 {% elif value_json == 255 %} 0 {% else %} value_json {% endif %} | int"
why does it not convert to int?
i've also tried to pipe each value, but says '55' is not a number
if I remove the template it works, but gives errors for the odd values (101 and 255)

marble jackal
marble jackal
glacial bridge
#

that's why I piped to int

#

I expect conversion

marble jackal
#

you placed the filter outside the template

#

that doesn't work

glacial bridge
#

the entire payload is just a number, it works for another sensor to convert number to strings

#

I placed it inside too, no help

#

"value_template": "{% if value_json == 101 %} 100 | int {% elif value_json == 255 %} 0 | int {% else %} value_json | int {% endif %}"

marble jackal
#

no, 100 is already an int

#

it is value_json which is not already an int, you need to convert that

glacial bridge
#

100|int is still 100

#

so no harm

#

value_json|int ==> string

#

it does not work...

marble jackal
#

but "101" is not 101

glacial bridge
#

"value_template": "{% if value_json == 0 %} Scurt circuit {% elif value_json == 1 %} Normal {% elif value_json == 2 %} Incendiu {% elif value_json == 3 %} Sabotaj {% elif value_json == 4 %} Panicฤƒ {% elif value_json == 5 %} Deconectat {% else %} Necunoscut {% endif %}",

#

this works flowlesly

#

why does not work when I want an INT out, not a string?

marble jackal
#

then in this case value_json is an integer

glacial bridge
#

it is always just a number

#

in both cases

#

{% elif value_json == 1 %} Normal
"Normal" is a string

#

so I expect
{% if value_json == 101 %} 100
100 to be a string too

marble jackal
#

You are not providing any information what value_json is, and where it comes from. Remember that you are the one asking for help, and crystal balls are in short supply

#

no, you are defining it to be 100

glacial bridge
#

value_json is a number only, raw payload is "101" (no quotes)

marble jackal
#

100 is a integer

glacial bridge
#

I can't post screenshots

marble jackal
#

if you want it to be a string, you need to define it as '100'

glacial bridge
#

so it is hard to see

marble jackal
#

or 100 | string

glacial bridge
#

I want it as a number for a slider

#

but it complains to be an string

marble jackal
#

If value_json in this template: "{% if value_json == 101 %} 100 {% elif value_json == 255 %} 0 {% else %} value_json {% endif %} is always an integer, the result will also always be an integer

#

either 100, 0 or value_json itself

#

if the result is not an integer, then value_json was not an integer

glacial bridge
#

that's my problem, it says it's a string... I control the payload is just a number, no quotes no nothing

marble jackal
#

Well, it's not a complicated template, and there are only three outputs possible. Either 0, which is an integer, or 100, which is an integer, or value_json, which according to you is an integer

glacial bridge
#

that's what I say

marble jackal
#

So, if HA complains that the result is not an integer, it must be from another part in your configuration, or value_json is not an integer

mighty ledge
#

You should post the actual error instead of a paraphrased error

#

@glacial bridge ^

glacial bridge
#

one sec, I deleted my config, was done by hand, now I do it via code

glacial bridge
#

Logger: homeassistant.components.mqtt.number
Source: components/mqtt/number.py:208
Integration: MQTT (documentation, issues)
First occurred: 3:19:29 PM (3 occurrences)
Last logged: 3:19:30 PM

Payload '55' is not a Number
Payload '255' is not a Number

#

both values are numbers on the MQTT message

#

they are not strings

mighty ledge
#

can you post the full action?

glacial bridge
#

not sure what to post

#

I send the messages via Mqtt Explorer

mighty ledge
#

then post the configuration of your MQTT number and take a screenshot of the topic in question in MQTT explorer

glacial bridge
#

I am not allowed to add images here

marble jackal
#

you should not post images of configuration code

#

and if needed you can upload an image to imgur, and post the link

plain magnetBOT
#

Please use a code share site to share code or logs, for example:

Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.

glacial bridge
#

does this help?

#

I'm not sure if message was delivered, it says it was converted to a file

mighty ledge
#

share your images with imager

#

@glacial bridge

#

anyways, I see your issue

#
value_template: >-
  {% if value_json ==  101 %} 100 {% elif value_json == 255 %} 0 {% else %}
  {{ value }}{% endif %}
glacial bridge
#

will try

marble jackal
#

ah crap, should have seen that.. shouldn't it be {{ value_json }} though?

mighty ledge
#

doesn't matter

marble jackal
#

oh okay

mighty ledge
#

the typing resolver will take care of it

marble jackal
#

ah okay, both value and value_json are valid, but the 2nd is converted to json

mighty ledge
#

yeah

#

no reason to convert to json when you don't have to, however that variable exists in the namespace so I don't think it matters which one you use because both are prepopulated

marble jackal
#

ah, clear.. I clearly don't use these kind of configs ๐Ÿ˜›

#

but anyway, the message that it was still not working suddenly disappeared

glacial bridge
#

now it works out of the blue with the same payload

#

same template

#

I just deleted the whole device from ha and rediscovered

#

wtf?

mighty ledge
#

Your old template would only work when the value is 101 or 255, it wouldn't work with any other value

#

you need to update your template to what I wrote

marble jackal
#

well, the problem with your earlier version was that you were returning the string value_json and not the value in the variable

glacial bridge
#

it's my template that works

mighty ledge
#

it will fail

glacial bridge
#

value_template = "{% if value_json == 101 %} 100 {% elif value_json == 255 %} 0 {% else %} value_json {% endif %}",

#

this works... now

mighty ledge
mighty ledge
glacial bridge
#

trust me it does

mighty ledge
#

you're literally returning the string value_json instead of the variable

glacial bridge
#

I can see the slider moving

marble jackal
glacial bridge
#

value_json is int because of pre-parsing

mighty ledge
#

no

#

you don't have it in {{ }}

#

so it's the literal string

glacial bridge
#

ok, then how does it work?

mighty ledge
#

it doesn't

#

you just think it is

glacial bridge
#

since I can post numbers and see the slider moving in the dashboard

marble jackal
#

It would work in something like this {{ 0 if value_json == 255 else 100 if value_json == 101 else value_json }}

mighty ledge
#

right, but the way you have it currently, it will not work.

glacial bridge
#

then I'm imagining the slider moves with the payload?

mighty ledge
#

๐Ÿคทโ€โ™‚๏ธ your template is wrong, here look:

marble jackal
#

no, it is probably using the config you had before

mighty ledge
marble jackal
#

reload MQTT from devtools > yaml

mighty ledge
#

Notice how it says 'value'

marble jackal
#

does it still work then?

mighty ledge
#

now, look when I put brackets

#

hey, look, proof that your template's wrong. Who would have thought

#

Most likely what's happening is that you're working off an old discovered topic and your current one hasn't been used. Send the discovery info again and It will stop working.

glacial bridge
#

oh well... just checked, it works... even after removing and rediscovering, so I will leave it as is

#

when I delete the device, the respective MQTT discovery topics get deleted as well on the server

#

so it was a clean discovery

mighty ledge
#

just don't come crying here for help when it fails, because it will

#

that template is wrong.

glacial bridge
#

ok, thank you

#

I won't

mighty ledge
#

๐Ÿ‘

marble jackal
# thorny snow All right. So, right now `state: 3`, content is five items: `changes_on: binar...

This returns 4, which is what I would expect from it

{% set on = {
  'binary_sensor.1_121_allapot_dbz': '2022-12-08T11:05:48.912156+01:00' } %}
{% set off = {
  'binary_sensor.1_121_allapot_dbz': '2022-12-08T11:05:18.254059+01:00',
  'binary_sensor.1_117_allapot_dbz': '2022-12-08T11:03:28.438085+01:00',
  'binary_sensor.1_122_allapot_dbz': '2022-12-08T11:09:52.853203+01:00',
  'binary_sensor.1_128_allapot_dbz': '2022-12-08T12:07:38.643283+01:00' } %}

{{ (off.keys() | list + on.keys() | list) | unique | list | count }}
#

it should not return 3 though

thorny snow
frank gale
#

Is there any change on the | default filter in jinja? I'm getting a curius error on the template editor for this:

{{ [] | default(['0'], true) | average }}
#

ValueError: Template error: average got invalid input '(['0'],)' when rendering template '{{ [] | default(['0'], true) | average }}' but no default was specified

mighty ledge
frank gale
#

The , true wasn't there for an empty case? this was working in .11

#

oh sorry I had a string

mighty ledge
#

no, the true does nothing in that case

#

the default you're supplying is the [0]

#

this does not corelate to adding defaults to floats

#

or ints

#

this is a separate function/filter

frank gale
#

my fault was that I was given a string to pass to the average that needed a number

thorny bolt
#

Is it possible to write the tag_id (of an NFC Tag i read inside HA) into an "helper" to be able to Store it as "Last readed Tag" and compare it with current Tag?

mighty ledge
#

@frank gale if you're trying to avoid empty list errors use this

#
{{ ([] or [0]) | average }}
frank gale
#

default can be used with empty lists with ', true' argument, i'm not having any issues

mighty ledge
frank gale
#

if you use it on the template you wrote above it will render ok

#

you will get 0 as average

mighty ledge
#

then your error is that you're using ['0'] instead of [0]

frank gale
#

yes I wrote it already petro ๐Ÿ™‚

mighty ledge
#

sorry, bouncing between work and here

frank gale
#

no problem! thanks for sorrying ๐Ÿ˜›

thorny bolt
mighty ledge
#

you can trigger off events

thorny bolt
# mighty ledge why is that stopping you then?

I Trigger an Automation with tag read, but i need to Store and compare the UID inside an helper within that Automation:

I need i as helper to start/Pause/resume Playback of Audio Like Spotify or mp3/ogg

inner mesa
#

and that's not available in the event structure?

mighty ledge
#

you don't need it as an attribute, the information is passed via trigger objects

thorny bolt
# mighty ledge See what rob posted

I Just checked the Link, but as soon as i add {{ trigger. }} Into the Template Editor, i only get error "UndefinedError: 'trigger' is undefined"

So i dont know how to get the UID once i read an Tag

mighty ledge
#

you can only use it in automations or trigger based sensors, where are youtrying to use it?

thorny bolt
#

Dev-Tools / Template

To Test the result

mighty ledge
#

yeah you can't do that, it doesn't have a trigger

#

you have to test it in an automation

thorny bolt
#

So i need to Debug it somehow to See the correct trigger Part to See where the UID is listed

mighty ledge
#

you can listen to events in the event page on developer tools

inner mesa
#

No, you listen to the events in devtools -> Events

mighty ledge
#

you can view your traces of an automation as well

#

many tools to do this

#

you can even view a different automation that uses scanned tag events to get the shape as it will have a trace with that info

thorny bolt
#

event_type: tag_scanned
data:
tag_id: E0040350********
device_id: a761e58243837915de***********
origin: LOCAL
time_fired: "2022-12-08T20:13:51.107420+00:00"
context:
id: 01GKSNYY4***********
parent_id: null
user_id: null

#

Thats what i get, but i think iam to stupid to get it somehow inside {{ }}

#

I need the "tag_id" saved in an input_text

inner mesa
#

trigger.event.data.tag_id

thorny bolt
#

service: input_text.set_value
target:
entity_id: input_text.tag_uid
data:
value_template: "{{ trigger.event.data.tag_id }}"

spice current
thorny bolt
#

Thanks that worked

hollow mortar
#

I have this sensor for yesterday with:

end: '{{ now().replace(hour=0).replace(minute=0).replace(second=0) }}'
duration:
  hours: 24```
It gets reset (somehow it calculates a new value) each time I restart HA. Is this expected behaviour?
marble jackal
#

and you can do all those replaces in one go, if you do want to use them "{{ now().replace(hour=0, minute=0, second=0) }}"

#

In what kind of sensor are you using this config?

lyric jungle
#

hi, I'm trying to make alexa announce the remaining time on my washing machine.

the "message:" block should get a string value, but when I enter {{ states(sensor.washing_machine_remaining_time }} I get a notification that "template value should be string for dictionary value..."

the sensor value is string when i put the same command in the developer section.

any ideas how to make this work?

marble jackal
#

what is the actual code of the service call in which you used this template

plain magnetBOT
#

Please use a code share site to share code or logs, for example:

Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.

marble jackal
#

Yep, just as I expected. Rule #1 of templating, surround your template with quotes if you use the single line notation

#

message: "{{ states('sensor.remaining_time}}"

lyric jungle
compact robin
#

What would this look like with the template updated code?

    sensors:
      wetemp:
        friendly_name: "temperature_outside"
        unit_of_measurement: 'ยฐC'
        value_template: "{{ state_attr('weather.accuweather_house', 'temperature') }}"
#

I heard that's a little outdated and should be template: - sensor: and not -platform: template sensors:
But trying to replicate it makes the code break all the time lol

#

Like the ID would be temperature_outside and the name Temperature: Outside which is also something I cannot replicate properly

marble jackal
#

what was your best attempt

#

and please format your code as code, not as a quote

plain magnetBOT
#

To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks.
```yaml
example: here
```
Don't forget you can edit your post rather than repeatedly posting the same thing.

compact robin
#

Apologies, properly edited. That's the best attempt - the one I am using at and "works".

#

But considering I am currently messing / fixing some stuff, thought would be a good timing to updae to the new format and not use the old one

#

Can't seem to pull it off tho

marble jackal
#

I can produce it for you, but I would like you to show what you tried to do, so I can tell you were it is going wrong

#

first of all, you know this new code can not be placed in something like sensor.yaml right?

compact robin
#

I ended with this mess:

  - sensor:
      - name: "Temperatura Fora Teste"
          unique_id: temperatura_fora
        unit_of_measurement: 'ยฐC'
        value_template: "{{ state_attr('weather.accuweather_house', 'temperature') }}"
#

But it gives synthax error when I post it on HA VSC

#

I am putting in configuration.yaml, which is the right place to, right?

#

At least that's the place I had the old (and current) one.

marble jackal
#

unique_id is indented too far

#
template:
  - sensor:
      - name: "Temperatura Fora Teste"
        unique_id: temperatura_fora
        unit_of_measurement: 'ยฐC'
        state: "{{ state_attr('weather.accuweather_house', 'temperature') }}"
#

this should work

#

but if you place it where it was, it might break everyting coming after it, if there are more sensors belonging under the sensor: key, they will not work anymore

#

there are two different integrations here, the old template sensors are using the sensor: integration, and should be under that key

#

the new format uses the template: integration, which should be a separate section in your configuration.yaml

compact robin
marble jackal
#

sorry, my bad

#

value_template should be state

#

so that will fix both issues

compact robin
#

I've added it in a different place of configuration.yaml to avoid errors, but still getting them. But I understand what you meant.

marble jackal
compact robin
#

Was testing it out before saying anything, it did work! Thank you so much @marble jackal!
Think now with this as base I will be able to create the others I intended. Have a wonderful day man.

stark spindle
#

I'm creating a frost warning, and quickly getting out of my templating depth.
so far I have this:

{{ state_attr('weather.dark_sky', 'forecast')[1]['temperature'] <=2}}

Though I've realised I need the output to tell me wether any of the forecasted temperatures in the next 16 hours are equal to or below 2ยบC, not just for the next hour (dark sky provides hourly temp forecasts) which I have currently ([1]).

Am I right in thinking substituting [1] for [1-16] would do what I require? or am I doing something I do not intend/is there abetter way to achieve my goal?
Thanks in advance for any assistance.

marble jackal
arctic cape
#

Hello. How can I get a full list of my addons and integrations with a template?

marble jackal
#

as far a I know you can't. You can get the entities of an integration, but there doesn't seem to be a way to get the intgration of an entity

#

for add_ons you could use update entities

#

{{ states.update | selectattr('attributes.entity_picture', 'defined') | selectattr('attributes.entity_picture', 'search', '/addon') | map(attribute='name') | map('replace', ' Update', '') | list }} for add-on

marsh cairn
#

Is it possible to create big random numbers with a template? I need random numbers with exactly 20 digits. The random integration can't handle such big numbers.

wheat junco
#

Maybe you could use a template and append multiple random numbers together?

#

Then you could also just cutoff any excess using something like {{ states('sensor.random_number')[:20] }}

wheat junco
#

I'm beginning to see your problem as I try this out myself...

marsh cairn
#

19 digits seem to be the magic barrier. ๐Ÿ˜…

wheat junco
#

oh, of course it would be something like that. lol

#

I was trying to get it to treat it like a string, but since it's only numbers, it seems to ignore my attempts.

mighty ledge
#

i believe that's outside the integers range

#

Yep

#

the max value you can do with an integer is 15 characters

#

so... 999999999999999

#

and the max range for selecting a random number is 100000

#

@marsh cairn what do you actually need this for?

#

hmmm, what you could do is...

plain magnetBOT
mighty ledge
#
{% set ns = namespace(items=[]) %}
{% for i in range(20) %}
  {% set ns.items = ns.items + [ '0123456789' | random ] %}
{% endfor %}
a {{ ns.items | join }}
#

you'd have to put a letter in front of it to avoid errors in python to keep it a string.

wheat junco
#

Nice. Maybe he can use it.

marsh cairn
#

I'll give it a try. Thank you!

hollow mortar
# marble jackal In what kind of sensor are you using this config?
  - platform: average
    name: "Daily average outside temperature yesterday"
    unique_id: "daily_average_outside_temperature_yesterday"
    entities:
      - sensor.fasada_temperature
      - sensor.aqara_temperature_1
    end: "{{ now().replace(hour=0, minute=0, second=0) }}"
    duration:
      hours: 24 ```
#

sorry for late reply... you think its the sensors fault?

marble jackal
hollow mortar
#

Yes

marble jackal
hollow mortar
#

Will that reset at 0:00:00?

marble jackal
#

The start will be yesterday at 00:00, the end will be today at 00:00

hollow mortar
#

Ok I will try, thanks !

ancient lynx
#

Hi all. I'm looking to make a template that checks if there is an event at any point during the day that contains a certain word. I know how to check to see if the next event contains that word, but not if it exists at any point during the day. How would I go about that, while also not having things like an all-day event throw it off?

hollow mortar
marble jackal
#

Could be, maybe create an issue for it

hollow mortar
#

Its calculating value for next interval

marble jackal
#

Is one of the two sources unavailable?

hollow mortar
#

Not at the time of checking

#

You think it may be that it starts this sensor before those temperature sensors become available?

#

That would most likely be the case I think. One is a Hue, another is Zigbee(deconz)

hollow mortar
#

I cant seem to find an official way of doing a sensor like this, even if its ugly?

marble jackal
#

Your screenshot states count sources: 2 and available sources: 1, so that's why I asked

#

As it is data from yesterday it should not really matter which comes online first

hollow mortar
#

I see. Other "today" sensor has 2 out of 2. Maybe that is the bug

#

Im pretty sure now this is where the bug is coming from. Is it possible to make this sensor wait for those 2 to become available? It probably wont recalculate with 2 out of 2 before midnight.

#

Because rarely the whole sensor is "unavailable" (probably then its 0 out of 2) but couldnt seem to exactly reproduce it, because I cant restart HA everytime I want.

#

I wouldnt in a million years figure that out, I have so many sensors just for this central heating, thats why Im doing everything from scratch before I iron all bugs like these out.

hollow mortar
radiant vault
#

How do I group multiple phones to get notifications at once?

heavy crown
#

Hi, I have a sensor that totalizes the number of hours one of my lights is on (history_stats), this however is only showing for as long as my recorder has states (10d at present). How can I move the daily total into long term statistics? I have setup sensors for total/total_increasing/measurement but they also show the values intra-day...I only want the total of the day tracked. ```
- name: "PC Game On LT1"
unique_id: PC_Game_On_LT1
state_class: total_increasing
state: "{{ states('sensor.pc_game_on') |float(0) }}"

marble jackal
#

It needs an unit_of_measurement to be added to long term statistics

heavy crown
#

so that would be hours then I guess...thx

mental violet
#

Hello, I have a template sensor with 12 attributes which all store a list.
On the date 1.1. now all entrys on all 12 attributes should be deleted (or set to an empty list aka [])
How can I do that?

marble jackal
#

You need to convert it to a trigger based template sensor then

mental violet
#

ah ok, yes I am sitting right now on it

#

can you define an action in a "trigger template sensor" based on which trigger triggered, if I have 2 triggers? aka how in automations you can use trigger ids?

#

would this work correctly?:

      monthly_tally_1: >-
        {%if trigger.idx == 1%}
          {{[]}}
        {%else%}
          ...
        {%endif%}```
marble jackal
#

Yes, that's the way to do it

#

Or define a trigger id and use that

mental violet
#

I tested it right now, and the attribute still has all his entrys in that list.

marble jackal
#

What did you use as trigger?

mental violet
#
    - platform: state
      from: "0.0"
      not_to: "0"
      entity_id: input_number.number1
      id: "0"
    - platform: state
      from: "12"
      to: "1"
      entity_id: sensor.month
      id: "1"```
these are my 2 triggers
nocturne chasm
#

why does this capitalize the first letter of every word except the first word?
{{ (states|selectattr('entity_id', 'search', 'node_status')|selectattr('state', 'in', 'alive, unavailable, unknown')| map(attribute='object_id')|list|replace('[', '')|replace(']', '')|replace('_node_status', '')|replace('_', ' ')|title ) }}

surreal ocean
#

is it possible to template a header image url?

marble jackal
waxen rune
#

I was about to migrate all my legacy templates to "the modern format". But it seems that you can't specify a friendly_name in the modern template: format.
You define a name: which then is converted to an entity name. On most sensors, I don't want that since I may have several entities with same "display name". Also, the conversion of Swedish characters creates confusing entity names sometimes.
This means I will end up using the name for entity name and then use customize.yaml (which is not recommended and supposed to be phased out) for every template sensor. This is somewhat confusing. Is this really the preferred way or am I missing something?

buoyant pine
#

Tbh I haven't bothered switching to the new format since the legacy format still works

marble jackal
#

name specifies the friendly name, and is used for the entity_id

#

If you add a unique_id you can change both in the GUI

#

You can also not provide a name and add a friendly_name attribute

#

The unique_id will then be used for the entity_id, but (if I'm not mistaken here) the object_id will start with template_

#

Anyway, no need to use customize if you add a unique_id

waxen rune
#

I sure can change the "display name" in the GUI, but when you have like a hundred templates, it's much faster in YAML.
I think it's strange you can't specify them both separately. I, for example, always use English entity names (for easy sharing examples), but Swedish friendly names.

#

Well, I guess I'll stick with the old format them. Thanks for explaining.

inner mesa
#

Or:

You can also not provide a name and add a friendly_name attribute

waxen rune
#

If it does, everything is fine ๐Ÿ™‚

inner mesa
#

Adding a friendly_name before was exactly the same as providing a friendly_name attribute

#

You can add whatever attributes you want

mental violet
#

is there a way to break or return nothing in a template? So I can make nested ifs easier to read?

waxen rune
inner mesa
#

You sure?

waxen rune
#

Gives me:

friendly_name: altandorr_battery_level_tmpl_test icon: mdi:battery unit_of_measurement: % device_class: battery

#

So either I am doing something very wrong , or I just found a bug

#

(the device_classcomes from customize_global)

#

I'll restart just in case I messed something up..

#

Same thing. It's like HA overrides my manually created attribute

waxen rune
# inner mesa You sure?

Hmm.. I tried to create a completely new template sensor.

  - name: "Template Test Sensor Name"
    unique_id: unique_id_on_my_template_test_sensor
    state: "Template Test Sensor STATE"
    attributes:
      friendly_name: "Template Test Sensor Friendly Name"

Gives me: https://ibb.co/pZhHxhN

#

So friendly_name is not used and name becomes entity_name

#

unique_id is not used in the GUI at all

inner mesa
#

maybe that's why TheFes said

You can also not provide a name and add a friendly_name attribute

waxen rune
#

Yeah. I just thought you said the opposite ๐Ÿ™‚

inner mesa
#

unique_id isn't ever "used" in the UI, but it allows you change the name and entity_id in the UI

#

well, I thought it would

waxen rune
#

I wish you were right ๐Ÿ‘

inner mesa
#

without a name:

#

then you can change the entity_id to be whatever you want, but you'd have to do it in the UI

waxen rune
#

Yep. But with 100+ templates, I think I'll wait until the modern template gets more options/settings - or the legacy template stops working (which ever comes first)

inner mesa
#

I suppose the thinking is that you have to enter it somewhere, so just do it in the UI along with every other entity

nocturne chasm
#

Give me customize.yaml or give me death

marble jackal
heavy mortar
#

Whatโ€™s the best approach to setting an iconโ€™s color for 30 seconds after a sensor is triggered?

{% if is_state('binary_sensor.kitchen_motion','off') %}
green
{% else %}
red
{% endif %}

#

Thatโ€™s what Iโ€™m using now. I just want it to stay red for 30 seconds before going back to green. To simulate the motion cool down period

tacit sun
heavy mortar
tacit sun
#

Are you utilizing the developer tools template tool?

#

I have found it to be helpful as I fumble through the templates... haha

heavy mortar
#

Thanks! Jinja, that's what I couldn't find yet in terms of the syntax being used

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

waxen rune
marble jackal
#

Do note it adds template_ before the unique_id

heavy mortar
waxen rune
heavy mortar
#
{% set stateNow = (states.binary_sensor.kitchen_motion.state) %}
{% set timeThreshold = (now() - ls < timedelta(seconds=10)) %}

{% if (stateNow == 'on' and timeThreshold == True) %}
orange
{% elif (stateNow == 'on' and timeThreshold == False ) %}
red
{% else %}
green
{% endif %}```
#

^ this is working well ๐Ÿ˜„

#

Can we reference the last time an action was performed? "toggled"?

marble jackal
#

You can see the last time it had a state changed

#

But you are already using that

heavy mortar
#

Asking, as I'd like to apply this same logic to a garage door, to show a visual feedback that the action is being performed. But, with a single binary sensor for on/off, my logic fails to update the icon when an action is performed to close the door.

marble jackal
#

That is the last_changed object

heavy mortar
#

But, my last_changed logic fails, since the door has been "open" for a while

#

So, my mental rough logic would be: if the door is open, and last changed is greater than 30 seconds, AND you just performed an action, then color = orange

#

The last_changed would only be updated once the door is actually closed and the sensor is updated again to off

marble jackal
#

What do you mean with "just performed an action"?

heavy mortar
#

Double tap to perform the toggle action

#

Ohhh. I'm an idiot I think.

#

I have a door sensor, but also switch

marble jackal
#

I see only a motion sensor in that template, the is no reference to any button press action

heavy mortar
#

So I just need to include the switch in my logic

#

I'm using a mushroom card

#

Let me paste in my whole code

marble jackal
#

Yes, and you should also now that templates with now() are rendered once per minute (on the minute) so it will probably stay orange somewhere between 10 seconds and a minute

#

Depending on the time of the button press

heavy mortar
#

Of note, "kitchen_motion"... is the garage door sensor

inner mesa
#

Of course it is ๐Ÿ™‚

heavy mortar
heavy mortar
marble jackal
#

A trigger based template sensor triggering on a state change of the garage door sensor and an auto_off of 10 seconds

#

Then you can use that binary sensor and don't have to rely on last_changed or now()

heavy mortar
#

Ok. I'm going to attempt to digest that ๐Ÿ˜„

heavy mortar
#

Ah, so Automation -> Trigger: Template Trigger?

marble jackal
#
template:
  - trigger:
      - platform: state
        entity_id: binary_sensor.kitchen_motion
        from: "off"
        to: "on"
    binary_sensor:
      - unique_id: cooldown_garage_door_sensor
        name: Cooldown garage door
        state: "{{ true }}"
        auto_off: "00:00:10"
#

This will create binary_sensor.cooldown_garage_door which will stay on for 10 seconds after the kitchen motion sensor turns on

heavy mortar
#

Amazing. Much easier to use

#

And similar format for creating a binary_sensor from a switch vs. another binary_sensor as well?

marble jackal
#

Yes, just change the trigger to the switch entity

#

And give it a different unique_id and name

#

And don't repeat the template: line in your configuration

heavy mortar
#

And, potentially dump question, I'm just adding this to the code for the card before I make any references to cooldown_garage_door_sensor

marble jackal
#

This code needs to be added to configuration.yaml, not to your dashboard code

heavy mortar
#

Roger that.

#

Man, thanks for being so responsive!

#

Would modifications to the template section of the configuration.yaml require a restart? Or does one of the reloadable subsections cover that?

inner mesa
#

the one that says "template entities"

heavy mortar
#

Is that list of reloadables dynamic? I don't have Template Entities, so wondering if I need to restart and then I'll see it?

inner mesa
#

then you don't have one yet

heavy mortar
#

Gotcha

inner mesa
#

you need to have at least one, and yes, it's dynamic

heavy mortar
#

Awesome.

#

THIS IS FUN ๐Ÿ˜„

heavy mortar
marble jackal
#

The entity is binary_sensor.cooldown_garage_door

heavy mortar
#

Yes. I'm looking at it in the Dev -> States

#

It's just 100% on

marble jackal
#

And the kitchen motion sensor has changed from off to on?

heavy mortar
#

Yup

#

Would the default state of the binary_sensor.cooldown_garage_door be off?

#

In the dev tools, I can see the state changing for the kitchen motion sensor, but the cooldown is staying on

marble jackal
#

It would start at unknown after first creation, then after the first time it has been triggered it should turn on, and after 10 seconds it should turn off

heavy mortar
#

So a full restart, it should show as unknown?

marble jackal
#

No, triggered based template sensors retain their state after restart or reload

heavy mortar
#

Gotcha.

#

Setting the state manually to off, it's staying off after the kitchen motion triggers

marble jackal
#

I see what's wrong

#

The - before binary_sensor should not have been there

#

With it it indeed basically creates a binary sensor which is always on

#

I removed it in my code above

heavy mortar
#

Sweet! That's working now

#

This is much superior to the time based method, and, will be super helpful for future stuff!

marble jackal
#

Nice ๐Ÿ‘๐Ÿผ

heavy mortar
#

Note to self for future garage door setups: Have two contact sensors for open and closed. ๐Ÿ˜„

#

(YAML meme)

obtuse wraith
noble pawn
#

can someone please give me a hint why my mqtt sensor do not work anymore since Home Assistant 2022.12.0?

#

they are all configured like:

plain magnetBOT
noble pawn
#

and so on

#

nvm, fixed it

pine musk
#

hello, wise men (and women)... got a template question.

#

I have a input_select named remote, with values: remote.living_room & remote.bedroom

#

and 2 apple TVs. Living_room & Bedroom

#

I am trying to send commands, to the selected apple tv

tropic hill
#

With mqtt.dump i get this data

edi/cmd/telinit,{"args": "4", "user": "tioan", "replyTo": "edi.msg.edish.send.21204", "touchedByExchangeTopicBridge": "True"}

How can i use the args value, in this example 4 as an value_template for an mqtt text sensor?

pine musk
#

like this:

    - state_topic: "HomeAssistant/rtlsdr/event/234"
      name: Outside_Humidity
      unit_of_measurement: "%"
      icon: mdi:water-percent
      value_template: "{{ value_json.humidity }}"

#

your value_template would look like:

value_template: "{{ value_json.args }}"
#

did that help ?

tropic hill
pine musk
#

Apple TV selector

tropic hill
pine musk
#

glad to be of service

pine musk
#

what is wrong with this? :

service: remote.send_command
data:
  device_template: "{{ input_text.remote }}"
wheat junco
#

Without seeing more (or if there is history above since I just logged on), I would say it should be formatted like this, no?

service: remote.send_command
target:
  entity_id: remote.tv_room
data:
  command:
    - PowerOn
    - Mute
  device: Receiver
  delay_secs: 0.6
pine musk
#

I am trying to use a template to choose between 2 appleTVs

#

so I. don't need 2 sets of scripts

wheat junco
#

Sorry. I've not tried that, so I'll bow out. I can only reference what's listed here (https://www.home-assistant.io/integrations/apple_tv/). Depending on what value "{{ input_text.remote }}" hold, you should be able to substitute it on the examples they list. Without seeing more, I'm not sure.

pine musk
#

yeah, that's what I'm working from

wheat junco
#

what does "{{ input_text.remote }}" contain?

pine musk
#

remote.Living_room or remote.bedroom

wheat junco
#

Okay, so the line that says entity_id: should look like this I would say: entity_id: "{{ input_text.remote }}" since it contains the remote entity.

pine musk
#
service: remote.send_command
target:
  device_id: "{{ input_text.remote }}"
data:
  device: "{{ input_text.remote }}"
  hold_secs: 1.5
  command:
    - home_hold
    - select
wheat junco
#

I think you need to keep the device_id: line and remove the device: line listed below that.

inner mesa
#

That is not the way to get the state of an entity

#

If that's what you're trying to do

pine musk
#

RobC, yes!

wheat junco
#

I'll bow out. Thanks @inner mesa

pine musk
#

thanks cbhiii

inner mesa
#

Did you the docs?

pine musk
#

yes, but I am confused

inner mesa
#

I doesn't seem like you did

#

Just looks like a guess

inner mesa
#

The second tells you how to get a state.

#

I gave you a link

pine musk
#
service: remote.send_command
target:
  device_id: "{{ states.input_text.remote }}"
data:
  hold_secs: 1.5
  command:
    - home_hold
    - select
#

better?

inner mesa
#

No

#

Try again. I gave you the direct link

pine musk
#

i am reading

#
service: remote.send_command
target:
  entity_id: "{{ states.input_text.remote.state }}"
data:
  hold_secs: 1.5
  command:
    - home_hold
    - select
inner mesa
#

Now read the big warning box

pine musk
#

that got it, thanks @inner mesa

keen holly
#

https://photos.app.goo.gl/7Kdoci42AuUvwU9TA

How do you do a platform correctly? Iv been messing with it and it still only puts a value of unknown when I check it's state, I have it a name after platform once but then was complaing I was initializing it twice idk

keen holly
#

alright so here is whats stumping me

#

`template:

  • sensor:
    • name: Office HVAC Activity
      state: "{{ state_attr('climate.office', 'hvac_action') }}"
  • sensor:
    • name: Kitchen HVAC Activity
      state: "{{ state_attr('climate.kitchen', 'hvac_action') }}"
  • sensor:
    • name: Dining Room HVAC Activity
      state: "{{ state_attr('climate.dining_room', 'hvac_action') }}"
  • platform:
    name: office heating Today
    entity_id: sensor.office_hvac_activity
    state: 'heating'
    type: time
    start: '{{ now().replace(hour=0).replace(minute=0).replace(second=0) }}'
    end: '{{ now() }}'`
inner mesa
#

the last bit is nonsense. What are you trying to do there?

#

history_stats?

keen holly
#

im trying to count how long heating is on

#

and i had that after platform

#

it complained

inner mesa
#

so...history_stats?

#

where did you get that?

keen holly
#

the first part is working as expected

inner mesa
#

and the first line says

#

- platform: history_stats

keen holly
#

yes i said i removed that

inner mesa
#

and that was wrong

keen holly
#

il send you the error that makes

inner mesa
#

why?

#

no, don't

#

it's just wrong

#

don't put it under template:. It belongs under sensor:

keen holly
#

mhmmmmmmmmmmmmmmmmmmmmmmmm ok let me try that

inner mesa
#

blindly copying from the forum is bad

keen holly
#

come on now that was completely blind, i tried to find info and other examples of platform being used

#

*wasnt

#

i thought history stats was just the name that i could then call on

#

still getting error Invalid config for [template]: [platform] is an invalid option for [template]. Check: template->sensor->0->platform. (See /config/configuration.yaml, line 30).

plain magnetBOT
keen holly
#

thats the new code now

inner mesa
#

don't put it under template:. It belongs under sensor:

#

like in the docs

keen holly
#

i didn't think i could just say sensor outside of template in there ok let me try that

#

even copy and pasting in the example it gets mad

#

so its def not my spacing

#

` duplicated mapping key (41:1)

38 | start: "{{ now().replace(ho ...
39 | end: "{{ now() }}"
40 |
41 | sensor:
------^
42 | - platform: history_stats
43 | name: office heating Today `

inner mesa
#

you already have sensor: somewhere

#

put it under that

#

duplicated mapping key (41:1)

plain magnetBOT
keen holly
#

the secret was pulling it out on its own

#

I really appropriate the help

heavy mortar
#

For Mushroom Template Card whatโ€™s the syntax for referencing the selected entity in following fields? To get the Name?

heavy mortar
#

Figured it out: {{ device_attr(entity,'name') }}

marble jackal
#

That's the name of the devices

#

Which could be different from the name of the entity

marble jackal
heavy mortar
#

Because entity != device?

marble jackal
#

Correct, some entities, like helpers and groups won't even have a device

#

The device is more like the physical object, like a washing machine. Several entities can belong to a device, like s switch to turn it on and off, a sensor to indicate the state, a timer to set a delayed start etc

#

Your new template binary_sensors won't have a device either

inner patrol
#

Hello all, I need some assistance with a quick template. I have a template which gets the warning details for weather; however I want to put each warning on a separate line. Currently it displays them all after each other. Here is the code
{%- for state in state_attr('sensor.highett_warnings', 'warnings') -%}
{{state.phase | upper}} - {{ state.short_title}}
{% endfor %}

orchid onyx
#

Hello, I have a fan tamplate and so far so good. Now i'm trying to make 3 preset speeds but cant get it working. Any suggestions? Here is my code:
https://pastebin.com/wfZn00Y3

waxen rune
# marble jackal With `unique_id` and `friendly_name` attribute: ```yaml sensor: - unique_id: t...

I found a way to get the entity_name I want AND the display name, without using customize, but it requires creating them first and renaming them afterwards. However, it works to rename them in YAML.
1: Create the template sensor with the future entity_name you want (sensor.test_sensor) as name and prepare the display name you want for fast search and replace:

    - unique_id: test_sensor
      name: test_sensor
      # name: 'The Display Name you really want'
      state: ""

2: This creates the sensor with the entity name I want (sensor.test_sensor). Now reload.
3: Change the name to the display name you want
4. Reload and profit.

#

This way you don't get the leading 'template_' and you can still avoid the GUI.
If you prepare a separate file with all the templates you create, you can now search and replace all ' name' with '# name' and all ' # name' with ' name' and copy them all at once.

velvet sigil
#

Hi,
why this template doesn't work?

  entity: light.christmas_lights
  icon: |-
    {% if is_state('light.christmas_lights, 'on') %}
    none
    {% else %}
    mdi:pine-tree
    {% endif %}```
#

I cannot change icon dependent on state

mental violet
#

try icon_template:
i think it has to be a "_template" to accept a template

velvet sigil
#

doesn't work. Its then show attribute icon permanentaly

mental violet
#

Than i am sry ๐Ÿ˜ฆ than you have to wait for a pro

velvet sigil
#

thanks for the effort

marble jackal
#

@velvet sigil only mushroom template cards can use templates

marble jackal
velvet sigil
marble jackal
#

and what is your goal? It looks like you don't want an icon when the light is on

marble jackal
#

try: icon: "{{ 'mdi:pine-tree' if is_state(entity, 'off') }}"

#

with the template you are currently using, your result will be the string "none"

#

not the special empty thingy none

velvet sigil
velvet sigil
marble jackal
#

you need mdi:pine-tree

#

by bad

velvet sigil
#

fixed it , doesn't work aswell

marble jackal
#

works fine here

velvet sigil
#

how come

marble jackal
#
type: custom:mushroom-template-card
primary: Christmas lights
secondary: ''
icon: '{{ ''mdi:pine-tree''  if is_state(entity, ''off'') }}'
entity: input_boolean.test
velvet sigil
#

Is here any mistake I cannot see ?!

primary: Christmas lights
secondary: ''
icon: '{{ ''mdi:pine-tree''  if is_state(light.christmas_lights, ''off'') }}'
entity: light.christmas_lights```
marble jackal
marble jackal
#

in the template

#

but as you specified it as entity, you can use the variable like I did

velvet sigil
#

done thank you, fixed everything. now it works

frail scarab
#

Hello Everyone,
i'm new here and stuck at a sensor-template which i didn't get to run
Is there someone who can help me?

#

I try to get a sensor from a sensor attribute

buoyant pine
#

Sure, share the template sensor config

frail scarab
#

how is the trick to put code in readable form?

#

@buoyant pine

sensor:
  - platform: template
    sensors:
      sensor_pricelevel:
      friendly_name: PriceLevel
      entity_id: 
        - sensor.electricity_price_myhome
      value_template: "{{ state_attr('sensor.electricity_price_myhome', 'price_level' }}"
plain magnetBOT
#

To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks.
```yaml
example: here
```
Don't forget you can edit your post rather than repeatedly posting the same thing.

buoyant pine
#

But the problem is you're missing a closing parenthesis in the template and everything below sensor_pricelevel: needs to be indented two spaces

#

Also, you don't need

entity_id:
  - sensor.electricity_price_myhome
frail scarab
#

sensor is from the integration of Tibber (if this helps)

buoyant pine
#

That's not really relevant, no

frail scarab
#

hmmm
i have the entity now but it's unavailable

heavy crown
#

You should use the new (since quite while) way of templating

frail scarab
#

i'm happy to but i don't know how

heavy crown
#
template:
  - sensor:
      - name: sensor_pricelevel
        unit_of_measurement: "ยฐC"
        state: "{{ state_attr('sensor.electricity_price_myhome', 'price_level' }}"
buoyant pine
#

To be fair, the legacy version still works and doesn't have a deprecation announcement

heavy crown
#

and wihtout this unit of course

#

I know but it is better to start ahead

buoyant pine
#

But yeah, it definitely makes sense to use the new format for any new sensors

#

I'm not migrating my old ones unless they deprecate that format

frail scarab
#

never touch a running system ๐Ÿ˜‰

buoyant pine
heavy crown
#

yeah... I now see it too

#
template:
  - sensor:
      - name: sensor_pricelevel
        unit_of_measurement: "โ‚ฌ"
        state: "{{ state_attr('sensor.electricity_price_myhome', 'price_level') }}"
buoyant pine
#

name can have spaces and stuff btw

frail scarab
#

and where we're talking abount a clean way to config....
i would like to have this in a extra file to keep config.yaml as clean as possible

heavy crown
#

in your configyaml put this

#
template: !include template.yaml
#

and the template.yaml should then start alike this

#
  - sensor:
      - name: "Gas Usage"
        unique_id: Gas_Main
        unit_of_measurement:
#

with 2 spaces

frail scarab
#

@heavy crown are you sure with the )?
i would put it behing "myhome'"
here: myhome'),

frail scarab
buoyant pine
#
- sensor:
    - name: sensor_pricelevel
      unit_of_measurement: "โ‚ฌ"
      state: "{{ state_attr('sensor.electricity_price_myhome', 'price_level') }}"
frail scarab
#

that's why i don't like yaml ๐Ÿ˜‰

buoyant pine
#

unique ID is optional. It just lets you change settings for the entity in the UI

heavy crown
#

I use the unique id so I can delete it via the gui...I play around alot

#

and as @buoyant pine said...settings

frail scarab
#

i can do this via GUI?

#

it makes so much fun to me to work with yaml, but i can live with working with gui only
(contains slightly sarcasm)

buoyant pine
#

No, you can't create template sensors in the UI

frail scarab
#

How can i add a screenshot here?

heavy crown
#

Better get used to it.. the more complex stuff require yaml

#

although the devs DO work on improving the GUI

#

e.g. they just moved scrape to GUI

#

ss not allowed

marble jackal
#

Use imgur or similar to post images

frail scarab
#

i really like the gui of HA
I'm currently switching from OH

#

okay, then in this way:
It works!
@heavy crown @buoyant pine Thank you for your help!

plain magnetBOT
#

viper539 Please use imgur or other image sharing web sites, and share the link here.

Image posting is blocked in most channels to discourage people from sharing text as images. Sharing text as images assumes that everybody sees the world as you do, which isn't the case. Some people are colour blind, or have visual impairment that means they can't make sense of an image of text.

mighty ledge
#

@frail scarab ^

frail scarab
#

i have to leave now

#

have a nice evening

stiff crane
#

Does anyone how I can template my today's Google Calender events?
{% for cal_events in expand(states.myCALNAME) %} {{ as_timestamp(cal_events.attributes.start_time) | timestamp_custom('%H:%M') }}, {{ cal_events.attributes.message }} {%- endfor -%}
Does not work. (only one event)

grizzled bluff
#

generic_thermostat: How to get the target_temp as sensor_value to show in a the mini-graph-card?

mighty ledge
mighty ledge
stiff crane
mental violet
#

can i set a variable as the friendly name of this sensor via:
{% set name = this.get('friendly_name')%}
or is the syntax off or is there another way?

marble jackal
mental violet
#

ok thank you ๐Ÿ˜„

marble jackal
#

You can use get() if you're unsure if it exists at all

mental violet
#

is there a this.attribute.name?
when I am inside of an attribute template? or can I get the name of the attribute I am currently inside anyway?

inner mesa
#

I don't know what the last part of your question means