#templates-archived

1 messages ยท Page 118 of 1

shell ferry
#

looks much better :) gonna write that down somewhere

#

would mqtt sensors work any better? if the sensors had retain flag enabled?

dreamy sinew
#

i'm not sure, i haven't messed with those

#

maybe? ยฏ_(ใƒ„)_/ยฏ

shell ferry
#

well, thanks for your input anyway :) gonna play around later

#

hmm, could I create an if there? to check that all the 5 sensors have data, unless return the value of another sensor?

dreamy sinew
#

you could

#

would that other value be populated?

#

it can get a lot messier though

#
{{ [
  states('sensor.sensor_1') if states('sensor.sensor_1')|float else states('sensor.sensor_2'),
  states('sensor.sensor_3')...
]|map('float')|sum|round(2) }}```
#

or are you wanting to default the whole thing if any of them are missing?

#
{%- set values = [
    states('sensor.shelly_makuuhuone_total_consumption'),
    states('sensor.shelly_norttinurkkaus_total_consumption'),
    states('sensor.shelly_nuutin_huone_total_consumption'),
    states('sensor.shelly_tv_taso_total_consumption'),
    states('sensor.shelly_tv_taso_viihde_total_consumption')
  ]|map('float') -%}
{{ states('sensor.other_sensor') if 0 in values else values|sum|round(2) }}
ruby tiger
#

I have the following mqtt light defined in configuration.yaml

  - platform: mqtt
    schema: template
    command_topic: 'insteon/command/modem'
    state_topic: 'scenestate/movielighting'
    command_on_template: '{ "cmd" : "scene", "name" : "movielighting", "is_on" : 1 }'
    command_off_template: '{ "cmd" : "scene", "name" : "movielighting", "is_on" : 0 }'
    optimistic: true
    state_template: 'value.upper()'
    unique_id: 'movielights'
    name: 'Movie Lights'

I'm totally guessing on that state_topic and state_template. I want to be able to send mqtt messages so that HASS will update the state of the device. I thought I could send a MQTT message to topic scenestate/movielighting with a payload of "ON" or "OFF" and that would make HASS think the scene state was ON or OFF accordingly. But when I do that, all I get is an error message:
WARNING (MainThread) [homeassistant.components.mqtt.light.schema_template] Invalid state value received

How can I send a message to make HASS think this device is ON or OFF?

#

Oh, and that optimistic: true, I have no idea about that. I saw it in the docs and thought I'd try it.

dreamy sinew
#

none of your template values are correct

ruby tiger
#

That doesn't surprise me! I'm just starting out and I saw some of this online. The command_on_template and command_off_template seem to be working. I can send messages to turn it on and off. But I want to be able to update the state independently of activating the light.

deft timber
#

state_template should be a template. (in {{}} / {% %}}

#

@ruby tiger ๐Ÿ‘†

upper mulch
#

Hello! I have seen templates beginning with > and >-. What is the difference? I haven't found it in HA documentation.

thin vine
#

> is used for multiline templates, - is used to remove line-breaks also inside templates eg: {%- something -%} if you have a short oneliner, just surround it with "" on the same line and don't use the >

glossy viper
#

morning.... some help insert complicated formula in tmeplate?

deft timber
#

Is it not just that?

{% set a = 17.62 %}
{% set b = 243.12 %}
{% set alpha =  log(hIndex/100) + a*temp/(b+temp) %}
{% set ts = b * alpha / (a - alpha) %}
{{ts}}

?

glossy viper
#

ah...lo instead of ln ๐Ÿ™‚

timber locust
#

Quick question: is it possible to use templates for scan_interval? Currently I have the config below, but HA complains about this line.

    scan_interval:
      minutes: "{% if is_state('device_tracker.blokmeisternas', 'home') %}1{% else %}1440{% endif %}"
thin vine
#

scan interval sounds like something in the configuration.yaml. templates there don't seem very usefull

deft timber
#

So I guess you can't ๐Ÿ™‚

timber locust
#

๐Ÿ˜ฆ

thin vine
#

as these are only read at reload to determin HA config

deft timber
#

What you could to is to put a very very high scan_interval so that you entity actually never refresh, and manage the refresh of the entity in an automation

timber locust
#

That's too bad. I'm monitoring my home server. But sometimes I turn it off for power saving. In that case, HA is throwing lots of errors for all command line (ssh) and rest sensors.

#

That might actually work.

deft timber
#

That's what I did for my solar panel, to not refresh the sensor when the sun is down

timber locust
#

Good idea guys! ๐Ÿ˜„

#

Or girls

deft timber
#

๐Ÿ™‚ from what I read, the higher scan_interval you can set is 315360000

timber locust
#

In minutes?

deft timber
#

which is about 10 years ๐Ÿ™‚

#

seconds

#

scan_interval: 315360000

thin vine
#

my name might confuse people... it's my gamertag, but I'm a guy ๐Ÿ˜‰

timber locust
#

Okay. I have written the automation. Let's see how that works! Thanks again for the suggestion!

glossy viper
#

end of the stream or a document separator is expected at line 7, column 8:
{% set a = 17.62 %}

#

and in dev-templates runs succesfully

thin vine
#

can you show the whole config, likely you forgot quotes "" or > for multiline?

glossy viper
#
  • platform: template
    sensors:
    real_feel:
    value_template: >
    {% set temp = states('sensor.temp_act') | float %}
    {% set humid = states('sensor.um_buc') | float %}
    {% set a = 17.62 %}
    {% set b = 243.12 %}
    {% set alpha = log(humid/100) + atemp/(b+temp) %}
    {% set ts = b * alpha / (a - alpha) %}
    {% set hIndex = -8.78469475556 + 1.61139411
    temp + 2.33854883889ts - 0.14611605tempts - 0.012308094temptemp - 0.0164248277778tsts + 0.002211732temptempts + 0.00072546temptsts - -0.000003582temptempts*ts %}
    {{ (hIndex) | round }}
#

Error loading /config/configuration.yaml: while scanning for the next token found character '\t' that cannot start any token in "/config/sensors/real_feel.yaml", line 7, column 1

#

oh....wierd...seems i have a tab space instead of space space

#

now it says ok

#

in front of line 7

thin vine
#

not sure if this is what you want:

          {% set humid = states('sensor.um_buc') | float %}
          {% set a = 17.62 %}
          {% set b = 243.12 %}
          {% set alpha =  log(humid/100) + a*temp/(b+temp) %}
          {% set ts = b * alpha / (a - alpha) %} 
          {% set hIndex = -8.78469475556 + 1.61139411*temp + 2.33854883889*ts - 0.14611605*temp*ts - 0.012308094*temp*temp - 0.0164248277778*ts*ts + 0.002211732*temp*temp*ts + 0.00072546*temp*ts*ts - -0.000003582*temp*temp*ts*ts %}
          {{ (hIndex) | round }}```
#

you seem to miss that you need to add * between variables to make them calculate. just writing 1.6temp does give warnings

glossy viper
#

guess is a copy/paste thing but looks like u wrote . thank you

deft timber
#

You had a tabulation instead of spaces somewhere

#

I guess

fossil hearth
#

hi how to get the days of the week ? like now(). to give as Wednesday for example..

#

just to print out the name of the day only

fossil hearth
mighty ledge
deft timber
#

Or {{now().strftime("%A")}}

mighty ledge
deft timber
#

oh ok, what kind?

mighty ledge
#

well, if you set your system up incorrectly or expect it to work on all datetimes, it won't work because the timezone may or may not be set

#

in normal python, i'd use the strftime, but you can't ensure a timezone in jinja because you can't create a timezone

#

it's best to always use the filter

dreamy sinew
#

use utcnow + strftime -> strptime with your timezone added

#

or they could just set up their system properly ๐Ÿ˜›

mighty ledge
dreamy sinew
#

oh i know, i'm just being an asshole

#

dealing with time shit sucks

thin vine
#

indeed

tardy patio
#

Hello, does anybody know how to extract one part of a mqtt topic to forward it to another topic, or make a sensor with one of the values? Let's say I have a topic where I can find the following string: (1.0, 20.0) . I want to send one of the 2 values to another topic, or make an mqtt sensor with one value.

dreamy sinew
#

is the one you want always in the same position?

tardy patio
#

I tried to make an automation with```

  • alias: OpenTherm Send
    trigger:
    • platform: mqtt
      topic: "HVAC/otresult"
      action:
    • service: mqtt.publish
      data:
      payload: "{{ trigger.data.split(',')[0] }}"
      topic: "opentherm-thermostat/setpoint-temperature/set10"
      retain: true
      qos: 0
#

the position is of interest, because the value changes

#

but yes, position is always the same,

#

so something ending in .split(',')[0] will be ok

#

I do not know what to write before this ๐Ÿ™‚

dreamy sinew
#

i wonder if the data is coming back as a tuple? i'm not sure if json supports that though

tardy patio
#

I am publishing the data

#

it is something like this: {% set result = (1.0,20.0) %} {{ result }}

#

and this (1.0, 20.0) can be found in the mqtt topic

#

i can see it in mqtt explorer

dreamy sinew
#

try trigger.data[0]

tardy patio
#

nope, nothing ๐Ÿ˜ฆ

lime grove
#

how do i add 2 state_attr together?

#

this just appends one to the end of the other

#

state_attr('switch.dehumidifier', 'total_energy_kwh') + state_attr('switch.washing_machine', 'total_energy_kwh')

ivory delta
#

Yes, adding two strings together does that.

#

You need to cast them to a number type first.

#

'1.0' + '2.0' = '1.02.0'
'1.0' | float + '2.0' | float = 3.0

dreamy sinew
#

yay string math

solar egret
#

hello guys, is it possible to combine two templates somehow? I'd like to control a fan via hassio, its all about calling curl (for which I found a template, called command_line) - also there is a template for fans - can I just merge them?

jagged obsidian
#

you can create template entities that use data from two or more existing entities

solar egret
#

thanks alot, will try that ๐Ÿ™‚

narrow topaz
#

{{states.media_player|map(attribute='entity_id')|list|random}} Now to download squeak sounds and drive my dog crazy ๐Ÿ˜

silent barnBOT
narrow topaz
#

something wrong with my templating?

#

nvm it just didn't like the media folder

fossil hearth
#

how to remove the initial 0 in a date by replace ? for example converting 01/18/2021 to 1/18/2021

or is there a way to avoid the 0 from the beginning in this formula ? timestamp_custom("%m/%d/%Y")

solved: .lstrip('0')

thin vine
#

possibly timestamp_custom("%-m/%d/%Y") would work too according to python time format documentation

tardy patio
#

Hello everyone and sorry to come back again with the same issue, but I am still trying to split the info on an mqtt topic. Maybe someone here did not see my request yesterday. I have this: (1.0, 20.0) coming in an mqtt topic. I want to either forward one of the values (they change, position remains the same), or make a sensor out of one of the values. ```

  • alias: OpenTherm Send
    trigger:
    • platform: mqtt
      topic: "HVAC/otresult"
      action:
    • service: mqtt.publish
      data:
      payload_template: {{ 'trigger.payload[0]' }}
      topic: "opentherm-thermostat/setpoint-temperature/set10"
tardy patio
#

Coming from a very nice guy, who makes me even more interested in learning c++, :```

  • alias: OpenTherm Send
    trigger:
    • platform: mqtt
      topic: "HVAC/otresult"
      action:
    • service: mqtt.publish
      data:
      payload_template: "{{ trigger.payload.split(',')[0][1:] }}"
      topic: "opentherm-thermostat/setpoint-temperature/set10"
      retain: false
      qos: 0
oak summit
#

How can I make a template output the number of days in the current month. So like right now it would output 31, but next month it would output 28.

I'm pretty sure I've done it before, but I can't find the docs to remember how to do it.

#

for context, I'm trying to make a template sensor with my estimated electric bill by effectively doing
( [bill so far] / [day in month] ) * [total days in month]

#

but I'm open to doing it other ways if there is another better way

ivory delta
#

{{ (now().replace(month = now().month % 12 +1, day = 1)-timedelta(days=1)).day }}

oak summit
#

thank you friend!

#

that doesn't look the same as I remember it from last time, but if it works it works ๐Ÿ˜›

ivory delta
glossy viper
#

statistics platform can be used for templating max value of a sensor for a day ?

ivory delta
#

No need for a template for it, it's just an integration.

glossy viper
#

well....i have 24 values (one each hour) and i want to now the max of them

#

then i want to store that value

ivory delta
#

Where do the values come from? Same sensor or different sensors?

glossy viper
#

same sensor

ivory delta
#

Then... no template ๐Ÿ˜‰

#

Just the statistics integration

silent barnBOT
ivory delta
green solstice
#

I'm trying to get the number of seconds remaining for an active timer. Is there a function for that specifically or do I need to compare "finishes_at" with the current time?

silent barnBOT
dreamy sinew
#

i can't tell from the docs. What are the attributes of the timer when its running?

green solstice
#

duration, editable, finishes_at, and remaining.

dreamy sinew
#

what's the value of remaining?

green solstice
#

It looks like it's deprecated in favor of using the finishes_at attribute

#

the value is the same as duration, doesn't appear to change

#

I thought I had an easy with with the "relative_time" method, but it only works with dates in the past

pliant viper
#

Is it possible to concat a !secret value with text in a template?

#

Trying to do something like this

#
  - service: notify.all_ios_devices
    data_template:
      message: 'A {{trigger.payload_json["after"]["label"]}} was detected.'
      data:
        image: '{{"!secret ha_url"}}/{{trigger.payload_json["after"]["id"]}}/thumbnail.jpg?format=android'
        tag: '{{trigger.payload_json["after"]["id"]}}'```
