#templates-archived

1 messages · Page 101 of 1

dreamy sinew
#

need to send a proper json object

#

otherwise REST gets cranky

brazen bronze
#

Any way I can pad utcnow().month to two digits for a month like August (08, not 8)? I'm trying to have an automation curl an api where that's an issue

#

So like dateutc=2020-08-25+04%3A39%3A46 instead of (now) dateutc=2020-8-25+4%3A39%3A46 (please @ me since I'll be AFK for a while)

thorny snow
#

Hello everyone! Looking for a jinja guru to streamline an integration of 17track. How can I add a filter on the below template sensor to only look for entities that contain 'seventeentrack' ?

  sensors:      
    seventeentrack_packages_not_found:
      value_template: "{{ states | selectattr('state','eq','Not Found') | list | count }}"
mighty ledge
#

@thorny snow entity states?

thorny snow
#

@mighty ledge No I want to filter entity_ids. This integration creates multiple entities with names like sensor.seventeentrack_package_lb988831186b3

mighty ledge
#

You'll have to use namespace and a for loop, there isnt' a test that works for selectattr for matching parts of a string

thorny snow
#

I see. I also looked at selectattr and select but couldn't find a way to do it. I thought I may be missing sth

mighty ledge
#

you can try this, it might work:

{{ states | selectattr('object_id[:14]','eq','seventeentrack') | list | count }}
#

the problem with select and select attr is that the use built in tests like "eq" and "==" etc

thorny snow
#

Ok, I will try that thanks a lot!

mighty ledge
#

so you'd need one that is "contains" and that doesn't exist

thorny snow
#

yeah it is pretty restrictive in that way

#

exactly

#

ok thank you so much @mighty ledge will try that and hopefully get somewhere!

keen crater
#

Can somebody help me with my REST binary_sensor? It's a Nuki brudge which returns a json where I want to check the doorsensorState value that tells if the door is open (or not). Currently, the sensor always stays OFF/Closed.

Door sensor status is currently not supported by the HA Nuki integration, that's why I'm building it custom.
Sensor: https://pastebin.ubuntu.com/p/sKDFyXqqzQ/
Example Json: https://paste.ubuntu.com/p/X5dHhYbG66/

mighty ledge
#

value template should be

{{ value_json[0].lastKnownState.doorsensorState == 2 }}
#

can't use is_state because it's not a state object and not in the state machine

#

also, you'd want to make this a binary_sensor

keen crater
#

ahh i see

#

it is a binary_sensor indeed

mighty ledge
#
{% if value_json[0].lastKnownState.doorsensorState in [ 2, 3 ] %}
  {{ value_json[0].lastKnownState.doorsensorState == 3 }}
{% else %}
  Unknown
{% endif %}
keen crater
#

it works like a charm! thanks petro!

mighty ledge
#

np

halcyon ridge
#

hi, is there a way how to make sensor from JSON response for REST API endpoint ?

silent barnBOT
distant plover
#

How do I get just the 'episode' from the list {{ state_attr('sensor.sonarr_upcoming_media', 'data') }} ?

halcyon ridge
#

thx, I didn't noticed that it support other methods

buoyant pine
#

@distant plover would need to see the output of that template

distant plover
chrome temple
#

There are three items in that list, the last two of which both have an episode. Which do you want, and will the list always be the same?

distant plover
#

Well, I kinda used it as an example. I'm creating a sensor from an external API but not sure how I should store the data. So I looked at the sonarr_upcoming_media. And if I can grab 'episode' from that somehow with templating, I may go for a similar approach. To answer your question: Say 'episode' from the second list, and say list will always be the same.

dreamy sinew
#

most seem to 2 part it. 1 to pull the whole payload and another to parse out the attribs into individual sensors

distant plover
#

What I want to store is basically the 10 last bank transfers. Already have the sensors for each bank account. So I'm thinking something like this:

account_id: 23525235232asfasgfasfaf2535
account_number: 23525235235
available: 1000 USD
name: Bank account
transactions: {'26.08.2020: 500 USD from 23523523', '25.08.2020: 100 USD from 233523523', '24.08.2020: -500 USD to 23522352352'}
dreamy sinew
#

might want to edit out those numbers

distant plover
#

Splitting the transactions into date, value and text is probably smarter, but a bit more effort perhaps

#

You mean from discord? They're not real. Just hammered keyboard.

rugged laurel
#

Looks like dummy nubers

dreamy sinew
#

ok cool

distant plover
#

Thanks though.

buoyant pine
#

should have made yourself look like a baller

transactions: {'26.08.2020: 5000000000 USD from 23523523'}
distant plover
#

But templating can easily access nodes with lists down in the hierarchy like that?

buoyant pine
#

yeah, but you need to specify which dict within that list you want to reference

chrome temple
#

The short answer to your original question I think is: {{ state_attr('sensor.sonarr_upcoming_media', 'data')[1].episode }}

buoyant pine
#

right, assuming it's always the second item in the list

distant plover
#

Maaan... [1].episode outside the ()

buoyant pine
#

yep, [1] is specifying the second item in the list (zero indexed) which is a dict that has an episode key

distant plover
#

Yeah, I did all kinds of data[1]...

#

Thanks. Now I know that I can procede with building my sensor. 🙂

silk stream
#

Sounds like me when I tried get the 1st temperature from a weather forecast yesterday 😂

hardy iris
#

im having trouble getting the value of the sensor to translate. im using the mqtt.publish service using this
payload: "states('sensor.ikea_dimmer_brightness')" topic: iotlink/workgroup/htpc/commands/audio/volume

#

but when i look at the value in mqtt explorer it says volume = states('sensor.ikea_dimmer_brightness')

hollow bramble
#

Templates need to be wrapped in curly braces "{{states('sensor.ikea_dimmer_brightness')}}"

dreamy sinew
#

Probably rule 1 too

hardy iris
#

thats weird. when I posted that comment I actually realized that I didnt have the braces and tried it with the braces and it still didnt work

#

but I just copied your snippet right now and it worked

#

I gotta learn more about how this all works. Thanks for your help! 😄

spiral imp
#

is this still a viable template for an automation action:

    action:
      service: script.water_alert
      data:
        alert_title: "Water Sensor Alert"
        alert_message: "Water detected from {{ trigger.to_state.attributes.friendly_name }}"
chrome temple
#

Well, until the change hits a release the makes data_template no longer necessary, you need to change data to data_template.

spiral imp
#

duh...thanks

chrome temple
#

FWIW, you can use trigger.to_state.name which is a shortcut for the friendly name attribute (or the entity_id if the entity does not have a friendly name.)

inner mesa
#

devs are trying to make me obsolete

#

and put the bot out of work

silent barnBOT
silent barnBOT
#

@hardy iris Rule #6: Please do not post codewalls (longer than 15 lines) - use sites such as https://hasteb.in/, https://paste.ubuntu.com/, or others.

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

dreamy sinew
#

If I had to guess it might be a bad unit of measurement

#

Anything in the logs?

hardy iris
#

nothing was showing up in my logs. I followed someone's example on reddit just now and added a "name" field and now its showing up, its just listed as a seperate entity now. But atleast I can see it and I can see the value chaning

solid dock
#

hi, how do i set up a similar template for rgb_color instead of kelvin?

  entity_id: light.entity
  kelvin: "{{ state_attr('sensor.circadian_values', 'colortemp') | int }}"```
violet oyster
#

@solid dock where would you be pulling the rgb_color name from? another sensor?

frozen vale
#

I have a similar setup where I use an input_select. Does not scale wery well to millions of colors, but works fine for a few basic ones

#
    - service: light.turn_on
      data_template:
        entity_id: light.foobarbaz
        color_name: "{{ states('input_select.color_foobarbaz') }}"
violet oyster
#

yeah i have one where tasker sends the color name

#

changes a light color if i get a notification. yellow for snapchat, blue for facebook, etc

tidal eagle
#

Lots of good stuff here! Its like a treasure huntmindblown

tidal eagle
#

I'm fairly new to HA and have found all to often that I have made thing harder than need be. I want to make use of templates to reduce bloat and make maint easier. I see groups and templates but have found a way to use State of a group to trigger a action that refers to the item in the group the triggered to group state. Did miss something or can you offer advice or guide to notification triggered by groups of like devices? Thanku

ivory delta
#

What are you trying to do?

tidal eagle
#

Functionaly, I want to know when doors are opened, when garage doors are opened and left open, when motion is triggered on cameras all sending notifications. I haven't investigated it yet but later I'd like the notification from the camera to cast video, Specifically, I'd like to know which group member state chgd to trigger the group chg. If that isn't doable I will just use the entity's as a list in the trigger

urban walrus
#

Hey - I'm not very skilled in this code syntax and usage. But perhaps some one can help me. If i have a sensor that gives me a message as an atrribute.

last_message: 2020-08-28T18:17:00.175423+00:00: SIA: Code: TR, Type: Tamper Restoral, Description: Alarm equipment enclosure has been closed, Message: 1

How would i use as an example regex to take out the different values in this?
A regex like this i found to be successful (not good perhaps) Code:\s(?<Code>\w+|\d+)|Type:\s(?<Type>\w+\s\w+)|Description:\s(?<Description>.+),

But how would i do such a thing with a template?

chrome temple
#

Not sure HA's Jinja regex accepts all of that, but I found this might do it for you: {% set result = state_attr(ENTITY, ATTRIBUTE)|regex_findall_index("Code:\s(\w+|\d+).*Type:\s(\w+\s\w+).*Description:\s(.+)") %} Then you can use {{ result[0] }} for the code, {{ result[1] }} for the type, etc.

wispy chasm
#

Hi there, is this possible to use templates within configuration.yaml ?

#

I'm trying to build a dynamic input_select entity

chrome temple
#

What do you mean by "dynamic"?

wispy chasm
#

I'm using this declaration in order to build an input selector:

input_select:
  harmony_hub:
    name: Harmony Hub
    options:
      - Powered Off
      - Regarder un film
      - Écouter de la musique
      - Écouter un vynile
      - Regarder un DVD
      - Steam
    initial: Powered Off
    icon: mdi:monitor

And i would like to populate options list with the content of another list, coming form one attribute of anther entity (in this case remote.harmonyhub.attributes.activity_list)

chrome temple
#

You might be able to use a YAML anchor & alias. Wait, never mind. Use a service. See the doc link above.

wispy chasm
#

there maybe a much smarter way of doing this... i'm try to enhance some conf block grabed on a glog

#

Anchors and alias could work if activity_list was declared in the same yaml file, which is not the case. I'm i wrong ?

#

ok

#

I don't really understand how could I use the service. maybe by not declaring options in the yaml, and create/update the attribute through an automation ?

chrome temple
#

You have to declare some initial list of options. (Not sure if it allows an empty list.) But, yeah, you'd use an automation to update the options from the remote attribute.

#

Maybe just start with a list of one entry like Not Defined Yet or something.

wispy chasm
#

ok, like delcaring options: {}

#

ok i'll try that

chrome temple
#

I think you have to have at least one entry in the list. Yep, just verified.

wispy chasm
#

ok thanks for the check

chrome temple
#

options: Not Yet Defined should work.

wispy chasm
#

ok gonna try this thx

solid dock
#

@violet oyster from the circadian_lighting sensor

tidal eagle
#

I'm shamelessly copying code and testing to learn how to create template based automations. Can anyone tell me why

trigger:
  - event_data: {}
    event_type: state_changed
    platform: event
  condition:
  - condition: template
    value_template: '"{{ trigger.event.data.entity_id in (expand(''group.doors'')
      | map(attribute=''entity_id'')) }}"'
  action:
  - data_template:
      message: '{{ state_attr(trigger.event.data.entity_id, ''friendly_name'')}}'
      title: State changed!
    service_template: notify.mobile_app_jeffs_iphone

homeassistant.exceptions.TemplateError: UndefinedError: 'trigger' is undefined

inner mesa
#

you have some quote problems there

#

single quotes, double quotes, double single quotes all mixed up like a salad

tidal eagle
#

Thanks - I think its time for me to move on from using the UI and cutting and pasting into it. I'm temporarily one handed but this is second time you've pointed this out.... walk of shame

oblique raptor
#

I'm looking for a way to save the data of a sensor at a certain time to use it in a template. How can this be done.

wispy chasm
#

Hi, as advised by @chrome temple i'm using this to template options of an input_selector through the input_select.set_options service.

data_template:
  entity_id: input_select.harmony_hub
  options: '{{ trigger.to_state.attributes.activity_list }}'
service: input_select.set_options

It basicaly works but seems to return a string and not a list. I've tried to add |list filter but the result is the same (or look the same : a string containing a pyhton list declaration)

#

I've tried several things, like iterating to build a yaml list, but nothing works so far.

#

Any idea ?

ivory delta
#

You can't get it to make YAML. YAML is a representation of data structures in text form - once they're loaded by HA, you're dealing with lists and dictionaries.

#

A possible answer was already given yesterday. Look at maps.

wispy chasm
#

ok, i've tried to deal with map but it seems i did not yet understand how to 😦

chrome temple
#

You need to use a python_script

wispy chasm
#

I'll look into this post

ivory delta
#

Yeah, Python script seems about the only reliable way to get around the limitations of Jinja templates always returning a string.

#

If an integration can automatically cast a string to the data type it needs, great. Otherwise, you're expected to provide the correct data type.

wispy chasm
#

understood

chrome temple
#

I'm on my phone so can't provide more details. Just search the forum for python_script and input_select and you'll probably find an example.

wispy chasm
#

Right, thanks again 🙂

tribal rock
#

I'm having some trouble passing an array from an event to a template light.
The event correctly shows

"service_data": {
  "hs_color": [360, 0]

But trying to pass that into a template is not working, returning homeassistant.exceptions.TemplateError: UndefinedError: 'hs_color' is undefined

data_template:
  h: "{{ hs_color[0] }}"
  s: "{{ hs_color[1] | round }}"
  v: "{{ ( state_attr('light.strip', 'brightness') / 2.55 ) | round }}"
silent barnBOT
ivory delta
#

Where are you using that data template? I don't see it in the rest of your code wall.

#

Also, don't forget the rules

silent barnBOT
#

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

tribal rock
#

Ah, okay, I'm sorry about that @ivory delta. I didn't know if it was 15 lines per snippet or collectively
I will be sure to review the rules, looks like I'll be on here often 😅

ivory delta
#

The 15 lines is because looking at any wall of text is annoying, especially for mobile users.

tribal rock
#

That's understandable

#

The data_template in question is used in the configuration of a Template Light, under the set_color action

ivory delta
#

It would help if you shared that config upfront too if it's the core of your problem.

#

But the error message it's giving you is all you need to know. You're asking it to read from a variable called hs_color that doesn't exist in that context.

#

Don't share pictures of text.

silent barnBOT
tribal rock
#

sorry..

ivory delta
#

If you're going to share, share via one of those tools.

#

Or don't... but then you won't get the help you came for.

tribal rock
#

I'm installing haste on pi, for future use as well

ivory delta
#

There's no need to install anything. You just copy/paste into the website, hit save, share the link it generates.

tribal rock
#

Hmm, formatting seems off though

tribal rock
halcyon ridge
#

Hi, I want to filter out 0 values, so I've created this template, but it does not work. My sensor is zeroed during night. Why ?

  sensors:
    covid19_sk_daily:
      value_template: "
      {% if state_attr('sensor.covid19_sk', 'dailyConfirmed') != 0 -%}
        {{ state_attr('sensor.covid19_sk','dailyConfirmed') }}
      {%- endif %}"
      entity_id: sensor.time
      friendly_name: "Daily cases"
      icon_template: "mdi:arrow-up-bold"      
      unit_of_measurement: "people"```
inner mesa
#

What do you want it to report if the number is zero?

#

You’ve only told it about what to do if it’s non-zero, but not what to do when it is zero. It comes down to what you mean by ‘filtering’

#

You just want it to report the previous value?

#

I would use an input_number and an automation based on sensor.covid19_sk to update the count if it’s non-zero

halcyon ridge
#

yes, if it is non zero, update sensor with current value, if it is zero, skip, use previous value

inner mesa
#

Ok, see my last comment

#

I don’t think a template sensor is the right tool for this job

wispy chasm
#

@ivory delta and @chrome temple I've finally used a rest_command to update input_select like some others did in the thread you pointed me too. Works fine and it's pretty easy to setup. I'll look into python_script next time.

#

I end up with 3 automations, where i was using 2 automations and one script for each input... and the previous config was static where the new one is updated from the harmony hub states

#

way better then 🙂

chrome temple
novel vortex
#

Hello, so this is the scenario I am trying to figure out.

my water geyser has a rotating knob (already fixed a dc motor which works fine).

I want to set 3 steps, Low, Med, High by using rotation timing of the motor, e.g, 2s from med to high (middle to left).

How to deal with the complexity of let say making it know when it is on med, low or high so it moves accordingly. As in, having 3 button setup on HA, simple M L H, pressing M while it's on L, takes it to M and when pressed M again, it stays where it is.

Hope it makes sense. Thanks

inner mesa
#

you posted this same thing yesterday and I thought got some responses

#

are you looking for help with the UI part of it?

#

is a geyser a fountain?

hybrid spoke
#

Hello everyone! I have unsoldered the non-esp8266 wifi module and replace it with a esp8266 running tasmota on this gateway and I have most it it working thought console. https://www.aliexpress.com/item/4000303875313.html?spm=a2g0o.cart.0.0.5d773c004jMgEY&mp=1

The last bits of the message is a checksum for example to change the temperature: 55aa000c000f0633323137343502020004000000d230
06333231373435 is the ID of the TRV is going to control, D2 is the temperature I want to set and 30 (the last 2 bits) is a checksum of the rest of the message which can be easy calculated here https://www.scadacore.com/tools/programming-calculators/online-checksum-calculator/

Is it possible in HA somehow to calculate the checksum of the message?

mighty ledge
#

@hybrid spoke If it's a simple calculation, yes. If it's hidden behind that company, no way to know without reverse engineering.

hybrid spoke
#

@mighty ledge the payload is 55aa000c000f0633323137343502020004000000 atm I have it converting with {{ my_test_json['test'] | int(base=16) }} which results in a payload 489055346287242978748645544381040812968793604096
is now possible to sum all those numbers together with a template?!

mighty ledge
#
{% set v =  my_test_json['test'] | int(base=16) %}
{{ v | string | list | map('int') | sum  }}
#

@hybrid spoke are you sure you want to sum the ints? Wouldn't you want to sum the values of 55aa000c000f0633323137343502020004000000 ?

#

You get 2 very different results.

hybrid spoke
#

yes @mighty ledge that's what I'm understanding now

mighty ledge
#

What's the expected value of 55aa000c000f0633323137343502020004000000, 111?

hybrid spoke
#

55aa000c000f0633323137343502020004000000d230 this is the complete message

#

i should get 30

mighty ledge
#

Yes, but what do you expect as a sum

#

Ok, that's not what I would expect

#

what checksum equation are you using

#

I have no idea how you exepct to get 30 out of that. All the checksums listed on your link are much much higher.

hybrid spoke
#

@mighty ledge i need to sum all the byte values the result and the last byte should equal the result modulo 256

#

do i make sense?

jagged obsidian
#

Checksum = Byte-sum results from the beginning of the frame, 256 remainder

mighty ledge
#

you'd be better off making a python script

#

aslo modulo 256 still doesn't return 30 as a result with that value.

hybrid spoke
#

I'm already struggling with a template @mighty ledge 😅

mighty ledge
#

it's not the template that you're struggling with it's the equation

#

and your expected value

#

None of the checksums that i've tried result in 30.

#

also, they are infinitely easier in python opposed to jinja

#

Anyways, going off what appears to be modulo 256, I get an answer of 139

#
{{ my_test_json['test'].encode('ascii') | sum % 256 }}
jagged obsidian
#

its a sum of all bytes then mod 256

mighty ledge
#

yes, the problem is he says he expects 30

#

my jinja template does a sum of ascii bytes and mod 256 directly above your post

jagged obsidian
#

that message is likely not following the proposed spec for checksum

hybrid spoke
#

sorry trying to work it out on excel, but the @jagged obsidian they follow or at least on the checksum calculator they all match 55AA000C000C063332313734356501000100ba taking ba out will result on modulo 256 ba

#

thanks alot @mighty ledge

jagged obsidian
#

let's take it from the top: how can i turn a string 55aa0003000103 into a list of 55,aa,00,03,00,01,03?

mighty ledge
#

If you're trying to support a beginner, asking that is basically talking about magic.

rugged laurel
#
{% set string = namespace(input="55aa0003000103" | list, output=[]) %}
{% for x in string.input %}
{% if string.input[0:2] %}
  {% set string.output = string.output + [string.input[0:2] | join("")] %}
  {% set string.input = string.input[2:] %}
{% endif %}
{% endfor %}
{{ string.output | join(".") }}

There must be a better way

mighty ledge
#

lol I can’t think of one

#

If regex findall returned a list we could do it in 1 line

#

But whoever made that forced it to be a single index

hybrid spoke
#

i was close then {{ my_test_json['test'] |join('[2]) }} lol

rugged laurel
#

findall would definitly work (I tried that first and got the same problem)

hybrid spoke
#

and the results match the given checksum

#

is it possible to have that calculation on a template?

mighty ledge
#

@hybrid spoke

{%- set input = "55aa000c000f063332313734350202000400000037" %}
{%- set string = namespace(input=input | list, output=[]) %}
{%- for x in string.input %}
{%- if string.input[0:2] %}
  {%- set value = string.input[0:2] | join("") | int(base=16) %}
  {%- set string.output = string.output + [ value ] %}
  {%- set string.input = string.input[2:] %}
{%- endif %}
{%- endfor %}
{{ string.output | sum % 256 }}
#

don't see how it will work if your last value is 3 characters or 2 characters and there's seemingly no way to know that.

#

Er, nevermind, i read your excel sheet wrong. that code should work.

hybrid spoke
#

thank you a lot!! I'm gonna work out the rest and test

distant plover
#

I have this template that shows date, amount and text of a transaction: {{ state_attr('sensor.account_241412412', 'transactions')[2].accountingDate[:10] }} | {{ state_attr('sensor.account_241412412', 'transactions')[2].amount }} kr | {{ state_attr('sensor.account_241412412', 'transactions')[2].text}}
I'm using it in markdown card in Lovelace and it's working fine. But how can I have another line with transaction number [3] without corrupting the entire card if there is no transaction number 3?

mighty ledge
#

Make a for loop and iterate based on the number of transactions

distant plover
#

I was just about to ask if that was the way 🙂

mighty ledge
#
{%- for transaction in state_attr('sensor.account_241412412', 'transactions') %}
  {{ transaction.accountingDate[:10] }} | {{ transaction.amount }} kr | {{ transaction.text }}
{%- endfor %}
tidal eagle
#

SOLVED!!!!! I have several automations that I c/want to/can now/ check a group of entities binary sensor for change and send a notification, By following examples I've gotten an automation to send a notif for any state_chaged in a particular group but I need to constrain the notif to "on" status for the sensor and have been unable to so after many tries at copying examples. I've also reviewed https://www.home-assistant.io/docs/automation/templating/ several times over several days. Can anyone suggest how I can better understand the nomenclature of triggers in an automation or other documentation and examples?

- event_data: {}
    event_type: state_changed
    platform: event
  condition:
  - condition: template
    value_template: '{{ trigger.event.data.entity_id in (expand(''group.doors'') |
      map(attribute=''entity_id'')) }}'
  - condition: template
    value_template: '{{ trigger.event.data.entity_id.new_state == ''on'' }}'
  action:
  - data_template:
      message: '{{ state_attr(trigger.event.data.entity_id, ''friendly_name'')}}'
      title: Door opened
    service_template: notify.mobile_app_jeffs_iphone
dense wing
#

Hello,
I have a timestamp in a MQTT topic. How can I create a rule that triggers 5 minutes before that timestamp?
I allready set up a time_date sensor, but unfortunately, I don't know how to compare the current timestamp with the one from the mqtt topic.

slim sage
#

Anyone have a decent example of mapping one number to another? I want to use the Circadian Lighting value, which goes between 100% and -100% approximating the sun's elevation, to adjust the saturation of a color. My present goal is a blue accent light, which adjust slowly throughout the day to be a cool blue (nearly white) at solar noon, and is a deep saturated blue in the middle of the night. When I figure this out, I'll work on adjusting its brightness separately. Ideally, I'll use the UI to adjust the solar noon color and brightness and solar midnight color and brightness, and I'll have a light template track this color, then I'll assign one or more Philips Hue lights as "accent lights" which track this accent color. Any help with this task would be appreciated.

violet oyster
#

@slim sage dont mean to be rude but that question is way too broad to get an answer here. you'd need to show what you've tried and be asking why it didn't work. if you want guidance on broad concepts like this you'll have better luck on the subreddit or HA forums

#

only thing i can really say is manually adjust the light to match the current circadian value and then build a template to return the thing you want

mighty ledge
#

@slim sage there’s a custom circadian lighting integration that you can use.

silent barnBOT
lyric night
#

So what I was saying is that my templating works fine in the templating page but not with a sensor, code in link above

distant plover
#

Maybe this is a #frontend-archived question, but what does one do with templating in the markdown card if it's an interation over a null value because the entity isn't initiated yet? I'm getting a TypeError: 'NoneType' object is not iterable. Here is the iteration: {%- for transaction in state_attr('sensor.account_214242', 'transactions') %} {{ transaction.accountingDate[:10] }} | {{ transaction.amount }} kr | {{ transaction.text }} {%- endfor %}

rugged laurel
#

Just slap a or [] in the for statement

lyric night
#

@rugged laurel sorry to ping but do you have an idea for my issue ? been searching since yesterdayy :/

distant plover
#

Haha. That crashed HA. Just spinning. You meant like this? {%- for transaction in state_attr('sensor.account_214242', 'transactions') or [] %} {{ transaction.accountingDate[:10] }} | {{ transaction.amount }} kr | {{ transaction.text }} {%- endfor %} EDIT: Nevermind. It crashed because I had manually set the values of the entity to something really invalid. I was able to find this in logs: AttributeError: 'str' object has no attribute 'keys'

rugged laurel
#

Yeah, that worked in my test

distant plover
#

A restart of HA fixed things and no errors in log on this matter anymore. Thanks a bunch.

rugged laurel
#

if it fails, you can use this instead | default([], True)

lyric night
#

How is it possible that a manually defined templating does not render as the exact same templating (copy/paste) set within a sensor and that this same sensor does not render the same result through templating page and the real entity ? This makes me crazy

#

i wish someone achieve to explain this to me

novel vortex
#

you posted this same thing yesterday and I thought got some responses
@inner mesa no, I was redirected here. Not just the UI, more of "how-to" guide. It's a water boiler/geyser. Thanks

burnt silo
#

@lyric night It looks like you're using {{ states("volet_roulant_salon_status") }} in the template page to check the value of the template sensor, however, the entity id will be sensor.volet_roulant_salon_status so you should be using {{ states("sensor.volet_roulant_salon_status") }}

dense wing
#

`- id: '1570917544192'
alias: Lichtwecker
trigger:

  • platform: template
    value_template: >
    {% set time_now = as_timestamp(now()) %}
    {{ time_now >= ( **MQTTValue **- 900 ) }}
    action:`
#

But unfortunately I haven't found any possibility to get the MQttValue

lyric night
#

oh you're right

#

but the state is still not the same between the sensor and templating 🤔

ivory delta
#

now() is not continually updated in templates, so your sensor won't update either.

#

You'll need to use something like the datetime integration.

silent barnBOT
ivory delta
#

For templates to be re-evaluated, at least one of the entities within that template has to change. now() is not an entity and I assume your MQTT value remains mostly static.

lyric night
#

@ivory delta is this for me ?

ivory delta
#

I don't see anyone else wondering why their template isn't updating...

#

Wait, I do. D'oh.

#

What's the problem with yours, repz?

lyric night
#

i don't have the same value between the sensor i declared and the same templating in the template page

ivory delta
#

What values do you have?

burnt silo
#

@lyric night I notice that you have entity_id: [] in your template sensor. That option is used to override the default detection of entities to track for changes for a template, so I would assume that this would stop it from working as it is telling it not look at any entities.

ivory delta
#

But unfortunately I haven't found any possibility to get the MQttValue
@dense wing You'll need to set up an MQTT sensor. Check the integrations page to see how.

#

That link doesn't work for me, repz.

lyric night
#

ok that was the entity_id, thanks a lot @burnt silo

ivory delta
#

But what states does the sensor give? And what are you trying to do?

lyric night
#

and mono

#

the states it was giving is in the screenshot

ivory delta
#

Ah. So it works when you remove entities: []?

lyric night
#

half-open

#

while it is in fact open

#

yes

ivory delta
#

Awesome

lyric night
#

made me craZY

ivory delta
#

I'm glad Steven was paying attention. I haven't had coffee yet 😄

lyric night
#

thanks a lot

dense wing
#

@dense wing You'll need to set up an MQTT sensor. Check the integrations page to see how.
@ivory delta ok thank you. I managed to build up the following:

#

{% set time_now = as_timestamp(now()) %} {{ time_now >= ((states.sensor.alarmtime.state | float ) - 60.0) }}

#

If i paste it to the template check in the web interface it says true ore false as expected. However the rule still not fires 😦

cerulean cipher
#

mono please go have some coffee

ivory delta
#

No need, I'm awake now. 😉

cerulean cipher
#

well awake /= !grumpy

#

😛

ivory delta
#

But they're using a template with only a single entity that doesn't change... of course it'll never trigger their automation 😄

cerulean cipher
#

LOL

dense wing
#

Thanks for your replies, I finally managed to get it working 🙂

stuck tundra
#

Hey, how can i day "now-7days" in template ?

cerulean cipher
#

now - 7 days?

#

as in one week ago?

stuck tundra
#

yes

#

i have a sensor giving me my weight, i would to make a delta with my weight from a week ago

chrome temple
#

Some more details and/or context might help. E.g., what format do you want the result of the template to be in? Where is it being used? In a template sensor configuration, in a service call in an automation or script, ...?

#

Do you have any existing code that you could share, even if it doesn't exactly work yet?

stuck tundra
#

ok! I don't have anything yet, i'm more planning and try to figure how to do it. Maybe template is not the best solution for that, i'm kind of a newbie in creating sensors etc...

So I have a sensor from withings giving me my current weight in an entity, tracked by the history component. My dream would be to make a sensor that gives me the average value of day-1 to day-8 (yesterday+one week) so that I can compare how my weight has evolved in comparaison to the average of the last seven days (which is more significant that comparing one day to another day).

chrome temple
#

Yeah, sounds like you should be asking for help on the community forum instead. 😉

stuck tundra
#

So TLDR an average of a value based on X days of history

#

Ok, just wanted to make sure I didn't miss something obvious, thank you!

ivory delta
#

There's always the existing statistics integration.

chrome temple
#

Well, not saying you can't get a useful response on discord, just that when asking strategy questions, it's a little harder to answer here. At least maybe try #integrations-archived ???

stuck tundra
#

There's always the existing statistics integration.
I'm going to check this integration 🙂 ty

#

Well, not saying you can't get a useful response on discord, just that when asking strategy questions, it's a little harder to answer here. At least maybe try #integrations-archived ???
yeah obviously, I was just thinking maybe i'm missing a simple function somewhere, but I understand that my question is not just "easy" to answer if there's no obvious function available to get some stuff ^^

ivory delta
#

Nah, you just need to be clear about the problem you're trying to solve. You've done that now and it sounds like there's an existing solution for you. That integration will give min/max/mean/etc over a specified period.

stuck tundra
#

Statistics would be perfect if I could just skip one day (today)... But i can start with that and think about a solution later to make it perfect! Thank you

ivory delta
#

Another option would be to use Influx/Grafana magic.

stuck tundra
#

You just made me realize i could use SQL...

tribal rock
#

I'm having trouble using a template message with Google Cloud TTS, is it specifically not supported?
When I try, it returns Failed to call service tts/google_cloud_say. extra keys not allowed @ data['data_template']
Using the dev tools to call the service for testing:

entity_id: media_player.kitchen
data_template:
  message: "Good morning, it's {{ now().strftime('%A, %B %-d, %Y') }}"
  cache: false
buoyant pine
#

You can't use data template at dev tools > services

tribal rock
#

oh

buoyant pine
#

That text field is the data: field

tribal rock
#

Right, silly me. Is there an alternative for testing?

buoyant pine
#

All good. Unfortunately you'll have to make a script with what you want to test, or if you just want to see the output of the template, use dev tools > template

#

In 0.115 data_template: won't be required anymore, so theoretically templates should work at dev tools > services then

tribal rock
#

Yep, I verified its the correct output in the Template pane, but I want to make sure the TTS engine is using the correct verbage

#

ooo, now I'm looking forward to that release 🙂

slim sage
#

Anyone here mess with lights much? I have a value that approximates the sun's elevation that goes between 100% and -100%. I want to define a color/brightness at solar noon, and another color/brightness at solar midnight. Then I want to create a color/brightness (i.e. the "accent color") that blends the two inputs based on the sun's elevation. Then I intend to set one or more physical lights (e.g. Philips Hue lights) to be this accent color (with an automation that updates it every minute or so). The end result is a bulb that smoothly transitions between two desired colors/settings throughout the day. I'm not sure if I should be using complex templating to define the solar noon and midnight colors/brightnesses, or light templates (the latter would be better I think). Should I be using a light template to hold the "accent color" and just set up automations to follow it? I'm getting started but I'd love input from anyone with ideas.

#

I'm also struggling to get a color picker to work for a light template.

violet oyster
#

@slim sage did you try what was suggested when you asked about this yesterday?

#

seems like you are trying to reinvent the wheel maybe

slim sage
#

@violet oyster Thank you, I tried to not clutter the already cluttered question. I am familiar with Circadian Lighting, and use it throughout the house. Several rooms have LED strips and such intended to provide accent lighting. My ultimate goal is provide accent lighting to works alongside Circadian Lighting, and emulates its features but for a color or palette. This way, for example, the accent light LED strip that makes a wall look very good when teal can be a bright desaturated cool white in the middle of the day, but as evening rolls along, the light becomes a deep heavily saturated teal. Ideally, the actual color (e.g. teal) of the accent lights, and perhaps secondary lights, can be automated to go along with the outside light and weather conditions. So on darker days, the colors are allowed to be more saturated, but on bright sunny days I want it to feel bright inside.

violet oyster
#

oooooooh i finally understand what you are trying to do

slim sage
#

My thought for the easiest first approach at the moment is to set two colors/brightnesses and assign them to solar noon and solar midnight, and then use the Circadian Lighting sensor value (which goes from 100% to -100% following the sun's elevation) to blend between them. I can use Node Red to do all of the automations, like updating the sensor value every 60 seconds, etc. I was hoping to set the solar noon/midnight colors using template lights and a color picker, but I can't get that to work because you cant use a color picker on a light template! So I'm still trying to figure out how to make the UI for this wife-friendly.

violet oyster
#

you dont want the accent lights to be circadian, you want them to simply react to the circadian changes and become a different color altogether

slim sage
#

Yes! Or rather, to "follow" the circadian changes, so that the accent light's saturation and brightness track the circadian value that the rest of the lights are using.

violet oyster
#

cool idea

slim sage
#

Basically, Circadian Lighting adjusts color temperature throughout the day. I want it to instead adjust saturation :).

violet oyster
#

i'm thinking...

#

what field do you usually use to set 'saturation' on the accent lights? rgb_color?

#

and about how many different settings would you need?

#

i mean you could just make several scenes with the lights at the color saturation you want and then use an automation to activate the scene when the lighting sensor value changes

#

the problem with trying to template this is that templates always return a string, which can't be used to set rgb_color in the light.turn_on service. so you'd need to pre-define the rgb_color you want somehow (using scenes or scripts) and then call that in an automation. unless I'm missing something (which is entirely possible)

#

you could template if you are using color_name instead of rgb_color but then you can't adjust the saturation like you want to

#

the user who responded gave an idea of how to maybe do it but i've never tried that. give it a look

slim sage
#

Apologies, I was called away for a bit. I'll check out your link, thank you for the ideas and input!

violet oyster
#

let me know if you figure it out. its a cool idea

brisk temple
#

I have National Weather Service integration setup. In it, they have a daily forecast, one that is ongoing every hour and another that is at 18:00 hours. It also lists tomorrow at 06:00 hours and 18:00 hours. What I am trying to do is store the next day's 06:00 into a template sensor which I can grab in an attribute_template {{ state_attr('weather.kiad_daynight', 'forecast')[2]['detailed_description'] }} but when that no longer matches, it just blanks out the sensor attribute.

#

How can I get it to not blank out the template sensor and keep the correct value? If it was an automation, I'd use a condition so it wouldn't run

mighty ledge
#

@brisk temple add an else statement referencing the attribute, it will pull the past data. {{ state_attr('sensor.daily_forecast', 'forecast_6pm') }}

brisk temple
#

ah perfect, thanks!

heady tulip
#

hey there,
i'm wondering a thing, and need to find an answear on how to change a timestamp data recieved from a sensor. To human readable thing.

Oregon Update Time 1599063410
it's configurated on a .yaml file
i have found a lot of converter, but don't know howto use it . :\

dreamy sinew
#

{{ as_timestamp(states('sensor.your_sensor')).strftime("your format here") }} iirc

#

searching strftime in google should get you the formatting arguments. Should also be a link to it on the template docs

heady tulip
#

Thanks, this had to be cp un configuration.yaml ? Or in sensor.yaml ?

dreamy sinew
#

depends on what you are doing. What integration are you using?

heady tulip
#

it's an rflink sensor

#

Oregon

#

oregontemphygro_228c8_update_time:
sensor_type: timestamp
name: Oregon Update Time

#

It's for print the up time in lovelace card 🙂

dreamy sinew
#

gotcha. you're probably going to have to create a template sensor from that then

heady tulip
#

Oh thnx, i will try to learn how it works.

#

I have never created template 😄

dreamy sinew
#

if you want to play around with it without having to restart your instance a ton of times you can use devtools > Templates

heady tulip
#

devellopement tools, ok. I'm using Hass core in docker. And it's in french xD

#

it's the 4th ?

#

i have etat, Service Modèle Evenement

#

oh, it's modèle i think

dreamy sinew
#

should be the 3rd of 4

heady tulip
#

yeah i think is the 3rd ( they are line code )

#

i didn't know that was an test area 😄

#

thanks 🙂

dreamy sinew
#

np!

heady tulip
#

I'll be back , i'm gonna eat 🙂

nimble marten
#

can anyone help me with my google calendar event

#

if so pm me

silent barnBOT
#

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

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

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

on a template sensor how do I make sure 0 is represented as 0 not None? I need to do math on that number in other places and now I end up with nan because I need a number.

dreamy sinew
#

What's the logic you are doing?

cerulean cipher
#

pass it to |int?

rose brook
#

Okay, not sure if i am in the right spot. Also a warning I am like level 0 HA ninja at this point...

I am trying to make a Sim Garage Door Opener like I had in Samsung's DumbThings. I am trying to combine an sensor.garage.acceleration + binary_sensor.garage.contact and a switch.garage.

Id like to be able look at the garage Icon and see when open when its closed and show when its in motion. I have searched the web and have only found peeps that combine binary_sensor.garage.contact and a switch.garage

inner mesa
#

you're not

rose brook
#

Roger, thought I would need to make a template for this to work. Again, it scares me how much I DONT understand....

inner mesa
#

you might, but first have a plan for getting the icon to do what you want, and then figure out what it needs to do that

dreamy sinew
#

Hmm is there a door template?

hollow bramble
dreamy sinew
#

That's the one

#

Looks like it doesn't take "opening/closing"

hollow bramble
#

maybe if you have a position template defined

inner mesa
#

I think it could be done with a custom button card and icon templates. Or state customization

small roost
#

i am feeling really dumb regarding value templates

#

the formula for a new EPA wildfire AQI for the purpleair sensor is going to be 0.524 * purpleair_pm25 - 0.0852 * purpleair_humidity + 5.71. I'm trying to define a new sensor in my config yaml copying from some other examples, but its not working.

#

i feel like im writing a gopher phlog

#

do i even do this w/ a value template? the value of new sensor = existing sensor 1 * 3 + existing sensor 2

#

sensor is probably not even the right word to use

buoyant pine
#

Your value template should look something like

"{{ (0.524 * states('sensor.purpleair_pm25') | float) - (0.0852 * states('sensor.purpleair_humidity') | float) + 5.71}}"
silent barnBOT
honest mauve
#

Hello

#

I have a for on my switched

#

and I want to set a variable to count

#

"x" in the example

#

the x gets increased to 1 in the first loop

#

but then it's always 1... doesn't increase

#

seems like it always do 0 + 1 = 1

#

do you know why?

#

What I want to achieve: create an inline_keyboard of commands... with 2 commands per line (telegram bot)

mighty ledge
#

Jinja doesn’t allow scoping outside loops

#

You’ll have to use namespace to make a counter

honest mauve
#

like?

mighty ledge
#

{% set ns = namespace(x=0) %}
{% for i in range(5) %}
{% set ns.x = ns.x + 1 %}
{% endfor %}

honest mauve
#

I'll try

#

thanks

#

It works, thanks

#

How can I easily remove the last comma?

#

@mighty ledge

mighty ledge
#

You can try if loop.last but it may not work. My personal recommendation is to look into using filters like select, select_attr, reject, and reject_attr instead of your current approach. I don’t have examples because I’m replying on mobile

#

Basically, filter your search down. Then map the attribute you care about, then join the list of strings with a comma

honest mauve
#

I'll try loop last

#
    data_template:
      title: '*Controlla lo stato delle luci...*'
      message: Accendi o Spegni le luci
      data:
          inline_keyboard: >-```
#

The template doesn't seem to work properly

#

If I copy and paste the result of the code, from the developer, model page and I invoke the service

#

the inline_keyboard work properly

#

if I use it with the template, it's not formatted properly

#

It seems I'm not able to set a list of items "-" with the \n option

#

All inline keyboard are on one line....

#

@mighty ledge do you get what I mean?

small roost
#

Your value template should look something like
Thanks @buoyant pine i was confused (obviously) about whether states() applied to numerical values or only like on/off. Also didn't expect to have to declare the variable type

mighty ledge
#

@honest mauve Templates only return a single string. inline_keyboard requires a list of strings. It will be impossible to do what you want it to do dynamically because of that reason.

#

You should use a python script instead to get the job done.

honest mauve
#

what a pity 😦

#

What if I try to remove the "-" ?

mighty ledge
#

doesn't matter, inline_keyboard requires a list. Templates only return single strings.

#

I'm not sure why you don't want to use a python script, the code would be almost the same.

honest mauve
#

I never used one

#

I need to understand how to integrate it

#

inside automations.yaml

#

😦

mighty ledge
#

it acts as a service

#

so you just call the script as a service. All of this is described in the python_script integration

honest mauve
#

I can do it within script.yaml?

mighty ledge
#

No, it’s a python script. Just check out the docs

honest mauve
#

I wlll

#
    platform: event
    event_type: telegram_command
    event_data:
      command: /controlloluci
      chat_id: 808687121```
#

About this... can I make the "command" a template, inside automation.yaml?

#

@mighty ledge

#

I also saw the syntax of Python scripts... it's not just a copy and paste

#

I don't get how to transform the loop template into a python script

#

would you help me?

silent barnBOT
inner mesa
#

It’s just Python at that point

small roost
#

i thought i could round the whole thing outside of the braces. do i need to round each value individually after | float? like | float | round(2)

inner mesa
#

Your curly braces are in the wrong place

#

You need to surround the whole expression that you want to round and then filter with ‘|round(2)’

#

Hard to tell with the curly braces messed up, but it looks like you’re just rounding the last part

small roost
#

oh hey the web ui file editor shows you which braces go together. thats handy.

#

i was using notepad.

inner mesa
#

Gack. Yeah, use a real editor 🙂

small roost
#

well i have about 14 tabs open in notepad++ and i thought oh this is simple i'll just copy/paste into notepad

inner mesa
#

oh, Notepad++ is better than "notepad"

#

anyway, did you get what I was saying about grouping and then rounding?

small roost
#

yeah i thought i had done that honestly by putting it right inside the outermost brace. but do you group them with regular parens?

dreamy sinew
#

yep, normal pemdas but | are after ()

inner mesa
#

I think you want this:

#

"{{ ((0.524 * states('sensor.purpleair_pm25')) - (0.0852 * states('sensor.purpleair_humidity')) + 5.71) | round(2) }}"

dreamy sinew
#

need to cast the two states() calls to |float

#

otherwise string math

inner mesa
#

oh, yeah. I removed that, but you need them because they're strings

#

sorry

small roost
#

this is what im trying, restarting now. value_template: "{{ ((0.524 * states('sensor.purpleair_pm25') | float) - (0.0852 * states('sensor.purpleair_humidity') | float) + 5.71) | round(2)}}"

inner mesa
#

optimization kills 🙂

small roost
#

hey it works

#

now i need to add a state for when it first starts up and there are no values for sensor.purpleair_pm25 so it doesnt report just 5.71

#

state isnt the right word

distant plover
#

I'm using value_template: '{{ trigger.to_state.state | int > trigger.from_state.state | int }}' as condition to notify me. But when I try to use the value as title in the notify service it just says 'trigger' is undefined. title: '{{ trigger.to_state.state | int - trigger.from_state.state | int }} moneys.' What am I doing wrong?

inner mesa
#

you're probably not using data_template:

#

but would need to see the rest if you are

hollow bramble
#

Or you're not using an automation/trying to manually run it without a trigger

distant plover
inner mesa
#

you're probably not using data_template:

#

or, you're just executing it from the UI

#

but probably the former

#

because you're clearly not using data_template:

silent barnBOT
distant plover
#

Thanks. That did it.

vagrant monolith
#

Hey!

#

How could i possible take this Fri Sep 04 06:45:00 GMT+02:00 2020 and change that to a time like 06:45:00 ?

#

I want a hour:minute state from the next alarm in android companion to an template sensor

dreamy sinew
#

looks like a timestamp already. whats it coming from?

keen crater
#

Question; im using the DSMR power meter which publishes the timestamp over MQTT. The thing is, my power meters time is 41sec's early, and because it is out of my control, I want to try to correct it by substracting 41 seconds from the published timestamp. The device class is timestamp. I think I'm nearly there.. sample incoming timestamp: 2020-09-03T23:06:24+02:00
value_template: "{{ strptime(value) - strptime(41, '%S') }}"

vale nymph
#

hey, @vagrant monolith I just happened to be messing with something like that myself, and this is what i came up with:
value_template: "{{as_timestamp(states('sensor.sm_g930p_next_alarm')) | timestamp_custom('%X') }}"
or
value_template: "{{as_timestamp(states('sensor.sm_g930p_next_alarm')) | timestamp_custom('%H:%M:%S') }}"
just replace the sensor with your phone and you should be all set

soft coral
jagged obsidian
#

Noone clicked the edit button to say that

mighty ledge
#

@keen crater wrap the strptime in a as_timestamp. The subtract 41. Wrap that in quotes an convert it to timestamp_local

#

@soft coral it does return a timestamp, if it’s returning a string you’re using the function wrong

dreamy sinew
#

strptime string parse time, input a string, get a datetime object
strftime string format time, input a datetime object, get a string in your format

mighty ledge
#

Unless strptime fails to convert based on a bad format. when it fails it returns the string that was input

dreamy sinew
#

True, that was a happy path description

mighty ledge
#

what's happy path?

dreamy sinew
#

Meaning that's what happens when you do everything right

mighty ledge
#

Ah ok, i started googling happy path and I found something similar to nodered

#

definitely through me in a confused path

dreamy sinew
#

Lol sorry 😛

soft coral
#

Unless strptime fails to convert based on a bad format. when it fails it returns the string that was input
@mighty ledge Here it is! That was very confusing, honestly.

honest mauve
#
    platform: event
    event_type: telegram_command
    event_data:
      command: /controlloluci
      chat_id: 808687121```
#

Hi all, is there a way I can make the command a template?

#

@mighty ledge

inner mesa
#

Generally frowned on to randomly tag people

vale nymph
#

^^^ Why is this not in the docs 🙂 Spent one hour figuring out how to format dates
The doc claims that strptime returns a datetime object, but it returns a string. https://www.home-assistant.io/docs/configuration/templating/
@soft coral I had a "oh, duh" it dawned on me moment - strptime is both a python and php function, and since home assistant is lousy with .py files, i realized the yaml file is probably being parsed by python. so you can use python's date formatting. https://www.w3schools.com/python/python_datetime.asp

#

(also, thank you w3schools! how many times have i looked programming/web stuff up and you've been like "I've got you, bro")

halcyon ridge
#

hi, when I've added new sensor template file (not in configuration.yaml), and every time when I change it do I need to restart HA , or is there any better way ?

#

I know, that there is service for reload, but it looks like only for configuration.yaml

#

and there are other services for reload automations, scripts, etc, but none of them apply my changes in sensor template yaml file

vale nymph
#

The only way I've found is to restart HA, sadly 😦

#

even if it's in configuration.yaml

#

(I'd gladly be proven wrong on this though)

halcyon ridge
#

and restart from GUI does not work 😦 [supervisor.utils] Can't execute restart while a task is in progress

honest mauve
#

Is it possible to use a template for the command event_data of an event?

#

Like an event_data_template, with a variable command text

#

to get for example all the commands that ends with "on" or "off"

mighty ledge
honest mauve
#

Thanks petro

mighty ledge
#

you guessed right btw

honest mauve
#

how can I make a loop on switches inside a python script?

#

I don't think it's copy and paste of the code, from automations, like you said

#

right'

#

?

mighty ledge
#

it's close, have you looked into python's syntax for a for loop?

honest mauve
#

is it better in private, maybe you can dedicate me 2 mins to give me the right hints

#

and I will proceed than autonomously

mighty ledge
#

it's fine here

honest mauve
#

Ok thanks

#

this is my original automation snippet

#

it works

#

but all commands are on one line

#

so what shall I do first?

mighty ledge
#

well, how much do you know about python?

honest mauve
#

a bit... I'm a coder

#

but not so deep into python and the way python interacts with HA objects

#

if you can drive me step by step

#

I would really appreciate it

mighty ledge
#

Well first you should study the python API

#

You're trying to replicate {%- for state in states.switch -%}

honest mauve
#

Yes that one...

mighty ledge
#

in python theres multiple ways you can do this

#

you can either request switch entity_id's then iterate the state machine and get each state. Or you can get all the state objects and only act on the switch domain ones.

#

this is all done through the hass.states object

honest mauve
#

I'm really lost

#

I would need some more guidance

#

do you have time/willing to deep dive it?

mighty ledge
#

If you got the entity_id's... for entity_id in hass.states.entity_ids('switch'), you'd then need to get the state object state = hass.states.get(entity_id)

honest mauve
#

I just need to put those 2 lines in the code?

mighty ledge
#

that would get you what's eqivalent to {% for state in states.switch %}

#

but make sure it follows python rules. Like spacing & punctuation

honest mauve
#

Do you mind creating a sort of prototype for me that I can test and correct?

mighty ledge
#

Why don't you try it first

honest mauve
#

I dunno how to... 😦

mighty ledge
#

You do though...

#

What's the first step?

honest mauve
#

I'm following it...

#

I'm already doing the config

mighty ledge
#

Did you create the hello world python script?

#

So you can learn the process for creating the script. It's where I linked

honest mauve
#

I'm doing it

#

action:
service: python_script.ControlloLuci
data:
name: you

#

Like this, in automation?

mighty ledge
#

yep

#

remove the capital letters from the entity_id name

honest mauve
#

even if file has it?

mighty ledge
#

yep

honest mauve
#

I'll raise the log and test

mighty ledge
#

Then, go line by line in your jinja and convert each line to python

#

The difference is that you'll be building up a list, then calling a service at the end

honest mauve
#

I will need help here 🙂

mighty ledge
#

so you want to create a list in your python script and append entity_id's to it

honest mauve
#

one sec

#

restarting HA

mighty ledge
#
mylist = []

... 

mylist.append(entity_id)
#

or if it's a bunch of strings that you concatenate, then that's what you'll be appending to the list.

honest mauve
#

How can I then invoke Telegram bot

#

with list of inline_keyboard?

#

I do the loop, I fill the list

#

then I loop on the list and create the inline_keyboard

#

but how to invoke it with several lines (like a list of keyboard commands) ?

mighty ledge
#

hass.services.call There's an example in the docs I listed

honest mauve
#

hass.services.call("light", "turn_on", service_data, False)

#

yes I see it

#

but I mean, how can I make it a list of inline keyboards?

mighty ledge
#
data = {
    'title': '*Controlla lo stato delle luci...*',
    'message': 'Accendi o Spegni le luci',
    'data': {
        'inline_keyboard': mylist,
    }
}
hass.services.call('notify', 'allarme', data)
#

you just need to populate mylist

honest mauve
#

Cool

#

let me try it... I'm about to test first the hello world

#

I got

#

2020-09-04 12:18:42 DEBUG (MainThread) [homeassistant.core] Bus:Handling <Event you[L]: wow=from a Python script!>

mighty ledge
#

yep, and in your logs under info you should have "Hello world'

#

or

#

Hello you

#

whatever you used in name: ... for the service call

honest mauve
#

Yes

#

2020-09-04 12:20:25 INFO (SyncWorker_5) [homeassistant.components.python_script.controlloluci.py] Hello Stefano

#

Great, good start ! 🙂

#

Now... shall I restart HA each time I change the python script?

mighty ledge
#

now start creating the real script that you want to create

#

For now you have to. I believe in 0.115 you can just reload the python_scripts

honest mauve
#

😦

#

It will take ages 😦 ... ok let's start

mighty ledge
#

Now that I think about it, you should only have to restart when you add a script. Not for changes. We’ll see

honest mauve
#

I tested with this...

#

name = data.get("name", "world")
logger.info("Hello %s", name)
hass.bus.fire(name, {"wow": "from a Python script!"})

for entity_id in hass.states.entity_ids('switch')
state = hass.states.get(entity_id)
logger.info("Switch %s %s", entity_id, state)

#

And I didn't even receive the "Hello Stefano"

#

I'm trying to restart HA now...

mighty ledge
#

Because you’re missing vital python punctuation

#

This is why I suggested you learn some beginner level python

#

Like making a for loop

#

Making a list

#

Making a dict

#

You know code based on what you created in jinja without much help. So it shouldn’t be hard for you. You just gotta learn the nuances and you’ll be flying in no time

honest mauve
#

I'll check

#

Invalid syntax

#

let me fix it

#

I added the ":" and it works

#

not even needed to restart

#

let me continue with it then

mighty ledge
#

Yep! You got it

honest mauve
#

from state I can read:

mighty ledge
#

The state objects are the same shape as jinja

honest mauve
#

<state switch.bagnogrande=off; tuya_device_id=XXXX, friendly_name=Bagno Grande @ 2020-09-04T12:32:07.507551+02:00>

#

it will be state.state?

mighty ledge
#

Yep

honest mauve
#

😄

mighty ledge
honest mauve
#

I'm fast learning

mighty ledge
#

State.attributes

#

Yah, like I said, it’s not too different from jinja

honest mauve
#

It works

#

2020-09-04 12:40:18 INFO (SyncWorker_40) [homeassistant.components.python_script.controlloluci.py] Switch Bagno Grande off
2020-09-04 12:40:18 INFO (SyncWorker_40) [homeassistant.components.python_script.controlloluci.py] Switch Scala unavailable
2020-09-04 12:40:18 INFO (SyncWorker_40) [homeassistant.components.python_script.controlloluci.py] Switch Bagno Piccolo off

mighty ledge
#

Nice

honest mauve
#

I'm make the data for the inline keyboard now

#

UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 468: character maps to <undefined>

#

What does it mean?

mighty ledge
#

You won’t be able to use those special characters unless you change the encoding of the file

silent barnBOT
honest mauve
#

Ah....

#

the emoji....

mighty ledge
#

Yeah

honest mauve
#

What shall I do?

mighty ledge
#

Well, there should be an ascii representation of those emojis that your notification service understands

honest mauve
#

from automations.yaml

#

it works straight forward

mighty ledge
#

No like for discord, :man_shrugging: will display 🤷‍♂️

#

those are all ascii characters

honest mauve
#

NameError: name 'replace' is not defined

#

stato = state.name + ' ('+ stato + '):/' + state.name.replace(' ','') + state.state.replace ('off','On').replace ('on','Off').replace ('unavailable','Unavailable')

mighty ledge
#

that should work

honest mauve
#

yes... 😦

#

but it doesn't

mighty ledge
#

but you're getting a name error

#

that means you're using replace somewhere else

#

you'd be getting an attribute error if it was broken in that line.

#

AttributeError

honest mauve
#

works now

#

I removed spaces

#

replace ( --> replace(

mighty ledge
#

Nice. Aight have fun scripting I have to get ready for vacation

#

If you need more help, make a forum post

honest mauve
#

Thanks for your time

mighty ledge
#

Np

honest mauve
#

Shall I add the "-" before each inline keyboard?

mighty ledge
#

No, each time you want to add the -, append it to the list

#

Remember, your making a list. Not a long string

#

Again, a beginner python tutorial would work wonders

honest mauve
#

True

#

😄

#

It works!!!

#

I'm able to generate the buttons

#

thanks

#

I need to fix only the character set

#

issue

#

and I'm done

#

@mighty ledge you've been so helpful

#

thanks

honest mauve
#

for entity_id in hass.states.entity_ids('switch'):

#

Is there a way to sort it?

#

@mighty ledge

#

found it: sorted(hass.states.entity_ids('switch'))

honest mauve
#

I fixed also the asc stuff

#

just had to add asc(code)

vagrant monolith
#

looks like a timestamp already. whats it coming from?
@dreamy sinew yea but it's like 04:45 and my alarm is 06:45 which is weird

mighty ledge
#

Unix time. Convert it to local

distant plover
#

Can a template be cropped to fit one line in markdown card?

dreamy sinew
#

what do you mean?

rugged laurel
#

Yes it can

#

{{}} fits quite nicely

nimble marten
#

Can i get some help with this please.

I have an automation runniing based on a calendar event, and it had the following condition in it value_template: "{{is_state_attr('calendar.calendar_name', 'message', 'vacation') }}", i beleive this means that if the calendar event matches the name vaction in my calendar then run the action. how do i get it to not trigger the action if vacation is not in the calendar event.

Example if todays date does not match the calendar event date/time or name then action not fire if it does match then the action fires

distant plover
#

Hehe. I have a list of strings at variable lengths in a markdown card. Can I make it trunc at card width?

dreamy sinew
#

gonna need some examples @distant plover

#

@nimble marten you too

#

.share what you have

silent barnBOT
distant plover
#

I've tried using substring as you can see but various devices have various widths of the card

nimble marten
#

@dreamy sinew heres my automation
alias: Calendar lights
description: Turn on Christmas lights
trigger:

  • entity_id: calendar.christmas_lights
    platform: state
    to: 'on'
    condition:
  • condition: template
    value_template: {{not is_state_attr('calendar.christmas_lights', 'message',
      'Christmas Lights') }}
    action:
  • scene: scene.calendar_lights
    mode: single
silent barnBOT
inner mesa
#

To start, you need to quote your templates

nimble marten
#

when i hit execute my light should come on which it does, i want to add another conditon that also checks todays date against what is in the calendar if it does not match then dont turn on

#

@inner mesa like this "{{not is_state_attr('calendar.christmas_lights', 'message',
'Christmas Lights') }}"

inner mesa
#

Yes

nimble marten
#

ok done

silent barnBOT
nimble marten
#

@inner mesa ok rob to test if the condition works, i changed where it says christmas lights to a random name and then pressed execute, in theory the action should not have fired but it did.

inner mesa
#

Please share the whole thing

dreamy sinew
#

doesn't the default trigger skip conditions?

nimble marten
#

alias: Calendar lights
description: Turn on Christmas lights
trigger:

  • entity_id: calendar.christmas_lights
    platform: state
    to: 'on'
    condition:
  • condition: template
    value_template: "{{not is_state_attr('calendar.christmas_lights', 'message',
      'tom') }}"
    action:
  • scene: scene.calendar_lights
    mode: single
inner mesa
#

Dear god. For the third time:

silent barnBOT
nimble marten
#

sorry

dreamy sinew
#

formatting is important in yaml. Without using a code block or a sharing site the formatting gets mangled and that hides potential issues

inner mesa
#

And a willingness to read helpful bot messages

dreamy sinew
#

help us help you, use a sharing site for code

nimble marten
#

@inner mesa @dreamy sinew Should i try changing the trigger to the condition then trigger to the action, still all new to this

inner mesa
#

no, I think it's okay. As phnx said, I believe that manually triggering an automation from the UI skips the conditions

#

it's equivalent to just running the action

nimble marten
#

@inner mesa oh ok how would i test it then without executing it

inner mesa
#

no need to keep tagging

#

add a different trigger that you can control, like an input_boolean

nimble marten
#

like a toggle switch

inner mesa
#

or make the calendar entry change state. I don't know anything about Google calendar

#

sure. or just an input_boolean that you control manually from devtools -> States

#

or use devtools -> Services, choose automation.trigger and set the skip_condition parameter to false

#

skip_condition Whether or not the condition will be skipped (defaults to true). true

distant plover
inner mesa
jade slate
#

will this work as a trigger?

#

- platform: template entity_id: {{ is_state_attr('lock.garage_door_locked', 'notification', 'Keypad Lock') }}

#

or should I be using a {% if

inner mesa
#

and you don't need the if

jade slate
#

thanks, I knew I was forgetting something

#

- alias: Garage Door Lock Keypad initial_state: true trigger: - platform: template value_template: {{ is_state_attr('lock.garage_door_locked', 'notification', 'Keypad Lock') }} condition: - condition: state entity_id: 'group.users' state: 'home' action: - service: lock.unlock entity_id: !secret BACKDOORLOCK - service: switch.turn_off entity_id: !secret GARAGELIGHTS

violet oyster
#

not entity_id. value_template

#

there u go

jade slate
#

wrong copypasta

#

reward for locking the garage is the backdoor gets unlocked and the lights are turned off

violet oyster
#

looks like itll work

inner mesa
#

~share in the future

silent barnBOT
inner mesa
#

gotta quote your template

violet oyster
#

true

inner mesa
#

and maybe not quote your entity_id, but that may not matter

jade slate
#

hastebin has some issues not sure why I cant click save

inner mesa
#

looks fine to me

jade slate
#

just updated from 0.100.3 docker the other day and just cleaning up all the things. its been pretty fun

violet oyster
#

lol thats a long time to go without updating. i don't envy you

jade slate
#

stopped letting watchtower auto update the container a while back because breaking changes were not ideal at the time

#

yeah maybe like 9 months

#

honestly there wasn't much to fix, just a few minor things really

#

zwave was the main issue for not updating and then updating

violet oyster
#

ah

jade slate
#

just trying to do some clean up and improve some automation handling while I've been digging around, been a while since I've messed with templates... really need to re-read the new automation docs. sounds great but I don't think I still quite understand all the new options

violet oyster
#

yeah the new mode option is huge

#

chooser is cool too

buoyant pine
#

@inner mesa the entity ID does need to be quoted

jade slate
#

like this: entity_id: 'group.users' ?

inner mesa
#

I never do that

#
  condition:
    - condition: state
      entity_id: input_boolean.heat_water
      state: 'on'
jade slate
#

me either, i dont know why i did it on the first paste

#

yeah i only single quote state

inner mesa
#

but it's a string, so doubt it matters

jade slate
#

and single or double quote value_template

inner mesa
#

doesn't matter - just don't use the same ones inside and out

jade slate
#

right

buoyant pine
#

In the template I mean @jade slate @inner mesa

inner mesa
#

ah, yeah. I was talking about the condition

buoyant pine
#

Just a heads up

#

Ohhhh gotcha

inner mesa
#

which had an unnecesarily quoted entity_id

buoyant pine
#

Yeah, that doesn't need to be. Won't hurt though

crisp marten
#

Is there a better way to keep track of wheter a time is within a range than this.

binary_sensor:
  - platform: template
    sensors:
      daytime:
        value_template: "{{ 'on' if ('08:00' < now().strftime('%H:%M') < '22:00') else 'off' }}"
        friendly_name: Is Daytime
#

Is the binary_sensor the correct form of entity and does the template make sense?

dreamy sinew
#

If all you want is a binary display, then that is a good choice

#

Do you always want it to be between those too times?

#

Also, it is very likely that that sensor will never update. You need to use an entity for that

keen crater
#

@soft coral it does return a timestamp, if it’s returning a string you’re using the function wrong
@mighty ledge I tried this but did not work. value_template: "{{ as_timestamp(strptime(value)) - timestamp_local('41') }}" But maybe I misunderstood you.

mighty ledge
#

@keen crater (as_timestamp(strptime(value)) - 41) | timestamp_local

soft coral
crisp marten
#

@crisp marten This will not work. now() is evaluated at the yaml parse time, so this sensor is telling you you restarted your HA during daytime or not. You need to compare your time with https://www.home-assistant.io/integrations/time_date/
@soft coral Thankyou now it works perfect. I am a bit curious how Jinja is able to compare the times without me typing them as time. But it seems to work.

tribal rock
#

Is it possible to set the min/max value of an input_number to a template value?

buoyant pine
#

@tribal rock nope

tribal rock
#

hmm fair enough, I just found a little tidbit on the forums too.
I've never looked at custom components, but this seems like the time to look into it

buoyant pine
#

What's the use case?

#

I can't think of a reason to make that dynamic

brisk sonnet
tribal rock
#

@buoyant pine Super late response, but for my auto-climate control automation (ACC), I'm using input_number to set the high and low temperatures for sleep and wake cycles. I could monitor inputs manually, but it'd be nice to programatically make it a rule that the max value for the low temperature should not exceed the state value for the high temperature for example.

coarse tiger
#

I get 'Template sensor 'network_devices' has no entity ids configured to track nor were we able to extract the entities to track from the value template(s). This entity will only be able to be updated manually
Verbindung getrennt. Verbinde erneut...'

with

        unit_of_measurement: "Device"
        value_template: "{{ states.device_tracker | selectattr('state', 'eq', 'home') | selectattr('attributes.scanner', 'eq', 'LuciDeviceScanner') | list | count }}" ```
But the sensor works fine, the error just appears on boot.
can I do something about that?
inner mesa
#

@coarse tiger

coarse tiger
#

so I‘m futureproof with this? 😄

#

i cleared my log today of misc issues and stuff... this is the last message remaining

inner mesa
#

Seems so. I have a few warnings like that and now I need to tackle them

tribal rock
#

Wait, @inner mesa I didn't know that's being removed. I hope my sensors still work if I remove the entity_id variable

inner mesa
#

the workarounds are easy

tribal rock
#

If I'm using a template for the is_state() part, will it still update accordingly?

inner mesa
#

does it match the description of the problem?

tribal rock
#

For example:

{% set temp_lim_id = "input_number.acc_%s" % states("sensor.time_cycle") + "_%s_limit" %}
{% set temp_lim_high = states(temp_lim_id % "high") | float %}
{% set temp_lim_low = states(temp_lim_id % "low") | float %}
inner mesa
#

in mstone's example, there's no entity ID, so it's exactly the problem

#

I would think that just having this in there is enough:

#

states("sensor.time_cycle")

#

I think if you're not getting a warning in the log, you're okay

tribal rock
#

Fair, but I also want it to reevaluate if the other entities' states update. E.g.
input_number.acc_wake_high_limit and
input_number.acc_wake_low_limit when is_state("sensor.time_cycle", "wake")
And vice versa for "sleep"

inner mesa
#

and you have a list of entity_ids now?

#

you may just need to give it a hint based on the description in the thread for the ones you care about

tribal rock
#

I do, I added them just for insurance when I created the automation, but I'm going to run a test without them

keen crater
#

@keen crater (as_timestamp(strptime(value)) - 41) | timestamp_local
@mighty ledge I can't get it to work 😦 Is it also possible to get the "received timestamp" from the MQTT message? Not sure HA records that. I figured that maybe a better solution because it uses the Home Assistant server time.

inner mesa
#

I don't think it'll figure the other ones out without help

#

you could try pulling the sensor.time_cycle out and see if you get a warning

tribal rock
#

Hmm, maybe it should be okay since I have an entity in the template that updates every minute

inner mesa
#

your call

tribal rock
inner mesa
#

are you having a specific issue with it?

tribal rock
#

You mentioned the entity_id config variable is being removed from template sensors, I'm about to test it now, but I'm just unsure if it will work the same way without some refactoring

inner mesa
#

it's not really a big deal - it only affects when the template sensor is re-evaluated, and it's easy to work around

#

if you were already using entity_id with a list of entities to ensure that it's updated regularly based on state changes, then just add them into the template

#

that same list would still apply. if you weren't doing that before and were happy with when it's automatically evaluated, you have nothing to worry about

mighty ledge
#

@mighty ledge I can't get it to work 😦 Is it also possible to get the "received timestamp" from the MQTT message? Not sure HA records that. I figured that maybe a better solution because it uses the Home Assistant server time.
@keen crater whats the format of the time value

keen crater
#

@keen crater whats the format of the time value
@mighty ledge 2020-09-06T15:36:38+02:00

thorny snow
#

reading lewx template I ask me if I you can set a variable in jinja.
I got an automation to dim the light if it is turned on.
I have to define the entety 3 times and wondering me if I can get around this.

buoyant pine
#
{% set light = "states('light.whatever')" %}
tender prawn
#

anyone in here on beta?

inner mesa
#

yep

tender prawn
#

i tried to shorten a template but can't make it work.. it's a condition in an action of an automation

#
    - condition: template
      value_template: "{{ now().strftime('%M') < '58' and now().strftime('%M') > '02' and (states('sensor.sonarr_queue') == '0') }}"
#

that works

#
    - condition: "{{ now().strftime('%M') < '58' and now().strftime('%M') > '02' and (states('sensor.sonarr_queue') == '0') }}"

doesn't???

inner mesa
#

try conditions:

dreamy sinew
#

Is that something that is supposed to be available in the beta? Because it's definitely wrong for current

inner mesa
#

yes, it's new

dreamy sinew
#

Gotcha

tender prawn
#

tried conditions: as well

inner mesa
#

what does the rest of it look like?

tender prawn
#

the whole automation?

inner mesa
#

at least the rest of the condition

#

or is it just that?

tender prawn
#

that is the only condition.. the whole thing

#
    action:
    - service: input_boolean.turn_off
      entity_id: input_boolean.retrigger
    - delay: '00:00:01'
    - service: input_boolean.turn_on
      entity_id: input_boolean.retrigger
    - condition: template
      value_template: "{{ now().strftime('%M') < '58' and now().strftime('%M') > '02' and (states('sensor.sonarr_queue') == '0') }}"
    - service: input_boolean.turn_off
      entity_id: input_boolean.retrigger
inner mesa
#

conditions don't start with "-"

#

yeah, that's not how that should be written

#

oh, nevermind

#

sorry, was confused

tender prawn
#

um... ok... well it's valid and working like that..

inner mesa
#

no idea

tender prawn
#

hmm... it's not really a beta issue... I might try there though

inner mesa
#

if the "new way" doesn't work and the old way does, then it does seem like a beta issue

#

they don't have an example in the docs that looks just like that

midnight elm
#

What am I doing wrong with this sensor template? I'm trying to have a combined data rate in Mbps converted from kib/s
`sensor:

  • platform: template
    sensors:
    rt_ac68u_7578_mib_s_total:
    unique_id: rt_ac68u_7578_mib_s_total
    friendly_name: RT-AC68U-7578 Mb/s total
    unit_of_measurement: 'Mbps'
    value_template: "{{ (states('sensor.rt_ac68u_7578_kib_s_sent') + states('sensor.rt_ac68u_7578_kib_s_received')) | float * 0.008192 }}"`
dreamy sinew
#

String math

#

Convert both to floats before adding

midnight elm
#

So just float() both of them?

dreamy sinew
#

|float them

midnight elm
#

Awesome, got it working now. Thanks!

dusky bane
#

hi all ! i try to begin with templates, i write something and its not working :

#

{% if is_state("sensor.thermohygro3_temperature", " > 15 " ) -%}
its over 15°
{%- endif %}

rugged laurel
#

It's exact match

dusky bane
#

i want to start action when temp raise 15 °

#

ok

rugged laurel
#

"{{ (states('sensor.thermohygro3_temperature') | float) > 15 }}"

dusky bane
#

okay, very nice thnak you !!

brisk sonnet
dusky bane
#

now i try to use this in an action , i don't know if its in the right place or what, and i don't know if i can increment a number directly like this 😗

#

action:
- service: input_number.increment
data_template: >
{% if (states('sensor.thermohygro3_temperature') | float) > 15 %}
input_number.servo_control
{%- endif %}

mighty ledge
#

@tender prawn from what i've read, it was broken in the beta. A fix is on the way. All you really need is just the condition:

- "{{ x == y }}"
#

@brisk sonnet

{% set rainfall = state_attr('sensor.bom_perth_possible_rainfall_4', 'possible_rainfall') | replace('mm', '') %}
{% if 'to' in rainfall %}
{% set values = rainfall.split('to') | map('float') %}
{{ values | sum / values | length }}
{% else %}
{{ rainfall | float }}
{% endif %}
#

@dusky bane you can't template the data_template field. Only field's inside data_template.

      - service: input_number.increment
        data_template: 
          entity_id: >
            {% if (states('sensor.thermohygro3_temperature') | float) > 15 %}
            input_number.servo_control
            {%- endif %}

Also, you'll need a backup plan because you can't call a service without a template. FYI you can place conditions in automations too. So instead of going this route, you can just place a condition prior to the service call and it will cancel all remaining actions.

brisk sonnet
#

Thanks @mighty ledge would you be able to explain that to me please ? Is that splitting the two values and then adding them together ?

distant plover
#

I have an automation on my robot vacuum with a trigger from 'returning' to 'error' but I need a condition when the attribute 'error' == 'Charging fault'. Should I use templating for that? How?

mighty ledge
#

@brisk sonnet the state appears to be "2 to 6 mm". So with that in mind, I'm splitting on the word 'to' and averaging the results.

#

And if they just give a single value, we default to that. I could see this not working if states like '< 1' occur. You'll have to add each of those cases as they come up.

dusky bane
#

thank you @mighty ledge !! i will try to understand your advice and write something

mighty ledge
#

@distant plover that's a very simple template, what have you tried?

brisk sonnet
#

Ok got it. Thanks 🙂

dusky bane
#

Well i have been trying different routes to Adjust the value of a slider with the variations of a sensor,
but i don't find a concise template to do it other than telling at 20° move the slider 10 at 21° move the slider 20 etc...
Maybe someone can indicate me a way to tell the slider to move proportionaly according to the sensor value ?

distant plover
#

petro, well... {{ state_attr('vacuum.xiaomi_vacuum_cleaner', 'error') }} seems to work but I'm not sure how to use that in automation. I'm a bit confused on that part when comparing to other stuff I'm using in automations. For instance I tried {{ trigger.to_state.error == 'Charging fault }} but I don't think that works.

