#templates-archived

1 messages · Page 164 of 1

stuck remnant
#

yeah, it's just an explanation for what triggered me to come and ask again about the same thing :p

#

normally I try not to waste anyone's time

#

sorry

marble jackal
#

@stuck remnant I looked it back, but I see I actually put the state change in the notification, so it should have shown in changed from off to off

stuck remnant
#

oh okay

#

I'll read better next time

marble jackal
#

Well... I think we need to amend the automation which sets the input_datetime

#

Because that will also be triggered here, where it shouldn't

stuck remnant
#

ok

marble jackal
#

So there is actually an issue here

#

add a condition which checks if the to_state differs from the from_state

#

Can you share that automation again?

stuck remnant
#

yes

#

this one I believe

#

but doesn't already have it?

marble jackal
#

No, it checks if the previous state is either on or off, and if the new state is either on or off.
So off to off is valid

stuck remnant
#

oh okay

#

to: null?

marble jackal
#
condition:
  - condition: template
    value_template: "{{ trigger.from_state.state != trigger.to_state.state }}"
stuck remnant
#

ok so now I think I get it

#

and why it didn't make sense to me until now

#

because this also stamped from off to off, it messed up the other sensor

#

or at least it messed up my understanding of it

#

now it makes sense

#

thank you

silent vector
#

Is there a way to use an attribute of a template sensor to access the value of a variable in the state template? I would want to use the hours list in a script for loop without having to harcode the list in the script and make any changes in 2 places. What I am trying to accomplish could be accomplished if there is a way to have the attribute, in this example output the next item in the list of the states template? Meaning if the state template outputs 65 can the attribute output 6:10 and add the : to 610 which is the next item in the list {{h[0]}}?
https://dpaste.org/2QVZv

marble jackal
#

No, you can not reuse part of your template in the attributes like that

#

The other way round is possible, set the hours in your attribute, and use the attribute in your state template

#

However, the state template will be rendered first, and then the attributes, so you have to work around that

silent vector
#

How could I do this?

marble jackal
# silent vector How could I do this?

Something like this

sensor:
  - unique_id: "daniels_thermostat_schedule"
    name: Daniels Thermostat Schedule
    state: >-
      {% set hours = this.attributes.hours if this.attributes.hours is defined else [] %}
      {% set t = states('sensor.time').replace(':','')|int %}
      {% for h in hours if h[0] <= t <= h[1] %}
          {{h[2]}}
      {% endfor %}
    attributes:
      hours: "{{ [[530, 610, 65], [610, 740, 69], [740, 1500, 66]] }}"
#

changed it to match your format

silent vector
#

And this gets around the fact the state is rendered first?

marble jackal
#

yes, because it will first use an empty list, and update after the attribute is updated as well

silent vector
#

I see. Perfect thank you.

#

I actually don't have a sensor.time I copied this template from the forums. What was the format you had before? Or should I just make a sensor.time?

marble jackal
#

No, just use now(), but you can do that in a better way than I did, because I had to jump some hoops to get to the right format

silent vector
#

Meaning replace sensor.time with now() or make sensor.time template now()

marble jackal
#

{% set t = now().strftime('%-H%M') | int %}

silent vector
#

Perfect thank you

#

Is it possible to do what the state template is doing but instead select the next list item {{h[0]}} meaning If the state result is 65 can a template using the hours attribute in a script select 610 from the next list item [h0] and output {{h[0]}}.

If it's after 530 and before 610 it selects 65 in the state template. In a script I would want to use the hours attribute list to select the next item which would be [610, 740, 69] and output {{h[0]}} which is 610

marble jackal
#

What if the state is 66?

#

There is no next one then

silent vector
#