whole marsh
#

never tried it but i highly doubt that would work.

pliant viper
#

Well I can confirm it doesn't

whole marsh
#

makes sense, secrets are only read on boot/once. you're trying to call it after HA has started

pliant viper
#

Ended up just creating a template sensor first

#

that works

#

just more steps

deft timber
# pliant viper Ended up just creating a template sensor first

You can create a variable that you can use in your template

 - action:
     - variables:
         ha_url_var: !secret ha_url
     - service: notify.all_ios_devices
       data_template:
         message: 'A {{trigger.payload_json["after"]["label"]}} was detected.'
         data:
           image: '{{ha_url_var}}/{{trigger.payload_json["after"]["id"]}}/thumbnail.jpg?format=android'
           tag: '{{trigger.payload_json["after"]["id"]}}'
thin vine
#

ah, that's a nice new way to do this, before variables you had to use template sensors for that. I'll have to update some of my config too then ๐Ÿ™‚

dreamy sinew
#

Neat. I'll have to remember that

thin vine
#

hmm too bad that doesn't help here:

camera:
  - platform: generic
    name: iss
    still_image_url: 'https://maps.googleapis.com/maps/api/staticmap?key={{states("sensor.google_api_key")}}&center={{state_attr("sensor.iss", "latitude")}},{{state_attr("sensor.iss", "longitude")}}&zoom=6&size=600x300&maptype=hybrid&markers=color:blue%7Clabel:ISS%7C{{state_attr("sensor.iss", "latitude")}},{{state_attr("sensor.iss", "longitude")}}'
    limit_refetch_to_url_change: true
#

this is a secret: sensor.google_api_key but since this a configuration thing no way to use the variable there

#

I have to say even though it's configuration, it works very well to get maps of your appointments etc. or in this case the postition of the ISS space station ๐Ÿ™‚

half tiger
#

Hi all! I'm new to HA and I'm trying to create temperature graphs for my rooms. I figured out how I can build a template sensor to extract the temperature attribute from the climate/termostat entity. However some rooms have several termostats and thus several readings. I can't figure out how to aggregate them into one sensor (average?). It seams like it should be straight forward but haven't found any example. Does anyone have any suggestions?

deft timber
half tiger
#

Ah thanks will try that and see if I can get it to work.

tardy patio
#

Hello! Is there a way to get a value of a specific mqtt topic in templating, withoutt it being used as a trigger?

#

I want to make an automation, and do something with the value of an mqtt topic. But the automation will have to be triggered on different triggers, not THAT topic.

deft timber
tardy patio
#

So how could I get te value on the mqtt topic intro the payload_template section?

deft timber
#

That I don't think you can do with wait_for_trigger

#

you have to create a sensor on that other topic, so that you can use that value in your automation

tardy patio
#

Yep, I know that is one way,

#

I thought I could jump that step ๐Ÿ™‚

half tiger
deft timber
#

min/max can't access to attribute

#

you can then create a simple template sensor

half tiger
#

Ah. Thanks. Yeah - that's what I have now {{climate.guest_room_temperature.attributes.current_temperature}}

deft timber
#
{% set temps = [state_attr('sensor.one', 'temperature'), state_attr('sensor.two', 'temperature'), state_attr('sensor.three', 'temperature')] %}
{{ (temps | sum / temps |count) | round(1) }} 
half tiger
#

Even better - thank you so much!

deft timber
#

just pay attention that this simple code doesn't deal correctly with unavailable states

half tiger
#

Would you do it like this or create a template for each termo and then use min/max on those? What is the better route?

tardy patio
#

One small pickle, if anybody knows how to send off from (1.0, 20.0, 'off') using this: payload_template: "{{ trigger.payload.split(',')[1][:-1:] }}" - service: mqtt.publish data: payload_template: "{{ trigger.payload.split(',')[2][:-1] }}" topic: "opentherm-thermostat/mode/set" retain: true qos: 0 first line manages to extract the value 20, but last line will result in 'off' instead of off

deft timber
half tiger
deft timber
tardy patio
#

Hmmm Let me see ๐Ÿ™‚

#

Getting some errors.

#

Looks like it can't take out the 'character

#

unexpected end of the stream within a single quoted scalar

deft timber
#
  payload_template: >
     {{ trigger.payload.split(',')[2][:-1] | replace("'","") }}
tardy patio
#

Yep, that is my syntax as well,

#

and I get that error

deft timber
#

sure ? ๐Ÿ™‚ on a second line ?

tardy patio
#

wait

deft timber
#

Using > avoid using the quotes around the template a fix therefore your issue

tardy patio
#

ohhhh thank you thank you thank you ๐Ÿ™‚

lethal sparrow
#

hi! I have my cameras sending motion detected data to nodered and I was wondering if there's something like a "virtual motion sensor" in HA that could receive the current state from nodered

#

because it seems like the "value_template" field just accepts values from existing devices

lethal sparrow
#

got it! -> entity node in node red (required HACS)

lime grove
#

Could CT clamp accuracy be improved by using the line voltage somehow in the template?

green solstice
#

I've got an automation triggered by timer.finished. In the action, trigger.event is empty. Am I missing something silly?

modest sparrow
ivory delta
#

You just linked to someone's entire config. Would you like to narrow it down a little so we know what you're actually asking?

modest sparrow
#

I've altered this part:

#

variables:
switch: "{{ 'switch.{}'.format(name) }}"

#

to this:

#

variables:
switch: "{{ 'switch.{}'.'plug_' + name + '_relay_0' }}"

ivory delta
#

And that's way too narrow... ๐Ÿคฆโ€โ™‚๏ธ

#

Context please.

#

.share the script

modest sparrow
#

sorry mono, was still anwsering ๐Ÿ™‚ Yes, hold on

silent barnBOT
#

Please use https://paste.ubuntu.com/ to share code or logs. Please don't use Pastebin, since it can randomly add spaces to the main view.

modest sparrow
ivory delta
#

So you're changing line 13? What's the problem?

modest sparrow
#

The original script uses the name variable and I think it matches exactly in the authors code, but in my case I need to change it to match, but that doesn't work it seems

#

setting up the variable switch: "{{ 'switch.{}'.'plug_' + name + '_relay_0' }}" give an error when reloading my code

#

(TemplateSyntaxError: expected name or number) for dictionary value @ data['variables']['switch']. Got None. (See /config/configuration.yaml, line 15).

ivory delta
#

Ok. Your template is invalid. If works for them because the .format function does a substitution of {}

modest sparrow
#

Figured as much, I can't find any documentation on this format function. Is this Python? Or some custom Home assistant stuff?

ivory delta
#

It looks like you want something more like this:
{{ 'switch.plug_{}_relay_0'.format(name) }}

modest sparrow
#

Aha, so format() puts the name instead of the {}'s?

ivory delta
#

.format is Python, yes. Templates are a mix of Jinja2 and native Python, with a few things turned off for safety.

modest sparrow
#

Thanks, makes it easier to search myself

ivory delta
#

If you want to test something that uses variables, you can do stuff like this in Dev Tools > Templates:

  "temperature": 25,
  "unit": "ยฐC"
} %}

