#templates-archived

1 messages · Page 41 of 1

grand walrus
#

Sorry I start again : Hello to all... I've adjusted an IMAP template as below... Something is wrong in the text of the email I get from my Alarm provider... When I send an email just with "partiel" in the text, it is ok.. but not when it receive the original email... any clue on what is wrong in this email? How can I see if there is any specific formating in the email?
Here is the config file : https://dpaste.org/6z8U0

plain magnetBOT
#

@thorny cargo I converted your message into a file since it's above 15 lines :+1:

marble jackal
#

@thorny cargo I would create a trigger based template sensor in that case:

template:
  - trigger:
      - platform: state
        entity_id:
          - light.schlafzimmer
          - light.nachttisch_links
          - light.nachttisch_rechts
       to: "on"
    sensor:
      - unique_id: last_light_turned_on
        name: Schlafzimmer Last Controlled
        state: "{{ trigger.entity_id }}"
        icon: mdi:lightbulb
#

you can also remove to: "on" so it will also change the entity id if you use other actions, like dim it, or change color

thorny cargo
#

I´m new to HA. Where would i put that solo template?

marble jackal
#

in configuration.yaml

thorny cargo
#

What´s the advantage to my solution?

marble jackal
#

you only have one entity, instead of an automation and an input_text, and it's not possible to change the value by accident (you can't change a sensor state)

#

But it's just a suggestion, you can also use your automation and input_text

thorny cargo
#

Thanks!

#

I´m using HA for just a few days and I´m already loving it.

#

Totally easy even as a beginner. There´s always a way to do it.

#

And it supports literally everything.

haughty breach
# grand walrus Sorry I start again : Hello to all... I've adjusted an IMAP template as below......

How do you have your IMAP integration sensor(s) search terms configured? If your IMAP sensor isn't exclusive to the sender for this Content sensor (or you have multiple IMAP sensors), you must limit the trigger for any Content sensor with more specific event data and/or additional templating. Otherwise, every new email from any sender will be evaluated and possibly cause the Content sensor's state to change.

sonic ember
#

I have a template sensor that works perfectly well and sets a list if values in an attribute of my sensor. I'd like to add the average of those values as an additional attribute in the entity, how would I go about that?

#

THis is the part setting the values:

      prices: >
        {% set ns = namespace(prices=[]) -%}
        {%- set today = state_attr('sensor.energyprices','raw_today') -%}
        {%- for hours in today -%}
          {%- set ns.prices = ns.prices + [hours.value | float(0) + states('input_number.nextenergy_additional_electricitycosts') | float] -%}
        {%- endfor -%}
        {%- set tomorrow = state_attr('sensor.energyprices','raw_tomorrow') -%}
        {%- for hours in tomorrow -%}
          {%- set ns.prices = ns.prices + [hours.value | float(0) + states('input_number.nextenergy_additional_electricitycosts') | float] -%}
        {%- endfor -%}
        {{ ns.prices }}
mighty ledge
#

you have to replicate that code again and end with {{ ns.prices | average }}

#

@sonic ember ^

sonic ember
#

Ah, that simple 🙂

#

Thanks

grand walrus
# haughty breach How do you have your IMAP integration sensor(s) search terms configured? If your...

Hello.. No, I installed the new IMP integration... so the selection is done in the config file.. so I don"t have any sender selection.. I really feel it comes from the email... I ran some more test, from the same email address :

  • I send an new email email with "partiel" in the text body ==> it works
  • I take the email I 've received from the alarm company.. make a forward.. but before sending (from same email), I remove all the text and subject, and put the same thing that I had in the first email... and it doesn't work!! 🤬
haughty breach
sonic ember
#

I've created a template sensor to add some costs to my base gas costs. But the energy dashboard is complaining about it. I think I'm getting the unit of measurement wrong?

#
  # Gas price all in
  - name: "Current Gas Price"
    unique_id: d2ab4f7d-759d-44d0-b7ec-89aade5fbad9
    icon: mdi:currency-eur
    unit_of_measurement: "EUR/m3"
    state: >
      {% set gasprice = states('sensor.current_gas_market_price') | float(0) * 1.21 + states('input_number.nextenergy_additional_gascosts') | float(0) %}
      {{ gasprice }}
#

This is the error:

Unexpected unit of measurement
Translation Error: The intl string context variable "energy_units" was not provided to the string "The following entities do not have an expected unit of measurement (either of {energy_units}):"
sensor.current_gas_price (EUR/m3)
lofty mason
#

IIRC "m3" is not valid, it has to be that stupid superscript thing.

sonic ember
#

Ah... great. how do I get that on a mac?

lofty mason
#

find one and copy paste it 😛

sonic ember
#

hahaha was fearing that answer

lofty mason
#

I was working on a PR related to this recently and I had to figure out how to get that into vim and it can't even display it in ascii .

#

🤦

sonic ember
#

Thanks, that worked!

mighty ledge
#

\xEF etc

lofty mason
#

beats me I don't know how that stuff works. just copy paste and pray 🙂

mighty ledge
#

it's just bytes

#

when it cant' figure it out, it displays the bytes

#

or at least it should

#

or a box

#

[]

lofty mason
#

I see it displayed as an underscore, but it also screws up the line and visually doubles the next character after it, it's weird.

#

must not be installed with the right support or something

#

anyway I've moved on from that now

mighty ledge
#

IIRC you can set the encoding in vim

grand walrus
grand walrus
plain magnetBOT
#

@knotty stirrup I converted your message into a file since it's above 15 lines :+1:

knotty stirrup
#

Hey there,
I am working on a mqtt discovery sensor.
It works fine.
The Sensor gets a payload with a json object, and i can read the attributes.
But now i want to use the json_attributes_template to customize the attributes.
If i send the config over mqtt, it does not work.
If i configure the template via configuration.yaml, it works.
in yaml:
json_attributes_template: "{ "testattribute": 3 }"
in mqtt as a payload:
"json_attributes_template": "{"testattribute": 5 }",
yaml works, mqtt not.
What am i doing wrong?

#

fyi. Discord removed the escapings on the double quotes in the dict.

knotty stirrup
#

Nevermind.... Dont know why, but i deleted the config in mqtt retain and recreated it and it works now.

marble jackal
plain magnetBOT
#

To format your text as code, enter three backticks on the first line, press Shift+Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks.
```yaml
example: here
```
Don't forget you can edit your post rather than repeatedly posting the same thing.

plain magnetBOT
#

@woven folio I converted your message into a file since it's above 15 lines :+1:

mighty ledge
#

@woven folio there are alot of things wrong with that code

#

what are the intentions of it?

errant hinge
#

Is it possible to inject a variable for an mdi icon into a card_mod style please?

