#templates-archived

1 messages · Page 104 of 1

topaz silo
#

I have a sensor that has 3 possible states... 1, 2 and 3.. i am trying to assign 'names' to those states, and failing..

bitter atlas
#

@topaz silo post your sensor .share

silent barnBOT
topaz silo
#

working on it

#

cant seem to copy/paste from the HA mac app

bitter atlas
#

don't paste into discord, use one of the services i linked

topaz silo
bitter atlas
#

{% if is_state('sensor.goodwe_battery_mode', '3') %}

deft timber
#

or states.sensor.goodwe_battery_mode.state but is_state is better

topaz silo
#

oh, i need to add .state (or use is_state)

deft timber
#

@small wolf maybe by using a statistics sensor? you choose a max_age of, let's say, 30 seconds, then you will be able, in another sensor, to compute (max_value - min_value) / 30 ?

jagged iron
#

im dumb anyone get any idea as to why im dumb;
basically want a push button when i hold it down it sends the code, ON (....2445) then on release of the button it sends, OFF (...0695)
http://puu.sh/GxwFK/edd3115578.png

binary_sensor:
 - platform: template
   name: "ir curl"
  on_state:
    rest_command:
    method: GET
    url: http://10.0.0.92/ir?code=16712445
   then:
    rest_command:
    method: GET
    url: http://10.0.0.92/ir?code=16750695
glad wren
#

Indentation?

elder moon
#

im trying to template timestamp to this data format but im struggling with miniseconds: 2020-09-19T08:18:47.096Z

#

%f makes microseconds (.00000) but how can i make milliseconds?

#

{{ utcnow().timestamp() | timestamp_custom("%Y-%m-%dT%H:%M:%S.%f") }}

#

in Python i would just add [:-3] at the end

deft timber
#

{% set a= "2020-09-19T12:01:25.000000" %} {{a[0:-3]}} will produce 2020-09-19T12:01:25.000

#

@jagged iron , I don't understand what you are trying to do. If you want to trigger rest call when a button is pushed or release, you should do it in an automation

#

by the way, as Tyler Marrs sayd, your indentation is wrong, and I don't know what are these tag on_state and then that you are using

elder moon
#

@deft timber thanks

#

{{ (utcnow().timestamp() | timestamp_custom("%Y-%m-%dT%H:%M:%S.%f"))[0:-3] ~ "Z" }} works

jagged iron
#

on_state
"This automation will be triggered when a new state is received (and thus combines on_press and on_release into one trigger). The new state will be given as the variable x as a boolean and can be used in lambdas.
"

elder moon
#

@jagged iron you need an automation for that, you cannot do a binary_sensor which actions something like sending a code

deft timber
#

ok, this is an esp. Your "on_state" should be indented on the same level as platform

jagged iron
#

yeah sorry its and ESP
@elder moon thanks will try

#

not send rather just call it, there no POST or GET needed it just needs to be access or called then it executes on the device thats being called

elder moon
#

@jagged iron ah dont mind me, i thought youre talking about Home Assistant

jagged iron
#

im not sure if i am not either :D!

#

total noob to this

#

perhaps i should clarify , i am using home-assitant is which has the esphome "plugin" installed and im trying to program the esp to do curl commands for, which now that i typed it out sounds dumb....

#

i should be using home assitant to do for me and not getting another mcu to do it

#

is that possible?

elder moon
#

one more question regarding templates - is it possible to remove starting/trailing whitespaces, something like strip() in python

#

@jagged iron im not really sure what exactly you want to do, i dont have any ESPs, but the general principle is that HA is getting data from other sources (like your ESPs) and runs automations based on that data

#

you're looking at ESP documentation, which suggests that you want to do something ON the ESP, in this case people here wont be able to help as this is Home Assistant discord

#

if you want to do an automation on Home Assistant though, then you're following documentation for a wrong software 🙂

#

im assuming that after you done with that you will have your buttons state exposed to HA

#

like a binary_sensor created out of it

#

and then you can create a really simple automation within HA, triggered by your binary_sensor going on, sending data you need, waiting for binary_sensor going off, sending some more data

deft timber
#

@elder moon , concerning your question related to the 'strip()', for that you should replace the {% and %} by {%- and -%}

mighty ledge
#

or just use .strip() in your template. By default all templates strip whitespace accept for templates in markdown cards or notification service calls.

#
{{ ' dlsajdflak  '.strip() }}
#

returns 'dlsajdflak'

elder moon
#

Thanks all

#

Unfortunately I found out that I don't need to template this as Restful sensor platform doesn't accept templates for headers anyway:(

dreamy sinew
#

it doesn't remove the newlines and crap added by the template itself that's what the - are for

reef barn
#

After an upgrade from 114 to the latest 115 many of my template sensors (mainly temperature calibration) are now saying unknown?

#

Seems to calculate right on template developer tool

#

However if I click the sensor the graph shows the correct value. Lovelace problem?

#

Reloading template entities (new entry in server controls) seems to correct it

woven folio
#

i'm getting an analog value from tasmota rain sensor. It goes from 1024(dry) to 0 or near 0 with heavy rain. How i transform that value in a 0/100% being 0% the analog 1024 and 100% the analog 0?

oak kiln
#

when using a value_template for json its value_json. What do I use if it isn't json? just value ?

dreamy sinew
#

should work

oak kiln
#

oh boy

#

value_template: "{{value * 100}}"

#

so if value is a string, you get a string consisting of 100x 1

#

apart from that it works. thx

dreamy sinew
#

@woven folio creating a simple percentage is rather trivial with a template, but it looks like you want to invert the percentage and that would be a pita

#

would need to find a formula to do what you want

mighty ledge
#

@woven folio The compensation integration would translate values using a linear fit, but I haven't finished writing it. For now, you'd have to use this equation: "{{ -0.0494071146245059 * value + 100 }}" in a template sensor.

sensor:
- platform: template
  sensors:
    heavy_rain_percent:
      friendly_name: Rain Percentage
      value_template: >
        {% set value = states('sensor.tasmota_rain_sensor') | float %}
        {{ -0.0494071146245059 * value + 100 }}
craggy schooner
#

Hey, I have a problem with my RGBW light. When I say Google to "change the light to white", it doesn't change to the white channel, it changes to some RGB values (and the RGB LEDs are lower watts than the white LED, so it's really dimm and not nice at all). I found a workaround via automation. It listens if any of the light turns to that exact RGB values that Google changes the light to, and then changes to the scene with white channel. My problem is that I would like to change only the light I am saying to the google. Now it changes to the scene, which is not optimal. Is there any line of code that would change only the light that got those "white" RGB values? https://paste.ubuntu.com/p/ztyqrbrqS4/ (it uses the scene now in the "actions") I am sorry I am a big noob with codes. Thanks for any help ❤️

robust lodge
#