In the script I would want to know the next time. The first number is the start of a time block for the temperature and the second is the end. In the script I want to run the time between now and the next change time 610 from [[530, 610, 65], [610, 740, 69]. The state of the sensor would be 65 if it's between 530 and 610. Then the 610 from [610, 740, 69] would be used to take the time between now and 610 in a loop to check weather conditions decide whether to adjust the temperature

marble jackal
#

so, when the state is 66 you would like to have 530

silent vector
#

Yes and if the state is 65 I would want to have 610 for example. Without hard coding this so that I can expand the list without having to make other changes to achieve this

marble jackal
#

You can use single backticks to use inline code parts

#

makes your posts more readable

#

and less page filling

silent vector
#

Single instead of 3?

marble jackal
#

yes

silent vector
#

[610, 740, 69]

#

I see

marble jackal
#

See the difference between my post and yours?

silent vector
#

Yep I see the difference.

#

Eventually the list will be much bigger to cover 24 hours I only have [530,610,65],[610,740,69],[740,1500,66] for testing the concept

marble jackal
silent vector
#

Awesome thank you.

#

Would next_start need a >- instead of >?

#

What's the difference between the set time in state and set t in next_start?

coral geyser
#

Hey, i have issue with scrape integration. When url is not accessible the sensor is delete with history of sensor. do you have any solution for keep history ? thanks

silent vector
#

Not sure if this is the place for that? That is likely an #integrations-archived question. But I could be wrong.

marble jackal
#

And the set time is the same, but there is no way to reuse it, the variable time from the state template is not known in the template for the attribute

silent vector
#

It would have been in the current time. [610, 740, 69], [740, 1500, 66] now it is [740, 1500, 66] and should show 530 [530, 610, 65]

#

Somehow without doing anything and another template reload it worked

mighty ledge
#

You would have had to wait 1 minute for it to show up properly

#

without restarting

silent vector
#

Oops lol. Good to know. I'm working on taking a massive choose automation and changing it to a clean variable automation that is both dynamic based on weather and easy to modify vs a 400+ line choose automation. I will be back tomorrow with a question on a loop for the weather conditions between now and the next_time if I can't figure it out myself.

marble jackal
silent vector
#

I see.

coral geyser
#

Hey, i need to remplace value 1.0 and 0.0 to on and off when open and close the door. I have this for moment --> - platform: rest # INCUBATEUR 1 # resource: http://xx.xx.xx.xx/atmoweb?DoorOpen= name: incubateur01_doorstatus device_class: door scan_interval: 10 value_template: > {{ value.replace('"DoorOpen": ', '').replace(',','') }}

gusty pulsar
#

Hi Guys, Im relatively new to HA and need a hand with parsing some json in a template, the json that ill be working with is below. Essentially what I need is a loop that will check if any of the values are true then do something else do something else

#

{"abc123": false, "cbda123": false, "fsdfsd2": false, "dfgdfg222": false, "sdfdsf22": false}

inner mesa
#
{% set map={"abc123": false, "cbda123": false, "fsdfsd2": false, "dfgdfg222": false, "sdfdsf22": false} %}
{{ map.items()|selectattr('1', 'true')|list }}
#

depends on what you need to do with the results, but that will output a list of items where the value is true

gusty pulsar
#

Thanks Rob, ill give that a try now

inner mesa
#

which will be an empty list for that data

gusty pulsar
#

Essentially the data is number plates, so if none of the plates are known then get the number plate and alert me

#

the data is coming from an entity attribute

inner mesa
#

so:

#
{% set map={"abc123": false, "cbda123": true, "fsdfsd2": false, "dfgdfg222": true, "sdfdsf22": false} %}
{{ map.items()|selectattr('1', 'true')|map(attribute='0')|list }}

->

[
  "cbda123",
  "dfgdfg222"
]
gusty pulsar
#

Ill paste you the entity attribute as I think that will make more sense

inner mesa
#

if that doesn't already help you solve the problem

#

I have no need for such a thing 🙂

gusty pulsar
#
vehicles: 
- {}

orientation: 
watched_plates: 
abc123: false
qwe123: false
321sss: false
www123: false
eee123: false```
#

in the vehicles array it will show the registration detected, so if its not in the watched_plates section I'd like it to notify me

gusty pulsar
gusty pulsar
#

ok I'm almost there, how do I extract the plate from this json? I think the additional [ ] is tripping me up

[{"box_x_centre": 926.0, "box_y_centre": 637.5, "confidence": 0.898, "plate": "abc123", "region_code": "gb", "vehicle_type": "Sedan"}]

inner mesa
#
{% set map=[{"box_x_centre": 926.0, "box_y_centre": 637.5, "confidence": 0.898, "plate": "abc123", "region_code": "gb", "vehicle_type": "Sedan"}] %}
{{ map|map(attribute='plate')|list }}
#

->

#
[
  "abc123"
]
#

or just {{ map[0]['plate'] }}

#

but if it's going to be a list with more items, you'd want the first

gusty pulsar
#

It'l just be a single result so that should do the trick, lets see if i can adapt that 🙂

#

Thanks for the help, really appreciate it

gusty pulsar
#

Any ideas why the following:

{{ plate_json }}

{% set plate_check = plate_json|selectattr('1', 'true')|map(attribute='0')|list %}
{{ plate_check }}```

is giving me [] on plate_check?

```{"abs233": false, "sdfsdf2": true, "sdfsd1": false, "qweqwe1": false, "ydfdf22": false}

[]```
marble jackal
#

Because you've put quotes around true in your selectattr filter

gusty pulsar
#

if i remove the quotes i get

TemplateRuntimeError: No test named True.

inner mesa
#

yeah, you need that

gusty pulsar
#

if its easier, do you know of a way to output the number of values that equal true? aka on the above json it would output 1

marble jackal
#

Ah right, what Rob said!

gusty pulsar
#

I dont need to plates i just need to know if any are true

gusty pulsar
inner mesa
#

you need plate_json.items()

#

as in my example

#
[
  "sdfsdf2"
]
gusty pulsar
#

UndefinedError: 'markupsafe.Markup object' has no attribute 'items'

inner mesa
#

sigh

#

my code:

#
{% set plate_json = {"abs233": false, "sdfsdf2": true, "sdfsd1": false, "qweqwe1": false, "ydfdf22": false} %}
{% set plate_check = plate_json.items()|selectattr('1', 'true')|map(attribute='0')|list %}
{{ plate_check }}
#

see what's different

#

my guess is that you forgot the ()

gusty pulsar
#
{{ plate_check }}```
#

I feel like this is staring me in the face yet i cant see it

inner mesa
#

you need from_json

#

not to_json

#
{% set plate_json = '{"abs233": false, "sdfsdf2": true, "sdfsd1": false, "qweqwe1": false, "ydfdf22": false}'|from_json %}
{% set plate_check = plate_json.items()|selectattr('1', 'true')|map(attribute='0')|list %}
{{ plate_check }}
#

you want it to take json and turn it into a dict

gusty pulsar
#

so thats giving me
TypeError: the JSON object must be str, bytes or bytearray, not dict

inner mesa
#

ok

#

unfortunately I cannot debug on your system

#

it actually looks like you just need to remove the to_json

#

it's already a dict

gusty pulsar
#

bingo

inner mesa
#

not dict

gusty pulsar
#

thats got it

#

Rob, you're a hero my friend

#

thank you

inner mesa
#

TheFes is Robin to my Batman

gusty pulsar
#

😂

#

All of this just to get my gate to open on number plate recognition.... the things we do eh!

inner mesa
#

That's a cool use case, but spoofable is somebody cared.

#

I wouldn't jump to plate number as the trigger if I was guessing how it worked

rain condor
#

So im trying to get my garage to only send a command if the port is open with this:

#

close_cover: >-
{% if is_state('binary_sensor.shelly__switch','off') %}
service: switch.turn_on
data:
entity_id: switch.shelly_shsw_1_
{% endif %}

#

But I have the wrong format

#

How can I archive this i yaml?

inner mesa
#

you can't template a whole service call like that without some advanced logic

#

you should use if/then

rain condor
#

Can that be used in a cover device?

inner mesa
#

yes, the action in the template cover links to that page

rain condor
#

sorry could you guide me a bit more with a example of the open cover action im trying to do?

#

I only want the template to send the switch turn off if the cover is open

#

otherwise nothing

inner mesa
#

you just have to put the two things together

#
close_cover:
  - if:
      condition: state
      entity_id: binary_sensor.shelly__switch
      state: 'off'
    then:
      - service: switch.turn_on
        data:
          entity_id: switch.shelly_shsw1
rain condor
#

close_cover:

#

-if: property if is not allowed

#

it says

inner mesa
#

looks like you're missing a space

#

anyway, this checks fine in my config:

#
        open_cover:
          if:
            condition: state
            entity_id: binary_sensor.garage_door_sensor
            state: 'off'
          then:
            service: switch.turn_on
            data:
              entity_id: switch.garage_door_switch
rain condor
#

what am I doing wrong lol

inner mesa
#

you're worry what VSCode tells you, and not what HA's config check tells you

#

and you appear to be using an old HA extension for VSCode that doesn't understand if/then

rain condor
#

ha also complain

inner mesa
#

maybe you're using an ancient version of HA

rain condor
#

yes can be so

#

is this a new feature?

inner mesa
#

if everyone who had issues would start by making sure they're up to date

#

update to 2022.6.3

dreamy sinew
#

but then i would have to migrate my zwave 😭 🤣

rain condor
#

yes same here

#

haha

#

with zwave

#

thats why I have note updated

dreamy sinew
#

still no excuse though, should just do it

inner mesa
#

if you stay behind, you're on your own

dreamy sinew
#

i'm just lazy but also none of my stuff is currently broken

rain condor
#

Version core-2022.2.9

dreamy sinew
#

i'm sure that will change

inner mesa
#

the docs move forward without you, and then you'll just be sad and confused

rain condor
#

im gonna throw out all crap zwave and put in shellys

inner mesa
#

you can also use choose: there, but you're on your own to convert it

rain condor
#

nah I just get rid of the zwave and update

#

thank you for your help

inner mesa
#

or even just an inline condition. That's really the easiest

#

didn't think about that at first, but it's just what you want. There are many ways

rain condor
#

Don’t know what’s a in-line condition is

inner mesa
#

ok

#

suggest reading that whole page

rose scroll
#

What is the raw output from your rest sensor, before doing the replace?

lyric comet
#

Since updating to 2022.6 using states.binary_sensor|selectattr('attributes.device_class', 'eq', 'window') fails with "UndefinedError: 'homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'device_class'" I suspect because the device_class is not set on all my binary sensors and the fact you need a default for most template values, but I can't work out how to provide one. Any suggestions?

patent ruin
#

Hi guys, I was using an automation that was working like a charm since last update.
The automation is checking for rain precipitation in the daily forecast to allow the morning irrigation.

{{ state_attr('weather.city', 'forecast')[0].precipitation == 0 }}

Unfortunately now I get this error: template value should be a string for dictionary value @ data['value_template']. Got None

for what I understand seems the value is not considered as a number anymore but i I check the state i get this value: precipitation: 6.5

coral geyser
rose scroll
#

This will return true if the rest sensor returns the string "DoorOpen": 1.0 and false otherwise. Which is a binary sensor.

coral geyser
#

{{ value.replace('"DoorOpen": ', '').replace(',','')}} I have this now

rose scroll
#

Yup you don't have to use replace to isolate out the 1.0 or 0.0. Just use the whole string

coral geyser
#

{{ value == '"DoorOpen": 1.0' }} this ?

rose scroll
#

The rest sensor only returns two possible strings? "DoorOpen": 1.0 or "DoorOpen": 0.0?

coral geyser
#
  resource: http://10.10.30.4/atmoweb?DoorOpen=
  name: incubateur04_doorstatus
  device_class: door
  scan_interval: 10
  value_template: >
    {{ value.replace('"DoorOpen": ', '').replace(',','')}}``` It's my config
rose scroll
coral geyser
#

ok i will test

#

thx

marble jackal
lyric comet
coral geyser
rose scroll
#

If you want to test in Dev Tools > Template, put the whole thing into the text box {{...}}

rose scroll
#

Then you can go open and close the door and see if the output changes from true to false as expected in real time.

marble jackal
#

And just to be sure, check the first pinned post

coral geyser
rose scroll
#

Oh right...in Dev Tools > Template, you won't have access to the value from your rest sensor. Mmm afraid you can't test it as-is in Dev Tools > Template then.

#

Try just putting that in the value_template of your actual rest sensor and then see how the sensor state changes in Dev Tools > States when you open/close the doors.

coral geyser
rose scroll
#

Where you had {{ value.replace... }}, replace it with the new one.

coral geyser
#

Just value ?

#

haa ok

coral geyser
lethal ingot
#

who can help me out. Someone on the facebook home assitant group suggested me to adjust my template setting so i don't get any negative values anymore in my graph. But when i adjust it i get errors. Sorry i'm new to ha and still learning. https://imgur.com/a/ZVkjM9w https://imgur.com/a/vSrPSBC

coral geyser
rose scroll
#

Nope. What I meant is:

- platform: rest # INCUBATEUR 4 #
  resource: http://10.10.30.4/atmoweb?DoorOpen=
  name: incubateur04_doorstatus
  device_class: door
  scan_interval: 10
  value_template: >
    {{ value == '"DoorOpen": 1.0' }}
coral geyser
#

In dev tool. ?

rose scroll
#

No, in your config directly.

dark rock
#

Hi guys, not sure if this is the proper channel. If not, sorry about that.

I'm building a bridge to integrate a 433mhz controller fan using home assistant to mqtt to esp8266 to 433 mhz.

The communication is working great and I'm able to send the payload to the esp and make it do whatever i want.

I need to parse into the payload the value of an slider named: input_number.nivel_luz

The templeate {{int(states('input_number.nivel_luz'))}} returns the value of the slider.

If i put this templeate into a button which on tap runs the mqtt:publish service and as a payload template i use the previous template it doesn't work. After saving it changes the template to [object object]: null

I not really sure what I'm doing wrong here, if you could give me some guidance it will be great

coral geyser
#

UndefinedError: 'value' is undefined

#
  resource: http://10.10.30.4/atmoweb?DoorOpen=
  name: incubateur04_doorstatus
  device_class: door
  scan_interval: 10
  value_template: >
    {{ value_template == '"DoorOpen": 1.0' }}```This
#

or

mighty ledge
coral geyser
#
  resource: http://10.10.30.4/atmoweb?DoorOpen=
  name: incubateur04_doorstatus
  device_class: door
  scan_interval: 10
  value_template: >
    {{ value == '"DoorOpen": 1.0' }}```
#

this, it's same

#

@rose scroll

dark rock
mighty ledge
coral geyser
mighty ledge
#

can you copy/paste everything from the endpoint here?

#

go to the endpoint

#

use CTRL+A, CTRL+C, then CTRL+P the result here.

coral geyser
#

I don't understand for endpoint, my dev tool don't work

mighty ledge
#

trying to see if there is hidden characters

#

this is a rest sensor correct?

#

open a browser. Go to: http://10.10.30.4/atmoweb?DoorOpen=

coral geyser
#

Ho no with {{ value.replace('"DoorOpen": ', '').replace(',','')}}

#

it's work

#

but i want replace 1.0 and 0.0 to on or off

mighty ledge
#
value_template: "{{ 'on' if '1.0' in value else 'off' }}"
coral geyser
mighty ledge
#

you can also just make it a binary sensor

#

with

#
value_template: "{{ '1.0' in value }}"
#

but your rest sensor needs to go in the binary sensor section

#

and it will then become binary_sensor.<name_of_sensor> instead of sensor.<name_of_sensor>

silent vector
#

Any idea why both "{{ state_attr('sensor.right_dockpro', 'status'). water_level <= 40 and not is_state_attr('sensor.right_dockpro', 'status.water_level','0') }}" and "{{ state_attr('sensor.right_dockpro', 'status'). water_level <= 40 and not 0 }}" are evaluating to true when the value is 0. I tested both in the template editor and the not works.

marble jackal
#

The first because you put quotes around the 0

#

The second because you are not staying what should be not 0

silent vector
#

Alright use the first and remove quotes?

marble jackal
#

"{{ 0 < state_attr('sensor.right_dockpro', 'status').water_level <= 40 }}"

coral geyser
marble jackal
#

Unless it can be below 0, in that case this doesn't work

silent vector
#

I set it to notify me with the value when it triggered and it was 0 never below 0. It becomes 0 when there's a disconnect or API issue

rain condor
#

Is if option not supported in light template?

coral geyser
marble jackal
#

Corrected it

marble jackal
rain condor
#

Invalid config for [light.template]: Unexpected value for condition: 'None'. Expected and, device, not, numeric_state, or, state, sun, template, time, trigger, zone @ data['lights']['kitchen_fan_light']['turn_off'][0]['if'][0]. Got None
required key not provided @ data['lights']['kitchen_fan_light']['turn_off'][0]['then']. Got None. (See ?, line ?).

#

@marble jackal

merry marsh
#

How can I get the translated/plain value from a sensor via template? Eg. states('alarm_control_panel.abc') returns 'armed_home'. Fine. But I would like to e.g. receive the German value like it is shown in UI, History, Log, etc.: "Aktiv, zu Hause". How can I get this (without endless if-else-rebuilding of the different states)?

marble jackal
rain condor
#

deleted*

#

can you please help me format it right @marble jackal

#

its the turn off section

marble jackal
#

Did you actually read my message? Use a code sharing site. Don't place walls of code on the channel

rain condor
#

Invalid config for [light.template]: required key not provided @ data['lights']['kitchen_fan_light']['turn_off'][0]['then']. Got None. (See ?, line ?).

marble jackal
#

Don't tag me please, I'm on the channel and trying to correct it

#

This should be better https://dpaste.org/kqT8R
And data_template had been depreciated over 2 years ago, and you are not even using a template there

#

The then is part of the if action, so no dash there. And your actions which are part of the if-then should be intended so they are part of the then

rain condor
#

thank you

#

that worked like a charm

simple edge
#

How do you do regex with templates, or starts with?

marble jackal
#

Think we need a bit more info better

long pecan
#

Are you using Helium network? You can add sensors, binary_sensors, and devices trackers to HA using the API and no config is needed in HA or mqtt at all, its all done in the helium console. devices are created when you submit data. If you want more info i can share my console setup. I have GPS trackers and, voltage sensors and relays from Helium in HA now.

#

I think more people would use the Helium LoRa network if they knew about it, and how cheap is is. $0.00001 per packet. way cheaper than Hologram.io

mighty ledge
#

But if you only use 10 packets, what does it cost?

#

Is it free or 900% markup

long pecan
#

0.0001 would be the cost of 10 packets. I edited my original comment, i put not enough 0's

#

It would cost $0.50 to have a GPS tracker send location every 10 minutes for a year.

#

I dont know what you mean by markup..

mighty ledge
#

Are you getting charged a penny?

simple edge
long pecan
#

packets.. not packages. a packet is a beacon, like a GPS sending its info once..

mighty ledge
#

Yeah, on mobile, auto corrected

mighty ledge
#

lets say the billing cycle is 1 year

long pecan
#

When you sign up for the helium console they give you 10,000 data credits free, $10 worth.

#

it will last a long time..

mighty ledge
#

yeah, but that still doesn't answer the question

#

I want to know where it rounds

long pecan
#

There is no billing cycle... you buy data credits a head of time.. every packet costs $0.00001

#

you tell me how many packets you want to send in a year and then times that by the cost.

mighty ledge
#

but banks do not deal in 0.01 or lower...

#

do you udnerstand?

long pecan
#

You cant buy just one data credit.

mighty ledge
#

and that's where I was going with this, thanks

long pecan
#

So you would pay $10 and you get 1,000,000 data credits. But the cool thing is when you create your free account, they give you 1,000,000 data credits for free. to incentivize using this network. explorer.helium.com lets you look at the coverage area.

#

in your account that do not expire ever

mighty ledge
#

regex is extremely complicated. There are 1000s of tutorials, outside HA.

#

and if you don't know, regex was not created by HA, it's simply used by HA. And it uses pythons regex.

#

Every language has a rendition of regex and they are all slightly different

#

so you should just ask how to format the regex unless you feel like learning a whole new symbolic language

simple edge
#

just {{trigger.value2 == "^Starting*"}}

mighty ledge
#

doesn't seem right

#

why do you have 0 or more of indicator there

#

remove the *

#

you're literally seraching for Startin or Starting or Startingg etc

simple edge
#

I dont want to learn regex, I just want a command that I can use regex in for example in python re.pattern("some string","regex") would allow me to use regex. Im just trying to find the command, in this example re.pattern

simple edge
#

my regex is def wrong

mighty ledge
#

what's the phrase you're looking for in trigger.value2?

simple edge
mighty ledge
#

You don't need regex for that

#

simple == will work

#

if "Starting Upload" is anywhere in the string, you can simply

#
{{ "Starting Upload" in trigger.value2 }}
#

if you want to see that it starts with "Starting Upload"...

#
{{ trigger.value2.startswith("Starting Upload") }}
simple edge
#

your right, might be overcomplicated it

mighty ledge
#

Only resort to regex if you have to.

simple edge
#

Thank you so much😁

gusty pulsar
#

Hi Guys, I've setup a custom sensor in my configuration.yaml and need to get the last time it was updated for an automation, is that possible?

inner mesa
#

last_updated or last_changed

#

{{ states.sensor.whatever.last_updated }}

gusty pulsar
#

We meet again Rob! - Thanks 🙂

quick yacht
#

HA & Jinja noob needs help with a simple template

gusty pulsar
inner mesa
#

yes

#

Your example isn't really a trigger, though. A trigger is a point in time when something happens or becomes true

#

what you described is a condition, perhaps, with something else as a trigger

gusty pulsar
#

My situation is for my number plate recognition for the gate opener. Its all working fine but if the same number plate is detected with no other cars in between then because the stored number plate is the same it doesnt trigger the opening

inner mesa
#

and you're using a template binary_sensor or similar?

#

so the state doesn't change?

#

I would just add auto_off: "00:00:02" or something like that

gusty pulsar
#

Its just an ordinary sensor, is it possible to do something similar to auto_off? perhaps remove the state entirely after x seconds

inner mesa
#

what do you mean by "ordinary sensor"?

#

how does it get its state?

#

as opposed to binary_sensor?

gusty pulsar
#

Apologies for what is very likely awful coding but here it is:

    sensors:
      number_plate: 
        friendly_name: "Number Plate"
        entity_id: "sensor.number_plate_id"
        value_template: >-
          {% if states('image_processing.platerecognizer_gate') != "unknown" and states('image_processing.platerecognizer_gate') > "0" %}
            {% set raw_data = state_attr("image_processing.platerecognizer_gate", "vehicles") %}
            {{ raw_data[0]['plate'].upper() }}
          {% else %}
          No Plates Detected
          {% endif %}```
inner mesa
#

then what do you do with the state of that sensor?

#

it seems like in the end, you just need to encapsulate whatever logic you care about in there

gusty pulsar
#

I have an automation with the trigger being that sensors state being updated followed by a number of IF's for each plate

inner mesa
#

it depends on what you're actually doing in the automation, but if it's just "is it a recognized plate or not?", then I recommend making a template binary_sensor that just encapsulates all of that and gives you "on" or "off", with an auto_off to reset it

gusty pulsar
#

Yeh it is, so if its recognised then open the gate and notify me

inner mesa
#

you would just need something like:

{% set known_plates = ["AAA", "BBB", "CCC"] %}
{{ raw_data[0]['plate'].upper() in known_plates }}
gusty pulsar
#

once again you've been supremely helpful, thank you

inner mesa
#

there's a bit more to think about to form a complete solution, but I would do the following:

#
  • Make it a binary_sensor
  • Add a trigger to your template sensor to watch for state changes of image_processing.platerecognizer_gate
  • Add the logic above to make the state 'on' if a known plate is identified
  • Add an auto_off: "00:00:05" to have it auto-reset
  • In your automation, use a state trigger on your template binary_sensor and notify with the logic from above:
            {% set raw_data = state_attr("image_processing.platerecognizer_gate", "vehicles") %}
            {{ raw_data[0]['plate'].upper() }}
#

just a thumbnail sketch. there are lots of ways to accomplish it

#

maybe you need a longer auto_off value to ensure that it doesn't trigger for the same car before it's cleared the gate

gusty pulsar
#

That does sound like a good way to do it, I'll give that a go and see what the results are

#

If it triggers more than once for the same car it wouldnt matter as the input is ignored by the gate

silent barnBOT
quick yacht
#

Hi, my first ever question to the community. Also a newbie in the python world but managed to write a small integration for my Chinese inverter (https://github.com/basghar/teslapv_pk). Basically I am saying that feel free to roast me but like a rookie 😳 . I am still grasping the core concepts. Let's see how the journey goes. So here goes my question.

I need to calculate current from the values that my inverter is providing.
https://hastebin.com/sadoqiwuto

It works fine but I have few questions.

  • For things like this, is using template the recommended way or does HA have another trick up it's sleeve
  • Under certain conditions, the value cannot be calculated and therefore I return unavailable. Is that the correct implementation? I saw availability in the docs but I am confused. If the value unavailable of a state of a sensor does the job, then why is the availability attribute needed? I thought that the state template would not be evaluated if the availability attribute returns False. Please excuse me if that is a dumb question.
  • I had to do the same calculation for a few other energy sensors. Replication bit me a few times so I started looking for a way to reuse. Looks like it's not straightforward in the templating world. I came across https://github.com/home-assistant/core/pull/42244#issuecomment-716042818. python_script does not support imports so I looked at the custom component method but the custom component does not appear to be designed for providing such functionality. Like the iot_class manifest attribute seems irrelevant for such a use case. I looked for an example but could not find a way.
winter pilot
#

Afternoon all. I am trying to create a quick template that compares the current and old value of a sensor and keep running into issues. What would be the best way to do this? This is not an automation, just a regular template.

inner mesa
#

What have you tried and what were the issues?

winter pilot
inner mesa
#

Ok

#

There isn't really much there

winter pilot
#

Just added a previous attempt I forgot about

inner mesa
#

it's all just random stuff

#

what you're asking for only makes sense in the context of a state change, which you detect with a trigger in a template sensor or an automation

#

so in that context:

winter pilot
#

so I am trying to add this to the config of the UI card so it changes the icon as the comparison changes, if that makes sense.

inner mesa
#
trigger:
  platform: state
  entity_id: sensor.whatever
condition:
  condition: template
  value_template: "{{ trigger.from_state.state|float < trigger.to_state.state|float }}"
action:
  ...
#

for example

#

I'm sure there are threads on the forum for stuff like this

winter pilot
#

i've found examples for a fixed number or a on/off state but that doesn't help for trying to compare the previous value of the sensor.

inner mesa
#

you can't just get the previous value of an entity from the entity itself

#

it's part of the state change event when it changes state

#

that was hit #1 🙂

#

and it's basically doing exactly what I have above

winter pilot
#

yup, i've been there a few times. I'm not sure how I can apply that to the card code.

inner mesa
#

it doesn't belong in a card

winter pilot
#

so I can change the icon of the card from an automation template like that?

inner mesa
#

you could use it in an icon_template for a template sensor, or other integration that supports it

#

but again, it needs to be based on a trigger where you have the old and new states available

winter pilot
#

ok. i'll focus my search on that and see what I can find. I saw that early on but I don't remember why I passed it up. I'll have something else for you/the channel later on lol. (new topic)

#

thanks for the guidance ... hopefully I have my eureka moment soon.

umbral pond
#

how could I modify this:

{% for state in states.light -%}
  {%- if state.state == 'unavailable' %}
    {{ state.name }}
  {% endif -%}
{%- endfor %}

so that instead of showing the name of the entity that is unavailable , it counts all those entities and return the number of them being unavailable ?

dreamy sinew
#

{{ states.light|selectattr('state', 'eq', 'unavailable')|list|count }}

#

also, to simplify your first one:
{{ states.light|selectattr('state', 'eq', 'unavailable')|map(attribute='name')|list }}

umbral pond
#

Ah! Thanks alot!

quasi token
#

Hello! I'm trying to set a picture card in home assistant that the url is what's displayed as the art cover of a media player.

#

this template gives me the url correctly {{state_attr('media_player.denon_avr_s740h', 'entity_picture')}}

#

but this template doesn't return the image if I put it inside a picture card

#

anyone knows why this doesn't work?

quasi token
#

it works if i just use image: /api/media_player_proxy/media_player.denon_avr_s740h?token=(my_token)

#

just realized it doesn't update unfortunately

dreamy sinew
#

most cards don't support templates

hollow moat
#

how do i exclude an entity from a list

{{ states.light | selectattr('state', 'eq', 'on') | rejectattr('entity_id', 'in', area_entities('Bedroom')) | map(attribute='entity_id') | list }}

#

never mind i see my mistake

mild mica
#

hey i am trying to make a temp

#

late so i can track my dehumidifer run time. i have this

  - sensor:
      - name: Dehumidifer state
        state: >
          {% if (states('sensor.dehumidifier_power')|float > 3.5) %}
              "on"
          {% endif %}

i was trying to get it to say on

#

but i can't figure out how to get that part to work.

#

i can have it report false, but i really want on.

#

also is there somewhere to check what state. attributes things have ?

#

the multiline example is using a switch with pwr sense capabilities. how can we find the same info

#

also where are all the i guess programming directives like state_attr and stuff?

#

is there a central place to ref them?

marble jackal
#

If you want to use on and off as state for your template sensor, a binary sensor makes more sense

mild mica
#

it still shows false

#

with the binary sensor.

marble jackal
#

The template yes, but the state of a binary sensor is either on or off

#

Check devtools > states

marble jackal
mild mica
#

then shouldn't this work instead of saying it got None?

          {% if state_attr('sensor.dehumidifier_power', 'W')|float > 3.5 %}
marble jackal
#

No, that doesn't output anything

mild mica
#

so then i am going to ask again about state_attr()

marble jackal
#

{{ state_attr('sensor.dehumidifier_power', 'W')|float > 3.5 }}

mild mica
#

why doesn't the fi work?

#

the line you provided also has the same result

marble jackal
#

Because the that statement is not complete, it needs what you want to output in case that the statement is complete, and an {% endif %}

#

Test your template in devtools > template

mild mica
#

i only provided the part that is failing.

#

and i am testing it tehre

#

and that is why i am here with all of these questions

#

and i pasted the full if statement above. it is a complete if statement.

#
{{ state_attr('sensor.dehumidifier_power', 'W')|float > 3.5 }}

is also failing and daying float got invalid input. it is behaving the same as the my if statement.

marble jackal
#

Well, then your input is wrong

mild mica
#

"{{ states('sensor.dehumidifier_power')|float > 3.5 }}"

#

that produces true or false.

#

and its still not clear how to get state_attr from the states and how to correlate them

mild mica
marble jackal
#

Example:

entity_id: sensor.bureau_martijn_power
state: 69.1
attributes:
  state_class: measurement
  unit_of_measurement: W
  device_class: power
  friendly_name: Bureau Martijn Power
#

{{ states('sensor.bureau_martijn_power') }} output: "69.1"
{{ state_attr('sensor.bureau_martijn_power', 'device_class') }} output: "power"

mild mica
#

i guess i need to review the examples again

#

as there is a disconnect somewhere. is the state_attr function documented anywhere? i checked on the jinja site, and this seems to be an HA thing

marble jackal
tepid onyx
#

ahola , haven't touched ha for a while except for upgrades. looking at moving to appdaemon. Is this the right place to ask for hints. thanks

marble jackal
#

This is the place for jinja templates 🙂

tepid onyx
#

hint

coral geyser
#

Hi, i need to create a virtual sensor with link to a rest or scrape sensor. I need that because i want to keep history of sensor when a rest or scrape integration sensor do not respond. Do you any solution /idea for my issue ?

coral geyser
#

@tranquil yew

tepid onyx
#

pastebin some info

marble jackal
tepid onyx
coral geyser
floral shuttle
#

if I were to set my mqtt sensor to unavailable if the value wouldn't be a state, could this do it?```
{{iif(is_number(value), min(value|round(2,none),2500),'Unavailable')}}

#

thing is, we can only use the availability_template on the Mqtt sensors with a real topic, and not like in template:

#

thing is, if I test this: {% set value = 'no_number'%} {{iif(is_number(value), min(value|round(2,none),2500),'Unavailable')}} I get the ValueError on round..... 'but no default was specified' even though it is? And can only get that to work if I feed it a number {{iif(is_number(value), min(value|round(2,default=-1),2500),'Unavailable')}} which is what I was trying to prevent... it should error as Unavailable on Not number..heck.

mighty ledge
#

{{ min(value|round(2,none),2500) if value | is_number else none }}

floral shuttle
#

thx, been struggling here, because even the additional comparison below needs a default... {% set max = 2500 %} {{iif(is_number(value) and value|float(-1) > 0, min(value|round(2,default=-1),max),'Unavailable')}}

#

would be {{ min(value|round(2,none),2500) if value | is_number and value|float(-1) > 0 else none }} ?

mighty ledge
#
{% set maximum = 2500 %}
{{ [ value | round(2), maximum] | min if value | is_number and value | float > 0 else none }}
#

you don't need defaults if you check for it in order

floral shuttle
#

ok let me try that, thanks!

#

to be sure, did you purposely change my 'max' to 'maximum' ? reserved word maybe?

mighty ledge
#

yes, and yes

floral shuttle
#

👍

#

on the float filter: neither yaml checker nor ha core check find that, and let one restart without it. With all failing sensors as a consequence, and a lot of errors in the log....

#

right, so apart from my obvious mistake the sensor should also be allowed to be 0... I now see None W as state on those. Shouldnt I see Unavailable in the Dashboard for an unavailable entity? The dev states also show None, and not 'Unavailable'.

silent vector
#

Any idea how to stop the first block [530, 630, 65] from providing a next_start of 1730 [1730,1845,64] when it should be 630 from [630, 740, 69]. I assume it has something to do with h[2] == this.state as I have 2 65s in h[2] one at [530, 630, 65] and one at [1500,1730,65]? The rest works.

For context next_start is to use the hours list in a script to check the weather conditions during the time between now and next_start

https://dpaste.org/4rekQ

exotic jungle
#

hi I have a snippet of code to trigger when the current time = my alarm time set by the HA app as below:
{{now().strftime("%a %h %d %H:%M %Z %Y") == (((state_attr('sensor.ha_app_next_alarm', 'Time in Milliseconds') | int / 1000) + 0*60 ) | timestamp_custom('%a %h %d %H:%M %Z %Y'))}}
It looks like this is now broken with the latest 2022.6 update.. probably due to timestamp_custom function not having a default value.. any suggestions on how to fix this? thanks

inner mesa
#

You have some curious math in there

#
  • 0*60 isn't doing much
exotic jungle
#

if you know of a better way to do it i'm happy to switch, i think i took this code from somewhere in the web.. the 0*60 was probably an offset I set to 0

inner mesa
#

I figured as much

#

Like I said, I suggest putting it in devtools -> Templates and seeing what's wrong

exotic jungle
#

ValueError: Template error: int got invalid input 'None' when rendering template '{{now().strftime("%a %h %d %H:%M %Z %Y") == (((state_attr('sensor.ha_app_next_alarm', 'Time in Milliseconds') | int / 1000) + 0*60 ) | timestamp_custom('%a %h %d %H:%M %Z %Y'))}}' but no default was specified

#

i pasted parts of it and the bit that's error-ing is the timestamp_custom function, I thought adding default=X in it will work but it still fails

#

thanks - looks like it works and it was because I was not putting in the right sensor name.. sorry about it.. but the templates function was very helpful in debugging.. so many thanks for that 🙂

ocean marsh
#

is there no switch { case: .. } syntax in jinja2? i have to use if elif ... ?

inner mesa
#

yes

silent barnBOT
ocean marsh
#

damn indention 😦

silent vector
#

Any idea how to stop the first block [530, 630, 65] from providing a next_start of 1730 [1730,1845,64] when it should be 630 from [630, 740, 69]. I assume it has something to do with h[2] == this.state as I have 2 65s in h[2] one at [530, 630, 65] and one at [1500,1730,65]? The rest works.

For context next_start is to use the hours list in a script to check the weather conditions during the time between now and next_start

https://dpaste.org/4rekQ

inner mesa
#

that direction wasn't to you

silent vector
#

Rob are you talking about me?

inner mesa
#

no, the person who deleted their misplaced post

silent vector
#

Oh ok lol.

inner mesa
#

Images of text are evil and not useful. Please share the actual text

silent barnBOT
#

Please use a code share site to share code or logs, for example:

Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.

inner mesa
#

sigh

#

you saw the bot message, right?

cyan pier
#

yes, however did not see the 15 line max limit

mighty ledge
inner mesa
#

was deleted

#

probably something like this:

{% set data = [{"a": "foo", "b": "bar"}, {"a": "blah", "b": "floop"}] %}
{% for item in data -%}
  {{ "a: " ~ item.a ~ ", b: " ~ item.b }}
{% endfor %}
#

I wish there was a way to use format() as a filter to output different pieces of an incoming data structure without the need for a for loop

cyan pier
#

basically writing a for each departure in departures, print line, time. manually referring to each index would be clumsy

inner mesa
#

or maybe there is and I just can't figure it out

#

->

a: foo, b: bar
a: blah, b: floop
paper hazel
#

I cant seem to find in the documentation how to use home_assistant_start in a template. I'd like to create a condition like this:```
{% set val = now() %}
{{ ((as_timestamp(val) - as_timestamp(states.home_assistant_start.last_updated))) > 180 }}

marble jackal
marble jackal
paper hazel
#

Awesome! That will do the trick - Thought I might get away with leveraging off the event...

silent vector
#

Is it also possible to add specific days of the week for Example. It would filter through what day of the week is today and the time to find the correct match {{h[3]}} and correct next_time.

[weekday,530,630,65],[SatSun,630, 740, 69],[weekday,530,630,65],[MWFSS,740, 1500, 66]

Something along the lines of?

      {% set MWFSS = [0,2,4,5,6] %}
      {% set weekday = [0,1,2,3,4] %}
      {% set SatSun = [5,6] %}
slate tundra
#

any idea why this trigger won't work:

- platform: template
  value_template:  "{{ today_at(states('input_datetime.sleep_time')) - timedelta( minutes=5 ) }}"
minor dune
#

any pro templaters here?

its my first time using them and im trying to put the value of my next alarm sensor into a text helper but modify the text before writing it to the text helper

slate tundra
#

it renders something like 2022-06-09 22:55:00+03:00

#

just won't trigger

minor dune
opaque creek
#

Heya!
I use this template sensor:
state: "{{ state_attr('weather.smhi_home', 'wind_speed') | float / 3.6 }}"
And it returns a value with a lot of decimals. And if I just want to show 1 decimale shouldn't I just add "| round(1)" after 3.6 in the code? I tried that but it doesnt return anything.. what am I doing wrong? 🙂

slate tundra
#

tried also:

{{ now() == today_at(states('input_datetime.sleep_time')) - timedelta( minutes=5 ) }}

still nothing

silent vector
#

I think it's round (1)

opaque creek
#

Right! wrong of me, was suppose to be "round(1)" 🙂 But yeha it still doesnt show any less decimals

silent vector
#
 "{{ state_attr('weather.smhi_home', 'wind_speed') | float / 3.6 | round(1) }}"
opaque creek
#

just want that 1.9

#

if I remove "(1)" and just go "round" it give me 1,75

silent vector
#

Hm not sure. Will need someone with more experience lol.

opaque creek
#

Yeha.. probably something we're not seeing here hehe

inner mesa
#

You're rounding 3.6

#

You need to add parens

winter pilot
#

I am trying to figure out the best way to add/remove alerts into the dashboard I created based upon data from an html table. The catch is I only want certain items. The table has 4 columns, two of which I will use to filter the results I want to work with.

What is the best way to add/remove items to a sensor (figure logbook or markdown as best option?) based on the “alerts” that I want to see from the data source?

rose scroll
opaque creek
orchid oxide
#

i know at the end of the day, its minutely easier, but any possibility of doing this? (using a template in a service call)
"{{'switch.turn_'~states('light.lamp')}}"

inner mesa
#

Sure

#

Services support templates and it's done all the time

orchid oxide
#

oh it really just works, huh

#

love it

marble jackal
marble jackal
chrome ether
#

hi all, i was wondering if a template can be made to set a rolling shutter position by using some sort of time based button pressed and convert it to percentage

#

i have a zigbee rolling shutter that does not have a cover.position working, the only exposed working things are open/close/stop button

#

from what i can see, the close button stops the movement, and the open/close move up and down the shutter for XXsec, lets say 180sec (you can hear the relay click after that amount of time).. the shutter goes from fully open to fully close in maybe 25sec

#

my idea was to do something like:
-> i know that my shutter is fully open ->
-> i want 50% of my shutter closed ->
-> use close button for 12sec ->
-> report in HA slider that is 50%

#

some sort of time based calibration, dunno how to call it

marble jackal
#

Should be possible with a template cover

silent vector
#

Hey TheFes Is it possible to filter for specific days of the week. It would filter through what day of the week is today and the time to find the correct match {{h[3]}} and correct next_time.

[weekday,530,630,65],[SatSun,630, 740, 69],[weekday,530,630,65],[MWFSS,740, 1500, 66]

Something along the lines of?

      {% set MWFSS = [0,2,4,5,6] %}
      {% set weekday = [0,1,2,3,4] %}
      {% set SatSun = [5,6] %}

https://dpaste.org/Nmb9V

marble jackal
#

Not like this I guess, but your hours also don't work like you did them now, you should let it start at 000 and end at 2359

#

now it won't work after 1845

#

didn't see that yesterday as I was on mobile, but it does explain why it wasn't working for me at that time (it was after 1845 for me)

silent vector
#

Yep the state is broke but next_start works. So change it to this?
hours: "{{ [[530, 630, 65],[630, 740, 69], [740, 1500, 66],[1500,1730,65],[1730,1845,64],[1845,2359,63],0000,530,63]] }}"

marble jackal
#

next_start works because I added a default there

#

This would be more clear (to me) "{{ [[000, 530, 63], [530, 630, 65], [630, 740, 69], [740, 1500, 66], [1500, 1730, 65], [1730, 1845, 64], [1845, 2359, 63]] }}"

silent vector
#

Yes more clear to me too lol.

chrome ether
opaque creek
marble jackal
#

Do note that you can put an entire script sequence in the actions fields, you do need to add a dash then:

        open_cover:
          - service: cover.open_cover
            target:
              entity_id: cover.some_cover
          - delay: 25
          - service: cover.stop_cover
            target:
              entity_id: cover.some_cover
slate tundra
#

any other good way to implement an offset of 5 minutes or so before a input date and time?

#

i think i found a way

#
trigger:
  - platform: template
    value_template: "{{ (today_at(states('input_datetime.damian_sleep_time_school_day')).timestamp() - 300) | timestamp_custom('%H:%M:%S') }}"
#

yah this will work for sure

marble jackal
#

That's not a trigger, that's providing a timestamp

#

a template trigger should evaluate to true or false

silent vector
#

Hey TheFes, do you think what we were talking about earlier is possible or should I have separate template sensors for different days? Here's the dpaste with the revised hours
https://dpaste.org/G9EFr

marble jackal
#

Your hours attribute is incorrect on that one, the last one is not a list, and I thought we agreed the other order was a bit more understandable

silent vector
#

I pasted the wrong one whoops. It is more understandable how you set it up.

#

"{{ [[000, 530, 63], [530, 630, 65], [630, 740, 69], [740, 1500, 66], [1500, 1730, 65], [1730, 1845, 64], [1845, 2359, 63]] }}"

https://dpaste.org/nwqCf

marble jackal
#

I think it would be easier if you add different attriutes, so an attribute hours_weekday and hours_weekend

#

And then determine in the state and next_start templates which should apply

silent vector
#

Whatever you think is easiest/cleanest. I am not the wizard lol just thinking of the possibilities not exactly as capable as you are in realizing those possibilities.

marble jackal
#

Well do that then.
Then assign the right attribute with a template like this:

{% if now().weekday() < 5 %}
  {% set hours = this.attributes.hours_weekday if this.attributes.hours_weekday is defined else [] %}
{% else %}
  {% set hours = this.attributes.hours_weekend if this.attributes.hours_weekend is defined else [] %}
{% endif %}
silent vector
#

And If I wanted to get specific such as Tuesday and Thursday. Would that be now().weekday() in (1, 3) for example?

marble jackal
#

I would use [1, 3] but a tuple should also work. But you'll have to create a sepearate attribute for that as well then

silent vector
#

Perfect thank you as always. Does the use of "{{ [[000, 530, 63], [530, 630, 65], [630, 740, 69], [740, 1500, 66], [1500, 1730, 65], [1730, 1845, 64], [1845, 2359, 63]] }}" fix the issue after 1845 of not returning a state?

marble jackal
#

yes, because you were checking if this in your previous version 1845 < 2100 < 530 That is never true, as the 530 is lower as 1845. Now your are checking 1845 < 2100 < 2359

silent vector
#

Makes sense, thank you.

slate tundra
marble jackal
#

That could work, this is a bit shorter.

trigger:
  - platform: template
    value_template: "{{ now().strftime('%H:%M') == (today_at(states('input_datetime.sleep_time_weekend')) - timedelta(minutes=5)).strftime('%H:%M') }}"
slate tundra
#

ah yes strftime

#

ty

silent vector
marble jackal
#

indentation is a bit off

#

and you need to define the attributes of course

silent vector
#

Yep I would have to do that. Just making sure that part is correct.

mighty ledge
#

now() always resolves slightly past the minute, like ~15 microseconds

marble jackal
#

I suggested that, but according to Hellcry it would trigger when changing the value in the input_datetime

#

which is true when you change if from something after now() to before

#

This would also work:
"{{ now().replace(second=0, microsecond=0) == today_at(states('input_datetime.sleep_time_weekend')) - timedelta(minutes=5) }}"

silent vector
#

Thefes or Petro. Now that I'm past the scheduling part. I would want to use next_start to evaluate the time between now and then against weather conditions. The goal is to make a dynamic HVAC Schedule. This is not proper formatting just thoughts and placeholders for temperatures so that I can fix in the future as I figure out what I want. Is this possible to evaluate the weather conditions in the time between now and next_start. I brought in some stuff from a previous script you guys helped with related to the weather.

I missed this part from the previous script. {%- for hourly in forecast[:6] the :6 would need to be a variable i Assume.

https://dpaste.org/t1B7w

marble jackal
#

:6 is the first 6 items from the array

silent vector
#

Yep I know. But I wouldn't use that if the next start is only 2 hours away for example. So it would need to be a variable? (The weather forecast is hourly). I'm just guessing as to how this could be done.

chrome ether
chrome ether
#

that went really faster and better then expected 😮

young ridge
#

I added a template sensor to a yaml. I then changed the type of the sensor from sensor to binary sensor. There is no reference in the yaml to the sensor any more, but I'm still seeing the entity..... How do I get it to go away?

#

I tried restarting....

#

And it isn't selectable in the entries settings page

slate tundra
marble jackal
young ridge
#

👍

heady trellis
#

I'm using an automation which is basically a while loop that decrements an helper input_number.irrigation_timer until it is 0 (zero) and the loops stops .
The decrement I use the following YAML
- service: input_number.set_value
data:
value: '{{ (states(input_number.irrigation_timer) |int ) - 1 }}'
target:
entity_id: input_number.irrigation_timer

and this is the trace log output
Error: Error rendering data template: Undefined Error: 'input_number' is undefined

What is cooking here?

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://dpaste.org/ (pick YAML for the language), https://www.codepile.net/ (pick YAML for the language), or https://paste.debian.net/ (pick YAML for the language).

arctic sorrel
#
            value: '{{ (states("input_number.irrigation_timer") |int ) - 1   }}'
#

You missed quotes around the entity

#

Don't forget you can test in devtools -> Templates

heady trellis
#

Yep , this works.
You know, I'm an archaic UNIX guy , but this stuf is more pickier about quotes " , ' , ` 🙂

arctic sorrel
#

Not any worse than a UNIX commandline 😉

inner mesa
#

That part is straightforward. Strings are surrounded by quotes, and other things are either functions or variables

#

Pretty similar to any other language

heady trellis
#

I do not agree, Unix does not care about the amount of (white) spaces, this does. 😦

inner mesa
#

You said 'quotes'

#

I agree about white space

heady trellis
#

yeah. so quotes is "the same", but spaces makes this a hell

inner mesa
#

I wish you luck with Python

mighty ledge
#

I find the whole “whitespace is bad” argument ridiculous. Every IDE in the past 20 years formats whitespace for you, exactly the same way that python does. You just don’t have brackets that define the start and end.

inner mesa
#

Exactly that. If maintaining consistent whitespace is a problem, then I contend that other code that you've written is probably hard to read and would benefit from attention to whitespace and indentation

#

In other words, it enforces conventions that really should be used anyway

#

After writing a Python integration, it was annoying to have to add all the curly braces in the accompanying JS-based card

slow vine
#

I want to toggle my kitchen lights together with secondary lights in the kitchen area. If I just do toggle then if not all switches are in the same state I will not have all on or all off. I am trying to script it so it toggles only the main lights and sets the other lights to match. I think its done right but it does not work, the switches are out of sync.

#
- service: homeassistant.toggle
  entity_id: switch.kitchen_lights
- service: homeassistant.turn_{{ states('switch.kitchen_lights') }}
  entity_id: 
  - switch.kitchen_accents
  - switch.kitchen_porch
#

Could it just be that the state does not get changed right away in the first service call?

tepid ice
#

After the update to 2022.6. Sensor -template: rest with resource are not working. Is there any breaking changes to update the format?

marble jackal
slow vine
marble jackal
#

Why not the variable?

sequence:
- variables:
    current: "{{ states('switch.kitchen_lights') }}"
- service: homeassistant.toggle
  entity_id: switch.kitchen_lights
- service: homeassistant.turn_{{ 'on' if current == 'off' else 'on' }}
  entity_id: 
  - switch.kitchen_accents
  - switch.kitchen_porch
slow vine
#

Yeah, I'm doing that now. I didn't realise about variables so I was thinking that before I read your message.

marble jackal
#

Ah, okay 👍🏼

#

You basically don't need the toggle action then, you can add the kitchen lights to the other action

slow vine
#

that's a good point, I am anyway doing the toggle logic...

#

Is there a way to debug scripts? It was not working at all without the toggle service, and with it only the main lights are toggling nothing else. 😦

  variables:
    initial_state: "{{ states('switch.kitchen_lights') }}"
  sequence:
  - service: homeassistant.toggle
    entity_id: switch.kitchen_lights
  - service: homeassistant.turn_{{ 'off' if initial_state == 'on' else 'on' }}
    entity_id: 
    - switch.kitchen_accents
    - switch.kitchen_porch
marble jackal
#

The scripts also have a trace

slow vine
#

I missed that.

#

I learnt two things 🙂 (the yaml code block colors...)

marble jackal
#

Well I'm on mobile, the app doesn't show the colors then. But the built in YAML validation is also nice

slow vine
#

Its working, I am not sure what was wrong but the script was not reloading because of an error, but it didn't notify me (usually in automations that have an error I get a notification that its not reloading). I think I needed to switch the quotes on the template of the variable.

#

I now have single quotes on the outside and double inside. and its working

marble jackal
#

I've noticed that as well, that it sometimes doesn't really notify on errors in scripts, and just keeps the script as it was before the changes. A config check works though.
The quotes shouldn't be the problem though

silent vector
orchid oxide
#

im have a list of entities that match certain attributes, lets make it 3 for simplicity's sake: [front door, side door, front window] How can I change this to a string that say "front door, side door, and front window"?

#

full use case, to avoid xy problem. i want to send a single notification when I leave my home zone, for all entities that match a condition, to say "x, y, and z" are open

inner mesa
#

The 'and' is going to be annoying, but |join(', ')

#
{% set data1 = ['foobar'] %}
{% set data2 = ['foo', 'bar'] %}
{% set data3 = ['foo', 'bar', 'blah'] %}

{% set data = data3 %}

{% if data|count == 1 %}
  {{ data|first }}
{% else %}
  {{ data[:-1]|join(', ') }} and {{ data[-1] }}
{% endif %}
winter pilot
#

Anyone around who is good with multiscrape ?

orchid oxide
inner mesa
#

All except the last one

marble jackal
silent vector
#

Oh yes, what would that be to fix it? Just reuse this? Or a more elegant way?

{% if now().weekday() in [0,2,4] %}
       {% set hours = this.attributes.hours_mwf if this.attributes.hours_mwf is defined else [] %}
      {% elif now().weekday() in [1,3] %}
       {% set hours = this.attributes.hours_tt if this.attributes.hours_tt is defined else [] %}
      {% else %}
       {% set hours = this.attributes.hours_weekend if this.attributes.hours_weekend is defined else [] %}
      {% endif %}

this.state.hours?

marble jackal
silent vector
#

Sounds good. Any idea how to use the next start in a script to check the weather conditions between now and next_start? https://dpaste.org/TAnAg

marble jackal
#

Yes, but you've made a bit hard on yourself by the way you build your list for the hours

#

But I don't have time right now to go into that further

silent vector
#

because there's no :? Ex. 530 vs 5:30? I'll check back another time not a problem.

wise cedar
#

Is there any way to reject all entities that does not have area defined? I tried this, but I don't think it works:

| rejectattr('entity_id', 'in', area_entities(''))```
silent barnBOT
iron bison
# silent barn

the main question there is:
- if: **# How do I check the wait.trigger = none?** - condition: template value_template: ''

#

any help is appreciated

iron bison
#

hi guys,
Where can I find what's the syntax for using templates?
i.e. why there are 2 {{, what other actions/checks/methods are available besides e.g. "{{ is_state(... "?
I'm a bit lost in the documentation and the examples are not always applicable to my use-cases

inner mesa
#

I'll repeat

silent barnBOT
iron bison
#

thanks

inner mesa
#

Because that's the syntax...

iron bison
#

so everything from jinja is available in HA?

inner mesa
#

Yes

#

Where templates are supported

iron bison
inner mesa
#

Nope

#

'{{ wait.trigger is none }}'

iron bison
#

thanks a lot!

inner mesa
#

{{}} returns/outputs something, {% %} is for logic

iron bison
#

appreciate the help!!

orchid oxide
sage zodiac
#

Can someone please assist me with adding the current time to the end of this template? I'm trying to make something to display on the home page of my tablet home view.

      friendly_name: "TOD Greeting"
      value_template: >
        {%- if now().hour < 12 -%}Good Morning, the time is now
        {%- elif now().hour < 18 -%}Good Afternoon, the time is now
        {%- else -%}Good Evening, the time is now{%- endif -%} ```
inner mesa
#

lock and manual are strings

orchid oxide
#

Ok thanks

sage zodiac
#

Thanks Rob, that's definitely progress, any idea how I can format it to be something more easily readable at a glance, something similar to 10:23 AM Saturday, June 11

inner mesa
#

Yes, with strftime

sage zodiac
#

I'll start googling, thanks!

inner mesa
sage zodiac
#

Nice it looks like something like now().strftime('%H:%M')

inner mesa
#

Yep

sage zodiac
#

Alrighty, one final question and then I'll have this nailed down, I ended up with this, how can I force the time/date bit to be on a seperate line? My end goal is to display this in a card. tod_greeting: friendly_name: "TOD Greeting" value_template: > {%- if now().hour < 12 -%}Good Morning, the time is now {%- elif now().hour < 18 -%}Good Afternoon, the time is now {%- else -%}Good Evening, the time is now{%- endif -%} {{ now().strftime("%H:%M%p on %b %d, %Y") }}

#

After googling it looks to be problematic to add a new line to a template, maybe adding it to the card markdown is a better bet.

inner mesa
#

Depends on the card. <br> may work, or \n

sage zodiac
#

I'm trying to put this into a button card at the moment, i'll give that a shot

#

@inner mesa Adding <br> to my template worked and shows a new line in the button card. I appreciate your help.

keen sky
#

i have json question, is this correct channel

#

want to make one sensor from json output

tepid ice
#

value_template: '{{ states("sensor.date") }} {{ states.sensor.prayer_times.attributes.data.timings["Sunrise"] | timestamp_custom("%H:%M") }}'
After the core update above template for sensor is showing error with ‘no default was specified’ Please, anyone help me on this template working.

orchid oxide
nocturne chasm
#

if I used this as a trigger:

- platform: event
  event_type: timer.finished
  event_data:
    entity_id: timer.mailbox

Can I use this as a condition template:

{{ trigger.entity_id == 'timer.mailbox'}}
inner mesa
#

entity_id is not an option

#

You can get to it through event_data, but you might as well use a trigger id

nocturne chasm
#

So I would define id: in the trigger and use trigger.id == my_trigger_id`

inner mesa
#

Or a regular condition that checks the ID

astral pebble
#

i made a template to say when the rain will stop/start but i feel like there might be a way to make it work better internally, does anyone have any ideas?
https://hst.sh/aqiliguwag.txt

#

im working on smth on my own rn

sacred sparrow
#

how do I do a 'less than 10 for 1 minute':
{{ states('sensor.energy_monitor_smartplug_watts')|float < 10 }}

marble jackal
#

Create a binary sensor using this template, and then use last_changed

sacred sparrow
#

ah - is that the only way?

marble jackal
#

Yes, because if it changes from 9 to 8 for example, your template is still true, but last_changed will get a new timestamp

sacred sparrow
#

ah good point - thanks

sacred sparrow
#

{{ as_timestamp(now()) - as_timestamp(states.sensor.washer_dryer_watts_10.last_changed) < 60 }}

#

does that look right?

#

I want it to trigger the automation after the watts go above 10 for 10 minutes (that makes it certain the the washer/dryer is on)
then I want it to wait for the watts template sensor to be true for 60 seconds before sending the message

marble jackal
#

No need to use timestamps, I would expect a binary_sensor here

#

{{ (now() - states.sensor.washer_dryer_watts_10.last_changed).seconds < 60 }}

sacred sparrow
#

does it matter that its not a binary? it will still show False/True right?

marble jackal
#

Binary will be on or off, but sure, you can use a normal sensor as well

#

With a binary sensor you could also add a delay in turning it on (10 minutes) and off (1 minute) and just use the state changes

#

But based on your explanation you want it to be < 10 for more than 60 seconds, not less

#

You can simply use holding the state as well then

sacred sparrow
#

I've changed it around a bit:

    - name: "Washer/Dryer Status"
      availability: "{{ not is_state('switch.washer_dryer_smartplug', 'unavailable') }}"
      delay_on:
        minutes: 10
      delay_off:
        minutes: 1
      state: "{{ states('sensor.washer_dryer_smartplug_watts')|float > 10 }}"```
proper ore
#

hi all. i have this template in the dahsboard card

#
{% if is_state('light.office_fan', 'on') %}
  orange
{% elif is_state('binary_sensor.frontdoor_contact', 'off') %}
  grey
{% endif %}
#

is there anyway to get the current bulb color to show instead of a static orange etc?

#

thx alot!

mighty ledge
#

rgb({{ state_attr('light.office_fan', 'rgb_color') | map('string') | join(',') }})

sacred sparrow
#

how can I make this work:

{{ as_timestamp(state_attr('calendar.holidays','start_time')) - timedelta(hours = 3) }}

#

I'm getting error; "TypeError: unsupported operand type(s) for -: 'str' and 'datetime.timedelta':

#

I want to use it with {{ now() }}

marble jackal
#

You can't use timedelta on a timestamp

#

Use as_datetime if it isn't a datetime yet

sacred sparrow
#

as in:

>=
as_datetime(state_attr('calendar.holidays','start_time')) - timedelta(hours = 3) }}```
?
marble jackal
#

Yes, but calendar triggers support offset in 2022.6

sacred sparrow
#

I need it in a condition - theres no offset for condition right?

#

I am using the offset for the trigger but I need it for the condition

#
{{ now() >= as_datetime(state_attr('calendar.holidays','start_time')) - timedelta(hours = 3) }}

get me: "TypeError: can't compare offset-naive and offset-aware datetimes"

marble jackal
#

Add as_local then

#
{{ now() >= as_local(as_datetime(state_attr('calendar.holidays','start_time'))) - timedelta(hours = 3) }}```
sacred sparrow
#

ah that works great - thank you

#

for my Option 2 - can I just have
as_local(as_datetime(state_attr('calendar.holidays','end_time'))) + timedelta(minutes = 1) }} without the now() ?

#

or should I just have
{{ now() >= as_local(as_datetime(state_attr('calendar.holidays','end_time'))) + timedelta(minutes = 1) }}

marble jackal
#

What is option 2 again? If it is a condition, it has to evaluate to true or false

proper ore
silent barnBOT
sacred sparrow
silent barnBOT
marble jackal
#

What went to true? There is no template in your trigger

sacred sparrow
#

the condition went to true but the trigger didnt fire even though its basically the same as the condition

merry marsh
#

If I use a trigger for a template sensor

  - trigger:
      - platform: state
        entity_id: sensor.foo
    sensor:
      - name: Bar
        state: >
          {% if is_number(trigger.from_state.state) and (float(trigger.to_state.state,default=0) > float(trigger.from_state.state,default=0)) %}

where sensor.foo is a REST entity. Why I'm getting UndefinedError: 'None' has no attribute 'state' during startup. If it has no state, the state trigger should not fire, shouldn't it?

#

And which part is causing the error? Is there any way to see it?

manic tartan
#

Hi. Didn't found in HA documentation - is there a Python file counterpart for automation, script filenames (or automation/script id or name) to use it in error messages or templates?

#

default:

  • service: persistent_notification.create
    data:
    title: "!!! script.maindoor_handler - unknown command: '{{command}}'"
    replaced to
    title: "!!! {{file}}} - unknown command: '{{command}}'"
inner mesa
#
test_msg:
  sequence:
  - service: persistent_notification.create
    data:
      message: "script: {{ this.entity_id }}"
#

Script variables that may be used by templates include those provided from the configuration, those that are passed when started from a service and the this variable whose value is a dictionary of the current script’s state.

manic tartan
#

Many thanks :-), this is exactly what I'm looking for. I have noticed 'this' object in manual, but never try to read about it. My fault.

#

Any chance that there is also ... C language assert() macro counterpart?

inner mesa
marble jackal
#

Add not_from: [ 'unavailable', 'unknown' ] to the trigger

merry marsh
#

Thanks. Can somehow understand and thought this, but do not really "agree" to the logic, because if there is a state trigger = state change, it is not logical, that there is no from_state.state. If it would be None or whatever, but completely no state of from_state or no from_state seems to be not logic. Same problem in my mind with you not_from. If there is no from_state, why can I check with not_from to a value, if there is no from_state?

inner mesa
#

I don't think testing the value will work if there's no previous state. This is what I do:

  condition:
    - "{{ trigger.from_state is not none and trigger.to_state is not none }}"
    - condition: template
      value_template: >-
        {% set to_state = trigger.to_state.state|int(0) %}
        {% set from_state = trigger.from_state.state|int(0) %}
        {{ (from_state != to_state) and (from_state > 0) }}
merry marsh
#

Currently I have a if trigger.from_state and trigger.to_state around and it is working now. But still curious that in such cases from_state.state is not there instead of e.g. "intial", "n/a", None

inner mesa
#

All of those things are arbitrary

#

if there's no previous state, there's no previous state

merry marsh
inner mesa
#

you cannot get translated states in a template

merry marsh
#

Grrrrrr. What a pity. But thanks for the info/confirmation. Any Improvement requests I can vote for? 😉

inner mesa
#

you can look

silent barnBOT
#

If you have a feature request for the frontend you can open one here, for Home Assistant itself please post on the forum. All other feature requests should be made to the developer of that custom card/component.

inner mesa
#

you can do your own translation for display, but using consistent states makes more sense in logic

merry marsh
#

Did that ofc before. Should be only a joke. At least didn't find.

dark rock
inner mesa
#

You're using the same type of quote inside and outside the expression

versed shore
#

how do you use an input selector in a blueprint automation in a jinja template?

#
{{ (state_attr('sun.sun', 'elevation') - !input 'min_sun_elevation') / (!input 'max_sun_elevation' - !input 'min_sun_elevation') * (!input 'max_color_temp' - !input 'min_color_temp') + !input 'min_color_temp' }}
#

is that valid?

versed shore
#

can I make a variable with the input to use?

mighty ledge
#

the only option is to plop the selector into a variable and then use the variable

versed shore
#

@mighty ledge so is this how I'd set the variables in the blue print?

   variables:
       - min_sun_elevation: !input 'min_sun_elevation'
       - max_sun_elevation: !input 'max_sun_elevation'
       - min_brightness: !input 'min_brightness'
       - max_brightness: !input 'max_brightness'
       - min_color_temp: !input 'min_color_temp'
       - max_color_temp: !input 'max_color_temp'
mighty ledge
#

no, remove -

versed shore
#

then {{ min_brightness|int }} ?

mighty ledge
#

you also don't need quotes

#

yes

#

but you don 't need int

versed shore
#

thanks, it's helpful having your experience to get me over this hurdle

mighty ledge
#

np

versed shore
#

I had one other weird issue w/ selectors maybe you've seen before

#

I used:

input:
  min_color_temp:
    name: Minimum Color Temperature
    description: Color Temperature to use with lights when the sun is lowest on the horizon.
    default: 370
    selector:
      color_temp:
        min_mireds: 173
        max_mireds: 370

And the color temp picker says undefined* up where in other areas of the UI it says 'Color Temperature' on other color_temp inputs like on a device's settings.

mighty ledge
#

Sorry, cant help with that one

inner mesa
silent vector
#

Hey Petro. I want to use next_start to evaluate the time between now and then against weather conditions. The goal is to make a dynamic HVAC Schedule. This is not proper formatting just thoughts and placeholders for temperatures so that I can fix in the future as I figure out what I want. Is this possible to evaluate the weather conditions in the time between now and next_start? I brought in some stuff from a previous script you helped with related to the weather tts script.
https://dpaste.org/C02yr

versed shore
#

yeah makes sense @inner mesa I started there for the issue @mighty ledge helped with

dull hinge
#

Hello guys,

#

i am just a bit lost. I searched the web upsidedown but cant find an answer. So i like to try it here:
I cant get my "wait_for_trigger" working. I try to compare two sensors and if thats true, it should trigger the trigger.

#

I currently have:

#

action:

  • wait_for_trigger:
    • platform: template
      value_template: >-
      {{ states('sensor.innen_temperatur') | float >
      states('sensor.aussen_temperatur') | float }}
      continue_on_timeout: false
      timeout: '12:00:00'
inner mesa
#

first:

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://dpaste.org/ (pick YAML for the language), https://www.codepile.net/ (pick YAML for the language), or https://paste.debian.net/ (pick YAML for the language).

inner mesa
#

second, that won't "trigger" if it's simply true, it has to transition from false to true

dull hinge
#

Developer menu shows that the value template returns true / false, so that does not seem to be a problem.

#

I see. I will formate in the future.

dull hinge
#

Thanks for helping.

#

So seems like this should work, however i just can not test it because i can not make the value change.

inner mesa
#

you can always test by changing the value(s) in devtools -> States

dull hinge
#

ah nice, i did not know that.
One last question: What happens if the "wait_for_trigger" gets probed while the value template is already true? Is the timeout still active and waiting for a transition from false to true? The step details do not seem to show that the timeout is running. So i assume it just gets canceled?

inner mesa
#

Is the timeout still active and waiting for a transition from false to true?

#

yes

#

you told it to wait for a trigger and the trigger hasn't happened

silent vector
#

The continue on timeout needs to be true to continue.

dull hinge
#

Thanks again!

#

I think got everything figured out with your help!
Nice evening to everyone!

native sparrow
#

It seems when using "utcnow" in the template editor in dev tools, you ALWAYS have to wait for one minute for the template to evaluate. I understand why but surely it should re-evaluate whenever you edit the template? There seem to be some cases where it does evaluate or even partially evalute the template on edit, but I cant follow the logic. Really confusing when your edit immediately results in an error, but one minute later is correct.

#

And there also appears to be some weird browser caching issues where I return to a browser tab that previously evaluated utcnow correctly and now it shows the results from a previous template, then after one minute -evaluates correctly again.

native sparrow
#

OK This seems to be a minefield when using sensors and times that update at different times. I'll just try to be aware of it and not get misled by unexpected results. Restarted my browser (and PC to be safe) and issues disappeared. I wish I had figured this out 6 months ago. Has probably cost me days and much frustration. Live and learn.

orchid oxide
#

why does the following evalute true in dev template for an entity_id of null: {{states.group.person.attributes.entity_id==None}}

but in an automation '{{trigger.from_state.attributes.entity_id==None}}' evaluates as false for the follow from_state:

  from_state:
    entity_id: group.person
    state: home
    attributes:
      entity_id: null
      order: 0
      friendly_name: home group```
dark rock
marble jackal
#

Or the other way around

dark rock
#

If i put the automation like this:

"{{ as_timestamp(now()) - as_timestamp(state_attr('automation.riego', 'last_triggered')) > 172800 }}" or
''{{ as_timestamp(now()) - as_timestamp(state_attr('automation.riego', 'last_triggered')) > 172800 }}''
(First is double quote character and second is two single quote char)

Error is: Error occurred while testing condition
template value should be a string for dictionary value @ data['value_template']. Got None

If i put it the other way (single outside, double inside), error is the same. I'm sure I'm doing something wrong, but i can't find what.

Automation code is here btw: https://pastebin.com/DSuEUBRr

@marble jackal

marble jackal
dark rock
#

It's not working sadly

marble jackal
#

What is not working?

#

The template works in devtools >Templates you just said right?

#

And you are using different quotes inside and outside the template now

#

You are not in the code you linked above

dark rock
# marble jackal What is not working?

Condition under automation is not working. If i put the template under the template checker it says "true" (which indeed is beacuse the now time - last time triggered is greater that the delay).

I have runned the automation in order to check if it's going to work and it gets "rejected" because the condition is marked as false. Maybe is something with the formating?

"New" code is here:
https://pastebin.com/qJrvGVyL

marble jackal
#

@dark rock No, it's because you are checking if your automation has triggered over 1000 seconds ago in the same automation which has just triggered

#

that will never be true

#

Fortunately this.attributes.last_triggered will contain the timestamp you actually need

buoyant sapphire
#

This template returns "Result type: list", as can be seen in the link below.

{{ state_attr('weather.home', 'forecast') }}

Result: https://dpaste.org/mVWV5

How can I extract from this entire result only certain lines, eg. line 3,5,6 (tomorrows weather).

Thx.

marble jackal
#

{{ state_attr('weather.home', 'forecast')[0].temperature }} for temperature 🙂

buoyant sapphire
#

thanks a lot. very hard to find that out via google 😄

marble jackal
#

well, with [0] you take the first item out of the list (which is tomorrow). And then you can take out the different values by using the key

buoyant sapphire
#

easy to see now, that someone (you) pointed it out. now its obvious 😄

silent vector
marble jackal
#

Well, it's a getting more complicated every time I help you add something. What are the plans after you have the weather in?

silent vector
#

@marble jackal That's it. I just needed to get the temperature from the first part. Then off that see if any adjustments are made based off when the next start is and the weather. The rest I can handle as they aren't super complex variables.

marble jackal
#

Well, if you replace your current hour format to "07:30" you could just use today_at on the next_start variable

#

and then you have a timestamp which you can use to get the weather conditions

silent vector
#

I copied that state template format from a post on the forums from taras, I didn't know if 7:30 could be used in [07:30, 08:30, 63]

marble jackal
#

{% set t = now().strftime('%-H%M') | int %} change this to {% set t = now().strftime('%H:%M') %} in both templates (for state and next_start) to have them working with the new time format

#

use quotes

#

and a 0 like the example I just gave

#

otherwise a string comparison will not work

silent vector
#

Like that? 07:30

marble jackal
#

["07:30", "08:30", 63]

silent vector
#

Yep I just realized what you meant by quotes. That's also more readable than 630 lol

marble jackal
#

You might want to use single quotes though (or replace the quotes outside the template to single quotes)

silent vector
#

I see and will going all the way to 00:00 ["18:45", "23:59", 63] still be necessary, ["00:00", "05:30", 63]

marble jackal
#

Yes

silent vector
#

I see, I wasn't sure if changing to a proper format negated the need for that.

marble jackal
#

Well, you totally have to rebuild the hours format to something else to remove that need

silent vector
#

It's ok

marble jackal
#

you can change {{ (hours[index + 1] | default(hours[0]))[0] }} to {{ (hours[index + 1] | default(hours[1]))[0] }} so it won't report 00:00 as next_start

silent vector
#

I'll do that

dark rock
dark rock
#

So, would you mind sharing how the template will be? I don't know how to write it :(

In the ha forum post I shared the solution seemed to work for the fella asking there 🤣

marble jackal
#

Use this.attributes.last_triggered instead of state_attr('automation.riego', 'last_triggered')

dark rock
unreal beacon
#

hi, im trying to cost up the energy consumption "live" for a device in the house ive currently got this template

#

£ {{(states('sensor.plug_this_month_energy') | float * 0.07319) | round(2)}}

#

which is using a harcoded unit cost and thats working fine

#

however ive built a helper to do this for me so i dont have to change it in a million places

#

which is input_number.electricitycost

#

so i thought i could do this

#

£ {{(states('sensor.plug_this_month_energy') | float * states('input_number.electricitycost') | round(2)}}

#

but this doesnt work?

marble jackal
marble jackal
dark rock
unreal beacon
#

i cant paste image haha

#

well it just seems to ouput the template

#

so just £ {{(states('sensor.plug_this_month_energy') | float * states('input_number.electricitycost') | round(2)}}

silent barnBOT
#

Please use a code share site to share code or logs, for example:

Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.

marble jackal
#

Ah you actually fixed the round, and that broke the template

unreal beacon
marble jackal
#

because now you are not casting the input_number to a float

#

{{(states('sensor.plug_this_month_energy') | float * states('input_number.electricitycost') | float) | round(2)}}

marble jackal
unreal beacon
#

youre a star

silent vector
marble jackal
#
{% set this = {
              "entity_id": "automation.zz_automation_for_quick_tests",
              "attributes": {
                "last_triggered": "2022-06-01T06:37:40.686363+00:00",
              } 
            }
%}
{{ as_timestamp(now()) - as_timestamp(this.attributes.last_triggered) > 1000 }}
#

This is using the data from the test condition trace I just created

#

in devtools >templates is returns true however in the condition it returns false

dark rock
#

yep

#

been stuck there for about a week before asking here

#

I know how to do this in a different way, with two automations and some input_helpers.. but this should be done in a more elegant way 😁

marble jackal
#

This should work

#

it's a bug I think

dark rock
#

I wasn't sure and I don't want to be the "guys who raises issues just to seek for help"

#

😁

#

i just solved it in the more simplistic and idiotic way possible

#

if the template value is wrapped around int casting it just works 😮

{{ int(as_timestamp(now())) -
int(as_timestamp(this.attributes.last_triggered)) > 1000 }}

#

maybe its unable to compare as_timestamp to 1000 as it returns a float ?

marble jackal
#

No, it wouldn't have worked in devtools then

dark rock
#

yeah, that is. i just checked with value_template: '{{ as_timestamp(now()) - as_timestamp(this.attributes.last_triggered) > 1.0 }}' and it also works

Great Scott! (and @marble jackal for all your help)

marble jackal
#

Does that work in your automation?

#

hmm, strange

#

but okay

#

still a bug I would asy

#

say

buoyant sapphire
#
Todays date is {{ now().date() }} 
Last time the vacuum robot ran was {{ states('input_datetime.staubilastruneingang')[0:10] }}

It would be great to get the delta/difference from these two dates. eg: 1, when it was running the last time yesterday.

Any idea how I can compare two dates, or any other template-idea on how to extract the information how many days it has been since a certain script was run?

marble jackal
#

becasue you put quotes around your template and you are also using the multi line notation

dark rock
dark rock
marble jackal
#

Then you put quotes around the template in the GUI

#

but that is why that one isn't working

#

hasn't got anything to do with the int

dark rock
marble jackal
#

Check the trace for a faulty one, it probably has something like value_template: '"{{ template }}"'

#

yes, you should not put quotes around your templates in the GUI

#

the GUI will do that for you, if you also do it, it will double quote it, and treat it like a string

dark rock
marble jackal
#

Yes, that's what I said, don't put quotes around it

marble jackal
#
condition:
  - condition: template
    value_template: >-
      "{{ as_timestamp(now()) - as_timestamp(this.attributes.last_triggered) > 1000 }}"
dark rock
#

ok

marble jackal
#

That one is incorrect

dark rock
#

thanks for your help

#

👍

marble jackal
#
condition:
  - condition: template
    value_template: >-
      {{ as_timestamp(now()) - as_timestamp(this.attributes.last_triggered) > 1000 }}
condition:
  - condition: template
    value_template: "{{ as_timestamp(now()) - as_timestamp(this.attributes.last_triggered) > 1000 }}"
#

these 2 are

dark rock
#

great, thank you so much. Just understood the difference

#

as the gui/yaml was different it was weird and lead me to not be sure

#

thanks again for your help

#

also, when i started doing this automation I tried the test button without knowing that it was bugged as you reported

marble jackal
# silent vector How would I implement this? To get the weather conditions between `now` and `nex...
{% set weather = 'weather.climacell_hourly' %} {# change to your own weahter entity #} 
{% set next_start = '15:00' %} {# replace with a reference to the attribute of your sensor #} 
{% set forecast = state_attr(weather, 'forecast') %}
{% set n = today_at(next_start).astimezone(utcnow().tzinfo).isoformat() | string %}
{{ forecast | selectattr('datetime', '<=', n) | map(attribute='temperature') | max > 80 }}
#

That returns true if there is a temperature between no and next_start above 80

silent vector
#

If I wanted to add multiple conditions (if, elif, else) to this rather than just above 80 what would I need to do?

marble jackal
#
{% set weather = 'weather.climacell_hourly' %} {# change to your own weahter entity #} 
{% set next_start = '15:00' %} {# replace with a reference to the attribute of your sensor #} 
{% set forecast = state_attr(weather, 'forecast') %}
{% set n = today_at(next_start).astimezone(utcnow().tzinfo).isoformat() | string %}
{% set temp_max = forecast | selectattr('datetime', '<=', n) | map(attribute='temperature') | max %}
{% set temp_max = forecast | selectattr('datetime', '<=', n) | map(attribute='temperature') | min %}
#

use temp_max and temp_min in your statements

silent vector
#

If 80 is <= temp_max or >= temp_min for example?

marble jackal
#

for example

#

you could also do someting like
{% set temp = forecast | selectattr('datetime', '<=', n) | map(attribute='temperature') | list %}

#

it will list all temperatures between now and next_start

#

I just based it on the information you've given, that you wanted to check if it ever went above 80

silent vector
#

I know I only gave 1 temperature I am not 100% sure how I want to do it, just good to have options. If I use the list, what would the if,elif statement be?

marble jackal
#

I would not know without you telling me what you want to achieve

silent vector
#

Let's say

         {% if the temperature between now and the next_start is <= 55 and > 50 %} 
         {{ operating_temperature - 1 }}
         {% elif time between now and next_start <= 50%}
         {{ operating_temperature - 2 }}
         {% else %}
         {{ operating_temperature }}
         {% endif %}
marble jackal
#

what is the temperature? there could be multiple temperatures between now and the next_start

silent vector
#

I see, so I need to figure out max and min as you stated and then determine if any are leas than or equal to 55 and greater than 50 for example.

marble jackal
#

using the list option, you could do this:
{% if temp | select('>' , 50) | select('<=', 55) | list | count > 0 %}

silent vector
#

And if > 0 then it returns true right?

marble jackal
#

yes

silent vector
#

Perfect. This is exactly what I needed thank you as always. You need to have a buy me a coffee link or something.

marble jackal
#

There is one on my Github profile (which I link to from my profile here) if you really want to, but don't feel obliged

tame rain
#

Hi Everyone!

This is probably a pretty stupid question, but I’m a bit at a loss.

I followed a guide how to use license plate recognition in HA.
I got everything up and running. When I run the service in Developers Tools I get this output in states:
https://imgur.com/a/VP5uc7O

Now I would like to use this information to check if it’s a plate that is allow so I trigger my gate.

Trigger: When last_detection is changed
Condition: Plate is true to some value
Action: Open Gate

The trigger and action I figured out.
But I’m not sure how I would go and check if it’s the correct plate
https://imgur.com/a/PirxWvl
https://imgur.com/a/CATctwg

marble jackal
#

what is your actual trigger here? Is it a state trigger?

tame rain
#

Yes whenever last_detection changes

marble jackal
#

you could use:

condition: template
value_template: >
  {% set allowed_plates = [ 'abc123', 'def456' ] %}
  {{ state_attr('image_processsing.whatever', 'vehicles')[0].plate in allowed_plates }}
tame rain
#

Man if this works you are a legend

#

I tried it, but it does not seem to work. When I click "test" I get this message:

marble jackal
tame rain
#

Yea I already seeing some mistake I made. Going to copy your code in the automations.yaml file instead of the GUI

marble jackal
#

test the template in devtools > templates

#

and stop posting images of text

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://dpaste.org/ (pick YAML for the language), https://www.codepile.net/ (pick YAML for the language), or https://paste.debian.net/ (pick YAML for the language).

tame rain
#

I think it works. Thanks!

tepid onyx
#

If i have a jinja template like:
{%- if is_state('binary_sensor.person_2_in_bed','on') %}
{{ ' ' ~ name2 ~ ', ' }}
why do I have to concatenate ' ' in front of a variable (name2) for it to work

#

' ' is just a space but could be any string

mighty ledge
tepid onyx
#

it's passing the template to a input_text which sends it off to an aws skill lamba. I think it's just the configuration the way it works

#

Thought i was going nuts

#

That info probably would of helped...telepathy again

mighty ledge
cobalt otter
#

Got this error when I restarted HA. I'm guessing it's because Zigbee2MQTT didn't reregister the object in the MQTT running in HA yet? What do I need to wrap the function with just to avoid the error?
homeassistant.exceptions.TemplateError: ValueError: Template error: float got invalid input 'unknown' when rendering template '{{ (states('sensor.compressor_inside_temp_temperature')|float - states('sensor.sonoff_temp_2_temperature')|float ) > 2.0 }}' but no default was specified

inner mesa
#

you need to specify a default that you're comfortable with, or add an "availabilty" key