#templates-archived

1 messages ยท Page 50 of 1

gritty grail
#

I make a sensor using template state: "{{ state_attr('climate.home','equipment_running') }}" this can have 3 values, " " "fan" or "coolcomp,fan" can i somehow rename those when i create the sensor, i want off, fan, cooling

inner mesa
gritty grail
#

this attribute "compCool1,fan" causes problems, | replace("compCool1,fan", "On") gives value OffcOffoOffmOffpOffCOffoOffoOfflOff1Off,OfffOffaOffnOff I think it does not like the comma between compCool1 and fan. Any idea how to handle this? i tried compCool1* but did not work

inner mesa
#

It doesn't look like you followed the example I pointed to

gritty grail
#

- name: "HVAC Status" state: > {{ state_attr('climate.home','equipment_running') | replace("", "Off") | replace("fan", "Fan") | replace("compCool1,fan", "On") }}

inner mesa
#

yeah, not at all like I pointed to

#

๐Ÿคท

gritty grail
#

aaa i see, let me try

#

thc

#

thx

eternal island
#

Hello, I have a problem to hopefully solve: I create a markdown card to show lyrics of songs. There are parts (in the start and end) that I want to delete, can someone explain to me how can I edit that to delete the first and last line for example. Thanks.

lyric comet
#

You could try something like this:

{% set lines = 
"1 cdcdcd
2 cdcdcdc
3 cdcdcd
4 cdcdcd"
%}
{% set list = lines.split('\n') %}
{% set count = list | count %}
{{'\n'.join(list[1:count - 1]) }}
#

So it takes the lines in a string, splits it on new lines and then keeps the middle lines.

eternal island
#

But every song has their own lines... The text get it from a link and it's for every song a new one.

lyric comet
#

Yes, but presumably this is a string which you replace the set lines line with your string. I just gave you a working example so you could insert your data into the lines

#

You asked how to remove the first and last line

eternal island
#

Oh, of course... Too tired... ๐Ÿคฃ ๐Ÿฅด
Thanks @lyric comet !

eternal island
#

And last question @lyric comet, how can I delete only the last 5 characters ?

lyric comet
#
{{lines[:-5]}}
gritty grail
solid fox
#

How can I add 1 minute to a now() datetime object?

#

and then assign it to a helper with:

data: {}
target:
  entity_id: input_datetime.cooldown_living_room_motion_sensor_1_minute
marble jackal
#

now() + timedelta(minutes=1)

solid fox
#

Running this:

data: {{ now() + timedelta(minutes=1) }}
target:
  entity_id: input_datetime.cooldown_living_room_motion_sensor_1_minute

returns this:

#

That helper is a 'date and time' datetime helper

#

The template should set the helper to the current time + 1 minute

#

Maybe there's something there though. Just looking at what it's setting the time to, it seems it's setting it to the current value of the helper + 1 minute and formatting it as a time only. I don't understand if the '>' character is being used a stream operator or not. Greater than doesn't make sense to me here

marble jackal
#
# wrong
data: "{{ }}"

# correct
data:
  datetime: "{{ }}"
plain magnetBOT
soft breach
#

no way round that one for device tracker.

radiant spindle
#

mmh, what's wrong with that? - name: usd_change_percent state: "{{ 100*((float(states("sensor.yahoofinance_chf_x"))/0.87)-1) }}" unit_of_measurement : '%'

#
in "/config/configuration.yaml", line 93, column 9
expected <block end>, but found '<scalar>'
in "/config/configuration.yaml", line 94, column 40```
inner mesa
#

You have a space before the :

radiant spindle
#

oh

inner mesa
#

And you're also using the same type of quotes inside and out of the template

heavy island
#

I have a template sensor for tracking the energy for the lights in my living room. This is done via a power meter on the circuit running to those lights. There is one other thing on that circuit -- an outlet in the crawl space that also has some lights plugged into it, but via a smart plug with energy monitoring. So I have this template that subtracts the energy use of the smart plug from the total for that circuit:

        {% set total = states('sensor.crawl_space_and_living_room_leds_total_energy') | float(0) %}
        {% set crawl_space = states('sensor.crawl_space_lights_total_energy') | float(0) %}
        {{ (total - crawl_space) if (total - crawl_space) > 0 else 0 }}```

I had the 0 checks in there because for a while it was negative because I couldn't figure out how to clear the data from the crawl space lights plug. But looking at the history graph for that template sensor I see that it does drop to zero if say the sensor on the circuit goes away when rebooting. I think that has messed up my energy graph in a strange way (all of the sudden it's showing an impossibly large total energy use for that sensor). 

Is there a better way to bridge interruptions in the circuit sensor? like have the energy use report as the last non-0 value instead of 0?
marble jackal
steep raven
#

How can i create a sensor wich displays how much kw is left in our battery we get how much % it is live. 100% is 7kw and 0% 0kw ofc xd

steep raven
#

been trying some things with this sensor: - name: battery soc kwh unit_of_measurement: 'kWh' state: > {% set procent = state_attr('sensor.solis_battery_soc', '%') %} {% set kwh = ('7', 'Kwh') %} {{ procent * kw }}
but it keeps saying status unavailable

obtuse zephyr
#

It's not clear what you're trying to do with your line 2 there...

I think what you want is just {{ 7000 * (state_attr('sensor.solis_battery_soc', '%') / 100) }}

steep raven
#

i figured it out eventually ๐Ÿ˜…

#

this is working in my templates section now

      - name: "Battery SOC kWh"
        unique_id: "solis_battery_soc_kwh"
        unit_of_measurement: kWh
        state: >
          {% set batterypro = states('sensor.solis_battery_soc') | float(0) %}
          {{ batterypro * 7 / 100 }} ```
steep raven
#

so eeuhm i have now this adjusted with losses etc but i cant seem to get it to round to 2 decimals and show only 2 decimals

      - name: "Battery SOC kWh Bruikbaar"
        unique_id: "solis_battery_soc_kwh_bruikbaar"
        unit_of_measurement: kWh
        state: >
          {% set batterypro = states('sensor.solis_battery_soc') | float(0) %}
          {{ batterypro * 7.1 / 122.5 | round(2) }} ```
inner mesa
#

You're rounding 122.5

#

Add parentheses

steep raven
#

what?

#

seems to work now it has updated tho idk for how long

marble jackal
#

You are only rounding 122.5

steep raven
#

i have now this on the last line {{ batterypro * 7.1 / 122.5 | float | round(2) }} does this work then for the number/

marble jackal
#

Still only rounding 122.5 and the float doesn't do a thing here

inner mesa
#

You need to review order of operations

marble jackal
#

Use parenthesis (( and )) around the formula to round the result

plain magnetBOT
silver pewter
#

Hi all! Would be awesome if someone knows how to do this!
I have a automation with reapeat UNTIL.
And i want it to repeat until a specific rfid tag opens the door.
This is what the event looks like when rfid tag number 41 opens the door.
As condition template
http://pastie.org/p/1UpBT4pPOyKqKlcNKikV6s
I have this code in another automation that might help? i dont know hehe ๐Ÿ˜„
http://pastie.org/p/44j7nye4u13u0KlI8fTpgS

If this even works? in UNTIL

#

hmm cant remove the bot message ๐Ÿฅน sry

floral shuttle
#

back with another datetime template, and this time I have no choice but compare it with a string. Would this be the best way to do so: {{today_at(states('sensor.master_bedroom_schedule_day')) > today_at(states('input_datetime.alarmclock_wd'))}}

#

the schedule is a template sensor it self, based on a rest sensor calling the Hue api... its state is string 08:00, the datetime obvious format is 07:30:00 so most obvious way I found was throwing them both in the today_at()..

#
         states('input_datetime.alarmclock_wd')}}``` also works but that is just luck and not very robust..
marble jackal
#

Looks fine, but if both states use a leading 0 in the hour notation, a string comparison will also work.

dense swan
#

If I wanted to make sure an entity is getting updated but may not change (e.g. Temperature staying the same) which do I want? {{ states.sensor.acurite_tower_a_15338_temperature.last_updated }} or {{ states.sensor.acurite_tower_a_15338_temperature.last_changed }}? Trying to see if my integration goes stale and monitor that value.

marble jackal
plain magnetBOT
marble jackal
#

@ruby vault remove condition:
This is the short hand notation for template conditions:

trigger:
  - platform: foo
condition:
  - "{{ some single line template }}"
  - |
    {{ a
      multi line
      template
    }}
ruby vault
#

well, thast the parent key. I just didn't CnP it in the second one

#

interestingly you wrote conditionS, I literally hvae 'condition' in every one of my automations. SO I Don't think thats it

marble jackal
#

No that's my bad, typo. I'm on mobile

ruby vault
#

yeah, allg. How come you can edit your post. ๐Ÿ™‚ I can not edit mine

marble jackal
#

But that's my point, you only need the parent key. You had

condition:
  - condition: |
        {{ template }}
ruby vault
#

and I have other automations using the one line short hand syntax and thats good

#
   condition:
    -|
      {%- if ('from_state' in trigger) and ('to_state' in trigger) -%}
        {{ trigger.from_state.state != trigger.to_state.state }}
      {%- else -%}
        true
      {%- endif -%}
#

I mean, yaml syntax wise it passes right

marble jackal
#

Without seeing the rest, I can't judge if that's correct

ruby vault
#

its just the same condition, short hand syntax doesn't work, old syntax does

marble jackal
#

It's valid yaml, that doesn't mean HA can work with it

ruby vault
#

yeah, but I see no errors

#

in the logs

marble jackal
#

That's because it will treat the whole thing as one template

#

Post the entire automation

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.

ruby vault
marble jackal
#

That condition can be replaced by adding to: null to your state trigger by the way

#

But it should work like this

ruby vault
#

sure, this automation is wild and super old and probably redundant now in many ways but it solved some problem from 5 years ago. ๐Ÿ™‚
but yeah, I am seeing this 'short syntax' vs 'old syntax' issue in a few places recently and this was the least complicated automation to use as an example.

#

but yeah, it should work fine. THat was my thought also

#

Thanks

pulsar glacier
#

I have an issue with a variable. In the template tab I can use

{{ states('sensor.sovrum_temperature') }}

and get a temperature readout..

when i want to pass that into my front end the following way:

            variables:
              circle_input: "{{ states('sensor.sovrum_temperature') }}"
              circle_input_unit: "ยฐC"

it just passes on the whole string "{{ states('sensor.sovrum_temperature') }}" without processing it though. Why does this happen?

plain magnetBOT
queen girder
#

I'm trying to get 0.92 but regardless of the round value I set, the number always has 15 sub-values

marsh cairn
#

The way your template is set up, you are rounding your devisor only, not the devidend. You need to add parentheses around the whole formula (without the round part).
{{ (states('sensor.load_power') | float / states('sensor.load_apparent_power') | float) | round(1) }}

queen girder
#

Ahhhh, thank you
Stupid mistake

mighty ledge
pulsar glacier
#

ok.. one sec

#

So that guy has a climate control that has temp reporting. I'm just trying to adapt it to get the state from my temp sensor instead

marble jackal
#

That's a custom button card which uses JavaScript

#

Not jinja

pulsar glacier
#

ah

#

gtocha I'll read up on that then.. thanks

mighty ledge
#

Yes, and that's using decluttering templates or button templates

#

there's alot going on with that.

pulsar glacier
#

yeah, I know about the decluttering tempates.. I just need to figure out how to pass a value into that variable

mighty ledge
#

I'm 95% sure thats button card templates

#

which is slightly different

#

anyways, use JS

pulsar glacier
#

ywah it is button-card

#

yep.. trying.. tried just returning the state but I need to read up on what functions etc I can access in JS for HA

mighty ledge
#

"[[[ return states['....'].state; ]]]"

pulsar glacier
#

ah... there a good place for documentation on this? I kinda wanna learn it as well so I'm not just stuck adking questions ๐Ÿ™‚

mighty ledge
#

custom button card

#

as that's the only place with those templates

pulsar glacier
#

ah

#

found it under triggers update.. sorry, and thanks again!

calm tinsel
#

Afternoon all,
I am struggling with adding an RF device through Tasmota RF bridge.
All documents I have found for how to add seems to be no longer valid.

mighty ledge
#

this is not the correct channel

plain magnetBOT
mighty ledge
#

@thorny snow you're mixing the template integration with the serial integration

#

You can't do that

#

also, you're not using the correct entity_id as entity_id's do not have capital letters

#

those configuration variables are all that you can use for your serial integration.

#

so state, unique_id, device_class, unit_of_measurement, state_class are all not valid for your platform: serial setup

verbal juniper
#

I have the following template sensor https://dpaste.org/qd8EP to calculate the COP of my geothermal heatpump.
While it is working, I do get a . for decimal while all other HA sensors are with a comma , ? Any idea why that is?

#

The last two sensors are from my templating yaml

mighty ledge
#

add state_class: measurement

#

and it might translate it to a , on the UI

plain magnetBOT
marsh cairn
#

The serial sensor cannot be in template, but in sensor itself. And the - in front of name seems to be wrong.

plain magnetBOT
marsh cairn
#
  - platform: serial
    serial_port: /dev/ttyUSB0
    name: "Gasverbrauch"```