entity: sensor.givenergy_batteries_soc
name: Battery
card_mod:
  style: |-
    :host {     
      {% set soc = states('sensor.givenergy_batteries_soc') | int | round(-1) | round(0) %}
        --card-mod-icon: {{ 'mdi:battery-' ~ soc ~ ';' }}```
#

The concatenation syntax seems to work in Dev Tools, I'm just not sure of the nested syntax for card_mod style.

woven folio
meager vector
#

Hi, i have troubles to create binary_sensor with device_class

template:
  - binary_sensor:
    - name: "living_room_camera_motion_detected"
      state: >
        {% if is_state('switch.living_room_camera_motion_alarm', 'on') %}
           {{ is_state('select.living_room_camera_sound_detection_densitivity', '1') }}
        {% else %}
           False
        {% endif %}
      #device_class: "motion"

There is 2 problems:

  • sensor shows as sensor, not binary_sensor
  • if i uncomment device_class, sensor is not showing.

Any suggestions?

mighty ledge
woven folio
fickle sand
mighty ledge
#

so you should make that a choose

#

with a condition

woven folio
mighty ledge
woven folio
fickle sand
#

The action is something different than a template in the service data

woven folio
#

i wrote that action some years ago. It probably had that extra quote, and the "if" wasn't working, but the automation was fine besides that
since some times ago (maybe an update), HA started disabling it because of the error

mighty ledge
#

that would have errored every time

#

the extra quote causes all sorts of syntax errors and everything below it would not work

#

code flows top down, if it fails with a syntax error, it drops the rest

woven folio
#

yep, but maybe an error in logs, but automation working
or maybe i've put the quote sometime in the past without noticing
i can assure you that the if wasnt working (i've always heard the message even from Agostina)
but the rest of the action was working (outdoor lights, screenshots in telegram, fence opening, etc. etc.)

#

this evening i'll test it by going home from office

fickle sand
#

You can always test by manual changing the state of an entity in the dev-tools

woven folio
#

it's working

frank beacon
#

Hey all. I have the following template to calculate how much money I've made exporting energy:
£{{ ((states('sensor.myenergi_home_grid_export_today') | float) * (states('sensor.electricity_export_current_rate') | float)) | round(2) }}

The current precise output value is £0.29889. Which rounds to £0.3.

Being very particular, is there any way to keep trailing 0 when it rounds to 1 decimal place? e.g. £0.30 instead of £0.3? Thanks!

lofty mason
frank beacon
spiral iris
#

Beside apexcharts, custom button-cards, card-mod, what other plugins/add-ons are worth to install to HA?

marble jackal
spiral iris
#

Ok

#

Because i see ppl seeking assistance for coding of those custom cards

#

I thought this room was the right place

inner mesa
#

Only the templates that may be used with them

thorny cargo
#

Why is this not valid:

  - condition: numeric_state
    entity_id: "{{ states('input_text.schlafzimmer_last_controlled') }}"
    attribute: brightness_pct
    above: 10```
#

Message malformed: Entity {{ states('input_text.schlafzimmer_last_controlled') }} is neither a valid entity ID nor a valid UUID for dictionary value @ data['condition'][0]['entity_id']

#

But it works for the action?

meager vector
thorny cargo
#

but the state is the entity_id in text

inner mesa
#

You can't use a template there

thorny cargo
#

How would i do it then?

inner mesa
#

You need to use a template condition

#

{{ state_attr(states('input_text.schlafzimmer_last_controlled'), 'brightness_pct') > 10 }}

thorny cargo
#

Seems like it doesnt work.

plain magnetBOT
#

@thorny cargo I converted your message into a file since it's above 15 lines :+1:

thorny cargo
#

Does that look correct?

inner mesa
#

it's fine. "doesn't work" isn't helpful

thorny cargo
#

Stopped because a condition failed

#

Error: In 'template' condition: TypeError: '>' not supported between instances of 'NoneType' and 'int'

inner mesa
#

see, that's helpful

thorny cargo
#

Just found it. I´m new to HA.

inner mesa
#

you're probably trying to do that when the light is off

thorny cargo
#

No it´s not.

#

It´s above 10 pct

inner mesa
#

put {{ state_attr(states('input_text.schlafzimmer_last_controlled'), 'brightness_pct') }} in devtools -> Templates

thorny cargo
#

null

inner mesa
#

then:
{{ states('input_text.schlafzimmer_last_controlled') }}

thorny cargo
#

string

light.schlafzimmer

#

string is the type above the output

inner mesa
#

so there is no "brightness_pct" attribute

#

there is probably a "brightness" attribute

#

devtools -> States

#

how do you know that it's above 10%?

thorny cargo
#

Learning curve just rockets to sky.

#

no there is no birghtnes_pct

#

but why can i controll brightness_pct for the same light in action then?

inner mesa
#

because you can use brightness_pct when changing the brightness, but the actual brightness is represented as an absolute value

thorny cargo
#

Is there an easy conversion or do I have to consier 10% of 250 is 25, so 25 myself?

inner mesa
#

the easy conversion is multiplication

thorny cargo
#

Sure, but do i have to be aware of types (float, int)?

inner mesa
#

?

thorny cargo
#

0.1*254=25,4

inner mesa
#

{{ state_attr(states('input_text.schlafzimmer_last_controlled'), 'brightness') > 255*.1 }}

thorny cargo
#

can HA do some int >25,4?

inner mesa
#

not with commas

thorny cargo
#

*25.4

#

sorry german habits

inner mesa
#

of course

#

you can test this in devtools -> Templates

thorny cargo
#

I reduce the brightness by 10% in action. Can i use this value twice in my automation somehow?

inner mesa
#

which value?

thorny cargo
#

The percentage of reduction

#

Like some variable

inner mesa
#

yes, you can create and use variables

floral shuttle
#

why cant I round this template??:```
{% set date = '1964-08-24' %}
{{(states('sensor.date') | as_timestamp - as_timestamp(date))/( 86400*365)}}

inner mesa
floral shuttle
#

trying to calculate the years since a date (also called age...) and day count to this years event with these:```
{% set date = '1964-08-24' %}
{{(states('sensor.date') | as_timestamp - as_timestamp(date))/( 86400*365)}}

{% from 'easy_time.jinja' import count_the_days %}
{% set current_date = date.replace('1964', (now().year)|string) %}
{{count_the_days(current_date)}}``` cant |int it either..

thorny cargo
inner mesa
#

see that page

#

you can put it where it says

#

there are several examples

thorny cargo
#

But the site is referring to scripts, isnt it?

inner mesa
#

the action of an automation is a script

thorny cargo
#

But i need my variable also in the condition.

inner mesa
#

then you can put it in the trigger_variables section

floral shuttle
#

heck, it missed a set of parenthesis...```
{% set date = '1964-08-24' %}
{{((states('sensor.date') | as_timestamp - as_timestamp(date))/( 86400*365))|int}}

{% from 'easy_time.jinja' import count_the_days %}
{% set current_date = date.replace('1964', (now().year)|string) %}
{{count_the_days(current_date)}}

thorny cargo
floral shuttle
#

hmm, seems this should be possible to make simpler:```
{% set event = '1964-08-24' %}
{{((states('sensor.date') | as_timestamp -
as_timestamp(event))/( 86400*365))|int}}

{% from 'easy_time.jinja' import count_the_days %}
{% set current_date = event.replace((event|as_datetime).year|string, (now().year)|string) %}
{{count_the_days(current_date)}}```

jolly crest
#

With this, the state is the total amount of attributes in my sensor. Can I change it so it states the highest number in the attribute list?
value_template: >
{{ value_json.series | length }}

#

Its for a rest sensor

inner mesa
#

replace "length" with "max"

jolly crest
#

No way

#

Yea too good to be true:/

inner mesa
#

what are the values in the list?

#

{{ value_json.series }}, in other words

#

I suspect that this is just from incomplete information

jolly crest
#

friendly_name: Vindkast
series:

  • time: '2023-05-26T22:00:00Z'
    gust: 3.3
  • time: '2023-05-26T23:00:00Z'
    gust: 2.8
  • time: '2023-05-27T00:00:00Z'
    gust: 2.7
  • time: '2023-05-27T01:00:00Z'
    gust: 3
#

List is longer tho

inner mesa
#

see, that would have been helpful 🙂

#

it's not just a list of numbers

jolly crest
#

Haha true

inner mesa
#

{{ value_json.series|map(attribute='gust')|max }}

#

might need this if it's not really a number:
{{ value_json.series|map(attribute='gust')|map('float')|max }}

jolly crest
#

Thanks!

thorny cargo
#

Can I specify a dimming transition time for all my light somehow?

inner mesa
#

Nothing to do with templates

thorny cargo
#

Does this also refer to dimming or only on/off?

floral shuttle
#

this is getting somewhere: - unique_id: marijn_verjaardag name: Marijn Verjaardag unit_of_measurement: dagen state: > {% from 'easy_time.jinja' import count_the_days %} {% set event = this.attributes.datum %} {% set current_date = event.replace((event|as_datetime).year|string, (now().year)|string) %} {{count_the_days(current_date)}} attributes: leeftijd: > {% set event = this.attributes.datum %} {{((states('sensor.date') | as_timestamp - as_timestamp(event))/( 86400*365))|int}} type: Verjaardag persoon: Marijn

#

and it gets its attributes.datum from a customize (had it set as this.attributes.datum at first, but then the template wouldnt render.

#

only thing is, this does not jump to next event when the date has already passed, and now it counts the days since this years event.... I want it to count to next years event. how to replace the 'replace' ...?

inner mesa
#

Yell Wonder Twins Powers Activate!

#

I don't know, restart HA?

pearl bough
#

Is there a way that I can either:

  • Import a jinja macro function so it's available hass-wide without having to import it each time i want to use it
  • import a jinja macro function so it's available across an entire automation without having to import it each time i want to use it
#

From my digging and not being able to find anything specific, i'm suspecting the answer is "Not Currently" unless I missed something obvious (which I'm not ruling out) but just wanted to confirm

thorny cargo
mint viper
#

hi, is there a way to do "latching" in a template? i have a template sensor for "sleeping" and want to have it turned on when a bunch of conditions are met but only turn off when a select few of them are no longer met. im thinking if i can "latch" the ones i dont want to turn it off untill the others are also unmet

inner mesa
#

Again, it really sounds like you're describing an input_boolean and trying to shoehorn it into a template sensor

#

A man with a hammer, so to speak

mint viper
#

oh i might have misunderstood what you said before, i thought you said you thought i would be able to build the logic into the template

inner mesa
#

I suspect you can, but it may make the template a lot more complex

#

Your question lacks enough detail to say more

#

If you really want to 'latch' a template sensor, use a trigger and return this.state if you don't want it to change

mint viper
#

ok thanks

mint viper
#

how would i check if the current time is after 4am?

inner mesa
#

{{ now() > today_at('4:00') }}

mint viper
#

thanks, the stuff i found on the forums wasnt working

#

also i think i have worked out a dirty but working way to do this, just have and if statement to change the conditions at ~4am (my normal sleep is from ~1-2am till ~8am)

#

it might mean things break if i have a nap in the middle of the day but thats not that big of an issue

#

actually, can a template sensor be self referencing?

#

im assuming no

fallow gulch
#

how would I go about adding a 5 minute delay to one of the 'off' triggers on this?

#
  - id: 'on'
    platform: state
    entity_id: binary_sensor.ewelink_ms01_iaszone_3
    to: 'on'
  - id: 'off'
    platform: template
    value_template: "{{ is_state('binary_sensor.ewelink_ms01_iaszone_3', 'off') and is_state('binary_sensor.workshop_devices', 'off') }}"
  binary_sensor:
  - name: Workshop Occupancy
    state: "{{ trigger.id }}"
    device_class: occupancy
    unique_id: bt_occupancy_workshop
    icon: >
      {{ iif(trigger.id == 'on', 'mdi:toolbox', 'mdi:toolbox-outline') }}```
#

the "devices" binary sensor already has a 5 minute delay_off, but the motion sensor only has a 60 second cooldown. I want this to wait for the motion sensor to have been off for 5 minutes.

marble jackal
#

Check for last_changed in the template sensor, or create similar binary sensors for those two entities as well

thorny cargo
#

How would I do some action for all lights and only those which are turned on?

viral bolt
#

Hi girls and guys, please help

#

I want to create a switch that controls the floodlight of an IP Camera

#

I've managed to create the switch using some curl .... commands

rose scroll
viral bolt
#

The problem I want to solve is how can I get the status of that floodlight

#

when checking with curl I get this answer:

#

table.Lighting[0][3].Mode=Off
or
table.Lighting[0][3].Mode=Manual

#

where Off means the floodlight is OFF, Manual means ON

#

Thanks, please be gentle, I'm below zero when it comes to coding/scripting 🙂

floral shuttle
#

so I finally have all fields correctly outputted, after startup. This replaces a perfectly simple python script, but as that sets an entity using hass.states.set, and we are not supposed to do that, I had to rebuild it in jinja. All good. except, it throws many errors on has no attribute 'id' when rendering and homeassistant.exceptions.TemplateError: UndefinedError: 'count_the_days' is undefined

#

id love some feedback please. the main datum attribute is set in a customize on the entity, so it is known right from the start. somehow this is causing a lot of issues

inner mesa
#

The value_template would be {{ 'on' if value_json.table.Lighting[0][3].Mode == 'ON' else 'off' }}

split pivot
#

is this the correct way to build a energy price sensor that automatically changes it's value on a specific date?

- sensor:
    - name: "Strompreis"
      unique_id: strompreis
      unit_of_measurement: "EUR"
      state: >
        {%- if now() > strptime('2023-06-01 00:00 +0200', '%Y-%m-%d %H:%M %z') -%}
          {{ (0.2712 * 1.19) | round(4) }}
        {%- else -%}
          {{ (0.3332 * 1.19) | round(4) }}
        {%- endif -%}
inner mesa
#

{{ now().date()|string < '2023-05-26' }}

#

For example

split pivot
#

so, I don't have to care about timezones?

inner mesa
#

now() is in your time zone

split pivot
#

ok. do I need to make it a trigger based template or does HA evaluate the template all the time?

inner mesa
#

It will evaluate once per minute. If you want to it less often (like once a day) you can add a time trigger for midnight

split pivot
#

once per minute is fine, thanks!

rose scroll
inner mesa
#

Yeah, that 🙂

#

It's early and I haven't had my coffee yet 🙂

viral bolt
inner mesa
#

Share your full binary_sensor definition and the JSON that's returned from the curl command

#

And you should use DanielLeong's version of the template

viral bolt
#

the output of the curl is table.Lighting[0][3].Mode=Off

#

or =Manual at the end

inner mesa
#

That's not JSON

viral bolt
#

yep, it's a plain text 🙂

inner mesa
#

So use this template instead: {{ (value.split('='))[1] == 'Manual' }}

viral bolt
#

only this?

#

name: dahua_floodlight_status
device_class: light
value_template: "{{ (value.split('='))[1] == 'Manual' }}"

inner mesa
#

Don't change anything else, just the template

plain magnetBOT
#

@grand robin I converted your message into a file since it's above 15 lines :+1:

marble jackal
#

Remove the unit of measurement line.

grand robin
#

Thanks it works now 🙂 just a simple thing...

plain magnetBOT
#

@rapid tinsel I converted your message into a file since it's above 15 lines :+1:

viral bolt
# inner mesa Don't change anything else, just the template

Sorry to bother you but I'm still unable to make the binary sensor to reflect the status of the floodlight. The GET command works fine as I've made a sensor that contains the full output of the command, so the only difference between sensor and binary_sensor is this line: value_template: "{{ (value.split('='))[1] == 'Manual' }}"

stuck remnant
#

I have a timestamp attribute and am trying to use a template to update it after it hasn't had any updates for 5 minutes, anyone know how the template should look like?

#

updated_time: '2023-05-27T06:57:22.280085+03:00'

inner mesa
#

works fine for me:

{% set value = "table.Lighting[0][3].Mode=Manual" %}
{{ (value.split('='))[1] == 'Manual' }}
viral bolt
#

That's right, it works on Template section for me also ...

#

I'll look further maybe I'm missing something

stuck remnant
#

the timestamp always changes, therefore I can't use it as is...
is there a template for this?

inner mesa
#

that's not gonna work

#

{{ now() - '2023-05-27T06:57:22.280085+03:00'|as_datetime > timedelta(minutes=5) }}

#

before you ask -

#

{{ now() - state_attr('sensor.miaomiaoce_t2_ae84_relative_humidity', 'updated_time')|as_datetime > timedelta(minutes=5) }}

rapid tinsel
#

Hello lovely people of home assitent,
i am having an issue with a total_increasing-template sensor that is not working as expected.
My power meter does not return a value for the amount of kWhs returned to the grid, so I want to use a total_increasingtemplate sensor for this job, so I can use it for the energy dashboard.
Currently I am having the following code:

#

- sensor: - unique_id: "grid_feed_in" name: "Einspeisung" unit_of_measurement: kWh device_class: energy state_class: total_increasing state: > {% if states('sensor.aktuelle_leistung') | int > 0 %} 0 {% else -%} {{ (states('sensor.aktuelle_leistung') | int) | abs / 60 / 1000 }} {% endif %}

#

With this code I am getting the following statistic data:

#

As you can see on the picture the statistic data recorded is seems not to be correct.

#

Can you please help me with this issue, so I can fix my energy dashboard

inner mesa
#

does that sensor report instanenous usage (power)?

rapid tinsel
#

yes, it does

inner mesa
#

that is not how you make an energy sensor from a power sensor

#

you're just telling what it is rather than actually doing the calculation

rapid tinsel
#

@inner mesa Thanks for the helpful tip, i've rewritten my code. I can only validate tomorrow when the sun is back if the sensor is reporting correct data.

ancient sleet
#

There appears to be a weird RESTful integration bug. Considering the below API json data:

#

The below code works when its broken up into multiline mode:

#
rest:
  - resource: http://192.168.1.2:61208/api/3/all
    sensor:
      - name: "Process 0 EXE"
        value_template: >-
          {{ value_json.processlist[0].cmdline | regex_findall('([^\\\\]+\\.exe)', False) | join(', ') }}
#

However, the below returns a value of Unknown:

inner mesa
#

sigh

ancient sleet
#

`rest:

  • resource: http://192.168.1.2:61208/api/3/all
    sensor:
    • name: "Process 0 EXE"
      value_template: "{{ value_json.processlist[0].cmdline | regex_findall('([^\\]+\.exe)', False) | join(', ') }}"`
plain magnetBOT
#

To format your text as code, enter three backticks on the first line, press Shift+Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks.
```yaml
example: here
```
Don't forget you can edit your post rather than repeatedly posting the same thing.

inner mesa
#

I think that's just an artifact of how the YAML parser works

ancient sleet
#

there are no syntax errors... they both pass lint format test

inner mesa
#

yes

ancient sleet
#

they also work correctly outside of HA templating

inner mesa
#

yes

ancient sleet
#

is there any way to get it to work like the way its expected?

inner mesa
#

use a multiline template, as you discovered

ancient sleet
#

i meant on the second example

inner mesa
#

is that an issue?

ancient sleet
#

both are valid

#

not an issue, i juist want to know why.. not just cause

inner mesa
#

you're welcome to file an issue

#

like I said, I think it's just a weirdness of the YAML parser

ancient sleet
#

okay thank you for your time

rapid tinsel
#

@inner mesa Again regarding the grid feed in issue: I've updated my code as you've recommend but i am still having an issue with the new integration sensor, that the values of it are not updating. I've changed the source of the integration sensor to the a source that returns the current power consumed from the grid. In that case the sensor updates its data (in kWh). Here is the current code that i am having: https://gist.github.com/faken/194775a9b605269ce44d75d3bba0174d

inner mesa
#

Unless you renamed it, I don't think the template sensor is named what you think it's named

plain magnetBOT
#

@teal umbra I converted your message into a file since it's above 15 lines :+1:

rapid tinsel
past wigeon
#

So if I have a sensor that has as attributes: ```labels:

  • Export
  • Import
  • Total
  • Total_Solar
    data:
    • 24346
    • 421632
    • 8867137
    • 2652647
      friendly_name: IoTaWatt (Select)
#

and in my template I do:

#
  - {{ state_attr('sensor.iotawatt_select', 'labels')[i] }}: {{ state_attr('sensor.iotawatt_select', 'data')[0][i] }}
  {%- endfor -%}```
#

it will output : - Export: 24346- Import: 421716- Total: 8867220- Total_Solar: 2652647

#

how can I insert a new line between each - ?

#

trying to generate a template sensor that has as attributes, the values of each of those. separately.

#

I guess I could make a json as the state; and use that instead. But setting attributes instead seems a nicer way to go about it

inner mesa
#

I would just add ~ '\n' to the second output statement

floral shuttle
#

blding a list of people home, I wonder if this is the most efficient way of setting that custom timestamp home: > {% for p in expand('group.family') if p.state == 'home' %} {% if p.last_changed.day == now().day %} {% set stamp ='%H:%M' %} {% else %} {% set stamp = '%d/%m - %H:%M' %} {% endif %} {{p.name}} ({{as_timestamp(p.last_changed)|timestamp_custom(stamp) }}) {% endfor %}

#

I had this in my python script:```
if (state.state == filter or debug):
dt = state.last_changed + datetime.timedelta(hours= timeDifference)
time = '%02d:%02d' % (dt.hour,dt.minute)

  # If state changed in the past days show the date too
    if dt.date() < datetime.datetime.now().date():
        time = '{} {}'.format('%02d/%02d' % (dt.day,dt.month),time)
worn laurel
#

I have a problem createing a bianary sensor i keep getting an error and i am not sure what it means

#

Invalid config for [sensor.template]: invalid slug Studs_Alarm_off (try studs_alarm_off) for dictionary value @ data['sensors']. Got {'wake_hour_1': {'friendly_name': 'Wake Hour 1', 'value_template': '{{ states("input_number.wakehour_1") | round(0) }}'}, 'wake_minutes_1': {'friendly_name': 'Wake Minutes 1', 'value_template': '{{ states("input_number.wakeminutes_1") | round(0) }}'}, 'wake_time_1': {'friendly_name': 'Wake Time 1', 'value_template': '{% if states("sensor.wake_hour_1")|length == 1 %}0{% endif %}{{ states("sensor.wake_hour_1") }}:{% if states("sensor.wake_minutes_1")|length == 1 %}0{% endif %}{{ states("sensor..... (See ?, line ?).
Invalid config for [input_boolean]: invalid slug Studs_Alarm_Off_Room (try studs_alarm_off_room) for dictionary value @ data['input_boolean']. Got {'wakestatus_1': {'name': 'Studs Room Alarm', 'icon': 'mdi:alarm'}, 'wakeweekday_sun_1': {'name': 'Sunday', 'icon': 'mdi:calendar'}, 'wakeweekday_mon_1': {'name': 'Monday', 'icon': 'mdi:calendar'}, 'wakeweekday_tue_1': {'name': 'Tuesday', 'icon': 'mdi:calendar'}, 'wakeweekday_wed_1': {'name': 'Wednesday', 'icon': 'mdi:calendar'}, 'wakeweekday_thu_1': {'name': 'Thursday', 'icon': 'mdi:calendar'}, 'wakeweekday_fri_1': {'name': 'Friday', 'icon': 'mdi:calendar'}, 'wakeweekday_sat_1': {'name': 'Sa.... (See /config/configuration.yaml, line 48).

plain magnetBOT
#

@worn laurel I converted your message into a file since it's above 15 lines :+1:

marble jackal
floral shuttle
#

! Thx. Any thoughts on the loop itself? (Consider these are attributes on a template sensor, and I also have one for != home …)

inner mesa
#

Just read the first line

worn laurel
#

i figured it out

#

how do you make a simple push button in the ui for starting automations?

inner mesa
worn laurel
#

i mean trigger

#

like i just want a boolean push button to trigger a automation

#

or a scipt

inner mesa
#

Still, manually triggering an automaton isn't recommended. It should be a script

#

Push buttons aren't boolean, either

worn laurel
#

like i just want a switch that does not latch how do i do that>

#

that is what i am confused about

#

a boolean non latching switch

inner mesa
floral shuttle
thorny cargo
#

How can I do seomthing with all lights that are currently turned on?

inner mesa
#

what part of "do something" are you looking for?

#

I mean, {{ states.light|selectattr('state', 'eq', 'on')|list }} gives you a list of lights that on..

thorny cargo
#

I want to change the color temps of those lights.

#
  - service: light.turn_on
    target:
      entity_id: "{{ states.light|selectattr('state', 'eq', 'on')|list }}"
    data:
      color_temp_kelvin: 5000
mode: single
#

nvm

#

the map is missing

#

Doesnt work. It´s removing the map function each time.

#
service: light.turn_on
target:
  entity_id: >-
    {{ states.light|selectattr('state', 'eq', 'on')| map(attribute='entity_id')|
    list }}
data:
  color_temp_kelvin: 5000
#

Why is it turning on all my lights now?

#

Ah there´s a group for all lights in that list.

#

That´s stupid.

#

How do I get rid of that?

thorny cargo
#

| rejectattr('attributes.entity_id', 'defined') seems to do the trick

thorny cargo
#

Can I use templates for entity in trigger?

inner mesa
#

No

thorny cargo
limpid stratus
#

I'm trying to do something that should be easy, but I can't seem to find the correct test. I have a blueprint where I select a set of zwave devices (using a "multiple: true" input). I then want to set a condition (or a trigger if possible) that checks to see if the device_id in the event_data of a zwave_js_notification is one of the device ids in the blueprint !input device list. Can some one help? Thanks.

sacred sparrow
#

anyone know how I can make this work: {{ as_timestamp(now()) - state_attr('automation.bedroom_tap_switch_1_wake','last_triggered') | timestamp_custom("%H:%M") }}

inner mesa
#

Seriously, what is wrong? What are you trying to achieve?

sacred sparrow
#

I want to show when the automation was last triggered in H:M 🙂

marble jackal
sacred sparrow
#

how long ago

errant hinge
#

Hi. Is this an error with my Helper template code or just a temporary glitch with the data from the inverter (MQTT) ? Have I put the default(0) in the wrong place?

Source: helpers/template_entity.py:379
First occurred: 08:42:50 (5 occurrences)
Last logged: 08:42:50

TemplateError('ValueError: Template error: int got invalid input 'unknown' when rendering template '{{ (( states('sensor.givtcp_ceX_invertor_power')|default(0) | int * -1 )) | round(0) }}' but no default was specified') while processing template 'Template<template=({{ (( states('sensor.givtcp_ceX_invertor_power')|default(0) | int * -1 )) | round(0) }}) renders=4>' for attribute '_attr_native_value' in entity 'sensor.givenergy_invertor_power_inverted'```
#
  sensors:
    givenergy_invertor_power_inverted:
      unique_id: 88744980-fc66-11ed-be56-0242ac12000
      value_template:
        "{{ (( states('sensor.givtcp_cX_invertor_power')|default(0)
        | int * -1 )) | round(0) }}"
      device_class: power
      unit_of_measurement: W
      friendly_name:
        "{% if states('sensor.givtcp_ceX_invertor_power')|default(0) | int > 0 %}
        Discharging{% elif states('sensor.givtcp_ce_invertor_power')|default(0) | int < 0 %}Charging{% else %}Neutral{% endif %}"
marble jackal
#

unknown or unavailable are perfectly valid states, so your default filter won't do anything here

#

Your int filter will fail on it though, so add the default there

#

value_template: "{{ (states('sensor.givtcp_cX_invertor_power') | int(0) * -1 ) | round(0) }}"

cinder plank
#

Hi, I'm struggling to filter for group entities. given a list of entity objects, how would I filter if an entity is a group?

#

the only difference in attributes I was able to see is that groups contain an array of the group members, but trying to filter by that didn't lead me anywhere.

obtuse zephyr
#

You could add selectattr('attributes.entity_id', 'defined'), but that will pick up things like scenes as well

cinder plank
#

ok scenes shouldn't be an issue because I'm filtering for light domain anyway

#

that works, thanks alot!

compact robin
#

What am I doing wrong here?
I wanna template this:

entity_id: fan.bedroom
attribute: percentage
above: 30
below: 35``` (this works in a test automation condition)

But for some reason, this doesn't work: ```{% if states('fan.bedroom') == 'on' and state_attr('fan.bedroom', 'percentage') == '33' %} mdi:fan```
inner mesa
#

That doesn't reflect the same logic

#

At least finish it

compact robin
#

I don't know how 😓

inner mesa
#

there's no 35 there at all

#

alright

compact robin
#

I know, but I managed to make the condition being between those values (fixed number is 33).

#

It's like those modes of a fan that have like 33, 66 and 100 as levels

inner mesa
#

then what are you trying to do?

#

you said that you wanted to turn that numeric_state condition into a template for some reason?

compact robin
#

I wanna make it so it shows which mode the fan is. so I wanna me that template only show (an icon) when is ON and in Mode 1 ( 33 ), Mode 2 (66) or Mode 3 (100).
Be it with exact values OR "betweens", same thing, but I can't seem to get it right with neither.

compact robin
#

On the "states" on the programmer part, it calls that "fan level" but on the automation conditions, it pulls the "percentage" lol. It's quite confusing.

inner mesa
#

is it possible for it to be "on" and not in one of those modes?

compact robin
#

(forgot to not ping u sorry)

compact robin
inner mesa
#

then what's the point of the complexity around the percentage?

compact robin
#

I don't have any point to make it complex or not, I was trying to figure out a WAY that it would work, since with exact numbers isn't working

inner mesa
#

did you have some other icons in mind for the other modes?

compact robin
compact robin
inner mesa
#

excellent, so try that 🙂

compact robin
#

I have the values, just need to get the template right

#

You can't help me I see, I'll ask in the forums or smt. Appreciate your time ❤️

fickle sand
#

should be something like:

{% if state_attr('fan.bedroom', 'percentage') | int == 33 %} 
  mdi:fan
{% elif state_attr('fan.bedroom', 'percentage') | int == 66 %}
  mdi:another-fan
{% elif state_attr('fan.bedroom', 'percentage') | int == 100 %}
  mdi:another-fan
{% else %}
  mdi:fan-off
{% endif %}
compact robin
#

@fickle sand You're amazing, this is exactly what I needed. Added the "on" in the condition, and those templates work wonderfully with the modes. It was the "int ==" part. Thanks!

marble jackal
#

You added quotes around the number, making it a string

#

Unlike entity states, attribute values can be a number

fickle sand
compact robin
#

Gosh I'm so happy this is exactly what I needed lol

#

Thank you!

true otter
#

hey guys, can anyone help me see where the issue is. Invalid config for [sensor.template]: invalid template (TemplateSyntaxError: Unexpected end of template. Jinja was looking for the following tags: 'endif'. The innermost block that needs to be closed is 'if'.) for dictionary value @ data['sensors']['front_door_status']['value_template']. Got "{% if is_state('binary_sensor.back_door_sensor_contact','off') and is_state('lock.back_door_lock','locked') %}Locked {%- elif is_state('binary_sensor.back_door_sensor_contact','off') and is_state('lock.back_door_lock','unlocked') %}Unlocked {%- elif is_state('binary_sensor.back_door_sensor_contact','on') and is_state('lock.back_door_lock','unlocked') %}Opened {%- elif is_state('binary_sensor.back_door_sensor_contact','on') and is_state('lock.back_door_lock','locked') %}Opened and Locked {%- .... (See ?, line

compact robin
#

@true otter I'm pretty sure it's the {% endif %}

#

Which has to be at the end.

#

{% if ...
{% elif ...
{% elif ...
{% endif %}

#

Use one of those tools to paste all code with a URL (Pinned messages)

plain magnetBOT
#

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.

real hound
#

Hi all, I need a little help. I'm using hass.agent & mqtt to poll network usage from a pc. Polling frequency is every 1 minute and the entity "pc_networkusage" is cumulative. What is the easiest way to subtract the current "pc_networkusage" from itself when it's updated every minute?

  • platform: attributes
    friendly_name: "pc_networkusage"
    attribute: datareceived_mb
    entities:
    • sensor.network_ethernet
floral shuttle
#

nvm: {{as_local(s.last_changed).strftime(stamp)}}

cursive fern
#

are there any tips/easier methods of writing templates like an ide which helps auto correcting what you write

magic peak
#

Is there a way to take a trigger ID and format it to be more human readable? Ala can I take the id sheets_changed and be able to make a notification that say Thanks! The sheets changed basically is there a way to change an underscore to a space?

inner mesa
#

Can't you just use that as the trigger ID?

#

I think it's just a string

magic peak
#

well I'm also using that to do stuff with input_booleans

#

so that's the entity ID

#

I want to trigger the input and send a notification

inner mesa
#

There's no automated thing that will change that ID into some arbitrary sentence

magic peak
#

I guess in my head the string would be Thanks! The {{template here}}

still plank
#

i am trting to create a template sensor for my electricity price

#

`template:

  • trigger:
    • platform: time_pattern
      hours: 0
      minutes: 30
      sensor:

    Keep track how many days have past since a date

    • name: "Octopus GO unit rate"
      state: '{{ 0.095 if (now() > today_at("00:30")) and (now() < today_at("04:30")) else 0.4165 }}'
      unit_of_measurement: "GBP/kWh"`
inner mesa
#

If you want to change _ to a space, {{ (trigger.id).replace('_', ' ') }}

still plank
#

but it's value is "unkown"

#

but the template works in the developer tools template section

inner mesa
marble jackal
true otter
cursive fern
#

how would i debug templates? automations you can see the traces

inner mesa
#

devtools -> Templates

still plank
# inner mesa Did it trigger?

ah probably not yet, that might be it. i've not used the trigger before but the unit price for electricity only ever changes on the half hour so it seemed more efficient

inner mesa
#

You can manually call homeassistant.update_entity

marble jackal
still plank
#

i've tried calling the update entity service on it but it's still unknown

#

and if i make a non-trigger regular template sensor it works, so i am confused.

marble jackal
#

Just wait for the trigger

#

Which will only be at XX:30 the way you configured it now

#

No sorry, only at 00:30

still plank
#

i removed the hour: line

#

that was a mistake, otherwise it won't trigger at 04:30

marble jackal
#
template:
  - trigger:
      - platform: time_pattern
        minutes: "/30"
#

This will trigger every 30 minutes

still plank
#

this problem is a problem though. assuming it does start working tomorrow at 00:30 , it's goign to break every time HA restarts

marble jackal
#

Also at XX:00

still plank
#

maybe i should just bin the trigger and have it as a regular template sensor.

marble jackal
#

Trigger based template sensors restore their state after a restart

still plank
#

ah ok. so if the restart happened at 00:29 - 00:31 i might get half an hour with the wrong value? but otherwise it'd be ok

marble jackal
#

Correct

still plank
#

ok, thank you

true otter
inner mesa
#

it's weird that homeassistant.update_entity doesn't work on that

cursive fern
#

is it possible to set "{{ (state_attr('weather.forecast_home', 'forecast') | first).condition }}" as a variable so it is easier to write?

inner mesa
#

{% set foo = whatever %}

cursive fern
#

thank you

#

why if i do this:

{% set variables = {
  "temperature": "{{ state_attr('weather.forecast_home', 'temperature') | float(default=0) }}",
  "alt_temperature": "{{ state_attr('weather.buienradar', 'temperature') | float(default=0) }}",
  "humidity": "{{ state_attr('weather.forecast_home', 'humidity') | float(default=0) }}",
  "forecast": "{{ (state_attr('weather.forecast_home', 'forecast') | first).condition }}",

  "hot_temperature": float(25),
  "cold_temperature": float(10),
  "cold_time_add": int(45),

  "time_delay": int(30)
} %}

{{ variables.temperature * variables.temperature }}
```i get this error ``TypeError: can't multiply sequence by non-int of type 'str'``?
inner mesa
#

You made strings out of your numbers

#

You're also nesting your templates

cursive fern
#

because i try to make a dict it becomes a string?

inner mesa
#

Get rid of all the {{ }}

#

And the suites that you surrounded them with

cursive fern
#

a, the " make it strings

#

what would you recommend a dict or setting each independently?

inner mesa
#

Doesn't matter

cursive fern
#

is there a way of updating a variable? like delay += 5
{% set vars.time_delay = vars.time_delay + 5 %}

inner mesa
#

There's lots of good documentation in the channel topic

cursive fern
#

is it not possible to add multiple elif statement after eachother?

#
{% if vars.forecast == "sunny" %}
  {% set vars.time_delay  = vars.time_delay  + 10 %}
{% elif vars.forecast == "partlycloudy" %}
  {% set vars.time_delay  = vars.time_delay  + 20 %}
{% elif vars.forecast == "cloudy" %}
  {% set vars.time_delay  = vars.time_delay  + 20 %}
{% elif vars.forecast == "rainy" %}
  {% set vars.time_delay  = vars.time_delay  + 20 %}
{% endif %}
```because i get this: ``TemplateRuntimeError: cannot assign attribute on non-namespace object``
inner mesa
#

You can't modify a dict

cursive fern
#

aha that explains it why it triggers at cloudy, thank you

inner mesa
#

There's no point in wrapping all those in a dict if that's what you're going to do

wind pulsar
#

i hope this is a silly question. but how to do i add a template? in the dev tools i can see that i can test one but there's no "create" option anywhere i can see. the docs page for templates fails to explain where to save them.

inner mesa
#

They can be used in lots of places

#

They don't just exist by themselves

wind pulsar
inner mesa
#

The first one goes in configuration.yaml, the second is a card in the dashboard

#

See the link I posted

cursive fern
#

could i use logarithm mathmetics function ?

wind pulsar
#

docs say yes, just look for log

cursive fern
#

awesome!

floral steeple
#

Hi, I have one trigger (rain) with one condition that contains 15 entities (for window is open), how do I create a notify message that contains the friendly name of the window in the open state? thanks

inner mesa
#

Put them all in a group and use the group in the condition

#

Then, something like {{ expand('group.windows')|selectattr('state', 'eq', 'on')|map(attribute='attributes.friendly_name')|join(', ') }}

floral steeple
#

Thanks!

#

😁

cursive fern
#

how would i use time_delay in a delay in an automation from my template? because i cant acces the variable

alias: Bewatering
description: ""
trigger: []
condition:
  - condition: template
    value_template: >
      {% set vars = {

        Deleted for codewall

      "{{time_delay}}"
action:
  - delay: >-
      {% set duration = time_delay %} {% if duration > 0 %}
        {% set duration = duration - 1 %}
      {% endif %} {% set seconds = duration % 60 %} {% set minutes = (duration /
      60)|int % 60 %} {% set hours = (duration / 3600)|int %} {{
      "%02i:%02i:%02i"|format(hours, minutes, seconds)}}
mode: single
plain magnetBOT
#

@tired sandal I converted your message into a file since it's above 15 lines :+1:

tired sandal
#

Right now I have this:

#
{{ value_json | selectattr('LOB', 'eq', 'Residential')
  | selectattr('serviceImpacted', '==', true)
  | selectattr('date' '==', today)
  | list
}}

Problem is - that takes the timestamp into account and so it fails to find Memorial Day because the timestamp in the dataset is midnight and it's currently 6:45pm

#
{% set today = now().date().isoformat() %}
{{ value_json | selectattr('LOB', 'eq', 'Residential')
  | selectattr('serviceImpacted', '==', true)
  | selectattr('date', 'gt', today)
  | list
  | first
}}

this gets me the right answer, but i was wondering if there was a better way than that by comparing the dates correctly.

pseudo ice
#

Hello, i need help. i am new to HA but trying to setup something for a client, he wants a new email to trigger a strip light, I have the google Imap working in HA i can see a new email count and the light strip is in but i cannot figure out how to trigger from a new email.

tired sandal
#

is the email count a sensor?

haughty breach
haughty breach
# tired sandal wait what...

There are 2 different types of variables at play. Jinja variables defined using set within a template and Script variables which are defined in YAML with or without Jinja.

tired sandal
plain magnetBOT
#

@tired sandal I converted your message into a file since it's above 15 lines :+1:

tired sandal
#

Starting with that one ^

#

@haughty breach nice username btw

keen hedge
#

Hi probably a stupid question, but can we have 2 different state than on off off a binary sensor ? Like 2 string like 'sun' and 'grid' ?

rose scroll
#

Nope. You'll need to use a sensor. Or if you just want to change the displayed text in the UI, you can handle that in certain cards.

keen hedge
#

Yes that's what I thought. Thanks !

merry marsh
#

What yould be the right synstax/way to return none as a Default in a filter? float(default=none), float(default=None), float(default="none"), float(default="None") or completely different?

marble jackal
#

The first two will result in none so really nothing, null.
The second two will result in the string you specified, so really "none" or "None"

merry marsh
#

Thanks. I need null for the numeric sensors and new hard error if it is not getting a number from e.g. a template. Thought about using this instead of checking against a number in an if. Will try it and hopefully it delivers then the "right" null then.

mighty ledge
#

Maybe not none, but None will

marble jackal
#

Like if you use it in the variables section?

mighty ledge
#

Yeah as well as any template

#

Templates still return strings, then the resolver tries to “type” the result

#

If it looks like a python object, it will resolve a python object

marble jackal
#

Yeah okay, but inside the template it does matter. Like eg

{% set test1 = 'bla' | float(none) %}
{% set test2 = 'bla' | float('none') %}
{{ iif(test1,'foo','bar') }} # result: bar
{{ iif(test2,'foo','bar') }} # result: foo
mighty ledge
#

correct

#

basically, if the contents of {{ }} return None or 'None' it will resolve to the None python object, which in turn will show as null in the template tester

floral shuttle
#

need to set a default in the 'leeftijd' but can not find the correct syntax, please have a look? {% set jaartal = this.attributes.leeftijd|int(default=-1) + 1 %} {{ '{} wordt {} over:'.format(this.attributes.persoon,jaartal) }}

#

is stil, throwing UndefinedError: 'homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'leeftijd' on reload, and startup

mighty ledge
#

you have to check if leeftijd is defined

#

or provide a default directly on leeftijd

#

not inside the int

floral shuttle
#

yes I was looking to do the latter

mighty ledge
#

i.e. | default

#

then | int

floral shuttle
#

{% set jaartal = this.attributes.leeftijd|default(-1)|int + 1 %} you mean?

#

dont I need to set a default for the |int then, (because it has already been set on the leeftijd itself?

mighty ledge
#

why are you casting it to an int in the first place

#

it's an attribute

#

it's going to be an int

#

just give it a default for when it's not defined

floral shuttle
#

ok will try now

mighty ledge
#

i.e. for when leeftijd does not exist as an attribute

floral shuttle
#

thx, its working now without startup warnings, had to add another default too: name: > {% set jaartal = this.attributes.leeftijd|default(-1) + 1 %} {{ '{} wordt {} over:'.format(this.attributes.persoon|default('Nog niet bekend'),jaartal) }}

#

on that |int casting, if I use {% if this.state|int(default=-1) != 0 %} in an attribute, and the state is a number, are you saying I dont need to |int there and only provide a default?

#

so {% if this.state|default(-1) != 0 %} in this case?

mighty ledge
#

you only need int when converting a string to another type

floral shuttle
#

right. thx. I have a lot of those missing default when reloading templates I see now, they dont appear on startup....

#

that is all fixable. However I have another challenge I coulkdnt find a documented solution for:

#

when using expand in```
state: >
{{expand('group.family')|selectattr('state','eq','home')|list|count}}

#

{{expand('states.person')|selectattr('state','eq','home')|list|count}} is the exact same set of entities, but I doint want to iterate all state

#

so now I repeat the state template several times in my attributes....

mighty ledge
#

I dont understand what you're asking

floral shuttle
#

bottomline questio. is: why cant we use this.state on a state template that us using expand(group), while we can use this.state when using expand(states.person)

mighty ledge
#

I still don't understand

#

you aren't using this.state anywhere in those templates

floral shuttle
#

no, its about another template....

mighty ledge
#

what does that have to do with this.state

#

this.state just gets the state, it doesn't run any templates

floral shuttle
#

I cant use the this.state and have to rewrite the expand('group.family') template several times

mighty ledge
#

this.state in your circumstance is an int

#

it's not a list, so it's not a 1 to 1 comp

floral shuttle
#

yes, and I would need that int in the commented picture and count home template

mighty ledge
#

this.state should work fine

#
{{ this.state | default(-1) | int(-1) }}
#

remember, this may not have state

#

technically, you don't even need to cast it as an int because the template resolver will do that.

#

so simply {{ this.state | default(-1) }}

floral shuttle
#

yes I was doing that now, and although it doesnt throw a warning or error, it still does not create the attribute.

#

changing to states.person in the state template immediately fixes this

mighty ledge
#

there's no guarantee that your attributes will execute after your state

#

I'm guessing you're running into a race condition

#

not much you can do about that

#

thats why I do not use this.xxx at all unless I need to fall back

#

i.e. I don't use it to reduce code, only to use the previous state.

floral shuttle
#

didnt consider the race possibility tbh. suppose you are right. I am right using the expand on group is more efficient than on states though am I? or doesnt it really matter because of the expand is expensive on its own

#

btw, what baffles me is that the final phrase template works without issues, using that this.state

mighty ledge
#

expand will be more efficient

floral shuttle
#
          phrase: >
            {% set last = as_local(states.zone.home.last_changed).strftime('%D %X') %}
            {% if states('zone.home')|int(default=-1) != 0 %}
            {% set count = this.state %}
              Thuis: {{count}} --  {{state_attr('sensor.familie_samenvatting','home')}}
            {% else %} Niemand thuis sinds {{last}}
            {% endif %}```
mighty ledge
#

there's no guarentee on resolution order for attributes. Not sure how else to explain it

#

Everything is async

#

you get it when it thinks it updates

floral shuttle
#

yeah, its really odd now. of edited the template and reload yaml, but it wont see the changes I made. have to restart now to get this to work. Anyways, thanks!

#

1 final troublemaker, And the default does not help jaren: > {% set event = this.attributes.datum|default('1995-20-02') %} {% from 'easy_time.jinja' import count_the_days %} {{(count_the_days(event)|int(default=-1)|abs/365)|int}}

#

results in TemplateError: UndefinedError: 'None' has no attribute 'month'

#

even though the attribute is in fact set like:```
datum: '1995-02-20'

mighty ledge
#

that's not a valid date

#

or event

#

it needs to be a fully fleshed out datetime object

#

well, it works with a partial datetime too

#

'1995-20-02' is not valid, that's year day month

#

1995-02-20 is year-month-day and that will work

floral shuttle
#

😊

marble jackal
#

So it will work the first 12 days of each month, but it will give an incorrect result 😛

mighty ledge
#

lol yeah

#

and the error will be cryptic because it's a python error

inner mesa
#

Year/day/month makes as much sense as US format month/day/year (not much)

mighty ledge
#

yep

#

I get why it was originally done, but it really doesn't need to be done that way anymore

inner mesa
#

dates and times should be represented in a way that you can do string comparisons 🙂 (because software engineers should rule the world)

#

yes, that means that 12-hour time should also go away

mighty ledge
#

I could take or leave 12 hour

#

but the date thing annoys the shit out of me because I have to deal with it for server communication

#

half our servers like EU datetimes, the other half, US datetimes. dumb dumb dumb

cursive fern
#
delay: >-

  {% set duration = time_delay %} {% if duration > 0 %}
    {% set duration = duration - 1 %}
  {% endif %} {% set seconds = duration % 60 %} {% set minutes = (duration /
  60)|int % 60 %} {% set hours = (duration / 3600)|int %} {{
  "%02i:%02i:%02i"|format(hours, minutes, seconds)}}
enabled: true

how could i add that it prints out time_delay everytime that it runs in an automation so i can figure out what time_delay is. or is this not possible?

copper wharf
#

Hi there.. this was working up till the 2023.5.x version and I can't seem to figure out if I missed a breaking change.. can anyone help

  • platform: file
    name: Sump_Pump_Run
    file_path: /config/sumppump/neocam.txt
    value_template: '{{ as_timestamp(as_local(as_datetime((value.split("|")[0])[0:26]+"-00:00")))| timestamp_custom("%d-%b %-I:%M %p") }}'
    unit_of_measurement: ""

I get an entity not available error at the moment in the front end...

inner mesa
#

if it's part of a script or automation, you can use persistent_notification.create or system_log.write

cursive fern
#

well i dont know really how this works or how i should explain it,
i got an automation with a delay based on a template, i removed most of the template because it is just math and so i dont have a codewall

inner mesa
#

well, I gave you some options

plain magnetBOT
#

@cursive fern I converted your message into a file since it's above 15 lines :+1:

floral shuttle
marble jackal
#

Yes, it was. If you use the YYYY-DD-MM format you will have a valid date in YYYY-MM-DD format for the first 12 days of each month

floral shuttle
#

ah, but I use YYYY-MM-DD throughout

#

above was a typo.. hence me blushing there

floral shuttle
#

for testing purposes, I also have leeftijd: > {% set event = this.attributes.datum|default('1995-02-20') %} {{((states('sensor.date') | as_timestamp - as_timestamp(event))/(86400*365))|int}} so I can see if it produces other results than the easy time macro

#

this is what I am using currently, as replacement for the python date counter. In the end the challenge seems to be the template considering the current date, and calculating the next event

#

and using those anchors to be able to do - unique_id: wijke_verjaardag <<: *state attributes: id: wijke datum: !secret vj_wijke type: Verjaardag <<: *shared

#

for all other events

still surge
#

hi mates, i'm using state_attr("calendar.differenziata", "message") to catch message for today event in calendar, but if i need to catch the tomorrow one, how can i do?

#

in this calendar each day has a single event per day

marble jackal
#

Not, a calendar entity only has the current or next event

hushed sinew
#

Hi, can someone explain to me why if I set nested attributes for a template sensor like this:

0: "{{ dict.from_keys([['label', 'Clear Sky'], ['day_icon', 'sunny'], ['night_icon', 'clear_night']]) }}"

it works, but like this:

0:
  label: ClearSky
  day_icon: sunny
  nigh_icon: clear_night

it doesn't?

still surge
#

on attributes table i can see just actual (today) event, how can i focus on tomorroe one?

marble jackal
#

Again, not, you won't see it until today's event is over

marble jackal
hushed sinew
#

but shouldn't a dict be equivalent to the yaml datastructure? that seems like a very arbitrary limitation

marble jackal
#

Your template is a bit overcomplicated though

0: "{{ { 'label': 'Clear Sky', 'day_icon': 'sunny', 'night_icon': 'clear_night'} }}"
hushed sinew
#

yeah, just realized that I can just define the dict directly in a template 🙂 . still not as legible as the yaml, but I guess it's the best I'll get... thanks

floral shuttle
#

on those this variable attributes and defaults, I've been able to use {{this.attributes.get('home')}} and that seems to take care of that, not defaults used, no warnings, and all templates work as desired.

#

but, it is peculair on certain types, because this can not be done on the date template using```
{% from 'easy_time.jinja' import count_the_days %}
{% set event = this.attributes.get('datum') %}
{% set month = (event|as_datetime).month %}
{% set day = (event|as_datetime).day %}

frozen plank
#

Hey guys, im new here on Discord but have been running HA for over a year now with some pretty neat automations in and around my house.

Is there anyone who could help me with a rain sensor? I want a sensor which just says its raining=true raining=false. At the moment I have a Bresser wetter station with a rain sensor which measures total fallen rain. At the moment its at 70mm. So I want to make an automation/sensor which just checks if this number increases and then stay in the state raining for at least an hour. I want to use this to control my robotmower.

I got no clue on how I could make this. Is there somebody here who could maybe help me out?

mighty ledge
#

I'm not sure why you don't just hardcode it

floral shuttle
#

because I have the full template config in an anchor...

#

it's very revealing for some template stuff... Ive also discovered these templates will not be correectly evaluated using them as trigger template with:```
template:

  • trigger:

    • platform: time_pattern
      hours: 0
      minutes: 0
    • platform: homeassistant
      event: start
    • platform: event
      event_type: event_template_reloaded

    sensor:

atomic blade
#

Is there some weird gotcha with return values when using custom templates? This template outputs "on":

{{ area_occupied('bedroom') }}

But this outputs "false":

{% set o = area_occupied('bedroom') %}
{{ o == 'on' }}

(I've excluded the import statement here)

#

Ok it's a bunch of newlines I think...

pearl bough
#

Can I call/import a template macro inside a template macro?

#

eg say i have misc.jinja

{% macro randomstrings() %}
{{ ['textone','texttwo','textthree','textfour','textfive','textsix'] | random }} 
{% endmacro %} 

and then in formatter.jinja

{% macro formatfordiscordorsomething() %}
{% from 'misc.jinja' import randomstrings %}
[... some code here to format for use]
{% endmacro %} 
inner mesa
#

did you try it?

#

seems like you wrote most of it 🙂

pearl bough
#

.... That's a very good point.

#

One way to find out then!

#

Oh hey nice it does work

#

Hm, a newline appears

inner mesa
#

add some -

pearl bough
#

aha

#

found wheree to stash the -

#

{% macro randomstrings() -%}

inner mesa
#

I usually add them everywhere and then start removing them 🙂

pearl bough
#

Now my notification message base is more portable so I can slam it into the different notif pushes across my devices \o/

#

so glad for these macros

rose scroll
frozen plank
#

I just need to make a sensor thats sends a true value if another sensor increases its value

#

And stay true for a couple of hours

#

That would help me a bunch

#

Gonna look those up which you have listed

marble jackal
floral shuttle
#

having this frontend markdown, but I'd love to make it into a template sensor. Can this be made so it auto-creates the attributes per domain? Id love to be able to reference these attributes for other purposes, and would hate to hard-code that...

#
          {% set x = ['unavailable','unknown'] %}
          {%- for d in states|groupby('domain') %}
          {% if loop.first %} ### Domains: *{{loop.length}}* - Entities: *{{states|count}}* {% endif %}
            **{{- d[0]}}:** *({{states[d[0]]
                                |rejectattr('state','in',x)
                                |list|count}})*
            {% for i in d[1] if i.state not in x -%}
            > {{i.name}}: *{{i.state}}*
            {% endfor %}
          {%- endfor -%}```
hollow shadow
#

Hello all. I have an issue where multiple sensors have started reporting 'Unknown'. Only changes seem to be with HA updates. Neverless, whilst I trawl through logs and work out root cause, i'd like to suppress the 'Unknown' value from all sensors and display previous value until next valid value. Any help appreciated

marble jackal
#

My first guess is that you added a unit_of_measurement to sensors which have a non numeric state

#

But without code all we can do is guess

#

It's impossible to show the previous value from when the sensor was still working

hollow shadow
#

i thought same re unit_of_measurement too 🙂 but alas it is not the onlyissue as it is across all sensors even if pulling from same JSON. Some will say Unknown, when the very next JSON attrib will be fine

frozen plank
#

Hmm, anyone can help with converting windspeed from weather station from m/s to km/h? The weatherstation reports it as a sensor in m/s

#

sensor:

  • platform: template
    sensors:
    wind_speed_kmh:
    friendly_name: "Wind Speed"
    unit_of_measurement: 'km/h'
    value_template: "{{ (state_attr('sensor.bresser51_wind_speed', 'wind_speed')|float * 3.6)| round(1)}}"
#

I am trying something like this

#

But home assistant reports unavailable

#

Got it

#

Chat gpt awesomeness

mighty ledge
#

the float is incorrect

#

it's wrong because chatgpt copies people who incorrectly add crap like that

cerulean cipher
#

"leave your AI at the door" eh

mighty ledge
#

blind leading the blind

cerulean cipher
#

lol

frozen plank
#

I am a total noob in programming and asked chatgpt

#

And that got me a right script

#

sensor:

  • platform: template
    sensors:
    wind_speed_kmh:
    friendly_name: "Wind Speed (km/h)"
    unit_of_measurement: "km/h"
    value_template: "{{ (states('sensor.windspeed') | float * 3.6) | round(1) }}"
cerulean cipher
#

suppose chatgpt gave you code that blew up your PC

#

you wouldn't know till it blew up?

mighty ledge
frozen plank
#

And how would that look and why?

cerulean cipher
#

like sensor.windspeed = 0 , so when the system restarts and hasn't gotten info from the sensor yet it has a value

#

but in whatever format you need it

#

mine was example for concept

mighty ledge
#

float(0)

cerulean cipher
#

what he said

#

even tho they are basically the same 😄

frozen plank
#

I just restarted HA and it just displayed the sensor with km/h

#

platform: template
sensors:
wind_speed_kmh:
friendly_name: "Wind Speed (km/h)"
unit_of_measurement: "km/h"
value_template: "{{ (states('sensor.windspeed') | float(0) * 3.6) | round(1) }}"

So like this then?

#

{{ (states('sensor.windspeed') | default(0) | float * 3.6) | round(1) }}

#

I added this now

mighty ledge
#

Sorry, this is correct

      value_template: "{{ (states('sensor.windspeed') | float(0) * 3.6) | round(1) }}"
```
#

was a way from pc

#

@frozen plank ^

frozen plank
#

Ah thanks

#

Got it to work thanks to you and gpt haha 🙂

mighty ledge
#

np

cerulean cipher
mighty ledge
#

it really just depends on what integration the sensor comes from

#

if it's a helper, it will always be available, if it comes from anything else, it'll be hit or miss

cerulean cipher
#

well I don't have anything cool that even uses them yet

#

but I'll be an expert by the time I do LOL

mighty ledge
#

Templates simplify everything

#

if you do it right, you can minimize your automations, scripts, and entities while having everything you need

cerulean cipher
#

oh I know this as a regex man

mighty ledge
#

scripts + variables are amazing

#

you can basically compartmentalize your setup.

cerulean cipher
#

well a script without a variable is useless

#

lol

mighty ledge
#

yep

cerulean cipher
#

I know kung fu

mighty ledge
#

also, tip

#

use script.turn_on to not wait for the script to complete

#

it fires and forgets

#

basically acts as a non-blocking function call

#

but you need to put your variables inside variables:

#

inside data

cerulean cipher
#

will add that to my swiss army knife

cursive fern
#

hey, i created a formula to get a delay value, my problem currently is that my setup doesnt work, now i have read that you can use datetime to trigger, but i do not understand how it works
How does it work for the first time when there is no new datetime, and how do i set it up? scripts templates and automations all seem kind of the same to me because you can everywhere add some logic as in jinja

mighty ledge
#

datetimes have a default date and time and they only trigger at that date and time

#

if the data/time is in the past, nothing will trigger

#

input datetimes are helpers, so you create them like any helper

#

scripts and automations are not the same. automations have triggers, scripts do not.

#

and yes, you can use jinja many places throughout automations and scripts

cursive fern
#

if i understand the logic correctly, by helper you mean a state machine in the automation with global variables?

mighty ledge
#

you can add any trigger you want

#

it doesn't need to be just a datetime trigger

#

so if you want the automation to trigger on restart to recalc the date then do that

cursive fern
#

found it, settings > devices > helpers

cursive fern
inner mesa
#

By comparing with now()

cursive fern
#

good point

cursive fern
#

thank you everyone for helping me making this work!

swift veldt
#

I get the following (begin of an) answer for a
curl 'http://192.168.0.103/ajax/post' -X 'POST' --data-binary 'key=150'
:

plain magnetBOT
#

@swift veldt I converted your message into a file since it's above 15 lines :+1:

swift veldt
#

can someone please help me to understand what’s wrong with this platform: rest switch configuration?
The last 0 in the answer is a 1, if the machine is on instead of standby

#
  - platform: rest
    name: coffee_machine_switch
    method: post
    resource: "http://192.168.0.103/ajax/post"
    body_on: "key=200&id=11&value=1"
    body_off: "key=200&id=12&value=1"
    is_on_template: "{{ value_json.status[12] == '1'}}"

Switching on/off works, but the status doesn’t

mighty ledge
#

value_json.status[12] == 1

#

Or

#

value_json.status[-1] == 1

#

@swift veldt

still plank
#

i am trying to do some stuff with template entities. and it's leading me to wonder what is the different between a sensor whose state is a number, and a number entity. is there much difference?

swift veldt
#

ah Ty . And where would I need to put the ‚key=150‘ payload that I’d probably need to post to get the answer? params ? state_resource ?

#

nvm, wrong channel for that

ivory harbor
#

trying to troubleshoot an action based on a template... the template works in the template editor and is fairly similar to the example in the docs:
service: input_datetime.set_datetime target: entity_id: input_datetime.sprinkler_rain_delay data: datetime: > {{ (now() + timedelta(minutes=90)).strftime('%Y-%m-%d %H:%M:%S') }}

dim roost
#

I'm completely stumped on what seems like it should be really easy - I'd like an automation to trigger at the earlier time of 23:00 and sensor.astronomical_dusk

marble jackal
ivory harbor
#

nevermind ... indentation error

marble jackal
#

And besides that, you can define actions when it changes. They have totally different use cases compared to sensors with a numeric state

lofty mason
dim roost
#

Huh. I guess I could just trigger on both without the condition, since the second one wouldn't do anything.

lofty mason
#

that works too

dim roost
#

(can't close a shutter that's already closed)

#

well, that was easy :) Thanks @lofty mason

ivory harbor
dim roost
ivory harbor
#

although be careful with the conditions section because otherwise it will fire twice

dim roost
#

It can fire twice, it doesn't matter

ivory harbor
#

cool

dim roost
#

I want it to close the shutters at min(23:00, astronomical dusk)

#

so if it triggers again while they're already shut, nothing will happen

hearty verge
#

I'm struggling to get a relative_time for the next sun rise/set:

{{ relative_time(as_datetime(state_attr('sun.sun','next_rising'))) }}

doesnt render correclty - is there a trick i'm missing?

#

If i do: {{ relative_time(as_datetime(as_timestamp(state_attr('sun.sun','next_rising')) - as_timestamp(now() ) )) }} i get 54 years 🙂

#

oh duH: Note that it only works for dates in the past.

inner mesa
hearty verge
#

I've used it before

#

And hate to have to embed the mecro inside a blueprint

#

but it looks like i have to do so again 😦

pseudo ice
slate tundra
#

hello, is it any way to count (add) how many times in current month an event occurs ? for example how many working days I have (every work day I have a calendar event named Work) I just want to add those and multiply by 8 so I know how many hours to bill at the end. thanks in advance

heavy crown
slate tundra
floral shuttle
#

this is odd... have this template: - unique_id: utc_offset name: Utc offset state: > {{now().utcoffset().total_seconds()/3600}} icon: > mdi:numeric-{{this.state|int|abs if this is defined and this.state|is_number else 'negative-1'}} which works perfectly, other than its a float in the frontend, resulting in state being 2.0. No big deal, but id love it to show 2. So, I use |int on the state template {{(now().utcoffset().total_seconds()/3600)|int}} which effectively makes that result in 2 (and being a number). However, this now makes the icon template fail and default to the negative-1....

rose scroll
floral shuttle
#

remarkable...

rose scroll
#

Hmm why do you need the if logic? The state will always be defined and parseable as a number right?

marble jackal
#

this.state will be the previous state in this logic

#

so it will not match your state

#

use states(this.entity_id) instead

#

it should fix itself after a minute though

#

but after a template reload, you will have a state change from unavailable to 1 or 2 and this.state will be unavailable then, so that will result in negative-1

heavy crown
# slate tundra that will not work, or at least I do not see a way, how is that gonna count all ...

It keeps a running total from whatever startdate you define. So if you start from 1st current month and measure a specific 'event' at a specific state then this will work imo. But this may be overkill if you only need to count the number of entries in a calendar, I am not sure what you mean with 'event'. Update, I never looked at the calendar this way and it seems to not keep historical entries so if this is the case then no option to count them, or? Still, you could use histstats where if an entry pops-up...it adds to the sensor and with a monthly reset, this should be OK

floral shuttle
#

states(this.entity_id) sounds like a sane solution indeed! believe I can use that in other places as well.... thx for that, never used it in the backend before

#

the this variable has to be guarded, adn this was wwhat I came up with at that time..... But, Ive found it to be another reason: it has to do with the trigger platform for these templates, and that simply is not reliable in updating upon template reload.

#

ive now set this unlimited:```
- unique_id: utc_offset
# name: Utc offset
state: >
{{(now().utcoffset().total_seconds()/3600)|int}}
icon: >
mdi:numeric-{{this.state|int|abs if this is defined and
this.state|is_number else 'negative-1'}}

#

silly thing is I only need it to check on day change, so had it under```

  • trigger:
    • platform: time_pattern
      hours: 0
      minutes: 0
    • platform: homeassistant
      event: start
    • platform: event
      event_type: event_template_reloaded```
marble jackal
#

I was not aware you were using a trigger

floral shuttle
#

so as you can see, that template reloaded event causes havoc on the this variable

marble jackal
#

but then you are always one state behind, because the this variable will be populated at the moment of the trigger, so before the state is changed

#

so this.state is the state on trigger, before the new state is rendered

floral shuttle
#

yes, I am aware that is the logic. Practice is not always aligned with that however.... as in this case. But, I will note that extra, and keep an eye out for it. It might be the fact this is only change every now and then, and not continuously.

#

to be sure, I made this now: icon: > mdi:numeric-{{states(this.entity_id)|int|abs if states(this.entity_id)|is_number else 'negative-1'}} figured I could take out the 'is defined' if |is_number is also in the condition

#

but, even that, does not work under the trigger. It's a real nasty aspect of trigger templates (or the this variable)

mighty ledge
#

why do you even have a utc_offset sensor?

#

it's useless

floral shuttle
#

before I get into that, I just settled for this icon template icon: > mdi:numeric-{{(now().utcoffset().total_seconds()/3600)|int}} don't remember why I had that |abs... and now I have this only updated once a day under the trigger. works perfectly.

mighty ledge
#

if your offset is negatvie, you'll end up with a numeric--number instead of numeric-number

#

someone from a - timezone must have written your template

floral shuttle
#

I had these, because This was the only way in python scripts to get to the bottom of those time shift issues. remember how we fought the fact python could not import libraries? we had to resort to:utc_offset = hass.states.get('sensor.utc_offset').state try: timeDifference = float(utc_offset) except ValueError as err: timeDifference = 0.0 so I had this notifying me:```
service: notify.system
data:
title: 'Ha Main: Utc time'
message: >
{{now().strftime('%X')}} Utc Offset changed to {{states('sensor.utc_offset')}}.
Check if time is set correctly in Python scripts, and day-time sensors.

floral shuttle
mighty ledge
#

🤷‍♂️

mighty ledge
#

as_datetime and as_local should handle it all

cursive ice
#

is there a way to template time so all time always uses a specific font, I tried via a card and could not get it working ?

floral shuttle
#

correct, because I ditched all of these python scripts following Frencks orders.

mighty ledge
#

and converting to UTC or to your local timezone can be done with tzinfo and astimezone

floral shuttle
#

I now use it as a mere visualizer of the timezone

mighty ledge
cursive ice
mighty ledge
#

there are no global 'font' settings

#

outside of using themes, which does "all font"

floral shuttle
#

I just like to have it somewhere under a fold and dont have to think...

#

I mean, I also know its the 1st of June today..

cursive ice
floral shuttle
#

also great to know, Next Noon is Tomorrow.... 🤯

#

let me change that format to datetime

floral shuttle
#

removing as much yaml as is possible I now enter the realm of my energy template sensors...... and all of a sudden notice that we also have a Unit dropdown now. I did use that on some conversion in other entities (temp/windspeed) and believed it only to be for that purpose. Now wonder: is this a real replacement for the unit_of_measurement: watt line in the Yaml?

#

or is it only there to facilitate conversion between units

frank beacon
#

Hopefully a simple question... I want to include the time in a template. The following works however if there is a trailing 0 it's always removed:
{{ now().hour }}:{{ now().minute }}

For example. "12:00" becomes "12:0" or "17:30" becomes "17:3". How can I fix this?

compact rune
#

{{ now().strftime("%H:%S") }} possibly

#

er, H and M, not S. But, same idea

pastel crescent
#

is there a command(/modifier/subroutine?) to convert datetime into local. I know I can as_timestamp | timestamp_local | as_datetime, but it would be great to be able to keep it in datetime

slate tundra
#

thanks

mighty ledge
#

all datetimes out of HA are TZ aware. So then all you need is | as_local

pastel crescent
#

My states('input_button.litterbox_cleaned') does not appear to be TZ aware.

mighty ledge
#

that's a string

pastel crescent
#

or I am pulling it wrong

mighty ledge
#

so you have to convert it to a datetime first

pastel crescent
#

ok

broken forum
#

Good evening everyone! I have a probably very stupid question, but I wanted to ask anyway because I didn't understand it. I would like to create an entity that can be set to 'true' and 'false' and thus block the lights from turning on in the middle of the night by motion. This entity should later be 'edited' with Alexa. How can I implement this?

real saffron
#

I think you want an input_boolean

#

you can create those in the helpers section <ha>/config/helpers

broken forum
#

Thank you. I will try

swift veldt
#
sensor:
  - platform: rest
    name: coffee_machine_state
    resource: "http://192.168.0.103/ajax/post"
    method: POST
    payload: 'key=150'
    value_template: "{{ value_json.status[12] }}"

still also only gives me state unavailable :/
(curl 'http://192.168.0.103/ajax/post' -X 'POST' --data-binary 'key=150'
gives me via terminal:

plain magnetBOT
#

@swift veldt I converted your message into a file since it's above 15 lines :+1:

swift veldt
#

how would i debug this? should every key automatically be an attribute if the integration worked and i only used {{ value_json }} ?

sly thistle
#

How can I change the template value of a sensor inside an automation?

#

Is this even possible?

inner mesa
#

please don't crosspost

sly thistle
#

@marble jackal can you take a look at my project sometime and make a suggestion on templates? We are creating thousands of UI elements because it was easier at the time. It works, but it slows down some people who have inadequate rigs. It’s kind of difficult to explain unless you see it running. Which means you’d have to install it. Take a look at our wiki

https://github.com/FutureTense/keymaster/wiki

You don’t actually need a lock or ZWave to run it. And you can use HACS to do most of the install.

clear mist
#

hey guys, if i've got 2 datetime objects is there a way to tell how many days between them? so like any time today would be classified as a 0 (no days) but any time yesterday would be 1 day and so on?

haughty breach
#

{{ (x - y).days }} will give full days.
{{ (x.date() - y.date()).days }} is probably more what you are looking for since it will count partial days

clear mist
#

perfect, thanks!

sweet oasis
#

Hi, how can be possible to make in automation condition with random value, please?

mighty ledge
#

you'll need to provide more information

#

e.g. what value do you want in with what type of condition

sweet oasis
#

ok, e.g. by IF condition=1 THEN RunMotor1For.random(5)minutes

mighty ledge
#

then the condition is not 'with a random value' the action is

sweet oasis
#

zes, wrongly desribed

mighty ledge
#

and for that, we'd need to know what action you're running

sweet oasis
#

sorry

#

e.g. for light (only ON or OFF action) and run it in ON state for 0-5 minutes (randomly).

mighty ledge
#

you run a turn on service, then you run a delay action

- delay:
    minutes: "{{ range(1, 6) | random }}"

then you run your turn off service.

range(1, 6) provides 5 numbers, 1,2,3,4,5

#

so if you wanted any time for 10 minutes range(1,11)

#

It seems like you're making fake occupancy stuff for HA and it seems like you're a beginner. I recommend using blueprints someone else made.

sweet oasis
#

yes beginner, thank you.

mighty ledge
#

you can find blueprints in the blueprint area of the forums, i'm sure there's 100s of fake occupancy blueprints

sweet oasis
#

understood. One more question (I saw it somewhere, but not found again) - e.g. for measure consumption of gas or water . I want show not only consumption (in m3, ...) but show it in price representation, but price is changing in time (new higher price for unit after defined date, e.g. two times per year). That means how to create table with dynamic cost per unit?

mighty ledge
#

setup utility meter and provide it with peak/offpeak sensors

sweet oasis
#

this is not mostly for electricity (different day and night prices of consumption)?

plain magnetBOT
#

@opal echo I converted your message into a file since it's above 15 lines :+1:

mighty ledge
#

That's what template sensors are

#

but you build the logic in the template sensor, not in an appdaemon script.

opal echo
#

And how would I be able to use python to edit the values of an entity?

mighty ledge
#

you can't

#

There's nothing in the logic you posted that requires python

#
sensor:
  - platform: template
    sensors:
      emu_analog_sensor:
        friendly_name: Emulated wattage Sensor
        unit_of_measurement: "W"
        value_template: >
          {% set wattages = {
                "input_boolean.oven": 2500,
                "input_boolean.verwarmingskachel": 1500,
                "input_boolean.grill": 1500,
                "input_boolean.wasmachine": 1300,
                "input_boolean.droogkast": 2200
            } %}
          {% set ns = namespace(on=[]) %}
          {% for k, v in wattages.items() if is_state(k, 'on') %}
            {% set ns.on = ns.on + [ v ] %}
          {% endfor %}
          {{ ns.on | sum }}
#

No python, does what you want.

#

@opal echo ^

opal echo
#

ok thanks I will test this

mighty ledge
#

@marble jackal you're too slow, i saw you typing 🤣

#

mobile again?

marble jackal
#

yep, yours was more efficient anyway

#

nope, you beat me fair and square this time 😛

mighty ledge
#

haha

#

I'm not sure how it could be made more efficient

#

well, actually

#
{{ wattages.items() | selectattr('0', 'is_state', 'on') | map(attribute='1') | sum }}
#

forget that I added is_state as a test

#

I think that should work

#

yep

#

so if you want it shorter...

#
sensor:
  - platform: template
    sensors:
      emu_analog_sensor:
        friendly_name: Emulated wattage Sensor
        unit_of_measurement: "W"
        value_template: >
          {% set wattages = {
                "input_boolean.oven": 2500,
                "input_boolean.verwarmingskachel": 1500,
                "input_boolean.grill": 1500,
                "input_boolean.wasmachine": 1300,
                "input_boolean.droogkast": 2200
            } %}
          {{ wattages.items() | selectattr('0', 'is_state', 'on') | map(attribute='1') | sum }}
opal echo
#

it works fine thank you!

mighty ledge
#

NP

sonic nimbus
#

how can I select only those entities which are opened more than 20%?
I have for example now this:

service: cover.close_cover
data:
  position: 20
target:
  entity_id:
    - cover.ds_d
    - cover.ds_l
    - cover.ds_s
    - cover.ss_d
    - cover.ss_l
    - cover.rs_d
    - cover.rs_l

But I dont want to lift some covers if some covers are below 20

floral steeple
#

if I wanted to use the new date entity (in beta) as automation trigger, i cant seem to use it. Is it a numeric state or state, or I presume its a template trigger?

#

like, I want the trigger to be a date April 1, 2024

#
platform: state
entity_id:
  - sensor.date
to: 2024-04-01

I guess it is this above

#

not numeric?

inner mesa
#

sensor.date isn't new

#

and it's a string, like every other state

#

date.xxx, time.xxx, and date_time.xxx are what are added in beta, to be provided by integrations. And #beta stuff should stay in #beta

floral steeple
#

Okay I miss understood thanks for clearing that up

#

By the way, did I correctly set up that trigger for april first 2024?

inner mesa
#

yes

willow wing
#

Hey, someone knows why this is unknow? {{ states('input_datetime.klimaautomatik_schlafzimmer_timer.last_changed') }}

#

i want that an automatisation runs only when these state was changed or updated in the last 23 hours

lofty mason
willow wing
#

thanks

marble jackal
#

Do note that that timestamp resets after a reboot, so effectively your automation now also only runs 23 hours after a reboot

swift veldt
rocky vector
#

How can I set this string from a sensor into an input_datetime please? “3 June 2023 at 18:00”. Just the 18:00 - I don’t need the date part.

inner mesa
#
service: input_datetime.set_datetime
data:
  entity_id: input_datetime.test2
  time: >-
    {% set data = '3 June 2023 at 18:00' %}
    {{ data[data.rindex(' '):] }}
rocky vector
#

Thanks - and I just replace the string in that with states(‘sensor.datetime’)?

inner mesa
#

Yes

rocky vector
#

Thanks!

undone jungle
#

Hi all, I thought this would be a good place for that question. I've created a group helper for 2 of my covers ( front gate and garage door) to open them easier from my Google Assistant when driving or similar.

#

At first I thought the issue is one with Google Assistant but it turns our that the problem persist from HA directly as well.

#

When I activate each entity separately they open, close and indicate state perfectly fine.

#

When I try to open the group helper it's always that my garage door opens but the gate doesn't

#

And since group helper accepts state of either being open as both being open the state of the group changes to open and closed but the main gate remains shut

#

Not sure if there is anything beyond that I could add but please feel free to follow up with questions.
I'd appreciate a ping/@ when responding

marble jackal
#

@undone jungle #integrations-archived is a better place for this question. But I expect the wanted states are reversed for both covers, basically one is closed when the other is open, and you both consider that open. (and vice versa)

undone jungle
#

Maybe I misunderstood what you meant but they are physically and programatically close while sending an open action to the group doesn't initiate the main gain (while it does the garage door) and at the same time sending the same to each separately works just fine.

marble jackal
undone jungle
#

Yes!

marble jackal
#

Did you actually check that? Because this response was very fast

undone jungle
#

I knew it from memory but checked at again just now. I can offer screenshots if you'd like 😉

#

A piece of additional information - both these covers originate from a switch entity via a Satel alarm system integration which are made into a cover via a cover template

radiant spindle
#

Hey, I'm trying to create a template sensor that will display the current power, but I'm not able to access it through the energy tab. Here's my template ```

  • name: current_power
    state: "{{ states('input_number.current_power') }}"
    state_class: 'measurement'
    unit_of_measurement : 'W'```
    I think I'm supposed to fill the field device_class as well but I'm not sure where to put it
mighty ledge
floral shuttle
#

came up in #beta: what is more efficient: have template sensors round raw states using round() inside that template, or have the frontend take care of those. remark was made that having the round() inside the template would prevent huge amounts of db state changes...

#

seeing eg many battery/temp/humidity sensors with more than 8 decimals change continuously, and recording those, I could indeed see a benefit there. otoh, it would require template power, so not sure which strategy would be leanest

floral shuttle
#

other challenge: i have this tenmplate based on a Hue light group: {% set hue_group = 'light.alarm' %} {% set names = state_attr(hue_group,'lights')|join('|') %} {{states.light|selectattr('name','match',names) |map(attribute='entity_id')|list}} to create an on the fly scene for those lights, before raising the alarm, and to get back to that when alarm is off.

#

I now need to add a single light to that list, not belonging to that hue_group. how do I add that entity_id?

#

should I do {% set hue_group = 'light.alarm' %} {% set names = state_attr(hue_group,'lights')|join('|') %} {{states.light|selectattr('name','match',names) |map(attribute='entity_id')|list + ['light.x']}}? feels so silly I figured to ask for confrmation...

marble jackal
#

That should work

undone jungle
#

@marble jackal any further ideas?

marble jackal
#

You could try a template cover

undone jungle
#

As it stands they look like this:


# Garage door cover
      garage_door:
        device_class: garage
        friendly_name: "Garage door"
        value_template: "{{ is_state('binary_sensor.garage_door', 'on') }}"
        open_cover:
          service: switch.turn_on
          entity_id: switch.garage_door
        close_cover:
          service: switch.turn_on
          entity_id: switch.garage_door
        stop_cover:
          service: switch.turn_on
          entity_id: switch.garage_door
        icon_template: >-
          {% if is_state('binary_sensor.garage_door', 'on') %}
            mdi:garage-open
          {% else %}
            mdi:garage
          {% endif %}

# Main gate cover
      main_gate:
        device_class: gate
        friendly_name: "Main gate"
        value_template: "{{ is_state('binary_sensor.main_gate', 'on') }}"
        open_cover:
          service: switch.turn_on
          entity_id: switch.main_gate
        close_cover:
          service: switch.turn_on
          entity_id: switch.main_gate
        stop_cover:
          service: switch.turn_on
          entity_id: switch.main_gate
        icon_template: >-
          {% if is_state('binary_sensor.main_gate', 'on') %}
            mdi:gate-open
          {% else %}
            mdi:gate
          {% endif %}
#

They've been integrated 3 years ago, so maybe it's an obsolete syntax issue?

#

No idea honestly - since one opens and the other doesn't the only difference I see is one is a garage (which opens) and the other is a gate which doesn't.

floral shuttle
#

nvm, I misread, sorry

marble jackal
undone jungle
#

I've been scratching my head wondering if this won't leave me with some strange flip-floping situation

#

But since there are momentary switches, it seems like it's no different

#

Switching, this entity technically should just send an open/close signal, since it's the same signal. Am a write?

#

The question now is then, for the sake of argument it work, why doesn't it work for a group?

marble jackal
#

Oh wait, the open command is the same as the close command

#

So it's basically a button, not a switch

#

What determines the state of that binary sensor?

undone jungle
silent flicker
#

can someone tell me if this is the proper use of "lower"? i want to make sure the email subject is converted to lower in the event the text is different

"{{ 'made a sale' in state_attr('sensor.imap_content', 'subject') | lower  or 'received an offer' in state_attr('sensor.imap_content', 'subject') | lower }}"
inner mesa
#

It's fine

silent flicker
marble jackal
# undone jungle Magnetic contact sensor
# cover group
      door_gate_group:
        friendly_name: "Door and Gate"
        value_template: "{{ is_state('binary_sensor.main_gate', 'on') or is_state('binary_sensor.garage_door', 'on') }}"
        open_cover:
          service: switch.turn_on
          target:
            entity_id: >
              {{ ['binary_sensor.main_gate', 'binary_sensor.garage_door'] | select('is_state', 'off') | map('replace', 'binary_sensor', 'switch') | list }}
        close_cover:
          service: switch.turn_on
          target:
            entity_id: >
              {{ ['binary_sensor.main_gate', 'binary_sensor.garage_door'] | select('is_state', 'on') | map('replace', 'binary_sensor', 'switch') | list }}
        stop_cover:
          service: switch.turn_on
          target:
            entity_id:
              - switch.main_gate
              - switch.garage_door
        icon_template: >-
          {% if is_state('binary_sensor.main_gate', 'on') or is_state('binary_sensor.garage_door', 'on') %}
            mdi:gate-open
          {% else %}
            mdi:gate
          {% endif %}
#

you can try something like this

undone jungle
#

Thank you so very much for your time and effort. I'll certainly give it a go!

lucid trail
#

starting of with :im not awesome with templates. But can i write something like this? {% if is_state('sensor.kaffekokare_active_power',
'W')|float < 60 > 5 %}

#

its the part after float i wondering about

#

if its beetween 60 and 5 is what im looking for

undone jungle
marble jackal
#

As the action to open or close is the same, you want to avoid turning the swithc on for both, if one is open, and the other not

#

as that will open the one which is closed, and close the one which is open.

undone jungle
#

so in other words, it will check which one is open and only activate the one that is not

marble jackal
#

that should have been switch instead of cover

#

I corrected it now

undone jungle
#

So just for my future use case, the ... | map('replace', 'binary_sensor', 'switch') | list }}) how does this section get processed

#

What is replaced?

#

I've tried looking up the map syntax but it's not self-explanatory enough for me

#

Invalid config for [cover.template]: not a valid value for dictionary value @ data['covers']['both_gate_group']['close_cover'][0]['entity_id']. Got None not a valid value for dictionary value @ data['covers']['both_gate_group']['open_cover'][0]['entity_id']. Got None. (See ?, line ?).

#

With the latest version, it seems to struggle with the entity_id definition

marble jackal
marble jackal
# undone jungle So just for my future use case, the `... | map('replace', 'binary_sensor', 'swit...

I start with a list of your binary sensors: ['binary_sensor.main_gate', 'binary_sensor.garage_door']
Then I check which of those are in the wanted state (either on or off): | select('is_state', 'off')
But that still gives me binary sensor entities, and I need switch entities for that service call, so I use map to use the replace filter on all items in the selector: | map('replace', 'binary_sensor', 'switch')

#

so map allows you to use another filter on the items in a list or selector

undone jungle
#

Understood!!

#

I learned a lot from this, but unfortunately the original issue remains unsolved. The new template cover opens the garage but not the main gate exactly like the cover group did.

#

The main gate doesn't move either when opening or closing the cover group and it remains in off state

#

Just to double-check, we are not getting tangled up in what is off and what is on - the gates closed means off, while gates open means on

floral shuttle
#

getting bk to my date counter.... can this be made shorter: {% set event = '1964-05-17' %} {% set month = (event|as_datetime).month %} {% set day = (event|as_datetime).day %} {% if month < now().month or month == now().month and day < now().day %} {% set yearnext = 1 %} {% else %} {% set yearnext = 0 %} {% endif %} {% set next_date = event.replace((event|as_datetime).year|string, (now().year + yearnext)|string) %} {% from 'easy_time.jinja' import count_the_days %} {{count_the_days(next_date)}}

#

especially the 'replace' line, but, maybe also the logic before that

mighty ledge
#

anyways, shorter:

#
          {% set event = '1964-06-04' | as_datetime | as_local %}
          {% set year = 1 if event.month < now().month or (event.month == now().month and event.day < now().day) else 0 %}
          {% from 'easy_time.jinja' import count_the_days %}
          {{count_the_days(event.replace(year=now().year + year)) }}
#

You can also approach this a different way

#

using just datetimes

#

still same number of lines

mighty ledge
#

You can verify this by making your value_template an and instead of or. You'll see how long it takes for both to 'turn on'.

#

if it takes a long ass time, then that will cause issues for your turn on/turn off stuff

#

especially if the switches are momentary switches

#

getting this in sync will be painful and probably won't make sense. It'll also require patience from the person using the cover in the UI

#

Personally, I'd make template switches or template covers for each one separately

#

then possibly a cover group from the resulting entities.

floral shuttle
#

thx, same would goe for the opposite: {% set event = '1964-08-27'|as_datetime|as_local %} {% set year = 0 if event.month < now().month or (event.month == now().month and event.day < now().day) else -1 %} {% from 'easy_time.jinja' import count_the_days %} {{count_the_days(event.replace(year=now().year + year))|int|abs }} count days since the last time

mighty ledge
#

sure

undone jungle
#

In short, I have two working entities and each works just fine from templates for each cover.

#

The binary sensors respond within 1-2 seconds and they work just fine.

floral shuttle
#

and for an 'age' attribute: leeftijd: > {% set event = '1995-02-20'|as_datetime|as_local %} {{((now()|as_timestamp - event|as_timestamp)/(86400*365))|int}}

#

would be ok?

undone jungle
#

I've also created groups, which was the simple way to achieve it, but this doesn't work, hence the long way around and it also doesn't work in the same way

mighty ledge
mighty ledge
#

(now() - event).days // 365

undone jungle
mighty ledge
undone jungle
#

But a group made out of them doesn't.

undone jungle