#templates-archived

1 messages · Page 147 of 1

buoyant pine
#

It's also its own data type in python

atomic blade
#

How would I get n minutes in the future within a template?

#

I know there's now() but I'm a little disoriented to figure this out on my own because there are things missing I would have expected like the type() builtin. Not sure how to go about searching

#

Worked it out:
{{ now() + timedelta(minutes=5) }}

#

Thanks rubber_duck

marble jackal
#

It is compatible since 2021.8.3 (from the top of my head)

cursive ice
#

have I over complicated it ?

azure tinsel
#

hello, i'm trying to create month dependent template sensor like this

{% set winter = ['1', '2', '3', '11', '12'] %}
{% if now().month not in winter %} not winter {% else %} winter {% endif %}

But it does not work.. what i'm doing wrong?

#

doh.. {% set winter = [1, 2, 3, 11, 12] %} worked, maybe i've mixed strings with integers

hollow girder
mighty ledge
mighty ledge
sage aurora
#
  - platform: mqtt
    name: "Outdoor Power Temperature"
    state_topic: "rtl_433/Blueline-PowerCost/12080/temperature_C"
    unit_of_measurement: '°C'
    value_template: “{{ (value | round(1)) | float }}”

Anyone know why my temperature is still showing up as a string in my dashboard?

inner mesa
#

How would you know?

sage aurora
mighty ledge
inner mesa
#

Oh, yeah. The quotes are fancy

coarse tiger
#

I use this in my cover template:
{{ states('sensor.wohnzimmer_curtain_2_position') }}"
which goes from 0 (open) to 100 (closed)

#

I use this in position_template which apparently reads 0 as closed and 100 as open

#

how can i switch these?

#

i get the current value with {{ value_json.body.slidePosition }}

#

eh, | float *-1 + 100 does the trick thank you all, very helpful 😡

mighty ledge
coarse tiger
#

what? 😄

coarse tiger
mighty ledge
#

when you set it to 100, it should be zero on your hardware

#

inverse the equation

coarse tiger
#

ooof

cursive ice
#

yep still did not do, it maybe because I was following a guide lol petro

cursive ice
mighty ledge
#

Copy your configuration into the template editor. Not just the template and see what the output is.

cursive ice
#

This template listens for the following state changed events:

Entity: input_select.aj_room_scene

mighty ledge
#

Just do what I asked and look at the output

cursive ice
mighty ledge
#

Nope, still same mistake

#

Paste that entire chunk into your template editor

#

And look at the fields where you template and the results of that field

cursive ice
mighty ledge
#

Nope, not it

#

What field are you templating?

#

Type it in here so I know you know

#

This isn’t a trick question. I’m trying to gage what you know.

cursive ice
#

I was just typing I am old and only 4 months in still, I know some, but always get stuck when it comes to templating a fair bit, normally work it out but yes I am still a noob. but I presume the field is the condition value.

#

condition state lol I meant (which probably means i know nothing lol)

mighty ledge
#

What field is your template in…

#

Do you know what signifies a template?

cursive ice
#

not really some more education is needed

mighty ledge
#

Check the pins

#

3rd pin shows you the differences between templates and yaml

cursive ice
#

probably my own fault for following a guide on this one lol

mighty ledge
#

You shouldn’t be using templates if you can’t even identify a template in yaml

mighty ledge
#

This is a very simple question

cursive ice
#

I know the template is the state.

mighty ledge
#

no

cursive ice
#