As i said... not in the template section, but the sensor one.
plain magnetBOT
thorny snow
marsh cairn
#

Almost. The - in front of name is still wrong. Look at my example.

thorny snow
#

i tried to remove the "-" but I get an error message from the file editor:
bad indentation of a sequence entry (21:4)

18 | # Gasverbrauch Sensor
19 | - platform: serial
20 | serial_port: /dev/ttyUSB0
21 | name: "gasverbrauch"
---------^
22 |

#

nevermind - i was one space off in the config

verbal juniper
# mighty ledge add `state_class: measurement`

Lol indeed, oopsie
https://dpaste.org/Z7FhA
Works like a charm, now need to reject values above 6 or so, because when it stops working, gives 0-100W electrical power but heating power is outdated and you get COP's of 100 :-D, which is impossible, sadly :). Or I need to refresh current heating power more often.

mighty ledge
verbal juniper
mighty ledge
#

that's not the correct entity_id in one of the if statements.

#

if you're just trying to filter the value, use a filter entity

plain magnetBOT
fluid radish
#

I don't think I got an answer, how would I make the set_level part of a template light not fail when brightness or transition are not present?

#
        set_level:
            service: light.turn_on
            target: 
                entity_id: light.ceiling_light_1
            data:
                brightness: "{{ brightness | int }}"
                transition: "{{ transition | float }}"
#

The example isn't very useful for showing how to make a light that passes through most stuff (in my case due to a light that lies about all the color temperature numbers).
color_template: "({{states('input_number.h_input') | int}}, {{states('input_number.s_input') | int}})" -- but I don't want to use an input_number, I want to use the underlying light.

marble jackal
#

My guess is that it fails on transition.

#

I don't completely understand from the docs what that variable returns, but my guess would be true or false and not a number

fluid radish
#

When it fails for me, it fails with "brightness is not defined" or something like that.

#

Apparently the variable doesn't exist at all even though the docs say it should? Or maybe it only sometimes exists?

#

argh, fffs, I can't paste a screenshot of the earlier conversation where somebody said "you can put a whole script" but didn't explain a darn thing about how or what to put there.

marble jackal
#

Brightness exists when you change the level

fluid radish
mighty ledge
#

brightness only exists when it's provided by the service call

fluid radish
#

That linked answer is sort of like saying, "oh, you can do whatever you want with it." great, but I don't know what I want to do with it, all I know is the result I want.

marble jackal
#

Otherwise it doesn't, the brightness variable is the value when you change the slider in the GUI

#

Still not sure about transition, I guess it's taken from the service call

fluid radish
#

What I want is a template light that passes through just about everything verbatim, except color temperature, which it will recalculate to work around the bulb being stupid.

mighty ledge
#

it's also only populated if provided by the service call

fluid radish
#

How do I make the body of the set_level call pass brightness if brightness is provided, but not try to pass it if it isn't provided?

mighty ledge
#

as I said when you asked last time, you need to check for is defined

#

you can use a choose, check if the variable is defined and then perform the action you want to do if it is using it.

fluid radish
#

I don't know how to do that, though.

mighty ledge
#

then look it up

#

it's literally a built in part of home assistant

#

it's called choose

#

I'm not using that word for my health

#

thats a direct link to choose

fluid radish
#

Also, the "template light" doc uses the outdated term data_template instead of the current data.

mighty ledge
#

both are acceptable

fluid radish
#

So what would the choose usage look like?

            data:
              choose:
                ???
marble jackal
#

Check the docs for examples

mighty ledge
#

If you're unsure how to build the yaml, you can also use the automation editor to build it for you

fluid radish
#

But it's not an automation, it's a template light.

mighty ledge
#

as I said last time.... the turn_on field accepts actions

#

the same actions as an automation

#

the same paradigm is used everywhere

#

scripts, action sections, sequences, they all use the same yaml

#

including template lights turn_on, turn_off ,set_...

fluid radish
#

The example shows the "choose" going outside the "service" block, so I guess I'd need four versions? One with both variables defined, one with one defined, one with the other defined, and a fourth with none defined?

marble jackal
#

BTW, I would say that for the set_level sentence brightness should be defined, I don't see why that sequence would be called anyways.

mighty ledge
#

actions

#

If you click that action link, it takes you right to everything that's allowed in that section

fluid radish
#

"turn on" may receive brightness, but sometimes doesn't.

mighty ledge
#

right

#

so you have to build a condition using choose...

fluid radish
#

And it sometimes may receive transition, and sometimes doesn't.

mighty ledge
#

right

#

so your choose statement would look for 1, the other, both, or none

marble jackal
#

I don't think you need to use brightness in the turn_on sequence.
If you use light.turn_on and provide brightness in the service data, it will use the set_level sequence as well

fluid radish
#

Also, do lights have a set_color service, or only a turn_on?

mighty ledge
fluid radish
#