#

But perhaps I shouldn't look at the trigger but use {{ states.xiaomi_vacuum_cleaner.attributes.error == 'Charging fault' }} instead?

distant plover
#

Can a condition simply be {{ state_attr('vacuum.xiaomi_vacuum_cleaner', 'error') == 'Charging fault' }} ?

mighty ledge
#

if you want to dynamically pull it from the trigger {{ trigger.to_state.attributes.error == 'Charging fault' }}

distant plover
#

What is the benefit from pulling it from the trigger?

mighty ledge
#

in 115 you can also just trigger off attributes

#

if you don't pull it from the trigger, there's a chance that it's not the same state when you check in the condition

distant plover
#

Ah. Clever.

mighty ledge
#

@dusky bane if the values are linear, make a chart in excel and get the trendline equation. Then plug the information in properly in a template step. I can help you.

#

@dusky bane the equation from excel will be y=ax+b. So in a template it would be {{ a*x + b }} to get Y.

#

it will probably look something like this {{ 10 * states('sensor.xxx') | float + 9 }}

dusky bane
#

oh ok i start to understand

#

y will be the value set to the slider

mighty ledge
#

yep

dusky bane
#

very nice

#

well i put my data in excel, and watch a tutorial about trendline equation, but i really don't know how to get to it...