The temperature is {{ my_test_json.temperature }} {{ my_test_json.unit }}.```
modest sparrow
#

I have some experience in programming, but mostly Javascript/PHP so Python is a little awkward for me still

ivory delta
#

set lets you assign something so you can test the variable in a subsequent template.

modest sparrow
#

Yes, Dev tools is a great resource to quickly test stuff out

#

Was already working in it to test

dreamy sinew
#

or {{ 'The temperature is {}{}'.format(my_test_json.temperature, my_test_json.unit) }}

modest sparrow
#

Great, I'll try the use the format() function and see how it works

dreamy sinew
#

useful for constructing strings from multiple vars

ivory delta
#

Before I learned more about templates ๐Ÿ˜Š

dreamy sinew
#

haha

ivory delta
#

No, wait... it's lost my stuff ๐Ÿ˜ฎ

dreamy sinew
#

i've been learning ya

ivory delta
#

That's a native example... ๐Ÿ˜ฎ

dreamy sinew
#

browser cache reset?

ivory delta
#

Kinda. Just realised what it was... I pointed a subdomain of my personal domain at my home server. The cached versions I'm used to are from when I was using DuckDNS... ๐Ÿ˜„

#

Copying them across now ๐Ÿ˜„

dreamy sinew
#

lol

ivory delta
#

But yeah, good to know they're just cached by the browser. I did wonder what the mechanism was.

dreamy sinew
#

yup, i hop across machines often enough that i have different things in all of them

#

almost none of it for stuff i actually use ๐Ÿ˜›

ivory delta
#

I don't use any of the stuff lying around in my Dev Tools, which is kinda the point. Stuff I care about is in config already... this is a playground and where I keep examples for quick access to share with people.

#

I should probably save them somewhere just in case.

dreamy sinew
#

lol i just re-create things

sonic nimbus
#

Hello, how to match time from the trigger or something similar

#

I have two triggers, and I want to set my input_boolean to true if '00:30:00' and to false if '07:30:00'

#

or maybe to create two helpers time and set those timings

ivory delta
#

{{ now().hour == 0 and now().minute == 30 }}

#

Change the numbers as needed.

#

But since you didn't say what you want to happen at 00:31:00, 00:32:00, 00:33:00, etc, I don't know if that's what you're after ๐Ÿ˜‰

sonic nimbus
#

I will check it tnx..well, I want just to set my input boolean at specific time

#

so if my boolean goes to true at '00:30:00' it should stay in true status until the morning at '07:30:00' when its setting it to false and so on

ivory delta
#

I gave you an example of a template you can use for your condition.

sonic nimbus
#

I think I got it..I will test it ๐Ÿ˜‰

modest sparrow
silk smelt
#

hey everybody! Any idea why this doesn't add up?
{{ states('sensor.watt_panelovn_stue_a') + states('sensor.watt_panelovn_stue_b') }}

ivory delta
#

{{ binary_sensor }}
binary_sensor isn't defined there ๐Ÿ˜‰

charred dagger
#

Because states are strings.

ivory delta
#

String math ๐Ÿ˜„

silk smelt
#

ah

#

hehe

ivory delta
#

Milenco - to debug stuff like that, you should send a persistent notification with the variable name, then you'll see what its current value is (if it has one).

modest sparrow
#

Hmm, not sure how to do that..Just noticed that I made some other mistakes as well, will take a few more hours I guess..

young jacinth
#

Hi, if i use a template in a variable and use that variable in a loop inside a script, will the value of the variable be updated if it changes? or will the variable only be set at the beginning of the script?

distant island
#

Hey Everybody im triyng to get a temparute offset to work but no template sensor is showing in my entity list ๐Ÿ˜„ i already created a topic in the forum but iยดm a bit impatient. tought maybe some of you could help me out ๐Ÿ˜„

ivory delta
#

.share your config

silent barnBOT
#

Please use https://paste.ubuntu.com/ to share code or logs. Please don't use Pastebin, since it can randomly add spaces to the main view.

distant island
#

Me or Sam

ivory delta
#

Sam asked a general question. You said you have a problem with your config.

distant island
ivory delta
#

It looks okay. What does the command line config checker say?

silent barnBOT
#

Always run the configuration check command when you make changes. Don't trust the UI check - it misses some problems.

distant island
#

good question how do i check that learning everyday something new

#

nevermind think figured it out waiting for the result

#

oh no did the core check i post if i got any news

#

so did the check it says: Successful config (partial) octoprint

ivory delta
#

No complaints about the template sensor then? Have you restarted HA since you added the config?

distant island
#

yeah did via the server menu in the gui maybe a hard reset will solve the problem?

ivory delta
#

A 'hard reset'? You should never reboot the host. Just use the restart button.

distant island
#

i meant just pulling the cord dont know the term in linux language ๐Ÿ˜„

#

bit yeah you right doing a restart the right way

#

ohhh yeah thanks mono

#

the command line ha core restart did the trick i dont know if the restart button in the gui did not work but now iยดm seeing my sensor

#

i just saw it becuase you gave me the tip with the command line checker ๐Ÿ˜„

earnest cosmos
#

I want to set a trigger to fire eg. 30 minutes before my alarm clock is set input_datetime.alarmtid, but I cannot get this right:

{{ ((now().strftime("%s") | int - 1800) | timestamp_custom("%H:%M")) == states.input_datetime.alarmtid.state  }}
fossil totem
#

I suspect I am doing something dumb here, trying to pull an item from a weather provider forecast.

#
{% set weather_provider= "weather.kgrr_daynight" %}
{% set forecast_index= "0" %}
{% set forecast_attribute= "detailed_description" %}
Not working: {{state_attr(weather_provider, "forecast")[forecast_index|int].forecast_attribute}}
working: {{state_attr(weather_provider, "forecast")[forecast_index|int].detailed_description}}
jagged obsidian
#

don't you have to concat weatehr provider?

fossil totem
#

not sure i follow that one

jagged obsidian
#

and quote it

fossil totem
#

weather_provider is a var

jagged obsidian
#

like: '{{ state_attr(""~ haspentity ~"","node") }}'

#

haspentity is a var

fossil totem
#

check the working example

#

using a variable for the index of the list works

jagged obsidian
#

no idea about those attributes

fossil totem
#

but trying to do the same as a key for a dict... doesn't. at least not the way i'm trying to do it up there ๐Ÿ˜„

dreamy sinew
#

you can't dotwalk with a variable. it'll just try to find an attribute with that name instead

#

{{state_attr(weather_provider, "forecast")[forecast_index|int].get(forest_attribute) }}

fossil totem
#

BOOM that was exactly it. i've never heard of dotwalk, so now i have some googling to do. thank you @dreamy sinew for helping me and giving me something new to learn. i really appreciate it!

jagged obsidian
#

ah that's the python part of templating

fossil totem
#

and now HASP has a blueprint to show weather forecasts ๐Ÿ˜„

dreamy sinew
#

yeah you're touching a dict() so all of the dict functions are available there

fossil totem
#

i'm trying really hard not to make a joke about touching dict()s

dreamy sinew
#

"dot-walking" is a thing that JS and jinja let you do. its kinda odd.
Given this dict:

d = {"foo": {"bar": "blah"}}
#

you can get to "blah" by using:
{{ d.foo.bar }}

#

but it doesn't work in some cases. You can't use it with a variable as you noticed and you can't use it if the key you want to use has a space in it

scenic solstice
#

I am using a template sensor to pull out an attribute of a climate entity that captures what equipment (heat, fan, etc) is running. When no equipment is running the climate's equipment running attribute exists but has no value and template sensor has a value of *unknown *instead of *none *like I'd like. My various template attempts work fine in devtools but not as config.

#
  - platform: template
    sensors:
      hvac_equipment:
        friendly_name: 'hvac equipment'
        value_template: >-
          {% if state_attr('climate.living_room', 'equipment_running') %} 
          {{ state_attr('climate.living_room', 'equipment_running') }} 
          {% else %} 
          None
          {% endif %}
#

I've tried the states.entity.attirbutes.attribute_name method, ive tried if.., and "if... defined", is_state_attr looking for '', and others. Nothing that I try that works in dev tools templates works in the actual config. I've googled and searched here a good bit and I'm out of ideas

dreamy sinew
#

None is a special word

scenic solstice
#

ok let me try something

dreamy sinew
#

Also it's probably in state unknown so just check for that

scenic solstice
#

dev tool states has it has nothing after the name just equipment_running:

#

trying something other than none now

#

ha! <template TemplateState(<state sensor.hvac_equipment=something; friendly_name=hvac equipment @ 2021-01-29T22:23:35.561688-05:00>)>

#

and as soon as you said that, i recall someone saying that a few weeks ago

#

thank you!

thorny snow
#

I want to make an if statement for a sensor, this because one of my sensors becomes negative, but if the value is negative it must be 0. I found this:
{% if states.sensor.measured_current_spa_heating.state < '0' %}
But i dont know how to go further?

ivory delta
#

You can use logic like this to ensure you always return zero or higher:
{{ [-10, 0] | max }}

#

The -10 is just an example, you'd put your sensor state there.

restive flume
#

I want to use an input_number in place of the '3' in a service call like this:

#
service: climate.set_fan_mode
data:
  fan_mode: '3'
entity_id: climate.hvac_office
#

it seems like I can just replace the '3' with a template but I'm not sure that's right

ivory delta
#

Have you tried it?

restive flume
#

oh.. shit.. I just remembered I can trigger an automation!

#

well now I'm just confused.. something happened that I don't understand.. I'm going to guess that my template was wrong because rather than switching to 2 which is what it was set to it switched to AUTO.. So I'm guessing maybe it has to be converted to a string first

#

or maybe the other way around.. I can't remember how it works..

#
fan_mode: '{{ states(''input_number.office_aircon_boost_level'') }}'
#

is what I tried

#

no... string IS the default... can't possible be a number as AUTO and QUIET are not numbers... so.. I don't know..

#

I tried

#
fan_mode: '{{ states('input_number.office_aircon_boost_level') }}'
#

that works in the template editor (to get the number).. but it still doesn't work in the automation.. and is apparently not valid

#

for now I'll just continue editing the automation about 6 times a day to change the number until I can figure out if this is possible to do

deft timber
#

| float. And use states() function instead of states. ...

sinful bison
#

any idea if i can make this work ?

  mode: parallel
  fields:
    service:
      description: 'the service to run'
      example: 'light.turn_on'
    data:
      description: 'the data to pass to the service'
      exemple: '{"entity_id": "light.thatlight", "effect": "blink"}'
  sequence:
  - service_template: "{{ service }}"
    data_template: "{{ data|to_json }}"```
molten scroll
#

What do I need to write to have a template that sends me a message in the official android app, to turn off the ventilation when all humidity sensors report a value <=60.0, and s message to turn it on when any sensors reads >=60.1 ?

sinful bison
#

2 trigger with state number above or below your value
a choose block in the sequence that send the notif with a diferent text based on the said value, then you wait for the event on the button click and add another choose based on the reply

molten scroll
#

Could you show me a mock-up of what the code would look like?

#

I don't know the syntax

south rain
#

I use utility_meter to calculate monthly consumption price. Is there way to "save" monthly price and have chart of those values ?
Jan - $x
Feb - $x
Mar - $x
....

ivory delta
#

Sure... but you don't want to do it from HA's database.

keen crater
#

Is there a way to dynamically populate an input_select? I would like to build some front end in HA to OTA update my z2m lights. Lights with updates available publish update_available: true, so it would be nice to dynamically populate an input_select with all lights with an update available. I can then trigger the update command once I selected a lamp from the list.

ivory delta
keen crater
#

Did't really think about it like that, brilliant! ๐Ÿ˜›

sinful bison
#

as much as i try i can't get this to work

  mode: parallel
  fields:
    service:
      description: 'the service to run'
#      example: 'light.turn_on'
    data:
      description: 'the data to pass to the service'
#      exemple: ''
  sequence:
  - service_template: '{{ service }}'
    data_template: '{{ data|to_json|d({}) }}'```
I feel like it should now that template can return other thing than string...
thin vine
#

how do you call the script, as this is only showing the definition, calling it determines what's data is going into service and data. Also I wonder if this might be because these names might be reserved. Also do you get errors ?

sinful bison
#

right no i don't call the script since i can't reload them

: expected dict for dictionary value @ data['sequence'][0]['data_template']. Got None. (See /home/homeassistant/.homeassistant/config
uration.yaml, line 218)```
#

i need to make a warper in order for other script to call service that may failed, without failing themself.
So i though i could make a generic one, with data_template being a json map given as a parameter

thin vine
#
warper_service_nofail:
  mode: parallel
  fields:
    service:
      description: 'the service to run'
#      example: 'light.turn_on'
    data:
      description: 'the data to pass to the service'
#      exemple: ''
  sequence:
    - service_template: '{{ service }}'
      data_template: '{{ data|to_json|d({}) }}'
#

I think it's identation ๐Ÿ™‚

sinful bison
#

wut ? you mean the '-'

thin vine
#

after sequence you need to ident the rest 1 step deeper

sinful bison
#

this is how the UI save them in the script file, but i can try moving the all sequence block one space :)

#

nop, no luck
janv. 31 11:33:15 ap-univm-016 hass[23150]: 2021-01-31 11:33:15 ERROR (MainThread) [homeassistant.config] Invalid config for [script]: expected dict for dictionary value @ data['sequence'][0]['data_template']. Got None. (See /home/homeassistant/.homeassistant/configuration.yaml, line 218).
But to note, the UI say that the config is valid when i check, on the log say otherwise

#

i have also tried - service_template: '{{ service }}' data_template: '{{ data|d({"message": "empty"})|to_json}}' just to make sure it wasn't because it was empty

thin vine
#

data is usually a list of things:

data:
  something: value
  something2: value2
#

so not a single string

sinful bison
#

yea i know, that's why i wish to send it a map.
It wasn't possible before the rework of template because template where always string.
But now template can return anything, map, int, array...
so this should work, no ?

thin vine
#

yeah it should... I'm messing with it in devtools -> template

sinful bison
#

it work well in template, but that sadly not what happend :(
Maybe it's simply not possible based on how data_template is rendred.

#

i am working on a pythonscript alternative for now... i hop i won't need it but at least i'll have something :)

#

tankyou for trying

#

i've made this python script as a workaround ```nofail_service = data.get('service')
nofail_data = data.get('data')

try:
hass.services.call(nofail_service.split('.')[0], nofail_service.split('.')[1], nofail_data, False)
except Exception as error:
logger.warning('error occured in a nofail call: {}'.format(error))```

amber hull
#

I have a template that I have used for a long time that now shows an error. I can't see the issue ```
platform: template
sensors:
ha_uptodate:
friendly_name_template: >
{{states('sensor.ha_local_version')}}
value_template: >
{{state_attr('sensor.supervisor_updates','newest_version') == state_attr('sensor.supervisor_updates','current_version')}}

icon_template: >
  {{ 'mdi:circle-outline' if states('sensor.supervisor_updates','newest_version') !=
      states('sensor.supervisor_updates','current_version') else 'mdi:check-circle-outline' }}