I mean the underlying light, not the template light, how do you set color aside from calling turn on? (that paradigm seems silly to me, since it's already on)

mighty ledge
#

lights are wierd, everything is done through the turn_on service, which makes it complicated

fluid radish
#

The template light example also seems to put the entity ID under data_template, yet my implementation has it outside the data, in the "target" section instead.

mighty ledge
#

Yes

#

you can put it in 1 of 3 places

#
service: ...
target:
  entity_id: <here>

or

service: ...
entity_id: <here>

or

service: ...
data:
  entity_id: <here>
#

the 2nd one doesn't allow templates, the first and third do

fluid radish
#

Maybe I should just ignore "transition" entirely for now, to make things simpler.

mighty ledge
#

You can also avoid the choose and go straight template for the data section, but it is a hard to understand template

#

typically only myself, thefes, robc, and a few others on the forums know how to do it

fluid radish
#

I should file a bug/ticket (or whatever you call it) to make an example that just does a straight passthrough of every value. The current example does some silly stuff with input_number that I don't really understand.

#

jinja2.exceptions.UndefinedError: 'transition' is undefined

#

Actually, let me see if "transition | float(0)" works.

mighty ledge
#

that would work but that will cause issues

fluid radish
#

Actually, it still says transition is undefined.

#

And come to think of it, the examples for "choose" don't say how to choose based on a variable being defined or not. They have a bunch of stuff with state attrs, but not variables.

mighty ledge
#
set_level:
- if:
  - condition: template
    value_template: "{{ brightness is defined or transition is defined }}"
  then:
  - service: light.turn_on
    target:
      entity_id: light.abc
    data: >
      {{ dict.from_keys([ ('transition', transition | default), ('brightness', brightness | default ) ] | rejectattr('1', 'eq', '')) }}
  else:
  - service: light.turn_on
    target:
      entity_id: light.abc
#

that will do everything

#

Had to update it

fluid radish
#

huh, I was staring right at it and didn't see what you edited. Thanks, I'll try pasting that (I'm assuming right under the set_level: line)

mighty ledge
#

yes, right under the set level, let me update it

#

updated again, apparently from_keys accepts a generater @marble jackal

fluid radish
#

Cool, now the level changing works.

mighty ledge
#

how many of these template lights are you making?

fluid radish
#

It looks like the initial on/off state of the template light isn't matching the underlying light. Here's what I have in it right now:
level_template: "{{ state_attr('light.ceiling_light_1', 'brightness') }}"

#

I have 4 lights, all of the same model (so the same color temperature correction math).

mighty ledge
#

ok

#

then I have a suggestion

#

this will help you debug as well

#

make scripts

#

that accept variables

#

I'll make this one for you as an example

fluid radish
#

Perhaps I should file a bug to quirk these zigbee lights to fix the color temperature.

#

temperature_template: "{{(370-153)/(500-153) * ((state_attr('light.ceiling_light_1', 'color_temp') | int(370)) - 500) + 370 }}"
set_temperature has this:
color_temp: "{{ (500-153)/(370-153) * (color_temp - 370) + 500 }}"

#

Basically, the light claims over Zigbee to be 153-500 mireds, but the actual color temperature range of the LEDs is 153-370 mireds.

mighty ledge
#
template_light_turn_on:
  mode: parallel
  max: 25
  variables:
    my_light: "{{ light | default(None) }}"
    my_brightness: "{{ brightness | default(None) }}"
    my_transition: "{{ transition | default(None) }}"
  sequence:
  - condition: template
    value_template: "{{ my_light is not none }}"
  - if:
    - condition: template
      value_template: "{{ brightness is defined or transition is defined }}"
    then:
    - service: light.turn_on
      target:
        entity_id: "{{ my_light }}"
      data: >
        {{ dict.from_keys([ ('transition', my_transition), ('brightness', my_brightness) ] | rejectattr('1', 'none')) }}
    else:
   - service: light.turn_on
      target:
        entity_id: "{{ my_light }}"
#

that would be your script

#

and then your turn_on would be, for all lights (just change entity_id)

turn_on:
  service: script.template_light_turn_on
  data:
    light: light.abc
    brightness: "{{ brightness | default(None) }}"
    transition: "{{ transition | default(None) }}"
#

you can employ that 'style' everywhere

#

and it will create a trace for your script so you can debug where it goes wrong

fluid radish
#

Thanks. I also went and tweaked the editor to use 2 space indents instead of 4, because 4 was the default for some reason.

mighty ledge
#

oh, evveryone else likes 4

#

I like 2

#

you do what you like

#

I ilke 2 because I press the button less

fluid radish
#

The wiki's example template light uses 2, as well.

mighty ledge
#

Ah

fluid radish
#

So editing a pasted 2-space thing with a 4-space editor didn't work nicely. The whole file is an odd mix of 2 and 4.

#

Thanks for the help, and the script suggestion!

marble jackal
#

Just use a decent editor which adjusts based on the file extension

fluid radish
#

I'll also try adding hs_color into that script, though I'm not sure whether it's better to use "h" and "s" as variables or use "hs" and array indexing.

#

It didn't seem to like hs_color. The way I tried adding it was the same as you did with transition, and adding it to the generator:

  my_brightness), ('hs_color', 'my_hs_color') ] | rejectattr('1', 'none')) }}```
#

Error executing script. Invalid data for call_service at pos 1: None for dictionary value @ data['hs_color']

inner mesa
#

nevertheless, the bit is pretty cool

#

it's going in my snippet library

fluid radish
#

I'll probably just take hs_color back out of the script.

#

oh, hs_color is an array, so it probably would need special handling.

marble jackal
#

At least the exact syntax

fluid radish
#

There's one missing space before the last dash in the template script paste.

#

Weird, even after re-pasting the script and taking out hs_color, I'm still getting that dict error -- so it's not the script giving that error.

mighty ledge
#
  variables:
    my_light: "{{ light | default(None) }}"
    my_brightness: "{{ brightness | default(None) }}"
    my_transition: "{{ transition | default(None) }}"
    my_hs_color: "{{ hs_color | default(None) }}"
fluid radish
#

Weird, I thought I'd tried that, and it didn't work the first time, but it did this time.

#

Perhaps it was because the first time, I didn't edit it via the actual script editor.

#

The first time, it was via file editor, and I had assumed I didn't need to restart HA. But it seems like it only reloads on the fly if you use the proper/real script editor.

marble jackal
#

If you change a script using the GUI, it will automatically reload the config. If you change it in a file editor, you can reload it in developer tools > yaml

#

Or by using that reload yaml service call

#

No need to restart

fluid radish
#

I copied that template light for the other three such lights, and now I'm going to try pointing Adaptive Lighting at the adjusted light instead of the physical light.

#

I renamed the physical lights so I could name the templates to replace them, but I see this:
TemplateError('ValueError: Template error: int got invalid input 'None' when rendering template '{{ state_attr('light.ceiling_light_3a', 'brightness') | int > 0 }}' but no default was specified') while processing template 'Template<template=({{ state_attr('light.ceiling_light_3a', 'brightness') | int > 0 }}) renders=4>' for attribute '_state' in entity 'light.ceiling_light_3'

#

What's a good value to use as default for the value_template and brightness_template?

#

TemplateError('ValueError: Template error: int got invalid input 'None' when rendering template '{{ state_attr('light.ceiling_light_4a', 'brightness') | default(0) | int > 0 }}' but no default was specified') while processing template 'Template<template=({{ state_attr('light.ceiling_light_4a', 'brightness') | default(0) | int > 0 }}) renders=4>' for attribute '_state' in entity 'light.ceiling_light_4'
Weird, I do have a default, as far as I can tell. I also tried with | int | default(0) and that didn't work either.

inner mesa
#

try using default(0, true)

fluid radish
#

Interesting, with that default of 0, turning on a light that wasn't already on turned it on to 0%. I guess 0 isn't a reasonable value for default brightness.

supple forge
#

Hi! I use an ESP as a data-recorder and send (as long as there is a wifi connection) data via mqtt via a wireguard vpn to my home assistant ... if there is no wifi connection, the data is collected in a queue and transmitted when there is a connection .... unfortunately the mqtt-sensor does not seem to support a timestamp, so that all data transmitted "at once" are evaluated as simultaneously.. is there a possibility? the data is recorded at 1 minute intervals

marsh cairn
supple forge
#

ok.. sry

waxen umbra
#

There are a new set of integrations in the latest HA release that DO ingest historical data. This feature is not part of the ESPHome integration.

supple forge
supple forge
# waxen umbra the way HA ingests data from integrations (including ESPHome) is not set up to i...

to be more precise .. i have soldered an esp-c3-13u to an OBD2-adapter and wrote a program that collects all kind of data from the car and sends it over an wireguard-vpn (also an esp-library) to my node-red instance.. which attaches the json-keys to the mqtt-topic-prefix i defined ... but there are lot of placed where my phone has no mobile data connection... so i thought i would save the data in a std::vector<String> and send it as soon as the net is back

but that belongs even less in the template channel ๐Ÿ™‚

flat kayak
#

Anybody know why this isn't rounding my value to two decimal places? {{ electricitycost + gascost | round(2)}}

#

ah, needed parenthesis. Ever noticed you can spend 15 minutes trying to figure something out, post the question online, and then figure it out yourself immediately after

waxen umbra
#

to be more precise i have soldered an

fluid radish
#

weird, the template light thinks it's in HS mode rather than Color Temp mode.

cunning flame
#

Hey folks, I am trying to create a custom sensor using template: !include templates.yaml

#

for the life of me I cannot figure out what I am doing wrong.

fluid radish
#

Considering the top-level of a template sensor or such needs to be the "sensors:" key, I wonder if you need to set the include on that instead of on an overall "templates:" key?

#

How would I make that template light not report an HS color if the underlying light is in color temp mode?

#

When I took out the color_template key, the light properly went into color temp mode. color_mode: color_temp
Here's what I had in the line:
color_template: "{{ state_attr('light.ceiling_light_1a', 'hs_color') | float }}"

#

Here's my guess:
color_template: "{{ state_attr('light.ceiling_light_1a', 'hs_color') if state_attr('light.ceiling_light_1a', 'color_mode') == 'hs' else None }}"

sour salmon
#

Hi - I'm having some trouble with the Template Alarm Control Panel and Homekit. By default homekit has "Home", "Away" "Night" states. I created a template for the alarm like so:
`alarm_control_panel:

  • platform: template
    panels:
    house_alarm_panel:
    name: "House Alarm"
    value_template: "{{ states('alarm_control_panel.house_alarm') }}"
    arm_away:
    service: alarm_control_panel.alarm_arm_away
    target:
    entity_id: alarm_control_panel.house_alarm
    disarm:
    - service: alarm_control_panel.alarm_disarm
    target:
    entity_id: alarm_control_panel.house_alarm`

and then expose the new panel in homekit. But homekit still has all the states

#

Am I doing something wrong here, please?

lyric comet
#

Template items do not replace the originals, I suspect you have created a 2nd control panel so you will need to use that one in your dashboards.

marble jackal
gritty grail
#

`template:

  • name: "HVAC Status"
    state: >
    {% set mapping = { '': 'Off', 'fan': 'Fan', 'compCool1,fan': 'On' } %}
    {{ mapping[states.climate.home.attributes.equipment_running]}}

  • trigger:

    • platform: state
      entity_id: sensor.hvac_status
      from: 'Off'
      to: 'On'
      sensor:
    • name: Ac Last Started
      state: "{{ now() }}"`
#

why trigger not work?

#

HVAC Status works

mighty ledge
#

theres no way HVAC status works because the yaml is wrong and the template is wrong

#

unless you're putting that into a sensor: section that you left out.

gritty grail
#

yeah my bad sensor is there. i removed a one unnecessary item and accidentally removed the sensor as well

plain magnetBOT
mighty ledge
#

that configuration looks fine then

gritty grail
#

should i use mapped or nonmapped attributes in from to section?

#

nevermind it works now

marble jackal
#

You should use state_attr() instead of states.your.sensor.attributes.some_attribute

sour salmon
thorny snow
#

How do I get rid of a template sensor entity if I 1) already removed the template file containing the entity and 2) have removed the offending entity from .storage/core.entity_registry?

#

with all references removed the entity shows up in the entity list with status 'restored' and with the checkbox for selection disabled

mighty ledge
#

you can't get rid of them on existing sensors, thefes did not have that information when he said what he said

#

what you're doing to remove the functionality is correct

#

i.e. continue making a template alarm

thorny snow
#

with the source template file in place the entities show up as 'unavailable' and they are selectable, but not eligible for deletion (because now there is a source file specifying they should exist)

lyric comet
thorny snow
#

restarting HA unfortunately did not remove them

#

I've tried many times. What confuses me is where it stores the entity's existence, since their source is now gone

lyric comet
#

Were they actually templete sensors so MQTT or similar ones?

thorny snow
#

at the very least they should be eligible for deletion

#

nope, they are regular template sensors that depend on a restful sensor

#

the source restful sensor still exists

#

that works fine

#

but the derivative sensors never worked

#

so I wanted to remake them

#
- sensor:
  - name: "Pollen Grass Text D0"
    unique_id: e2728459-4226-4b84-9544-74f46a56bf7c
    availability: is_state('sensor.pollen_data_today', 'OK')
    state: >-
      {% set text = ['Nil','Very Low','Low','Medium','High','Very High'] %}
      {% set today_grass_idx = state_attr('sensor.pollen_data_today', 'intervals')[0]['values']['grassIndex'] | int %}
      {{ text[today_grass_idx] }}
lyric comet
#

Try removing the restful sensor and do a couple of reboots.

thorny snow
#

the template itself works in dev tools

#

๐Ÿคทโ€โ™€๏ธ okay

lyric comet
#

Also check the actual state value for the pollen_data_today sensor.

thorny snow
#

that has the correct state. OK for the actual state and the correct attributes

#
- scan_interval: 86400
  resource: https://api.tomorrow.io/v4/timelines?bunchastuffhere
  sensor:
    - name: Pollen Data Today
      unique_id: e3245ca0-a621-4969-b881-5ec0d6a3d686
      value_template: "OK"
      json_attributes_path: "$.data.timelines[0]"
      json_attributes:
        - intervals
lyric comet
#

I don't give my template sensors weird values like that for unique_ids so I am not sure if that will have any affect

thorny snow
#

that was an attempt to ensure that while I try to figure out fetching the attributes it doesn't go around making pollen_grass_text_d0_0, pollen_grass_text_d0_1, pollen_grass_text_d0_2 etc... when I reload the template sensors

#

that's just even more of a mess to clean

#

especially since the dev tools template editor shows a working template, but the defined sensor doesn't work

#

anyways, my HA is going through a full reboot cycle (it's been a while since I did that anyway)

#

so let's see what happens when it returns

lyric comet
#

Ok, one of the experts will be in later, so they might have some other ideas.

thorny snow
#

sure thing, thanks for the tips anyway ๐Ÿ™‚

mighty ledge
#

if you're trying to delete the entities, but you can't, it means they are referenced somewhere in your system

thorny snow
mighty ledge
#

typical references -> automations, scripts, history

thorny snow
#

none of those. BUT

#

do dashboards count?

mighty ledge
#

probably

thorny snow
#

then that might be it

mighty ledge
#

but history is the big one

#

because it holds on to the entities until they are purged from the database

thorny snow
#

they never worked so I don't think they have any history

mighty ledge
#

which takes 10 days

thorny snow
#

plus they'd be excluded from recorder by default in my case

#

hmm

mighty ledge
#

did you have a unique_id?

thorny snow
#

I removed their references in the dashboard but they remain unselectable

mighty ledge
#

what do you mean "unselectable"

thorny snow
#

on the entities list page. On the left is a checkbox for mass actions

#

that one is grayed out

#

on the right their current state is 'restored'

#

when they are not referenced anywhere

mighty ledge
#

click on the entity

#

go to cog

thorny snow
#

something is very wrong

mighty ledge
#

see if you can delete

thorny snow
#
This entity ('sensor.pollen_grass_text_d0') does not have a unique ID, therefore its settings cannot be managed from the UI. See the documentation for more detail.
#

it very much does have one

#

what the

mighty ledge
#

right, so that means you didn't provide a unique_id and it came from yaml

thorny snow
#

it did come from yaml

#

it should not be coming from yaml anymore

#

is the point

mighty ledge
#

customize?

thorny snow
#

it should be gone

mighty ledge
#

search your files for the entity_id

thorny snow
#

I did

#

nothing

#

only .storage

mighty ledge
#

they are in storage? what files?

thorny snow
#
config # grep -r "Pollen Weeds Text D1" .
./.storage/core.entity_registry:        "original_name": "Pollen Weeds Text D1",
#

there's 6 entities, so like the other one I posted it's just one of them as an example

inner mesa
#

That's not an entity_id

thorny snow
#

no

mighty ledge
#

Yeah, that's the name

thorny snow
#

yes

mighty ledge
#

search for the entity_id

#

developer tools -> states page will show you the entity_id

thorny snow
#
config # grep -r pollen_weeds_text_d0 .
config # 
#

none

mighty ledge
#

are you sure that's the entity_id?

thorny snow
#

yes

inner mesa
#

It's not

thorny snow
#

mind you I left out the domain

mighty ledge
#

what does dev tools -> states page show for that?

thorny snow
#

sensor.pollen_weeds_text_d0

mighty ledge
#

yeah i mean for state and other crap

#

FYI, you have restarted right? Not just reloaded?

#

like FULL restart

thorny snow
#

full restart

#

ha host reboot

mighty ledge
#

well, that's a full reboot

#

restart will clean up entities

#

restart of ha ha core restart

#

Just for shits and giggles, restart again.

thorny snow
#

oh I did a bunch of those

#

doing it again

mighty ledge
#

There's no way that it can restore state if it's not showing up in .storage

thorny snow
#

I don't understand where this stuff is coming from

#

right

mighty ledge
#

there's like 4 or 5 areas that the entity can reside in

#

history, your config, .storage/conf.entity_registry and whatever the restore file is called

thorny snow
#

okay, so so far I've eliminated .storage/conf,.entity_registry and the config

#

so either history or the restore thing

mighty ledge
#

well if you're doing grep it should look in your entire config

#

all you need to look for is the object_id

inner mesa
#

Try clearing your browser cache

thorny snow
#

...

mighty ledge
#

oh yeah, that's also a thing too

thorny snow
#

that is a thing

mighty ledge
#

UI shows what it had

thorny snow
#

ffs if that's what it is...

mighty ledge
#

well it shouldn't because it's in your states page

#

but your entity lists... yes

#

unless they changed the dev tools states page

#

I always forget about the browser cache, I clear like it's my job

thorny snow
#

browser

#

friggin

#

cache

#

thank you so much

mighty ledge
#

well well then

thorny snow
#

yes it was just my browser

#

both pages are now correct

mighty ledge
#

๐Ÿ‘

thorny snow
#

Thank you all for the help

mighty ledge
#

seems like dev tools -> states page must have changed, probably to speeed the page up

thorny snow
#

I will go smash my face into a wall now

inner mesa
#

Takes rest of the day off

mighty ledge
#

CTRL+F5 is your friend

inner mesa
#

Its 8AM

thorny snow
#

ctrl+shift+R but yes

#

same difference

mighty ledge
#

11am for the cool people

marsh cairn
#

5pm

mighty ledge
#

5pm for the degenerates

inner mesa
#

That's beer o'clock, coincidentally

marsh cairn
thorny snow
#

17:03 for the cool people who use normal time ๐Ÿ˜›

#

hmmmm

#

I replaced the template entities and they show up but there's something wrong since they show up as unavailable again... I do have an availability so did I just mess up the syntax?

marsh cairn
#

Maybe

thorny snow
#
  - name: "Pollen Grass Text D0"
    unique_id: e2728459-4226-4b84-9544-74f46a56bf7c
    availability: is_state('sensor.pollen_data_today', 'OK')

Does the availability string need to be quoted maybe?

marsh cairn
#

"{{ }}"

#

quoted and double curly braced

thorny snow
#

okay yeah so I just messed up

#

good

#

awesome, thank you again

winter cape
#

Please, how could I add "default=0", when some of the sensors are unavailable: {% set temp_dif = states('sensor.bedroom_atc_temperature') | float - state_attr('climate.bedroom_thermostat', 'temperature') %} ?

inner mesa
#

float(0)

mighty ledge
#

apparently this is one of them

#

IIRC the changes came around the same time that entity_id was brough back into that selector

winter cape
# inner mesa float(0)

But i need it for complete template not only for one of sesors. When temp diff is unavailable, default 0

loud flume
#

Is there a way to reuse templates? Like "in X days" would be nice to have as a reference rather than copy pasting over a template.

inner mesa
#

There's a section in the docs labeled exactly that ๐Ÿ™‚

loud flume
#

I was looking for it before asking. What's it called?

inner mesa
#

Reusing Templates

loud flume
#

Thank you!

fluid radish
#

How do you reuse a template sensor? A template sensor isn't itself a single large template, it's a collection of templates for different fields.

fluid radish
#

Yeah, I asked the question after reading that page.

#

You can't fit a whole template light or sensor config into the syntax of a single template string, can you?
The example does this, which is one string.
{{ state_attr(entity_id, 'friendly_name') }} - {{ states(entity_id) }}

mighty ledge
#

I don't think you understand the difference between Jinja (templates) and yaml

#

and I think you're assuming this channel is for template integrations (light, switch, etc), but this channel is really for Jinja (templates)

#

the 2nd pin covers the difference between yaml and Jinja (templates)

fluid radish
#

Jinja uses various delimiters in the template strings. โ€ฆ
That's the second pin?

mighty ledge
#

Yes

inner mesa
#

Your option is YAML anchors, and it's not a great option

fluid radish
#

I don't see how that pin answers my question or covers the difference.

mighty ledge
#

There's other pins below it, so continue reading other pins

#

4th from the bottom links to a post that covers YAML/Jinja

fluid radish
#

Ah, when somebody says to look at the second pin, I think literally, so I look at the second pin, and then don't go 4 or 5 or 6 beyond what they said.

#

One of the posts in that 8th from the top / 4th from the bottom pin says:
One other thing worth mentioning is that YAML is processed first followed by Jinja2. Not knowing the order of processing, and the boundaries between YAML and Jinja2, is what has led some people to โ€œtemplate YAMLโ€ where they attempt to use a Jinja2 template to generate complete YAML statements.

#

So I guess you can't template a whole yaml stanza (or whatever the term is).

mighty ledge
#

You can, but it has no concept of variables

#

it's all or nothing

#

and it's called yaml anchors as robc pointed out

fluid radish
#

But it seems like I could at least template the color-temperature conversion to take the desired value and old min, old max, new min, new max.

mighty ledge
#

you can probably tempalte alot of it and combine alot of it with anchors

#

if you make scripts, it's even easier with ancors

fluid radish
#

Really, I need to file a ticket for an option to fix buggy lights like those. Because it would be nice to be able to just define that model X of light lies about its color temperature range, and have it fixed without all the templating.

marble jackal
#

I use several template lights, all with the same config using YAML anchors. But this requires that you can derive the source entities from the name or entity id of the template sensor

fluid radish
#

That would work for me. Currently I have the template light named ceiling_light_1 and the underlying light named celing_light_1a (though maybe I should make it 1x or 1_real or something).

loud flume
#

Is it possible to do something like this?

template:
  <<: !include domain/waste/templates.yaml
  <<: !include domain/other_domain/templates.yaml
#

where each file exposes an array of templates?

mighty ledge
#

no

#

but you can....

template: !include_dir_merge_list templates/
#

and then have waste.yaml and other_domain.yaml

#

inside templates/

#

and both of them are lists

loud flume
#

Oh bummer!

#

I really wanted to keep my code coherent by separating folder not per type of resource, but by domain

mighty ledge
#

just use packages

loud flume
#

That seems to be exactly what I'm looking for ๐Ÿ™‚

#

Thank you!

plain magnetBOT
mighty ledge
#

well your temperature template isn't correct. It's got all that junk after the #. Yaml will see that whole thing, including everything after the #. yaml only allows comments on other lines. No in-line-comments after a value.

fair gull
#

Ok will try that Studio Code did not complain about it

mighty ledge
#

I'm not sure if that's causing your problem

#

the rest, while a mix of old things, should still work

fair gull
#

well it did not improve anything, But i just have noticed that one of my templated lights is working .... for unknown reason.

#

looks same for me

#
      turn_on:
        - service: switch.turn_on
          data_template:
            entity_id: switch.switch_swiatlo_kuchnia
marsh cairn
#

If I remember correctly, the service has to be called a bit differently

  - service: switch.turn_on
    target:
      entity_id: switch.switch_swiatlo_kuchnia```