#

ok i have the equation thank you petro

#

and i used it like you said and it works

#

i love you @mighty ledge

mighty ledge
#

np

dusky bane
#

and what condition can i use to make this action work only when the sensor value move for at least 1 point

#

because know it's acting with every decimal

mighty ledge
#

You'd need to check the current value against the new value. How are you using the template?

dreamy sinew
#

and even then, you'd only get the previous value, nothing historical

#

so if it ticked up 10 times of 0.1 you'd only ever see the last 0.1 change

wise cedar
#

I have set up a template sensor which adds three temp sensors together and splits in 3 to get the mean. However, some entities may go to unavailable state and that messes up the measurement. Is there any way I can know which amount to split by, based on number of available sensors?
Current code looks like this:

(( 
(states('sensor.temperature_stue_1')|float) + 
(states('sensor.temperature_stue_2')|float) + 
(states('sensor.temperature_stue_3')|float) 
)/3)
| round(1) }}```
dreamy sinew
#

i have something similar

#
        downstairs_avg_temp:
          friendly_name: "Downstairs Average Temp"
          device_class: 'temperature'
          unit_of_measurement: '°F'
          value_template: >-
            {% set sensors = [
                states('sensor.living_room_temperature')|float,
                states('sensor.office_temperature')|float,
                states('sensor.thermostat_temperature')|float
              ]
            %}
            {{(sensors|sum / sensors|reject("eq", 0.0)|list|length)|round(1)}}```