I have a template question: I have a rest_command , with payload with a {{state}} variable. now I want to set state via service_variable as {{ states('switch.e) }}.
This does not work, I get OrderedDict([('[object Object]', None)]) in there

obsidian cypress
#

@robust lodge Is it because you’re missing a quotation mark? Or was that a typo into Discord?

robust lodge
#

typo in discord

dull stump
#

This problem has been quite a frustrating one. HASS is running under OS X via virtualenv and I need to execute minidsp mute enable as a shell command, where minidsp is a Node.js utility.

switch:
  - platform: command_line
    switches:
      workstation_screens:
        command_on: "/usr/bin/caffeinate -u -t 2"
        command_off: "/usr/bin/pmset displaysleepnow"
        friendly_name: Screen
      dirac_minidsp:
        command_on: '/Users/haru-tan/.nvm/versions/node/v10.7.0/bin/node "/Users/haru-tan/.nvm/versions/node/v10.7.0/lib/node_modules/minidsp/minidsp.js mute enable"'
#

I have provided complete paths to all elements, yet it returns a "command failed" error.

#

Executing node and minidsp alone is successful but upon adding the arguments for the latter, it fails.

#

Perhaps I have overlooked a syntax error but making changes to it has been unsuccessful, thus far.

inner mesa
#

did you try removing the quotes around the argument?

dull stump
#

Yes. I also tried inverting the quote forms.

inner mesa
#

you may be better of making a shell script that just does that for you. I had some issues with a shell_command and doing that helped

#

put the commands/logic in the shell script and just worry about calling that

#

that way, you can test the shell script independently and add debug to try to figure out what's wrong

dull stump
#

I would expect a script to behave effectively as a proxy to the direct command.

inner mesa
#

just throwing stuff out there based on my experience

dull stump
#

I will certainly give it a try, however.

#

HASS should really make use of the PATH variables. It would simplify much of this.

dreamy sinew
#

most installs of HA are not in the system path at all

dull stump
#

Granted, this is a relatively niche installation type.

inner mesa
#

and using full paths eliminates any ambiguity about what you're doing

dull stump
#

It would still be handy to have the option.

inner mesa
#

but that's also where creating a shell script helps - you can make it do whatever you want

dull stump
#

Anywho, let's see if this works.

inner mesa
#

pull in your environment, set the path, etc.

dull stump
#
#!/bin/sh

minidsp="/Users/haru-tan/.nvm/versions/node/v10.7.0/lib/node_modules/minidsp.js"
node="/Users/haru-tan/.nvm/versions/node/v10.7.0/bin/node"

node minidsp mute enable
#

This still fails.

robust lodge
#

hmm if I click edit as yaml it shows: '[object Object]': null

dull stump
#

Ah. There may be a path issue with that one. Hold on.

#

Path issue corrected but it still fails. It works when run in the terminal.

inner mesa
#

$node and $minidsp

dull stump
#

Yes, caught that.

#

Got it. After fiddling the with script permissions, it is working.

#

Thank you for that suggestion, @inner mesa.

craggy schooner
#

I am trying to make an automation that, if any light changes to a specific RGB value, it will set the white_value of that one light to 100% (255) What am I doing wrong? (I have no idea what I am doing)

silent barnBOT
craggy schooner
#

Basically what I want to achieve is this: If any of the RGBW lights receives the RGB value of 255,221,172, turn that light's white_value to 255 (or 100%).

Also now I noticed that in the code I sent here, I left the RGB value of pink or some weird color just to test if it works. normally there would be white_value or how it is properly written.

violet oyster
#

well, not a comment per se on the template, but your trigger will fire the automation every single time any entity at all changes state. and you have it set to mode 'single'

#

the odds that the one it would catch happens to be the light is extremely unlikely

#

maybe the condition would fix that but idk

#

@craggy schooner

#

i would try running it as parallel instead

#

or use a different trigger

hardy iris
#

I see that in the Templating docs it mentions "Process incoming data from sources that provide raw data, like MQTT". Is there any way I can change my value template from something like: "{{ states('sensor.player_songtitle') }}" to where it just reads from the MQTT topic without needing to make a sensor for it? my topic is musicplayer/songtitle

violet oyster
#

this is for an automation @hardy iris ?

hardy iris
#

no, its for a custom component im working on. I just need to read that topic and feed it into my component

#

so I'm seeing if theres a way to template this without having to need a sensor be made

violet oyster
#

oh i see. ive never made a custom component but with an automation I'd use an mqtt trigger and just use {{ trigger.payload }} or something to pull the song title

hardy iris
#

Ill look into it more, it was a bit hard wording this on google and finding the right results

mighty ledge
#

@hardy iris no unless you go custom

hardy iris
#

Alright, thanks for the help guys!

craggy schooner
#

@violet oyster sorry that was an automation that my friend made, I have no idea what I am doing. https://paste.ubuntu.com/p/ztyqrbrqS4/ This is the template that works for lights, only thing that I don't have is the action, I need it to set only that light that changed to that specific RGB color, not any other. Is there a way to do it?

bitter atlas
#

@craggy schooner I am sure one of the guru's would have a much better way of handling your situation but you could create a template sensor that outputs the light entity's name as a state depending on if values where you would check the rgb of each light then use that sensor as a trigger for the automation as well as the trigger.to.state in the action template.

woven folio
#

@mighty ledge thanks, i'll give it a try

tidal heart
#

Can I somehow show the name of the user in lovelace as a template? Like Hello {{username}}

lofty arrow
tidal heart
#

@lofty arrow Thanks!

silver pewter
spiral imp
deft timber
#

Yes you chould, by using a choose in the action part

#

(is_state('binary_sensor.morning', 'on') and is_state('sun.sun', 'below_horizon') and is_state('binary_sensor.someone_home', 'on')) or is_state('binary_sensor.morning', 'off')
and in the choose, if binary_sensor.morning is on, turn off, otherwise turn on.

#

Maybe you could also use a template to define the service instead

#

action: service: {{ "switch.turn_off" if is_state('binary_sensor.morning', 'off') else "switch.turn_on" }}

spiral imp
#

cool, totally forgot about that new choose option. Guess I should have posted in automations. Thanks

deft timber
#

action: service: switch.turn_{{states('binary_sensor.morning')}}
to make it shorter

oak mason
#

Since upgrading to 0.115 some (but not all) of my time sensitive sensor templates have given a result as "Unknown". I have updated them so that all entity_id's have been removed, and I have added the trigger line "{% set sensor_trigger = states('sensor.time') %}" to get the sensor.time to work. The templates give the expected correct result when I put them in Developer Tools/Template. The template is at https://paste.ubuntu.com/p/yBVcWWckKX/
Thank you for your advice.

violet oyster
#

@oak mason are any of the referenced sensors template entities themselves?

oak mason
violet oyster
#

did you use the new template reload feature recently?

#

for me, they work again if I restart HA

oak mason
#

Yes I have used that. I have used it again now and I now have an "Entity not available" showing on the web page. From memory this reverts to the "Unknown" when I reload HA. I will take a look at your link. Thanks again for your help.

violet oyster
#

Sure.

#

I'd try restarting again and see what happens. I'd bet it'll work.

oak mason
#

I am back to the sensor showing "Unknown" again after restarting HA.

#

But it is definitely something to do with the template entity "sensor.pool_heat_multiplier". When I replaced it with a number the master template worked as expected ie gave a correct output.

violet oyster
#

interesting. wonder why

#

@oak mason is the pool_heat_multiplier showing unknown also?

oak mason
#

@violet oyster Sorry for the delay. The pool_heat_multiplier shows the correct output.

dreamy sinew
#

which one is defined first in the config.yaml?

oak mason
#

Hi @dreamy sinew, calc_pool_pump_active comes first and pool_heat_multiplier comes lower down the page.

#

Does that make a difference?

dreamy sinew
#

yep, flip the order

oak mason
#

I'm on it

dreamy sinew
#

referencing something that doesn't exist

oak mason
#

You're a champion @dreamy sinew, problem solved! I wonder why it has become an issue only since 0.115. Is it because when the entity_id was being used all the referencing was being done before the calculating?

dreamy sinew
#

i'm not sure. they definitely changed how things are initialized but i haven't dug in to what actually changed

oak mason
#

Rock and roll, thanks very much for your help!

vague relic
#

i want to trigger alexa routine from home assistant

#

what i can do to do it

#

the only method is the binary sensor but I don't know how to configure it

#

I tried this:

#
-binary_sensor:
- platform: template
    sensors:
      alex_a:
        friendly_name: alexat
        value_template: ->
         if ('input_boolean.alexas', 'on')|float > 0 }}
dreamy sinew
#

{{ is_state('input_boolean.alexas', 'on') }}

vague relic
#

only in the last string? @dreamy sinew

#

there was only this problem?

dreamy sinew
#

yeah, what you wrote isn't a template

silent barnBOT
vague relic
#

yeah, what you wrote isn't a template
@dreamy sinew now I have to past that in configuration.yaml and everythings is ok?

dreamy sinew
#

Should work but you should verify in the template tester

vague relic
#

Should work but you should verify in the template tester
@dreamy sinew tester? 😅

buoyant pine
#

developer tools > template

clear pulsar
#

hi all. let per say I got this sensor showing 13:47:06 up 3 days, 22:24, load average: 1.45, 1.58, 1.40 and would like to used only up 3 days 22 and 24 is this possible? anyone can help me out?

charred dagger
#

@clear pulsar Here's something to get you started ```yaml
{% set value="13:47:06 up 3 days, 22:24, load average: 1.45, 1.58, 1.40" %}
{{ value.split(" ",1) }}
{{ value.split(" ",1)[1] }}
{{ value.split(" ",1)[1].split(",") }}
{{ value.split(" ",1)[1].split(",")[0] }}

clear pulsar
#

got it.. thanks @charred dagger

clear pulsar
#

yes.. thanks for @wise arrow and @charred dagger ya all been great.. it working now

#

now got my synology uptime

deft timber
#

You can also use regexp. The following will only select what you want and put it in a table:
{{ (value | regex_replace("[^ ]* ([^,]*), ([0-9]*):([0-9]*).*$", "\\1,\\2,\\3")).split(",")}}

charred dagger
#

Some people, when confronted with a problem, think
“I know, I'll use regular expressions.” Now they have two problems.

deft timber
#

🙂

clear pulsar
#

alas.. still have work to do hahahaha... if it only show minute its saya 10 min

#

arrgggghhhh

#

rather then showing 10:30

charred dagger
#

Maybe you should try uptime -p?

deft timber
#

{{ (value | regex_replace("^.*(up .*)days?, ([0-9]*):([0-9]*).*$", "\\1days,\\2,\\3")).split(",") if value|regex_match("^.*day.*$") else (value | regex_replace("^.*up ([0-9]*) min.*$", "up 0 days,0,\\1") ).split(",")}}

#

should work

clear pulsar
#

Maybe you should try uptime -p?
@charred dagger you are correct I should used that command instead just uptime. Arrrgggghh after I complete the what I need too hahahaha... Again thank you soo much

silver pewter
charred dagger
#

What's happening and what isn't?

#

And alsoyaml {% if now().hour < 12 %} {{ state_attr('sensor.nordpool', 'today')[now().hour + 12] }} {% else %} {{ state_attr('sensor.nordpool', 'tomorrow')[now().hour - 12] }} {% endif %}

silver pewter
#

@charred dagger
Tack för svar! I want to make a graph for future electricity prices from these attributes. https://paste.ubuntu.com/p/tcWfsgkSmq/. Is it better to use raw_today as they contain date and time maybe? Testar jag det du skrev får jag ett värde rätt bara 😛 för svårt för mig.. hehe

fallow sand
#

so i updated to 0.115.5 ...can anyone tell me why this does not work ...

  - platform: template
    sensors:
      ds_avg_temp:
        friendly_name: "Downstairs Average Temperature"
        unit_of_measurement: "°F"
        device_class: temperature
        value_template: >-
          {{ ((float(states.sensor.downstairs_temperature.state) + float(states.sensor.living_room_temperature.state) + float(states.sensor.entryway_temperature.state) + float(states.sensor.office_temperature.state) + float(states.sensor.front_entry_fibaro_multisensor_temperature.state)) / 5) | round(1) | default('unknown') }}
#

...but this does?:

  - platform: template
    sensors:
      us_avg_temp:
        friendly_name: "Upstairs Average Temperature"
        unit_of_measurement: "°F"
        device_class: temperature
        value_template: >-
          {{ ((float(states.sensor.upstairs_temperature.state) + float(states.sensor.nursery_temperature.state) + float(states.sensor.guest_room_temperature.state)) / 3) | round(1) }}

both worked fine until now.

inner mesa
#

how does it "not work"?

fallow sand
#

ah sorry - more specifically, all those values still show numeric results individually and collectively with:

{{ ((float(states.sensor.downstairs_temperature.state) + float(states.sensor.living_room_temperature.state) + float(states.sensor.entryway_temperature.state) + float(states.sensor.office_temperature.state) + float(states.sensor.front_entry_fibaro_multisensor_temperature.state)) / 5) | round(1) | default('unknown') }}

in developer tools.
However, in my frontend, and in the sensor for value sensor.ds_avg_temp shows unknown

#

driving me crazy! lol

inner mesa
#

what does the whole thing show in devtools -> Templates?

fallow sand
#

normally it is due to one of the sensors being offline, obviously but they are all giving me values...

inner mesa
#

you should use states('xxx') rather than what you're doing

#

that helps in exactly this situation

#

and...less typing

fallow sand
#

it shows this:

sensor:
  - platform: template
    sensors:
      ds_avg_temp:
        friendly_name: "Downstairs Average Temperature"
        unit_of_measurement: "°F"
        device_class: temperature
        value_template: >-
          78.7

works!

#

wait what? explain `states('xxx') please

inner mesa
#

ok. I just meant the template part, but that's good

#

replace states.sensor.front_entry_fibaro_multisensor_temperature.state with states('sensor.front_entry_fibaro_multisensor_temperature') and so on

fallow sand
#

I think i ran into issues that way if im following ...this gave me results so i went with it lol

#

ah I'll give that another try...ever see it work in the evaluator but not at the sensor?

inner mesa
#

no

fallow sand
#

ah - ok thanks, I'll give this a try and clean up the code maybe too.

#

shit, I've seen that before too - I thought I went thru my templates at the time 🙂

dreamy sinew
#

Also, is the sensor that isn't working depending on another template sensor?

fallow sand
#

no, they are all ecobee except for the fibaro

inner mesa
#

Unless you're using the Homekit Controller, Ecobee sensors aren't terribly reliable

#

that's actually a pretty great page. I don't think I've gone through it before

#

I probably point people to it more than I actually spend time there myself

sweet patrol
#

I'm just getting unknown, not sure why

#
  name: “Upstairs HVAC Lineset Vapor”
  state_topic: “tele/tasmota_6839FD/SENSOR”
  availability_topic: "tele/tasmota_6839FD/LWT"
  payload_available: "Online"
  payload_not_available: "Offline"
  device_class: temperature
  unit_of_measurement: ‘°C’
  value_template: >-
    {%- set sourceid = '3C01B5562F1C' -%}
    {%- for tsensor in value_json  -%}
      {%- if value_json[tsensor].Id == sourceid -%} {{value_json[tsensor].Temperature}}
      {%- endif -%}
    {%- endfor %}
#

tele/tasmota_6839FD/SENSOR = {"Time":"2020-10-01T23:00:34","DS18B20-1":{"Id":"3C01B5561C7F","Temperature":17.6},"DS18B20-2":{"Id":"3C01B5562966","Temperature":18.3},"DS18B20-3":{"Id":"3C01B5562F1C","Temperature":21.9},"DS18B20-4":{"Id":"3C01B5567958","Temperature":23.6},"DS18B20-5":{"Id":"3C01B5568B3A","Temperature":9.3},"TempUnit":"C"}

dreamy sinew
#

So the block at the bottom is the data?

sweet patrol
#

yes

dreamy sinew
#

Value_json is not a list

sweet patrol
#

but as the sensors could go missing, be replaced, ...

#

I need to match it via id and not name

#

I'm not sure what not a lost, means

dreamy sinew
#

Not a list

sweet patrol
#

still not sure what list means

#

you only have objects and arrays in json

dreamy sinew
#

Python term. Object == dictionary array == list

#

That data is not an array

sweet patrol
#

ok

dreamy sinew
#

You can't iterate that way

sweet patrol
#

it's valid json

#

I guess it's a python issue

dreamy sinew
#

No, your logic is wrong

sweet patrol
#

na, my logic is from a json background, but not python

dreamy sinew
#

You can't iterate over an object that way in jinja2

sweet patrol
#

ya this python makes no sense to me 😦

dreamy sinew
#
{%- set sourceid = '3C01B5562F1C' -%}
{% for value in value_json.values() if value.Id == sourceid  %}
{{ value.Temperature }}
{% endfor %}```
#

you can't iterate over an object directly

sweet patrol
#

I was slowly getting to that

#

probably take me another 20min

#

hmm, still no values

dreamy sinew
#

that works in the template tester

sweet patrol
#

I made a typo, retesting

dreamy sinew
#

oh and to be clear, you don't need that set value_json in yours

#

i just needed it to test since i don't have your data

sweet patrol
#

ya, I didn[t put that

dreamy sinew
#

its not completely obvious so i wanted to be sure

sweet patrol
#

still not

#
  name: “Upstairs HVAC Lineset Vapor”
  state_topic: “tele/tasmota_6839FD/SENSOR”
  availability_topic: "tele/tasmota_6839FD/LWT"
  payload_available: "Online"
  payload_not_available: "Offline"
  device_class: temperature
  unit_of_measurement: ‘°C’
  value_template: >-
    {%- set sourceid = '3C01B5562F1C' -%}
    {% for value in value_json.values() if value.Id == sourceid %}
      {{value.Temperature}}
    {%- endfor %}
dreamy sinew
#

oh wait, value is a thing already. change value to anything else

#

for v in ... if v.Id... v.Temperature

sweet patrol
#

still nothing 😦

#
    {%- set sourceid = '3C01B5562F1C' -%}
    {% for item in value_json.values() if item.Id == sourceid %}
    {{item.Temperature}}
    {% endfor %}

dreamy sinew
#

hmm, not sure then. its a valid template

#

you have a bunch of fancy quotes in your yaml there, might not be helping

sweet patrol
#

works fine in template editor too here

dreamy sinew
#

vs
unit_of_measurement: 'C'

#

name and state_topic as well

sweet patrol
#

thats almost got it

#

ah, that sensor that isn't worked dropped offline

#

reason why matching them via id and not name

dreamy sinew
#

haha

sweet patrol
#

7 total temp sensors on the hvac unit

#

5 of these ds18b20's

dreamy sinew
#

wow

sweet patrol
#

2 bme280's

#

just need to add two pressure sensors, and some relays and should be finished up

#

but wanted to run awhile with just the tempature sensors so I can do the calculations

#

used to do HVAC work, this will give me full complete calibaration of the unit on each cycle

dreamy sinew
#

noice

sweet patrol
#

can adjust fan speeds, notify if filters need changed

#

coil freezing, refrigerant leak, or a ton of other self diagnostics

#

must have a bad crimp on the jst for that sensor

clear pulsar
#

guys... need more advice..

#

I need to get uptime from 2nd synology

#

to do that I will need to used SSH command

#

however from HA command its keep showing fail

#

any idea how to do that?

#

2nd synology dont have HA running

deft timber
#

when calling ssh from HA you need to make sure that you are using the full path of ssh binary, and the the user used to run HA can connect to ssh without prompting for a password

#

you could also use SNMP instead of ssh, but it requires more setup

elfin terrace
#

I have a template sensor which has broken in the latest version, but the template string still works in the dev tools. Any ideas? {{(((states("sensor.electricity_wholesale_estimate")|float) + (states("input_number.electricity_supply_charge")|float))*state_attr("sensor.electricity_usage_statistics","change_rate")*3.6*1.1)|round()}}

keen sky
#

hello guys, can you help me with this template. I have this one :

#
  • platform: template
    nodemcu_ds18b20_bme280_temperature:
    entitiy: sensor.nodemcu_ds18b20_bme280_temperature
    friendly_name: 'Huidige opbrengst'
    value_template: "{{ sensor.nodemcu_ds18b20_bme280_temperature | replace('unknown','0') }}"
#

in my sensor.yaml

#

but when i did check I have error:

#

root@plex-server:~# ha core check
Error: Testing configuration at /config
INFO:homeassistant.util.package:Attempting install of httplib2==0.10.3
Failed config
sensor.template:
- Invalid config for [sensor.template]: [nodemcu_ds18b20_bme280_temperature] is an invalid option for [sensor.template]. Check: sensor.template->nodemcu_ds18b20_bme280_temperature. (See ?, line ?).

deft timber
#

your line nodemcu_ds18b20_bme280_temperature:should not be there

#

it should be
- platform: template name: nodemcu_ds18b20_bme280_temperature entitiy: sensor.nodemcu_ds18b20_bme280_temperature friendly_name: 'Huidige opbrengst' value_template: "{{ sensor.nodemcu_ds18b20_bme280_temperature | replace('unknown','0') }}"

keen sky
#

same result

#

ha core check
Error: Testing configuration at /config
INFO:homeassistant.util.package:Attempting install of httplib2==0.10.3
Failed config
sensor.template:
- Invalid config for [sensor.template]: [name] is an invalid option for [sensor.template]. Check: sensor.template->name. (See ?, line ?).

deft timber
#

are you sure about the indentation of your configuration file? everything should be aligned in the sensor config

keen sky
#

yes, it is in separate file sensors.yaml

#
  • platform: template
    name: nodemcu_ds18b20_bme280_temperature
    entitiy: sensor.nodemcu_ds18b20_bme280_temperature
    friendly_name: 'Huidige opbrengst'
    value_template: "{{ sensor.nodemcu_ds18b20_bme280_temperature | replace('non-numeric','0') }}"
#

for example other sensors, which are described here with other platforms work fine

deft timber
#

according to this page https://www.home-assistant.io/integrations/template/, it should be
`sensor:

  • platform: template
    sensors:
    nodemcu_ds18b20_bme280_temperature:
    friendly_name: "Huidige opbrengst"
    value_template: "{{ sensor.nodemcu_ds18b20_bme280_temperature | replace('non-numeric','0') }}"`
keen sky
#

[name] is an invalid option for [sensor.template].

#

sensors: by my opinion have not to be there. It is already in separate file sensors.yaml

#

which is described in configuration.yaml

deft timber
#

yes indeed, that was a generic answer 🙂

marble jackal
#
  • platform: template
    name: nodemcu_ds18b20_bme280_temperature
    entitiy: sensor.nodemcu_ds18b20_bme280_temperature
    friendly_name: 'Huidige opbrengst'
    value_template: "{{ sensor.nodemcu_ds18b20_bme280_temperature | replace('non-numeric','0') }}"
    @keen sky you should remove name: in line 2
    and as your friendly name is the same as the name (besides the senor. part), it's not needed to specify it
keen sky
#

I remove it and frendly_name as well

#
  • platform: template
    nodemcu_ds18b20_bme280_temperature:
    value_template: "{{ sensor.nodemcu_ds18b20_bme280_temperature | replace('non-numeric','0') }}"
#

Error: Testing configuration at /config
INFO:homeassistant.util.package:Attempting install of httplib2==0.10.3
Failed config
sensor.template:
- Invalid config for [sensor.template]: [nodemcu_ds18b20_bme280_temperature] is an invalid option for [sensor.template]. Check: sensor.template->nodemcu_ds18b20_bme280_temperature. (See ?, line ?).
- platform: template
nodemcu_ds18b20_bme280_temperature: None
value_template: {{ sensor.nodemcu_ds18b20_bme280_temperature | replace('non-numeric','0') }}

#

what mean this ? INFO:homeassistant.util.package:Attempting install of httplib2==0.10.3

#

did i miss to install something ?

deft timber
keen sky
#

yes

#

hmmmmm

#

i put sensors: and it is work now ....

#

hmmmm

#

even it is at seprate file snesors.yaml

marble jackal
#

Yes, that is why the first sensor: is not needed

#

But after that you define (within sensor.yaml) that you want to use the template plaform

#

And in this template platform, you can the define multiple sensors, that is why that sensors: is needed

keen sky
#

okay understood

#

thank you. let the MQTT send values to see the result

marble jackal
#

So you could multiple template sensors under that one - platform: template line

#

*could create

keen sky
#

now i replace it in my gauge card with new entity : sensor.nodemcu_ds18b20_bme280_temperature_2

#

but still have some picture

#

fixed 🙂

#

thank you guys !

#

just remove value_template: {{ sensor.nodemcu_ds18b20_bme280_temperature | replace('non-numeric','0') }}

#

i have additional question. I have a lot of sensors as this one. Have i do templates for each one ? Or have more intelligent way to do for all of them ?

summer ore
#

Hi ! I have created a scrape sensor that checks if there is a new FW for my router. It works. Now I would like to create a binary sensor that shows me if the value of my scrape sensor changed. All the examples that I found are using a template binary sensor, but all of them rely on a threshold with which you need to compare your value. In my case, I don't have a threshold. I would just need the binary sensor to be triggered when the FW sensor changes after a while (1 day, for example). Any suggestions ?

deft timber
#

I'd say 1 template sensor for each

thorny snow
#

Hi all, I have 4 sensor entities to get ink levels and a 5th to get status of my printer. When my printer is on, I have the ink levels like this :
https://ibb.co/LtbQxpD
When my printer is off :
https://ibb.co/9TDPHc4
I'd like to get the last ink levels with normal color drop icon when printer is off
and the update ink levels with personalised ink color (black, yellow, magenta, cyan) drop icon when printer is on

I looked around templates and icon_color with custom UI but without success
Thanks for you help

thorny snow
#

@thorny snow you should create 4 template sensor with a condition if is not unknown return value...

wicked gazelle
#

Hi can anyone help me with the shelly em config in homeassistant? when i use value_template: "{{ value_json.ENERGY.Power }}" the result is [0,449] how to i remove the []?

thorny snow
#

@summer ore i have create a input_text which get the fw version when i check a button card.. And a automation which compare sensor.fw_version and input_text.current_version

dreamy sinew
#

@wicked gazelle do you want both numbers?

#

oof please stop with the quote replies

summer ore
#

@thorny snow So you have to fill in the current version every time ?

wicked gazelle
#

@dreamy sinew no i just want the 449 part

dreamy sinew
#

is it always 2 values?

thorny snow
#

@summer ore yes because i update every first weekend but the automation can update input_text with service

wicked gazelle
#

i dont mind if its 0,449 i can multiply it by 1000 to get 449 i just need to remove the square brackets

dreamy sinew
#

that is a list of 2 numbers, so please answer the question. Are there always 2 items in that list?

wicked gazelle
#

oh ok yes the shelly em has 2 clamps but im not using the other one so if its a list then yes i only want the 449 part the 0 will allways be 0

#

i didnt know the comma was a list

dreamy sinew
#

{{ value_json.ENERGY.Power[-1] }}

wicked gazelle
#

i will try that thank you.

#

just out of curiosity how would i get the first number?

dreamy sinew
#

[0]

wicked gazelle
#

[-0]?

#

oh just 0

dreamy sinew
#

-1 is shorthand for "last"

#

since its only 2, you could do [1]

wicked gazelle
#

ok and if i wanted the middel value of 5 options i could use [2]

#

i get it

#

thanks

dreamy sinew
#

yep, 0 index

wicked gazelle
#

i see

dreamy sinew
#

- starts from the end

wicked gazelle
#

I just rebooted and that works perfectly thank you.

#

and thanks for the rest of the information

brave root
#

is there any way to extract information about persistent notifications?

#

for example, I would like to get a push notification on my phone whenever something generates a persistent notification

dreamy sinew
#

not that i've seen

brave root
#

the only thing I have found is I can do:

{{ states.persistent_notification | length }}
inner mesa
#

I wonder if there’s an event

brave root
#

which will let me now that something happened... just can't get info about it

#

@inner mesa good idea

#

there is: persistent_notifications_updated

#

which gives:

Event 0 fired 10:08 AM:
{
    "event_type": "persistent_notifications_updated",
    "data": {},
    "origin": "LOCAL",
    "time_fired": "2020-10-02T17:08:53.852771+00:00",
    "context": {
        "id": "f31f603904d111ebbff64fdec341da28",
        "parent_id": null,
        "user_id": null
    }
}
#

doesn't seem to have any of the data of the notification though (title, message, etc)

topaz walrus
#

still having trouble with this after updating

#
    sensors:
      last_motion:
        friendly_name: 'Last Motion'
        icon_template: 'mdi:motion-sensor'
        value_template: >
          {%- set pirs = [states.binary_sensor.kitchen_motion_sensor, states.binary_sensor.master_bedroom_motion_sensor, states.binary_sensor.master_closet_motion_sensor, states.binary_sensor.living_area_motion_sensor, states.binary_sensor.full_bath_motion_sensor, states.binary_sensor.half_bath_motion_sensor, states.binary_sensor.stairs_motion_sensor, states.binary_sensor.kids_room_motion_sensor, states.binary_sensor.play_room_motion_sensor] %}
          {% for pir in pirs %}
            {% if as_timestamp(pir.last_changed) == as_timestamp(pirs | map(attribute='last_changed') | max) %}
              {{ pir.name }}
            {% endif %}
          {% endfor %}```
inner mesa
#

@brave root When I call the actual service, I get this:

#

I don't know if "internal" ones follow the same path, but that has the content

brave root
#

what event were you listening for?

inner mesa
#

but presumably "call_service" would have done it too

brave root
#

right, I guess I could try to filter all call_service events, but you're right, does the 'house' use some internal thing

inner mesa
#

you could add garbage to your automations.yaml and reload automations. that will create a persistent notification

#

hmm, doesn't fire

topaz walrus
#

did an update lately brake all of these?

#

😕

keen sky
#

hello people, can I ask for your help. I just start to learn how to make templates and have not idea at all about the logic. However, i have this {{ nodemcu_ds18b20_bme280_temperature | replace('non-numeric','0') }} and obviously this always replace with 0. This sensor is online not all the time and I want when it is online to read the data from nodemcu_ds18b20_bme280_temperature, but when is offline to display 0 or even better to display "Not available"

#

or if you can point me some link to read about the "program language" for templates will be best

silent barnBOT
topaz walrus
#

anyone willing to help, feel free to @ me so ill get a notification.

keen sky
#

why % is at the beginning like {% if state.sensor.nodemcu_ds18b20_bme280_temperature ......%}

inner mesa
#

It’s part of the template syntax

silent barnBOT
keen sky
#

actually let me ask if i take correct way. I have card for one sensor, which is not all the time online. I want , when is it to display the data, when is off to display something like "Not online"

#

so have i use templates for that ?

#

and really which program language use templates ?

inner mesa
#

it's "jinja", as above

keen sky
#

okay .. very exotic for me 🙂

inner mesa
#

if you're not happy with the sensor state text when it's available and when it's not, you can either create a template sensor to customize the state names, or you can use a card that lets you add a template right in the Lovelace config

#

it's generally Python-like

topaz walrus
#

RobC you able to help me if you have time?

next bluff
#

Hey I have custom template sensor state with a list of entities comma separated which needs to be turned off, how to provide the entities list for the turn off action?

young jacinth
#
  - platform: template
    sensors:
        wz_tv:
            friendly_name: WZ TV
            value_template: >
                {% if is_state_('binary_sensor.wz_fire_tv', 'on')
                      or is_state('media_player.ps4', 'playing') %}
                  active
                {% else %}
                  inactive
                {% endif %}

what is wrong with this template over here? the sensor shows as unavailable

bitter atlas
#

improper indentation?

young jacinth
#

its looking fine for me, but iam not sure

buoyant pine
#
is_state_('binary_sensor.wz_fire_tv', 'on')
        ^
young jacinth
#

oh 😫 copy and pasting fault. Thanks for your help that should do it

torn gorge
#

Hello, is it possible to get the last state of a cover in its own value template?
I try somethings like this:

{% if is_state('binary_sensor.garage_open', 'on') and is_state('binary_sensor.garage_closed', 'off') %}
open
{% elif is_state('binary_sensor.garage_open', 'off') and is_state('binary_sensor.garage_closed', 'on') %}
closed
{% elif is_state('binary_sensor.garage_open', 'off') and is_state('binary_sensor.garage_closed', 'off') and is_state('**xyz last state of this cover **xyz', 'closed') }} %}
opening
{% elif is_state('binary_sensor.garage_open', 'off') and is_state('binary_sensor.garage_closed', 'on') and is_state('**xyz last state of this cover **xyz', 'open') }} %}
closing
{% endif %}

oak kiln
#

how do I negate is_state_attr?

inner mesa
#

With ‘not’

clear pulsar
#

hi everyone I used variable to create yesterday info, however need to ada info on the numbers. Try to used ```

  • platform: template
    sensor:
    worldwide_coronavirus_new_today_dot_separated:
    friendly_name: New cases in the World Today
    value_template: "{{ '{:,}'.format(states.variable.worldwide_coronavirus_new_today.state | int).replace(',','.') }}"
    unit_of_measurement: ""
#

I got error..

#

is there away to show variable.worldwide_coronavirus_new_today with dot seperated?

sweet patrol
#

@dreamy sinew well it's been working good after all that annoyance the other day

bronze horizon
#

Wow. I wanted to fix an automation that was firing at startup because a trigger state doesn't populate immediately. Wasn't expecting it to stop the error in the logs, but it did that too :D

not ((states('sensor.homeassistant_uptime') | int) < 5 and is_state_attr('sensor.homeassistant_uptime','unit_of_measurement','minutes'))

Is the second part necessary? I'm not sure if it'll change to 'hour' after 60 minutes, haven't waited long enough 😛

fresh yoke
#

hi
I have an issue with my template covers

I have multiple RF covers in my home
They're all controlled using BroadLink RM Pro

I've set up a template cover for each one of the covers
With each having a scripts for OPEN / CLOSE / PAUSE .

My problem is when I restart HA , The covers default to OPEN
and not the pervious state before restart

Any ideas on how to fix that ?

inner mesa
#

~share one

silent barnBOT
inner mesa
#

You should check out the value_template

fresh yoke
#

https://paste.ubuntu.com/p/BB98FVpczf/
That's my cover setup
I'm new to templating
so I don't really know what to do

But I figured the problem might be because the covers have no reference / or sensor that tells them the current state of the blinds/curtains so they just default to OPEN

inner mesa
#

Right, you have no value_template at all, so there’s no indication of current state

#

It should just default to what it was (optimistic mode)

fresh yoke
#

But they're RF controlled no sensors (:
I've been thinking of maybe creating a sensor that is "last_state" for each cover and set that to the value template
But I don't really know how to do that

inner mesa
#

An input_boolean would do it

fresh yoke
#

isn't there a way to do it with a sensor
Input Booleans aren't that appealing lol

inner mesa
#

On for open, off for closed

#

Does it matter?

#

Sure, you could do it with a sensor

fresh yoke
#

can you show me an example please (:

bitter atlas
#

you would use the bool to reserve the state upon restart,m you wouldn't ever see the bool

inner mesa
#

You can solve it however you like

fresh yoke
#

well I got the gist of it so i'll try to figure it out
Thanks for the help (:

silent barnBOT
thin cedar
#

Hey guys, I've just started playing around with templates and i'm running into a problem. when i have this template as a part of my script, i can reload scripts without getting a notification. But it hangs on the spinning wheel when i try to validate config. Any ideas what might be wrong?
This is my script: https://paste.ubuntu.com/p/hWQdc36jYX/

inner mesa
#

I don’t think that’s what you want to do

#

You should use ‘is_state_attr’ to test ‘current_activity’ against your Apple TV activity

#

There’s no attribute called "Watch Apple TV", and the expression doesn’t result in a boolean true/false

#

@thin cedar

thin cedar
#

Thanks @inner mesa !
that explains a lot. i gotta do some more reading in how templates work "Watch Apple TV" . is what the activity in Harmony is called. i want the condition to be that that activity is currently active.

inner mesa
#

Right, I have several of those. Test ‘current_activity’

thin cedar
inner mesa
#

Yes, like that

thin cedar
#

Thanks @hoary aspen !
for some weird reason It still freezes my config validation though. i'll keep trying

inner mesa
#

Weird. I’ve heard a few people mention the config check never ending. If you gace a simple example, please file an issue

silent barnBOT
summer summit
#

Hi, does anyone have experience with not displaying the data from the sensor template in LOVELACE, but the data is shown in the test template?

inner mesa
#

~share the template

silent barnBOT
summer summit
inner mesa
#

that's a lot of templates

#

do you have a more specific problem?

summer summit
#

OK, only the one that doesn't work is needed, I guess the third is the sensor

#

line 12-16

inner mesa
#

is that like "unknown"?

summer summit
#

no, it's like "undetected" and in detail "status history is missing". But it appeared after the reboot. Sometimes it was just there and it worked and sometimes it didn't. But in / developer-tools / template it works and shows the current curve.

inner mesa
#

where does the sensor data come from? MQTT?

summer summit
#

No, the data comes from the Viessmann API

inner mesa
#

are you running at least version 0.115 of HA?

summer summit
#

0.115.6

inner mesa
#

try configuration -> Server Controls -> Reload Template Entities

summer summit
#

super 🙂

inner mesa
#

better?

summer summit
#

Thank you. Amazing, now it works like a miracle. I tried many restarts and it didn't work. But this is now happening immediately.

#

👍

inner mesa
#

excellent. that means that one or more of those entities wasn't available or reporting data when HA started and none of the entities changed later to cause the template to be reevaluated?

#

which is weird, because it seems like they clearly did change

summer summit
#

I don't know why this is so, but it is possible that one of the code could not have changed and that is the target temperature, so it is probably always the same?

#

but it would probably be a good idea to adjust it somehow in some automation, so that this always plays after the restart, so that the data is then in order. Is it possible to treat it in any way?

inner mesa
#

you can call homeassistant.update_entity on that entity when you wish, or you can add something like {% set t = states('sensor.time') %} to your template to make it reevaluate regularly

summer summit
#

I'm not so experienced to do this. Where exactly should it be in that antite to update it regularly?

inner mesa
summer summit
#

OK, thank you very much for your help. I didn't expect a quick response from "our" Home Assistant community 🙂

queen pawn
#

Good morning! I'm working on a template sensor which works fine in the templating tool, but when it's present in my sensors.yaml file, the Configuration Check spins with no end. When I remove it, everything's fine. I figured I'd start here, but happy to go elsewhere too.

#

The template in question is to turn a numerical Air Quality Index number range into friendly English text.

inner mesa
#

posts here 30mins ago recounted something similar

queen pawn
#

I'll scroll back

inner mesa
#

~share your sensor template

silent barnBOT
queen pawn
#

Nice to see you again, Rob! Hope you're well.

inner mesa
#

yep, thanks

#

'Hazardous' should be 2 spaces to the right

queen pawn
#

D'oh

inner mesa
#

and everything below air_quality_lang: needs to be 2 spaces to the right

queen pawn
#

The rest of the indents look ok?

inner mesa
#

yes

queen pawn
#

Well, the check no longer breaks, but the sensor still doesn't show up in states.

#

This gets me past the other hurdle, though. Many thanks!

topaz walrus
#

still looking to get help with this template that broke after the last update:

#
- platform: template
    sensors:
      last_motion:
        friendly_name: 'Last Motion'
        icon_template: 'mdi:motion-sensor'
        value_template: >
          {%- set pirs = [states.binary_sensor.kitchen_motion_sensor, states.binary_sensor.master_bedroom_motion_sensor, states.binary_sensor.master_closet_motion_sensor, states.binary_sensor.living_area_motion_sensor, states.binary_sensor.full_bath_motion_sensor, states.binary_sensor.half_bath_motion_sensor, states.binary_sensor.stairs_motion_sensor, states.binary_sensor.kids_room_motion_sensor, states.binary_sensor.play_room_motion_sensor] %}
          {% for pir in pirs %}
            {% if as_timestamp(pir.last_changed) == as_timestamp(pirs | map(attribute='last_changed') | max) %}
              {{ pir.name }}
            {% endif %}
          {% endfor %}
#

feel free to @ me if you can help out

coarse tiger
#

have you tried manual checking the date comparison in dev tools? there could be a difference when one of them has ms while the other only has seconds

topaz walrus
#

thanks for the help yeah when i check it in the tool it says: This template listens for all state changed events.

#

and the state of the sensor says "unknown"

noble herald
#

Hello, i'm wanting to add an attribute template to my template sensor but when i check the config in the ui, it throws me an error, can you help me ?

#
next_train_from_beautiran_to_bordeaux_humanized:
        friendly_name: "Prochain Départ de la gare de Beautiran"
        value_template: '{{ as_timestamp(states.sensor.next_train_from_beautiran_to_bordeaux_raw.state)  | timestamp_custom("%H:%M:%S") }}'
        attributes_template:
          delayed: >-
            {% if state_attr('sensor.next_train_from_beautiran_to_bordeaux_raw','delayed') == false %}
              A l'heure
            {% else %}
              En retard
            {% endif %}
inner mesa
#

move the "s"

#

attribute_templates:

noble herald
#

oh god thank you

#

now the config is valid

#

🙏

inner mesa
#

easy to miss

noble herald
#

you saved my entire night

#

and the attribute is here (after a restart) thank you

inner mesa
#

glad it's working

noble herald
#

now, i need to create a new device in node red to be discovered by alexa, an ultra nightmare...

blazing burrow
#

hmm, can't use templates for colors in hs_color?

#

want to turn on a light to a random color

inner mesa
#

the forum has examples of what you can do

blazing burrow
#

hmm, so is that a no or a yes?

hollow rampart
#

Hello everyone. I have a ISY994i controller running in conjunction with Home Assistant and HomeKit. I’m on 5.016 and latest Home assistant version. Most of my devices are Zwave. For the most part, the integration is working great. The problem I’m trying to figure out is how to communicate with dimming lights using 0-100 parameters vs 0-255. I can control the dimmer but 100 out of 255 shows up 100% on the ISY. I tried using input numbers but that does not translate well into HomeKit because it shows up as a switch. I tried several light templates and while I can control the on and off feature, I am unable to figure out how to scale the dimmer slider. I’m hoping that some one here has had the same issue and there is an easy fix that I’m missing. This may not be the place to ask the question and if that’s the case I apologize. If someone could point me in the right direction or help me with this I would very much appreciated. I’m new to HA and I’m not big on programming but I can figure things out with a little help.

blazing burrow
#

@inner mesa gotcha, so the trick is just changing from data: to data_template:

#

that doesn't appear to let me set a template for transition though

inner mesa
#

no

#

you don't need that anymore

#

the point is that you cannot construct a template that returns a list because they only ever return a string. So when you need to provide a list, the best you can do is to provide each list element as a template

blazing burrow
#

I've done that

silent barnBOT
blazing burrow
#

but I did have to change to data_template

inner mesa
#

what version of HA are you using?

blazing burrow
#

0.116.0.dev20200921

inner mesa
#

🤷

blazing burrow
#

hmm, any idea why a template wouldn't work in transition?

#

just not supported I guess

hollow rampart
#

Would be possible for someone to look at the template. This is related to changing dimmer values from 0-100 vs 0-255

silent barnBOT
#

Don't ask to ask, just ask your question. Then people can answer when they're around.

When you do ask a question, try to provide as much background detail as possible. Ask yourself these questions first so that others don't have to:

  1. What version of the Home Assistant are you running? (remember, last isn't a version)
  2. What exactly are you trying to do that won't work?
  3. Is the problem uniform or erratic?
  4. What's the exact error message?
  5. When did it arise?
  6. What exactly don't you "get"?
  7. Can you share sample code, ideally with line errors where the error occurs?
blazing burrow
#

how about this one? https://pastebin.com/uw0qJ6uC
the entity_id value there gives me an error when checking config:
Invalid config for [automation]: not a valid value for dictionary value @ data['action'][0]['repeat']['sequence'][0]['entity_id']. Got None.

#

why would it be none? that template works fine in the template tester

#

this doesn't work either 🤔
entity_id: "light.lr_{{ ['top', 'middle', 'bottom'] | random }}"

#

nor this: entity_id: "states.light.lr_{{ ['top', 'middle', 'bottom'] | random }}.id"

#

🤬

inner mesa
#

Put it under data:

#

I.e., add 2 spaces

blazing burrow
#

ah, thank you 👍 that's totally working now

#

if the transition one worked that'd be cool

#

might be my bulbs?

blazing burrow
#

🤔

#

yeah idk, seems to not make any difference

faint salmon
#

Hi, Is it possible to get the device info to use in a template? I have a Zigbee device (ZHA) and I want to get the LQI and RSSI from there.

thorny snow
#

I think a dumb question: I have a sensor that reports a date in epoch and I want to create a new sensor that contains the same date, but formatted cleanly in %a, %b %d format. I think I need a template integration for this right?

I tried this but I think I'm doing it wrong:

template:
  - sensors:
      next_trash_pickup:
        friendly_name: "Next Trash Pickup"
        value_template: '{{ states("sensor.next_trash_pickup_raw") | int | timestamp_custom("%a, %b %d") }}'

That value_template is all one line but its just not formatting right here.

#

Never mind, I got it 🙂 I had it backwards. This works:

sensor:
  - platform: template
    sensors:
      next_trash_pickup:
        friendly_name: "Next Trash Pickup"
        value_template: '{{ states("sensor.next_trash_pickup_raw") | int | timestamp_custom("%a, %b %d") }}'
silent barnBOT
thorny snow
#

Is there any (recommended) way to make a value_template re-usable. I'm converting/translating values from one sensor using value_template (and icon_template). This works great, but I want to have it applied to many sensors, and don't want to repeat myself all over my configuration with the same template snippets. Typically it seems that YAML anchors are an option, but I don't see how it would be done in my case:

#
      fk1:
        friendly_name: "Linker Fensterflügel"
        value_template: >-
          {% set state = states('sensor.srh1_state') %}
          {% if state == 'open' %}
            Geöffnet
          {% elif state == 'tilted' %}
            Gekippt
          {% elif state == 'closed' %}
            Geschlossen
          {% else %}
            ?
          {% endif %}
#

Now I would like to have this template applied to many other sensors, so essentially the set state= line would be different in each case, while everything else would be the same.

clear pulsar
#

hi everyone.. wondering how can I replace the entity_id with? because its depreceated

#
- platform: template
  sensors:

  #----- Count Automations
    count_automations:
      entity_id: sensor.date
      value_template: "{{ states.automation | list | length }}"
thorny snow
#

HI!
Could someone give an idea to implement device_tracker using mqtt?

buoyant pine
#

@clear pulsar there are multiple posts on the forum about this, but one common way to fix it is by doing something like this:

value_template: >
  {% set date = states('sensor.date') %}
  {{ states.automation | list | length }}
clear pulsar
#

@clear pulsar there are multiple posts on the forum about this, but one common way to fix it is by doing something like this:

value_template: >
  {% set date = states('sensor.date') %}
  {{ states.automation | list | length }}

@buoyant pine got it.. thanks

torpid gust
#

Is it possible to set a card name dynamically using a template/sensor value?

faint salmon
coarse tiger
#

Is it possible to set a card name dynamically using a template/sensor value?
@torpid gust #frontend-archived

thin cedar
#

Hey, i got some help with this one yesterday, but still can't get it to work.
I'm trying to get home assistant to check that current activity is "Watch Apple TV" before it turns the activity off. But whenever i include the template as a condition my config check freeezes. I suspect this is just user error. can anyone help me spot the error?
https://paste.ubuntu.com/p/Q5pjS4BhWb/

Thank you,
V

vagrant monolith
#

How can i do something like this? {{ state_attr({{variable}}, 'gps_accuracy') }}

woven magnet
#

Drop the inner {{}}'s…

#

Outside the {{}}'s, is text. Inside the {{}}'s, is template (Python-ish)…

vagrant monolith
#

Okey but in this situation then?

          {{ state_attr(alias, 'gps_accuracy') }}```
#

that not working

#

Nothing me passing wrong variable xD

#

Instead of it creating etc ida_for_ida and so on

fringe leaf
#

How can I split and get only a part of a sensor's value?..
like if I have a sensor that gives back a value of 88,-834,-34 (angle sensor)..
how can I get only the middle number?

coarse tiger
#

{{ value.split(",")[1] }} @fringe leaf

fringe leaf
#

ty!

thorny snow
#

Is there any (recommended) way to make a value_template re-usable. I'm converting/translating values from one sensor using value_template (and icon_template). This works great, but I want to have it applied to many sensors, and don't want to repeat myself all over my configuration with the same template snippets. Typically it seems that YAML anchors are an option, but I don't see how it would be done in my case:
@thorny snow Does anyone have some ideas here?

dim iron
#

how would I add or truck besides car?

dreamy sinew
#

Template reuse isn't really a thing @thorny snow

dim iron
#

im not used to this syntax 😒

dreamy sinew
#

What's the raw data look like?

dim iron
#

um doods output

dreamy sinew
#

I don't use doods

dim iron
dreamy sinew
#

Hmm, I'd need to get to a computer to work it out

dim iron
#

yah, this is the hard part

#

defining box areas for sensors so I can send notifications based on criteria

dim iron
dreamy sinew
#

Lol wow. Yeah, he's usually on top of things

hollow rampart
#

Has anyone figured out how to scale a dimmer from 0-255 to 0-100. If I use pct. HA still passes it as a 0-255.

topaz walrus
#

anyone know how to tweak this template? I need it to ONLY display when the motion sensors trigger... the issue i am having right now is it will trigger when someone walks through the house and then trigger a second time when the state of the entities its watching changes to "no motion" does that make sense? lol

#
    sensors:
      last_motion:
        friendly_name: 'Last Motion'
        icon_template: 'mdi:motion-sensor'
        value_template: >
          {%- set pirs = [ entity 1, entity 2 so on... ] %}
          {% for pir in pirs %}
            {% if as_timestamp(pir.last_changed) == as_timestamp(pirs | map(attribute='last_changed') | max) %}
              {{ pir.name }}
            {% endif %}
          {% endfor %}```
#

almost need some type of "filter" so that it only display the state "motion detected"

buoyant pine
#

I think an automation that writes the friendly name of the last motion sensor to go to 'on' to an input text would be better here

topaz walrus
#

im pretty noobish

buoyant pine
#

Pretty noobish and you wrote that template?

topaz walrus
#

can you elaborate? im all for doing something more efficient

#

heck no haha

#

someone shared it with me while back in this channel

buoyant pine
#

State trigger with to: 'on' and a list of the motion sensors for entity_id:

#

The action is input_text.set_value with the value being "{{ trigger.to_state.name }}"

topaz walrus
#

btw all of this to just have a glance card on my lovelace so i can see which room had motion in it last

#

so that automation your saying i should build would stop my template from displaying the entity when the state changes twice?

buoyant pine
#

It would only trigger when one of the sensors goes to 'on'

topaz walrus
#

so i have a hard time understanding most of the template. what line in the template tells the sensor to look for a "state" on the sensors its watching?

#

or does it just watch for "all" state changes?

buoyant pine
#

It's basically triggered on every state change of that list of sensors

#

It updates when last_updated for any of the sensors changes

topaz walrus
#

got ya, think im on the same page.

#

i guess i just dont understand why building an automation would fix it. Wouldnt it just now see the state "on" and then "no motion" and trigger twice?

#

sorry just trying to understand it lol

buoyant pine
#

No

#

That's why I said to make the state trigger with to: 'on'

#

I can throw it together in a bit if you're having trouble visualizing what I mean

topaz walrus
#

i am... and just trying to be polite not to wear you out haha

#

no worries on the time frame take your time thanks for the help thus far

buoyant pine
#

Nah you're good

topaz walrus
#

i have zero background in this so its all self taught and this discord that gets me places..

buoyant pine
#

There's a pretty big learning curve with home assistant

topaz walrus
#

been a pretty fun hobby so far!

buoyant pine
#

For sure, it's very powerful

topaz walrus
#

if you think of me later, fell free to PM or tag so i can find it in the flood of messages lol

buoyant pine
#

Yeah no prob, I'll ping you

topaz walrus
#

yeah its super powerful and I have a TON of different sensors so its been cool to collect all the date and think of different automations to build and all

buoyant pine
#

create an input_text named whatever you want and change the entity ID for it in the action. also update the entity IDs in the trigger as needed

dreamy sinew
#

@hollow rampart not sure what you're asking for

hollow rampart
#

Hello. I have an Isy994i controller. I’m running rpi with HA. All d3vices are ZWave. ISY accepts brightness on a scale of 0-100. HA uses a scale of 0-255. I was trying to write a template to scale the dimmer. I did try pct attribute which doesn’t work because it will still convert it to 0-255. I have been working on this for a week.

#

Sorry hope that makes sense

dreamy sinew
#

I don't think it is possible. What integration are you using?

hollow rampart
#

Universal devices isy994

dreamy sinew
#

This is not something that could be handled with a template. It'll be at the integration level

hollow rampart
#

I did see couple templates I tried but the entities keep fighting themselves.

#

Ok

#

Thank you

copper blaze
#

Is it possible to add custom attribute to an entity (climate) and set it to its state ?

stone lintel
#

Is there a way to pull the hvac_action state from a thermostat into a template sensor? I can pull the state of the thermostat itself through but want to pull the hvac_action state which is either idle or eco..

bitter atlas
#

@stone lintel if hvac_action is an attribute of an entity you can call it's state with state_attr('whatever-the-main-entity', 'hvac_action')

stone lintel
#

Amazing, thanks!

mighty ledge
#

@copper blaze you'd break the entire functionality of climate devices if you did that. Best to make a template sensor to display the altered info that you want to display.

torn plinth
#

It complains it wants a float for the temperature

mighty ledge
#
temperature: >
  [[[ return states['climate.bathroom'].attributes.temperature + 0.5; ]]]
#

also, as an fyi... even if it did support jinja templates, you would have needed to wrap your whole template in quotes or use the multiline template indicator (> or | ).

torn plinth
#

Ahh, okay. I'll try this, thanks!

#

Works like a charm!

rain cove
#

Where can I find info about advanced templates? I have two entities, a date and a number, and want to get the average energy per day. (The date is the start date of the total energy draw)

silent barnBOT
inner mesa
rain cove
#

Im using tasmota and in the JSON in my MQTT topic it stores total energy and total energy since, so all HA needs to do is do total power / days since <json date>

inner mesa
#

I'm useless with any date calculations

rain cove
#

Thanks, I'll see what I can do, I may come back if I get stuck though 😉

inner mesa
#

you can usually find solutions on the forum for stuff like this

rain cove
#

yea, I did a quick search but wasn't sure what keywords to find what I was looking for

rain cove
#

So this is what I have put together so far:

# SONOFF 01 - Average daily power
  - platform: template
    sensors:
      sonoff01_average_daily:
        value_template: '{{ sensors.sonoff01_total / (as_timestamp(now()) - as_timestamp(sensors.sonoff01_total_since) ) | timestamp_custom("%j")| int }}'
        entity_id: sun.sun
        unit_of_measurement: 'kWh'```

But unfortunately the state is just "unavailable" and I don't know how to tell whats wrong or what to check.
#

For info sensors.sonoff01_total is the number of kWh and sensors.sonoff01_total_since is a timestamp

inner mesa
#

sensors.sonoff_xxx is incorrect

rain cove
#

Ah

#

Let me try that, thank you

inner mesa
#

Test in devtools > Templates

rain cove
#

Ah this page is super helpful

#

Ty

marsh thunder
#

Morning all, bit of a noob with templating but I seem to be bumbling my way through it.
Could someone explain to me what int and float are. I use them but don’t quite understand them

dreamy sinew
#

int == Integer. Whole numbers.
float == floating point number. Decimal number

marsh thunder
#

Ah ok thanks 🙂

rain cove
#

Do templates auto update when the values referenced change? ie I do not need to add sun.sun to my entity_id list?

inner mesa
#

If it can identify the entities, yes

#

The entity list is also deprecated

#

Most of the time it will work fine

rain cove
#

On the template page it says it listens for state changed events for my two entities

inner mesa
#

Good

rain cove
#

Also, I got it to work temporarily, but now it keeps saying unknown even though the template works in the dev page

#

any logs or something I can check?

inner mesa
#

Temporarily?

rain cove
#

Wait now its working again... I didnt change anything except restart HA

#

Hmmm, I am wondering if it is only updating when the state changes and on startup it has a null state

inner mesa
#

Could be

rain cove
#

So I need to update this sensor template once a day, as it depends on days since another value. I am using now() for that. What would be the way to get it to update once a day if entity_id is deprecated?

rain cove
#

Thanks, wish they added a better way to do this when removing the old way :/

inner mesa
#

You really shouldn’t need to do anything

rain cove
#

The problem is I have two values, one never changes (unless I reset it) and the other only changes when power is used. If I don't use any power the value doesn't change but the average daily power draw should be going down (since we are getting further away from the permanent date)

inner mesa
#

Adding a line to your template is pretty much equivalent to another entity_id: line, right?

#

Adding sun.sun isn’t ideal, either

rain cove
#

Maybe what would be best is using an entity instead of now() that updates once a day?

#

not sure how I would do that though

inner mesa
#

Seems like sensor.date does that

rain cove
#

Yup, but I do not have that unfortunately. (at least according to the developer tools states page)

#

I think I have to create a template for that too

inner mesa
#

Then add it

rain cove
#

But then wont we have the same issue? It wont update automatically using now()

inner mesa
rain cove
#

Oh!

inner mesa
#

The updates will be based on sensor.date, which is what you want

rain cove
#

This is what I was missing, thank you

coarse tiger
#

when I make a loop like {% for device in states.device_tracker %} - how do I get the device's mac address?

#

I was able to do that with the luci device tracker but not anymore with the nmap dev tracker :/
the MAC addresses get saved in known_devices though

coarse tiger
#

nvm, I made my template shenanigans work with the devices ip

torn meteor
#

is it possible to add a template attribute to an existing hue light/group?

#

i'd like having a current_scene or last_scene on the light group

dreamy sinew
#

You can't add stuff to existing entities with templates

torn meteor
#

ok. i guess i can make a helper of some kind per hue light group that, when the script activates a scene by name, also save that name to that helper

dreamy sinew
#

Yep, that can be done

torn meteor
#

template_attributes may be efficient for that - have an sub-attribute for each light group. avoids having a ton of custom helpers

blazing burrow
#

why doesn't this work? url: 192.168.1.253:8123{{ state_attr('media_player.hedwig_2', 'entity_picture') }}

dreamy sinew
#

Does it work in template tester?

blazing burrow
#

yep

dreamy sinew
#

Well, that's not an actual url

#

So that's probably the problem

blazing burrow
#

needs http://

dreamy sinew
#

Yup

blazing burrow
#

hmm, seems to not fill reliably anyways

#

not too big of a deal

#

how about this: i want to have a switch turn on for a total of 12hr, with equal time before sunrise and after sunset

dreamy sinew
#

if you can figure out a way to determine that, you can plug it in to a template

topaz walrus
#

@buoyant pine getting to this late, sorry been traveling for work. Thanks for you help! I saw the automation and understand it now. I do forget, what change to the template you told me to make.

buoyant pine
#

@topaz walrus no prob, what I provided will replace the template entirely

#

You can display the input text in your frontend instead

slow vine
#

how can I get the date from the timestamp of a sensor and make it one day later in a template?

dreamy sinew
#

is it a timestamp as in the seconds from epoch or a date-time string?

slow vine
#

timestamp

#

1601162500 for example.

#

I can use timestamp_custom('%Y-%m-%d') to convert it to a datetime I guess. But I'm still lost.

dreamy sinew
#

yeah, trying to work something out but not having luck atm

#

there's a timedelta global but it doesn't seem to be working

blazing burrow
#

@dreamy sinew ok I figured out the template, and can get my desired offset, but don't think I can use a sensor value as sun offset in a trigger

tiny sphinx
#

hope this is the right section. how do i change clock to 24hr instead of 12hr?

blazing burrow
#

0{{ timedelta(0, (12*60*60) - (as_timestamp(state_attr('sun.sun', 'next_setting')) - as_timestamp(state_attr('sun.sun', 'next_rising')))) }}

inner mesa
#

is this what you're looking for?

#
automation:
  trigger:
    platform: sun
    # Possible values: sunset, sunrise
    event: sunset
    # Optional time offset. This example will trigger 45 minutes before sunset.
    offset: "-00:45:00"
blazing burrow
#

I put the leading 0 because I couldn't figure out how to get timedelta to format into a HH:MM:SS

#

yeah, can I use a template there?

inner mesa
#

for the offset?

blazing burrow
#

yeah

inner mesa
#

I thought you wanted like 6 hours before?

blazing burrow
#

how about this: i want to have a switch turn on for a total of 12hr, with equal time before sunrise and after sunset
@blazing burrow ^

#

currently calculated to be about 35min, but as the year goes on, it'll be longer and longer

inner mesa
#

based on light level or something? simply have a fixed offset before sunrise and after sunset is trivial

#

oh, I see what you're doiung

#

nevermind

blazing burrow
#

👍

inner mesa
#

it's a weird requirement 🙂

blazing burrow
#

yep lol

inner mesa
#

like an interview question or something

blazing burrow
#

lmao

inner mesa
#

or homework problem 🙂

blazing burrow
#

it baffles me that templates don't just work anywhere

#

I mean I get it

#

but I keep expecting them to and then not lol

inner mesa
#

they work in a lot more places now than they did a couple of releases ago

blazing burrow
#

understandable

inner mesa
#

and, #hacktoberfest

blazing burrow
#

👍👍

#

I've considered a couple things, but don't really feel I'm at "contributor" level yet in terms of HA

#

I do quite a bit of kodi stuff, but hacktoberfest guidelines this year changed up so it's only marked repos?

#

or something

thorny snow
#

After doing research for some days: Is there really no way to re-use template snippets / codes (e.g. similar to a macro) for multiple sensors, with only slight differences in between those (e.g. the name of the sensor). In my case I have a long value_template expression that is 99% equal across 20 or so sensors, only the name of the "upstream" sensor changes between all of those ...

wraith monolith
#

Hey guys, any way to use data_template: when using Developer Tools > States or Services?
Seems like the YAML part forces the use of data: making it impossible to test templates

buoyant pine
#

no, but theoretically templates should work there in 0.115 or newer since data_template: is no longer required

wraith monolith
#

Aha I didn't know that! Thanks

#

Hmm cant seem to get it to work:
brightness_pct: '{{100}}'
gives:
expected float for dictionary value @ data['brightness_pct']

buoyant pine
#

are you on 0.115 or newer? if so, looks like that field still doesn't accept templates

#

i'll have to try that out when i get home

wraith monolith
#

im on 0.115.6

buoyant pine
#

yeah, guess it doesn't accept templates, or at the very least it doesn't convert the template output (which is a string) to a float

wraith monolith
#

Hmm guess I have to find another way, thanks for the help!

slow vine
#

Can I make the date of a timestamp one day later in a template?

woven magnet
slow vine
#

{{ as_timestamp(now()) | timestamp_local }} works but if i try to add time to that but it doesn't.

#

I looked there but it doesn't say anything about what I am doing.

woven magnet
#

okay, doing it that way, you some some brackets… {{ (as_timestamp(now()) + 3600) | timestamp_local }}

#

| is a jinja operator, and is way up in precedence…

#

The alternative would be {{ now() + timedelta(…) }} something, but I assume timedelta was added very recently, because I don't appear to have it.

slow vine
#

ok that worked thanks.

dreamy sinew
#

timedelta was added in 0.115

slow vine
#

I can get it working in a template but I am having trouble using it in a service call to set an input_datetime object.

#

I get an error that could not parse date.

white ruin
#

~~Anyone mind looking at a template sensor for me? This used to work but when I migrated to a new Pi it has stopped. I validated the template itself in the template editor and it spits out a valid number so not sure why it isn't working in the sensor. I just get an Unknown state with nothing in the logs: https://paste.ubuntu.com/p/nyPp2Dj9KG/~~ Well it just started working again after a couple weeks of not working so 🤷‍♂️

teal cove
#

Using the template sensor, previously one could just use entity_id: [] to have the sensor NOT update automatically. How could I achieve this past version 0.114?

For context: I have two 'sensors' whose data I only push via HTTP, and because of that their states are purged upon a HA restart. I work around this by defining these sensors as template sensors and pull data from a dummy variable on an ESPHome device. This worked fine until 0.115, but now, as soon as a mentioned entity changes (e.g. the aforementioned ESPHome device loses WiFi) the values are reset. Any ideas on how to fix this? :)

dreamy sinew
#

Should probably just use input_* entities instead

blazing burrow
#

i feel like i had this right last night, but isn't working anymore 🤔

#

always get invalid url for dictionary value @ data['url'] from my service call

dreamy sinew
#

.share the full thing please

silent barnBOT
dreamy sinew
#

also images of text are rage inducing

blazing burrow
#

sure

#

{{ 'http://192.168.1.253:8123' + state_attr('media_player.hedwig_android_tv', 'entity_picture') }}

#

that's my template

#

http://192.168.1.253:8123/api/media_player_proxy/media_player.hedwig_android_tv?token=7febba290e2a771f41b0af9cb332abf278488152f2d5ee5334bbceb26321082a&cache=1602124321.277953

#

and what i get from it

dreamy sinew
#

and where are you using it?

blazing burrow
#

but for the moment i'm just testing it in a service call

dreamy sinew
#

how are you testing the service call?

blazing burrow
#

in the gui

#

umm, trying to come up with the right yaml for it

dreamy sinew
#

gui does not support templates in the dev-tools > services

blazing burrow
#

aha!

#

ok

#

lemme try in an automation

dreamy sinew
#

well, it definitely didn't prior to 115. it might now. ¯_(ツ)_/¯

blazing burrow
#

yeah, still getting that error from my automation

#
service: color_recognizer.turn_light_to_recognized_color
data:
  entity_id: light.lr_bottom
  url: '{{ states(''sensor.spotify_android_tv'') }}'
entity_id: light.lr_bottom
dreamy sinew
#

that's not what you were using earlier, what is the output of that sensor?

blazing burrow
#

ohh, it's that:

sensor:
  - platform: template
    sensors:
      spotify_entity_picture:
        value_template: "{{ 'http://192.168.1.253:8123' + state_attr('media_player.hedwig_android_tv', 'entity_picture') }}"
        friendly_name: Spotify Entity Picture
#

lemme use the template directly

#

ohh i made it further

#

now got an error from my script 😅

wispy compass
#
test_tts:
  alias: TEST TTS
  sequence:
  - service: tts.google_say
    data:
      entity_id: media_player.alla
      language: sv
      message: "Prisen för elen är just nu {{states('sensor.sensor.electricity_price_angshestre_120')}}."
      cache: false

I'm getting unknown for the state, where am I wrong in this code? 🤔

deft timber
#

Why do you have 2 times sensor ?

#

i should be {{states('sensor.electricity_price_angshestre_120')}}

wispy compass
#

@deft timber Thanks, don't know how I missed that one...

bronze horizon
#

I've got influxdb reporting my system uptime to HA in seconds like "35843" but I'm having trouble working out how to get it into relative_time format. I've tried passing something like as_timestamp(now()) - (states('sensor.influxdb_docker_nuc_uptime') | int ) to relative_time but haven't got anything to work :/

bitter atlas
warm isle
#

@white ruin I guess one of your sensors reported "unknown" wich then is not a number - but thats only a wild guess

acoustic wedge
#

Hi, I have a question regarding a history_stats sensor. I'd like that sensor to store the value my heater has been on since september 1st. For that, I used the following conf:

- platform: history_stats
  name: Heater ON
  entity_id: switch.heater
  state: 'on'
  type: time
  start: '{{ as_timestamp(strptime("01.09.2020", "%d.%m.%Y")) }}'
  end: '{{ now() }}'

The value of the sensor is less than 6 hours while I know it has been on more than that. Is there anything wrong in my template? Thanks.

deft timber
#

How many days do you keep in the DB ?

#

Configured in the recorder integration

#

By default it is 10 days

acoustic wedge
#

I did not configure the recorder so I assume it's set to 10. My history shows data only since september 30th (9 days then). However, within these 9 days, the heater has been on once during more than 8 hours. So the value should be greater than that.

deft timber
#

If you try with start: '{{0}}' that will look in the whole history, the value seems correct?

silent barnBOT
lapis quarry
#

Guess ill try that again..

Hey guys, not sure where to post this if here or in automations. I'm writing this automation where I'm trying to add a condition using a template but I cant seem to get it to work. Its the template in the condition I'm struggling with.

What I want to achieve is I have a set of input booleans that I would like to use as conditions and would like to use a template to choose the right boolean based on what entity triggered the automation.

jagged obsidian
#

you'll be better off using choose: in actions and define action depending on the trigger type

lapis quarry
#

the action portion works fine

#

Its the condition template im struggling with: Im trying to carry the name from the trigger to the condition and it doesnt seem to work, it doest trow any errors in the logs but does not trigger..

#

the triggers are called device_tracker.keyring0xx and the booleans I want to evaluate are called input_boolean.enable_keyring0xx

Trying to use replace to change the name in the condition but not sure if that is right

acoustic wedge
#

If you try with start: '{{0}}' that will look in the whole history, the value seems correct?
@deft timber I started with that and I got exactly the same value. While I'm at it, is there a way to reload sensors without restarting? I don't think so but I ask just in case.

marble jackal
#

the triggers are called device_tracker.keyring0xx and the booleans I want to evaluate are called input_boolean.enable_keyring0xx

Trying to use replace to change the name in the condition but not sure if that is right
@lapis quarry you need to remove the quotes around name. Now you are checking if the string 'name' is on. You want to check for the variable name

#
          {%- set name = trigger.to_state.entity_id | replace("device_tracker.", "input_boolean.enable_") -%}
          {{ is_state(name, 'on') }}```
lapis quarry
#

let me try

#

yes!! 😄

#

Amazing, thanks TheFes!

marble jackal
#

No problem!

#

Nice solution though, wouldn't have thought of this myself

lapis quarry
#

Thanks 😊

lime rose
#

I'm struggling to get a value_template configuration for an auto-discovered MQTT sensor (Tasmota based) working correctly. I'd like to avoid using a template sensor if at all possible. From the docs I see that MQTT sensors should be able to be configured with a value_template property which should be able to transform incoming values before representing them in HA. The sensor is a sonar distance sensor which measures a liquid ullage in mm, but I would like to see immediately the liquid level. I know the height of the tank is 1350mm, so I thought this should work:

value_template: '{{1350 - value}}'

Since the sensor is auto-discovered I tried overriding this property in the 'Configuration > Customizations' page in HA. Any help would be much appreciated

jagged obsidian
#

if its autodiscovered you cannot change that

dreamy sinew
#

you can't do stuff like that in customize

lime rose
#

😦 too bad, I really liked the auto discover feature 🙂

jagged obsidian
#

either make a template sensor or manual config

#

ooor manual discovery 😁

lime rose
#

Think I'll go with the template sensor then, Tasmota adds a bunch of useful stuff which I don't all want to have to configure manually

#

Thanks for the quick help!

jagged obsidian
#

you just configure an additional sensor manually, you can leave discovery on

lime rose
#

hmm, right

jagged obsidian
#

its same but different from a template sensor

#

if you want to go deep you can use the discovery message from the current distance sensor to craft a new discovery message for water level and send it from Tasmota using a rule triggered on boot so the water level sensor would appear under the same Device as a new entity

deft timber
#

@acoustic wedge If with 0 it gives the same result then I have no idea. Sorry. You can only refresh some sensor w/o restart, depending on their type. I think you only can for mqtt & rest sensor.

acoustic wedge
#

Thanks

lapis quarry
#

Hey guys, one question: I´m just wondering if HA will allow to use a For loop to populate a list or entity_id in the trigger section of an automation?

#
    trigger:
      platform: state
      entity_id: 
        - input_boolean.enable_keyring01a
        - input_boolean.enable_keyring01b
        - input_boolean.enable_keyring02a
        - input_boolean.enable_keyring02b
        - input_boolean.enable_keyring03a
        - input_boolean.enable_keyring03b
#

I mean replace the above by this:

#
{% for boolean in states.input_boolean if 'enable_keyring' in boolean.entity_id %}
- {{ boolean.entity_id }} {%- if not loop.last %} {%- endif %}
{%- endfor %}
#

I tried this loop in the developer tools and it that returns the same list of entity ids..

#

Can this be done?

thorny snow
#

having hard time, i want something to happen when alarm goes on at android phone ( or like 30mins before). value_template: "{{states('sensor.date_time_utc') == (states.sensor.oneplus_a5000_next_alarm)| timestamp_custom('%Y-%m-%d, %H:%M') }}"

#

cant make the timestamp match?

deft timber
#

@lapis quarry don't think you can do that...

wanton osprey
#

Some expert hint/tip on the following problem would be nice. I run multiple Bluetooth temperature sensors. Usually, the data of an individual sensor is collected by a particular (I have assigned the one that is typically closest to the sensor) Bluetooth2WIFi bridge, converted to MQTT, and then processed by Home Assistant which works fine. However, since I use in total 5x Bluetooth2WIFi bridges, it would be nice to exploit some redundancy. The temperature data broadcasted by an individual sensor is often received by more then one bridge. So it would be nice to collect the temperature data into a single value that is then further processed by HA, e.g., the temperature data received by bridge 1 is used until another (for example the one received by bridge 2) overwrites it and so on. Can this be achieved by a template sensor?

#

Previously I have tried to achieve this behavior by letting all bridges report to the same MQTT topic. Although this works in terms of the data collection of the temperature values, it seems to cause problems with the broker.

lapis quarry
#

@lapis quarry don't think you can do that...
@deft timber that is a shame, it would be convenient to be able to use templates there 😦

deft timber
#

@lapis quarry sure but you could use a template trigger instead. And in the template you could test all you entities

rain cove
#

Can anyone point me in the direction to figure out a template that is showing as unknown on my dashboard but works in the developer tools template page?

coarse tiger
#

Can anyone point me in the direction to figure out a template that is showing as unknown on my dashboard but works in the developer tools template page?
@rain cove show us the shy template thingie

rain cove
#
{{ ((states("sensor.sonoff01_total") | float) / (as_timestamp(states("sensor.date")) - as_timestamp(states("sensor.sonoff01_total_since")) ) | timestamp_custom("%j")|int ) | round(3) }}```

`sensor.sonoff01_total` float value (total kWh since below datetime)
`sensor.sonoff01_total_since` datetime
#

The goal of the template is to get the average daily kWh, so its total kWh / days since

silent barnBOT
coarse tiger
#

either ypu can use that or maybe try different parts of your template without the operations one by one in lovelace to figure out where it fails,
I don't see any wrong from here :/

rain cove
#

Darn. I guess I could look into having HA calculate it, thought it would be better considering the device basically already does it

#

One thing which I really hope isn't the issue but maybe it would be obvious to others is on startup, the values aren't populated so it tries to do timestamp - null and I get a type error. But wouldnt it try again once sensor.date updates?

#

TypeError: unsupported operand type(s) for -: 'float' and 'NoneType'

#

(I am only assuming this error message is from my template, not actually sure)

coarse tiger
#

one way to workround the undefined sensor state would be to use the statistics sensor in between I discovered

rain cove
#

yea, I am figuring it out now

#

Got it working using statistics 😄 Thank you!

dry matrix
#

Hi all...so I'm trying to wrap my head around how to create an automation that compares the outside temp (sensor.dark_sky_temperature) with the inside temp of my house (sensor.hue_motion_sensor_1_temperature) , and then notify me to open the windows if the temp outside is lower than inside.

I know I need a logic comparison template between those two sensors, but I'm struggling how to correctly form the template and trying to figure out where I should put it in that automation (e.g. do I call a separate script to do the comparison as a trigger, put the template right in the automation as a trigger, etc).

Thanks for the help!

coarse tiger
#

@dry matrix

buoyant pine
#
trigger:
- platform: template
  value_template: "{{ states('sensor.dark_sky_temperature') | float < states('sensor.hue_motion_sensor_1_temperature') | float }}"
coarse tiger
#

goddamn teddy let him some tasks on his own 😄

dry matrix
#

Ok great! I understand better now. Thanks @buoyant pine !

topaz walrus
#

@buoyant pine finally getting a chance to really look at what you sent me. Do you mind explaining it to me a little so I can build one of my own next time and don't have to ask for help? First 3/4 of the automation is pretty straight forward. My question is on the action itself.

  - service: input_text.set_value
    data_template:
      entity_id: input_text.last_motion
      value: "{{ trigger.to_state.friendly_name }}"

What is that actually doing?

dreamy sinew
#

It's dropping in the friendly name of whatever triggered the automation into the value of that input text entity

buoyant pine
#

Also I meant "{{ trigger.to_state.name }}" 😅

topaz walrus
#

so

#

what is the "input text entity"

#

and where is it dropping the friendly name

#

sorry trying not to be a pain in the ass

#

but would love to wrap my head around it so i can learn lol

#

i understand what a "template" is doing because your making sensor per say and that sensor "senses" changes in whatever you point at it. Changing it into a automation i dont understand whats thats doing exactly and how you could see that later on the frontend

buoyant pine
#

I explained that earlier--create an input_text and display that in your frontend instead of the template sensor

silent barnBOT
buoyant pine
#

This automation updates the input text with the name of the last motion sensor that detected motion @topaz walrus

topaz walrus
#

sorry i guess thats what i didnt understand

#

never done an input text

#

ahhh

#

lightbulb moment***

#

so all the automation is doing is taking the name of the last motion detector triggered, and pointing it at a "input text card or whatever" thats listening

buoyant pine
#

It's writing the friendly name of the last motion sensor that was triggered to an input_text entity

topaz walrus
#

yeah figured it out

#

mind blown

#

didnt know that was even a thing lol

#

thanks so much for you help

hollow rampart
#

Hello. I have a light template that if off, turns my lamp on moving slider 0-100%. I can also move the slider to 0% and the lamp turns off. The part I need help with is if the lamp is on I can not turn the lamp off using the template card toggle switch. When I try to turn it off, it turns back on. Any ideas?

upper sky
#

I have a LED strip that activates when you enter a url (for example http://x.x.x.x/set?color=FF0000 )
I'm trying to figure out how to use the light template to set color. Any help?

lapis quarry
#

@lapis quarry sure but you could use a template trigger instead. And in the template you could test all you entities
@deft timber How would a template trigger be written to include a For loop like the one I posted?

What I´m trying to achieve is being able to add or delete sensors that follow a certain naming convention and make it transparent to the automation, so I dont need to modify the code on every automation every time I add a sensor..

Is this possible somehow?

deft timber
#

depends on the test you want to execute on the different entities values. If for instance you want to trigger your automation as soon as one of your sensor becomes true, you can do this:
automation: trigger: platform: template value_template: >- {%- set ns = namespace(ret=false) -%} {%- for boolean in states.input_boolean if 'enable_keyring' in boolean.entity_id -%} {%- if boolean -%} {%- set ns.ret = true -%} {%- endif -%} {%- endfor -%} {{ ns.ret }}

lapis quarry
#

Interesting..

#

let me try this out see if I can get it to work

#

I have several instances where I would like to use it, one instance needs to trigger on every state change no matter the value, how would you write that?

#

specificaly its a timer: timer.keyring01a

deft timber
#

Normally, the template is re-evaluated each time an entity in the template changes. So maybe simply by doing:
{%- for boolean in states.input_boolean if 'enable_keyring' in boolean.entity_id -%} {%- endfor -%} {{true}}
it will work ?!?

lapis quarry
#

will try both and get back with the results

#

👍

#

actually forget that, it does work (My automation as initial state off so I need to re-enable it every time I reload automations)

#

it does work, amazing!! You just made my day, this is awesome 🥰

deft timber
#

Wonderful

lapis quarry
#

thanks very much, this is really usefull 😄

#

Actually I just noticed it has a weird problem.. 🤔

#

It works for 1 time only

#

Im reloading the automations, then I change the timer state to test and it triggers the first time, but then it will not trigger again when I change the timer state a second time...

deft timber
#

Hmmm... I guess the empty for did not do the trick afterall....

#

I don't know how HA determines which entity to watch when analyzing a template

lapis quarry
#

any other suggestions?

#

I guess i could use a if in the for loop

#

I want it to trigger on 2 states

#

active and idle

#

that might do the trick

#

dont know how to write it, trying to modify your first example but dont really know how this for loop works or what the namespace is

#

trying this:

deft timber
#

the namespace is needed to manage global variable.Ootherwise the variable set in the loop are not global

#

Replace trigger.to_state.state with timer.state

lapis quarry
#

Replace trigger.to_state.state with timer.state
@deft timber ok, that worked, but i get the same result as the empty for loop, it triggers one time only on the first state change...

deft timber
#

Gasp...

lapis quarry
#

Why would it do that, makes no sense 🤔

deft timber
#

I guess it is maybe because the first time it is triggered the template becomes true, and when something change again, the template is still true -> so no change -> no trigger

#

just a guess

lapis quarry
#

is this related to the namespace?

deft timber
#

no

#

it's because the automation is executed when the trigger becomes true, not just because it returns true

#

once again, just a guess

#

Indeed : Being a boolean expression the template must evaluate to false (or anything other than true) before the trigger will fire again

lapis quarry
#

I see

#

just thinking if there is a way force the template to render false once it triggers

#

any ideas?

deft timber
#

another idea. You create a template sensor, that will contain the number of timer matching your requirements (active or idle), and then you create a automation with a state trigger on this sensor, without giving from or to state (which will then be triggered at each change of the sensor)

lapis quarry
#

Not sure if that can work? because I´m carrying the entity id of the trigger to the conditions and actions portion of the automation, maybe can be done but not sure how

deft timber
#

you could store the entityId in an attribute of the sensor

#

but i agree, it becomes tricky 🙂

#

not sure if you can get that info in the sensor definition though

#

or you can also get, in your automation, the entity that changed in last, using last_changed

lapis quarry
#

yes that might work also

#

sounds a bit complicated but maybe its just that I cant fully wrap my head around how the sensor_template would work

#

so basically it would be a for loop as you just described to list all timers but placed inside a template_sensor?

#

🤔

deft timber
#

yep

#

you just need to make a sensor value that will change everytime one of the entity change (the number of entity with a give status, the sum of their last_changed, ...)

coarse tiger
#
835``` is that all entities?
bitter atlas
#

everything listed in the States page

brisk nebula
#

Hello everyone, is there a way to extract time of latest mqtt message in a subject? The last_updated doesn't work.

#

There are messages with certain topic sent every second. I've set up a mqtt sensor that listens to the topic. The sensor works fine, but the last_updated value doesn't change.

lapis quarry
#

you just need to make a sensor value that will change everytime one of the entity change (the number of entity with a give status, the sum of their last_changed, ...)
@deft timber

Been playing around in the template editor to see how it can be done, came up with this:

#
       {% for state in states
           if ( 'keyring' in state.entity_id and state.domain in ['timer'] and state.state == 'active' ) -%}
         {%- if loop.last -%}
           {{ loop.index }}
         {%- endif %}
       {%- endfor %}
#

seems to work in the template editor in counting the right timers that are active, but when i make a sensor using this its giving me a strange result:

deft timber
#

here your sensor will contain the index of the last active timer. I don't think it is what you want to do

lapis quarry
#

how would you do it?

deft timber
#

I would do something like
{% for state in states if ( 'keyring' in state.entity_id and state.domain in ['timer'] and state.state == 'active' ) -%} {{ loop.index }}# {%- endfor %}

#

it will create a string with the indexes of all the active timer

lapis quarry
#

ok, both seem to work now

#

lets see if i can get the automation sorted as you sugested

lapis quarry
#

or you can also get, in your automation, the entity that changed in last, using last_changed
@deft timber

Been researching how to do this, from what I gather last_changed gives you the time a entity changed last but cant see how to display what entity was last changed in a domain (which is what I understand you are sugesting)

Do you have any pointers regarding this?

deft timber
mighty ledge
#

@lapis quarry what are you trying to do?

#

count the number of active timers?

#

I don't need a huge explanation, just a simple overview

lapis quarry
#

end goal is trying to autopopulate a list of entities in the trigger section of an automation

#

best would be you read the last few posts you can she the "hack" im trying

#

now trying to write a template that will output the entity_id that last changed from a certain domain

mighty ledge
#

are you just trying to remove the list of entity_id's?

lapis quarry
#

i have a list of sensors in the timer domain, i want a template that outputs the id of the last one that changed in that domain

#

basicaly following slashback sugestion as a hack to achieve the results I want:
Have automations that auto-populate the list of trigger entity_ids when I add or detele sensors that will follow a certain naming convention

mighty ledge
#

Yes but based on the most recent template changes, you'll only get an update every minute

#

at best

lapis quarry
#

ok, I noticed the frontend was not updating was wondering why

#

the template editor was updating inmediatly so i assumed it might work

mighty ledge
#

if you want it to update based on any change inside that group, make a group and then a template that uses the group. But I'm still not sure why you need a template for getting the 'last updated'

#

your current state trigger does that

lapis quarry
mighty ledge
#

Yes I saw that

#

but I'm not sure what the problem is with your first automation.

lapis quarry
#

which one

mighty ledge
#

the one with this list:

#
  • timer.keyring01a
    - timer.keyring01b
    - timer.keyring02a
    - timer.keyring02b
    - timer.keyring03a
    - timer.keyring03b
lapis quarry
#

none, it works fine

mighty ledge
#

ok, so why are you trying to change it to the template trigger?

lapis quarry
#

I would like that list to autopopulate when I add or delete timers

brisk temple
#

i have a case use for that as well

lapis quarry
#

so i dont need to modify the automation every time

mighty ledge
#

Ok, so this leads to the other problem I said: Templates in 0.116+ only update once a minute when you use a states or states.domain in your template.