mighty ledge
#

No, that's an old way of doing it that still works

#

there's 3 ways to call out entity_id, most are old. The suggested way is to pass it via target like @marsh cairn pointed out

#

but the old ways still work

#

being insdie data or at the root level

marble jackal
#

One difference is that when passed at root level, templates are not working

fair gull
fair gull
marble jackal
#
# wrong โŒ
service: light.turn_on
entity_id: "{{ light }}"

# correct โœ…
service: light.turn_on
data: 
  entity_id: "{{ light }}"
fair gull
#

ok got it but in fact

#
      turn_off:
        service: switch.turn_off
        entity_id: switch.lazienkagora_1
#

works flawlessly from my first example

marble jackal
#

It doesn't use a template

#

So it's fine

fair gull
#

I do not wanna argue. Just pointing weird things tho

#

ok

#

is there any way to debug this ? There is no error in logs

honest wing
#

Hi uh, I need a little push here, trying to figure out what I'm doing wrong

#
sensor:
  - platform: template
    sensors:
      dardanosUPS_status_information:
        friendly_name: "UPS Status"
        value_template: >-
          {% if is_state('sensor.dardanosups_status_data', 'OL') %}
            {{"On Line Power"}}
          {% if is_state('sensor.dardanosups_status_data', 'OL BOOST') %}
            {{"Boosting Voltage"}}
          {% if is_state('sensor.dardanosups_status_data', 'OB') %}
            {{"On Battery Power"}}
          {% else %}
            unknown
          {% endif %}