unit_of_measurement: Up to date``` TypeError: __call__() takes 2 positional arguments but 3 were given
sinful bison
#

without diging at all, i see Up to date, witch is 3 word ... maybe quote this ?

amber hull
#

Thanks, Tried it in developers tool and same error

#

more of the error message 'Template("{{ 'mdi:circle-outline' if states('sensor.supervisor_updates','newest_version') != states('sensor.supervisor_updates','current_version') else 'mdi:check-circle-outline' }}")' for attribute '_icon' in entity 'sensor.ha_uptodate'

sinful bison
#

yea i am blind sorry

#

you are using states, not state_attr in the icon_template

thin vine
#

and states() can only have one attribute.. doh!

sinful bison
#

i have stuff to do, hop this fixed it bschatzow ๐Ÿ‘‹

amber hull
#

Do what you need. Thanks. I changed the states in the two places to states_attr and now in developer template I get UndefinedError: 'states_attr' is undefined

thin vine
#

state_attr not states_attr

amber hull
#

Thanks

#

It works now. Not sure why it worked with no errors for over 6 months until today

peak flame
#

I'm trying to convert from C to F, and round, and for some reason it isn't rounding {{ states('sensor.ble_temperature_a4c13807de90')|float*9/5+32|round(1)}}

#

{{ states('sensor.ble_temperature_a4c13807de90')|float*9/5+32|round(1)}}

#

am I chaining wrong?

#

also similarly, why does {{ 10|float+1|float*2 }} return 12, does it work backwards?

#

{{ (states('sensor.ble_temperature_a4c13807de90')|float*9/5+32)|round(1)}} works

#

I get it now, math operations aren't filters

fossil totem
#

I am struggling to figure out a way to cycle through a list and find next/previous items in the list. Anyone have any pointers? cycler is almost what I want but still not really.

#

For example, say I have a list {% set compare_list = [2,8,6,4,5] %}

#

and a current value: {% set compare_value = 6 %}

#

what i'd like is some way have a previous_value == 8 and a next_value == 4

#

The trick is that I want to loop/cycle/modulo/etc this list. So, if compare_value = 5 then previous_value == 4 and next_value == 2

#

finally, there's an off chance that compare_value is not in the list at all and I would need to do something intelligent in response. kinda doesn't matter that that actually is, so long as previous_value and next_value return some valid item from that list (maybe elements 0 and 1? or the first and last? open to most anything there)

fossil totem
#

think i have a workable solution. if anyone looks at this and thinks MAN LUMA YOU ARE DOIN IT WRONG MY FRIEND please let me know ๐Ÿ˜„

#
{% set page_current = 2 %}
{% set page_list = [2,8,6,4,5] %}
{% set page = namespace() %}
{% set page.previous = page_list[(page_list|length)-1] %}
{% set page.next = page_list[0] %}
{% for item in page_list %}
  {% if item == page_current %}
    {% if not loop.first %}{% set page.previous = loop.previtem %}{% endif %}
    {% if not loop.last %}{% set page.next = loop.nextitem %}{% endif %}
  {% endif %}
{% endfor %}
Page = {{ page_current }}
Previous page = {{page.previous}}
Next page = {{page.next}}
#

if page_current is outside of the list, previous will be the last element, and next will be the first element, and that seems pretty reasonable

wanton lichen
#

HI, I have the following in configuration but when I check configuration validation before restart the check seems never stops. If I comment the lines out.. all is oK

#
  • platform: template
    sensors:
    total_power_shelly_em:
    friendly_name: "ShellyEM Total Power"
    unit_of_measurment: 'Watts'
    value_template: "{{ states('sensor.shellyem_b03059_channel_1_power')|int + states('sensor.shellyem_b03059_channel_2_power')}}"
#

Waht am I doing wron here? Thanks

ivory delta
#

Your template is invalid. Test it in Dev Tools > Templates

#

And don't rely on the UI config check:

silent barnBOT
#

Always run the configuration check command when you make changes. Don't trust the UI check - it misses some problems.

wanton lichen
#

Thank you. Its states "unsupported operand type(s) for +: 'int' and 'str'"

#

I want to add the 2 figures together.

ivory delta
#

Yes... can you see why it's an int and a str?

wanton lichen
#

yes I'm missing the second |int

#

I think

ivory delta
#

Bingo

wanton lichen
#

Thank you.

#

First time I've done this so learning all the time...

ivory delta
#

Always be learning

wanton lichen
#

I have now corrected and checked it developer tools template and it returns the expected result. But when I paste it from there into config I'm getting the same loop when checking config before a restart... hmmm

ivory delta
#

Use the command line version of the check. Follow the link in the bot message.

wanton lichen
#

mono thanks for your help. After trying all sorts of things. I found that if I commented out the unit_of_measurment: 'Watts' it passed.

#

My template sensor doesn't like a unit of measurement

ivory pawn
#

Hello, I have this template -
value_template: '{% if trigger.payload_json.command is defined -%}True{%- else -%}False{%- endif %}'Can you tell me how to add an 'and' condition to the 'if' such that 'command' is defined and its value == "White" ? Thanks

dreamy sinew
#

those get funky

#

because if it isn't defined and you try to check the state it'll throw a value error

ivory pawn
#

thanks... can i just stack the conditions so that if it is defined then it checks on value ?

dreamy sinew
#

{{ True if trigger.payload_json.get('command', None) == 'White' else False }} might work

ivory pawn
#

@dreamy sinew cheers, ill try it

ivory pawn
opal dawn
#

Good morning all. I wanted to make a template with the full date of tomorrow. I already made something but found out yesterday that it returned 32 januari instread of 1 febrauri ๐Ÿ˜„
https://paste.ubuntu.com/p/nGSMXFQXNR/

Do I need check on over 30/31 , i.e. add more if statements. Or are there any nicer ways?

deft timber
#
{%set tomorrow = now() + timedelta(days=1) %}
{{ days[tomorrow.weekday()] + ' ' + (tomorrow.day) | string + ' ' + months[tomorrow.month-1] }} 
opal dawn
#

Thx will give it a shot Slash !

deft timber
#

Graag gedaan

deft timber
#

(fyi using tild avoid the casting in string {{ days[tomorrow.weekday()] ~ ' ' ~ tomorrow.day ~ ' ' ~ months[tomorrow.month-1] }})

opal dawn
#

Mooie toevoeging ! / Nice to add !

mint viper
#

hi how would i go about writing a template to simulate the numeric state trigger using the below and for options?

#

but using input_number helpers for the values

ivory delta
#

You don't. You'll likely have to use a template trigger to set/unset an input boolean when it dips below/above and another template trigger to see how long it's been on.

mint viper
#

can i use input helpers in a threshold binary sensor?

ivory delta
#

Sure. Why couldn't you?

#

Actually, that's cleaner than my solution ๐Ÿ˜‚

mint viper
#

ok they way i thought it would work it dident so im not sure it is possible

#

this is what i have:

binary_sensor:
  - platform: threshold
    entity_id: sensor.bedroom_temp
    lower: "{{states('input_number.ac_off_temp')}}"
    upper: "{{states('input_number.ac_on_temp')}}"
    hysteresis: 0.0
    name: Bedroom Temp Threshold
#

i also tried lower: {{states('input_number.ac_off_temp')}} and lower: input_number.ac_off_temp

arctic sorrel
#

Doesn't say they take templates

mint viper
#

ok i wanted template binary sensor not threshold

thorny snow
#

Hey all. I'm slightly confused around the use of is_state. I have 2 sensors which currently hold my e-mail address and when I use something like is_state('sensor.email_sensor_1', 'myemail@test.com') it becomes True, but if I use is_state('sensor.email_sensor_1', 'sensor.email_sensor_2') it becomes False. I have ensured that the state of both sensors indeed contains the exact same e-mail address. Is this not the way to compare 2 sensor values? or am I missing something else?

dreamy sinew
#

because that is checking if the first sensor has the state that matches the string you give

#

since that'll never equal sensor.email_sensor_2 it'll never work

thorny snow
#

not even if the second sensor contains a string value? It will only compare against an actual, hard coded, string?

dreamy sinew
#

but you can do {{ is_state('sensor.email_sensor_1', states('sensor.email_sensor_2')) }}

#

that's what you're telling it to do

#

you are giving it a hard coded string value to check against

#

if you want a var, you gotta give it the var

thorny snow
#

aaahhh cool! Checked it in the developer tools and it works!

#

Because it was "automagically" grabbing the state of the first sensor, I expected the same to happen if I passed a sensor in as the second parameter.

#

Thanks a lot ๐Ÿ˜

dreamy sinew
#

np

#
def is_state(hass: HomeAssistantType, entity_id: str, state: State) -> bool:```
#

ignore the first input but this is how its working

#

takes an entity id and compares against a state

thorny snow
#

Nice. I'll have to practice my Python a bit more ;P

dreamy sinew
#

jinja syntax is "pythonish"

#

you see more of the python when you're dealing with objects but its an odd mix sometimes

ornate ruin
#

@fleet wyvern let's chat here so we don't pollute the other thread

#

what's the state of your input number?

fleet wyvern
#

thanks a lot

#

sorry, i just saw what marcel wrote and i thought it was related

#

input_number.trv_living 255.0 initial: null
editable: true
min: 0
max: 255
step: 1
mode: slider
friendly_name: TRV living

ornate ruin
#

no worries

#

can you try changing it to 254 and see what happens then?

fleet wyvern
#

same error

ornate ruin
#

and you are casting it to int right?

fleet wyvern
#

this is the service call i am trying from developer tools

ornate ruin
#

oh... are you using data_template as a key instead of data?

fleet wyvern
#

no i am not

ornate ruin
#

try data_template

fleet wyvern
#

like this?

#

data_template:
entity_id: light.trv_living_dimmer
brightness: {{ states('input_number.trv_living') | int }}

ornate ruin
#

I checked the code, you shouldn't need to cast it, the service will convert it for you

#

ah you are calling it from dev tools

fleet wyvern
#

yes

ornate ruin
#

I don't know that dev tools supports templates

#

that may be your issue here

ivory delta
#

It doesn't ๐Ÿ™‚

fleet wyvern
#

aha, ok, i will try it in automations then

ornate ruin
#

๐Ÿ‘

fleet wyvern
#

thank you, i was using dev tools as a quick way to test actions without annoying the wife

ornate ruin
#

it's either you or your wife, you gotta pick one ๐Ÿ˜‰

fleet wyvern
#

better me of course :)) happy wife, happy life...

ornate ruin
#

fair

silent barnBOT
night imp
#

...ugh it's not a fkng codewall it was 8 lines. I hate hassbot

ivory delta
#

16 lines... and watch your attitude.

silent barnBOT
#

@night imp Rule #6: Spam will not be tolerated, including but not limited to: self-promotion, flooding, text walls (longer than 15 lines) and unapproved bots.

Please take the time now to review all of the rules and references in #rules.

For sharing code or logs use https://paste.ubuntu.com/.

night imp
#

Hi Mono.... so it was exactly at the bare minimum. I don't have attitude towards anybody, I was frustrated by hassbot

ivory delta
#

It doesn't matter if it's 'at the bare minimum'. Rules are rules. If you're unclear about any of them, go re-read #rules

night imp
#

awesome thank you so much for keeping me on track ๐Ÿ™‚

#

Let me rephrase.
Hi everybody, hope your day is going well ๐Ÿ™‚
I'm trying to implement kasa smart strip and get a lovelace card based on attributes in one of the plugs. However I don't know how. I'm looking at template sensors and I don't quite understand a few things. How do I know what to tab and why and what needs hyphens prior? Is this yaml specific or HA specific? an example (made sure to pastebin this time to make things easier for everybody ๐Ÿ‘ ) https://pastebin.com/42mk7H1n

#

@ivory delta is it 16 lines in discord or just /n returns? what's counted? I don't want to go over again if I keep typing. I'd imagine on crt monitors you get less space and more lines. Should I wait for another post first or can I add?

silent barnBOT
#

@night imp Generally, don't tag people to ask for help - it comes across as bad manners, youโ€™re demanding somebody answers you. Itโ€™s different if youโ€™re thanking somebody, obviously. If you do tag somebody keep it polite and respectful. Remember that everybody is a volunteer, and nobody has to help you, and people may block you.

Similarly, please donโ€™t DM (direct message) people asking for help. It also comes across as demanding, and means that others canโ€™t learn from what you do.

Finally, please keep tagging people in replies to a minimum. That too can become annoying very quickly and should be used only when it's necessary (such as if it's been a long time, or there's multiple conversations going on).

ivory delta
#

You're on a roll today.

night imp
#

I'm not tagging for help, it was asking you to clarify.

ivory delta
#

And no, don't keep adding to posts. That would still come under spam, since flooding is listed in the rules ๐Ÿ˜‰

#

I don't care what you're tagging me for. It's annoying being tagged.

#

And it will cause people to block you... like this.

night imp
#

I'm just asking for help and clarification. Dude I'm literally trying to be nice and ask about the rules

#

Should I use reply instead or just type only and hope you see it?

#

I'd imagine I can't just put text in one of these channels and guarantee to get a reply from a member of staff

arctic sorrel
#

There are no staff...

ivory delta
#

That explains why my drinks are taking so long to arrive.

arctic sorrel
#

Well, it doesn't help I gave the delivery to a geordie staggering on by

ivory delta
#

That doesn't narrow it down much. They all stagger.

dull sentinel
#

Hello,
I'm looking for an example to make a sensor to get the number of minutes between midnight (00:00) and an input_datetime (time)

Any ideas?

night imp
night imp
dull sentinel
night imp
#

While there may be something that fits you perfectly, there's not always a perfect match. There are lots of scripts and such out there that are close enough you just need to slightly adjust some things

dull sentinel
#

midnight or other input-datetime set to 00:00:

dull sentinel
night imp
# dull sentinel ```{{ (state_attr('input_datetime.ac_start_1', 'timestamp') / 60)|int }}```