{{ part or are you referring to what I wanted it to do

mighty ledge
#

Ok, that's identifying the template

#

so what field is it in

#

this should be a 1 word answer.

#

it involves you looking to the left.

#

it's that simple.

cursive ice
#

you mean the type of code?

mighty ledge
#

No.. what freaking yaml field is it in

cursive ice
#

well jinja (which I am trying to learn is not yaml)

mighty ledge
#
what:
  yaml:
    field:
      is:
        it:
          in:
#

it's not hard man

#

i'm trying to lead you to your problem and I can't even do that

#

it's entity_id

#

your template is in the entity_id field.

#

Ok, now that you know it's the entity_id field that the template is in. What is the result of that field in the last link you posted?

#

paste that result here.

cursive ice
#

ROFLMAO.... if you look over are previous private chats I was not this bad lol 😛

#

mabye I should of got some sleep after last nights night shift

mighty ledge
#

so did you figure out the issue?

#

if not, paste the result of taht field from your last link.

cursive ice
mighty ledge
#

no, paste just the reuslt of your template, which you now know is the result that you should see after the entity_id field

cursive ice
#

its changing the scene but under enter id if I roll the dial round

#

(in the results page)

#

but not actually changing it light wise

mighty ledge
#

dude

#

just look at your field and past the result here. Stop looking in the wrong place. Stay with me,.

#

I'm trying to show you how to debug your stuff

#

by leading you down the path

#

and you aren't doing that, you're looking in the wrong spots

#

just do exactly as I ask and I'll lead you to the answer

cursive ice
#

ok so the original script shows the entity_id scene. part (template) the result shows what I just pasted

mighty ledge
#

Yes. Paste the result of JUST the entity_id field in this chat

cursive ice
#

entity_id: scene.scene.front_bedroom_concentrate

mighty ledge
#

ok, now, focus on that field

cursive ice
#

and it changes if I roll the dial

mighty ledge
#

read it from left to right out loud

#

including punctuation

cursive ice
#

scene.scene lol

mighty ledge
#

OK

#

jesus

#

YOU FOUND IT

cursive ice
#

ok now I see why you were face palming

#

F**k you need a patience of a saint award

mighty ledge
#

Do you at least see the process you should use when testing this stuff now?

cursive ice
#

petro and me last 2 minutes

#

😂

mighty ledge
#

Man, I was trying to lead you to water!

#

it should work now

cursive ice
#

and it does.... lol

#

my boy will be happy when he gets home from scouts lol

mighty ledge
#

what's this even do?

#

is that a push button or something

cursive ice
#

its a dial that has 3 dial modes, normal toggle, brightness up and down and color temp and 3 taps and turns into scene selector

#

almost 3 dials in one

thorny snow
#

Im not massively familiar with template sensors - but I am trying to take two sensors and minus one from the other to give a result.
What have I overlooked here please

    sensors:
      - name: "Flow & Return Differential"
        unit_of_measurement: "°C"
        state: >
          {% set flow = states('sensor.flow_temperature') | float %}
          {% set return = states('sensor.return_temperature') | float %}

          {{ (flow - return) | round(1, default=0) }}```
fossil venture
#

The only thing you have missed is a default value for your |float filters.

thorny snow
#

I took an example from the docs and changed the entity to match mine and changed the maths operations to suit my needs - but other than that - nothing changed. But it wont let me restart HA

fossil venture
#

What error are you getting?

thorny snow
#

its a config error - let me grab it

marble jackal
#

I guess there is nothiing wrong with the template, but rather with the yaml for the sensor itself

fossil venture
#

Oh hang on. You have half the old and half the new format

#

New format```
template:

  • sensor:
    • name: "Flow & Return Differential"
      unit_of_measurement: "°C"
      state: >
      {% set flow = states('sensor.flow_temperature') | float %}
      {% set return = states('sensor.return_temperature') | float %}

      {{ (flow - return) | round(1, default=0) }}

thorny snow
#

so literally the top two lines ?

fossil venture
#

Yes

thorny snow
#

ah ok -

#

let me change that and see what it does!

fossil venture
#

Also this goes in your configuration.yaml file, not sensors.yaml

thorny snow
#

yeah it was is the config - thanks - it seems to be restarting now

#

so i have some "older" sensors (templated) - but they still work - do I need to change them at all ?

marble jackal
#

No need right now, but the new format supports more attributes, like e.g. state_class, which allows it to be added to the long term statistics
Don't know if the legacy template will become depreciated in the future.

sleek wing
#

Hi all, is there a way how to pop the value from a list? To append value we can merge lists like {% set b = b + ['a'] %}, but how to remove the 'a'?

dreamy ore
#

Hello folks, I'm having some trouble with universal media player rendering a template for it's state.. what I have works fine in the 'developer tools' but when I add it to my config the state always shows 'off'

#

Here is what I'm using if anyone can see why it wouldn't work..

#

basically, i'm aiming for the state to be 'playing' if the remote activity is Xbox, otherwise take the state from the actual media device i'm using

marble jackal
marble jackal
dreamy ore
#

ah jesus... i just realised it's state_template...

#

🤦‍♂️

#

I spent like an hour last night mucking around with the template trying to figure out why it didn't apply 🤣

sleek wing
marble jackal
#

Check the pins for some links to more jinja information

sleek wing
#

Believe me I was in the topics and docu last two days. To be honest, from my perspective Jinja is pure disaster (functionality, readability, documentation) and am wondering how it could even survive. But thanks god for people like you. I don't know why is HASS using it but I assume there's a good reason, is there a topic about it? Please don't take it as an attack. Truly appreciate your help here

mighty ledge
#

there is no discussion about it's use

sleek wing
#

Yeah, I think (but not 100%) I've read your answer already in some topic, when someone else was questioning Jinja. And unfortunately I do not agree with you at all. But I still do accept that HASS developers can see benefit in it. Just wondering if there is any mention about it.

marble jackal
#

Well, I can't say I'm on petro's level, but I can handle the jinja templates quite well, without a programming background and about 1,5 year of tinkering around with them.

#

So I would agree that it is relatively easy to learn

mighty ledge
sleek wing
#

@mighty ledge I will not open this pandora box, just looking for answers and definitely trying to learn this thing even though it drives me crazy. Am pretty on same level as you are @marble jackal , I didn't have programming background but as a software consultant I start write some stuffs like a 1.5y ago and since I was able to write some pretty codes in JS, C and mainly in PYTHON, but putting together Jinja code takes me ages and together with yaml I have to use workaround on workarounds. So spending really days in documentation and topics to write something what I can have in python in few hours (@mighty ledge I bear in mind what was in that topic mentioned about python). So someone could probably ask me why I do not use python than, if I can. The answer is easy, I want to use HASS as it is with it's own features. BUt yeah I was really pretty close to rather write a component than bit more complex automation. But again, hopefully no one is taking this personally

mighty ledge
#

Filters are used to avoid the loop scope issues and they create generators and are meant to be easy to read and understand. You’re filtering your list as you move further left.

#

To me, it seems like you don’t understand the basics of filtering using objects and that’s your problem with jinja.

sleek wing
# mighty ledge To me, it seems like you don’t understand the basics of filtering using objects ...

Definitely agree with you here. I don't understand the basics of filtering. And yes I can't see enough similarities with python, e.g. my first question here today about using lists, which is being solved using filtering again. And no it's not easily readable as python is (my opinion) even JS is easier to read (again just my opinion). And I don't think am a silly person, so definitely trying to learn this and understand how it works, so possibly help to others in the future. But as mentioned above, Jinja is not well documented and also does not have very wide community. Whichever dev I asked if s/he knows jinja, I never got positive answer, just from people using HASS.

mighty ledge
#

you want to learn filters, and they are very easy to understand if you understand lambda in python and its 1000x easier to read than pythons lambda functions

#

just to compare some for loops...

#

python

for x in ['a', 'b', 'c']:
   if x in y:
     ...
#

jinja

for x in ['a','b','c'] if x in y

or

for x in ['a','b','c'] | select('in', y)
#

which ones the easiest to read?

#

just take the time to learn filters and you'll see that they are WAY easier to read at a glance.

#

and typically less verbose

#

as well as more memory efficient because they use generators instead of lists

#

the only drawbacks to jinja are built in on purpose. I.e. make jinja object and memory safe. E.g. You can't create classes, you can't merge objects, etc

ashen hawk
#

I is there a way to get fetch context.user_id in automation using templates from call_service events. All examples seem to use to_state.context but call_service events only seem to have to root context node. (not under data as they are in state_changed events.

silent barnBOT
mighty ledge
ashen hawk
#

Yup. Two secs.

mighty ledge
#

I don't think you have access to it

#

unless it's just trigger.context

#

well, it could be trigger.event.context

#

seeing that it's at the root level of the event. That's probably it now that I think about it.

sleek wing
# mighty ledge Jinja is used to serve up forms comprised of strings. It's a markup language de...

Thank you for putting effort to explain this, I will take a look on it properly. Just can't right now. And yes at glance this looks similar and easy (not the last solution), but still add jinja's bloat paranthesis, write longer code than just one straigh forward example and this thing becomes nasty, meanwhile python stays as you have written it.

Happy day to all, and thanks again for you interactions!

ashen hawk
#

Trigger.context or trigger.event.context?

mighty ledge
mighty ledge
#

I purposely remove them all when I reply

#

order of operations is identical to python's order of operations

ashen hawk
#

YEY! trigger.event.context.user_id worked!

mighty ledge
#

pemdas

ashen hawk
#

Thanks!

mighty ledge
#

np

ashen hawk
#

Hm. But now I need some black magic to "guess" based on time of this was done through the home-assistant or by other means. I have a sonos tts notification that says "Garage has been open for 30 minutes", I wanted it to say "Garage has been open for 30 minutes and it's X's fault". But I then have to check that the input_text field was updated approx 30 minutes + 10 seconds ago..... Wish me luck! 🙂

mighty ledge
ashen hawk
mighty ledge
#

it's complicated...

#

You ahve to make assumptions

ashen hawk
#

Yup. I know.

mighty ledge
#

unless you know exactly who opened it through the interface

#

context is only populated when the frontend is used

ashen hawk
#

Well that I do know now. Since I update the "last_opened_by" input.text field that can be included in any input

#

My challenge is that there are multiple other ways to open the garage. All of them create the state "open/closed" because I have a door sensor. But that sensor has no idea what triggered it (its a curl call)

#

Hm. I can reset the text field on close. And if it's not updated.. Then it's done by other means. That might work. Yeye.

mighty ledge
#

and it's basically a list of people at home

#

and if I don't know the context, I list out who it could be

#

using people_at_home

#

just create a group with all the people named group.people and then you can use that template sensor in your setup

#

the or and and ttributes lists out the people nicely in english

ashen hawk
#

But I've found a way now. If i update the opened_by textfield to "system" when it's closed. So if its done outside it will be "system", unless someone actually fired the script.

mighty ledge
marble jackal
#

So it will be the system's fault that the door is open?

mighty ledge
#

I found that it's always the systems fault

#

hence why I made the people tracker

#

aka, it's one of these people who opened the door

#

but you have to store the list of people with the open event. Requiring another sensor. That's where I use MQTT

#

you can also use it to persist through shutdowns

fervent sorrel
#

Got a quick question, my mind doesn't seem to want to be able to figure this out.
I've got an iframe with a URL, and I want to change a portion of that URL with contents of an input_text state. How would I go about doing this?

#

I've tried doing things like this: .../file/clips/{{states['input_text.alert_clip_db_number'].state}}?mode=mjpeg... without any luck.

#

Using the Template Editor, it works. Does this just mean that iframe doesn't support templates? How does one get around this?

fervent sorrel
#

oof

#

What if I stored the entire URL in the input_text? Would I be able to just pull from that?

mighty ledge
#

mjpeg

silent barnBOT
fervent sorrel
#

Not sure why I didn't think of that

#

That's how I used to do my cameras. Haha - thanks

#

Although, not sure how I'd incorporate a template into the mjpeg_url - putting it straight into the config yaml as a template doesn't work for sure.

mighty ledge
#

good point, it may not be doable

#

you might have to use a condtional card instead

fervent sorrel
#

There will never be a time where two input_text.alert_clip_db_number states are the same

#

I can't believe you can't template an iframe url. Hahaha. That's crazy

#

Are custom_widgets still a thing?

#

I've never heard of them before. Looks like there might have been a custom 'widget' that could help.

mighty ledge
#

you can use a custom card to template the iframe. Like the custom-template card

#

but it requires js templating

wispy field
#

Is there a way to kind of debug the trigger object, or all variables/object accessible in an automation? For other objects like states and such i can of course use dev tools templating, but that does not work with the trigger object for example.

marble jackal
#

you can create a similar dictionary in the template editor

#

For example

{% set trigger = { 'id': 'test' } %}

for the trigger.id

#

If you download the json file from the trace you can copy/paste it from a previous run

wispy field
#

Ahh, didn't think of the trace, thanks!

wispy field
#

Can anyone see what i'm doing wrong here? Trying to make a sensor with the amount of snow about to come..
{%- set snow = 0 -%}
{%- for weather in states.weather.home_hourly.attributes.forecast -%}
{%- if weather.condition.split('snow') -%}
{%- set snow = snow + weather.precipitation -%}
{{snow}} #Becomes the same as weather.precipitation
{%- endif -%}
{%- endfor -%}
{{snow}} #expecting accumulated for all hours, but becomes 0.

inner mesa
#

You need to use a namespace to use variables in and out of a for loop

wispy field
#

ahhh, right, i think i've done that error before. Thanks, it was driving me mad.

inner mesa
#

It's not at all obvious

wispy field
#

Nope. I work as a developer, so it was really illogical that it didn't work

#

fuck me, 104cm snow😩 Not considering probabilty and using the thumb rule of 1mm precipitation == 1cm snow

inner mesa
#

Palm trees and sunshine here, so good luck with that 🙂

wispy field
#

Hah, thanks!
Also, is there a way to add to a variable in another way than var = var + var, like var += var?

inner mesa
#

I don't think so, but you're welcome to run a 1second test

#

There are more verbose ways

wispy field
#

i tried the usual tricks i know, but those didn't work. well, x = x + y works, so.

sonic nimbus
#

hello, I have a question regarding how to pass two arrays in my script

#
sequence:
  - service: icloud.play_sound
    data:
      account: !secret stefan_icloud_account
      device_name: !secret stefan_icloud_device
  - service: icloud.play_sound
    data:
      account: !secret anja_icloud_account
      device_name: !secret anja_icloud_device
#

what I actually want to pass two variables of arrays for example first array [account1, account2, ..] and second [device_name1, device_name2,...] and to do for loop to match each pair and to trigger service: icloud.play_sound

#

I want to create script that is uniform regardless on how many devices I have

marble jackal
#

Do you always want to find all?

#

But anyway, you could probably do this:

# secrets.yaml
accounts: [ 'account1', 'account2', 'account3' ]
devices: ['device1', 'device2', 'device3' ]
#
# script
alias: Find Iphone
sequence:
  - variables:
      accounts: !secret accounts
      device: !secret devices
  - repeat:
      count: "{{ accounts | count }}"
      sequence:
        - service: icloud.play_sound
          data:
            account: "{{ accounts[repeat.index -1] }}"
            device_name: "{{ devices[repeat.index -1] }}"
#

Not completely sure if you can import a list like that from secrets.yaml. Otherwise just put "account1, account2, account3" in secrets.yaml (same for devices) and use accounts.split(', ') | count and accounts.split(', ')[repeat.index -1] (again the same for devices)

sonic nimbus
#

thanks @marble jackal I will try

#

I started with something like this:

#
sequence:
  service: >
    {% set data = [{'account':'stefan_icloud_account', 'device_name': 'stefan_icloud_device'}, {'account':'anja_icloud_account', 'device_name': 'anja_icloud_device'}] %}
    {% for item in data%}
      persistent_notification.create
      data:
        title: 'item.account'
        message: "item.device_name"
    {% endfor %} 
#

this is just service persistent_notification, just to see if gonna to work but Im getting an error: Failed to call service script.find_iphone. Template rendered invalid service: persistent_notification.create data: title: 'item.account' message: "item.device_name" persistent_notification.create data: title: 'item.account' message: "item.device_name"

#

so, I believe that your approach is better, just for easier writing a variable data, I would like to be an complex array like this: [{'account':'stefan_icloud_account', 'device_name': 'stefan_icloud_device'}, {'account':'anja_icloud_account', 'device_name': 'anja_icloud_device'}]

marble jackal
#

you could use variables for that:

  - variables:
      data:
        - account: stefan_icloud_account
          device_name: stefan_icloud_device
        - account: anja_icloud_account
          device_name: anja_icloud_device

It will be the same dataset as you did, but more readable I guess

#

And then you can use the repeat:

  - repeat:
      count: "{{ data | count }}"
      sequence:
        - service: icloud.play_sound
          data:
            account: "{{ data[repeat.index -1].account }}"
            device_name: "{{ data[repeat.index -1].device_name }}"
sonic nimbus
#

can you please post here an example of calling that script?

#

like this? ```service: icloud.play_sound
data:

  • account: stefan_icloud_account
    device_name: stefan_icloud_device
  • account: anja_icloud_account
    device_name: anja_icloud_device```
marble jackal
#

No, just add the two code blocks together.

  - variables:
      data:
        - account: stefan_icloud_account
          device_name: stefan_icloud_device
        - account: anja_icloud_account
          device_name: anja_icloud_device
  - repeat:
      count: "{{ data | count }}"
      sequence:
        - service: icloud.play_sound
          data:
            account: "{{ data[repeat.index -1].account }}"
            device_name: "{{ data[repeat.index -1].device_name }}"
#

because of the counted repeat, it will repeat the icloud.play_sound action 2 times

#

if you add more accounts/device_names to the variable, it will repeat it more times

sonic nimbus
#

yes I know, but this is in the script itself..I want to be able to pass only one set of account and device name

#

or two, three sets

marble jackal
#

How do you want to determine to whom it should be sent?

sonic nimbus
#

so I was thinking to pass some array in data section when Im executing the script, or multiple device_name/account statetemnt

#

based on what I put in my data variable (it can be key-value pair)

#

for example

#

{% set data = [{'account':'stefan_icloud_account', 'device_name': 'stefan_icloud_device'}, {'account':'anja_icloud_account', 'device_name': 'anja_icloud_device'}] %}

#

but also I can just send: [{'account':'stefan_icloud_account', 'device_name': 'stefan_icloud_device'}]

marble jackal
#

Just use what I posted above:

- service: script.find_iphone
  data:
    phones:
      - account: stefan_icloud_account
        device_name: stefan_icloud_device
      - account: anja_icloud_account
        device_name: anja_icloud_device
#
alias: Find Iphone
sequence:
  - repeat:
      count: "{{ phones | count }}"
      sequence:
        - service: icloud.play_sound
          data:
            account: "{{ phones[repeat.index -1].account }}"
            device_name: "{{ phones[repeat.index -1].device_name }}"
#

But if you want you can also format the variable lin json like you did

#
- service: script.find_iphone
  data:
    phones: [{'account':'stefan_icloud_account', 'device_name': 'stefan_icloud_device'}, {'account':'anja_icloud_account', 'device_name': 'anja_icloud_device'}]
sonic nimbus
#

it works! thanks @marble jackal

rugged kernel
#

Hi, I'm missing something stupid I think. I'm trying to setup a generic thermostat using a temp sensor and a switch to toggle a space heater.

I made a climate folder in my config and made a file name generic_thermostat.yaml in that folder.

I followed the template provided at https://www.home-assistant.io/integrations/generic_thermostat/#-----configuration-variables--

I saved my file and restarted my homeassistant core.

I expect now to see a thermostart card available named "climate.bedroom_heater" or something similar. But all I'm seeing is my current thermostat as an option.

jagged obsidian
#

Did you point the climate: entry to that folder?

rugged kernel
#

I did not. Is there documentation I should look for to learn more about how to do that?

rocky vector
#

Hello - how can I make this work please? I think there are so many quote marks it might need escaping somewhere in the media_content_id piece as the 'sensor.next_pm_episode' part is not being rendered as text according to the HA check config tool. Thanks! https://pastebin.com/8bGVFbi6

rocky vector
#

It works in the template dev tools though… 🤔

#

'{"app_name": "bbcsounds", "media_id": "{{ states('sensor.next_pm_episode') }}"}'

light tundra
rocky vector
#

Thanks! So states("sensor……?

light tundra
#

yep. Should work, since whatever in double curly brackets just gets interpreted as python code or something

torn meteor
#

tricky one: for a template switch, can you add a "wait" or "timeout" for sensing that the switch is actually OFF before HA moves the toggle?

#

my turn_off command is not instant on the source device, so i switch it off, the toggle goes off, then immediately goes back on, then after 1-2 seconds, it properly reads the state of the source device and goes back to the off position

marble jackal
rocky vector
torn meteor
zenith junco
#

I'm trying to get my bitcoin miner reporting into my HA

#

but it seems like the JSON is not quite reporting correctly

#

when I pull the API Straight I get this output

#

`{'STATUS': [{'STATUS': 'S', 'When': 1642820988, 'Code': 11, 'Msg': 'Summary', 'Description': 'cgminer 4.9.2'}], 'SUMMARY': [{'Elapsed': 19724, 'MHS av': 55402837.74, 'MHS 5s': 57494209.4, 'MHS 1m': 55588695.16, 'MHS 5m': 55549978.78, 'MHS 15m': 55444417.61, 'HS RT': 55549978.78, 'Found Blocks': 0, 'Getworks': 1300, 'Accepted': 7220, 'Rejected': 1, 'Hardware Errors': 44, 'Utility': 21.96, 'Discarded': 953550, 'Stale': 0, 'Get Failures': 0, 'Local Work': 134003269, 'Remote Failures': 0, 'Network Blocks': 27, 'Total MH': 1092764884270.0, 'Work Utility': 3023.31, 'Difficulty Accepted': 252398752.0, 'Difficulty Rejected': 40336.0, 'Difficulty Stale': 0.0, 'Best Share': 435993055, 'Temperature': 72.0, 'freq_avg': 847, 'Fan Speed In': 7110, 'Fan Speed Out': 7110, 'Voltage': 1230, 'Power': 3429, 'Power_RT': 3430, 'Device Hardware%': 0.0044, 'Device Rejected%': 4.0585, 'Pool Rejected%': 0.016, 'Pool Stale%': 0.0, 'Last getwork': 0, 'Uptime': 21109, 'Chip Data': 'HPND06-19102101 BINV04-192106B', 'Power Current': 248, 'Power Fanspeed': 8850, 'Error Code Count': 0, 'Factory Error Code Count': 0, 'Security Mode': 0, 'Liquid Cooling': False, 'Hash Stable': True, 'Hash Stable Cost Seconds': 2286, 'Hash Deviation%': 0.2697, 'Target Freq': 824, 'Target MHS': 54166464, 'Power Mode': 'Normal', 'Firmware Version': "'20210322.22.REL'", 'CB Platform': 'ALLWINNER_H3', 'CB Version': 'V8', 'MAC': 'C4:08:20:00:E9:F2', 'Factory GHS': 55347, 'Power Limit': 3500, 'Chip Temp Min': 0.0, 'Chip Temp Max': 0.0, 'Chip Temp Avg': 0.0}], 'id': 1}'

#

'''test'''

#

damnit

silent barnBOT
buoyant pine
#

that's a dict, not JSON

#

json.dumps() will convert the dict to JSON

#

@zenith junco

zenith junco
#

@buoyant pine - Thank you for answering the question, but not quite understanding. can you help me with the python script to get it into HA?

#

'''import json

from whatsminer import WhatsminerAccessToken, WhatsminerAPI

token = WhatsminerAccessToken(ip_address="10.0.1.78")
summary_json = WhatsminerAPI.get_read_only_info(access_token=token, cmd="summary")

print(summary_json)'''

buoyant pine
#

seems like something that would be perfect to update to push data to MQTT and run in a container

#

btw:

silent barnBOT
#

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

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

For over 15 lines you must use a code share site such as https://www.codepile.net/ (pick YAML for the language) or https://paste.debian.net/ (pick YAML for the language).

zenith junco
#

@buoyant pine OK - how can I publish a dict into mqtt which I do have, and get publish the results to HA

#

sorry, not a full on coder but can read and write basic code

#

and I'll use the codepile from now on. than kyou

buoyant pine
#

the point of me using that command was to show you how to do inline code

#

it's not three single quotes, it's three backticks

zenith junco
#

@buoyant pine can I pay you to format and get it into MQTT? I don't have time to screw with this but I need monitoring on my miner

#

Or is there a good resource for HA guys that are looking for some work?

mighty ledge
#

$$

buoyant pine
#

I can throw it together tomorrow or Sunday. You don't need to pay me

zenith junco
#

@buoyant pine How about I donate or do something to pay it forward? I know I can figure it out if I spend the weekend trying to get the formatting correct but at the end of the day I just and to see if a) the miner is working and b) if its overheating. I dont want to have to go down a rabbit hole

buoyant pine
#

If you felt so inclined after I put it together, I do have a buy me a coffee link

zenith junco
#

Absolutely

#

Let me know what you need from me

#

And this seems like something that would be a great module for HA in general athough I dont know the users of whatsminer & HA together

#

and - I dont know what building a module entails so just tell me to shut up and appreciate the help 😄

sonic nimbus
#

Hello, I want to create a sensor which will tells me how many seconds are passed from last trigger to on

#

I have this {{as_timestamp(states.binary_sensor.bedroom_bed_left_motion.last_changed)

#

so, with combination with condition-state (triggered on), I think I will be able to know how many seconds passed away from last triggered on state

#

but I dont know how to cast to seconds, now, i get epoh linux time

fossil venture
#

{{ as_timestamp(now()) - as_timestamp(states.binary_sensor.bedroom_bed_left_motion.last_changed) }}

sonic nimbus
#

thanks!

fossil venture
sonic nimbus
#

yes

#

I want to have a sensor which will be telling me how much secons gone from last trigger state to on

fossil venture
#
value_template: >
  {% if is_state('binary_sensor.bedroom_bed_left_motion', 'on') %}
    {{as_timestamp(states.binary_sensor.bedroom_bed_left_motion.last_changed) | timestamp_custom('%A %d-%b-%y, %H:%M:%S')}}
  {% else %}
    {{ states('sensor.bedroom_bed_left_motion_last_occured') }}
  {% endif %}
#

Actually you probably don't want that first result in seconds. I just edited the post and added your template from the other channel.

radiant steppe
#

Hi everybody!

I'm not sure where to post this, i'm sorry in advance if this is not the correct channel.

I have implemented ESC control for a brushless motor via a ESP8266 using ESPHome.
The values used to control the ESC from HA range from -50 (0%) to 0 (100%)

Is there a way i can clean up these values in order to show them on the lovelace dashboard in the proper % values?
Any pointers are much appreciated!

silent barnBOT
obsidian lintel
#

I am trying to create a dummy light entity with hue options, I managed to get the brightness working and displaying on my floorplan. Color wise, it didnt work, can anyone advice? https://hastebin.com/alifusinik

mighty ledge
zenith junco
#

Question on JSON

#

#WhatsMiner

  • platform: command_line
    name: WhatsMinerHank
    command: "python3 whatminer.py"
    value_template: '{{value_json.summary.temperature}}'
#

give me a unknown

#

value

zenith junco
#

#WhatsMiner

  • platform: command_line
    name: WhatsMinerHank
    json_attributes:
    • Temperature
    • Power
      command: "python3 whatminer.py"
      value_template: '{{ value_json.SUMMARY }}'
#

So changed the calls to case sensitive

#

Does not appear to fix it

small rock
#

I have a template (https://pastebin.com/sUW1NRmX) to get the sum of all the consumption of smart plugs or lights. Each time I restart HA or Zigbee the value drops as some or all sensors all unavailable. Giving me a rather larger number of consumption which isn't correct. What I'm doing wrong ? Can this be resolved i a way?

marble jackal
#

Add an availability template so the sensor is only available when all source sensors are

#

Or add a statistics sensor to store the max value of your template sensor, and use that value in your template of the result is lower

#

Or both

small rock
#

@marble jackal could you please help me with an example?

#

I'm looking in to the statistics as it could always be that an consumption sensor is unavailable

#

How could I get the max value of

- platform: statistics
  name: "Statistics Overall Consumption"
  entity_id: sensor.overall_consumption
  state_characteristic: mean
next bane
#

hi all! Can you please help me find a way to access a sensor's past value ? (I'd like to get the diff between the actual value and the last one)
thx!

craggy rain
#

Hi everyone. I'm struggling with a recent idea I had. I have a Sonoff S31 (smart plug with power monitoring) that I've connected to my sump pump. I have a binary sensor template that I've created to track if the sump pump is "on" or "off" based on the power usage measured by the S31. This binary sensor is working just fine.

My new goal is to have a way to display (I'm assuming via a new template/entity) the last time that the sump pump was "on" based on this binary sensor's status. I'm building a display in my basement that would read various stats, but include something along the lines of "Sump Pump Last On: Jan 23 2022 8:00AM".

I've researched a few options, tried implementing them. Please take a look at my configuration.yaml code and see if I am close, or if you have any suggestions. Thank you!

https://www.toptal.com/developers/hastebin/wunovoteba.php

Also, I saw this recent advice from tom, which looked to be very close to what I am trying to do. https://discordapp.com/channels/330944238910963714/672223497736421388/934399119953371136

small rock
#

@next bane thanks

marble jackal
#

Is it somehow possible to template an entire script sequence? I have something which kinda works, but only for service calls.
I now use this:

    - repeat:
        count: "{{ action | count }}"
        sequence:
          - service: "{{ action[repeat.index -1].service }}"
            target: "{{ action[repeat.index -1].get('target', {}) }}"
            data: "{{ action[repeat.index -1].get('data', {}) }}"
#

I can use scripts as work around, since they can be called using a service call, but if somehow possible I would like to allow all types

inner mesa
#

Maybe everything below data, but not everything

marble jackal
#

Okay, I'll work with what I now have then 🙂

#

everything below service, target and data works

#

so basically all service calls work

buoyant pine
nocturne chasm
#

If he doesn’t need it…..I 110% don’t need it. Just saying.

#

And it is Sunday….you should be busy pampering your better half

vestal warren
# radiant steppe Hi everybody! I'm not sure where to post this, i'm sorry in advance if this is ...
calibrated_esc_value:
  value_template: '{{ (states.sensor.esc_entity.state|float +50)*2 }}'


calibrated_esc_value_better_if_min_max_available:
  value_template: '{{ (states.sensor.esc_entity.state|float - states.sensor.esc_entity.attributes.min) * 100 / (states.sensor.esc_entity.attributes.max - states.sensor.esc_entity.attributes.min) }}'

That might do it.
The second option is more dynamic and allows for variance in the reported min/max of the entity (if it is reported in the attributes of the entity)

zenith junco
#

@buoyant pine Hey So I got it outputing in JSON instead of DICT

#

But - I still am getting unknown when I try get it into a template

#
import json

from whatsminer import WhatsminerAccessToken, WhatsminerAPI

token = WhatsminerAccessToken(ip_address="10.0.1.78")
summary_json = WhatsminerAPI.get_read_only_info(access_token=token, cmd="summary")

json_object = json.dumps(summary_json, indent = 4) 
print(json_object)
#

Outputs to this

#
#WhatsMiner
  - platform: command_line
    name: whatsminerhank
    json_attributes:
      - Temperature
      - Power
    command: "python3 whatminer.py"
#

Is what I have in my configation.yaml

vestal warren
zenith junco
#

I'm still doing it wrong 😦

vestal warren
#

The ticks are '`' the key is to the left of the number 1, you appear to be tying the single quote

zenith junco
#

oh

#

k

#

Thank you

vestal warren
zenith junco
#
#WhatsMiner
  - platform: command_line
    name: whatsminerhank
    json_attributes:
      - Temperature
      - Power
    value_template: "{{ value_json['STATUS']['STATUS'] }}"
    command: "python3 whatminer.py"
#

Still saying unknown

#

Testing after name, before json_att

buoyant pine
#

Probably exceeds the state length limit

#

Check the log

#

Oh, nvm. Status, not summary

#

"{{ value_json['STATUS'][0]['STATUS'] }}"

#

@zenith junco

zenith junco
#

Still unknonw

#
#WhatsMiner
  - platform: command_line
    name: whatsminerhank
    value_template: "{{ value_json['STATUS'][0]['STATUS'] }}"
    json_attributes:
      - Temperature
      - Power
    command: "python3 whatminer.py"
buoyant pine
#

Check the log

zenith junco
#

Nothing is log as far as I can see. Searching for whatsminer

buoyant pine
zenith junco
#

is the file name, good catch but ya its correct

#

permissions?

#

maybe?

buoyant pine
#

really need some logs

zenith junco
#
logger:
  default: critical
  logs:
    homeassistant.components.http.ban: warning
    homeassistant.components.sensor: debug
    homeassistant.components.serial: debug
    homeassistant.components.sensor.serial: debug
#

Can I crank up the logs on this?

buoyant pine
#

your default is set to critical? that means you basically get no logs

zenith junco
#

k, fixing

#
Logger: homeassistant.components.command_line
Source: components/command_line/__init__.py:41
Integration: command_line (documentation, issues)
First occurred: 9:03:02 PM (2 occurrences)
Last logged: 9:04:03 PM

Command failed: python3 whatminer.py
buoyant pine
#

use the absolute path of the file in the container

zenith junco
#

I have another file in the same location that works

#
##Niles Home Audio
  - platform: command_line
    name: NilesActive
    command: "python3 pyserialtest.py znc,5"
#

I mean, I'll try the absolute path but its weird that one would work and one wouldn't

buoyant pine
#

exec into the container and run the command

real terrace
#

I'm trying to take a binary vibration sensor and turn it into my Dryer's status. But I want to delay the "Dryer Status" sensor from changing unless the vibration sensor has been in the Clear or Detected state for longer than a certain duration. Ican't figure out how to set this up in my config yaml

zenith junco
#

@real terrace Node Red works really well for doing that Kind of function

buoyant pine
zenith junco
#

what kind of vibration sensor are you using

#

and yes, listen to Tediore - I'm mediocre at best 😄

#

@buoyant pine So you want me to do

docker exec -it container-name sh
#

and then run the shel command

#

?

#

/config # python3 whatminer.py
Traceback (most recent call last):
File "/config/whatminer.py", line 3, in <module>
from whatsminer import WhatsminerAccessToken, WhatsminerAPI
ModuleNotFoundError: No module named 'whatsminer'
/config #

buoyant pine
#

or just do docker exec -it home-assistant python3 whatminer.py

zenith junco
#

OK

#

Got it

#

I need the whatsminer module installed in the docker?

buoyant pine
#

well yeah, but you'd need to do that every time you upgrade the container

zenith junco
#

ick

buoyant pine
#

which is why i suggested my solution 😄

zenith junco
#

what solution? Sorry Maybe I missed it

buoyant pine
#

what we talked about the other day

#

making a container of it that pushes the data to MQTT

zenith junco
#

Oh ya, the MQTT Thing

#

Well thats above and beyond my ability I think

buoyant pine
#

i said i'd make it

zenith junco
#

Well I would owe you 🙂

buoyant pine
#

you wouldn't; i do this stuff for fun

zenith junco
#

Yes, I saw that, but I figured I was making progress getting it into JSON

#

😄

#

I would very much appreciate a module that would publish to MQTT

buoyant pine
#

i'll probably have some time tonight

zenith junco
#

Thank you!

sonic nimbus
#

hello, can you please tell me what is wrong with my script that it has rgb_color templating:

#

Im getting the eror:

#

[22870602721072] Error handling message: None for dictionary value @ data['rgb_color']. Got None

#

more precise question would be: is this legit:

             ["{{range(256)|random}}","{{range(256)|random}}","{{range(256)|random}}"]```
mighty ledge
#

no, your numbers are in quotes

#

it expects a list of numbers, not a list of string numbers

#

you're confusing yourself by using the >

#

remove the quotes or remove the arrow and put it on the line above

sonic nimbus
#

Yes, I had earlier like this: rgb_color: > [{{range(256)|random}},{{range(256)|random}},{{range(256)|random}}]

#

but the same error message occurs

sonic nimbus
mighty ledge
dreamy sinew
#

could save 8 chars and probably a bit of processing time if you render the thing as one template instead of 3

sonic nimbus
#

hmm eventually I had a problem in other section of my script: rgb_color: "{{rgb}}"

#

and this is my input variable

#
      description: 'If rgb random is False, sets wled light to provided rgb color'
      example: '[0,255,0]' ```
craggy rain
#

I'm unsure if this is allowed, but I didn't see any responses to my question from over the weekend. Does anyone have a chance to take a look at this request for help? #templates-archived message

#

Sump Pump Last On Template

mighty ledge
#
template:
- trigger:
  - platform: state
    entity_id: xyz.abc
    to: "on"
  sensor:
  - name: Last on for xyz.abc
    unique_id: last_on_for_xyz_abc
    state: "{{ now() }}"
    device_class: timestamp
#

it won't persist through shutdowns. If you want that, make an automation that sets an input_datetime

craggy rain
mighty ledge
craggy rain
spiral imp
#

This sensor should stay "on" for 2 hours after it stops snowing or sleeting correct?

binary_sensor:
  platform: template
  sensors:
    snowing:
      friendly_name: Snowing
      value_template: >-
        {{ states('sensor.dark_sky_precip') in ['snow', 'sleet'] }}
      delay_off:
        minutes: 120
marble jackal
#

Yes, but I'm not 100% sure if delay_off accepts this format.
delay_off: "02:00:00" will for sure

mighty ledge
#

It’s any format

spiral imp
#

Is there something that could cause this to break? Earlier, sensor.dark_sky_precip changed from "snow" to "unknown" at 12:03 and the sensor turned off at 12:06

teal umbra
#

Hi i am trying to create a sensor which gives the remaining time of a running timer (set in an automation )
{{ (as_timestamp(state_attr('timer.leaving', 'remaining')) - as_timestamp(now())) | timestamp_custom('%Mm %Ss') }}
But this is throwing an error any help?

marble jackal
#

Define an error

teal umbra
#

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

marble jackal
#

This works if you replace the timer with yours

{% set seconds = (as_datetime(state_attr('timer.vaatwasser_timer', 'finishes_at')) - now()).seconds %}
{% set hours = (seconds / 3600) | int %}
{% set minutes = ((seconds - hours * 3600) / 60) | int %}
{{ hours ~ 'h ' ~ minutes ~ 'm' }}
teal umbra
#

It gives this error TypeError: float() argument must be a string or a number, not 'NoneType'

pliant agate
#

Evening all, don't suppose anybody would mind point out something I'm failing at here

#

wait_template: "{{ state_attr('climate.heating_2', 'temperature') == (states('input_number.boost_target_temperature')) }}"

#

Both figures from state_attr('climate.heating_2', 'temperature') and ('input_number.boost_target_temperature')) are coming out at 24.9 but it's returning false...

jagged obsidian
#

Are they returned as strings or float?

silent barnBOT
craggy rain
vague tulip
#

Hey guys, in my configuration.yaml I have "switch: !include switch.yaml" but when I try to edit my switch.yaml file to add a virtual switch I have the following on line 1 - platform: switch Property platform is not allowed

does anyone know why I would be getting that?

inner mesa
#

yes, you have switch: on teh first line and you should remove it

vague tulip
#

I don't have switch: on the first line, the first line is " - platform: switch"

inner mesa
#

ok, then I wonder what you're hoping to get from platform: switch

vague tulip
#

to create a virtual switch?

inner mesa
vague tulip
#

I have "switch: !include switch.yaml" in the configuration.yaml file to include the switch.yaml file so I shouldn't need the switch: on the first line

inner mesa
#

that is true

vague tulip
#

because the config is calling that file under the include command

inner mesa
#

what do you mean by "virtual switch"?

vague tulip
#

Yes... ?

#

where it's saying the light switches are using the platform switch not template

inner mesa
#

then that says platform: template

#

that's for a light switch

#

if you're talking about this:

#
- platform: switch
  name: "Patio Lights"
  entity_id: switch.patio_lights
#

that's under light:

silent barnBOT
inner mesa
#

this is why I asked what a "virtual switch" is - it isn't really a thing

vague tulip
#

ok... what I was using before Home Assistant was Samsung Smartthings where I could create a virtual switch that could trigger something... is there no way for me to create a switch without having something physical to tie it to?

inner mesa
#

that's the template switch that I mentioned above

#

you can do whatever you want when it turns on and off

vague tulip
#

I've had HA for only a few weeks and know... not a whole lot about it.

inner mesa
#

and report whatever state you want

#

but what you may want is just an input_boolean

silent barnBOT
inner mesa
#

that's just a thing that you can turn on and off and can trigger things

#

it's called a "toggle" in the UI

vague tulip
#

So if I wanted to have a button on the lovelace screen to trigger something in node red, the input boolean would be what I want?

inner mesa
#

a button generally has no state

#

you would just use a button card and do somethign in the action

vague tulip
#

ok, the button would toggle on/off or set a state, which in turn would trigger something in node red

inner mesa
#

I don't know what can trigger Node-Red

#

those are your options

vague tulip
#

ok, thanks for the help

vague tulip
#

@inner mesa, the input_boolean did the trick. Thanks for pointing it out.

manic onyx
#

hello. I have setup a statistics sensor. How do I round its value to an integer (its a mean value)?

#

do I need to make another sensor and use value_template?

haughty kiln
#

hi friends. i can't figure out what i'm doing wrong here to exclude these under cabinet lights. everything else in this template is working correctly: {% if expand(states.light)| selectattr('state','eq','on')| rejectattr('attributes.type','eq','browser_mod' )|rejectattr('cabinet' in 'attributes.friendly_name') | list | count == 1 %} There is a light on {% elif expand(states.light)| selectattr('state','eq','on')| rejectattr('attributes.type','eq','browser_mod' )|rejectattr('cabinet' in 'attributes.friendly_name') | list | count > 1 %} There are {{ expand(states.light)| selectattr('state','eq','on')| rejectattr('attributes.type','eq','browser_mod' )|rejectattr('cabinet' in 'attributes.friendly_name') | list | count }} lights on {% else %} All lights are off {% endif %}

inner mesa
#

You're using rejectattr with two different forms, and only the first is correct

haughty kiln
#

my first attempt was rejectattr('attributes.friendly_name','in','Under') - equally unsuccessful 😦

inner mesa
#

That's the opposite of what you want

#

Use 'search' instead of 'in'

haughty kiln
#

aha, thanks

inner mesa
#

And the rest of that page

#

It's about 6 months old

merry furnace
#

Good morning, I have a specific question trying to better understand the different use of {} and {{}} in automations.
I have read in the jinja docs that {} is for statements and {{}} for expressions.
I did however come across some instances where someone puts an if statement between {{}}. So now I'm a bit confused.

marble jackal
#

Hi! 😉

merry furnace
#

😉

marble jackal
#

Well, I'm not sure about the terminology here, but as I see it, you can write an if statement in a expression.

{{ 'hello' if is_state('person.you', 'home') else 'goodbye' }}

Is basically the same as:

{% if is_state('person.you', 'home') %}
  hello
{% else %}
  goodbye
{% endif %}
#

Depends a bit on how complicated your if/elif/else statement is, and how you are using the result on which one is more appropriate

merry furnace
#

that's indeed how I found it.

#

So the first one is indeed also alright.

marble jackal
#

Yes

#

You can test for yourself in devtools > Templates

merry furnace
#

And would this be a viable use?
- service: switch.turn_{{ 'on' if trigger.atribute == 'sunset' else 'off' }}

#

ah I'll have a look in templates in the dev tools

marble jackal
#

not sure what trigger.attribute should refer to, but it is a valid use

#

do you mean trigger.id?

merry furnace
#

the trigger is the sun platform

marble jackal
#

What do you have as trigger?

#

Please do note that the trigger data is only available in the automation itself, so you can not use that in devtools > templates

#

unless you copy it from a previous run of the automation (from the trace) and define it in the template checker

merry furnace
#

Just discovered that

#
alias: Buiten verlichting in de nacht
description: Zet de buitenlampen aan bij schemering en nacht
trigger:
  - platform: sun
    entity_id: sun.sun
    atribute: sunset
  - platform: sun
    entity_id: sun.sun
    atribute: sunrise
action:
  service_template:
- service: switch.turn_{{ 'on' if trigger.atribute == 'sunset' else 'off' }}
    target: 
      {% if state(light.tuin_schuur_251 == "off" %} - entity_id: light.tuin_schuur_251 {% endif %}
      - entity_id: group.tuinlampen_lights
mode: single
marble jackal
#

if you change it to:

trigger:
  - platform: sun
    entity_id: sun.sun
    atribute: sunset
    id: "on"
  - platform: sun
    entity_id: sun.sun
    atribute: sunrise
    id: "off"
merry furnace
marble jackal
#

you can use:

action:
- service: switch.turn_{{ trigger.id }}
merry furnace
#

ah clean

marble jackal
#

service_template is depreciated a long time ago

#

and your template for target won't work like this

#

What are you trying to do there?

merry furnace
#

I want to check if a main switch is on or off. If off I need to turn it on first. In the lights group there is a light (Hue) that only works if the main power to it is on.

marble jackal
#

you can not turn on a group with the service switch.turn_on

#

do you also want to turn that switch off on sunrise?

merry furnace
#

that specific main switch? no.

marble jackal
#

You are mixing different trigger types

#

either use:

  - platform: sun
    event: sunset
merry furnace
#

ah sunset and sunrise are not attributes. They are events of sun (happening at certain timing of attributes of sun.sun)

marble jackal
#

or

  - platform: state
    entity_id: sun.sun
    to: above_horizon

or

  - platform: numeric_state
    entity_id: sun.sun
    attribute: elevation
    above: 0
#

correct

#

elevation is an attribute

#

and the state of the entity sun.sun is either above_horizon or below_horizon

#

But, to go back to the action part. I think you could use this (after you fix the trigger):

- service: homeassistant.turn_{{ trigger.id }}
  target: 
    entity_id: >
      {% if trigger.id == 'on' %}
        [ 'light.tuin_schuur_251', 'group.tuinlampen_lights' ]
      {% else %}
        [ 'group.tuinlampen_lights' ]
      {% endif %}
#

messed up some quotes

#

note I'm using homeassistant.turn_on now, which can toggle everything which can be toggled

merry furnace
#

cool, was trying to search for how to turn on a group with different types of entities in it (Switches and lights)

marble jackal
#

indentation was also off, fixed that now

merry furnace
#

🙂

silent barnBOT
merry furnace
marble jackal
#

Is there a question?

mighty ledge
merry furnace
# marble jackal Is there a question?

No, sorry, I saw that HassBot pushed my code to hastebin and then signed on with codepile to paste the code in that way. I think that's how I should have posted it?

mighty ledge
#

well you didn't ask a question with the code

spiral imp
#

I have this template to get the next event from these calendars. Two of calendars do not have events so the start_time attribute is "None". This is causing an error with the min filter. I assume I need to use either is_number or is_numeric somewhere but not sure where.

        value_template: >-
          {% set event = [ 
            (states.calendar.family_gmail_com.attributes.start_time) | as_timestamp,
            (states.calendar.glen_meet_event_calendar.attributes.start_time) | as_timestamp,
            (states.calendar.teamsnap.attributes.start_time) | as_timestamp,
            (states.calendar.legacy_center_llc_calendar.attributes.start_time) | as_timestamp,
            (states.calendar.total_sports_complex_calendar.attributes.start_time) | as_timestamp ] %}
          {{ event | min | timestamp_custom ('%b %-d, %Y', false) }}
inner mesa
#

so they don't have a start_time attribute?

#

oh, sorry. you said it was "None"

spiral imp
#

that is correct, if the calendar doesn't have any events, that attribute is not even present

inner mesa
#

oh

spiral imp
#

I should say that the array of values shows "None"

#
value_template: >-
         
          [1643142600.0, None, 1643140800.0, None, None]
#

that is the output without the min filter

inner mesa
#

I don't know if that's a typed value or a string, but you can probably filter it with reject('eq', None)

#

(sorry, multitasking)

spiral imp
#

that filer would go before min?

#

that worked, thanks

#

what does the 'eq' do?

inner mesa
#

equals

spiral imp
#

gotcha

inner mesa
#

the same as '=='

spiral imp
#

One other question, another attribute for these calendars is "location" I would like to only include events in the array that have a location (not blank). Would that be a filter to include for each calendar?

inner mesa
#

yes

mighty ledge
inner mesa
#

could be. they claimed success, though 🙂

mighty ledge
#

🤷‍♂️

#

maybe that changed

#

annoyed the shit out of me for years

inner mesa
#

I think I remember seeing something similar for true vs. True. I just play with it until it works

#

{{ [None, "foo"]|reject('eq', None)|list }} -> ["foo"]

mighty ledge
#

🤷‍♂️

inner mesa
#

QED

mighty ledge
#

There's something that causes it to fail somewhere

#

I've been purposely using none because of whatever it was

#

Ah

#

found it

#

it's not a valid test

#

none is

#

{{ None is none }} works

#

{{ none is None }} does not

#

the test is the 2nd item

#

so, I just use none everywhere

mighty ledge
inner mesa
#

good thing I didn't recommend that 🙂

mighty ledge
#

although, is might not be a valid test for select

#

either way, I just use none everywhere

spiral imp
#

What would that filter to exclude events with a blank location attribute look like? This is still using my above template

mighty ledge
#

selectattr('attributes.xyz', 'defined')

spiral imp
#

and that would just go as a filter on each calendar entity?

mighty ledge
#

your template is bad, you should be using expand, not state objects. Then you could actually use filters properly

#

I'm guessing you copied/pasted this from someone else?

inner mesa
#

true, would be better to start with state objects and filter them

spiral imp
#

it may have been from you from a different template that you helped me with 😑

mighty ledge
#

no, I don't use state objects as declared items

#
          {% set event = [ 
            'calendar.family_gmail_com',
            'calendar.glen_meet_event_calendar',
            'calendar.teamsnap',
            'calendar.legacy_center_llc_calendar',
            'calendar.total_sports_complex_calendar' ] %}
          {{ expand(event) | selectattr('attributes.start_time', 'defined') | map(attribute='attributes.start_time') | map('as_timestamp') | min | timestamp_custom ('%b %-d, %Y', false) }}
inner mesa
#

(that's what I meant)

#

add the "location" filter in there too

spiral imp
#

that makes sense, thanks

#

what do the map filters do?

mighty ledge
#

@inner mesa would you rather have a new method selectstate('>', 45) or new tests that convert the comparision when running it. e.g. to make this work selectattr('state','>', 45)

#

i'm trying to think

#

or maybe a selectattrcast

#

selectattrcast('state', 'int', '>', 45)

inner mesa
#

I think the usage of "attribute" in Jinja is confusing

mighty ledge
#

it should be selectprop, but they named it attr for some reason

inner mesa
#

yeah

mighty ledge
#

anyways, I want to add this in because it keeps coming up, but I want it to work with datetimes or numbers, or any type

#

basically, states being a string is stupid and makes it hard to use filters when your trying to find numbers

#

or datetimes

inner mesa
#

I guess there's no other way to do a conversion like that without losing the rest of the object

mighty ledge
#

right now there isn't

#

however, i'm going to add something that does this

#

free rein atm

#

I've been holding off adding it because I can't think of a clean way to do it

inner mesa
#

I like that it could be smart about what to cast the value to based on the incoming data type, but I'm not sure you have enough information to do that right

#

or I guess you're casting the incoming data type based on the value

spiral imp
#

is this still related my template or someting else?

inner mesa
#

ssshh, we're solving world peace

mighty ledge
#

unrelated

spiral imp
#

haha, I figured. Thanks

mighty ledge
#

tests are basically 2 arguments

#

this and that

#

this and other

#

however you want to think of it

#

and you can type check both

#

so basically the definition of '==' is __eq__(self, other): where self is... well self, and other is the other object. And you can do isinstance(other, ...)

#

the only drawback to selectstate( is that it only works on state. If you have an attribute thats a string representation of a datetime, then it won't work.

#

anyways, if you come up with anything let me know, i've been asking people for ideas

inner mesa
#

yeah, I don't think adding n functions to handle n properties is the way

mighty ledge
#

right

#

well, it could be 2

#

selectstate( and selectstateattr(

#

but yeah, less work = better

inner mesa
#

"selectstateattr" is so confusing

mighty ledge
#

🤷‍♂️

#

i'm open to naming ideas

inner mesa
#

I'll think about it. I understand the problem and I don't see an existing solution that isn't gross

mighty ledge
#

yep, that's why I haven't added it

#

it's goign to be as complicated as selectattr

#

basically.

marble jackal
#

I think the selectattrcast is the best option

#

At this moment

inner mesa
#

I dint know if limiting it to casting types is the right call. Applying a filter, regardless of function, like map(), would be more general

mighty ledge
#

the problem is map transforms what you're looking at

#

the goal is to transform the result but maintain the object

inner mesa
#

I understand, just as an analog for what we could do

mighty ledge
#

i.e. filter based on an attribute, while comping the intended state, not the actual state

inner mesa
#

Point is that turning something into a float is just a function, as is multiply()

mighty ledge
#

but that won't solve things like filtering out battery levels while you only care about the names of said batteries

#

which is currently only possible via namespace

#

same goes for min or max, lets say you want to get the min temperature in your house. So, try to get the min temperature from a series of sensors without creating 2 generators and outputting only the name

obsidian lintel
#

expand(states.climate) |
selectattr('state','eq','cool')| list | count

Is there a "not equal to" option for selectattr?

mighty ledge
#

!=

#

or ne

obsidian lintel
#

Thankss

craggy rain
mighty ledge
#

or go straight strftime(.. with your timestamp

marble jackal
pliant agate
#

Evening all, don't suppose anybody would mind point out something I'm failing at here
wait_template: "{{ state_attr('climate.heating_2', 'temperature') == (states('input_number.boost_target_temperature')) }}"
Both figures from state_attr('climate.heating_2', 'temperature') and ('input_number.boost_target_temperature')) are coming out at 24.9 but it's returning false

#

I'm expecting if the two are equal it should be True but maybe I'm wrong..

sonic nimbus
#

Hello, how can I check which trigger is occurred from condition-event sunrise/sunset?

#

I tried something like this

#

I know how for example to check state (trigger.to_state.state) but I got confused with this event trigger

sonic nimbus
#

Can you please just point me to docs or write a piece of code?

inner mesa
#

The easiest thing to do would be to add |float to the states() call

buoyant pine
#

Does it have a unit of measurement?

urban pumice
#

Hey guys. I am trying to setup a notification to inform me how many hours/minutes/secs has passed since the last triggered automation e.g. AC power loss.
AC Power Restored. Total Outage Time: {{ as_timestamp(now()) -as_timestamp(states.automation.alarm_ac_power_loss.last_changed) | timestamp_custom('%H:%M:%S') }}
I am getting this error though 😭 TypeError: unsupported operand type(s) for -: 'float' and 'str'

inner mesa
#

you need an extra set of parens

#

you're currently converting the second items into a string and then trying to subtract that from a timestamp

#

but if you really want the time for the last trigger, you should use that instead

#

{{ (as_timestamp(now()) - as_timestamp(states.automation.alarm_armed.attributes.last_triggered))| timestamp_custom('%H:%M:%S') }}

tired sandal
#

Is there an easy way to get the next Monday at any given time?

#

For example, right now that should refer to 2022-01-31

#

A week from today it should be 2022-02-06

inner mesa
#

something like this:

#

{{ (now() + timedelta(days=7-now().weekday())).strftime("%Y-%m-%d") }}

#

2022-02-06 is a Sunday, not a Monday

tired sandal
#

Whoops. You got what I meant though 🙂

#

thanks

#

What governs which day I target? Is that the -7?

inner mesa
#

hard to test with bad data 🙂

#

now().weekday() is the numeric representation of the day of the week with Monday as 0

tired sandal
#

Ah ok

#

So...if I wanted that to be a Tuesday instead of a Monday, I'd change that 7 to...a 6?

inner mesa
#

no

#

7 days in a week

tired sandal
#

Right

inner mesa
#

every Tuesday:

#
{% set today=now()+timedelta(days=1) %}
{{ (today + timedelta(days=7-today.weekday()+1)).strftime("%Y-%m-%d") }}
urban pumice
inner mesa
#

the attribute is in UTC, now() is local

tired sandal
#

Okay...I think I understand. So to that would evaluate to the next Tuesday because days=1?

inner mesa
#

no

#

days=7-today.weekday()+1

tired sandal
#

oh okay, so if that +1 was removed it would then be Monday?

inner mesa
#

again, Monday is 0, Tuesday is 1, Wednesday is 2

tired sandal
#

Gotcha

inner mesa
#

yes, compare with the previosu

tired sandal
#

I think I understand now...

So, why use now()+timedelta(days=1) instead of just now()?

inner mesa
#

the first line is just to simulate a given day

#

change the days=xx to whatever you want and watch the result change

tired sandal
#

right

#

presumably that would mess with the date offsets in the expression

inner mesa
#

it's just changing what "today" is

#

for the purpose of the experiment that you could run

tired sandal
#

Yeah, but wouldn't now() also be today

inner mesa
#

yes

tired sandal
#

like, why use timedelta at all?

inner mesa
#

For example, right now that should refer to 2022-01-31
A week from today it should be 2022-02-06

#

testing that

tired sandal
#

Ah ok

inner mesa
#

just trying to solve your problem 🙂

tired sandal
#

I think I see what you mean now 🙂

#

yeah, thanks - I was just thinking of it all wrong

#

😛

#

so if I changed that to say days=5 that would then cause the expression flip to the following monday?

inner mesa
#

you should try this stuff

#

let's not guess

tired sandal
#

🙂

inner mesa
#

that's why I gave you that

tired sandal
#

yeah

urban pumice
tired sandal
#

thx

inner mesa
#

you can probably use utcnow() to have everything in UTC, but you can also review the large date/time section in the template docs

urban pumice
#

I think I understand now. I tried using utcnow(), but it gave me 23:53:38 😒

    timestamp_custom('%H:%M:%S')  }}```  = 13:57:05 which was my local time when it was triggered UTC +8

Since maybe the attributes is in UTC +8, so i thought I could use ```{{ now().astimezone() }}``` = my current local time. But it gave me the same result - additional 7h30mins
marble jackal
#

{{ as_local(states.automation.alarm_ac_power_loss.attributes.last_triggered).time() }}

urban pumice
#

Thanks guys. Got it sorted now

pliant agate
pliant agate
#

So I gave this a go
'''{{state_attr('climate.heating_2','temperature' |float) == states('input_number.boost_target_temperature')|float}}'''

#

Ignore that formatting was trying to make it look nice in Discord, failed

#

{{state_attr('climate.heating_2','temperature' |float) == states('input_number.boost_target_temperature')|float}}

pliant agate
#

It still returns False

granite whale
#

hello I would like to know if it is possible to condition the card display according to the connected user? I get there in a markdown card with an if user == "myuser" but impossible on a conditional card any idea? I try to create template sensor but not a success

mighty ledge
#

The backend does not know who's logged in like that. This can only be done through custom elements

inner mesa
pliant agate
#

As with most things, I gave in and went with the flow and moved over to Zigbee2Mqtt instead

#

No point trying to reinvent the wheel if it's been mapped already I guess

mighty ledge
#

order of operations () are before filters are applied

pliant agate
#

I may well return to it anyway so I'll keep that in mind

inner mesa
spiral imp
#

This binary sensor template periodically returns "unknown". I have a switch triggered by the state of this template that errors anytime that happens. What could cause this template to return "unknown" instead of on or off?

- platform: template
  sensors:
    snowing:
      friendly_name: Snowing
      value_template: >-
        {{ states('sensor.dark_sky_precip') in ['snow', 'sleet'] }}
marble jackal
#

Probably the dark sky sensor being unavailable

#

Add an availlibility template

spiral imp
#

what would that look like?

marble jackal
#

Look at the bottom at the legacy template sensor docs

#

I can't directly link to it, because the anchor of the new sensor is the same, so it will go to that one

spiral imp
#

I found it but still not sure where that would go. Would I create an availability template for the dark_sky sensor?

marble jackal
#

The template would be something like
{{ not states('sensor.your_sensor') in ['unknown', 'unavailable'] }}

spiral imp
#

so like this? This means the binary sensor state will stay the same if the dark sky sensor goes to unavailable.

- platform: template
  sensors:
    snowing:
      friendly_name: Snowing
      value_template: >-
        {{ states('sensor.dark_sky_precip') in ['snow', 'sleet'] }}
      availability_template: >-
        {{ not states('sensor.dark_sky_precip') in ['unknown', 'unavailable'] }}
marble jackal
#

Yep

spiral imp
#

so probably always a good idea to add these for sensors that determine state or a switch or other devices

marble jackal
#

Yep, I would also advise to have a look at the new format for template sensors, as you seem to be using the legacy format

spiral imp
#

I am trying to understand the availability template recommended above because I am not sure it solves my problem

spiral imp
#

When the dark sky sensor is snow or sleet, the binary sensors turns on. An automation is triggered by the state change of the binary sensor with an action switch.turn_{{ states('binary_sensor.snowing') }} The issue...presumably the dark sky sensor becomes unavailable (although this does not seem to be the case based on the history) and then the binary sensor becomes "unknown", the state change triggers the automation but throws an error because switch.turn_unknown is not a thing. How is the availability template fixing that?

inner mesa
#

you don't want the automation to trigger if it's going to result in an invalid action being executed

#

so whatever you have in the trigger needs to take that into account

torn meteor
#

template switch q: can i debounce a switch that needs a couple seconds to read the value_template?

#

toggle off --> value_template reading a power monitor -> switch turns itself back on -> 4s wait for wattage to drop -> switch turns itself off

#

not a fan of that

#

like "i want you to assume the device is OFF until at least 5 seconds pass, THEN read the value_template state"

inner mesa
#

won't delay_on or delay_off help with that?

fossil hawk
#

Hello, recently I found out that frontend can convert datetime entity states into nice human readable strings like "in 5 minutes" or "1 hour ago". I wonder if there was a similar filter for templates. There is relative_time, but it only works for timestamps in the past.

tired sandal
torn meteor
tired sandal
#

Anyone know how to go about filtering results from a REST sensor?

#

the REST sensor returns results that have a date field. I'm looking to only get results that are >= the current date...preferably just the first one

#

I'm also looking to get a bunch of different fields, but i dont know if that's possible

#

at this point, I'm starting to wonder if it would make sense to just write my own integration

inner mesa
tired sandal
#

Is it possible to filter values returned by sensors at all?

#

Currently, I have this:

- platform: rest
  resource_template: "https://www.republicservices.com/api/v3/holidaySchedules/schedules?latitude={{ state_attr('zone.home', 'latitude') }}&longitude={{ state_attr('zone.home', 'longitude') }}"
  name: 'trash_alerts'
  value_template: "{{ value_json['data'][0] }}"
  json_attributes_path: '$.data.[0]'
  json_attributes:
    - date
    - description
    - name
    - specialNotes
#

The problem is - I end up with the following in state:

date: '2022-01-01T00:00:00.0000000Z'
description: Your pickup will be delayed by one day due to the holiday.
name: New Year's Day
specialNotes: ''
friendly_name: trash_alerts
#

Clearly that's not useful, because that date has already passed.

#

I need a way to somehow manipulate the return value

#

could i do it inside value_template?

inner mesa
#

What do you want it to be?

tired sandal
#

The next item in the list with a date that's after today

#

so...just a sec

#

Here's what the API returns:

#
[{
    "date": "2022-01-01T00:00:00.0000000Z",
    "description": "Your pickup will be delayed by one day due to the holiday.",
    "name": "New Year's Day",
    "phone": "508-832-9001",
    "specialNotes": ""
  },
  {
    "date": "2022-05-30T00:00:00.0000000Z",
    "description": "Your pickup will be delayed by one day due to the holiday.",
    "name": "Memorial Day",
    "phone": "508-832-9001",
    "specialNotes": "Service will be on a one day delay due to the Holiday this week. Please place your cans out by 7 A.M. the day after your normal scheduled pickup day. Happy Memorial Day from Republic Services."
  }]
#

Right now it returns the first element becuase that's the first one. What it should do is filter that down somehow to find the one where date >= now()

#

can I do that in value_template?

#

I mean, I guess I can try it and see - but I want to know if I'm wasting my time before I spend 3 hours on something that just won't work or if there's a better way to do it

inner mesa
#

You should absolutely be able to do that

tired sandal
#

I mean...is that the "correct" recommended way to do this?

#

Basically, Trash night is every <insert day of the week here> - I want HA to show me a notification on that day, but also check in first with this API and see if there's an alert this week. If there is, then show the message from specialNotes

#

But the first part of that is obviously getting the data ingest right.

inner mesa
#

it's kinda horrendous, but it works:

#
{% set data = [{
    "date": "2022-01-01T00:00:00.0000000Z",
    "description": "Your pickup will be delayed by one day due to the holiday.",
    "name": "New Year's Day",
    "phone": "508-832-9001",
    "specialNotes": ""
  },
  {
    "date": "2022-05-30T00:00:00.0000000Z",
    "description": "Your pickup will be delayed by one day due to the holiday.",
    "name": "Memorial Day",
    "phone": "508-832-9001",
    "specialNotes": "Service will be on a one day delay due to the Holiday this week. Please place your cans out by 7 A.M. the day after your normal scheduled pickup day. Happy Memorial Day from Republic Services."
  }]
%}
{% set date = data|map(attribute="date")|map('as_datetime')|select('gt', now())|list|first %}
{{ (data|selectattr('date', 'search', date.isoformat().split('+')[0])|first).specialNotes }}
tired sandal
#

Ah interesting, thanks

inner mesa
#

this is where petro's "transform within select" concept would work well

tired sandal
#

I ended up with something similar

#

{{ trash_json | selectattr("LOB", "equalto", "Residential") | selectattr("serviceImpacted", "equalto", true) | list }}

#

I didn't get quite as far as the date filtering

inner mesa
#

basically, find the date, and then index into the original data structure

tired sandal
#

yeah

#

any reason to use select instead of selectattr?

tired sandal
inner mesa
#

it was a conversation in the last few days in this channel

tired sandal
#

Ah

inner mesa
#

because it's just a datetime at that point, not an structured object

tired sandal
#

Right

#

I mean, ideally, I'd still want the structured object so I can grab the specialNotes field because it sometimes contains useful info

#

Like "Please place your cans out by 7 A.M. the day after your normal scheduled pickup day."

inner mesa
#

yes, but I couldn't figure out how to do that in one expression because the date is a string

tired sandal
#

yeah

#

thanks

inner mesa
#

anyway, with that I'm going to bed

tired sandal
#

Yeah, well thanks for your help!

#

i too am going to bed, lol - it's 1:26am here

torn meteor
small rock
marble jackal
#

The availability template is incorrect. You should not add the numbers there

#

But I don't think you should do both at the same time

small rock
#

@marble jackal I reloaded the config and it just remains unavailable

marble jackal
#

and what is the state of sensor.statistics_overall_consumption

small rock
#

State template result in a value 2207, availability in false

marble jackal
#

then, that's the reason why the complete sensor is unavailalbe

#

remove the availalbility template, reload template entities, and check if that also changes the state of the statistics sensor

small rock
#

should I make a third sensor to be used in the statistics

marble jackal
#

I think the statistics sensor never got correct data so far

small rock
#

the state of the statistics is now the same as template sensor

#

change it again?

marble jackal
#

Yes, you can add it again

small rock
#

After a reload it works

#

after a restart it fails

#

If I add a secondary ccumulative sensor and add that to the sensor it works

#

I'll do it like that

marble jackal
#

Add it where?

small rock
#

hold on

#

@marble jackal ^

#

That works

marble jackal
#

If I'm not mistaken, the goal was to not let your sensor state be lower compared to a previous state
This won't prevent that

#

as, when the statistics sensor is not available, your float filter will default it to 0 and in that case, any result from the sum of device sensors will be higher

small rock
#

Yes that is true, the goal was indeed that never is lower. However it remains unavailable based on your codepile

#

when restarting HA that is

marble jackal
#

But now you achieved nothing compared with what you had 🙂

#

BTW, it just came to mind that when you remove one of the devices, or reset one of the sensors, you'll also have issues (as the sum will be lower). You will miss all energy until you reach the previous value again.

small rock
#

Any other idea then how I could manage that? As I use the sensor for the energy dashboard

marble jackal
#

Don't use it, just use the individual sensors 🙂

small rock
#

Add every item to the grid as net use and as individual device?

marble jackal
#

Well, the grid usage is intended to have your energy meter as input

edgy umbra
#

Hi, anyone know whats wrong with this? Soon as i add the ".round(1)" the card dissapears and no error showing.

#

label: '[[[ return states["sensor.openweathermap_temperature"].state.round(1) + "°C" + " • " + states["sensor.openweathermap_weather"].state]]]'

mighty ledge
#

state is a string

#

can you round a string?

#

also, is that how you round in JS?

edgy umbra
#

Well i have no idea, it was working before i added the round(1), have not realy knowledge about JS etc so i have no idea if this is the right way...

small rock
#

@marble jackal thanks for your help!

marble jackal
# small rock <@!723160143314812971> thanks for your help!

no problem, just thought of an alternative for the statistics sensor. You could create an automation to update an input_number if the value is higher compared to the current value of the input_sensor, and so create your own statistics max as comparison

#

But that value will be available when the source sensor is not

mighty ledge
#

I'm not trying to be an ass here, but I see you alot in here. Many of the questions can be solved with a simple search. I myself never knew JS prior to using HA... So I googled the way to do it and applied what I learned.

#

so the 2 things I would google based on what you already know is: 1. state is a string, and you want it to be a number. 2: You want to round that number.

#

So, search for convert string to number JS, and round JS

#

then apply what you found

#

Guessing about adding .round() at the end of your state is a recipe for disaster. Don't guess, find the answer. Apply the answer. When the application doesn't work, ask a question and post your code with your attempted application.

merry furnace
#

Done! https://www.codepile.net/pile/E89rExpA
One question: I had put the template on a single line with double quotes. HA turned this into multiple line. No issues there. However I was unfamiliar with the dash(-) behind the >
Why is it there?

#

hmm block chomping

mighty ledge
#

look up yaml rules regarding |, >, -

#

those characters are not templating characters, they are yaml characters

merry furnace
#

was just reading about it. They call it he a block chomping indicator apparently

#

To prevent a newline at the end

mighty ledge
#

yep

#

whitespace removal

merry furnace
#

What could be an issue with such whitespace of new line?

mighty ledge
#

well, there really isn't an issue in HA because HA by default removes leading and trailing whitespace on templates

#

so the - is pointless outside the markdown card

#

but everyone does it

merry furnace
#

it even automatically rewrites it in that style.

#

cool

#

Cool to be finally stepping in this templating. I'm trying to slowly convert all the scenes from Fibaro (lua) to HA

#

bytthe way in Fibaro I checked if something was already on before turning it on. It seems not necessary in HA. Is that assumption correct, or could I get into trouble that way later on?

mighty ledge
#

I personally do that check. Choice is yours. The light will receive a turn on command if already on if you don't check and the light is on.

merry furnace
#

in the html guide it states that you con use

condition: not
conditions:
  - condition: state
...```

Do you need to put that ``conditions:`` in there even if you only want to check against one condition?
marble jackal
#

Ah, whitespace control, I was also wondering the same about the dashes in jinja expressions, like eg {%- if foo == bar %-}

merry furnace
#

I guess my own answer should be yes, as I get an error if I leave the plural conditions statement out. Feels strange though.

mighty ledge
#

usually, you only need the {%- and you can forgo the -%}

mighty ledge
#

or you can just use templates

#

which is less verbose

merry furnace
#

If you create a condition and the condition is not met, does that mean that I will not find a log entry, or should i still see a log entry with a trace that tells me that the condition did not meet and the action is not taken? I would expect the latter.

mighty ledge
#

log entires only appear if you hit them and you're using alias

#

otherwise the trace will show you when it failed.. by looking at the trace

merry furnace
#

ouch... sorry. Just getting back and forth between these two channels trying to build automations with templates in them.

#

So not sure where to go with that .. automations or templates 😔

marble jackal
mighty ledge
#

Anyways, your template looks correct

#

Just keep in mind that those triggers will not occur unless they change from False to True

#

so if you're restarting, and they are already True, they will not turn further True and trigger.

merry furnace
#

{{ if state_attr('question' , '#templates') != True go #somehwereelse }}

buoyant pine
#
TemplateSyntaxError: expected token 'end of print statement', got 'True'
merry furnace
#

damn even my joke results in errors 😉

#

strange.. as soon as I compare with this template if the state of the valve is already the same as the trigger.id, the whole automation works fine, but does not show a log item when i change the trigger state to above or below the compared value.

#

So if the template states the condition is not met, nothing happens (which is perfect) but also a log entry won't be written.

mighty ledge
merry furnace
#

in developer tools I change the state of the temperature sensor to a value above or below the trigger level

mighty ledge
#

Actually, do you even know about the trace?

#

you don't have a unique_id attached to that automation

#

so I'm guessing you don't know what traces are

merry furnace
#

Thanks

merry furnace
mighty ledge
#

I don't believe it's covered in the docs

#

if you use yaml, it's just something you learn in time

#

the automation editor automatically adds it

#

for you

#

otherwise just add id: some_long_unique_phrase to your automation at the same indentation as alias

merry furnace
#

-- i guess we are getting to much into automation stuff now -- 😉

mighty ledge
#

we are

acoustic wedge
#

Hello, I'd like to receive a notification each time one of my Aqara temperature sensors stops working (for any reason). I'll detect that by checking if the temperature value did not change during the last 15 minutes. For this, i use this trigger code:

trigger:
    - platform: template
      value_template: "{{ as_timestamp( utcnow() ) | int > as_timestamp( states.sensor.meteo_room_temperature.last_changed ) | int + 15*60 }}"

But how can I do that for all my Aqara sensors without having one automation per sensor?
Thanks.

#

Following my question here, I'm wondering if that's achievable with a template in the trigger.
Let me try to explain.
Of course, I can use multiple entities as triggers like that:

- platform: numeric_state
    entity_id:
    - sensor.humidity1
    - sensor.humidity2
    above: '60'

That will trigger is the humidity value of any of my sensors is above 60. But I can't get how to pass a list of entities and then apply a value_template to each of them. If you have any idea, I'll be happy to try it. Thanks.

marble jackal
acoustic wedge
#

I’ll try that and report tomorrow. Thank you very much.

silent barnBOT
visual gust
#

hi.. hope this is the right place

created this template in configuration.yaml but can i add a icon to it?

#
sensor:
  - platform: template
    sensors:
      weather_wind_dir:
        friendly_name: Vind Retning
        value_template: >
          {% set dir = states('sensor.openweathermap_harboore_wind_bearing')|float %}
          {% if 11.25 < dir <= 33.75 %} NNØ
          {% elif 33.75 < dir <= 56.25 %} NØ
          {% elif 56.25 < dir <= 78.75 %} ØNØ
          {% elif 78.75 < dir <= 101.25 %} Ø
          {% elif 101.25 < dir <= 123.75 %} ØSØ
          {% elif 123.75 < dir <= 146.25 %} SØ
          {% elif 146.25 < dir <= 168.75 %} SSØ
          {% elif 168.75 < dir <= 191.25 %} S
          {% elif 191.25 < dir <= 213.75 %} SSV
          {% elif 213.75 < dir <= 236.25 %} SV
          {% elif 236.25 < dir <= 258.75 %} VSV
          {% elif 258.75 < dir <= 281.25 %} V
          {% elif 281.25 < dir <= 303.75 %} VNV
          {% elif 303.75 < dir <= 326.25 %} NV
          {% elif 326.25 < dir <= 348.75 %} NNV
          {% else %} N
          {% endif %}
silent barnBOT
visual gust
#

code wall 🤨

inner mesa
#

Yes, icon_template is described in the docs

visual gust
#

icon_template: >
{% if is_state('sensor.openweathermap_harboore_wind_bearing', 'clear-day') %}
mdi:weather-windy
{% else %}
mdi:weather-windy
{% endif %}

#

but when i check the config it says invalid

#

but i guess it has to go in a different file than configuration

#

time to read docs

inner mesa
#

It goes right with the rest of the sensor definition. But yes, let the docs be your guide

silent barnBOT
#

Rule #6: Please do not post codewalls (text longer than 15 lines) - use sites such as https://www.codepile.net/ (pick YAML for the language) or https://paste.debian.net/ (pick YAML for the language).

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

inner mesa
#

You're flooding the channel with unformatted code

visual gust
#

i give up... this is what i have come up with from reading the docs and seen what other people report as working
https://pastebin.com/9CwR8yNT
basicly i want to permant change the icon to be the same one always