#

when you |float a string it goes to 0.0

#

i have 3 copies of this with different sensors lists

wise cedar
#

Neat, @dreamy sinew . I just discovered the Min/Max sensor platform, which offers a mean type and seems to do the trick as well. Any reason to choose template over Min/Max sensor platform?

dreamy sinew
#

none that i can see

wise cedar
#

Ok. Thanks for providing the solution, much appreciated. Think I'll use that, then I can drop it in place of my existing variable.

dreamy sinew
#

if you're doing a simple average min/max seems like it'll work well since it'll handle unknowns and stuff automagically. If you wanted to add any extra logic though, that's where the template comes in to play

wise cedar
#

Makes sense. I'll try this for a while. Can't hurt to learn some more templating anyway! I have only had issues with sensors going to unavailable, which is now handled.

dusky bane
#

@mighty ledge this is how i use the template

#

action:
- service: input_number.set_value
data_template:
value: "{{ 10 * states('sensor.thermohygro3_temperature') | float - 250 }}"
entity_id: input_number.servo_control

inner mesa
#

String math

#

States are strings. Need to convert to an number

#
         value: "{{ 10 * (states('sensor.thermohygro3_temperature') | float) - 250 }}"

Should do it

violet oyster
#

i swear to god the last time i looked at this window yesterday it was robc explaining string math