Iโ€™d make sure you always watch the data types carefully. What they are and whatโ€™s needed. If thatโ€™s a time stamp, it has a specific format, can it be divided by 60? Imagine itโ€™s 1:00:59. Which it wonโ€™t be that pretty Iโ€™m sure. I think itโ€™s output is a string and it wonโ€™t be divisible by 60. Somebody with more experience can probably drop in on that, but likely.

thin vine
#

easiest way to find out is to test that in devtools -> Template. That gives what type it is too, at least when you just have 1 thing in there.

mint viper
#

is it possible to use a template with an if to set the value of a text helper?

#

the specific template is this:

{% if states('fan.bedroom_fan') == 'on' %}
  {{ state_attr('fan.bedroom_fan', 'speed') }}
{% else %} 
  off
{% endif %}
thin vine
#

yeah should be valid

gritty ice
#

Hi, I'm looking for a way to modify this tamplate in order to also show days:

value_template: "{{ states('sensor.time_remaining') | int | timestamp_custom('%H:%M:%S', 0) }}"

Currently it ignores the "day" part so if it's 25h it will just show 1h. Although nice, I don't need it to show 1d 1h... just 25h would be good enough. Any tips?

deft timber
#

to have the number if days, just add %d in your timestamp_custom

mint viper
# thin vine yeah should be valid

i must be formatiiong it wrong then. this wont save:

service: input_text.set_value
data: >-
  {% if states('fan.bedroom_fan') == 'on' %} {{ state_attr('fan.bedroom_fan', 'speed') }} {% else %} off {% endif %}
entity_id: input_text.fan_mode
#

this is the error Message malformed: expected dict for dictionary value @ data['sequence'][0]['data']

gritty ice
deft timber
thin vine
#

Correct tom:

service: input_text.set_value
data: 
  value: >-
    {% if states('fan.bedroom_fan') == 'on' %} {{ state_attr('fan.bedroom_fan', 'speed') }} {% else %} off {% endif %}
entity_id: input_text.fan_mode

see https://www.home-assistant.io/integrations/input_text/ you set a value, not the data

mint viper
#

i know it would be something like that

gritty ice
ivory delta
#

I use something like this for forcing a date into HH:MM:SS, where the HH can go beyond 23. You should be able to adjust it to mod 24 the hours and show days too:

{%- set map = {
       'Hour': (seconds / 3600),
       'Minute': (seconds / 60) % 60,
       'Second': (seconds % 60) } -%}
{% if seconds <= 0 %}Idle{% else %}
{% for item in map if map[item] | int > 0 -%}
  {%- if loop.first %}{% else %}, {% endif -%}
  {{- map[item]|int }} {{ item -}} {{- 's' if map[item]|int > 1 -}}
{%- endfor %}
{% endif %}```
#

That is, if you can't get strftime working for you.

gritty ice
#

thanks, I found something similar on the community forum. Seems to be working now after some tweaks.

#

lengthier piece of code, but gets the job done

silent barnBOT
sonic nimbus
#

hello, Im having a script which has some input fields such as speaker. The script is works fine - for particular speaker and message I play tts notification

#

but I want to pass multiple entities

#

such as {{ media_player.room1, media_player.room2 }}

#

is it doable through fields?

thin vine
#

because:

{% set speaker = "media_player.bathroom_ceiling_speaker" %}
{{ speaker | join(', ') }}

results in:

Result type: string
m, e, d, i, a, _, p, l, a, y, e, r, ., b, a, t, h, r, o, o, m, _, c, e, i, l, i, n, g, _, s, p, e, a, k, e, r
#

you can verify that yourself in devtools -> template

sonic nimbus
#

yes, I've just found that retrieves like that

#

but better approach I think would be

#

{{speaker.split(', ')}}

#

but when I add that into my script, Im getting error

#

voluptuous.error.MultipleInvalid: Entity ID m is an invalid entity id for dictionary value @ data['snapshot_entities']

ivory delta
#

I have no idea what your input looks like but this works just fine:

{{ speakers.split(',') }}```
Output: `['media_player.speaker_one', 'media_player.speaker_two']`
#

As long as snapshot_entities is a list, it'll work.

sonic nimbus
#

hmm..still I have an error

#

Set notification speaker: Error executing script. Invalid data for call_service at pos 2: not a valid value for dictionary value @ data['entity_id']

#

this is how I call the script entity_id: script.play_notification variables: speaker: "media_player.bathroom_ceiling_speaker" source: "Primary Chromecast" volume: "0.4" custom_message: "Welcome to the bathroom."

#

or

#
variables:
  speaker: "media_player.bathroom_ceiling_speaker,media_player.hallway_ceiling_speaker, "
  source: "Primary Chromecast"
  volume: "0.4"
  custom_message: "Welcome to the bathroom."```
ivory delta
#

So which bit is wrong? I don't know which entity_id line you're talking about.

#

Your script uses entity_id at least 3 times.

sonic nimbus
#

hm neither than I ๐Ÿ˜„

#

I have play_notification script

#

which is doing some math and calls another script

#

set_speaker.yaml

#

You can find both my script on the link above

#

so, I get it that in first (main) script I do split function and then I get an array of my speakers and thats seems quite ok, but when I try to proceed to my set_speaker.yaml with variable {{speaker.split(',')}}

#

in that moment, something goes wrong in the second script

#

Error during template condition: AttributeError: 'Wrapper' object has no attribute 'lower' this is the error now

sonic nimbus
#

when I tested with persistent notification I got just like media_player.bathroom_ceiling_speaker media_player.hallway_ceiling_speaker

silent barnBOT
sonic nimbus
#

and I tried just to pass through that speaker template entity but it doesnt work

silent barnBOT
shy yoke
#

Heya! ๐Ÿ™‚ I am pretty new to Home Assistant, so please excuse my ignorance about how the scripting works. I am trying to write a script that uses the android tv adb command runner to poll the TV about it's active HDMI port. What I need from it is basically the return value and do something with it (i.E. change color of lights etc.) I couldn't quite find how to handle the return of the adb command yet, however. This is what I have so far: https://pastebin.com/3Hkjf8F7

winged terrace
#

Hi, is it possible to expand this template code so that the status change is executed only if the value is below the defined voltage for a specific time (f.e. 30 secondes)?
https://paste.ubuntu.com/p/Mx3tfGr3xr/
same functionallity as possible in automations (for:)

sonic nimbus
#

how to extract entity names from list and pass them on service?

slow surge
#

Hi guys, I'm trying to get power consumption from few devices. The problem is that I cannot extract consumption from Samsung AC. When I'm trying to get it with:

{{ ((states.sensor.shelly_shsw_pm_e09806a9eefc_current_consumption.state | float) +
   (states.sensor.shelly_shsw_pm_f4cfa2e3ab20_current_consumption.state | float) +
   (states.sensor.shelly_shdm_2_8caab5557cd2_current_consumption.state | float) +
   (states.sensor.shelly_shdm_2_f4cfa2e113c2_current_consumption.state | float) + 
   (state_attr('climate.klimatyzator_biurowy', 'power_consumption_power') | float)) | round(0) }}

It works but only in Dev Tools -> Templates.
When I paste above code into configuration file, editor shows a message:

bad indentation of a mapping entry at line 10, column 24:
              (state_attr('climate.klimatyzator_biurowy', ' ... 
                     ^

What am I doing wrong?

glossy viper
#

show the sensor config

slow surge
#
sensor:
  - platform: template
    sensors:
      total_power_usage:
        value_template: '{{ ((states.sensor.shelly_shsw_pm_e09806a9eefc_current_consumption.state | float) +
          (states.sensor.shelly_shsw_pm_f4cfa2e3ab20_current_consumption.state | float) +
          (states.sensor.shelly_shdm_2_8caab5557cd2_current_consumption.state | float) +
          (states.sensor.shelly_shdm_2_f4cfa2e113c2_current_consumption.state | float) + 
          (state_attr('climate.klimatyzator_biurowy', 'power_consumption_power') | float)) | round(0) }}'
#

maybe its because of '

#

I will replace them with double "

glossy viper
#

try + "(state_attr('climate.xxxx ....floate))"

deft timber
#

You can't do multi line that way (and you are using single quotes within single quotes, which won't work):

  - platform: template
    sensors:
      total_power_usage:
        value_template: >
          {{ ((states.sensor.shelly_shsw_pm_e09806a9eefc_current_consumption.state | float) +
            (states.sensor.shelly_shsw_pm_f4cfa2e3ab20_current_consumption.state | float) +
            (states.sensor.shelly_shdm_2_8caab5557cd2_current_consumption.state | float) +
            (states.sensor.shelly_shdm_2_f4cfa2e113c2_current_consumption.state | float) + 
            (state_attr('climate.klimatyzator_biurowy', 'power_consumption_power') | float)) | round(0) }}
#

Or :

  - platform: template
    sensors:
      total_power_usage:
        value_template: >
          {{ [states('sensor.shelly_shsw_pm_e09806a9eefc_current_consumption'),
            states('sensor.shelly_shsw_pm_f4cfa2e3ab20_current_consumption'),
            states('sensor.shelly_shdm_2_8caab5557cd2_current_consumption'),
            states('sensor.shelly_shdm_2_f4cfa2e113c2_current_consumption'), 
            state_attr('climate.klimatyzator_biurowy', 'power_consumption_power')] | map("float") | sum | round(0) }}
winged terrace
#

just to know, why does some users have to post their code in "paste.ubuntu.com" and some not?

ivory delta
#

All users have to if it's over 15 lines ๐Ÿ˜‰

winged terrace
torn meteor
#

is there a special way to send integers to a shell_command? I have two variables in the command, {{ device }} and {{ hex }}. {{ hex }} is a string and works, but device is an integer and doesn't work

#

(the command fails)

#

i've tried debugging but it never shows the rendered command, it shows it with the {{ placeholders }} so i can't tell what it's sending ๐Ÿ˜ 

ivory delta
#

The command fails how?

#

Don't just say something is broken, say how it's broken. Then hopefully someone can answer the why.

torn meteor
#

sorry, that was bad of me:

#
Error running command: `ssh -o StrictHostKeyChecking=no pi@192.168.86.28 -i /config/ssh/pizero luxafor-python/luxafor-linux.py -d {{ device }} color -x \"#{{ color }}\"`, return code: 1
NoneType: None
ivory delta
#

If you suspect it's a problem with data types... what happens if you SSH into that Pi yourself and run the command manually with the arguments you're expecting it to pass?

torn meteor
#

oh it works fine. and if i hard code the values into the shell command config, also works fine

#

it's when i have a script that calls the shell command it seems to break

ivory delta
#

The fact that it's templated shouldn't matter at all. You could try sticking some logging in that Python script and see what it's receiving.

torn meteor
#

ok, will do

torn meteor
#

does shell_command: allow data_template:?

#

i'm wondering if it did, i'd be able to see the real values instead of the variable placeholders in the logs

torn meteor
#

new question. in the following context, what is the syntax for substituting the _1_ digit with an incoming data variable {{ device }}?

#
- service: script.luxafor_color
  data:
    hex: {%- set h = states('input_number.luxafor_1_color_h')|float / 60 %}
#

not sure how {{ }} reacts within {% %}

timid osprey
#

are you wanting to reuse that?

#

if not, you can ditch setting it to a variable

torn meteor
#

i am passing {{ device }} to the script hosting this service call

timid osprey
#

not that, h

torn meteor
#

it needs to be used 3 more times in the code body for hex

slow surge
#

@deft timber thanks

timid osprey
#

got it

torn meteor
#

oh yeah h is used a bunch. i truncated the inline ncode

ivory delta
#

.share the full thing.

silent barnBOT
#

Please use https://paste.ubuntu.com/ to share code or logs. Please don't use Pastebin, since it can randomly add spaces to the main view.

torn meteor
ivory delta
#

Oof, that's ugly. Use multi-line YAML...

torn meteor
#

every time i do, and edit with the UI later...

ivory delta
#

So don't use the UI if you're doing advanced stuff. UI's are for newbies.

#

I'll be honest... I'm not even going to try to read that mess.

torn meteor
#

i will have to separate this script to a separate YAML file then. i use the UI for certain things on the fly with my phone

#

the point is, inside that inline code, i want to use variables being sent to this script

#

{%- set h = states('input_number.luxafor_{{ device }}_color_h')|float / 60 %}?

ivory delta
#

Setting and re-using variables is fine. I just don't know what else is wrong with your template.

sonic nimbus
#

Why Im getting an error for simple check

#

Send Announcment to speakers: Error executing script. Invalid data for call_service at pos 1: Entity ID is an invalid entity id for dictionary value @ data['snapshot_entities']