mighty ledge
#

elif on 2nd and 3rd if

honest wing
#

hmm, still seems to be unhappy

#
value_template: >-
          {% if is_state('sensor.dardanosups_status_data', 'OL') %}
            {{"On Line Power"}}
          {% elif is_state('sensor.dardanosups_status_data', 'OL BOOST') %}
            {{"Boosting Voltage"}}
          {% elif is_state('sensor.dardanosups_status_data', 'OB') %}
            {{"On Battery Power"}}
          {% else %}
            unknown
          {% endif %}
neat prairie
#

if you stick the template into the template bit on the developer tools, what does it tell you?

honest wing
#

It says

#

On Line Power

#

Result type string

neat prairie
#

so when you say "seems to be unhappy" what you you mean?

honest wing
#

I'm unable to restart the HA

#

dardanosUPS_status_information (try dardanosups_status_information) for dictionary value @ data['sensors']. Got {'dardanosUPS_status_information': {'friendly_name': 'UPS Status', 'value_template': '{% if is_state(\'sensor.dardanosups_status_data\', \'OL\') %}\n {{"On Line Power"}}\n{% elif is_state(\'sensor.dardanosups_status_data\', \'OL BOOST\') %}\n {{"Boosting Voltage"}}\n{% elif is_state(\'sensor.dardanosups_status_data\', \'OB\') %}\n {{"On Battery Power"}}\n{% else %}\n unknown\n{% endif %}'}}. (See ?, line ?). ```
mighty ledge
#

Your slug is bad

neat prairie
#

doesn't like the upper case UPS it seems.

mighty ledge
#

Error even says what to fix

honest wing
#

I'm still not sure what a slug is, but yeah, lowercase "ups" worked

#

I'll look up the slug

neat prairie
#

A slug is a human-readable, unique identifier, used to identify a resource instead of a less human-readable identifier like an id. You use a slug when you want to refer to an item while preserving the ability to see, at a glance, what the item is

honest wing
#

okay, that is very helpful, thank you

cunning flame
#

Need some help with an issue I am creating. I am trying to calculate energy exported to grid using the following
- sensor: - name: "Exported to Grid" unique_id: 813ba605-3c45-4850-a987-8310c5509502 device_class: energy unit_of_measurement: Wh state: >- {%- set produced = states('sensor.envoy_202323166085_today_s_energy_production') | float -%} {%- set consumed = states('sensor.envoy_202323166085_today_s_energy_consumption') | float -%} {%- set battery_charged = states('sensor.envoy_202323166085_battery_energy_charged') | float -%} {{ ( produced - (consumed + battery_charged)) }}

#

As soon as I load the sensor energy consumption and battery energy charged both go to zero, and the entities do not increment again, even if I remove the template.

#

I am not sure how to fix the entities that I messed up, and I am not sure how I messed them up with the above custom sensor.

#

The energy production is unaffected.

plain magnetBOT
jagged coral
#

Any suggestions as to what I'm doing wrong?

haughty breach
#

Most core cards do not accept templates

jagged coral
#

As in I cant pass a variable? Hrmmm ok good to know.. Thank you

haughty breach
#

You can use custom cards that do allow templates or you can have your tap action call a script which contains your desired services and the associated templates.

#

If you do decide to use templates in a script, make sure to use the correct function, what you posted would not work...
angle_high: "{{ states('input_number.office_fan_angle') }}"

jagged coral
#

Sadly I still get an error.. but I appreciate the assistance..

inner mesa
#

Expected

#

Call a script, put the templates there

plain magnetBOT
plain magnetBOT
vocal valley
#

I now try to open or close the garagedoor by using node-red. Therefore I try to call the service 'open_cover'. But the garage door doesn't open and I don't see it in HA Logs. Do I need to implement the 'service' in the template?

fossil venture
vocal valley
#

it works in home assistant

vocal valley
#

hmm - now it works, thanks anyway

rocky crypt
#

Hey there. I am wanting to get all event_id's of devices that are "like" dimmer...
I have this: {{ states.light | map(attribute='entity_id') | list }} And it lists all my Lights, but I only want it to list my dimmable lights.. Is there a way to do this?
All my lights that are dimmable have a name of ....dimmer....

marble jackal
#

dimmer in the name or entity_id

rocky crypt
#

entitiy_id

marble jackal
#

{{ states.light | selectattr('entity_id', 'search', 'dimmer') | map(attribute='entity_id') | list }}

rocky crypt
#

Perfect ๐Ÿ™‚ Thank you!!

wanton girder
#

Hey all...im trying to make my ev charger Zaptec Go only, only charge with our extra watt from our solar system. Each phase is 16A, where are 3 phases, how do I set the charger to the correct Amps. I have a sensor that states my watt which is not used by ourselfs

wanton girder
#

Not sure if this is right:

        state: >
          {% if is_state('sensor.OverUnderForbrug' > 1000') %} 2 Ampere 
          {% elif is_state('sensor.OverUnderForbrug', > 2000') %} 5 Ampere 
          {% elif is_state('sensor.OverUnderForbrug', > 3000') %} 7 Ampere
          {% elif is_state('sensor.OverUnderForbrug', > 4000') %} 10 Ampere
          {% elif is_state('sensor.OverUnderForbrug', > 5000') %} 12 Ampere
          {% elif is_state('sensor.OverUnderForbrug', > 6000') %} 15 Ampere
          {% elif is_state('sensor.OverUnderForbrug', > 7000') %} 17 Ampere
          {% endif %}
mighty ledge
#

you'd get the state, convert it to a float, then build your if statments. You can't use is_state for greater than or less than comparisions

inner mesa
#

everybody wants to, though

mighty ledge
#

yeah I know

#

but it would look stupid if we added it

#

to be backward compatible

inner mesa
#

it would look similar to selectattr, I guess

mighty ledge
#

well, that and it wouldn't be in order

#

is_state(entity_id, value, operator)

#

aka, it'd be stupid

#

and if you wanted it in order, it would look even more stupid

wanton girder
mighty ledge
#

is_state(entity_id, operator=.., value=..)

inner mesa
#

I see similar issues with normal state triggers/conditions

#

adding > <

#

it's not just a template thing

mighty ledge
#

yep

#

so, you either make a breaking change ๐Ÿ˜ฑ or keep it the way it is with no progression

mighty ledge
#

entity_id's do not have capital letters

#

check the second pin for proper opening/closing characters and what they mean

wanton girder
#
state: >
          {% if states('sensor.overunderforbrug') | float > 1000} 2 Ampere 
          {% elif states('sensor.overunderforbrug') | float > 2000} 5 Ampere 
          {% endif %}
mighty ledge
#

Please read the second pin, compare the lines with your lines

#

๐Ÿ“Œ

#

in discord

wanton girder
#
state: >
          {% if states('sensor.overunderforbrug') | float > 1000} %} 2 Ampere 
          {% elif states('sensor.overunderforbrug') | float > 2000} %} 5 Ampere 
          {% endif %}
marble jackal
#

Reverse the order, as 8000 is also above 1000 it will use 2 Ampere

inner mesa
#

you just added %}, but didn't remove the broken }

marble jackal
#

And that

wanton girder
#

auch my head ๐Ÿ˜„

state: >
          {% if states('sensor.overunderforbrug') | float < 1000 %} 2 Ampere 
          {% elif states('sensor.overunderforbrug') | float < 2000 %} 5 Ampere 
          {% endif %}
#

please be gentle

marble jackal
#

It's not the same as what you had, now 1001 will return 5 Ampere opposed to 2 Ampere in your previous version

wanton girder
#

I cant wrap my head around it ๐Ÿ˜„

#
          {% if 1000 > states('sensor.overunderforbrug') | float %} 2 Ampere 
mighty ledge
#

he means, reverse the order vertically

#

{% if states(...) > 8000 %} blah

#

{% elif .... > 7000 %} blah2

wanton girder
#
state: >
          {% if states('sensor.overunderforbrug') | float > 7000 %} 16 Ampere 
          {% elif states('sensor.overunderforbrug') | float > 6000 %} 14 Ampere 
          {% elif states('sensor.overunderforbrug') | float > 5000 %} 12 Ampere 
      {% elif states('sensor.overunderforbrug') | float > 4000 %} 10 Ampere 
      {% elif states('sensor.overunderforbrug') | float > 3000 %} 7 Ampere 
          {% elif states('sensor.overunderforbrug') | float > 2000 %} 5 Ampere 
          {% elif states('sensor.overunderforbrug') | float > 1000 %} 2 Ampere  
          {% endif %}
mighty ledge
#

yes like that

#

you'll probably want an else

wanton girder
#

??

mighty ledge
#

look at your code, what happens when it's less than 1000

wanton girder
#

guess

<% else %> 0
mighty ledge
#

๐Ÿคทโ€โ™‚๏ธ that's up to what you want

wanton girder
#

Im still not quit sure how to calculate the corret amps allowed to charge the car...

mighty ledge
#

the formula is just amps & volts for watts

#

w = amp * v

wanton girder
#

I have 3 phases with 16 amp, and 230 v

#

In the changer breaker

mighty ledge
#

what are you using to make it equal 2 at 1000 for inputs?

wanton girder
#

I have made a sensor that tells me how much power my solar cells are making that we are not using ourselfs

#

That number I would prefer being used in this sensor..

mighty ledge
#

ruight, but you aren't answering my question

#

how are you getting the value of 2 from 1000?

#

2 amps from 1000 watts, what numbers are you using in that calculator

wanton girder
#
ValueError: Template error: float got invalid input 'unknown' when rendering template '{% if states('sensor.overunderforbrug') | float > 7000 %} 16 Ampere 
          {% elif states('sensor.overunderforbrug') | float > 6000 %} 14 Ampere 
          {% elif states('sensor.overunderforbrug') | float > 5000 %} 12 Ampere 
          {% elif states('sensor.overunderforbrug') | float > 4000 %} 10 Ampere 
          {% elif states('sensor.overunderforbrug') | float > 3000 %} 7 Ampere 
          {% elif states('sensor.overunderforbrug') | float > 2000 %} 5 Ampere 
          {% elif states('sensor.overunderforbrug') | float > 1000 %} 2 Ampere 
          {% else %} 0 Ampere
          {% endif %}' but no default was specified
#

AC 3 phase, 230 v, put in 2 amp, and it states about 800 watts

mighty ledge
#

best to use equations when you can ๐Ÿ˜‰

wanton girder
#

could you explain ?

mighty ledge
#

It's the equation to calcuate

#

literally pulled it off that website

#

you have watts, you want amps

#

P(w) is watts

#

I(A) is amps

#

solve for amps

#

I(A) = P(W) / ( sqrt(3) * PF * VLL(V))

#

P(W) is states('sensor.overunderforbrug') | float

#

PF is 1, so y ou can remove

#

VLL(V) is 230

#

solve for I(A)

wanton girder
#
Result type: number
-29.57288487531731

Its dark here in Denmark

mighty ledge
#

if you want it rounded {{ (states('sensor.overunderforbrug') | float(0) / (sqrt(3) * 230)) | round }}

#

it's impossible for that to go negative unless your watts are negative

wanton girder
#

it is...tv is on, its dark so right now I have no exessive power from my solar

#

I would like the option to charge from solar and then it uses only the exsessive power, or to just " power through" and now think about economics

#

{{ (states('sensor.overunderforbrug') | float(0) / (sqrt(3) * 230)) | round }} gives me that exsessive power (watts) in amps right ?

mighty ledge
#

it gives you amps

wanton girder
#

so all of the work above......is not nessesary ?

mighty ledge
#

if you already have watts and that's what you want, then you don't need amps

#

you're the one who came in here wanting amps

wanton girder
#

Yes, I have the watt not used, and the charger has an option to set max amps to pull

mighty ledge
#

Ok, then that equation gets you amps

#

the exact amount of amps

#

according to the equation you wanted to use

wanton girder
#

Not sure how the integration will react to negative amps or amps above 16 which is max

mighty ledge
#

if you want it to be between 0 and 16...

#
{{ ([0, (states('sensor.overunderforbrug') | float(0) / (sqrt(3) * 230)) | round, 16] | sort)[1] }}
#

and if you want it between 1 and 16, then change the first 0 to 1

wanton girder
#

wauw...impressed... so is it anything negative becomes 0 and above 16 becomes 16 ?

mighty ledge
#

yep

wanton girder
#

Often when one (me) is not that clever and good at HA, the biggest issue for me is to explain what I want to accomplis

hearty verge
#

How does one select a set of attributes you want out of a dictionary or from_json object in a template?

#

I guess i can do it programatically but i'm wonder if ther is a better way:

{%- set j = json | from_json -%}
{{ {'type':j['type']} }}
#

I'm trying to use this in a attribute_template for mqtt discovery ... and it would be nice to have a 1liner

marsh cairn
#

I'm using something like this:

{{ anruf.name }}```
In the json name is one of the attributes.
#