inner mesa
#

phnx is the string math dude usually

violet oyster
#

maybe it was him now that you say that

inner mesa
#

But we can take turns

mighty ledge
#

@inner mesa that doesn't matter, order of operation applies filters first. I asked him to show me how he was using it so I could help him only adjust when the change in states('sensor.thermohygro3_temperature') was greater than 1.

#

@dusky bane can you show me the whole automation, sorry for not being clear

inner mesa
#

Oh, alright. Good to know

mighty ledge
#

yeah, it's the same as float(states('x.y'))

dusky bane
#

yes

inner mesa
#

Sorry for jumping in the middle of a discussion in progress 🙂

dusky bane
#
  • alias: "Slider Movement Template"
    trigger:
    platform: state
    entity_id: sensor.thermohygro3_temperature

    action:
    - service: input_number.set_value
    data_template:
    value: "{{ 10 * states('sensor.thermohygro3_temperature') | float - 250 }}"
    entity_id: input_number.servo_control

mighty ledge
#

@dusky bane this condition will make the automation only fire when the delta is greater than 1 (or -1)

  condition:
  - condition: template
    value_template: >
      {% set before = trigger.from_state.state | float %}
      {% set after = trigger.to_state.state | float %}
      {% set delta = after - before %}
      {{ abs(delta) > 1 }}