timid osprey
#
- service: script.luxafor_color
  data:
    {%- set entityName = 'input_number.luxafor_' + device + '_color_h' -%}
    {%- set h = states(entityName) | float / 60 %}
    hex: {{ h }}
``` does this work
torn meteor
#

hmm. i'll try

ivory delta
timid osprey
#

check your template in dev tools if you haven't yet

ivory delta
#

Beat me by a second.

timid osprey
#

I'm sorry. I don't like cutting people off, haha

#

control + a

torn meteor
ivory delta
#

If you want to cut a few more characters, this might work:
{%- set h = states('input_number.luxafor_'~device~'_color_h')|float %}

#

Unless I've borked the syntax.

torn meteor
#

neat!

quiet kite
#

hey, today i have unexpected restart, and after this ui cannot turn on my light over mqtt. I thinks that because i cannot set colour, i can onlly set brightness. This is my template: https://pastebin.com/2bH1c1q2

charred dagger
#

I'd be surprised if that ever worked as intended. You're saying that the state of the light is whatever is in value_json['20'] if that exists, and the state of the light otherwise? That's bound to break.

pliant dagger
#

qq for here. I am moving over to zwavejs2mqtt and as a result the way that my motion sensor alarm levels are now reported changed a little bit. Instead of a sensor with a state its now a sensor with an attribute

#

So I'm working on it and so far I've come up with - platform: template sensors: living_room_motion: value_template: '{% if state_attr('sensor.living_room_burglar', value) %} {% if state_attr('sensor.living_room_burglar.attributes', value, "8") %} active {% else %} inactive {% endif %} {% else %} n/a {% endif %}' friendly_name: 'Living Room Motion'

#

but this bombs HA lol so now I discovered the Template Tool (very nice btw) trying to figure out what the magic formula is here to have this monitor the attribute of value

#

Ok fixed it ๐Ÿ™‚

#
  sensors:
    living_room_motion:
      value_template: >-
        {% if is_state_attr('sensor.living_room_burglar', 'value', 8) %}
          active
        {% elif is_state_attr('sensor.living_room_burglar', 'value', 0) %}
          inactive
        {% else %}
        n/a
        {% endif %}
      friendly_name: 'Living Room Motion'```
solar knoll
#

Okay, sorry for what I think is a very noddy question ... but I am clearly missing something ... any idea why this binary_sensor is not working in the way I think it should be ... It records "away" if only one person leaves the house where as I just want to know if anyone is home (incidentally using a group of people and checking their status seems to do the same)

glossy viper
#

maybe a group is simplier

#

family:
name: Family
icon: mdi:home
entities:
- device_tracker.xxx
- device_tracker.xxx

solar knoll
#

I tried with a people group ...

#

household: name: Family entities: - person.one - person.two - person.three - person.four

#

but get the same behaviour ... it will show away as soon as only one person leaves

glossy viper
#

impossible

#

as long as one person is home, the sensor should be home

solar knoll
#

I understand, which is why I am so confused and yet this is the behaviour I get ... when I put group.household into a lovelace dashboard (entities card) it switches to away whenever a single person leaves the house ... I have been scratching my head with this on and off for a few days now, hence the call for help - because I agree, its does not seem to be working as designed or documented to me

#

but its the reason I created the binary sensor to try and get different results, but all I can get is the same ๐Ÿ˜•

glossy viper
#

u track properly all persons?

solar knoll
#

yes, all 4 people are using the HA app. All 4 are showing individual home/away status correctly, all 4 people have their phone as a device tracker such as this:

#

(ahh no image pasting ? ;-))

#

1 sec ...

silent barnBOT
#

@solar knoll Your message has been deleted as it contains a link or a domain name 'pasteboard_dot_co' that is on the blocked list because of: 'Virus detected!'.
Please re-post by removing/changing the domain name/link. Your original message has been DM'ed to you.

solar knoll
#

anyway, individual status is reported correctly for each person

glossy viper
#

oh. u have viruses ๐Ÿ˜ฎ

solar knoll
#

LOL, no ... apparently the blacklist here thinks pasteboard_dot_co might though

harsh anchor
#

heya ppl
I want to track my energy usage and compare with my utility company, trouble is I don't have a proper ticking signal
I have continuous energy readings, does anyone have/knowof a readily available template to construct a sensor that ticks every kWh?

ashen isle
#

hi, i want to use tempating on service call ligth.turn_on. i want to configurie it via "gui" this is my approach:
brightness: >- {{ (2 + (state_attr('light.shellydimmer_indirekt', 'brightness') | float / 2.55)*0.3) | int }} white_value: >- {{ (2 + (state_attr('light.shellydimmer_indirekt', 'brightness') |float )*0.3) | int }} entity_id: light.shellyrgbw2_tv_led

i get an error like ...expected int for dictionary value @ data['brightness'], can you tell me how to proper use service template when working with the "gui" ?

#

all suggestions, threads and whatsoever are for configurations.yaml

#

i try to find the answer for like an hour

#

changing > to >- and try various versions of '' and ""

#

but most of the time the solutions are related to replace like data with template_data but when working with the "gui" i cant change this

dreamy sinew
#

where are you doing this?

#

in devtools > services?

ashen isle
#

yes

dreamy sinew
#

that tool does not support templates

ashen isle
#

๐Ÿ˜ซ

#

omg

#

pasting my educated guess into the automation i wanted to create and it worked right away

#

thx

thorny snow
#

How do I return the brightness of a light?

balmy wedge
#

Hi everyone. I have a doorbell a bit far away on a flaky wifi, and last_changed for the last ring instead turns into the last reconnection. Can a template that sets itself to on when the state is on, and to off any other time, be used instead?

dreamy sinew
#

as its own sensor probably

balmy wedge
#

A template sensor. I'll try that!

thin vine
ivory delta
strong idol
thin vine
strong idol
#

Thanks for the hint. I am talking about reading a variable if a script is running. Let's say a script is called with the varibale value "a". I would like to read this variable from another script or automation (or the UI).

thin vine
#

as far as I know only the calling automation and the called script have that information, but what do I know ๐Ÿ˜‰

deft timber
#

Yes there is no way to catch that information from another script. Except of course if your first script store that info somewhere

strong idol
#

Thanks to both of you! ๐Ÿ™‚

lime grove
#

This isnt rounding to 3 decimal places

#

value_template: "{{ states('sensor.dehumidifier_volts') | float / 230 | round(3) }}"

#

returns value_template: "1.0078260869565219"

#

any ideas why?

mighty ledge
#

cause you're just rounding 230

#

not the entire math operation

lime grove
#

how do i do that?

mighty ledge
#

how would you do that with math?

reef kestrel
#

Would anyone know how to do the following correctly, to compare multiple values for selectattr:
{{ expand('group.lights') | selectattr('attributes.brightness','equalto', [255, 245, 200]) | map(attribute='entity_id') | join(',') }} If not, is there a better method? Thanks!

lime grove
#

I mean, how do I round the resulting number from the sensor / 230

mighty ledge
#

right, but if you were to write this on a piece of paper, how would you write it?

#

think back to highschool math

lime grove
#

work the answer out then simplify?

mighty ledge
#

or use... parenthesis

#

( value / other value ) | round

lime grove
#

ok thanks

mighty ledge
#

np

mighty ledge
reef kestrel
mighty ledge
#

then your light isn't set to exactly 255, 245, or 200

reef kestrel
#

Apologies, this is working perfect. Human error! Thank you!

mighty ledge
#

np

ember wagon
#

Oh I would very much like to show which of my cameras is not in privacy mode (a camera entity attribute) do we have some sort of template wizard ?

ivory delta
#

Your template wizards tonight are petro and phnx. ๐Ÿง™โ€โ™‚๏ธ

fossil totem
#

and the template petro just posted might apply directly to your situation

ivory delta
#

But no... no templates. There are so many things you could write that there's no easy way to suggest templates.

ember wagon
#

Hm that's sad - I'm trying to find some examples where attributes will be shown in messages based on attribute conditions and only batteries states is the most typical

ivory delta
#

If you don't know how to write templates, start by reading the links in the topic and the pinned messages.

#

If you want to know more advanced techniques, read the Jinja2 documentation.

ember wagon
#

Thanks and thank you for a pleasant "tone" it is very much appreciated (most people starts as Noobs)

ivory delta
#

No problem. Templates are difficult. If you start with the basics, they gradually make more sense.

ember wagon
#

I think I've got it:

{% if state_attr('camera.kokken_cam_sd', 'privacy_mode') == 'off' %}
The camera in the kitchen is ON
{% endif %}

#

Now an OR sentence would be nice in the condition line - like if this camera1 OR this camera2 then message: The camera1 or camera2 is ON

ivory delta
#

That's okay... but what if you have 5 cameras? Or 10? The template gets big ๐Ÿ˜‰

ember wagon
#

Hm then I know something about groups

ivory delta
#

Try putting your cameras in a group and then doing something like this:
{{ expand('group.cameras') | selectattr('attributes.privacy_mode','equalto', 'off') | map(attribute='entity_id') | join(',') }}

ember wagon
#

cool yes

#

And now groups can be made from UI (I will go for that)

#

Well no groups from UI ๐Ÿ˜ซ yet - I bet I have seen something - ok YAML we go

#

Get it works Thanks again Momo

ivory delta
#

No problem, MrBorb

ember wagon
#

well MrMono - any idea why this is not showing anything:

{%- set ns = namespace(message = 'These cameras is turned ON:\n') -%}
{% set temp =expand('group.all_cameras')
| selectattr('attributes.device_class', 'eq', 'privacy_mode') -%}
{%- for item in temp -%}
{%- if item.state == 'on' -%}
{%- set ns.message = ns.message + ' - ' + item.name + ' \n' -%}
{%- endif -%}
{%- endfor -%}
{{ ns.message }}

#

when this one does:

{{ expand('group.all_cameras')
| selectattr('attributes.privacy_mode','equalto', 'on')
| map(attribute='entity_id')
| join(', ') }}

ivory delta
#

I have no idea what you're trying to do with the first one.

#

But if the second one works... just use the second one.

ember wagon
#

hehe - I just try to extract the "items" where attribute is eqto privacy_mode and then check state for each

ivory delta
#

Oh, you're trying to get the names instead of the entity ID's?

ember wagon
#

yep - Just like I do with this battery argument:

{%- set ns = namespace(counter=0) -%}
{%- set threshold = 100 -%}
{% set temp = expand('group.battery_levels')
| selectattr('attributes.device_class', 'eq', 'battery') %}
{%- for item in temp -%}
{%- if item.state | int <= threshold -%}
{%- set ns.counter = ns.counter + 1 -%}
{%- endif -%}
{%- endfor -%}
{{ ns.counter }}

ivory delta
#

