#templates-archived

1 messages · Page 32 of 1

mighty ledge
#

@compact panther your code is looping through all the prices associated with 7625 sawmill road. So there's more than 1 price. You have to decide which price you want for that address.

amber sleet
#

Not sure but something like the following might work.
{{ (state_attr('sensor.gar_stations_search', 'stations) | selectattr('address.line1','eq', '7625 Sawmill Rd') | list | first) | selectattr('price.credit', 'eq', 'price')}}

crimson lichen
#

how to use template: is_state('entity_id','comparative condition')
For example: is_state('entity_id', '!= off' )
I can use states('entity_id') != 'off' but I would like to learn more

#

how to compare with is_state

lofty mason
#

That's not what is_state is for. states is the correct function for this use case.

#

I don't believe it supports what you're asking for.

rose scroll
maiden magnet
#

Hi, i am trying to make a template Sensor which calculates my CO2 emission. Calculated with my power consumtion and 15.7g/kwh
This is my code but its not correct:

        - name: "CO2"
           unit_of_measurement: "g"
           state: >
            {{ states('sensor.plug_energy') * 15.7 | float(0) }}```
marble jackal
#

@maiden magnet you are converting 15.7 to a floating point number, which it already is

#

you need to convert the entity state to a floating point number, as all states are strings

maiden magnet
#

so do i have to do it like this?

    name: "CO2"
    unit_of_measurement: "g"
    value_template: '{{ states("sensor.plug_energy" | float )) * 15.7}}'```
this is also incorrect
grand quarry
maiden magnet
grand quarry
#

The same way as you had it but just with valid syntax

maiden magnet
#

but this is not correct :(

    platform: template
    name: CO2
    unit_of_measurement: 'g'
    value_template: "{{ states('sensor.plug_energy') | float * 15.7 }}"


crimson lichen
#

you can try template in Developer Tools

grand quarry
crimson lichen
#

{{ states('sensor.broadlink_khai_temperature') | float * 15.7 }} is good

marble jackal
#

what Impact posted is the new format, which should be placed directly in configuration.yaml

#

if you are using sensor.yaml you should use the old/legacy format

plain magnetBOT
crimson lichen
#

How to send images in Local with :
service: notify.hass_synchat
data:
message: teset
title: dsadsadsa
data:
file_url: /config/www/cam_captures/cam_bep_9.3.2023_15.46.png

that code don't run with file_url.
I change with https://hdjsahdjsdsadsadsdsa.png and run ok

marble jackal
#

that's not related to this channel

cyan elm
#

- sensor: - name: remaining_power unit_of_measurement: 'W' state: "{{ ( states('sensor.inverter_active_power') | float | round(1)) - ( states('sensor.smartdin_power_2') | float | round(2) - ( states('input_number.house_usage') | float | round(2)}}"

#

Returning this error Invalid config for [template]: invalid template (TemplateSyntaxError: unexpected '}', expected ')') for dictionary value @ data['sensor'][0]['state']. Got "{{ ( states('sensor.inverter_active_power') | float | round(1)) - ( states('sensor.smartdin_power_2') | float | round(2) - ( states('input_number.house_usage') | float | round(2)}}". (See /config/configuration.yaml, line 48).

#

Can someone give me a hand? even yamlchecker is showing this should be fine

#

I'm trying to make a sensor that does my solar panel production - ev charger usage - house usage

marble jackal
#

you using ( twice which you don't close

#

and most of these are not needed anyway

cyan elm
#

wheres this

marble jackal
#

you will also see errors from this sensor every time you reboot HA, as you are not using defaults for your float filters, or an availability template

#

I assume you can find those yourself, just check for every ( if there is a closing ) as well

wraith basalt
#

Hello. So i have a template sensore that should reflect the status of my dryer.
It's working perfectly fine so far, the only problem is, that it also gets set to on, after i restart home assistant and therefore triggers all the automations.
Could someone point me in the right direction on how i could solve this problem?

- sensor:
  - name: "Dryer Status"
    unique_id: "dryer_status"
    state:  >
        {% if (states('sensor.smart_socket_16a_5_power') | float > 1) or
              (states('sensor.smart_socket_16a_5_power') | float < 1 and
              now() < states.sensor.smart_socket_16a_5_power.last_updated + timedelta(minutes=5))   
        %}
          {{ "on" }}
        {% else %}
          {{ "off" }}
        {% endif %}
marble jackal
#

why are you creating a sensor, and not a binary_sensor (which uses the states on and off by default)

wraith basalt
#

I was thinking of creating a third status called "running" or something similar, but i didn't get that to work yet

marble jackal
#

anyway, last_updated get's reset when you reboot HA, so that's why it will be always on after a reboot

wraith basalt
#

Yeah, it makes sense to me why it happens, but i'll need a workaround now

#

Is there a sensor that reflects how long home assistant has been running for?
Maybe i could check if the last status change was after the restart, so that would turn the sensor to off by default

crimson lichen
#

you can use the automation check state after restarted and set state to off

marble jackal
#

how will you use an automation to set the state of a sensor?

marble jackal
#
- trigger:
    - platform: numeric_state
      entity_id: sensor.smart_socket_16a_5_power
      above: 1
      id: "on"
    - platform: numeric_state
      entity_id: sensor.smart_socket_16a_5_power
      below: 1
      for:
        minutes: 5
      id: "off"
  sensor:
    - name: "Dryer Status"
      unique_id: "dryer_status"
      state:  "{{ trigger.id }}"
      icon: "{{ 'mdi:tumble-dryer' if this.state == 'on' else 'mdi:tumble-dryer-off' }}"
wraith basalt
#

Ohh, that makes way more sense.
I haven't worked with trigger based template sensors yet, but based of of this it looks really simple.

I also change the icon with a condition currently

    icon: >
        {% if is_state("sensor.dryer_status", "On") %}
            mdi:tumble-dryer
        {% else %}
            mdi:tumble-dryer-off
        {% endif %}

Should i just leave like this or is there also a cleaner way to integrate that?

marble jackal
#

uhm, you were using the states on and off in your template, but you are checking for the stateOn

#

so the if statement will never be true

crimson lichen
#

"On" or "on"

marble jackal
#

anyway, you can use this.state

wraith basalt
#

Oh yeah, i changed it earlier and forgot about the icon state

marble jackal
#

I added icon template in the code above

wraith basalt
#

That looks so much cleaner, thank you very much

crimson lichen
#

{{ 'Yes' if is_state('light.kitchen', 'on') else 'No' }}

#

{{ 'mdi:tumble-dryer' if is_state('sensor.dryer_status', 'on') else 'mdi:tumble-dryer-off' }}

marble jackal
#

you mean like I already added here? <#templates-archived message> (but then using this.state so it will also work after an entity_id change)

#

Great if you want to help others though, so don't let me stop you!

#

try to format your code as code though 🙂

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.

crimson lichen
marble jackal
#

single backtick for one line code snippets

marble jackal
crimson lichen
marble jackal
#

it need template: above the current code block if you want to place it directly in configuration.yaml

#

unless you already have template: somewhere

crimson lichen
#

thanks

feral spade
#

is there a template to get the last time something was in a specific state?
I have {{ states.vacuum.roomba.last_changed < today_at('00:00') }} right now, but the state changes when I empty the bin (because it insists on "finding dock"), so I'd like to have the last time since it was in state "cleaning"

marble jackal
#

create a trigger based template sensor or an automation which stores it in a input_datetime

#

also note that last_changed will reset when you reboot HA

plain magnetBOT
#

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

feral spade
#

oh, it doesn't use the database used for recorder/history? Good to know
Though for this usecase it's fine. I'll look into the trigger based template sensor, thx

tidal pulsar
#

I defined:

`template:

  • sensor:
    • unique_id: sensor.sun_height_percent
      name: "Sonne aktuelle Höhe"
      state_class: measurement
      unit_of_measurement: "%"
      state: >-
      {{ (float(states.sun.sun.attributes.elevation) / float(69.82)) * 100}}
      `
      and expecte do see it as {{ states('sensor.sun_height_percent')}} in Developer - Template - or can use it on a lovelace as sensor.sun_height_percent, but it says 'unknown'

what did I wrong? how can I trace whats going on with this definition?

marble jackal
#

@compact robin add quotes around it

#

name: "CLIMATE: Termostat"

compact robin
#

Let me try that

marble jackal
tidal pulsar
compact robin
#

It did work, appreciated TheFees!

weak cradle
#

Back to utility_meter. I am able to get it working when using the Helper. I can see the history of a sensor. However if I add a similar part in configuration.yaml:

  util_hourly_gas:
    source: sensor.gas_consumption
    name: Hourly Gas
    cycle: hourly

It will not work. What goes wrong?

marble jackal
#

where did you put this?

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.

weak cradle
#

In /config/configuration.yaml

marble jackal
#

do you already have other utility meters in there?

weak cradle
#

No, i see another component in group.yaml

meter_readings:
  name: Meter readings
  entities:
    - sensor.energy_consumption_tarif_1
    - sensor.energy_consumption_tarif_2
    - sensor.energy_production_tarif_1
    - sensor.energy_production_tarif_2
    - sensor.gas_consumption

Is this the cause?

silent vector
#

Is there a way to do a select attr and ignore case? | selectattr('foo','equalto',bar)

mighty ledge
#

you ever figure out the dynamic dictionaries?

silent vector
#

Wait to who?

#

Lol

mighty ledge
#

you

silent vector
#

I figured I was thinking what? I don't see anyone talking about that. And I ended up going a different route. Honestly 50% of the time I ask Jinja questions now it's for work (Ansible).

mighty ledge
#

lol

silent vector
#

Now I'm wondering about a way to ignorecase with selectattr

#

But seriously thanks to you and thefes assisting me with home assistant is literally how I got this job

mighty ledge
#

ignoring case w/ selectattr isn't really possible

#

without mapping

silent vector
#

How would it be done?

mighty ledge
#

map(attribute='foo') | map('lower') | select('==', 'bar')

#

but then you lose the base object

silent vector
#

But what if it's lower/upper

#

A mix of the two

mighty ledge
#

mapping lower will lower it

silent vector
#

Ohhh

mighty ledge
#

you can't really manipulate data on the left side of your generators

#

without changing the object

silent vector
#

Oh interesting. I will test.

mighty ledge
#

What do you do now for work?

silent vector
#

I do infrastructure automation. Building vms, hp ilo physical servers.

mighty ledge
#

with ansible??

#

seems like an odd combo

silent vector
#

Yep infrastructure as code with Ansible.

#

They use Jenkins as well. But I only work with Ansible.

silent vector
mighty ledge
#

Otherwise, namespace

silent vector
#

Any examples for using a namespace?

mighty ledge
#

Namespace just allows you to keep memory with for loops and if statements

silent vector
#

Any idea how I would formulate this?

glossy sleet
#

Can someone explain to me how to create an upcoming event sensor for let's say birthdays
Just like this one

Upcoming_day: 15-03-2023
Upcoming_waste_types: papier
Hidden: false
friendly_name: Rd4 eerst volgende
hexed laurel
#

Would anyone be able to help me out with a MQTT Fan Template issue? I have it about 90% working, just can't get the state topic figured out.

slim sage
#

I'm trying to write a template that says whether or not Adaptive Lighting manual control is on for an Adaptive Lighting lighting group. test: {{ state_attr('switch.adaptive_lighting_adaptive_lighting_study', 'manual_control') }} shows test: [] when manual_control is empty/undefined/null (shows no value when I look at the attribute). The same template shows test: ['light.study'] when manual_control is enabled (it shows the entity that assumed manual control by changing more than 10%). I have tried an if statement for both state_attr('switch.adaptive_lighting_adaptive_lighting_study', 'manual_control') == '' and state_attr('switch.adaptive_lighting_adaptive_lighting_study', 'manual_control') == '''light.study''' and states.switch.adaptive_lighting_adaptive_lighting_study.manual_control is defined but they all yield as false. How do I check if it that attribute has content or not? If it has content, I want it to say "On", and if it does not (or is undefined?) then I want it to say "Off".

#

TL;DR: How do I tell if an attribute has content?

slim sage
#
{% if states('switch.adaptive_lighting_adaptive_lighting_study', 'manual_control') is not none %} hello {% else %} bye {% endif %}

V0: >{{ state_attr('switch.adaptive_lighting_adaptive_lighting_study', 'manual_control') }}<
V1: {{ state_attr('switch.adaptive_lighting_adaptive_lighting_study', 'manual_control') }}
V2: {{ states('switch.adaptive_lighting_adaptive_lighting_study', 'manual_control') }}
V3: {{ is_state('switch.adaptive_lighting_adaptive_lighting_study', 'manual_control') }}
V4: {{ is_state_attr('switch.adaptive_lighting_adaptive_lighting_study', 'manual_control', '') }}
V5: {{ is_state_attr('switch.adaptive_lighting_adaptive_lighting_study', 'manual_control', '[]') }}
V6: {{ is_state_attr('switch.adaptive_lighting_adaptive_lighting_study', 'manual_control', '''[light.study]''') }}
V7: {{ is_state_attr('switch.adaptive_lighting_adaptive_lighting_study', 'manual_control', '''[''light.study'']''') }}
V7: {{ is_state_attr('switch.adaptive_lighting_adaptive_lighting_study', 'manual_control', 'light.study' ) }}```

All of these yield the same value, except for V0 and V1, which show as  `V0: >[]<   V1: []`  when manual control is off, and as  `V0: >['light.study']<   V1: ['light.study']` when it is on.
#

{{ light in state_attr('switch.adaptive_lighting_adaptive_lighting_study', 'manual_control') }} shows False when manual_control is off/empty(?), but gives an error when manual_control is on as activated by light.strudy: UndefinedError: 'light' is undefined. This is the closest I've gotten so far.

#
{% if state_attr('switch.adaptive_lighting_adaptive_lighting_study', 'manual_control') == None %} false {% else %} false {% endif %}``` 
Both of those show 'false' no matter what.
#

my god its been like an HOUR of my life trying to deal with just figuring whether or not an attribute is empty or not. wtf am i doing wrong.

inner mesa
#

{{ []|length == 0 }} == True

slim sage
#

i'm hearing you say to check the length of the attribute's return to see if it is zero?

inner mesa
#

sure

#

you're saying that it returns an empty list

slim sage
#

{% if states('switch.adaptive_lighting_adaptive_lighting_study', 'manual_control')|length == 0 %}true{% else %}false{% endif %} returns 'false' regardless of the manual_control state

inner mesa
#

you're using "states()"

#

which is wrong

slim sage
#

ahhh, you're right!

#

{% if state_attr('switch.adaptive_lighting_adaptive_lighting_study', 'manual_control')|length == 0 %}true{% else %}false{% endif %} works!

inner mesa
#

you just need {{ state_attr('switch.adaptive_lighting_adaptive_lighting_study', 'manual_control')|length == 0 }} BTW

#

that's it

slim sage
#

omg this has been an hour and a half of my life, lol, THANK YOU, you have brought me so much relief here, thank you so much

#

I didn't realize it was returning a list. Lesson learned.

wet thicket
#
  - sensor:
      - name: rlinkLocationTracker
        state: sensor.rlinkLocationLat
        attributes:
          latitude: sensor.rlinkLocationLat
          longitude: sensor.rlinkLocationLong```

how can I use these sensors directly in a template?
inner mesa
#

if you format them as proper templates, yes

#

"{{ states('sensor.rlinkLocationLat') }}" for example

wet thicket
#

thanks will give it a shot

lofty mason
#

I wonder if it needs to be cast to floats, since the state will be a string.

wet thicket
#

yeah that may be possible because technically they are floats

lofty mason
#

it might work as is, just give it a try I guess

wet thicket
#

yeee it works

#

Appreciate the help homies

#

Now my motorcycle location tracker works, yay

lofty mason
#

You might also consider making a proper device tracker out of it.

#

Then it will do things like change its state based on zone.

wet thicket
#

ah thanks yeah ill probably do that

clear mist
#

hey guys, is there a way to have a template do stuff based on logged in user? for example, on my phone's dash, i want to see my phone's battery, but on my wife's phone, i want to display her battery on the dash?

clear mist
#

ah, not sure if this is the best way but i got it - i can use {{ user }} in templates, and i can set up some input text fields with the name of the possible users and the name of the phone in HA

brittle shore
#

Hello,

Im trying to template a service call to run a script. Im running a for each loop, during which, the script call is based on the loop iteration.

for_each:
- outdoor_led_1
- outdoor_led_2
- outdoor_led_3
sequence:
- variables:
iteration: repeat.index
- service: script.turn_on
entity_id: "{{ (script.number_generator_ ~ repeat.index) }}" #script.number_generator_3

#

ive tried various syntax changes inside the single line template without success. id appreciate ne help

sacred ridge
#

Is there a template for iOS media player widget android seems to have one not iOS

inner mesa
urban shard
#

I have a question. I have a tuya led strip with RGBW lights (rgb leds and white leds). I connected the data pin to a esp8266 to use with WLED. Both entites (wled and tuya led strip) are in home assistant. How can I combile these into one light entity and make sure white lights turn off if i use RGB and the other way around.

green scaffold
inner crest
#

i looked at template sensor docs and i dont understand it much (feel like 2 examples isn't enough)

template:
  - binary_sensor:
      - name: "Server Online Status"

i want to update my sensor using the api calls, what should I set as value? how would I call the sensor to update it externally? (curl is fine)

inner mesa
#

Seems like you really want an input_boolean

inner crest
inner mesa
#

Ok

inner crest
#

can i have some link so i can read?

plain magnetBOT
inner crest
#

so i dont need template sensor? oh lemme look into

inner crest
# inner mesa Ok

nice, is there a way i can automatically turn it off automatically after no updates?

green scaffold
cyan musk
#

Is there a way using templates to take something like this and extract the value of one thing (eg extract temperature):

{
  "datetime": "2023-03-12T00:00:00+11:00",
  "condition": "rainy",
  "templow": null,
  "precipitation_probability": 70,
  "temperature": 27,
  "precipitation": 7
}

Edit: I am silly and that was surprisingly easy to do a .[name of line]

sacred ridge
mighty ledge
cyan musk
mighty ledge
#

Lol aight, I just wanted to make sure you knew there was 2 ways to get items out of a dict in jinja

cyan musk
#

Ah yeah thanks! I probably could've guessed the [] way, but knowing me would've stuffed that up somehow 😄

sonic sand
#

hi
I got a sensor for the last time I fed the fish and I want to make an automation that will notify me whenever time has passed the 2 days and 3 hours (51 hours) of the last feeding time.
I assume I need a template condition/trigger to make it work, that's why I'm posting it here.
Thanks for helping!
Template:
http://pastie.org/p/1MYEOTtlyFPDOYbRN2G2Hg
The attribute of the sensor:
https://imgur.com/G0CujPx

maiden magnet
#

is there a possibility to make 2 separate template sensors from one variable? to remove part of the attribute: {{state_attr("sensor.iphone_geocoded_location", "Location")}})

obtuse zephyr
sacred ridge
obtuse zephyr
sonic sand
obtuse zephyr
#

That above template would be in addition

#

So that you track the time you want to be notified

#

Your current one tracks when they were last fed and the above one tracks when you want to be notified

sonic sand
#

So I just put it on the automation as condition?

obtuse zephyr
#

No

sonic sand
#

so I don't need any condition just to add that template as trigger and set on action the notification to my phone I assume?

obtuse zephyr
#

Right, the trigger will only trigger at exactly 2 days and 3 hours after that current sensor

#

No condition is needed unless you need to filter it any further

#

If you keep pushing out that feeding date, you'll never be notified as you'll have fed them on time

sonic sand
#

Sweet!

#

Thank you man

sonic sand
obtuse zephyr
#

You need to create a new sensor w/ that template

#

Very similar to the one you already have

obtuse zephyr
#

looks good

sonic sand
#

so now on the automation how do I use this sensor to make sure it will trigger when that sensor is detecting that past time over 51 hours

obtuse zephyr
#
  trigger:
    - platform: time
      at: sensor.feed_is_missing_timestamp
earnest cosmos
#

I wish I could do this, not having to define every light in a group 🙂

- service: light.turn_off
  target: light.*
#

Maybe there is an other way?

buoyant pine
#
- service: light.turn_off
  entity_id: all
#

Or with entity_id: all nested under target:

earnest cosmos
buoyant pine
#

Wouldn't make a difference. In general, if the domain of the entity matches the domain of the service (or if you use all), you can just do what I showed above

#

No clue if that will be removed at some point. The method with target seems to be the official way these days

maiden magnet
obtuse zephyr
maiden magnet
obtuse zephyr
#

What do you mean

fierce imp
#

as there a way to convert dates like this 2023-03-11T16:26:36 and 2023-03-11T05:36:08.316Z to just YYYY-MM-DD? or even just take the first 10 characters from the string?

fierce imp
#

These dates may not be now, they are coming in json from webhooks

obtuse zephyr
fierce imp
#

Local

obtuse zephyr
#

{{ your_date_str | as_timestamp | timestamp_custom('%Y-%m-%d') }}

fierce imp
#

perfect thank you again!

onyx juniper
#

How can I get a user_id to the friendly_name of said user with a template?

inner mesa
#

Last pinned message

marble jackal
civic bear
#

Can someone help me format the output of this code as a whole percentage? Right now I get “0.2345664355” and after searching, I have no idea how to accomplish this.

{% set original = states("sensor.ecu_current_power") | float %} {% set minimum = 0 %} {% set maximum = 5800 %} {% set adjusted = min(maximum, max(minimum, original)) %} {{ (adjusted - minimum) / (maximum - minimum) }}

inner mesa
#

do you mean just multiplying by 100 and rounding?

civic bear
#

Yes, exactly. It’s for a Watch complication that truncates at four decimals so I need to express it as a percentage instead.

inner mesa
#

easy, then

#

{{ (((adjusted - minimum) / (maximum - minimum))*100)|int }}

civic bear
inner mesa
#

|round

#

there are good docs link the channel topic

civic bear
#

Thanks again. Sorry the noob question and appreciate the help. I’ll check out the docs.

sleek fable
#

Dear members, running in circles, can't see it anymore 😦
I believe the BP is a beginners level, still can't get it to work.
error " failed to generate automation from blueprint: Missing input weightdiff, weightsensor.
I know this is a BP, but was advised to try it here. Its the calculation in the Action which is the problem and probbaly around the ~ ~ Any hint very much appreciated !

https://codeshare.io/6pk6r0

marble jackal
#

Are you trying to create this blueprint, or do you want to use it?

#
{{ states(weightsensor) | float(0) - states(weightdiff) | float(0) < states(okoksensor) | float(0) < states(weightsensor) | float(0) +  states(weightdiff) | float(0) }}
#

Guess this is what you are trying to do

#

You were turning everything into strings with the single quotes

little forge
#

hey peoples, another templating question. trying to set a time, but the types don't add up. any hint?

data:
  time: "{{ (states('input_datetime.wake_up_time') - timedelta( minutes = 15 )).strftime(\"%H:%M\") }}"
target:
  entity_id: input_datetime.wake_up_time_offset```
marble jackal
#

States are strings

#

You can't subtract a timedelta from a string

little forge
#

that makes total sense

marble jackal
#

You need to use as_datetime to convert the string to a datetime

#

And if you use single quotes inside your template, you don't need to escape them

little forge
#

still left with Error rendering data template: TypeError: unsupported operand type(s) for +: 'NoneType' and 'datetime.timedelta'

marble jackal
#

What do you have now?

little forge
#
data:
  time: "{{ (states('input_datetime.wake_up_time')| as_datetime - timedelta( minutes = 15 )).strftime('%H:%M') }}"
target:
  entity_id: input_datetime.wake_up_time_offset```
marble jackal
#

Is your input_datetime.wake_up_time time only?

little forge
#

darn. yes. should be too because it's daily

marble jackal
#
service: input_datetime.set_datetime
data:
  time: "{{ (today_at(states('input_datetime.wake_up_time')) - timedelta( minutes = 15 )).strftime('%H:%M') }}"
target:
  entity_id: input_datetime.wake_up_time_offset```
little forge
#

if i can use the wake_up_time with an offset was a trigger that would also work

#

lemme try your suggestion

#

perfect, thanks

#

now let's learn why this works 😛

marble jackal
#

Well, you need a datetime object if you want to subtract a timedelta

#

today_at converts a time only string to a datetime object

young lake
#

I'm trying to set the value of a template binary_sensor to the last known value during startup. I'm reading the Considerations::Startup section of the Template page and struggling to understand it. I think the answer to what I'm trying to do is there, but I'm not following what the page is saying. Could someone explain setting the initial value when the value is "unknown"? Or how to set the startup value to the last known value?

marble jackal
#

@young lake What is the current code of your template binary sensor?

edgy umbra
#

Anyone know how i can adjust this template so it can show day and days? So now it show minutes, hours and 1 day(s), 2 day(s) etc but i wan't to show minutes, hours, 1 day, 2 days, etc... https://paste.ubuntu.com/p/t4CSQX8Cwq/

marble jackal
edgy umbra
#

Yep i know 🙂

marble jackal
#

But that would not have affected the online status of your Pi, as you are only rebooting core

edgy umbra
#

Yeah i know but i think there is no other way around?

marble jackal
#

you actually have an uptime sensor so it seems

#

just use that?

#

what does that sensor return as value

#

sensor.raspberry_uptime

edgy umbra
#

12 maart 2023 om 20:05

#

So it also resets wen Core is retarted.

#

I don't think it's possible to bypass this?

marble jackal
#

How did you configure that sensor

#

This is what I have, the first seems to be what you want, the second is when core was last rebooted

#

And you don't need templates to show it like this on your dashboard, HA does that automatically when you add a sensor with the right device class and a time in the past

edgy umbra
#

It's the default uptime integration.

marble jackal
#

the default uptime integration indeed shows the uptime of HA (Core), not the uptime of your Pi

edgy umbra
#

How can i show the Pi uptime? 🙂

plain magnetBOT
marble jackal
#

specifically: type: last_boot

#

and if you then just add the sensor to your dashboard in an entities card, it will show it like above (in Dutch if your user language is set to Dutch)

#

I just rebooted because of an HACS update

edgy umbra
#

Ok i had that last_boot sensor but it seems i removed that.

#

Because i want to show the uptime in a little chip card i use that template so it's smaller in text size...

#

I just want to figure out how i can show/seperate day and days

marble jackal
#

BTW why are your doing an integer division (using //) then convert that to a float, then round that, then convert it to an int? all these steps are redundant, because you already had an integer to start with

#

sorry, that's not right

#

but you only need to add | int

#

anyway, you can do this:

          {% set sensor = 'sensor.last_boot' %}
          {% set last_boot = as_datetime(states(sensor)) %}
          {% set seconds = (now() - last_boot).total_seconds() %}
          {% set days = seconds / ( 60 * 60 * 24 ) %} 
          {% set hours = seconds / 3600 %}
          {% if days >= 1 %}
            {{ days | int }} dag{{'en' if days | int > 1 }}
          {% elif hours  >= 1 %}
            {{ hours | int }}u
          {% else %}
            {{ (seconds // 60) | int }}min
          {% endif %}
grave solstice
#

Probably asking in wrong channel...again however cant really place my question anywere so i go here anyway... 🙂

I have a Switch which by using the Helpers i have changed to Lock entity.... Lock.unlock turns switch on and Lock.lock turns switch off... However Lock.open i would want to associate with something maybe a button entity or so is there a way i can use all three Lock commands

edgy umbra
marble jackal
#

it will expose the largest of those

edgy umbra
#

Ok perfect, thanks!

marble jackal
#

Largest in time that is

silent vector
#

Merged for next release!

mighty ledge
#

Nice

marble jackal
#

We will also get loop controls

#

hope the is_hidden_entity will also make it

mighty ledge
marble jackal
mighty ledge
#

ah, that's a breaking change

#

I'll have to look through my variables

marble jackal
#

does it break things?

mighty ledge
#

I'm waiting on a review to get today_at and relative time added to the minutely updates

#

it breaks things if you use the variables 'continue' or 'break'

#

which are pretty common words

marble jackal
#

aaah, okay

#

sure

mighty ledge
marble jackal
#

I was thinking why that would be needed, but something like today_at('10:00') would stick to today until the next boot of HA or a template reload

mighty ledge
#

it would never update

#

ever

#

same with relative_time

marble jackal
#

not if you reboot HA?

mighty ledge
#

well yes, if you reboot or reload

#

or use the update_entity function

#

but a template on it's own would not

marble jackal
#

yes, that's what I meant

mighty ledge
#

technically it's a breaking change because you can't use it in limited templates anymore

marble jackal
#

I would expect in most cases you will compare it with now()

mighty ledge
#

right

#

however, many people use it to just output the relative_time

marble jackal
#

yeah, for relative time it's different, but there I would expect you will use it on an actual entity

mighty ledge
#

but it wouldn't update if it was on the entity

#

it would always be zero in that case

marble jackal
#

I actually don't really know the difference between a limited template, and a normal template. The docs mention for most that they are not limited templates, but I'm not sure what defines a limited template

mighty ledge
#

limited templates don't have access to the state machine

#

the hass object doesn't exist

#

so anything that talks to hass, won't work

#

but back to today_at, if you wanted to use the time difference between 10 am and your next calendar event, it would never update

#

unless you added now()

marble jackal
#

yeah sure

#

until the calendar updates, but then it's probably too late

mighty ledge
#

right

#

so, I just added it to the "now()" updates

#

same with relative_time

#

quick and dirty without changing logic

#

only breaks limited_templates

#

I probably should have omitted that change

#

so then it would get looked at by core

marble jackal
#

trying to think of a use case for those 2 in a limited template

mighty ledge
#

there isn't any

#

but someone might have done it

marble jackal
#

there's always that someone

sleek fable
urban shard
#

I have a question. I have a tuya led strip with RGBW lights (rgb leds and white leds). I connected the data pin to a esp8266 to use with WLED. Both entites (wled and tuya led strip) are in home assistant. How can I combile these into one light entity and make sure white lights turn off if i use RGB and the other way around.

urban shard
#

Thank you! I will do some research in that! Thanks for the help! ❤️ @marble jackal

plain magnetBOT
#

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

hexed laurel
mighty ledge
#

The state is determined by the value_template field

hexed laurel
#

I got everything else working, but this is the death of me.

mighty ledge
#

state_value_template: "{{ value == 'ON' }}"

#

unless the topic actually contains the phrase POWER = ON

#

in that case it would be

#

state_value_template: "{{ value == 'POWER = ON' }}"

hexed laurel
#

Tried both, but nothing.

#

MQTT Explorer shows it as just ON/OFF value so
state_value_template: "{{ value == 'ON' }}" should be it

mighty ledge
#

you can try

#

state_value_template: "{{ 'ON' in value }}"

hexed laurel
mighty ledge
#

your topic needs to be updated then

#

it's waiting for a value

hexed laurel
#

I have tele/Main_RF_Blaster/STATE as a topic too

#

It lists "POWER": "ON",

plain magnetBOT
#

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

mighty ledge
#

You can use whatever you want as your state topic, tele/Main_RF_Blaster/STATE is the state topic, use that instead

#
state_value_template: "{{ value_json.POWER == 'ON' }}"
hexed laurel
mighty ledge
#

🤷‍♂️ it should work just fine

hexed laurel
mighty ledge
#

is your payload on and off really 1 and 0?

hexed laurel
mighty ledge
#

ok then

hexed laurel
#

I'm running a D1 Mini to 433mhz transmitter via Tasmota.

mighty ledge
#
state_value_template: "{{ '1' if value_json.POWER == 'ON' else '0' }}"
hexed laurel
#

So this works, and now I am noticing a problem via MQTT Explorer.

#

The state isn't updating...

mighty ledge
#

how can it work but not update...

#

it's one or the other, so which is it?

hexed laurel
mighty ledge
#

Personally, I'd use this setup instead

mqtt:
  fan:
    - name: "Bedroom Fan"
      command_topic: "tele/Main_RF_Blaster/STATE"
      command_template: "{{ 1 if value == 'ON' else 0 }}"
      state_topic: "stat/Main_RF_Blaster/POWER"
      state_value_template: "{{ value_json.POWER }}"
      payload_on: "ON"
      payload_off: "OFF"
      preset_mode_command_topic: "cmnd/Main_RF_Blaster/RFSend"
      preset_modes:
        -  "Speed 1"
        -  "Speed 2"
        -  "Speed 3"
        -  "Speed 4"
        -  "Speed 5"
        -  "Speed 6"
      preset_mode_command_template: >
          {% if value == 'Speed 1' %}
            {"Data":"0x80930417","Bits":32,"Protocol":1,"Pulse":386}
          {% elif value == 'Speed 2' %}
            {"Data":"0x80930A19","Bits":32,"Protocol":1,"Pulse":386}
          {% elif value == 'Speed 3' %}
            {"Data":"0x8093081B","Bits":32,"Protocol":1,"Pulse":386}
          {% elif value == 'Speed 4' %}
            {"Data":"0x80930C1F","Bits":32,"Protocol":1,"Pulse":386}
          {% elif value == 'Speed 5' %}
            {"Data":"0x80930615","Bits":32,"Protocol":1,"Pulse":386}
          {% elif value == 'Speed 6' %}
            {"Data":"0x80930516","Bits":32,"Protocol":1,"Pulse":386}
          {% else %}
            {"Data":"0x80930112","Bits":32,"Protocol":1,"Pulse":386}
          {% endif %}
#

I'd probably clean up the preset mode template too but it's not a big deal

hexed laurel
#

That works perfectly for the status. Power command via HA now doesn't work.

#

Changed command topic to "cmnd/Main_RF_Blaster/POWER" seems to work now.

mighty ledge
#

yeah, sorry, ment to put that in state_topic

hexed laurel
marble jackal
mighty ledge
#

ya

hexed laurel
marble jackal
hexed laurel
hexed laurel
#

Thanks again @mighty ledge and @marble jackal I appreciate your time.

sonic nimbus
#

Hello Why this random template does not work in my case:

#
          - service: media_player.play_media
            data:
              entity_id: media_player.heos
              media_content_type: "favorite"
              media_content_id: "{{ range(1, 6) | random }}"
mighty ledge
#

The template's fine

#

It's most likely the service call

#

Yep, it doesn't allow numbers

#

@sonic nimbus ^

sonic nimbus
#

Hmm..should I put under the string then?

#

And how? Pipeline to string | string ?

mighty ledge
#

that won't fix it

#

is the id actually a number ranging from 1 to 5?

#

if it is, you have to template the whole data section

#
          - service: media_player.play_media
            data: >
              {{ {'entity_id': 'media_player.heos', 'media_content_type': 'favorite', 'media_content_id': range(1,6) | random | string} }}
sonic nimbus
#

I see, but I want to include 1 and 6, so I have 1,2,3,4,5,6 favorites

mighty ledge
#

then you want range(1,7)

#

anyways, you still have to template the whole data section

sonic nimbus
#

Ok, tnx, I will try

silent vector
#

Is there a way to do startswith that's case insensitive?

marble jackal
#

{{ ('BaNaNa' | lower).startswith('ban') }}

silent vector
# marble jackal `{{ ('BaNaNa' | lower).startswith('ban') }}`

Thank you. And if i wanted to check for starts with BaNanna- do x else if starts with BaNanna as in there's no - do x. The challenge is starts with would match both because it's truly there. But I care if it has the - and doesn't have - after BaNanna

marble jackal
#
{% set value= 'BaNaNa-Orange' %}
{% if (value | lower).startswith('banana-') %}
  Do something
{% elif (value | lower).startswith('banana') %}
  Do something else 
{% else %}
  Do nothing
{% endif %}
silent vector
#

I figured out my issue I had that but I didn't have the case right.lol

maiden magnet
#

hey, how does an event look when a button is pressed, so I can read it by event, which user triggered the event?

silent vector
#

How would I do a search of a list for a matching a piece of a string. You can use'testfoo' is search('testfooey') and it will return true because testfoo matched. How would I do that with a list? You can't do is search on a list and in list is an exact match I couldn't do 'testfoo' in ['testfoobar','bar'] There would be more than the exact match and it would be cleaner to avoid listing every exact match.

floral shuttle
#

still using this nex_alarm timestamp sensor, to build all of my other scripts/tts etc etc on. based on 4 input_datetimes, for weekday hour/minutes, and weekend hout/minutes....

#

was wondering if I could replace that with the new calendar feature, and maybe do away with all of those templates? Would it be better/simpler/easier?

#

to give you an idea, this is the Frontend for it

#

and some complex translations finally result in a completely Dutch sentence..... 😉

maiden magnet
#

hey, how does an event look when a button is pressed, so I can read it by event, which user triggered the event?

inner mesa
marble jackal
silent vector
#

Awesome didn't know that

marble jackal
#

But if you just want true or false I would use what Rob suggested

sonic nimbus
#

anyways you still have to template the

cyan musk
#

So I'm trying to use the android template widget, have something saying someone's location (person.person in this situation does exist)

{{states('person.person')}}

How can I make it conditional so it will read out as normal except if it says not_home to change to Not Home (I gather some sort of conditional but am not 100% how to do it)

grand quarry
#

I feel like this can be written more concise but maybe something like this?

{{ 'Not Home' if states('person.person') == 'not_home' else states('person.person') }}
shell cape
#

Can someone advise on my syntax here? I'm trying to output row['helper_id'] in an object i'm looping through but it's returning an error that indicates it's not reaching this object.

    - if:
      - condition: trigger
        id: {{row['helper_id']}}
    then:
      - service: input_select.select_option
        data_template:
          entity_id: {{row['helper_id']}}
          option: >
            {% set options = state_attr(row['helper_id'],
            'options') %}{% set current_index =
            options.index(states(row['helper_id'])) %}{% set
            next_index = (current_index + 1) % options|length %}{{
            options[next_index] }}

Error: UndefinedError: 'None' has no attribute 'index'

cyan musk
inner mesa
buoyant pine
#

Or

{{ states('person.person').replace('_',' ').title() }}
``` if it doesn't only need to be Not Home that's treated that way
urban shard
#

I have a question. I have a tuya led strip with RGBW lights (rgb leds and white leds). I connected the data pin to a esp8266 to use with WLED. Both entites (wled and tuya led strip) are in home assistant. How can I combile these into one light entity and make sure white lights turn off if i use RGB and the other way around. I cannot seem to get it working

hexed galleon
#

What's the most pythonic/Jinjaest way to check if any forecast condition within the next 3 days (weather.home.forecast[0-3].condition) is a certain value?

hexed galleon
#

Pretty sure this should do the job for telling me the # of days that are supposed to rain right? {{ state_attr('weather.home','forecast') | selectattr('precipitation','>',0) | list | count }}

#

Even better, found you can slice lists as you'd expect! {{ state_attr('weather.home','forecast')[0:3] | selectattr('precipitation','>',0) | list | count }}

plain magnetBOT
#

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

marble jackal
#

seems you already succeeded 😉

#

@crimson lichen why do you need this, to display it on a dashboard?

crimson lichen
marble jackal
#
{%- for a in states.sensor.lunar_exlab.attributes.items() %}
{{ a[0] }}: {{ a[1] }}
{%- endfor %}
silent vector
#

Looking back at this, it's not as good as 'foosanta' is search('foo') because it would still work as long as it matches the characters whereas the regex_search can't have any more than the string itself.

Is there another way?

{{ ['foo', 'bar', 'barfoo']|regex_search('foo') }}
mighty ledge
#

You have to use namespace if you want to 'lower' anything or regex. When you have a list like that, you have to use a generator too. Like | select('search', 'foo')

#

keep in mind that search doesn't exist in your environment

#

that's an HA only jinja test

#

but you're using ansible, so you have regex as a test

#

so you should be using that for pretty much every one of your "how do I select something and lower the case"

#

as regex has a built in kewarg called ignore case

silent vector
#

Yeah regex is a test there and if only I could use a list with is search and yeah I learned about the ignorecase=true here.

mighty ledge
#

| select('search',...)

#

also
| select('regex', ...)

silent vector
#

Got it {{ test | select('search','foo') | list | count > 0 }}

silent vector
#

Is there a way to do a regex replace if there are more than 1 - between characters in a string so foo--bar becomes foo-bar foo--bar---foosanta becomes foo-bar-foosanta?

marble jackal
#
{% set value = 'foo-----bar--banana---------orange' %}
{{ value.split('-') | reject('eq', '') | join('-') }}
silent vector
#

Seems like anything is possible with Jinja

lunar osprey
#

Hello

#

I want to template "inline_keyboard" item

#

in notify service

#

it's usually a list

#

e.g.

#
            - ":bulb: Controllo luci:/cont, :bulb: Stato luci:/sta"
            - ":window: Controllo tapparelle:/tap"
#

how can I make an if then else of this list?

#
                        - ":bulb: Disattiva Motion Detect:/mof"
                    {%- else -%}
                        - ":bulb: Attiva Motion Detect:/mon"
                    {%- endif -%}
#

like the above example...

marble jackal
#
                    {%- if is_state('binary_sensor.motion_detect_status', 'on') -%}
                        inline_keyboard[0]
                    {%- else -%}
                        inline_keyboard[1]
                    {%- endif -%}
#

something like that?

lunar osprey
#

I need more lines and more if...

#

what is inline_keyboard[0] ?

marble jackal
#

the first item of the list named inline_keyboard

#

as counting starts with 0

lunar osprey
#

Could you please explain me better your example?

#

How can I assign "💡 Disattiva Motion Detect:/mof" or "💡 Attiva Motion Detect:/mon" with if to inline_keyboard[0] ?

#

then to inline_keyboard[1] I need to assign another string

#

based on another different if

#

@marble jackal please help me 🙂

marble jackal
#

where does inline_keyboard come from?

lunar osprey
#
    data_template:
      title: '👮 *Centrale'
      message: Controlla la centrale
      data:
          inline_keyboard:
            - "🔴 Zone A B C:/alè, ⚪ Zone A B:/all"
            - "🟢 Disattivo allarme:/all, 🚨 Spengo sirena:/sir"
            - "🚨 Accendo sirena:/sir, 🟡 Panico:/pan"
#

This is an example

#

so I send to telegram

#

6 buttons

#

2 per row

#

I want those buttons to be parametric

#

with templates

#

the problem is that

#

inline_keyboard is a list

#

in this case it has 3 items

mighty ledge
#

You have to use namespace

lunar osprey
#

No need

#

I found a way

#

{%- if states('binary_sensor.motion_detect_status') == "on" -%}
{%- set x = "💡 Disattiva Motion Detect:/motiondetectoff"-%}
{%- else -%}
{%- set x = "💡 Attiva Motion Detect:/motiondetecton" -%}
{%- endif -%}
{{ [x, x] | list }}

mighty ledge
#
{% set ns = namespace(output=[]) %}
{%- if states('binary_sensor.motion_detect_status') == "on" -%}
  {% set ns.output = ns.output + [":bulb: Disattiva Motion Detect:/mof"] %}
{% else %}
  {% set ns.output = ns.output + [":bulb: Attiva Motion Detect:/mon"] %}
{% endif %}
{{ ns.output }}
lunar osprey
#

no need, my example above works

mighty ledge
#

it's not dynamic though

#

but if it works for you, 👍

marble jackal
#

also note that data_template has been depreciated for like 3 years now

shell cape
#

Is there a limitation to where I can use Jinja in an automation template? It's not letting me save often times and when I switch to YAML it often discards all my work. I'm trying to generate a list of triggers and actions but I'm getting the feeling the validation is missing required elements in plain YAML?

lofty mason
#

If you're using templates you should be in yaml editor, the UI editor does not support templates except in very limited spots.

#

Otherwise I'd have to see exactly what you're typing and where to explain what is happening to you.

shell cape
#

Yeah, often times it wont show me the save button though. So I switch to see if it does anything. But you're right. I'm doing that

#

Let me clean up my example. Thanks

plain magnetBOT
#

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

shell cape
#

It's good to note it passes the template developer tool

lofty mason
#

yeah I don't think you can do this. an automation is in YAML. All this {%%} stuff is not yaml, it won't understand it. You can use templates in places that support templates, but even there they have to be quoted as strings, so that the yaml does not try to parse it

shell cape
#

Automations do support templates right? But maybe not a structural level?

lofty mason
#

Certain fields may support templates, but as far as the YAML is concerned you're just passing a string to the field, to be later parsed as a template. You have to look at the documentation for a particular trigger, condition, or action to see which fields it has and which ones support templates.

shell cape
#

Ah will check which fields allow that, thanks. Any suggestions to a different approach where i can set things up like this without repeating myself a lot?

lofty mason
#
trigger:
{% for row in data %} - device_id: {{row['device_id']}}

e.g. this you cannot do either

marble jackal
#

you can't template the yaml structure

#

of an automation

lofty mason
#

If I wanted to trigger off when one of multiple remotes was pressed, I would not use devices, but maybe create a group of remote entities, or look for event trigger with some subfields of the event matching some of the properties of my remotes.

mighty ledge
#

you can't template the yaml structure of anything

#

you can only template in specific templateable fields

marble jackal
#

well, the data sections of a service call would be an exception

mighty ledge
#

you're templating JSON tho

shell cape
#

Yeah, i was about to say, I'm trying to workaround my lack of understanding of options to centralize this in a different way. I looked into groups but could not find one that allowed me to group the switches

mighty ledge
#

you still can't template yaml structure

lofty mason
#

I would go to #automations-archived and formalize what you're trying to do as a question, you can get some ideas there.

mighty ledge
#

e.g. yaml

xyz:
- 1
- 2
- 3

vs JSON

{"xyz": [1,2,3]}
shell cape
#

The way I specify objects inside Jinja2 is fine, it works. But i just cant output it in a loop like this on a structural level.

silent vector
# mighty ledge `| select('search',...)`

When I do

{% set list = ['foodaddddd','bar'] %}
{% set test = 'barfoo' %}
{{ list | select('search',test) | list | count > 0 }}

It is false. Since it's not an exact match. Is there a way to do wildcard or something I would want that to be true because bar is in barfoo

shell cape
#

Thanks so much for the insights

mighty ledge
#

for bar and foo

#

by rejecting things that don't have foo or bar in it

#

You gotta dream it up 😉

silent vector
#

Seems challenging because it could be

{% set list = ['foodaddddd','hello'] %}
{% set test = 'hellosanta' %}
{{ list | select('search',test) | list | count > 0 }}
mighty ledge
#

🤷‍♂️ not separating your test like that will lead to problems

#

how is the code supposed to know you just want to check hello and santa but not llos?

#

or osan

#

or hel

#

or nta

#

or just the letter t?

silent vector
#

No idea that's why I'm asking if we can do partial matches lol.

mighty ledge
#

that's what I'm saying, your logic is flawed

#

you gotta approach this differently

#

even if we had partial matches, it wouldn't work because of what I said above

silent vector
#

I have never done partial matches to have a clue of how to approach this

mighty ledge
#

I'm not sure why you'd even want partial matches

silent vector
#

More or less to avoid hard coding every possibility. By simply saying is foo in foo-bar or foobar

mighty ledge
#

yes but you'll still have a list of partial strings

silent vector
#

As in it found f but not foo? I'm just looking for true/false

mighty ledge
#

you aren't going to want to check for every permutation of the partial

mighty ledge
#

including single letter partials

#

so you're better off separating the string into the partials you want

#

explicitly

silent vector
#

How should I approach that?

mighty ledge
#

you have a number of ways, your current method or rejecting instead of selecting

pastel crescent
#

What is the best way to take a | list and get it into a nice human-readable format with an Oxford comma?

silent vector
#

| list | join(',')

silent vector
mighty ledge
#

Reject works the exact same way as select

#

no difference

marble jackal
mighty ledge
#

What rsplit?

silent vector
#
{% set list = ['foodaddddd','bar'] %}
{% set test = 'barfoo' %}
{{ list | select('reject',test) | list | count > 0 }}

TemplateRuntimeError: No test named 'reject'.

mighty ledge
#

dan

#

select

#

reject

silent vector
#

🤦‍♂️

mighty ledge
#

and you have to separate barfoo

#

using barfoo will never work for the reasons I mentioned above

#

aslo, word of advice, don't override the name list

#

same with all other functions/methods

marble jackal
# mighty ledge What rsplit?

yeah, but I usually start with a list, so you need to convert it to a comma seprated string first, and then split it again 🙂
so what would be more efficient?

{% set fruit = ['Banana', 'Orange', 'Grape', 'Lemon'] %}
{{' and '.join((fruit | join(', ')).rsplit(', ', 1))}}
{{ fruit[:-1] | join(', ') ~ ' and ' ~ fruit[-1] if fruit | count > 1 else fruit | join }}
silent vector
#

Yeah I noticed that could be an issue.
{{ listtest | reject(test,'') | list | count > 0 }}

#

Returns an error

#

I'm struggling lol.

mighty ledge
#

I think you should take time and learn what a test is and what tests are available in ansible

silent vector
#

I get the same error in home assistant too.

mighty ledge
#

yes, because you aren't using the correct test

#

reject and select filters first argument is a test

#

the second argument is what you're testing

silent vector
#

It was search

#

Yeah

mighty ledge
#

right, so why are you supplying the variable test?

silent vector
#

Because how do I tell it what to reject?

#

{{ listtest | reject('search',test) | list | count > 0 }} no errors with this

mighty ledge
#

You’re not thinking about your ending result

#

When rejecting are you looking for items or the absence of items

#

You’re rejecting items from the list that you want to find. So should you be checking for greater than 0?

#

You have to approach your problem differently, the whole problem, not just swapping out select for reject

silent vector
#

{{ listtest | reject('search',test) | list | count != listtest | count }}

#

That looks like it could work

#

Not sure if that's a weird way of approaching it

#

Not sure if it fully solves it though. As it returns true for even 1 letter matching.

mighty ledge
#

You have to add a reject for each one you want to find

silent vector
#

Each letter?

mighty ledge
#

Each word

marble jackal
#

you can do something like this:

{% set testlist = [ 'food', 'barcelona', 'banana'] %}
{% set searchlist = [ 'foo', 'bar'] %}
{{ testlist | reject('search', searchlist | join('|')) | list }}
mighty ledge
#

not sure if that search works the same as our search

#

that would be regex

marble jackal
#

it works, it returns [ 'banana' ]

mighty ledge
#

yah but he's in ansible

marble jackal
#

yeah, I forgot 🙂

mighty ledge
#

🤷‍♂️

silent vector
#

Home Assistant it works lol

#

Search works in Ansible

mighty ledge
#

in ansible it would need to be 'regex'

#

because | is or in regex

silent vector
#

Got it

#

Will test now

#

Both work surprisingly. 'regex' and 'search'.

#

Is it technically ok to ask these questions? They are Jinja questions and can be used in home assistant so I guess it's ok?

#

Anyway to prevent

{% set testlist = [ 'foo', 'santa', 'banana'] %}
{% set searchlist = [ 'f'] %}
{{ testlist | reject('search', searchlist | join('|')) | list | count != testlist | count}}

From being true.

#

Meaning not return true just because it marched a single letter. I guess it's impossible because of what I'm trying to do?

marble jackal
#

this is true becuase 2 is not equal to 3

#

you are rejecting foo becuase it contains an f

#

so there are 2 items left

#

2 != 3 returns true

silent vector
#

Is there a way to reject only if it's more than 2 characters that match?

#

To avoid that?

mighty ledge
#

why not just not use a single letter?

silent vector
#

That too

#

How would I build that I

#

In

mighty ledge
#

simply use 'foo'?

silent vector
#
{% set testlist = [ 'fad', 'fkm', 'banana'] %}
{% set searchlist = [ 'foo'] %}
{{ testlist | reject('search', searchlist | join('|')) | list | count != testlist | count}}

I just wanted to make sure but yeah that makes sense this works it doesn't return true just because of the f

finite peak
#

I have added a fan template to my configuration.yaml in order to be able to control the fan speed on my new GE zwave fan control switch. However, I'm not sure what the next step is. How can I create a lovelace card to be able to set the fan speeds?

lofty mason
#

I'm not aware if there are any default cards that have pretty fan controls. You could look for a custom fan card, or you can create a horizontal row of buttons, each one calling a different fan.set_percentage service.
This PR (https://github.com/home-assistant/frontend/pull/15819) leads me to believe that maybe something is coming soon, though could be a-ways out still. Actually I'm not even sure if this will be used for a lovelace card, so maybe it's nothing.

runic egret
#

Hi, I don't know if this can be created with a light template - but I have a 4 button switch, which has LED behind every button which can get controlled by setting a zwave_js.set_value with a hex color. Would it be possible to be a reuseable template, which could be used on multiple entities, Or do I have to copy the whole template for each switch I have in my house? (its a ZDB5100) https://community.home-assistant.io/t/homeseer-hsm200-zwave-led-on-off-and-color-control/223242/42?u=lauer - this show an example for a similar approach.

silent reef
#

Hi all. I got this https://github.com/djerik/wavinsentio-ha - But i need a helper to combine the air humidity. But i was told that it is a a thermostat (a climate in HA) so i need to create a template? 🙂

paper hazel
inner mesa
#

anything under data: can be templated

paper hazel
#

Hmmm.... I get the following error```
Error executing script. Invalid data for call_service at pos 4: length of value must be at least 1 @ data['command'][0]

#

This is the yaml:

#
    - service: google_assistant_sdk.send_text_command
      data:
        command: >-
          {% if is_state('input_select.speaker_destination', 'Kitchen') %}
            "Call Kitchen Speaker"
          {% elif is_state('input_select.speaker_destination', 'Living Room') %}
            "Call Living Room Speaker"
          {% endif %}
        media_player: >- 
          {% if is_state('input_select.speaker_source', 'Kitchen') %}
            media_player.kitchen_speaker
          {% elif is_state('input_select.speaker_source', 'Living Room') %}
            media_player.living_room_speaker
          {% endif %}
inner mesa
#

It looks like it wants a list

paper hazel
#

Thx! Will figure a work around

hollow girder
#

hello, on what order are the attributes set in the templates? Is there any pattern? I would like to know if it's safe to reference the same entity attributes, for example:

power: "{{ la la la something }}"
voltage: "{{ la la la another  something}}"
amp: "{{ this.attributes.power / this.attributes.voltage }}"
inner mesa
#

you can't reference a value before the sensor has been created and its state established

#

the order they're evaluated in doesn't mean that any are immediately available in the state object

hollow girder
#

so basically, doing this or using the states(...) is the same, I just need to check if they are available and have a valid value...

#

?

inner mesa
#

you can't do what you're trying to do

#

this is refers to the state object before you update anything

hollow girder
#

ohh I see... so this will always be the state before the changes in progress?

inner mesa
#

yes

hollow girder
#

ok, tks @inner mesa

inner mesa
#

I'm pretty sure. You're more than welcome to try it

#

see if it works

hollow girder
#

I kinda miss something like a try/catch in templates, sometimes the logic is just so big that matching all possible points of fail on the template (like is int, etc etc) is so mutch work... somthing like a try this and if fails the template just catch and return that..

hollow girder
#

i'll check it out

inner mesa
#

I don't know if that's the current value or the last one, based on the |default()

#

you shouldn't need that if it's the current value

hollow girder
#

@inner mesa

#

I tested out the template

#

it works, it take the default stataus for some seconds then it syncs

inner mesa
#

the current value or the last value?

hollow girder
#

the current...

#

it updtes the attribute and some micro seconds afther the state to the same value

inner mesa
#

in your example, you were trying to refer to other attributes

#

my point is that your references are probably to the last update, not what you're doing right now

hollow girder
#
- sensor:
    - name: test_self_ref
      state: |+
        {{ this.attributes.test | default('Value when missing') }} - 
        {{ now() }}
      # not: "{{ state_attr('sensor.test', 'test') }}"
      attributes:
        test: "{{ now() }}"
#

attribute: test: 2023-03-15 01:25:00.121364+00:00

#

state: 2023-03-15 01:25:00.121364+00:00 - 2023-03-15 01:25:00.439643+00:00

inner mesa
#

again, you were using attributes

#

you're not testing what you said you wanted

hollow girder
#

I wanted to reference attributes on the same entity

inner mesa
#

from other attributes

hollow girder
#

yes... let me see

inner mesa
#

I'm not saying that it won't work, just that you haven't actually tested it

#

and further, I don't think your test above proves that it's taking the current value while you're defining the state

hollow girder
#
- sensor:
    - name: test_self_ref
      state: |+
        {{ this.attributes.test | default('Value when missing') }} - {{ now() }}
      # not: "{{ state_attr('sensor.test', 'test') }}"
      attributes:
        test: "{{ now() }}"
        teste2: >
          {{ this.attributes.test | default('Value when missing') }} - {{ now() }}
inner mesa
#

as you say, it updates later

hollow girder
#

teste2: 2023-03-15 01:28:00.248990+00:00 - 2023-03-15 01:28:00.561057+00:00
test: 2023-03-15 01:28:00.248990+00:00
friendly_name: test_self_ref

#

state: 2023-03-15 01:28:00.248990+00:00 - 2023-03-15 01:28:00.561057+00:00

#

it did the state and the other atribute on the same micro second... thats impressive

#

yes it's later... but for my use case thats good enough

inner mesa
#

The most typical case for this is defining the state in the context of the previous state, in which case this.state is the previous state until you finish setting the value. I suspect that you'll get a different answer to your sensor above if you flip the order of the attributes

#

it does evaluate them in order

hollow girder
#

I flipped the order and I have the same result... state and test2 with the same value

floral shuttle
#

got an automation which logs Full data: {{trigger.event}} in a notification. I can probably use the automations last_triggered, or this.attributes.last_triggered, but for this purpose am trying to template that off off the event. Might even use the time_fired for that? Anyways, particular template reason is how to get to this timestamp: Full data: <Event system_log_event[L]: name=homeassistant.components.tradfri, message=['Keep-alive failed'], level=ERROR, source=('components/tradfri/__init__.py', 129), timestamp=1678838780.6360462, exception=, count=1, first_occurred=1678838780.6360462>

#

in the trigger.event

#

would that be as simple as trigger.event.data.timestamp? given the fact that these also work: Message: {{trigger.event.data.message[0]}}, Logger: {{trigger.event.data.name}}, Source: {{trigger.event.data.source}}, Level: {{trigger.event.data.level}}

floral shuttle
#

yes it is 😉 ```
- service: persistent_notification.create
data:
title: >
{{trigger.event.data.timestamp|timestamp_custom('%X')}}: Tradfri reloaded
message: >
{{now().timestamp()|timestamp_custom('%X')}}: Ikea Tradfri integration was

maiden magnet
#

hi, is there a possibility in an automation to read out who the trigger, in my case a button, has triggered, and how i can do it?

arctic sorrel
maiden magnet
#

me it would be enough to know how the event looks for a button when it is pressed, since you can read out who has triggered the event

marble jackal
#

You can take that from the context

mighty ledge
maiden magnet
mighty ledge
#

i.e. listen to tinkerer and post your automation.

maiden magnet
mighty ledge
#

well we can't help without it

#

sorry

#

the context object in automations is different depending on the trigger

#

typically it's always in the same spot, but it's not for state triggers and event triggers. So we really need to see the automation

#

also, the only way you can get that information is if you have a person attached to a user and the person can log into HA

plain magnetBOT
#

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

glossy sleet
#

Can someone help me out? I can't use tap_action here

#

It's not navigating

marble jackal
#

I guess that's because of navigate: null

plain magnetBOT
#

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

glossy sleet
#

Should have been

  action: navigate```
#

Thank you

marble jackal
#

Yes, use the context. trigger.to_state.context.user_id should have the user id of the person who pressed the button

mighty ledge
#

nope

#

he has to use the trigger.to_state.context

marble jackal
#

Fixed

#

Then use the oldest pinned post here to find out the person

mighty ledge
# maiden magnet does someone has an idea?

You have to use trigger.to_state.context.user_id If you want the persons name, then you'd use "{{ states.person | selectattr('attributes.user_id', 'eq', trigger.to_state.context.user_id) | map(attribute='name') | first | default('Unknown') }}" to get the name. Keep in mind it will be Unknown if it cannot find a user that is also a person.

marble jackal
#

If the person entities match the name you are using for the counter entities, you can just template the entity_id

maiden magnet
marble jackal
#

If my previous comment applies

heavy crown
#

Hi, I have following {% for x in range(0,somelist|count) %} is there a nice embedded way to limit this to max 5? i.e. use somelist|count but if it is more than 5, take 5. The alternatve is a if / then section following the for statement but ...trying if this cane look nicer 🙂

mighty ledge
#

{% for x in range(0,somelist|count if somelist|count <= 5 else 5) %}

#

if you're trying to access the object tho, that's the worse way to do it

#
{% for someitem in somelist[:5] %}
#

instead of using range

#

only use range when you need an index

#

and even then, you don't need that because of loop.index

heavy crown
#

thanks

#

the somelist is json and ahs dozens of groups, I onlu want to handle data of the first 5 groups IF there are 5 groups, sometimes there are less

feral spade
#

Is there a way to print the config of a template sensor?
I have a trigger sensor, but the trigger condition doesn't for an update

marble jackal
#

You mean like the trace of an automation/script?

feral spade
#

yea, something like that

#

or just what HA thinks the current template is to check when I last reloaded

marble jackal
feral spade
#
- trigger:
    - platform: state
      entity_id:
        - vacuum.roomba
      from: "Cleaning"
  sensor:
    - name: "Last Roomba Cleaning"
      state: "{{ as_timestamp(now()) }}"
``` in template.yaml
marble jackal
#

Check the actual state while it's cleaning in devtools > states

#

I don't think it will be Cleaning

feral spade
#

hm, that shows it as lower case cleaning. While the history view displays it in upper case, Cleaning. I'll try lower

#

I guess that was it 🤦

mighty ledge
robust quartz
#

Hi all,
i'm trying to make a repeat sequence in an automation using a condition to stop the repeat sequence. This is the condition

- condition: template
  value_template: {{ is_state('input_boolean.' + trigger.calendar_event.summary, 'off') }}

can you please tell me what my error is. i checked the syntax in the states page, but could not use the calendar trigger data and i got the expected result with another entity.
When trying to save my automation i get the error
Message malformed: invalid template (TemplateSyntaxError: expected name or number) for dictionary value @ data['action'][1]['repeat']['until'][0]['value_template']

inner mesa
#

you need to surround your template in quotes

robust quartz
#

🤨 thank you, man how dumb does i feel

ancient halo
#

Is there anyone on here that's using the Mopeka propane integration? I'm trying to convert the measurement into a percentage rather than distance.
I tried creating a Template sensor the code works but the entity has an unknown state.
https://pastebin.com/hRXujaAW

plain magnetBOT
#

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

grave solstice
#
  • condition: template
    value_template: "{{ is_state('sensor.mqtt*', 'grafitti_road') }}"
#

Trying this

inner mesa
#

That's still wrong

#

you're making up syntax that doesn't exist

#

{{ states.sensor|selectattr('object_id', 'match', 'mqtt')|selectattr('state', 'eq', 'grafitti_road')|list|length > 0}}

#

"graffiti" is also spelled incorrectly

grave solstice
#
  • condition: "{{ is_state('device_tracker.iphone', 'away') }}"

That came from documentation.....

inner mesa
#

you added a "*"

grave solstice
#

ahhh

inner mesa
#

I guessed at what you really meant

grave solstice
#

You were correct however im getting syntax problems trying to paste in your code - Nah got it... now going to test

inner mesa
#

Use devtools -> Templates to test

#

also, check the spelling

grave solstice
#

Well thats speellt wrong everywere ...so another day 😄

#

You code worked ... Big thanks.... Is there a smart way of removing all triggers.... Basically trigger on all states now that i got the condition?

lofty mason
#

Why not just make that condition the trigger instead? Overactive trigger is not optimal.

grave solstice
#

Care to show me?

lofty mason
#

not really. template trigger is the same syntax as condition trigger.

grave solstice
#

ok

grave solstice
#
alias: Door Unlock Presence Trigger
description: ""
trigger:
  - platform: template
    value_template: {{ states.sensor|selectattr('object_id', 'match', 'mqtt')|selectattr('state', 'eq', 'grafitti_road')|list|length > 0}}

condition: []
action:
  - service: lock.unlock
    data: {}
    target:
      device_id: 7300bb4e88885723308c41981ab00730
mode: single
#

Can someone get me on the right track

urban shard
#

I have a question. I have a tuya led strip with RGBW lights (rgb leds and white leds). I connected the data pin to a esp8266 to use with WLED. Both entites (wled and tuya led strip) are in home assistant. How can I combile these into one light entity and make sure white lights turn off if i use RGB and the other way around. I cannot seem to get it working

urban shard
#

I tried but it's super confusing

lofty mason
#

I don't understand why you have two entities controlling this. Does the LEDs have two drivers? why?

marble jackal
inner mesa
grave solstice
#

Sorry guys... just really tired...sorry

inner mesa
ancient halo
#

Any help would be greatly appreciate to my above post

lofty mason
half pendant
#

I'm trying to overwrite the attribute media_title in a universal media player but it doesn't seem to work. Is this not possible?

#

Seems like the issue is that the TV does not have a media_title attribute. Anyone know how to "clear it" if it is not matching my conditions?

        {% if is_state('media_player.lg_c2', 'on') and (state_attr('media_player.lg_c2', 'source') == 'Apple OTT') %}
          {{ state_attr('media_player.kontor', 'media_title') }}
        {% else %}
          {{ state_attr('media_player.lg_c2', 'media_title') }}
        {% endif %}```
floral shuttle
#

can we write a persistent trigger template, that reflects the amount of times a certain automation was triggered, and has say the last 5 times as attributes history? I have smth like that for last motion triggers, but then simply template the triggering sensor, and not a adding number

robust quartz
#

Hello all,
in an automation using a calendar event as a trigger i want an action repeating until the current time is after the event.end time.
this is what i've done but it does not work. Can you see what i'm missing ?
value_template: "{{ as_datetime(trigger.calendar_event.end) < as_datetime(now() | string) }}"

half pendant
floral shuttle
robust quartz
# robust quartz Hello all, in an automation using a calendar event as a trigger i want an action...

still seeking. I found some errors with my template.
I added an action feeding an input_text entity with {{ as_timestamp( trigger.calendar_event.end) }} that works and store a timestamp of the event.end time
I changed my condition to

 - repeat:
      until:
        - condition: template
          value_template: "{{ as_timestamp(trigger.calendar_event.end) | float < as_timestamp(now()) | float }}"

I had check this in the template dev tool and can see the result switches to true there, but my condition is still not stopping the repeat loop. 😦

#

works 🙂

ancient halo
#

@lofty mason I did and it works once I add it to the configuration the sensor is created and the status is unavailable.

tidal heart
#

Is there a template to know if a state is a list? I had one for number but the entities changed and the numbers are now in a list. I just want to say if list do this else do that.

mighty ledge
#

states are always strings

#

so you have to search for things that would make it a list, like ','

#

@tidal heart ^

tidal heart
#

Ah! I’ll will try that, ty

mighty ledge
#

are you sure it's actually a list and not a large number?

marble jackal
#

@mighty ledge I now made this macro as a Dutch variant for relative_time with the additional options to choose how many time periods you want tot use, and if you want to use weeks as a time period or not
https://dpaste.org/qRkec
Works nice in dev with the new import function:

{% from 'relatieve_tijd.jinja' import relatieve_tijd %}
{{ relatieve_tijd(1,3, true) }}

53 jaar, 2 maanden en 2 weken

#

So I checked if the first input is a string or a number (so you can apply as_datetime) and I wanted to add some check if it was a datetime for some error handling

mighty ledge
#

You can probably create a macro for checking datetimes too

#

when I get to the beta, i'll be revamping my system most likely

marble jackal
#

Hmm, i can maybe use as_timestamp(default="error")

#

that seems to work quite okay

unborn sequoia
#

Hello, I have a sensor that counts expenses and displays a number. This number changes throughout the day (increases). I need to create statistics that remember the total number for each day so that I can see what value the sensor has reached each day. I want to do this through a https://www.home-assistant.io/integrations/history_stats/, but I'm not succeeding. I keep getting a result of zero.

#

Thank you for help

mighty ledge
#

History stats won’t do what you want

plain magnetBOT
#

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

unborn sequoia
#

and this history_stats:

- platform: history_stats name: Celkové náklady na domácnost entity_id: sensor.home_costs_without_measurement state: "on" type: time start: "{{ now().replace(hour=0, minute=0, second=0) }}" end: "{{ now() }}"

marble jackal
#

you need to use a trigger based template sensor with a time trigger

#

and you need to use the new template sensor format for that. You are using the legacy format in your code above

plain magnetBOT
unborn sequoia
marble jackal
#

well, petro proposed to store the state of the sensor at midnight, for that you need a time trigger, which is not supported in the format you are using

unborn sequoia
marble jackal
#
template:
  - trigger:
      - platform: time
        at: "00:00"
    sensor:
      - unique_id: petunia_banana_whale_orange
        name: Sensor status at midnight
        state: "{{ states('sensor.your_source_sensor') }}"

put this directly in your configuration.yaml, amend where needed and wait until midnight

#

this will create. sensor.sensor_status_at_midnight (based on the name)

unborn sequoia
unborn sequoia
#

There will also be: sensor.home_costs_without_measurement

marble jackal
#

Whatever you want as long as it's unique

unborn sequoia
marble jackal
#

No, it's the unique id used to store the entity in the entity registry

unborn sequoia
marble jackal
#

Yes

unborn sequoia
# marble jackal Yes

in that case it doesn't work.

the sensor.home_costs_without_measurement now shows a value 276.87 and I already tried to execute this trigger twice and the value is still unknown.
I have 2 statuses recorded on the timeline and each time it is Unknown

austere raven
#

huge problem with my template to get a sensor value.
{{ states.sensor.10_0_0_26_containers_active.state }} returns TemplateSyntaxError: expected token 'end of print statement', got '_containers_active'

marble jackal
austere raven
#

Thanks for the attitude...An integration(Glances) named the object id's not me. No easy way to rename all 750 entities provided from this integration

marble jackal
#

You're welcome! 🙈

austere raven
#

And still thanks for the help 😀

mighty ledge
#

if you're dead set on useing the states object {{ states['sensor.10_0_0_26_containers_active'].state }}

marble jackal
#

I thought you needed to put the object id between square brackets, but both options seem to work

mighty ledge
#

__getitem__ for the states object is magical

#

fyi [ ] uses __getitem__ if you're looking at the code

#

and __getattr__ is what's used after .

#

so when you do ['x'] it calls __getitem__, when you do blah.x it calls __getattr__

#

blah( uses __call__

#

there, you have a crashcoarse in the backend code

#

for templates

balmy terrace
#

Hi guys! is it possible to get a value from an Area in templates?
For example, I created an Area called Bedroom
I'd like to do something like :

If any device inside the Bedroom is on , do this ... I know the template syntax , I'm interested in the area part.
Thank you

#

{{ states('area.bedroom') }} ... something like this to get on/off

weak cradle
mighty ledge
balmy terrace
#

but it would be something like this?

mighty ledge
#

The idea is correct and would work in most languages. Unfortunately that won’t work in jinja.

#

I’m on mobile so I can’t provide an example atm

marble jackal
#

the yes part you can do like this:

{% set entities = area_entities('Office') %}
{{ 'yes' if entities | select('is_state', 'on') | list | count > 0 }}
balmy terrace
balmy terrace
balmy terrace
tight tundra
#

Hey everyone, trying to think of a way to define a sensor that +1 every time a different sensor goes to a specific state (like a counter) that will reset at midnight. For example if sensor.i_need_help goes to ready I would like to count that on a daily cycle.

lofty mason
#

Are you opposed to using a counter helper and an automation? Seems pretty straightforward.
Actually I think history_stats does exactly this already, if that fits what you need.

tight tundra
#

I attempted a utility helper but there is no way to define a specific state that it needs to be to increment. I only want to count the "ready" state.

#

I'll go take a look thanks!

hard garnet
#

What template would read out the time an event was last fired? In my case the event type is mobile_app_notification_action, event data is - action: TOGGLE_LIGHT

marble jackal
#

You can create a trigger based template sensor, which triggers on the event, and just put the current datetime in it's state

analog mulch
marble jackal
#

it's an event

#

so you need to use event variables

#

trigger.event.data.tag_id

#

or

trigger:
  - platform: event
    event_type: tag_scanned
    event_data:
      tag_id: bananas
analog mulch
#

great, the trigger.event.data key works! THanks

silent vector
#

How would I get epoch time in miliseconds?

marble jackal
#

{{ (now().timestamp() * 1000) | int }}?

silent vector
#

Perfect thank you.

charred dagger
#

A couple of zeros to much there for milliseconds...

marble jackal
#

ah right

#

this is micro 🙂

#

fixed 🙂 @silent vector

silent vector
#

Turned out I actually needed microseconds so it was perfect lol. I found out when I used an epoch converter to check the to see how accurate the output was.

tidal heart
#

I'm trying to get check if a state is a list. This one is pulling the RGB and makes it in hex format for mushroom card to use. But my recent change with the bulbs the RGB state is changed from number to list.

Previously I used it like this

{%- if is_state("light.bathroom_mirror", 'on') %}
  {%- if state_attr("light.bathroom_mirror", 'rgb_color') is number  %}
  {{ '#%02x%02x%02x' % state_attr("light.bathroom_mirror", 'rgb_color') }}
  {%- else %}
  orange 
  {% endif %}
{%- else %}
grey
{% endif %}

But as it's no number anymore it fails the second IF check. How can I change the check from number to list?

#

{%- if state_attr("light.bathroom_mirror", 'rgb_color') is number %} its this part I'm wondering about

marble jackal
#

rgb_color is always a list with 3 numbers in it

tidal heart
#

The output of {{ state_attr("light.bathroom_mirror", 'rgb_color') }} is ```yaml
[
255,
237,
222
]

marble jackal
#

or none if the light is off

#

so I would suggest to check if it's not none

tidal heart
#

Ah ofc I could check if none and then if the light is on/off and if on it can be orange! Thanks

marble jackal
#

or just replace is number with is not none

silent vector
mighty ledge
#

int will do that

#

integers don't have decimals

silent vector
#

Doesn't seem to work

mighty ledge
#

then your parenthesis are wrong

silent vector
#

Got it

mighty ledge
#

order of operations

silent vector
#

| int before the *

mighty ledge
#

no, you'd int after you get the result

#

pedmas

#

parenthesis, exponents, division, multiplication, addition, subtraction

silent vector
#

This works
{{ (now().timestamp() + 300) | int * 1000 }}

mighty ledge
#

filters are applied before all of that

silent vector
mighty ledge
#

I'm assuming you orginally had this

{{ (now().timestamp() + 300) * 1000 | int  }}
silent vector
#

Yep

#

And inside the parentheses

#

Which is why it wasn't working

half pendant
#

Anyone know if you can tell universal media control which child should be active at any given time? It tends to select my apple tv even though it's not doing anything

mighty ledge
#

all you needed to do was

#
{{ (now().timestamp() + 300 * 1000) | int  }}
#

however, you probably wanted to reverse the 1000 and 300

#
{{ (now().timestamp() * 1000 + 300) | int  }}
#

because pedmas

silent vector
#

That isn't epoch time (microseconds) in 5 minutes.

mighty ledge
#

if the 300 is supposed to be seconds, then you'd need to add 300000

#

regardless, this is all just math and order of operations

silent vector
#

Yep and preference.

mighty ledge
#

that's the point I'm making here

#

lastly, I'm not sure why you're using seconds anyways

#
{{ (now() + timedelta(minutes=5)).timestamp() | int }}
silent vector
#

It's not me lol. It's nutanix. They use epoch time in miliseconds. So I started with seconds then converted to miliseconds.

marble jackal
#

milliseconds or microseconds?

silent vector
#

I thought it was microseconds because the sme told me it was but it's actually miliseconds apparently.

sonic ember
#

I made an entity in a template, and it's a copy-paste of others that work but for some reason I can't find the entity in the Dev Tools. I also see no problems in the Log. Do I have a stupid typo somewhere?

  # TEST - Hourly prices for the dishwasher
  - name: "Cost for dishwasher EUR per hour"
    unique_id: cost_hourly_dishwasher
    unit_of_measurement: "EUR"
    state: >
      {{ (states('sensor.dishwasher_hourly_energy_use') | round (3)) * (states('sensor.energyprices') | round (3))}}
marble jackal
#

where did you place it?

sonic ember
#

under sensor: in a templates.yaml file

#

The other sensors and templates in that file work perfectly

#

It almost looks like it's got an old entity ID from a previous version of my yaml. Could that be?

#

Since I just found another entity with the right data, but the entity id is different. And I don't have any YAML code or UI entity for that sensor. Which means HASS thinks the entity with that unique_id has a different id I think...

marble jackal
#

do you now have

sensor:
  - bla
sensor:
  - foo
marble jackal
sonic ember
#

If I change it, it will create a new entity right, with new data?

marble jackal
#

yes

#

but because you added it, you can change the entity_id in the GUI

#

that will not affect historical data

#

it will still be available

sonic ember
#

Great thanks!

#

Ah, adding the unique id is what makes it possible to change through UI? Good to know!

shell leaf
mighty ledge
#

that's correct for a cover

#

assuming you're making a cover template

shell leaf
#

correct

#

strange, my card doesnt seem to change the icon

mighty ledge
#

is cover.living_room_curtains_straight the cover that's being created?

shell leaf
#

yes, its a helper group of 2 curtain covers, i check the state and it is changing between open and closed. so the icon should work

mighty ledge
#

are you creating a template cover though?

#

in the cover section of configuration.yaml using platform: template?

#

a template cover is an integration that makes a cover entity in home assistant using other entities as reference while you provide your own code to determine it's behavior. That's the only place you can use icon_template for a cover entity.

shell leaf
#

oh right, so should i just be using "Icon:" instead of icon_template ?

#

see i have cover entities through z2mqtt, i grouped them as a cover group

#

so i did not crate any cover" section to my config yaml

mighty ledge
#

you can't set custom icons for on/off on a cover without icon_template

#

so if your goal is to have a unique icon for on/off on a cover, you can't do that

shell leaf
#

oh ok

mighty ledge
#

If your entity is in HA and provided by an integration, you can simply change the "display as" in the UI and choose what to display the cover as

#

chances are, it'll have curtain icons as an option

#

@shell leaf do you know where that option is?

shell leaf
#

i only want to change the icon in my dashboard based on state. Can you point me in how to crate the cover template that allows me to use icon_tempalte

mighty ledge
#

right

#

click on your cover entity, go to the cog wheel

#

that will be your settings page, there's a display as dropdown

#

and you should be able to switch it to curtain

shell leaf
#

ok thats done

mighty ledge
#

Ok, that's it then

#

no template needed

shell leaf
#

sorry, I have not provided enough clarity, I have a mushroom card, that asks me to select the icon i want for that entity, I would like to use a template to change that icon, ill share the full card

mighty ledge
#

You don't need to provide a icon

#

it'll just use what's added to the entity

shell leaf
#

ok, let me try that now

#

that works, didnt know it was automatic from the entity, thought all entities came with static icons

#

thanks for walking me through that

unborn sequoia
# marble jackal What is your current code?

Hi, sorry for the long answer.
So even at midnight, no value was recorded.

My current code is this:

template:

  • trigger:
    • platform: time
      at: "00:00"
      sensor:
    • unique_id: petunia_banana_whale_orange
      name: Sensor status at midnight
      state: "{{ states('home_costs_without_measurement') }}"
marble jackal
final sun
#

{{now() - 'sensor.saugroboter_og_cleaning_history' >= 3 }}

I am trying to check if the last cleaning was 3 or more days ago.
The sensor reports the following attributes:

Attributes 2023-03-15 10:10:21 cleaning_time: 26 min cleaned_area: 25 m² status: Cleaning completed: true water_tank: Not installed

marble jackal
#

Does that datetime string also have a key in the attributes?

final sun
marble jackal
#

Ah okay

#

It's the state

#

{{now() - states('sensor.saugroboter_og_cleaning_history') | as_datetime | as_local >= timedelta(days=3) }}

atomic blade
#

I'm trying to write a template trigger that acts as a counter. Is there a way to get the current state within this context? Or would I just have to refer to the absolute entity name? (e.g. this.state vs states('sensor.my_counter'))

#

Either would work, just trying to get a better idea of what context you have inside these template trigger sensors

final sun
marble jackal
atomic blade
#

Is there anything like that, though?

#

Also trying to make sure I'm differentiating here between the trigger context and the sensor context (if they are even different)

marble jackal
#

The this object is created when a trigger triggers

#

But I don't understand what you are trying to achieve

atomic blade
#
- trigger:
  - platform: state
    entity_id: sensor.foobar
    to: 0
  sensor:
    - name: My counter
      state: "{{ states('sensor.my_counter)|int + 1}}"

Roughly this I think

#

Just wondering if there's something more succinct I can do for the template there, such as accessing the current sensors state if that's possible

marble jackal
#

You can use this.state for that state template

atomic blade
#

Ok cool

marble jackal
#

You do need a default for the int filter though, as the first time it will trigger the state will be unknown

atomic blade
#

Ah yeah. I really need to stop getting lazy with my casting

atomic blade
marble jackal
#

Yes

atomic blade
#

I think I've actually been kinda hesitant to use defaults for casting, because I actually want it to error out if I get a weird value so I'm aware of the problem.

#

What are your thoughts there?

marble jackal
#

You can work around that using availability templates or using thing like is_number

atomic blade
#

Like if I have template that uses an underlying sensor, and that sensor starts reporting values I'm not expecting, I don't want to just fall back to a default, I want an error to bubble up.

marble jackal
#

Without filing your logs with errors

unborn sequoia
atomic blade
#

That sounds great, and I think I'd use that here. One thought that comes to mind is that I don't think all sensors have availability templates, no?

#

I get a sense that there are gaps somewhere though. I guess I'll cross that road when I get to it if that's the case.

marble jackal
#

And in this case you really don't want an availability filter, that will reset your count