dusky bane
#

thank you for the gift

#

i have a problem to use it with a switch i was putting as condition also to turn on/off the automation

#

condition:
condition: and
conditions:
- condition: template
value_template: >
{% set before = trigger.from_state.state | float %}
{% set after = trigger.to_state.state | float %}
{% set delta = after - before %}
{{ abs(delta) > 1 }}
#a switch to turn on/off the automation#
- condition: state
entity_id: input_boolean.automation_extracte
state: 'on'

#

it gives an error :bad indentation of a sequence entry at line 22, column 14:
value_template: >

dreamy sinew
#

your formatting is wrong. or could be. we can't tell because you didn't use code formatting or a code sharing site

dusky bane
#

ok

#

sorry first time

silent barnBOT
dreamy sinew
#

or at the very least:

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:

```
code here
```
Watch the animated gif here: https://bit.ly/2GbfRJE
DO NOT repeat posts. Please edit previously posted message, here is how -> https://bit.ly/2qOOf1G

dreamy sinew
#

if you're under 15 lines (you currently are)

dusky bane
#
    condition:
         condition: and
         conditions:
            - condition: template
            value_template: >
             {% set before = trigger.from_state.state | float %}
             {% set after = trigger.to_state.state | float %}
             {% set delta = after - before %}
             {{ abs(delta) > 1 }}
        #a switch to turn on/off the automation#
            - condition: state
             entity_id: input_boolean.automation_extracte
             state: 'on'