{"name": "John Doe", "nummer": "012345678", "zeit": "18:24", "datum": "24.07.2023" }

hearty verge
#

I want multiple attributes however ... i guess that kinda works

marsh cairn
#

with anruf.nummer, anruf.zeit and anruf.datum I can get the other values

sick ice
#

Hi,

I'm using this {{ today_at("05:50") }} in a template which works fine unless I pass that time.

Ideally, I would have something like {{ next_at("05:50") }}, but that isn't defined. Is there a simple way to achieve this without doing a more complex template?

tepid onyx
#

you can use timedelta(seconds=99)

sick ice
#

how do you mean? Add 1 day using time delta if < now()?

tepid onyx
#

yeh for e.g.: {{ now() == ( today_at(states('sensor.something')) + timedelta(minutes=5) ) }}

#

hmm why is my profile pic pink now...

sick ice
#

it looks fab, don't worry about it.

#

OK, I've ogt it sorted using the timedelta approach, with a bit more logic to suit my specific needs

#

THanks

grim flicker
#

i have a template sensor which i want to round to 2 decimals. Because i would like a nice clean dashboard i would like to have 0.3 to show as 0.30. Is there a way to show the second decimal when its a zero somehow?

fossil venture
#

I believe the HA frontend is coded to supress trailing zeros.

grim flicker
#

Thats too bad. On sensors made within ha not templated you can choose how many decimals you want. I had hope there was also an option for template sensors. but i guess not

marble jackal
fossil venture
#

Oh yeah I forgot about that newness.

fluid radish
mighty ledge
#

yaml anchors, like we said above

#

And because I have a feeling that you will say something: No yaml anchors are not an HA thing, they are a yaml thing. If you want to read up on them, they will not be in HA's documentation. They will be in yamls documentation, or somewhere else on google.

fluid radish
#

Thanks, I'll give it a try later (it's work time now).

fair gull
# plain magnet <@725716551856291880> I converted your message into a file since it's above 15 l...

@mighty ledge @marsh cairn Well I have partially debugged my problem. Everything in config is ok ... as soon as I change name of light template to something else it starts working if I return to old name I cannot turn_on light anymore. Any idea what could be cause of this ? I would like to resolve this without changing names because changing names everytime it happens will be step to madness ๐Ÿ˜‰

mighty ledge
#

Youโ€™ll have to elaborate on what you mean when you say โ€œchange the nameโ€

slate fossil
# grim flicker i have a template sensor which i want to round to 2 decimals. Because i would li...

Depending on the card that you're using to display the sensor info, you could always do the rounding and decimals at that point. This probably won't work with most stock HA cards (except for the Markdown card).
Something like {% set used_space = (states['this.entity_id'].attributes.Used / factor).toLocaleString('en-US', {minimumFractionDigits:1, maximumFractionDigits:1}); %} could be used. This was used to change a sensor value in bytes to gigabytes, includes commas where needed and rounded to 1 decimal place.
Simpler methods to consider are '[[[ return parseFloat(entity.state).toFixed(2) + " ยฐF" ]]]' or {{ "%.2f"|format(your_variable) }}.

fair gull
marble jackal
#

That's the object id

#

If you change that, you will get a new light entity with that object id

fair gull
#

Yes. So what can be the cause that only particular existng objects_id cannot run one of (remainder that switch.turn_off works all the time) and another existing entity with just diffrent oject_id cannot ?

marsh cairn
#

Could you share the code for the other object id?

#

The one, which isn't switchable

plain magnetBOT
fair gull
#

This is the one

#

I only have to change object_id to something else and poof it is working perfectly

marble jackal
#

So with this config, do you have a light.hol entity?

fair gull
#

yes

mighty ledge
#

You most likely already have that entity id in your system and itโ€™s creating an _1

#

Donโ€™t reload, restart

#

When changing the slug

#

Reloading will keep the old entity and make a new one. And you wonโ€™t be able to go back to your old one.

#

Or you can add a unique id to avoid that all together

marble jackal
#

Btw, if your actual smart light is turned off, but the switch is on, your template light will be on

fair gull
#

Also i am always restarting.

mighty ledge
#

adding ! causes the configuration to break

fair gull
mighty ledge
#

did your original entity have a unique_id? if so, that entity_id is registered

marble jackal
#

You could simplify that value_template to:
{{ states('switch.swiatlo_hol') | bool(false) }}

fair gull
mighty ledge
#

well that's your problem

#

when you're creating the new one, it cna't use the already in use entity_id

#

delete that old entity

fair gull
#

I am not sure that i understand. But I will disable part of template that is creating that entity. remove these entities by hand by hand if they exist. and then reanable them with same unique_id as they were

mighty ledge
#

no, just delete the entity from the UI

fair gull
#

I cannot, it says that is read only because it does not have unique_id ...

mighty ledge
#

the one named light.hol?

fair gull
#

yes. I have added value unique_id to template

mighty ledge
#

noooo

#

my man

#

you need to remove it from the system first

#

restart HA without the entity

#

in yaml

#

then see if it exists.

fair gull
#

i did that and it has persisted

mighty ledge
#

then it's coming from another integration if you cannot edit it

#

or it's somewhere else in your yaml

#

if you can't edit it, it's coming from yaml somewhere

#

and if you restart without the template in your yaml, then it's coming from some other area in your yaml

fair gull
#

weird and it has happened for like 6 templates at time

mighty ledge
#

search all your files for hol

fair gull
#

ok. I have removed that uniqe_id value that i have added. Commented out whole template configuration. Searched every file on config dir. Now restarting. Is there any diffrence if i restart whole VM ? - guess not.

mighty ledge
#

just restart HA

fair gull
#

ok i was able to delete it

#

from UI

mighty ledge
#

ok, now it should be good

#

This is why you don't remove unque_id's from things

#

and also never change them

#

change everything else but the unique_id

fair gull
#

No luck. After enabling template once again I have light.hol and light.hol1 none of them is working.

#

Weird

mighty ledge
#

Post your entire config, you're doing something wrong with it

fair gull
#

every light that i am using ?

mighty ledge
#

Yep, and how you include it in configuration.yaml

fair gull
#

W8. have to use paste bin

#

and in configuration.yaml i have this entry light: !include light.yaml

mighty ledge
#

do you have any other light sections?

fair gull
#

nope

#

templates that are not working are hol
jadalnia
salon
goscinny

#

i will go trough every file once again searching for light. Found one in customize but this was not related to templates that i had problem with.

#

google_assistant.yaml i have all of my lights there, in groups i have combined adaptive lightning entities, And nothing more

mighty ledge
#