Maybe this (I haven't tested it):
{{ 'These cameras is turned ON:\n'~(expand('group.cameras') | selectattr('attributes.device_class', 'eq', 'privacy_mode') | map(attribute='name') | join('\n')) }}

ember wagon
#

YES !

ivory delta
#

No namespaces needed. One line ๐Ÿ˜‰

#

๐Ÿช„

ember wagon
#

It's so easy if you know it

ivory delta
#

The trick is the pipes (|), especially | map. They're very powerful.

ember wagon
#

hm cool

ivory delta
#

There's a link to those filters in the pinned messages if you want to learn more.

ember wagon
#

thanks - I will check it

#

Just to tell you what this meant - now we get a message on our phones if somebody is at home and the cameras turns on = Exit Privacy-mode - and it tells us which of the cameras is turned on - Cool feature

viral bolt
#

Hi Guys, I'm extracting a temperature value using this code: value_template: "{{ state_attr('sensor.uRad_Cloud_Multiple', 'temperature') }}" How can I round the extracted value to no more than two decimal digits?

charred dagger
#

{{state_attr(...) | round(2) }}

viral bolt
#

thanks a lot @charred dagger

kindred moss
#

Hey nice people.... I have a DHT22 sending a mqtt topic once a min via cron on a remote machine..... The state gets set as nothing due to unreliable results from the sensor sometimes

#

is it possible to have a template that if the result from the last topic is null/0 uses the last value ?#

#

or maybe better the other end.. to not send if empty ... yea that sound better lol

fossil totem
#

i think you're spot-on fixing the problem at the source ๐Ÿ˜„

dreamy sinew
#

template stuff only really knows what the current state of something is

kindred moss
#

there ya go. bitta bash and mktemp tail -n 1 woop woop lol

#

oh and sed of course ๐Ÿคฉ

gray sequoia
#

good evening is it possible to make a template that check's if there is a value written on a sensor before writing it on a new sensor? i am using the utility meter for showing my last periods in dashboard but if the target sensors goes to 0 / nothing and the value comes back it counts up the complete value from 0 once extra on the utilitymeter

now i am making a comparison if the new value is greater then the already written value but home assistant makes note of a detected loop in the log

this is my current configuration

- platform: template
  sensors:
    stroom_export_totaal:
      icon_template: mdi:home-export-outline
      friendly_name: Stroom export totaal
      unit_of_measurement: kWh
      value_template: >-
          {% if (states('sensor.p1_meter_total_power_export_t1') | float + states('sensor.p1_meter_total_power_export_t2') | float) >= (states('sensor.stroom_export_totaal') | float) %}
            {{(states('sensor.p1_meter_total_power_export_t1') | float + states('sensor.p1_meter_total_power_export_t2') | float) | round(3, 'floor') }}
          {% endif %}
wary horizon
#

how to avoid TypeError: argument of type 'NoneType' is not iterable when checking for an attribute that may, or may not exist, but the execution requires it exists and matches pattern?

ivory delta
#

What are you doing?

#

You've shared nothing.

wary horizon
#

since in automation I can't directly use a sensor attribute as trigger, as I learned here last week, I'm using the state update as trigger, and using a condition. In this case, it's a phone notification.

#

State trigger is the last notification sensor.

ivory delta
wary horizon
#

original question

#

the condition is template, such as {{ 'foo' in state_attr('sensor.op7tpro_app_last_notification', 'json') }}

#

but the field 'json' may not exist every time this template is called, and the template engine doesn't like that - as such I'm getting errors in the log

ivory delta
#

So... you need to create a template that doesn't give an error ๐Ÿคทโ€โ™‚๏ธ

#

Next time... provide the template first ๐Ÿ˜‰

wary horizon
#

I had to ask my rubber duck and it told me to at least remove my home address from it

dreamy sinew
#

|default([])

ivory delta
#

Nah, that'll blow up ๐Ÿ˜‰

#

I was going to go with the messy...
{{ state_attr('sensor.op7tpro_app_last_notification', 'json') and 'foo' in state_attr('sensor.op7tpro_app_last_notification', 'json') }}

dreamy sinew
#

Would still fail because it'll eval both every time

ivory delta
#

It works ๐Ÿคทโ€โ™‚๏ธ

#

I just tested it

#

It's lazy evaluation, no? Shortcuts when the first half is false.

wary horizon
#

seems to me it wouldn't bother evaluating the 2nd step if the 1st fails, so this should be good

dreamy sinew
#

Odd probably some jinja stuff. Python evals the full thing

ivory delta
#

๐Ÿ˜„

wary horizon
#

iirc python lets you do lazy matches too, so why not lazy evals as this

ivory delta
#

I'm just looking forward to upgrading all my projects to Node 14 for that sweet sweet optional chaining.

thin vine
#

and of course this is just an example that works in devtools -> template

gray sequoia
blissful copper
#

Hi! I want to catch any action/subtype of an Ikea remote (integrated via z2m) with one trigger to avoid an automation for every action-type and also a long trigger-list. But out of course I need to filter other changes like linkquality&battery then. I'm just struggling with the template-condition:
{% if ((state_attr("trigger.from_state.entity_id", "action") != state_attr("trigger.to_state.entity_id", "action")) and not is_state_attr("trigger.to_state.entity_id", "action", "")) %} (...)
Valid code but this is also filtering out all actions...?! Has somebody an hint for me why?

final zenith
blissful copper
#

Just tried it out...

deft timber
#

You should not mix up variables that contains the id if an entity and strings that represent an entity. Here trigger.to_state.entity_id is a variable containing the identifier of an entity -> no quotes

limber harness
#

Hey guys can anyone explain how to view trigger/event data?
I have some MQTT things happening and I want to use templates but I don't know how to see what I can work with and what the layout of incoming trigger data is.

blissful copper
ivory delta
#

'not working' doesn't help anyone.

silent barnBOT
#

Please don't say I have an error or describe an error. Share the whole actual error message so we can help you.

limber harness
dry matrix
#

Hi all! I have a climate.hallway entity (Nest thermostat). I'm trying to write a script that will just add one degree to the current set temperature using the climate.set_temperature service. I tried using the following template as the service data , but I'm getting a Message malformed: expected dict for dictionary value @ data['sequence'][0]['data'] error:

temperature: {{ state_attr('climate.hallway', 'temperature') | float + 1 }}

The temperature is an attribute of climate.hallway that is what the thermostat cooling/heating temp it's currently set to, btw. Any ideas of what I'm doing wrong here? Thanks for the help!

blissful copper
harsh anchor
#

is there a way to access all sensors of a certain type?
like "for each sensor in binary_sensor" or something like this?

ivory delta
#

What do you need? All the state objects, just the state values, just the names?

tardy summit
#

hi guys, because HomeKit climate control doesn't have support for "Dry" or dehumidfiers, I've created a fan template that I will then present to HomeKit to give us control of the dry function on our split system A/C. But I can't remember how to get the input boolean switch i created for tracking the state of my fan template to detect the state of the A/C. Am I asking in the right channel for help with this?

thin vine
deft timber
harsh anchor
#

@ivory delta I created n utility meters, so I would have a template in the tariff switching automation to call all meters and switch their tariff
something like "for each meter in utility_meter do meter.select_tarif = xyz"

ivory delta
#

Ok, so you want the entity ID's? This gets you a list of ID's for a given domain:
{{ states.utility_meter | map(attribute='entity_id') | list }}

harsh anchor
#

ok I need to understand this syntax better, thanks for the hint @ivory delta !

#

different question:
{{ (((states('sensor.garage_powermeter_electric_w_value')) | float) * 0.001 ) }}

this template works perfectly when in developer mode, but when I put it into a yaml, the sensor doesn't work

garage_powermeter_kw: value_template: "{{ (((states('sensor.garage_powermeter_electric_w_value')) | float) * 0.001 ) }}" unit_of_measurement: kW device_class: power

any clue what I'm doing wrong?

ivory delta
#

'doesn't work' ๐Ÿค”

#

Say what it's doing.

#

Give any error messages.

thorny snow
#

I want to add a number of sensor values. However, if I do this, it does not add them up, but they come out one after the other. How do I fix this?

#

'{{ ((states.sensor.today_consumption_sven.state + states.sensor.today_consumption_los.state + states.sensor.today_consumption_wasmachine.state)) | round(2) }}'

ivory delta
#

You're adding strings together. 'bob' + 'bob' = 'bobbob'

#

You need to cast each item to a number type first. states.sensor.today_consumption_sven.state | float

#

Also, you should use that format (states.sensor.today_consumption_sven.state). Instead, use states('sensor.today_consumption_sven')

lime grove
#

How can I accumulate daily power costs if unit rate changes every half-hour? I have the current wattage and total for the day

#

and I have a rest sensor with the current unit rate

ivory delta
lime grove
#

the unit price varies, does tariff accept a number?

ivory delta
#

Read the docs I linked, it'll tell you.

lime grove
#

it just refers to peak and offpeak

#

it doesnt refer anywhere to a variable rate

ivory delta
lime grove
#

why even suggest it then

ivory delta
#

Because now you have more knowledge than you had before. I don't know if there's a finite or infinite number of prices for your energy supplier ๐Ÿคทโ€โ™‚๏ธ

#

If it was finite, you could create tariffs... ๐Ÿคฏ

lime grove
#

Yes but it isnt. I did say the rate changed every half hour

#

anyway, can I not just do unit price * watts then accumulate it in a sensor?

ivory delta
sonic nimbus
#

How can I set a list of spotify uri's and then do {{ list | random }} ?

#

should I put in this automation just above something like {{ set list = ['list1','list2','list3','list4','list5']}} (pseudo code)

ivory delta
#

There's a link to the available filters in the pinned messages...

harsh anchor
#

@ivory delta it doesn't give any error, it's just unavailable

#

I checked the logs and there is nothing about that sensor, but when I try to read it it's just not available

ivory delta
#

Dev Tools > Templates

#

Step 1: test it there

#

Step 2: stop tagging me.

thorny snow
harsh anchor
silent barnBOT
#

@harsh anchor Generally, don't tag people to ask for help - it comes across as bad manners, youโ€™re demanding somebody answers you. Itโ€™s different if youโ€™re thanking somebody, obviously. If you do tag somebody keep it polite and respectful. Remember that everybody is a volunteer, and nobody has to help you, and people may block you.

Similarly, please donโ€™t DM (direct message) people asking for help. It also comes across as demanding, and means that others canโ€™t learn from what you do.

Finally, please keep tagging people in replies to a minimum. That too can become annoying very quickly and should be used only when it's necessary (such as if it's been a long time, or there's multiple conversations going on). When using Discord's new Reply feature it defaults to pinging the person you reply to, click @ ON to @ OFF to stop this - on the right side of the compose bar.

ivory delta
#

Anyone can answer your questions if you give the right information. It gets really annoying being tagged throughout the day.

harsh anchor
#

ok sorry, I'm used to forums really

#

anyway as I said before, in developer tools - templates it works fine, when I put it in the config it doesn't, and there is no error in the logs

harsh anchor
rugged lichen
#

Hello Community, I would like to set an input_datetime but with my template is not wants to work.

Service: input_datetime.set_datetime
Entity: input_datetime.bedheater_time
datetime: {{ (utcnow().strftime('%s') | int + (60*60)) | timestamp_custom ("%y-%m-%d %H:%M:%S") }}

In the developer tools its giving back the correct value, but in services I cannot test it.
Error:

Failed to call input_datetime/set_datetime service. Invalid datetime specified: {'[object Object]': None} for dictionary value @ data['datetime']

Thank you very much.

#

It can be its an issue and the service is not working? Even the examples from the docs are not working. and I found 1-2 year old community forum entries about this problem and the moderator told them to open an issue.

deft timber
thorny snow
rugged lichen
#

Can someone be kind to test an example with input_datetime.set_datetime service? Looks like its not working, but I want to be sure.

#

before I spend hours or days to fix my script.

#

just try this please from the official documentation in developer tools -> Services

- service: input_datetime.set_datetime
  target:
    entity_id: input_datetime.XXX
  data:
    datetime: "{{ now().strftime('%Y-%m-%d %H:%M:%S') }}"
hybrid tide
#

Is there a syntax like: for name in states.person where name.state == 'home'?

#

background:

         {% if name.state == 'home' %}
           {%- if loop.first %}{% elif loop.last %} and {% else %}, {% endif -%}{{ name.name | capitalize }}{%if loop.last %} are home.{% endif %}
         {%- endif %}
       {%- endfor %}```
#

in the above, if the first person in the list is away, the result is ", Bill, Entrick, Jimmy, Mark and Sven are home." (note that it starts with a comma)

ivory delta
#

Something like this?
{{ states.person | selectattr('state', 'eq', 'home') | map(attribute='name') | list | join(", ") }}

#

It won't do the 'and' for the final entry. You'll have to get clever to do that.

hybrid tide
#

wheew...uh...that's way over my head. LoL

ivory delta
#

It's Jinja filters. Each step is just passing the results of the previous step through another filter.

hybrid tide
#

haha. I'm trying to grok your example

ivory delta
#

It takes state.person, picks only the ones where state=home, then picks the names of those, turns then into a list (because map() returns a generator), then sticks 'em together in a readable format.

#

Play around with it in Dev Tools > Templates.

hybrid tide
#

Will do.

ivory delta
#

I spotted you have a | capitalize in yours too. Add that in just after | list if you need it.

#

Tell ya what... this might work:

{{ people[:-1] | join (", ")~" and "~people[-1] }}```
#

First line returns a list (array, in other words) of the names. Second line just does some templating with the results. All but the last item are joined with ', ', then you add ' and ' and the final name.

#

And since I can see them lurking already, I'm gonna thank slashback for the ~ trick ๐Ÿ˜„

deft timber
#

You can add | map("capitalize")| to capitalize the elements of the list (just before the | list)

hybrid tide
#

...mind blown.

ivory delta
#

That template will probably give odd results if there's fewer than 2 names found. Be sure to test it yourself.

#

You can always separate the two bits of logic by doing something like this:

{{ people[:-1] | join (", ")~" and "~people[-1] }}```
#

Easier testing that way.

hybrid tide
#

After you gave me the first line, I was working down that path...creating the "people" variable then looping...but the second line I wouldn't have gotten ๐Ÿ™‚

ivory delta
#

The second bit is a mix of Python and Jinja. Jinja for the | join filter but Python to select items from the list and mash 'em together.

#

I used to hate templates. I'm making an effort to learn more.

hybrid tide
#

...just...wow!

ivory delta
#

Filters are incredibly powerful once you learn how they can be used. Someone recently had a 9 line nested loop with namespaces... turned it into one line with filters ๐Ÿ˜„

hybrid tide
#

Thanks mono for your help!

ivory delta
#

No problem. Always happy to help a newbie out.

hybrid tide
#

slightly off topic, but I'll keep it quick because it's cool. Using that template as an Intenet, which is called from a Google Assistant bot I created using Google's Dialog Flow project. Basically, I can ask my bot "who's home" or "is XXX home". Super cool stuff!

ivory delta
#

That sounds great ๐Ÿ˜„

hybrid tide
#
{% if peopleNotHere == ['pfunky'] %}
Everyone is home except you!
{% else %}
{% set peopleHere = states.person | selectattr('state', 'eq', 'home') | map(attribute='name') | list %}
{{ peopleHere[:-1] | join (", ")~" and "~peopleHere[-1] }} are home
{% endif %}```
fossil venture
#

Is the test is number supported for state attributes? It's giving me unexpected results in the template editor, see: https://imgur.com/a/4pRQsCU

deft timber
#

is number returns true if the variable is a number, not if it is String representing a number, and since states are always string, is number on a state will always return false

#

{{ 3 is number }} --> True
{{ "3" is number }} --> False

#

You your sensor should always be positive, you wan use this : {{ states('sensor.your_sensor') | int(-1) >= 0 }}. It it fails to cast in int, the cast will return -1 which is below 0 -> it will return False

#

@fossil venture ๐Ÿ‘†

fossil venture
#

This isn't a state. It's an attribute. Attributes can have different types than just string.

velvet coral
fossil venture
#

"Entities with templated attributes. Attributes keep their native Python type, thus if the attribute is used/processed in a template again later, the type might be different."

deft timber
#

Indeed, if it's an attribute, it can be a number (my bad, I missed that).. but is it a number in your case?

fossil venture
#

Yep. See the first template result in the images I posted.

deft timber
#

I don't think you can trust that.
I put {{ "3" }} in the template tool, and it says it is a number. While clearly it is a string type for jinja.

fossil venture
#

Hmmm.

#

You could be on to something. The dev tools states menu returns this for the attribute: temp: '19'

#

So it's the template editor that is misleading.

fossil venture
radiant pewter
#

Hi I'm trying to create a template for a binary sensor that show "on" when my iPhone is connected to the downstairs router. this is what I've got so far:

#
  - platform: template
    sensors:
      tonys_iphone_downstairs_sensor:
       friendly_name: 'Tony Downstairs'
       value_template: >-
          {{ is_state_attr('device_tracker.tonys_iphone_wireless', 'Connected to', Downstairs) }} ```
silent barnBOT
#

To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks. Here's an example

Don't forget you can edit your post rather than repeatedly posting the same thing.

For over 15 lines you must use a code share site such as https://paste.ubuntu.com/ or https://www.hastebin.com/.

ivory delta
#

These are backticks: ``

#

Close. 3 of them on each end looks better ๐Ÿ˜„

#
binary_sensor:
  - platform: template
    ...```
blazing cradle
radiant pewter
#

thanks for the tip! @ivory delta

ivory delta
#

If 'Connected to' is an attribute of that sensor, the only thing that looks wrong is the last part... you need quotes around 'Downstairs'

#

In case you didn't already know, you can test templates at Dev Tools > Templates. It's quicker than reloading sensors.

radiant pewter
#

@ivory delta ok, the example in the documentation has without quotes

#

let me try with

ivory delta
#

If you do it without, it's a variable. It needs to be with. Could you share a link to the docs?

radiant pewter
#

btw downstairs is the vallue its polling for, not the attribute

#

@ivory delta thanks! But same result. I'm starting to wonder if Connected to is even an attribute of the sensor: https://imgur.com/a/QQEuAOa

deft timber
#

go in the Tools > State and check the name of the attribute

ivory delta
#

Don't trust what you see in 'more info'

#

Always use the Dev Tools to check states/attributes.

radiant pewter
ivory delta
#

This?
is_state_attr('device_tracker.paulus', 'battery', 40)
That works because it's a number.

#

Strings must have quotes.

radiant pewter
#

@ivory delta @deft timber thanks so much! it should be "connected_to" not "Connected to". I feel dumb but I'm a bit smarter now. Thanks allot for your help, its working as expected now.

ivory delta
#

The UI will try to make it readable. The code doesn't care about readability ๐Ÿ˜„

copper seal
#

Hello everyone, quick question:
Using a command line switch

    command_state: "/usr/bin/curl --digest -u user:pass -X GET http://X.X.X.X/ISAPI/Intelligent/channels/2/behaviorRule/1/notifications"
    value_template: >-
      {% set status = value | regex_findall_index('(?<=id>).*?(?=<\/id>)') %}
      {% if status == "email" -%}
        true
      {%- else -%}
        false
      {%- endif %}
silent barnBOT
#

To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks. Here's an example

Don't forget you can edit your post rather than repeatedly posting the same thing.

For over 15 lines you must use a code share site such as https://paste.ubuntu.com/ or https://www.hastebin.com/.

copper seal
#

What's wrong in value_template?

ivory delta
#

We can't say what's wrong if you don't say what's happening. It would also be helpful if you shared some example values.

copper seal
#

value -> refers to GET result from command_state right?

#

I would like to understant you value_template works: if I want to turn the switch on whats should I put there? and if I want the switch off?

ivory delta
#

And if I don't know what possible values you can get back, I don't know if your template is valid ๐Ÿคทโ€โ™‚๏ธ

oak tiger
#

I wish to control my two covers Aqara switch. One click and it will open/close left one. Two clicks and it will open/close right. It works. But when they are moving and I click again it will not stop them and go back up. I am thinking I need to detect if they are moving. My covers are mqtt based connected to Shelly 2.5 without cloud. How can I tell covers are currently moving?

copper seal
#

@ivory delta thanks for your help friend. My switch was not updating the state correctly. And wont be able to fix it if I dont understant how things work. From GET im getting a xml file. Assuming the value is by default the response from GET applying this regex: regex_findall_index('(?<=id>).*?(?=</id>)') % on var status I will have either or "email" or nothing. If what I said is correct, I understood perfectly until here. My doubt is how to make the switch on? Is the if really necessary? To change the switch state should I use true and false like above?

glossy viper
#

@blazing cradle can u share new code and from where u get svg files ?

blazing cradle
glossy viper
#

u got rid of all conditionals?

blazing cradle
#

yes going from 120+ lines to 22 lines.
Can see that the icons/images look likes these, after i open on in NotePad++ and and search for @keyframes am-weather-cloud-1 on google.
https://gist.github.com/AlexBlack88

But I know it was an weather station i saw em at.

glossy viper
#

i have something similar but for whole dashboard and i thought it could be nicer to have only a weather card

ivory delta
blazing cradle
ivory delta
edgy umbra
#

Hi, anyone can help getting this automation working. It works fine sending a notification to my phone but the available version always is none instead of the latest available version of HACS. Hope that anyone can guide me what I did wrong. ๐Ÿ™‚ https://paste.ubuntu.com/p/GBn3swSSbz/

ivory delta
#

It's because the attribute you're looking for doesn't exist ๐Ÿ˜‰
{{ state_attr('sensor.hacs', 'available_version') }}

#

Check what's in Dev Tools > States. What's in the 'attributes' box for sensor.hacs?

edgy umbra
#

Seems itโ€™s there but under repositories, is that the issue?

ivory delta
#

That's part of the issue.

#

Firstly, it's not at the 'top' level.
Secondly, it's in a list and that list could be in any order.

#

So... you need to search that list for the item where the name is hacs/integration and then get the value of that item.

#

Like this...
{{ (state_attr('sensor.hacs', 'repositories') | selectattr('name', 'eq', 'hacs/integration') | list)[0].available_version }}

edgy umbra
#

Thanks allot, works perfect! I also asked it to @acoustic finch and posted the same. Thanks both! ๐Ÿ˜

dreamy sinew
#

{{ state_attr('sensor.hacs', 'repositories') | selectattr('name', 'eq', 'hacs/integration')|map(attribute='available_version')|first }}

#

slightly safer if you miss

edgy umbra
#

Thanks all! @acoustic finch posted this which is also working fine. Better to use the other one you and @ivory delta posted? {{ state_attr('sensor.hacs', 'repositories')[0].available_version }}

dreamy sinew
#

if you get None or [] back from that attribute, as you have it written it will throw an exception

ivory delta
#

This is true... but he's already using a condition that he can adapt to prevent that ๐Ÿ™‚

#

I'm sure there are better ways to do it in a single template too. I'm a mere padawan.

regal temple
#

I have a sensor which supplies the status as a text. I want to trigger an automation based on the content content of this text. So, if it contains a specific string, the automation should run. I am guessing that a data template should work, based on a text pattern in the string. Would that be possible? And if so... How? ๐Ÿ˜‹

thin vine
#
  trigger:
    platform: template
    value_template: "{{states('sensor.my-sensor') |regex_match('partial-val.+', ignorecase=False)}}"
#

match in this example is starting with, but with some regex magic, this can be anything

clear rivet
#

Good Morning. I am trying to match specific angles of a window or garage door with an Aquara Vibration Sensor. The Sensor has an attribute called orientation that returns three comma seperated, numeric values.

#

The output of this orientation attribute looks like this [ 1, -76, 14 ]

#

I am struggling now to find a way to match the position because the last value differs time to time by one or two.

thin vine
#

something like {{state_attr('sensor.something', 'orientation')[1]}} might work

copper seal
#

Is it possible to console log a value from value_template?

ivory delta
#

You don't have a console, so no...

#

What are you trying to do?

copper seal
#

I'm getting trouble with value_template, and I would like to see whats coming from value to help me debug

ivory delta
#

Is this in an automation or script, or something else?

copper seal
#

It's a Template Switch using command_line

ivory delta
#

Then you'll need to execute the command line yourself to see what is normally returned.

copper seal
#

It returns a xml file when I use curl on cmd

#

based on that curl if word "email" exists switch should be on

mighty ledge
#

ok, then paste the xml files contents into a string named value in the template editor, it's the same thing

copper seal
#

value_template: >-
{% set status = value | regex_findall_index('(?<=id>).*?(?=</id>)') %}
{% if status == "email" -%}
True
{%- endif %}

mighty ledge
#

{% set value = 'contents of email' %}

copper seal
#

That value_template I sent is causing "Update for switch.cam_piscina_mail fails"

mighty ledge
#

so you aren't even going to try what i'm suggesting, just argue?

copper seal
#

I'm going to try and I appreciate it, I just would like to know what I'm doing wrong

mighty ledge
#

again, take the contents of the email and set it in a variable. IF the contents of the email are "HEY MY NAME IS"...

{% set value = "HEY MY NAME IS" %}

then test your template

#

in the template editor

copper seal
#

Sorry petro, i'm not understanding, the GET from command_state returns a xml file. I need to search in that if the word email is present (it appears on xml <id>email</id>, when the motion detection on this camera is active) and use it to correct the status if home assistant restart or in power failure.
value_template: {% set value = "HEY MY NAME IS" %}

#

value_template: {% set value = "email" %} is this your sugestion?

#

sorry for bothering I just started templating a few days ago

ivory delta
#

If you want to test your template, do it in the Dev Tools. To simulate what you would get back from the GET, assign it to a value in the Dev Tools.

#

When you are confident your template works, put it in your value_template:

mighty ledge
#

On the main bar on the left side of home assistant, there's a section called "Developer Tools". Inside that page is a tab named "Templates"

#

That's the template editor

#

it allows you to edit and test templates

copper seal
#

yes petro I already done it

mighty ledge
#

I'm not telling you to put {% set value = "HEY MY NAME IS" %} in your value_template

copper seal
#

it works there

#

but there getting the error

#

can I add a pic here?

mighty ledge
#

now you can

copper seal
#

result is true or false according to xml, which seems nice to me

mighty ledge
#

Ok, so what's the template output

#

on the right hand side

#

can you please pastebin your email

silent barnBOT
#

Please use https://paste.ubuntu.com/ to share code or logs. Please don't use Pastebin, since it can randomly add spaces to the main view.