#

thank you @dreamy sinew

dreamy sinew
#

ok, then yes. your formatting is incorrect. the v for value needs to be lined up with the c for condition above it

dusky bane
#

oh ok it was dumb i already tried moving stuff around but not correctly it seems thank you for your help

silk stream
#

i'm trying to build a template sensor for a MQTT Sensor, its a door sensor an i try to strip out the "unavailable" message, so that i always just get 'open' or 'close' is there some kind of previous state i can use for that?

#
     entity_id: switch.door_sensor1
     icon_template: mdi:door-open
     value_template: >
       {%if is_state('switch.door_sensor1', 'on') %}
         'on'
       {%elif is_state('switch.door_sensor1', 'off') %}
         'off'
       {% endif %}```
jagged obsidian
#
{% else %}
        {{ states('sensor.balcony_door1') }}
#

or binary sensor

silk stream
#

thx exactly what i needed.

#

sometimes the answer isn't that far..

bitter atlas
#

should really rename this channel #phnxplates

dreamy sinew
#

Lol why?

bitter atlas
#

everytime i peak in here I see a phnx wall of code lol

dreamy sinew
#

Lol

lusty vine
#

Hi, need some help here with a template that is not rendering, it seems that because the sensor starts with 1, something breaks. When I try the template "{{ (states.sensor.1h_pool_kwh_difference.state | float) | round(2) }}" it gives me this error

#

Error rendering template: TemplateSyntaxError: expected token ')', got 'h_pool_kwh_difference'

#

Seems to not be able to render sensor.1h.... doesn't see the 1

brisk sonnet
rare sage
#

Good Day All, Anyone know how i can make a template that can calulate estimate time remaining on my investor battery?? I have sensors for capicty voltage and amps per hour.

mighty ledge
#

@brisk sonnet Can you post a screenshot of the state in the dev tool -> states page? Also, please make sure the attributes are present in the screenshot.

#

@rare sage do you have the equation already or do you need to generate the equation, because those are 2 very different questions and require very different skillsets.

brisk sonnet
mighty ledge
#

Oh ok, it's the main state, not an attribute. try this:

{% set rainfall = states('sensor.bom_perth_possible_rainfall_0') %}
{% if ' to ' in rainfall %}
{% set values = rainfall.split(' to ') | map('float') %}
{{ values | sum / values | length }}
{% else %}
{{ rainfall | float }}
{% endif %}
brisk sonnet
#

i get an error Unknown error rendering template

#

using sensor.bom_perth_possible_rainfall_1

#

sensor.bom_perth_possible_rainfall_0 returns a result of 0.0

dreamy sinew
#

this line:
{% set values = rainfall.split(' to ') | map('float') %}
needs to be
{% set values = rainfall.split(' to ') | map('float')|list %}

brisk sonnet
#

Bingo! That did the trick 🙂 Thanks @dreamy sinew @mighty ledge

mighty ledge
#

Ah oh yeah, forgot to cast the generator to a list

buoyant pine
#

@lusty vine try

"{{ states('sensor.1h_pool_kwh_difference') | float | round(2) }}"
lusty vine
#

@buoyant pine thank you, will give it a try

buoyant pine
inner mesa
#

More of an #integrations-archived question. I’ll bet the container doesn’t have the ‘ha’ cli command installed

halcyon ridge
#

Hi, how to change state attribute from template ? I've tried something like this, but I don't know correct syntax:

{{ state_attr('sensor.sms_parsed', 'number') = '999' }}
buoyant pine
#

you can't. what are you trying to accomplish?

high crater
#

so I saw somewhere that how template sensors are checked on startup is going to be changed again. Does anyone have a link to the post talking about that or a TLDR for what should be added to template sensors soon/now so they dont break in the future

high crater
bright prawn
#

can some one tell me what is wrong with this one ?
platform: command_line name: "Latest Version" command: echo "$(ha core info | grep 'version_latest: ' | cut -f2- -d:)"

the command it self works in cli but when i try to add it as a sensor i get following error:
Error loading /config/configuration.yaml: mapping values are not allowed here in "/config/components/packages/../sensors/latest_version.yaml", line 3, column 53

buoyant pine
#

.share the contents of that package

silent barnBOT
bright prawn
#

and in the logs its says the following
while parsing a block mapping in "/config/components/packages/../sensors/latest_version.yaml", line 1, column 1 expected <block end>, but found '<scalar>' in "/config/components/packages/../sensors/latest_version.yaml", line 3, column 17 mapping values are not allowed here in "/config/components/packages/../sensors/latest_version.yaml", line 3, column 62 mapping values are not allowed here in "/config/components/packages/../sensors/latest_version.yaml", line 3, column 53

buoyant pine
#

Also there's a version sensor

bright prawn
#

realy ??

silent barnBOT
bright prawn
#

ok leme check that

#

is there also a updates sensor ?

buoyant pine
#

There's the updater binary sensor but I've heard it's apparently but working

bright prawn
#

i need a normal sensor for that to get the amount of updates there are

buoyant pine
rugged lichen
#

How Can I check with templates the last state change on a sensor? Thank you

violet oyster
#

@rugged lichen you want to pull the date/time the sensor changed state? if so I would make an automation that is triggered whenever the sensor's state changes and then just use the automation's 'last_triggered' attribute in the template. might be another way but that is what popped into my head.

#

As for me, does anyone know if it possible to use wait_template with events? specifically I want a script to wait until a specific event fires.

inner mesa
#

0.115 will introduce a wait_for_trigger action that could do that. You can install the beta if you want to try it now, or wait until next Wed

violet oyster
#

what a shock that RobC knew the answer to my question. I think it was yesterday that I declared you know everything

#

thanks mayne

#

next wed is a long time... might have to try my first beta

inner mesa
rugged lichen
#

There is no default lets say attribute of every entity when the last time changed the status?

#

I would be able then use a template to (now() - when the sensor last changed) = I will get the time in hours since the last change was on the sensor.

#

that would be the thing what I want

#

to have a data what only contains a number in hours how many time left since my motion detector seen something.

violet oyster
#

for that I would probably use a timer. have the trigger be the state changing and the action be to restart the timer.