So these entities don't work "how", can you explain not working

fair gull
#

No. Only turning them off do not work. It does not matter if i try to turn them with assigned action in button card or just enavle light.turn_on service from dev tools. If i enable switch (that is assigned to turn_on in template) by using same methods light successfully is shown as enabled i can change temp and brightness or even switch it off (again with button or service). But I am unable to turn it on back again.

mighty ledge
#

are you sure the switch isn't going unavailable

fair gull
#

switch.swiatlo_hol is working as expected affecting light template. I have also checked it by phiscally looking at light.

mighty ledge
#

not sure what to tell ya

fair gull
#

Ok. I was testing Your procedure on diffrent template that also will not let me turn_on light. But one i did not played that much. And after commenting out template it once again will not let me delate entity compllaining about uniqie_id.

mighty ledge
#

all my light templates are working fine, and based on what I know it should turn back on

#

the only thing that would stop your light from turning back on is the things in your turn_on actions or the value_template itself.

#

your turn on should turn on the switch

#

and then the light should turn on after the value_template updates its state

fair gull
mighty ledge
#

na

#

you're the only one with this issue

#

it's something with yo ur setup

fair gull
#

Well one thing that i have notice that is weird lateley is that i cannot remove my *corrupted.db files

#

Nvm deleted it trough ssh

gritty grail
#

is there way a make sensor which is triggered and it records the biggest value between {{ now() }} and some past time like 2023-08-09 17:40:42.379012-04:00?

fair gull
tardy quest
#

Has anyone ever created a template for a sprinkler, garage door and thermostat all in one? Should this go in the hardware section?

#

I'm using esphome in ha

haughty breach
#

You'll have to explain what you mean by "a template for a sprinkler, garage door and thermostat all in one"... but ESPHome has it's own discord https://discord.gg/WQvB275q

tardy quest
#

OK I'll ask there. I have an 8 relay esp32 board and I'm trying to code up a nice all in one. I already have it all working but it's basic and I don't trust my coding enough.
I have opensprinkler on its own 4 relay board, and the garage door and thermostat on the 8 relay board. Just want to combine everything

steel swift
#

I am trying to make a sensor of a attribute but not really sure how to extract the value. Can anyone help? This is what I have done so far: ```template:

  • sensor:
    • unique_id: energy price level
      name: "Prisnivรฅ Strรธm"
      : "{{ state_attr('sensor.electricity_price_hjemme', 'price_level') }}" ````
#

As I could see from documentation, I shall use State?

steel swift
slender whale
#

Hi, this might be a tricky one..

I have several networks, one fully dedicated to guest wifi, this is a synology SRM based router. I want to count number of "guests".

I have the synology SRM device tracker running, but it looks rightly so at "devices" and not the "router statistics" so i need to make a template sensor. the only way i can think of is to make a template for all "device trackers" and count unique "mac addresses" with condition "scanner: SynologySrmDeviceScanner".. i have no idea how to write this though ๐Ÿ™‚

lyric comet
#

Do you also have an entity for the Router, does that have any attributes showing the cout value. If not if you post the attributes of one of the device trackers, someone will probably be able to sort out the filter with you.

crimson lichen
#

{{ states.device_tracker
|selectattr('entity_id', 'search', 'device_tracker.')
|rejectattr('state', '==', 'not_home')
|selectattr('state', '==', 'home')
|map(attribute='name')
|list
|join('\n')}}

Why can't I filter not_home devices?

inner mesa
#

What do you mean?

#

You don't need both of those

#

The rejectattr isn't doing any useful work there

crimson lichen
inner mesa
#

Filter meaning show or don't show?

crimson lichen
#

Show the name of entity with home state

inner mesa
#
{{ states.device_tracker
  |selectattr('state', '==', 'home')
  |map(attribute='name')
  |list
  |join('\n')}}
crimson lichen
inner mesa
#

Impossible

crimson lichen
marble jackal
#

Do you mean the device is not at home according to its physical location, or is the state in developer tools > states not_home

plain magnetBOT
crimson lichen
#

Is the states not_home in mikrotik router

#

I am try list all devices is connected to my network on mikrotik

lyric comet
#

I think my brain has packed up today: I have a sensor which checks to see if any person is home

{{ states.person | selectattr('state','eq','home') | list | count > 0 }}

However if we are all out the sensor goes unavailable. I am sure it used to work, so I have no doubt missed some update somewhere, can kind person tell me what I should be using.

#

If I set both persons to not_home in dev_tools it throws a state not available error.

plain magnetBOT
marble jackal
keen oriole
#

What am I doing wrong with my variable below.. have tried most possibilities I believe... (when putting the \nMute etc into the shell command it all works)

#

service: shell_command.nad_mute
data_template:
variable: "{{\nMain.Mute=On\n}}"

#

The shell command: nad_mute: echo -e '{{variable}}' | nc 192.168.212.174 8080

marble jackal
#

Remove the curly brackets in the service call

keen oriole
#

When I do that and saves it "malforms" the text and it appears as below.. (Something with the \n ?)

#

service: shell_command.nad_mute
data_template:
variable: |

Main.Mute=On

response_variable: Nad

#

I have to send CR (\n) before and after the "message"

marble jackal
#

Are you using the GUI?

keen oriole
#

GUI and "edit in yaml"

marble jackal
#

You can escape the \n with an additional \

keen oriole
#

variable: "{{\nMain.Mute=On\n}}"

#

like this

marble jackal
#
service: shell_command.nad_mute
data:
  variable: "\\nMain.Mute=On\\n"
keen oriole
#

Thanks, ill try

#

Then it ends up like this ๐Ÿ™‚

#

service: shell_command.nad_mute
data_template:
variable: \nMain.Mute=On\n
response_variable: Nad

#

(after saving)

marble jackal
#

That was what you wanted right?

#

Btw, you can just use data, data_template is depreciated for some time now

keen oriole
#

Then there must be something wrong with the command line with '{{variable}}' as if I replace that with the variable it works

#

Since the saving removes the " before and after the string I get error: No closing quotation

marble jackal
#

nad_mute: echo -e '\nMain.Mute=On\n' | nc 192.168.212.174 8080
This command works?

lyric comet
keen oriole
#

Correct, Just tested again and works

inner mesa
lyric comet
#

Ok thanks, I will check it again when we go out properly tomorrow and see if I can work out why it goes unavailable.

keen oriole
#

nad_mute: echo -e '{{variable}}' | nc 192.168.212.174 8080
nad_mute2: echo -e '\nMain.Mute=On\n' | nc 192.168.212.174 8080

below trace when running nad_mute:
Executed: 11 August 2023 at 21:05:34
Result:
params:
domain: shell_command
service: nad_mute
service_data:
variable: \nMain.Mute=On\n
target: {}
running_script: false

inner mesa
#

template binary_sensor also works fine:

- binary_sensor:

  - name: test_presence
    state: "{{ states.person | selectattr('state','eq','home') | list | count > 0 }}"
    unique_id: test_presence
lyric comet
#

What is weird is it works when we are home, but if we both go out it goes unavailable ๐Ÿ˜ฆ

lofty mason
#

Doesn't checking the state of zone.home accomplish the same thing?

lyric comet
#

No Zone.home is not accurate as it take too long to update as it only works off GPS, I use ping presence as it is quicker.
The error in the log is
TemplateError('UndefinedError: 'state' is undefined') while processing template 'Template<template=({{ states.person | selectattr('state','eq','home') | list | count > 0 or state('input_boolean.guest_mode') == 'on' }}) renders=68>' for attribute '_state' in entity 'binary_sensor.family_home'

inner mesa
#

well, there ya go

#

state vs. states

#

apparently that equals 68 ๐Ÿคท

lyric comet
#

I am an idiot. It was the input.boolean

inner mesa
#

it's always the part that's not shared ๐Ÿ™‚

#

people lie, it's in their nature ๐Ÿ™‚

lyric comet
#

Sorry

#

๐Ÿ˜ฆ

marble jackal
#

zone.home works with person entities, and if as accurate as the device trackers for those person entities

#

You can provide network or BT based device trackers for the person entities as well

lyric comet
#

I was forgetting, the or part of the template was only checked if the first part was false. I am more used to complied development.

#

I will experiment with zone.home, and see how it compares.

inner mesa
#

it's moar faster

keen oriole
marble jackal
#

I think it's treating {{ variable }} as a string because of the single quotes around it

keen oriole
marble jackal
#

That's because \n is a new line

keen oriole
#

yeah, experimenting with ascii now..

marble jackal
#

That's why you need to escape them with an \

keen oriole
#

that does not work to escape them in shell command

#

\n will then end up as \ in the response

#

sorry, doubble \n ends up as \ (Discord as well removes them)

#

How should this one be rephrased to include a variable in the middle? {{'\x0a' }}Main.Mute=On{{'\x0a' }}

marble jackal
#

Try this in devtools > services

service: notify.persistent_notification
data:
  message: >
    {% set variable = '\\nMain.Mute=On\\n' %}
    nad_mute: echo -e '{{variable}}' | nc 192.168.212.174 8080
#

You will see the result is your wanted result

#

Use code formatting to avoid Discord messing things up

plain magnetBOT
#

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

marble jackal
#

It creates a notification

keen oriole
#

nad_mute: echo -e '\nMain.Mute=On\n' | nc 192.168.212.174 8080

plain magnetBOT
marble jackal
#

@thorny snow did you test the template in devtools > templates?

thorny snow
#

I just pasted the code into the devtool and got this message:
"ValueError: Template error: float got invalid input 'unknown' when rendering template 'sensor:
' but no default was specified"

That's a step further. Is there a way to display the output of the sensor?

#

I already tried "minicom" via terminal but didn't get a single response

marble jackal
#

You need to check in devtools > states what the actual entity_id of your source sensor is

thorny snow
#

sensor.gasverbrauchsensor -> that's what "devtools>states" says -> state: "unknown" and only a friendly name set

#

for the template it says "sensor.gas_verbrauch_haus" and state "unavailable"

marble jackal
#

Well, fix the source sensor

#

As long as it's state is unknown you won't be able to multiply it with 0.01

inner mesa
#

kinda known

thorny snow
#

alright. Any idea how to do that? I unplugged that damn thing so many times that I couldn't even keep track. When switching to settings -> system -> hardware I can see the usb sensor being plugged in and being recongnised :/

keen oriole
thorny snow
keen oriole
#

Trying to use a "template entity" in media player cards but it does not work. Is there a way to create a media player "entity" which is based on: media_player.{{ states('input_select.sonos_music_master_speaker') }}

lofty mason
#

Yeah cards don't work with templates like that. You can create multiple media player cards, and then use conditional cards to choose a single one to show based on the state of the input_select.

keen oriole
#

The thing is that the helper is used to group the speakers based on motiion (adding/removing) If I then could have used the template entity the card woudl always control the "group"

#

but assume that workaround might work, but a little troublesome to update 12 cards

bitter atlas
#

having a brain fart moment. so ever since the change with the template sensors etc, where as before (still is) you could branch out like a sensor.yaml and binary_sensor.yaml I had branched out the template.yaml and it was simple enough inside how to struture the yaml with binary_sensors and sensors. but how do you do trigger sensors?

undone vault
#

script to play several local successive songs

bitter atlas
#

seems simple enough for me to add that into the sensor.yaml under template but isn't the whole idea to move away from those and into the main template platform?

#

ok the docs lists the - trigger and sensor being on the same line, same spacing but the editor gives me a red flag when i do that

#

oh i think i got it figured out

crimson lichen
#

Example configuration entry

template:

  • trigger:
    • platform: time_pattern

      This will update every night

      hours: 0
      minutes: 0
      sensor:

    Keep track how many days have past since a date

    • name: "Not smoking"
      state: '{{ ( ( as_timestamp(now()) - as_timestamp(strptime("06.07.2018", "%d.%m.%Y")) ) / 86400 ) | round(default=0) }}'
      unit_of_measurement: "Days"
bitter atlas
#

the problem is using multiple triggers and sensors

#

one works fine, but if i try and define a separate one i get errors

#

with sensors and binary_sensors each sensor is seperated with a -name but i don't know how to seperate diffrent trigger sensors in the same manor

#

like

   
     - name: sensor 1

     - name: sensor 2```
#

well my example spacing got fubared

inner mesa
#

There are examples of multiples in the docs

bitter atlas
#

there are examples of using multiple triggers for the same sensor, but didn't see multiple trigger sensors

inner mesa
#

It's not any different

bitter atlas
#

can you give an example how it would be done in yaml cause that's my whole issue

#

i can make one and it works, but the second i try and do a seperate sensor under the - trigger platform it errors

inner mesa
#

Just make a list

bitter atlas
#

unless i have to do - trigger for each one

inner mesa
#

That's what makes a list

bitter atlas
#

ok. that makes sense as in makes easier to seperate them but thought they could be cumped under the same platform like sensors

#

easy fix, thank you

flint beacon
#

Earlier I posted a question about making a "latching" helper that would only turn on when specific entities were all turned on and only turn off when they all turned off. I think this binary template sensor is pretty clean, but just want to know if maybe there's a better way of doing it :3
#automations-archived message

#
- name: "Both Laundry Machines"
  unique_id: "both_laundry_machines_binary_sensor"
  state: >
    {% set washer = is_state("binary_sensor.washing_machine", "on") %}
    {% set dryer = is_state("binary_sensor.drying_machine", "on") %}
    {% if washer and dryer %}
      True
    {% elif not washer and not dryer %}
      False
    {% else %}
      {{ states(this) }}
    {% endif %}
#

obviously with only two monitored entities it's not super complex, but it's more about the approach, as I'm likely gonna copy/paste this a whole bunch in the future for other similar problems

haughty breach
flint beacon
#

Oh that's smart

#

hadn't delved into trigger sensors, but that could also work perfectly, yeah

#

thank you!

haughty breach
# flint beacon thank you!

For larger groups you could change the trigger to something like:

{{ expand("binary_sensor.bs_1","binary_sensor.bs_2","binary_sensor.bs_3") 
| map(attribute='state') | unique | list | count == 1 }}
marble jackal
#

No need to expand them, you can access the states from the entity_id

{{ ["binary_sensor.bs_1","binary_sensor.bs_2","binary_sensor.bs_3"]
| map('states') | unique | list | count == 1 }}
pseudo plume
#

why are templates always such a PITA ? I changed min(a, b) to (a + b) / 2. and it doesnt like it

#

it''s like somebody went out of their way to ensure that whatever obvious thing you think of will not work

#

a and b are already cast to floats, so adding and dividing them should be a no brainer

#

i tiread putting the whole sum in parentheses, well that would have been too obvious, so obviously it didnt work

#

tried putting those % ... % inside the {{ }}, again not obscure enough so of course it doesnt work

#

it's probably going to turn out to be something like divide(add(a, b), 2.)

#

or maybe ((divide(add ((a | float), (b | float)) | float), (2.0 | float)) | float) | float)

#

sorry if I seem a bit annoyed but I am baking hot in here because my air condition is useing min(ouside temp, inside temp) as its base rather than average inside temp / outside temp

marble jackal
#

Just give the whole template your are using

#

Not just snippets

haughty breach
lyric comet
#

Works for me, are you sure you have set your variables to numbers. Remember min will work with strings, just not as you might expect
{{min('230','64')}}
will give '230'

pseudo plume
#

no, they are numbers, converted to float

#

I have 2. with a decimal poit

marsh cairn
#

As TheFes said, share your template - we are really bad at mindreading to pinpoint an issue

pseudo plume
#

I had put 2.
it seems 2 and 2.0 are OK, but 2. is not, I suppose it gets treated as a string, and takes numerical value 0

#

no no it is fine, you have provided the answer I was looking for

#

thankyou

#

I just wanted to see an example of the correct syntax

#

I'll rmemeber for the fure now, to always add a trailing 0 after a decimal point

#

I prefer to use 2.0 in cases like this so you can be sure it is a float not an int

#

but in C you are allowed to leave of the trailing zero, but it's a strongly typed language so it is understanble their might be differences, it just hasn't occurred to me

#

hah this is something I have been struggling to get right for a while, trying to work out the "perceptual temperature of my workspace", which is not easy as I dont have a very accurate thermometer

#

trying to calculate it by combing different values, for example the core CPU temperature of my lights' controller minus an offset

lyric comet
#

In general I find it best to use float or int to ensure numbers are numbers and not strings. Especially as all state values are strings

#

even if they look like numbers

pseudo plume
#

is it a ginga thing or a python thing ?

#

I mean like type conversions

lyric comet
#

The state values are a home assistant thing. I understand Jinja and Python are quite closely related.

pseudo plume
#

I know, for example in perl you can do 0 + $var

#

and then seeing the 0, it will try to convert $var to a number

#

Jiinja, yes sorry for the misspelling

lyric comet
#

No you need to get the variable in the right format.

pseudo plume
#

so there is no automatic conversion at all ?

#

everything is a string unless you specifically tell it otherwise .. is that how it wors?

lyric comet
#

Not that I have found, but as it does not mind you saying a = 1 | float() , it means if in doubt I convert them. I think some attributes may come in as numbers.

neat bear
#

I need to change long datetime format of MQTT sensor's attribute to short one, but I confused by templating. Is it normal that my sensor's template creates a "clone" sensor?

lyric comet
#

Yes.

#

If you just need to display it in short format, if you have mushroom cards you can do so directly on the template card.

pseudo plume
lyric comet
#

If you create a template sensor that will create a sensor.

pseudo plume
#

yes but atttributes may have fixed types

neat bear
#

Is is possible to show sensor's attributes in Mushroom Cards like in Entities Card?

pseudo plume
#

so it should know already if it is expectign float data

#

IIRC it gets sent as json dvia the mqtt topic, so converting back from json may do that conversion, I dont recall now

lyric comet
lyric comet
pseudo plume
#

its not vital, I just wanted to refresh my memory

neat bear
lyric comet
#

You will need to look at the documentation to see if you can use templates with in the entities card.

neat bear
lyric comet
#

Reading the documentation suggests you can set the format for date time attributes using format: have you tried that

neat bear
#

Next I'm unsure the way I created template. I'm planning to create more than 20 similar MQTT sensors and should I create template for every sensor?

lyric comet
#

No - I was talking about changing the value directly on the card.

#

Not using a Template sensor.

neat bear
# lyric comet No - I was talking about changing the value directly on the card.

Jane, of course I read it before. Those formats are very basic one: time, date or datetime. This is rather not format anymore. Just form of data.
The standard (without templating) output of datetime attribute shows in long form: "August 12, 2023 at 5:16:08 PM", but I need short one "12.08.23 15:16". And I made it with template but I'm unsure the way I done it.

lyric comet
#

If you have a huge list of these you could either create your 20 template sensors, or use something like the flextable card to display a list. This is what I do for my 8 zones on the heating system, with columns for the name target and current temp. https://github.com/custom-cards/flex-table-card

neat bear
# lyric comet If you have a huge list of these you could either create your 20 template sensor...

Thank you for tip with Flex-Table-Card. I have HACS so I'll see it later. But may I return to a Entities Card. This card is simple and powerfull enough and suits me. I can hide some attributes dynamically using "- type: conditional".
I just what to know if I'm on the right way creating this template while I have only one sensor. As I wrote, there will be more than 20 sensors and I must be sure that way I choose to create template is right one.
The main confusion: how should I create MQTT sensor?
Firstly I created it in my mqtt.yaml file:
sensor:
- name: "wifi_t580"
unique_id: "wifi_t580_client1"
icon: mdi:wifi
state_topic: "wifi_sensor/wifi_t580/state"
value_template: "{{ value_json.ap_number }}"
json_attributes_topic: wifi_sensor/wifi_t580/state
json_attributes_template: >
{ "ap_state_since": "{{value_json.ap_state_since}}",
"ap_power": "{{value_json.ap_power}}",
"ap_uptime": "{{value_json.ap_uptime}}",
"ap_location": "{{value_json.ap_location}}" }
Then I created Entitied card:

plain magnetBOT
lyric comet
#

As you are already adding in all the attributes, why not just add an attribute for the format of date and time you want.

neat bear
lyric comet
#

No, into your MQTT yaml where you build the json template. Create the value you want and include it as another value.

#

That way you can use it directly where ever you can display an attribute

neat bear
lyric comet
#

Just use the template code you have already written and add a value, to the json_attributes_template

neat bear
# lyric comet Just use the template code you have already written and add a value, to the json...

Is is correct?
sensor:
- name: "wifi_t580"
unique_id: "wifi_t580_client1"
icon: mdi:wifi
state_topic: "wifi_sensor/wifi_t580/state"
value_template: "{{ value_json.ap_number }}"
json_attributes_topic: wifi_sensor/wifi_t580/state
json_attributes_template: >
{ "ap_state_since": "{{value_json.ap_state_since|as_timestamp|timestamp_custom('%d.%m.%y %H:%M', local=True, default=0) }}",
"ap_power": "{{value_json.ap_power}}",
"ap_uptime": "{{value_json.ap_uptime}}",
"ap_location": "{{value_json.ap_location}}" }

#

WOW!!! Jane_t THANK YOU VERY MUCH! It works!