#templates-archived

1 messages Β· Page 8 of 1

lapis quarry
#

gotcha

#

modified it, does that look right now?

marble jackal
#

And there should be an ( before states() (you close it after `float*7)

#
  - platform: template
    sensors:
    
      airconlr01a_current_corrected_power_usage:
        friendly_name: AirConLr01a Current Corrected Power Usage
        value_template: >
          {% if states('sensor.airconlr01a_current_power_usage') | int > 10 %}
            {{ (states('sensor.airconlr01a_current_power_usage')| float*7) | round(2) }}
          {% else %}
            {{ states('sensor.airconlr01a_current_power_usage') | round(2) }}
          {%endif %}
        availability_template: "{{ states('sensor.airconlr01a_current_power_usage') | is_number }}"
        unit_of_measurement: W```
lapis quarry
#

yes that did it πŸ‘Œ

#

thanks guys you have been really really extremely helpfull today, I apreciate your time πŸ₯°

#

need to implement this in a bunch of places but i think i can figure it out for now, will be back if not πŸ™

marble jackal
#

Btw, now you updated, there is a complete new integration for template entities. The template integration

#

You are using what is now called the legacy template sensor format

lapis quarry
#

yes i know a lot has changed since 2021.04 to now

#

when you say template integration you mean in the gui or in yaml

#

ok got you, just found it

#

ill read about it thanks πŸ˜‰

nocturne chasm
#

how can I expand a domain and then search for attributes in a certain state? I tried this but it is blank:

{{expand('domain.climate')|map(attribute='preset_mode')| selectattr('state', 'eq', 'none') | map(attribute='name') | list |join(', ') | default(none) }}
mighty ledge
#

attribute='attributes.preset_mode'

#

once you do that, the map(attribute='name') won't do anything

#

so if you're trying to find preset_mode eq none, then it should just be

#
{{expand('domain.climate')| selectattr('attribute.preset_mode', 'eq', 'none') | map(attribute='name') | list |join(', ') }}
nocturne chasm
#

does eq=equal?

mighty ledge
#

yep

nocturne chasm
#

cause that still comes up blank

mighty ledge
#

is preset mode equal to the word 'none'?

nocturne chasm
#

yes

mighty ledge
#

attributes.preset_mode, sorry

nocturne chasm
#

yes

mighty ledge
#

no i'm telling you to use attributes.preset_mode

#

not attribute.preset_mode

#

missing an s

nocturne chasm
#

gotcha, but still blank

mighty ledge
#

{{expand('domain.climate')| selectattr('attribute.preset_mode', 'eq', 'none') | list }}, blank?

#

oh duh

#

it's not domain.climate

#

it's states.climate

marble jackal
#

And no expand needed then

nocturne chasm
#

still blank

marble jackal
#

{{ states.climate | selectattr('attributes.preset_mode', 'defined') | selectattr('attributes.preset_mode', 'eq', 'none') | list }}

mighty ledge
#

shouldn't make a difference

marble jackal
#

petro's version was still missing the s

nocturne chasm
#

UndefinedError: 'homeassistant.helpers.template.TemplateState object' has no attribute 'attribute'

mighty ledge
#

I'm assuming that it's not actually equal to 'none'

marble jackal
#

My edited version has it

nocturne chasm
#

that gives a whole list of the entities attributes

#

current_temperature=73, temperature=73, target_temp_high=None, target_temp_low=None, fan_mode=auto, hvac_action=idle, preset_mode=none,

#

a partial list

nocturne chasm
#

but the attribute preset_mode clearly says none in dev tools / states

mighty ledge
#

can you show me it in the developer tools -> states page

nocturne chasm
#

Auh, I had to map the name πŸ˜‰

mighty ledge
#

well yeah, trying to figure out if what you're saying is true πŸ˜‰

#

hardest part about support

#

the templatse without the map were testing, not the solution

nocturne chasm
#

when assisting people who only kinda understand templates πŸ˜„

tight canopy
#

a short question, i have a external light controller, currently controlled via nodered. but I would like to have them as a light switch in HA. is there a possibility to do this via restful api and/or templates?

obtuse zephyr
tight canopy
#

its a aquarium led controller and currently not available to HA. this is how I currently handle it

obtuse zephyr
rare linden
#

is there a way to check what set the last value of something? i have input_booleans that override certain automations but i have "scene"'s in the form of scripts (because real scenes are annoyingly limited) which will set the boolean themselves, i want to check if the input_boolean was changed by a script or not so i can avoid setting it in my "normal" scene if it was previously set manually

so basically i want to check if the last time 'input_boolean.override_light' for example was set by a script

marble jackal
#

You can use context

azure drum
rare linden
sharp frigate
#

Hi all. Could someone help me please with how to select the lowest of a bunch of temperature sensors? I have created a generic_thermostat to control my heating but it's using one room's temperature. I'd like to template something to always return the lowest of them for the heating control?

sharp frigate
rare linden
#

another way would be to sort the list by value and surround the whole thing with ()[0] and that will get you the highest/lowest depending on which direction you sort it, i do something similar to get the latest updated motion sensor

marble jackal
#

There's also a | min and | max filter. Sorting the list and taking the first item is not needed for that

quiet creek
#

'[[[ return states["sensor.rm4_mini_temperature"].state + "Β°F" ]]]'
How can I change this template to read 76 degrees F instead of 75.96 degrees F?

next patrol
#

Hi,
I want to add Watts and Amps entity values of 7 sonoff POW R2 devices and show them as separate entity(sensor). Can someone point me in right direction.

next patrol
#

I have managed to do this in template editor,
now i need help to post value from this script/template into my dashboard.

marble jackal
#

You need to create a template sensor with that template

azure drum
#

Hello, how do I create a new entity using e.g. template that shall be used as a storage variable. And how do I initialize that once, upon creation.

#

´´´ - name: sunsp_fro_dc_0_power_to_knx
unique_id: sunsp_fro_dc_0_power_to_knx
state: "{{ 0 | float }}"
device_class: power
state_class: measurement ´´´

#

if I do that it stays 'state unknown'

azure drum
#

How do I initialize that entity?

marble jackal
#

Reload template entities from devtools > YAML

#

But this will always be 0

azure drum
#

Well maybe you can tell me how to archive my goal? Can you give me a hint how it can be done?

#

I do not understand what you mean by "reload template entities from YAML" .

marble jackal
#

devtools == Developer Tools

azure drum
#

Maybe I don't understand the concept behind it? What I try to do. If sensor.A changes then check how much it changed, to then send out a knx packet if it has changed enough. So I thought I need a storage of the last sent value, compare the stored with the new value upon that change, to then update the storage and sent out to knx bus. Maybe there is another idea how something like that can be done in HA? Should I better try to do that using a python script? If so, I am willing to dig into that. But for the time I need to learn a lot...

azure drum
#

(the state is undefined...)

marble jackal
#

I would expect that template to have the state 0

azure drum
#

it doesn't.

#

OH! it does. sorry!

azure drum
#

Okay, I keep trying, in developer tools templates, but fail. How do I copy a state from entity A to state entity B?

azure drum
#

I read that 50 times... One example please, that could help me.

marble jackal
#

But what I would probably do is:

  • create an input number
  • create an automation which triggers on state changes of sensor A
  • compare the old and new state
  • add the difference to your input number
  • check the state of the input number to see if it is above the threshold
  • if that is the case, send the knx command and set the input number to 0
azure drum
#

I understand the idea. But again, the maybe simple question, how do I write to an entity (B) or "the input" number in the action part of the automation? I find no "service" that is writing a value to my sensor.B. Maybe I don't see the obvious?

marble jackal
#

{{ states('sensor.cucumber') }} will give you the state of that sensor

#

But do note that all states are strings, so you'll have to convert it to a number

azure drum
#

I know, but you seem not to understand what I search. Maybe I am unable to phrase it correctly. I try to WRITE the state of sensor.B Something (this is not working!) like that {{ set 'state.sensor.sunsp_fro_dc_0_power_to_knx' = float( 1 ) }}

#

I keep trying in developers templates, but fail... πŸ˜•

marble jackal
#

No, a template will provide you with a value, you can not perform actions in it

#

Use the service call for the particular entity, and use the template for the value

#

Eg

service: input_number.set_value
target:
  entity_id: input_number.apple
data:
  value: "{{ states('sensor.cucumber') | int + 6 }}"
azure drum
#

That clarifies it for me, finaly. Thank you!!!

#

´´´

#

service: input_number.set_value
target:
entity_id: sunspec_dc_1_power_to_knx
data:
value: "{{ states('sensor.sunsp_fro_mppt_module_0_dc_power') | float }}"

#

Message malformed: not a valid value for dictionary value @ data['action'][0]['target']['entity_id'] ????

#

But getting closer πŸ˜‰

marble jackal
#

The entity id needs to be an input number

#

Which you need to create first

azure drum
#

How do I do that?

#

I did some reading on it. HA turns out to very complicated for that. Maybe someone has a link how to do something that I do using s python script?

marble jackal
#

You can easily create an input number in the GUI

#

Settings > Devices and Services > helpers

dusty grailBOT
azure drum
#

Thank you for your help!

#

But then I will write the value to that input_number, not to where I want it, the entity that will be send out to the knx bus. Okay, then I could use send.knx once difference is reached in that input value. But, that is scalar, a fixed or variable amount of change. But not a percentage of the monitored value of sensor.A. I guess that will not solve the problem, right. I can't believe, that there is no way to write a value to the state of an entity. If not, then I think I cannot do what I want. I will have to revert back to the knx visualisation hardware. Almost all time spent no with HA will be wasted. I am disappointed...

#

Is there a way to use python to Read,calculate and write to an entity?

#

Could there be a dummy device/integration created, that is "fed" by python script generated output to do the trick?

marble jackal
#

What is the actual service call you want to use at the end

azure drum
#

knx.send

#

I want to send out data from the inverter integration, but only if the value has changed by x% or if y time no update to the bus. That's all, because the knx bus gets flooded otherwise....

marble jackal
#

I meant the complete service call

#

The YAML code

azure drum
dusty grailBOT
#

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

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

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

inner mesa
#

You need to fix your quotes

marble jackal
#

Use different quotes inside and outside the template

azure drum
marble jackal
#

You are using double quotes inside your template, and the template is wrapped in double quotes as well

#

Replace one of those with single quotes

azure drum
#

Okay, what does it do if make that error? Fix like that?

#

service: knx.send
data:
address: 12/0/99
type: power
payload: "{{ states('sensor.sunsp_fro_mppt_module_0_dc_power') | float }}"

marble jackal
#

Yes

#

Before you had "{{ states(" sensor.sunsp_fro_mppt_module_0_dc_power ") | float }}"

#

And again, please format your code as code

azure drum
#

Thanks, I would like to understand what it does? And, I try formatting, but I am rather new to discord. Where can I find how to format it. Your code is in nice boxes. I haven't managed to find how that is done. I am doing a steep learning curve ... πŸ˜‰

marble jackal
#

You are using single quotes when you try to format it, you need backticks

azure drum
#

Fine, I will do better! πŸ™‚

#

test

half pendant
#

Is there anyway to create a dictionary helper? I'd like to associate motion sensors with lights and the build automations based on that.

atomic blade
#

I'm trying to write a template which uses the last_changed time to make a decision. However, on reboot this value resets to the current time. What's the best way around this shortcoming of HA?

half pendant
#

Is this possible? I can easily write it in pseudo code but have no idea how to make it into a script or automation.
Basically i want to create a script that takes a motion sensor as an argument. Checks that sensor in a dictonary and gets a light back and then turns the light on or off depending on the sensors state.

inner mesa
#

that's straightforward

half pendant
#

Haha ⬆️ difference between amateur and professional at HA πŸ™‚

#

Any clues on how to achieve it @inner mesa?

inner mesa
#

something like this:

test2:
  variables:
    lights:
      binary_sensor.one: light.one
      binary_sensor.two: light.two
  sequence:
    - service: light.turn_{{ states(binary_sensor) }}
      data:
        entity_id: "{{ lights[binary_sensor] }}"
#

pass in the sensor via "binary_sensor"

half pendant
#

Does States(binary_sensor) return On if its on (motion detected)?

inner mesa
#

lots of capitalization problems in your question

#

but essentially "yes"

half pendant
#

And i would then create an automation based on this?

inner mesa
#

you asked for a script

#

so that's a script

#

if you want an automation, it's easy to convert

half pendant
#

I mean it doesn’t really matter

#

I can work with a script

inner mesa
#

it does matter

#

they're very different things

#

you don't pass a sensor into an automation, for instance

half pendant
#

Sure i get that. I meant for my self

inner mesa
#

this part:

#

Basically i want to create a script that takes a motion sensor as an argument.

#

I don't know what you're looking for with an automation

half pendant
#

So i would change out binary_sensor.one: light one to the pair matching? So
binary_sensor.downstairs_bathroom_motion_sensor_rorelselarm: light.hallway_lights

inner mesa
#

yes

half pendant
#

And - service: light.turn_{{ states(binary_sensor) }} should be - service: light.turn_on{{ states(binary_sensor) }}right?

inner mesa
#

no

#

exactly as I provided

half pendant
#

Oh ok. Trying to understand what happenes here

inner mesa
#

it will resolve to light.turn_on or light.turn_off based on the state of that sensor

half pendant
#

Cool!

#

Getting: Message malformed: Integration '' not found

#

Full script:

  variables:
    lights:
      binary_sensor.downstairs_bathroom_motion_sensor_rorelselarm: light.hallway_lights
  sequence:
    - service: light.turn_{{ states(binary_sensor) }}
      data:
        entity_id: "{{ lights[binary_sensor] }}"
inner mesa
#

your indentation is wrong

#

everything from the second line down needs to come back 2 spaces

half pendant
#

Would i call the script like this?

data: 
  variables: {{ binary.binary_sensor.bathroom_motion_sensor_rorelselarm }}
inner mesa
#

a few things wrong with taht

half pendant
#

I mean in an automation action

inner mesa
#

still, it's broken

#
service: script.1662915872850
data:
  binary_sensor: binary_sensor.bathroom_motion_sensor_rorelselarm
half pendant
#

Sorry.

data:
  variables: " {{ binary_sensor.bathroom_motion_sensor_rorelselarm }} "
inner mesa
#

still no

#

read that link

half pendant
#

I did.

inner mesa
#

I gave you the answer

#

this part is completely wrong: variables: " {{ binary_sensor.bathroom_motion_sensor_rorelselarm }} "

#

the relevant example there is:

automation:
  trigger:
    platform: state
    entity_id: light.bedroom
    from: "off"
    to: "on"
  action:
    service: script.notify_pushover
    data:
      title: "State change"
      message: "The light is on!"
#

you added "{{ }}" and "variables:"

half pendant
#

Ok. I think i understand, not entirely sure why my version didnt work though.
Was looking at this example:

automation:
  trigger:
    platform: state
    entity_id: light.bedroom
    from: "off"
    to: "on"
  action:
    service: script.turn_on
    target:
      entity_id: script.notify_pushover
    data:
      variables:
        title: "State change"
        message: "The light is on!"```
inner mesa
#

that's a different service call

#

script.turn_on is not script.1662915872850

half pendant
#

Ah i see

inner mesa
#

as it mentinos:

#

There are two ways to achieve this. One way is using the generic script.turn_on service.

#

The other way is calling the script as a service directly.

half pendant
#

Yeah i get it now.

inner mesa
#

still, you were trying to evaluate a template there rather than just passing the value

half pendant
#

yes it was two different errors. Still pretty much a novice on templating and writing stuff in yaml rather than in the UI

tepid oak
#

Hi all, I'm currently running mostly the minimalist frontend. On my front page I have a number of room cards. On the card for the basement I'd like the main entity to be one of two entities, 1. the washing machine time left if it's in the running state. 2. If not, the temperature from a temp sensor in the basement. Am I allowed to put a template directly in the YAML for the page or do I have to define it as a template in one of my config files?

#

Current entry which isn't working.

dusty grailBOT
tepid oak
#
- type: "custom:button-card"
  template:
    - card_room
    - grey_no_state
  name: Basement
     # entity: sensor.basement_temperature
  entity_id: >-
    {% if is_state('sensor.washing_machine_machine_mode', 'Running') %}
      sensor.washing_machine_time_remaining
    {% else %}
      sensor.basement_temperature
    {% endif %}
  icon: mdi:home-floor-b
  tap_action:...
inner mesa
#

That card does not use jinja templates

tepid oak
#

Ah, I guess that would explain it

rare linden
#

what's the correct syntax to provide a default timestamp? for example state_attr('binary_sensor.contact_door_front_house', 'last_updated')|timestamp(now()) where timestamp is obviously not valid i've also tried the default filter but that doesnt work if state_attr returns 'None' as that's a valid value to the default filter

inner mesa
#

{{ none|default(now(), True) }} -> 2022-09-11 12:45:24.116846-07:00

rare linden
#

Thanks, so was just missing ", true" in the default param, i take it that tells it to act upon a nonetype

#

or if the type doesnt match the 1st parameter

fossil totem
#

I'm trying to get a formatted time delta to tell me how much time is left on a 3D printer. I have octoprint configured which gives me a string with the estimated date/time of completion. i can convert that to a datetime, then subtract that value from now() to get the number i'm after. However, it's returned as a timedelta object which leaves me unsure of how to take that value and then format it correctly.

#

ex: {{ (states("sensor.octopi01_estimated_finish_time") | as_datetime() - now()) }} returns 9:18:28.877476

#

I'd like something along the lines of 9h:18m to be generated

#

I note in the docs that there are a couple functions timedelta and as_timedelta which both return a timedelta object. I think maybe what I'm trying to do is to go the opposite direction, take a timedelta object and format it via strftime or similar. strftime notably does not support timedelta objects.

rare linden
#

| timestamp_custom('%hh:%mm', True) i think is what you want

fossil totem
#

i'll try it!

rare linden
#

%H:%M

spark pelican
#

Is there a good reference for old-style vs modern template sensors, along with when I can use icon_template and when I can't?

fossil totem
#

sadly, nope. it also is expecting a datetime object, which isn't a timedelta

spark pelican
#

I am trying to use an icon_template on a modern-style (I think) sensor and am gettin the error Invalid config for [template]: [icon_template] is an invalid option for [template]. Check: template->sensor->0->icon_template.
3:09:41 PM - (ERROR) config. py

fossil totem
#

{{ (states("sensor.octopi01_estimated_finish_time") | as_datetime() - now()) | timestamp_custom('%hh:%mm', True, "boo") }}

#

returns a booooooo

inner mesa
#
{% set secs = ((now() + timedelta(hours=1, minutes=30)) - now()).total_seconds() %}
{{ '%0d' % (secs//3600) ~ "h:" ~ '%0d' % ((secs//60) % 60) ~ "m" }}
fossil totem
#

if i leave out the default, it directly says that it doesn't think the input is a datetime, which it isn't.

#

@inner mesa i think i can work with that!

#

also i appreciate the latte art πŸ˜„

#

{% set secs = ((states("sensor.octopi01_estimated_finish_time") | as_datetime() - now())).total_seconds() %} BOOM

#

that was exactly what i needed and i like the approach. the "total_seconds" method was the missing link and i appreciate the help!

#

i feel like the mod math is just showing off lol πŸ˜›

dry narwhal
#

Watching NFL and thinking about templating πŸ˜„
Anybody here using templating with auto-entities?

mighty ledge
#

I don’t remember tho

inner mesa
marble jackal
#

I'm definitely not a python expert, but the way I read that it's formatting a datetime.
a datetime with a timedelta added to it, is a datetime again right?

#

But 20 days is also not a month, so there is more strange going on there πŸ˜›

inner mesa
#

oh, yeah, you're right

#

in any case, I'm regularly disappointed with what can be done directly with a timedelta

marble jackal
#

yeah, it would be nice if you could just format a timedelta

#

there is an as_timedelta function now, which converts a time to timedelta

#

would be nice if it could be done the other way

dry narwhal
# mighty ledge I think I do

I am trying to create a sensor on the fly (or perform the value adjustment on the fly) whilst using auto-entities.

Right now I am using creating a sensor where state is
state: "{{ now().timestamp - states('sensor.last_restart_time')|as_timestamp(0) }}"
Any idea how I could create these uptime sensors on the fly with auto-entities so I can plot all restart_time sensors in one graph?

dense tinsel
#

Hey everyone! Perhaps is there a way to create a function to prevent me from calling repetitive code? Trying to follow the DRY principle in YAML has been difficult. I'm essentially looking to make a function with two arguments in which just checks to see if two media_player entities are grouped. I have everything working as pleased but it's not very redundant.

inner mesa
#

lol

#

that was repetitive

#

there's no easy way to create a function that returns a value like that, but you can create a script that takes parameters

dense tinsel
#

Hahaha my accidental dual messages or my statement, or both. πŸ˜‚ No problem, I appreciate the prompt response.

dusty grailBOT
inner mesa
#

whenever you feel compelled to return "true" or "false", just use the test itself

#

without fully understanding the rest of it, you can replace the last several lines with:

{{ (master_ensuite_grouped and master_bedroom) or (master_ensuite_grouped and not ensuite) }}
dense tinsel
#

Thank you so much, I forgot to bracket each of my statements which is what had caused me the headache.
Working code below for anyone who may want it.
https://hastebin.com/qutafoxoco

sacred sparrow
#

How can I make this template work for any state saying the word "On"
{{ is_state(''input_select.office_status'', ''on'') }}
eg. "On - Work", "On - Busy", "On - Standby" etc?

#

its for a condition so if theres a way not to use a template I'm happy to use that

mighty ledge
#

Your q doesn’t really make sense

inner mesa
#

{{ 'On' in states('input_select.office_status') }}

mighty ledge
sacred sparrow
#

ahh so simple!

#

thanks

harsh ridge
#

how do I make a template condition that triggers if a sensor state contains a string? my current code doesn't seem to trigger even though it seems like it should
{{ 'Chrome' in sensor.darkstar_activewindow }}

marble jackal
#

{{ 'Chrome' in states('sensor.darkstar_activewindow') }}

#

you need to get the state of the sensor, you are now checking for a (probably) non-existent variable

harsh ridge
#

yup that works perfectly, thanks πŸ‘

hollow lily
#

Hi, I've got a simple mqtt sensor with it's state being updated by node-red. The only issue is that when the MQTT broker is restarted (or for any other reason) the state_topic no longer exists on the MQTT broker I get an 'unknown' state. Is there a way to default a state for MQTT sensor? Failing that, my plan is to run an automation when MQTT Broker add-on is restarted to manually create the topic with a default. The question then is if there is a way to trigger an automation when MQTT Broker (or any other add-on) has 'started'?

open hound
#

Is there a way to check and see if the state is 'Unknown' and then assign a state if that is true?

marble jackal
#

You can create a template sensor which shows the state of the source sensor, and something else if the state of that source sensor is unknown

open hound
#

Is there a way to assign a default value through the configure.yaml?

#

Or through the configuration UI?

#

I'm not as familiar with MQTT.

hollow lily
hollow lily
open hound
#

Ok.

half pendant
#

Can someone help me figure out how I'd make a sensor that reports back the entity name of the latest sensor in a group that changes state?

marble jackal
half pendant
#

Thanks!

#

That gives me the friendly name. What do i use for the entity name?

#

Or where do i find the info on it

#

Found it (by guessing) it was entity_id

marble jackal
#

correct πŸ™‚

half pendant
#

Can someone help me troubleshoot this?

        friendly_name: 'Motion Sensor Latest Changed'
        value_template: >
          {{ expand('binary_sensor.motion_sensors') | sort(attribute='last_changed') | map(attribute='entity_id') | list | last }}
        attributes:
          last_changed: >
            {{ expand('binary_sensor.motion_sensors') | sort(attribute='last_changed') | map(attribute='last_changed') | list | last }}```
marble jackal
#

what's the trouble?

half pendant
#

Getting an error message when checking the yaml

#

Invalid config for [sensor.template]: [attributes] is an invalid option for [sensor.template]. Check: sensor.template->sensors->motion_sensor_latest_changed->attributes. (See ?, line ?).

marble jackal
#

you are using the legacy template format, and need to use attribute_templates

half pendant
#

How would a non-legacy version look?

marble jackal
#

do note that legacy doesn't mean depreciated

half pendant
#

Sure but if I'm writing new templates I should probably learn to write the new standard.

#

I'm guessing legacy doesn't mean deprecated, yet 😱

marble jackal
#

and that the new format falls under the template integration, not under sensor, so you can't use it in sensors.yaml or anything included under sensor

half pendant
#

I think all my templates live under the template integration.

marble jackal
#

no, what you posted above lives under sensor

#
sensor:
  - platform: template
    your_code: 
half pendant
#

You are correct.

#

So instead of ```yaml
sensor:

  • platform: template
    your_code:
It should be 

```yaml
template:
  - platform: sensor
    your_code: 
marble jackal
#

no

#

check the link to the docs. The format is completely different

dusty grailBOT
marble jackal
#
template:
  - sensor:
      - name: friendly name (used to generate the entity_id)
        unique_id: a unique id used in the backend (allows changes of icon/entity_id/name in the GUI)
        state: the template for the state (value_template in the legacy format)
        attributes: templates for attributes (attribute_templates in the legacy format)
half pendant
#

Thx

unreal merlin
#

can I assign a template sensor to an area?

#

there's a few discussions in the forums about this, but haven't found anything definite (guessing: only devices, not entities)

marble jackal
unreal merlin
#

The template: sensor one?

#

Cant find this in the docs, whats the trick? πŸ™‚

marble jackal
#

I just posted a link to the docs above, and an example

#

but the trick is to assign a unique_id: which allows changes in the GUI

#

including assigning an area

half pendant
#

Ok i managed to move it to the new format. But the attribute does not show up under ”Attributes” in developer tools.

  - sensor:
    - name: 'Motion Sensor Latest Changed'
    state: >
      {{ expand('binary_sensor.motion_sensors') | sort(attribute='last_changed') | map(attribute='entity_id') | list | last }}
    attributes:
      last_changed: >
        {{ expand('binary_sensor.motion_sensors') | sort(attribute='last_changed') | map(attribute='last_changed') | list | last }}```
marble jackal
#

try this:

    attributes:
      last_changed: >
        {{ (expand('binary_sensor.motion_sensors') | sort(attribute='last_changed') | map(attribute='last_updated') | list | last).isoformat() }}
mighty ledge
#

you don't need the isoformat()

#

it can store datetimes

#

I do it all the time

marble jackal
#

okay, any other idea why it doesn't work then πŸ™‚

mighty ledge
#

no, I'd wager it is

marble jackal
#

I must admit I was just guessing here πŸ˜‰

mighty ledge
#

(working)

marble jackal
#

indentation is off though

#

at least in the posted code, but then it would not show a state as well

mighty ledge
#

ah yeah It should have indentations that's probably his reason

#

it would create the first sensor then bitch about the remaining config

marble jackal
#
template:
  - sensor:
    - name: 'Motion Sensor Latest Changed'
      state: >
        {{ expand('binary_sensor.motion_sensors') | sort(attribute='last_changed') | map(attribute='entity_id') | list | last }}
      attributes:
        last_changed: >
          {{ expand('binary_sensor.motion_sensors') | sort(attribute='last_changed') | map(attribute='last_changed') | list | last }}
#

@half pendant try it like this

half pendant
#

When i save the yaml and check it i get an error in the log:
Invalid config for [template]: extra keys not allowed @ data['attributes']. Got OrderedDict([('last_changed', "{{ expand('binary_sensor.motion_sensors') | sort(attribute='last_changed') | map(attribute='last_changed') | list | last }}\n")]) extra keys not allowed @ data['state']. Got "{{ expand('binary_sensor.motion_sensors') | sort(attribute='last_changed') | map(attribute='entity_id') | list | last }}\n" required key not provided @ data['sensor'][0]['state']. Got None. (See /config/configuration.yaml, line 235).

mighty ledge
#

read our last few posts...

half pendant
#

I’m on an ipad and stupid discord ios app doesn’t allow to copy just the code so when i copy it will mess up the indentation

mighty ledge
#

your error says otherwise

#

your error is the exact error we would expect if your spacing was off

half pendant
#

I’m not saying you are wrong. I’m saying i cant copy paste from discord. Where is the error, i have to fix it manually

marble jackal
#

everything under name should have 2 extra spaces

mighty ledge
#

you can copy text in discord

#

click and hold the fes's last post with the code and copy text is the 3rd option down

half pendant
#

That copys all of the text. Not just the code.

mighty ledge
marble jackal
#

I also can not copy text on Discord mobile, I usually copy the post and on Android some small popup shows which I can click and then take out the part I need

mighty ledge
#

he only posted the template

marble jackal
#

Don't know about iOS

mighty ledge
#

so copying all the code is wha tyou want to do

marble jackal
#

it will include the backticks when you copy the entire message, but that's not so hard to take out

half pendant
#

Anyway, @marble jackal you were right. It’s working now

#

Also thx for helping me with how the new way of writing templates is! Gonna start moving stuff over!

limber sparrow
#

Hi, i'm trying to scrape a website (works) but I want the output filtered out because it gives too much info back. So I used a strip command and that is also working. However the strip command I use can have 2 different values 'op' or 'om'. And also that is working with the following code.

'{{ (value.split("op")[1]) }}{{ (value.split("om")[1]) }}'

But the log is showing an error BUT it does work. Is there any better code to strip this when the value can either be 'op' or 'om'.

marble jackal
#

'{{ value.split("om")[1] if "om" in value else value.split("op")[1] }}'

limber sparrow
#

That easy haha thanks! πŸ™‚ Kind of new to this

half pendant
#

I found this code snippet online that does exactly what i want, but i want to limit it to only sensors from a specific integration (mqtt). Is there an easy way to make that work?

   | selectattr('last_changed', 'lt', now()-timedelta(seconds=3600)) 
   | map(attribute='entity_id') | join(', ') }}```
marble jackal
#
{{ expand(integration_entities('mqtt'))
    | selectattr('domain', 'eq', 'sensor') 
    | selectattr('last_changed', 'lt', now()-timedelta(hours=1)) 
    | map(attribute='entity_id') | join(', ') }}
half pendant
#

@marble jackal Can you point me to where i can read up on what the different arguments does? Trying to figure out what ’eq’, ’lt’ for instance does in this case.

marble jackal
#

in the jinja documentation, you can find a link in the pinned posts

#

but eq is equal to, you can also use equalto or ==
lt is lower than, you can also use <

half pendant
#

Ok so the argument selectattr(’domain’, ’eq’, ’sensor’) should read as ”filter all items where domain equals sensor”?

marble jackal
#

yes, but you should not use these fancy quotes

half pendant
#

Yeah sorry i’m on a swedish keyboard layout and that’s the default

marble jackal
#

and this selectattr('last_changed', 'lt', now()-timedelta(hours=1)) compares the last time the state of the sensor was changed to the current time minus one hour

#

so you start with all entities from the mqtt integration, then select which one of those are sensors, and then select which ones changed in the last hour

#

out of that you take only the entity_id, and not the entire state object, and that you stitch together using a comma

half pendant
#

Got it. Another question. Trying to read up on the map() function. Wanted to change it so that it keeps the entity_id and the last changed time but couldn’t make it work with passing multiple arguments to the map function.

nocturne chasm
#

I am trying to do this for a template condition:

{{ expand('group.inside_switch_card_2') | selectattr('state', 'eq', 'on') | rejectattr('entity_id', 'eq', 'light.master_bedroom_light') | map(attribute='state') == 'on' }}
#

but it always says false

mighty ledge
#

what are you trying to do with that?

#

are you trying to get a count?

#

== 'on' at the end doesn't make sense

nocturne chasm
#

I have a group that includes all switches and one light

half pendant
nocturne chasm
#

I want to exclude the light and see if any of the switches are on

mighty ledge
#

replace the == 'on' with | list | count > 0

nocturne chasm
#

perfect. thanks

half pendant
#

Can i use the selectattr() function to test if a string contains another string?

marble jackal
#

selectattr('entity_id', 'search', 'something')

deep marsh
#

Hi all,
I am missing a very simple thing here. I want to subtract two datetime helpers from each other. This works using timestamps. But after that, I want to put the result in a new datetime helper. For some reason, it does not accept the value. I thought you can just put a timestamped value in a datetime helper, but it does not seem to work. I guess I am missing a very simple thing. Does anyone here have an example for this?

#

I think I got it...

sour linden
#

Is there a better way I can write this. More specifically is there a way I can recall the value of another element like this().weeks?

{% set alice_week_age = {
  "weeks": ((now() - '2022-03-15' | as_datetime | as_local).days / 7) | round(0, 'floor', 1),
  "days": (now() - '2022-03-15' | as_datetime | as_local).days - (((now() - '2022-03-15' | as_datetime | as_local).days / 7) | round(0, 'floor', 1) * 7)
} %}
#

What I have works, I would just like to clean it up

inner mesa
#

Set a variable?

#

My strategy for such things is generally to set a bunch of variables and then use them in the data structure

mighty ledge
sour linden
deep marsh
sour linden
mighty ledge
#
{% set something = 1 %}
#

now you have a variable named something

marble jackal
#
{% set birthday = '2022-03-15' | as_datetime | as_local %}
{% set weeks = (now() - birthday).days // 7 %}
{% set days = (now() - birthday).days % 7 %}
{% set alice_week_age = { "weeks": weeks, "days": days } %}
sour linden
#

so isnt that what I'm doing with set alice_week_age? how can I access alice_week_age.weeks within alice_week_age ?

marble jackal
#

like that

mighty ledge
#

yah, exactly how you wrote it

inner mesa
#

Right, you're already doing it

sour linden
#

that wasnt working but i'll try again πŸ™‚

inner mesa
#

This is where I wonder where you may have copied that from, since you're clearly already using a variable

marble jackal
#

BTW congratulations with Alice being 26 weeks old tomorrow!

sour linden
#
{% set alice_week_age = {
  "weeks": ((now() - '2022-03-15' | as_datetime | as_local).days / 7) | round(0, 'floor', 1),
  "days": (now() - '2022-03-15' | as_datetime | as_local).days - alice_week_age
} %}

UndefinedError: 'alice_week_age' is undefined

marble jackal
#

you can not use the variable inside itself before you defined it once

mighty ledge
#

you're referencing itself in it's declaration

#

chicken vs egg

sour linden
#

ahhhh

#

ok

marble jackal
#

but I've already provided the easy formulas for your calulations

sour linden
mighty ledge
#
{% set offset = now() - '2022-03-15' | as_datetime | as_local %}
{{ {'weeks': offset.days // 7, 'days': offset.days % 7 } }}
sour linden
#

Thanks!

mighty ledge
#

I just took what the fes did and shrunk it down

#

#lazy

marble jackal
#

Even better πŸ™‚

sour linden
#

Thank you!

#

My next calculation (after I get this one in lovelace) that I want to make is going to be Months old but on the set day of the month, so counting how old she is by months.
So if birthday is 2022-03-15
On 2022-04-15 -> 1 Month
On 2022-09-15 -> 6 Month

mighty ledge
#

oh, good luck...

#

you can't use time deltas for that.

sour linden
#

yea I feel like that one is going to be a far more of a challenge for me

#

learning experience πŸ˜‰

mighty ledge
#

you can estimate the number of months with {{ {'months: offset.days // 30 ,'weeks': offset.days // 7, 'days': offset.days % 7 } }}

#

but to get Actual months... no

marble jackal
#

with a lot of code

#

But you'll have to take into account the years, and changes of the year, and if they are full months (so compare the days in the month)

mighty ledge
#

yep

#

it's terrible

sour linden
#

πŸ˜†

inner mesa
#

I have no idea how many months old I am 🀷 . Many...

sour linden
#

haha ikr

marble jackal
#

I was trying to create the template, but I have to start preparing dinner now

#
{% set birthday ='1981-10-12' | as_datetime | as_local %}
{% set d = now().day >= birthday.day %}
{% set m = now().month >= birthday.month %}
{% set bday_this_year = birthday.replace(year=now().year) %}
{% set last_bday = bday_this_year if bday_this_year < now() else bday_this_year.replace(year=now().year - 1) %}
{% set years = last_bday.year - birthday.year %}
{% set months = now().month - birthday.month - (0 if d else 1) + (0 if m else 12) %}
sour linden
#

You made some pretty good progress so far! πŸ˜„

nocturne chasm
#

I am trying to figure out how to turn off only things that are on in a group or lock only things unlocked. Turning the group on/off won’t work. I was using the expand template but if you try and turn an entity off when all of them are already off you get an error. Any ideas?

#

Conditions won’t work because I am working with several different domains.

marble jackal
#

You can use a template like you had, map the entity id, and use that for the target of your service call

marble jackal
nocturne chasm
sour linden
#

Well, I figure I would only be calculating this for the first 2 years so not sure how much leap year would be a problem

marble jackal
fringe salmon
#

Hello! I've been pointed from the general thread over here to ask about color effects. Are there any good starting points for doing interesting color effects for something like a kids dance party? We have a few color zigbee bulbs that could be randomized or could have other effects applied to them, but I'm not sure what the best starting point would be. Thanks!

nocturne chasm
#
- service: cover.close_cover
  data:
    entity_id: >
      {% if expand('group.all_covers') | selectattr('state', 'eq', 'open') | map(attribute='state') | list | count > 0 %}
        {{ expand('group.all_covers') | selectattr('state', 'eq', 'open') | map(attribute='entity_id') | list |join(', ') | default(none) }}
      {% endif %}
mighty ledge
#

this is what you should use

#
- choose:
  - conditions:
    - condition: template
      value_template: "{{ expand('group.all_covers') | selectattr('state', 'eq', 'open') | map(attribute='state') | list | count > 0 }}"
    sequence:
    - service: cover.close_cover
      data:
        entity_id: "{{ expand('group.all_covers') | selectattr('state', 'eq', 'open') | map(attribute='entity_id') | list |join(', ') }}"
#

and if you want to optimize it..

#
- variables:
    lights_on: "{{ expand('group.all_covers') | selectattr('state', 'eq', 'open') | map(attribute='entity_id') | list }}"
- choose:
  - conditions:
    - condition: template
      value_template: "{{ lights_on | count > 0 }}"
    sequence:
    - service: cover.close_cover
      data:
        entity_id: "{{ lights_on | join(', ') }}"
#

I just realized they were covers, oops

inner mesa
#

this tactic seems to work:
{{ expand([states.light, 'switch.fr_reading_lamp'])|selectattr('state', 'eq', 'on')|map(attribute='entity_id')|list }}

#

you can add whatever other entities you want

nocturne chasm
# mighty ledge that will still error

i cant use a choose because i am doing multiple different things, lights, llocks, covers, switches i guess i am going to have to do multiple automations or just give it an else?

mighty ledge
#

just use that choose for that single action

#

or put all the remaining actions inside the choose

nocturne chasm
#

auh. multiple choose under each service?

mighty ledge
#

no

#

so the choose is only for that single action

#

you can put actions after it

#

or not

#

or you can put items inside that chooses sequence

nocturne chasm
#

auh, you can multiple action blocks?

mighty ledge
#

all you're trying to do is make it not error on that service call, so you use choose to conditionally call that service call

#

I'm not following your question

#

If all you want to do is make this service not error...

- service: cover.close_cover
  data:
    entity_id: >
      {% if expand('group.all_covers') | selectattr('state', 'eq', 'open') | map(attribute='state') | list | count > 0 %}
        {{ expand('group.all_covers') | selectattr('state', 'eq', 'open') | map(attribute='entity_id') | list |join(', ') | default(none) }}
      {% endif %}

you can replace it with this and it will be the same

- variables:
    lights_on: "{{ expand('group.all_covers') | selectattr('state', 'eq', 'open') | map(attribute='entity_id') | list }}"
- choose:
  - conditions:
    - condition: template
      value_template: "{{ lights_on | count > 0 }}"
    sequence:
    - service: cover.close_cover
      data:
        entity_id: "{{ lights_on | join(', ') }}"
nocturne chasm
#

if i have a light on, a switch on, a lock unlocked, and a cover open. a choose will get to complicated

mighty ledge
#

I still don't follow

#

the choose is literally for just that service

#

no other services

#

unless you want that

#

you can do this without any repercussion and it's not really complicated:

- variables:
    covers_open: "{{ expand('group.all_covers') | selectattr('state', 'eq', 'open') | map(attribute='entity_id') | list }}"
- choose:
  - conditions:
    - condition: template
      value_template: "{{ covers_open | count > 0 }}"
    sequence:
    - service: cover.close_cover
      data:
        entity_id: "{{ covers_open }}"
- variables:
    lights_on: "{{ expand('group.all_lights') | selectattr('state', 'eq', 'open') | map(attribute='entity_id') | list }}"
- choose:
  - conditions:
    - condition: template
      value_template: "{{ lights_on | count > 0 }}"
    sequence:
    - service: cover.close_cover
      data:
        entity_id: "{{ lights_on }}"
#

it'll still rip through the automation

nocturne chasm
#

ok, i see what you are doing

mighty ledge
#

You could even get super lazy (like i do) and just make a all in 1 turn off script

nocturne chasm
#

i thought about that but i like what you posted above

#

my alarm_away automation has become a complete mess with stuff i have been trying πŸ™‚

mighty ledge
#
action_based_on_state:
  mode: parallel
  max: 1000
  variables:
    target_entities: "{{ expand(group) | selectattr('state','eq', target_state) | map(attribute='entity_id') | list }}"
  sequence:
  - condition: template
    value_template: "{{ target_entities | count > 0 }}"
  - service: "{{ service }}"
    target:
      entity_id: "{{ target_entities }}"
#

then your automation is just:

- service: script.action_based_on_state
  data:
    group: group.all_covers
    service: cover.close_cover
    target_state: open
- service: script.action_based_on_state
  data:
    group: group.all_lights
    service: light.turn_off
    target_state: 'on'
#

the choice is yours, personally I like to make scripts and reuse them so that I don't have to have super complicated automations

#

I know the script will work. at that point, you're just debugging the automation itself if something doesn't go right. and your compartmentalized script can be tested easily in the service caller

#

especially if you add fields and descriptions

#

take a look at my config, it's all scripts and like 10 automations that use all those scripts that are parallel

#

and if you want them all to turn off / close at the same time....

#
- parallel:
  - sequence:
    - service: script.action_based_on_state
      data:
        group: group.all_covers
        service: cover.close_cover
        target_state: open
    - service: script.action_based_on_state
      data:
        group: group.all_lights
        service: light.turn_off
        target_state: 'on'
#

it's cool to watch

nocturne chasm
#

i think i am on my way with the variables example - variables should line up with the - choose for proper yaml corect?

mighty ledge
#

yep, but you can put them in the variables section too

#

instead of in the action sequence

mighty ledge
nocturne chasm
#

thank you

#

slowly building it then my alarm has to go to arm away so....may be a while

#

i really need to understand variables so some reading also

spring zenith
dusty grailBOT
fierce hornet
#

Could someone help me? I'm trying to create a system that cleans specific rooms using my vacuum based on some input bools. It seems like whatever I try gives an error. Most of the time it's ... required key not provided @ data['zone']. Got None

#

The template is moved to the link above

inner mesa
#

you have several extra "-"

mighty ledge
#

it also needs to output a list

#

not a yaml list

#

and you need to programatically add ,

#

not an easy template

#
service: xiaomi_miio.vacuum_clean_zone
data:
  repeats: 1
  zone: >
    {% set ns = namespace(items=[]) %}
    {% if is_state('input_boolean.stofzuig_kleed', 'on') %}
      {% set ns.items = ns.items + [25335, 25936, 27573, 27402] %}
    {% endif %}
    {% if is_state('input_boolean.stofzuig_keuken', 'on') %}
      {% set ns.items = ns.items + [21695, 25664, 24804, 28896] %}
    {% endif %}
    {% if is_state('input_boolean.stofzuig_woonkamer', 'on') %}
      {% set ns.items = ns.items + [24756, 25046, 28189, 28625] %}
    {% endif %}
    {{ ns.items }}
fierce hornet
#

Unfortunatly it doesn't work because it actually expects lists within a list. This just makes it one big list

#

Would you happen to know how to accomplish this? Have no idea how to come up with something like this. I believe the output in the end should be [[24756, 25046, 28189, 28625], [25242, 26014, 27662, 27272], [21695, 25664, 24804, 28896]] if all the booleans are enabled

inner mesa
#

just add another set of square brackets around each list

#
    {% set ns = namespace(items=[]) %}
    {% if 1==1 %}
      {% set ns.items = ns.items + [[25335, 25936, 27573, 27402]] %}
    {% endif %}
    {% if 1==1 %}
      {% set ns.items = ns.items + [[21695, 25664, 24804, 28896]] %}
    {% endif %}
    {% if 1==1 %}
      {% set ns.items = ns.items + [[24756, 25046, 28189, 28625]] %}
    {% endif %}
    {{ ns.items }}
fierce hornet
#

That works! Didn't know the last step would be so simpleπŸ˜… Thanks guys!

mighty ledge
#

thanks @inner mesa

gilded estuary
#

I have a water meter calculated in US gallons which I am converting to m3. When the HA restarts, sometimes the US gallons sensor spikes initially for a second before returning to normal, and unfortunately my m3 sensor adds this spike to itself. Because this spike only happens rarely and immediately after a restart, I'd like to make my m3 sensor wait like 3mins before starting after startup (this should ignore the spike). Question: Is it possible to add a delay to the following template:

  water_meter_water_consumed_m3:
    friendly_name: 'Water Meter - Water Consumed (m3)'
    icon_template: hass:water
    unit_of_measurement: cubic meters
    value_template: >
        {{ (states('sensor.water_meter_water_consumption_us_gallons')|float(0) * 0.0037854118|float(0))|round(4) }}
    availability_template: "{{ states('sensor.water_meter_water_consumption_us_gallons') not in ['unknown', 'unavailable', 'none'] }}"
marble jackal
#

No, that's not possible, but how high is this spike?

#

You could add it to the availability template, so it's unavailable if the source sensor value is above a certain threshold

gilded estuary
#

it's fairly significant... 107k to 279k, back down to 107k

gilded estuary
marble jackal
#

You could if you convert it to a trigger based template sensor

#

Then you can trigger on state changes of the source sensor, and compare the from_state with the to_state

#

Maybe it is not even needed to use a trigger based template sensor, you could use this.state and compare that to new calculation

#

But you are using the legacy format, which doesn't provide the this variable

gilded estuary
#

hmm, interesting. Can you provide me with a link to read an example on this?

#

Im happy to make the change if I know how πŸ™‚

marble jackal
gilded estuary
#

"you could use this.state and compare that to new calculation"

Can you suggest how this code should look?

#

...now that I have it updated:

template:

  • sensor:
    • name: 'Water Meter - Water Consumed (m3)'
      icon: hass:water
      unit_of_measurement: cubic meters
      state: >
      {{ (states('sensor.water_meter_water_consumption_us_gallons')|float(0) * 0.0037854118|float(0))|round(4) }}
      availability: "{{ states('sensor.water_meter_water_consumption_us_gallons') not in ['unknown', 'unavailable', 'none'] }}"
marble jackal
#
{% set new = (states('sensor.water_meter_water_consumption_us_gallons')|float * 0.0037854118) | round(4) %}
{{ new if (not this.state | is_number) or new < this.state | float * 1.5 else this.state }}
#

Something like this

gilded estuary
#

ok, so that would go under the 'State' variable

inner mesa
#

you don't need the |float(0) here: 0.0037854118|float(0)

marble jackal
#

BTW, you can simplify your availability template to

availability: "{{ states('sensor.water_meter_water_consumption_us_gallons') | is_number }}"
#

Right, didn't look at the existing template, I only used it to create the variable

#

But indeed, that's not needed

#

The default for the other float is also not needed, because of the availability template

gilded estuary
#

you guys rock!

#

Gonna try this out and see how it goes.

marble jackal
#

I forgot one thing, you should take into account what happens if the state of the template sensor is unavailable

#

Then you also want to use the new state

#

I've added that

#

And brackets, because I'm not completely sure to what the not applies

#

A quick check learns me the brackets are not needed

sour linden
#

I think I got my baby birth month counter figures out πŸ˜„

inner mesa
#

good thing you got it done before your baby is old enough to fix it for you πŸ™‚

sour linden
#

lol

inner mesa
#

Ok, dad. Lemme just do it for you...

sour linden
#

I'll share it in a second, pulling up hastebin now

#

I didn't account for leap year math because for what I'm aiming for I don't see how that makes a difference

sour linden
#

That didn't actually work as planned. Is there a way to take a date and subtract a month such that 2022-09-18 becomes 2022-08-19 ?

#

I was thinking about something like set lastmonth = concat (now().year "-" (now().month -1) "-" now().day) but I can figure out how to do that

sour linden
#

Got it!! πŸ˜„ {% set last_month = now().year ~ "-" ~ (now().month - 1) ~ "-" ~ now().day %}

obtuse zephyr
#

Careful of months w/ 30 or less days

sour linden
#

Ahh I see what you did there!

#

ty

obtuse zephyr
#

There is something like this {{ (now() - timedelta(days=30)).date() }}, you can't provide "months" likely because it's ambiguous

mighty ledge
chilly locust
#

Thanks for this. I think this is what I need for tracking daily HVAC duration, but I'm trying to "beef it up" and clean up the state based on if it's just minutes or minutes and hours (ex. 17 minutes will say "17 minutes" and not "0 hours 17 minutes".) I've pasted the code I use for a few other sensors and removed seconds and adjusted sensor names, but I can't get it to work in the template tab. Thoughts?
https://hastebin.com/ohajanubeg.csharp

azure drum
#

No answer in general, maybe it belongs here?

#

Good morning, Is there a way to modify the time at which a meter helper (reset daily) resets? Why, I use a battery in my solar system and I would like to know how much energy is used since sunset, or a time in the afternoon. Any idea?

#

there is an attribute cron pattern... ????

fallow gulch
#

ok so why am I getting two decimal places from this template?

#
    - name: "Main Room Temperature"
      unit_of_measurement: "Β°C"
      device_class: temperature
      state: >-
        {{ (float(states.sensor.kitchen_temperature.state) + float(states.sensor.lounge_rm_pro_temperature.state) ) / 2 | round(1) }}```
#

my very basic understanding is that round(1) should give 1 decimal place

marble jackal
#

Because you are only rounding 2 which is already an integer

#

You should also use defaults for your float functions or use an availability template

#

And you should use states('sensor.whatever') instead of states.sensor.whatever.state

fossil venture
#

Can this only be used in mqtt value_templates or any template sensor?

marble jackal
#

I think it's implemented in everything under the template integration

fossil venture
#

Sweet. That makes running totals a bit easier then.

marble jackal
#

that should be on my clipboard

#

it mentions all state based and trigger based entities

fossil venture
#

I assume it will be a string and needs to have a float or int filter applied if doing addition?

marble jackal
#

this.state will always be a string

fossil venture
#

Thanks Fes.

sour linden
marble jackal
# sour linden Good point
{% set m = 12 if now().month == 1 else now().month - 1 %}
{% set y = now().year - 1 if now().month == 1 else now().year %}
{% set last_month = now().replace(year=y, month=m).date() %}

This will work in January

teal cove
#

Hi. How can I generate a hash of a string in templates?

Background is I want to secure a webhook event. My idea was this: (what I assume to be the normal secret key method)
On the device sending the webhook, I hash a string containing the current date and a secret key, then I send both date and hash as event_data with the webhook.
Then in HA templates, I use that date and the secret key to generate a hash and if it matches with the hash sent via the webhook event_data, continue.

mighty ledge
teal cove
mighty ledge
#

you'd have to come up with some algorithm. It may not be possible.

#

Jinja is limited

#

TBH, it'll be a waste of time

teal cove
#

Do you happen to have another idea on how to secure a webhook like I mentioned above?

#

(apart from just keeping the webhook url a secret lol)

mighty ledge
#

not really a way to do that

marble jackal
#

This also works in January:
{{ (now().replace(day=1) - timedelta(days=1)).replace(day=now().day).date() }}

sour linden
mighty ledge
#

if not, it'll be off by an hour 🀣

#

the perils of time and coding

sour linden
#

It only counts months and days by day of month so 2022-08-22 -> 2022-10-24 is 2 months and 2 days

#

I think it would break for birthdays later in the month than the 27th but that isnt my case

#

The doctors office counts baby age by day of month, not sure what they would do with a birthday on the 31st for shorter months. didnt think to ask

sour linden
#

EST

mighty ledge
#

ah, then it won't break during dst

#

but it'll be off by an hour

sour linden
#

not the end of the world πŸ˜„

mighty ledge
#

what matters is if DST is applied on your birthday, but not applied when you're counting

#

basically datetimes change the offset when DST is applied

sour linden
#

ah

mighty ledge
#

right now I think ESTs offset is 4 hours because we are in DST, but when out it's 5 hours

#

or vice versa

sour linden
#

yes something like that

mighty ledge
#

so, when you create a datetime in the past, it uses your CURRENT dst setting, not the DST setting at that point in time

#

super dumb

sour linden
#

oh interesting

mighty ledge
#

well, it's not dumb, it makes sense why they do it, so that time deltas are correct

#

but when you're manipulating datetimes like you are, it screws it up

sour linden
#

well i think it should be close enough, not doing rocket science with her age counter πŸ˜‰ it's more of a quick reference / nice to know

mighty ledge
#

lol, if that was the case you could have just divided by 30.5

#

πŸ˜‰

sour linden
#

it's good to know thank you for letting me know

#

hahaha true

#

i often like to do things the long drawnout way πŸ˜‰

dusty grailBOT
sterile nacelle
#

akvarie ones work fine, but the 3d_printer one throws error :/

#

The system cannot restart because the configuration is not valid: Invalid config for [sensor.template]: invalid template (TemplateSyntaxError: expected token 'end of print statement', got 'd_printer') for dictionary value @ data['sensors']['3d_printer_power']['value_template']. Got '{{ states.switch.3d_printer.attributes.current_consumption }}' invalid template (TemplateSyntaxError: expected token 'end of print statement', got 'd_printer') for dictionary value @ data['sensors']['3d_printer_voltage']['value_template']. Got '{{ states.switch.3d_printer.attributes.voltage }}'. (See ?, line ?).

marble jackal
#

there is no DST on 1st of January 1970

#

as it was winter then

marble jackal
#

same for the others

marble jackal
mighty ledge
#

and then making a date when dst may or may not have been active

#

so your made up time will have a +0400, when it should have had +0500

#

dst is fucked up

#

when you run that exact same command during a non dst time, the top becomes null or 0:00:00 and the bottom will be -05:00 for tz info

#

actually, it looks like this was fixed??!?!?!?!?! in python 3.10??? holy crap

#

ugh, my dst calcs will be wrong now πŸ˜•

marble jackal
#

I mean this

mighty ledge
#

oh, no that's UTC vs Local

marble jackal
#

there is an offset of 1 hour between the 2

mighty ledge
#

that flag at the end basically says "Is my timestamp local or is my timestamp utc"

marble jackal
#

yes, but as it is DST here now, I found it strange that the offset was one hour

#

but there is no DST on 1st of January 1970

#

it took me some time that the timezone of that actual date would be used

mighty ledge
#

It's probably platform specific

marble jackal
#

and %F

mighty ledge
#

i.e. windows, linux, or mac

marble jackal
#

ah okay

#

they are quite convenient for date and time

mighty ledge
#

I'm not 100% sure on that

#

ah no, look

#

it's only a linux thing

#

LOL so if you visit strftime.org on a linux machine, you'll see %F... those cheeky fucks

#

but i'm assuming you're visiting the page on windows, so it shows the windows items

#

or if you're on your phone it'll be mac

#

@marble jackal ^

marble jackal
#

aaah

#

that's actually somewhat smart I guess

mighty ledge
#

πŸ€·β€β™‚οΈ

marble jackal
#

but I don't have any Linux machines on which I can acutally view a browser

#

oh my android phone of course

mighty ledge
#

i wonder what that would choose

#

is andriod linux?

marble jackal
#

it is, but I don't see them

mighty ledge
#

Maybe it doesn’t announce itself as linux to the browser

inner mesa
#

They should at least have a drop-down selection

marble jackal
#

is there a place for feature requests πŸ˜›

charred maple
#

hello is there an good tutorial how to make an template?

teal cove
inner mesa
inland stag
#

Good morning everyone! I have a rest sensor which gets a JSON response looking like this:

{"html":"<h3>Hemer-Becke/Oese</h3><p class="klein"> gew&auml;sserkundlicher Pegel </p><p class='klein'>Pegelst&auml;nde der letzten 3 Tage</p><img src='lib/php/gangl_p.php?stationsname=Hemer-Becke&breite=300&hoehe=210'  width=300 height=210 ><table align="center">
<tr><td></td><td></td></tr>   <tr><td class="klein">&nbsp;&nbsp;mittleres Niedrigwasser: </td><td class="klein" align="right">4 cm</td></tr>
   <tr><td class="klein">&nbsp;&nbsp;Mittelwasserstand: </td><td class="klein" align="right">16 cm</td></tr>
   <tr><td class="klein">&nbsp;&nbsp;mittleres Hochwasser: </td><td class="klein" align="right">122 cm</td></tr>
</table>
<div align="center"><p class="klein">Wasserstand am 14.09.2022 09:05 :&nbsp;14,00 cm</p></div><div align="center"><p class="wichtig">ungepr&uuml;fte Rohdaten</p></div><input type="hidden" id="hdnPgnr" value="Hemer-Becke">"}
#

so when I use value_json.html, I get the HTML code as state. How do I go from here to just get the 14,00 cm from the /div/p tag?

dusty grailBOT
jagged obsidian
#

how did that pass json validation?

#

there are unescaped quotes inside the value

inland stag
#

I cleaned those up

#

Home Assistant does it as well in the state output

#

right now I cannot get the state from HA as it exceeds 255 characters

#

(with only using value_json.html)

jagged obsidian
#

{{ value_json.split(' :&nbsp;')[1].split('</p>')[0] }} for that specific example

#

if you're extracting the value from <p class="klein">Wasserstand am 14.09.2022 09:05 :&nbsp;14,00 cm</p>

#

this one might be safer {{ html.split('Wasserstand am')[1].split('</p>')[0].split(':&nbsp;')[1] }}

inland stag
#

using split makes sense, I was investigating if I can use something like XPath

#

this is working now: {{ value_json.html.split('Wasserstand am')[1].split(' cm</p>')[0].split(':&nbsp;')[1] | replace(',','.') | float(0) }}

jagged obsidian
#

there's probably more ways, this is all i know πŸ˜„

mighty ledge
#
{{ value_json.html | regex_findall(">([0-9]+) cm<")[0] }}
#

also, no need to cast to float

inland stag
#

Hm, this leads to a TemplateSyntaxError: expected token 'end of print statement', got '[') for dictionary value @ data['value_template']. Got "{{ value_json.html | regex_findall('>([0-9]+) cm<')[0] }}".

#

do I need to escape the <>?

mighty ledge
marble jackal
#

None of this is related to templates

mighty ledge
#

deleted messages??

marble jackal
#

Yes, can't remember what it was about, but but about templates

#

I was not referring to your post

frank gale
#

Is there any way to get the last_changed of a device without entities? I have a zigbee device with 3 buttons that sends events and want to template the last_changed of a button

inner mesa
#

devices don't have states

#

you can build a trigger-based template binary_sensor and use its last_changed

frank gale
#

that was my plan if there was nothing else to do πŸ™‚
thank you Rob

mighty ledge
inner mesa
#

but if the device truly has no entities and relies on events, that won't help

frank gale
#

exactly, that doesn't help me. I want to know when a button last pressed, there is no entity for that, it's passed as an event

mighty ledge
#

sorry, i assumed button was the button entity

frank gale
#

I already did a trigger based sensor, but thank you very much for your tip petro

sacred sparrow
#
- trigger:
    - platform: state
      entity_id: light.hallway_front
      attribute: color_temp
  sensor:
    - name: "Hallway Lights - Colour Temp"
      device_class: power
      state: "{{ state_attr('light.hallway_front', 'color_temp') }}"

How can I make it keep the last state when the light is off? Right now its "None" when the light is off. Can i just have the last number is was set to?

#

I am happy to remove the trigger template as its probably not needed

solar hemlock
#

Is there a way to convert any negative number to a positive number, and leave positive numbers and 0 alone? I'm wanting this for a temperature comparison automation.

inner mesa
#

Absolute value?

solar hemlock
#

That sounds right, I'll test now to learn how that works.

#

{{ (states('sensor.temperature_difference_indoor_to_outdoor') | float) | abs }} seems to work great for my purposes. Thank you for pointing me in the right direction.

solar hemlock
#

Any ideas for how I could return a true template when a value changes from positive to negative?

rose scroll
#

You'd need to store the previous value somewhere, then use a boolean test to compare the previous and current values. But why do you want to do that?

inner mesa
#

a trigger-based template binary_sensor with a numeric_state trigger would do it

marble jackal
#

You probably want the trigger, as it will allow the state to be restored after template reload or HA restart

sacred sparrow
#

oh nice one - that makes sense

grand ravine
#

How do I create a sensor that defines the possible outcome in the state, so that the automation trigger UI can detect which possible outcomes there is for the sensor? (quite new to HA)

#

This is what I got:

#
- sensor:
    - name: "Bed status"
      unique_id: bed_status
      icon: mdi:bed
      state: >
        {% if states("binary_sensor.sonoff_door_sensor_2_contact") == 'on'  %}
        open
        {% else %}
        close
        {% endif %}
dusty grailBOT
#

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

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

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

marble jackal
#

You don't need a template sensor for this

#

you just need to assign the right device_class to the binary sensor you already have

mighty ledge
#

if the device has a unique_id, there's a dropdown in the UI that will change the display in the frontend on the device

grand ravine
#

Okay, so you would rather rename the device/entity, then creating new custom sensors?

marble jackal
#

no, we are not talking about renaming devices/entities at all

mighty ledge
#

change show as and it will adjust the words written in the UI

marble jackal
#

(binary) sensors can have a device_class, which determines how they are treated by the frontend (Dashboard)

mighty ledge
#

change show as to door

#

and it will say Open/Close

marble jackal
#

In the link I shared there are multiple device classes which use open/close

#

there is also opening

mighty ledge
#

yep

marble jackal
#

it will also have effect on the icon, if no icon is set

mighty ledge
#

if settings doesn't exist, then you have to do it in yaml

grand ravine
#

What if one wanted to use custom wording like made/unmade?

marble jackal
grand ravine
#

okay, thanks. Appreciate your time

ancient lynx
#

Hi all. Need some help with a notification template. I can never get my head around time-based stuff. I have a travel time sensor that has the commute time in minutes to a my kid's school that has the same pickup time every day. What is the best way to have a notification go off at the travel sensor's value before that fixed time? And maybe plus like a five minute buffer?

marble jackal
#
{% set pickup_time = '15:00' %}
{% set travel_time = states('sensor.travel_time') | float(30) %}
{% set buffer = 5 %}
{{ now() > today_at(pickup_time) - timedelta(minutes=travel_time + buffer) }}
#

The float filter on the second line defaults to 30 minutes now, in case the sensor is not available

ancient lynx
#

Super elegant. Thank you.

#

Haven't heard of the timedelta function. I'll have to look into it more. Appreciate it!

neon laurel
#

is it possible to create a template color_temperature for a light that maps an rgbw light like this:
warmest temperature: 0,0,0,255 (only white channel on)
coldest temperature: 255,255,255,255 (all channels on)

dusty grailBOT
rustic raft
#

aw that was less than 15 lines

inner mesa
#

it was 19

rustic raft
#

less than 15 lines of yaml*

inner mesa
#

doesn't matter

rustic raft
#

noted.

inner mesa
#

and no, what you have there is not valid

#

you cannot generate a bunch of conditions from within a template

#

you can, however, do that with just a template

#

I suppose. I can't really figure out what you're trying to do

rustic raft
#

thanks, that's helpful. It's a blueprint that mirrors the value of one or more select entities into a single select entity. i'm trying to make something similar to a group with custom logic and helper entities.

if i wanted to create multiple yaml conditions from a templated for loop, would i be able to do that in a script?

inner mesa
#

no

#

I'm still not clear on exactly what you want out of those conditions

#

you want to know if a bunch of input_select entities are the same value?

rustic raft
#

" if either of these two entities state's === "active", then [do something]"

inner mesa
#

so that's easy

#

conditions are "and", BTW, so they won't be "or" unless you explicitly specify that

#

anyway:

#

{{ expand(['input_select.x', 'input_select.y'])|selectattr('state', 'eq', 'active')|list|length > 0 }}

#

or

#

{{ 'active' in expand(['input_select.x', 'input_select.y'])|map(attribute='state')|list }}

rustic raft
#

appreciated, i'll slap that in a template condition and it should do what i need it to

inner mesa
#

you can easily test it in devtools -> Templates

lapis quarry
marble jackal
#
new_state.domain == 'binary_sensor' and new_state.object_id.startswith('windowbr') and is_state(enable_window_switch, 'on')
               and new_state.status != 'unknown' and new_state.status != 'unavailable' and new_state.status is not none
               and new_state.entity_id is not none and new_state.object_id is not none
               and is_state(window_auto_on, 'on') and 'tamper' not in new_state.object_id and not new_state.object_id.endswith('batt') ```
#

you are using new_state.object_id.startswith('windowbr') on the first line, while your check new_state.object_id is not none is on line 3

#

acutally you are already using it here {%- set room_number = trigger.event.data.new_state.object_id[-3:-1] %}

lapis quarry
#

Mmmm I see

#

What would be the best aproach to avoid this?

#

I guess I need to wrap this condition in another one that does those checks first

#

would this work better?

    condition:
      condition: and
      conditions:
        - condition: template to make those check? 
        - condition: my template```
marble jackal
#

no, you need to move it to the front of the template

#

but you also have a lot of redundant code in your templates

#

I did an attempt to improve it

#

btw, are you sure you mean new_state.status and not new_state.state ?

#

oh, and I just realized you create a variable with the old_state, but you never use it

lapis quarry
#

i do use old_state in other automations, just a copy paste thing, you are right can be removed in this particular one

#

i guess new_state.state would be right not status

#

but not sure other at this point lol

marble jackal
#

https://dpaste.org/Rqedd improved version with a typo fix, more consistant usage or quote-type, change of status to state and old_state removed

lapis quarry
#

thanks for the example im readind trought it πŸ™‚

marble jackal
#

state would be the standard for the entity state, status would be something custom for these specific entities

lapis quarry
#

then its state

marble jackal
#

I'm also not sure why you are using format to concatenate the strings

#

{%- set window_auto_on_on = is_state('input_boolean.windowbr' ~ room_number ~ '_auto_on', 'on') %} this would work fine as well

#

without format()

lapis quarry
#

because it worked and did what i wanted πŸ€·β€β™‚οΈ

#

its been 2.5 years since i wrote it, i have a bunch of automations using this style, chances are i did need it somwhere else and just copied it from that automation, as i say im not a programmer so this is quite out of my comfort zone ..

marble jackal
marble jackal
#

Oh, and one other thing

#

If you add some checks to your trigger, it would't have to render all these templates on every state change

#

on all your conditions you check for state changes in the binary_sensor domain, why not add it to the trigger?

#

That might also remove the results which cause you to check on all those values being non none

lapis quarry
#

but the trigger is state_changed based, can i make it trigger only when a binary sensor changes state?

marble jackal
#

by adding it to the trigger

platform: event
event_type: state_changed
event_data:
  domain: binary_sensor
lapis quarry
#

ok yes cool that makes a lot of sense

marble jackal
#

You could also add a lot of these variables you create again for each template to automation variables

#

so you won't have to recreate them in each template

#
trigger: []
conditions: []
action: []
variables:
  old_state: "{{}}"
  new_state: "{{}}"
lapis quarry
#

correct me if im wrong but I dont think that could be done back in the day when i wrote this, variables werent introduced yet

marble jackal
#

might be, but no reason to not add that now

#

btw, your approach to do the checks in a separate condition would also remove more redundant code

#

as you now do these checks in every condition

lapis quarry
#

like new state, old_state, room_number, windows_switch, etc, basicaly all the ones im constantly repeating in every section of the automation

#

and also that they will be local variables only persistent inside this automation

#

along these lines

trigger: []
conditions: []
action: []
variables:
  new_state: "{{trigger.event.data.new_state}}"
  old_state: "{{trigger.event.data.old_state}}"
  room_number: "{{trigger.event.data.new_state.object_id[-3:-1]}}"
  sensor_type: "{{trigger.event.data.new_state.object_id}}"
  window_switch: "{{"input_boolean.enable_windowbr" ~ '{}'.format(room_number)}}"
  window_auto_on: "{{is_state('input_boolean.windowbr' ~ room_number ~ '_auto_on', 'on')}}"
  window_auto_off: "{{is_state('input_boolean.windowbr' ~ room_number ~ '_auto_on', 'off')}}"```
#

and now i can use these variables without declaring them inside every condition, right?

marble jackal
#

correct, they are available in the entire automation, besides for the trigger

#

not sure why the bot compains about your yaml

#

the only thing is that you might need to check for the object_id not being none

lapis quarry
#

im testing it and the config checker also complains so the yaml must be wrong

marble jackal
#

so:

  room_number: "{{ new_state.object_id[-3:-1] if new_state.object_id is non none else none }}"
lapis quarry
#
in "/config/automations/Windows Automation Template.yaml", line 106, column 7
expected <block end>, but found '<scalar>'
in "/config/automations/Windows Automation Template.yaml", line 110, column 26
marble jackal
#

and you can use the variables you declared, so no need to use trigger.event.data.new_state if you already declared that to be new_state

marble jackal
lapis quarry
#

ok let me dig a little

marble jackal
#

okay, I'm actually going to work now πŸ™‚

lapis quarry
#

no worries, thanks men, ill try to implement all your sugestions see where it takes me πŸ˜‰

#

its defenitly when i add the variable line that breaks the config checker:

    action:
    variables:
      new_state: "{{ trigger.event.data.new_state }}"```
marble jackal
#

I assume you are on a recent version of HA?

lapis quarry
#

latest release

marble jackal
#

and you have at least one action, or [] to define an empty list?

lapis quarry
#

all the same automation as before, but when I add this line after action adding the variable i get the error

marble jackal
#

it should be after all the actions

#

so

action:
  - some action
variables:
  some_variable:
#

not:

action:
variables:
  some_variable:
  - some action
lapis quarry
#

at the end of the automation? I need the variables declared to use them in the the action

marble jackal
#

I know

#

that doesn't matter, it will load them after the trigger

#

the order in the dictionary is not relevant

#

but you can also put it before action

lapis quarry
#

ok that fixed it placing it after the first action

lapis quarry
#

thanks for the help ill keep chiping at it, will be back for sure πŸ‘

marble jackal
#

it will be available in the condition as well, so if you want the most logical order, but it right after the triggers

lapis quarry
#

yes that is what i did makes more sense

marble jackal
#

you can also define variables in the action sequence, but they won't be available in the conditions then:

action:
  - variables:
      some_variable:
  - service: some.service
lapis quarry
#

i need them available in both as i have sequences and conditions that both use the same variables

marble jackal
#

yes I know, it was just FYI πŸ™‚

lapis quarry
#

I need to correct my self, its actually its not working, i have tried to add the variables in a bunch of places in the automation and cant seem to add them without the config checker complaining, (i made a mistake before as I was editing wrong file as i have multiple windows open) i need to go now, working from home but wife just got back and need to take care of some stuff, will be back later see if we can implement this πŸ™

lapis quarry
#

im back, been trying to figure stuff out one by one

lapis quarry
#

would this also be correct to the state_change ongly triggers on only those 2 domains?

marble jackal
#

nope

#

then you need 2 triggers

mighty ledge
#

have to use a template condition

#

or that

marble jackal
#

proably a combination

mighty ledge
#

shouldn't have to if he's using 2 triggers

marble jackal
#

I've seen the rest of the automation πŸ˜›

mighty ledge
#

ah

#

you and you're insider info

#

that's illegal

lapis quarry
#

its all posted here LOL

marble jackal
#

You could as well, just scroll up a bit

mighty ledge
#

that requires effort

marble jackal
#

Trying to remove a lot of redundant code from his automation

lapis quarry
#

i do have a specific question for you petro:

lapis quarry
mighty ledge
#

what code?

lapis quarry
#

here

mighty ledge
#

I just copied what you originally had

#

if new_state is a state object, status isn't valid

lapis quarry
#

so state is right, just wanted to confirm

#

cool

#

TheFes, for adding the the variables I cant get them to pass the config checker no mattter what i have tried 😦

marble jackal
#

.share the entire automation

dusty grailBOT
#

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.

lapis quarry
#

anywhere i have tried to add them in the automation it doesnt pass

marble jackal
#

and the error code

lapis quarry
#

its prett much the same havent changed anything yet lol

#

just trying to add the variables (havent aplied any of your sugested changes yet) but han on i will share again

mighty ledge
#

I'm guessing you're a process engineer IRL?

lapis quarry
lapis quarry
marble jackal
#

I don't see variables anywhere

#

I need to know what you are trying to see what is wrong

lapis quarry
#

yes they are not there, this is the working code, what im saying no matter where i add variables in any portion of the code it breaks

#

can you mention the line where i should add them i will test please?

mighty ledge
lapis quarry
#

lol

marble jackal
#
  - alias: "Windows Automation"
    mode: parallel    
    max: 30
    trigger:
    - platform: event
      event_type: state_changed
      event_data:
        domain: binary_sensor
    variables:
      variable_here: 1
      and_another_one:
    condition:
      your_code:
lapis quarry
# mighty ledge I was just asking cause you're doing all this prep work without changes 🀣

short story is basicaly i have a working supervised install at a rental house i have a few hundred miles away and im cloning it to a new HAOS install at my home and trying to fix all breaking changes and updates so i can just go over there and swap one for another, i cant afford to break the working install and its running on a raspian that hasnt been updated in 3 years expposed to internet with malware currently on it so i need to fix it

lapis quarry
#

i get the same error no matter where i try to add the variables section in the code

#

i can share the full code but its the same as the first link

marble jackal
#

what is the code which generates this error

lapis quarry
#

adding

    variables:
      new_state: "{{trigger.event.data.new_state}}"
#

as per your intructions

#

if i comment it out it works

#

only diference is adding the variables as you told me to do

mighty ledge
#
      window_switch: "{{'input_boolean.enable_windowbr' ~ '{}'.format(room_number)}}"
#

uh, that's also poorly written

#
      window_switch: input_boolean.enable_windowbr{{ room_number }}
lapis quarry
#

TheFes also pointed it out allready thanks 🀣 🀣 🀣

mighty ledge
#

yes but that's what your error was coming from

#

in "/config/automations/Windows Automation Template.yaml", line 15, column 7

#

points directly to the error

#

it's hard to tell because you have those 2 commented out lines

#

which are not counted in the line number

sudden parrot
#

Hi all, newbie here. One of my sensors is not loading on restart.
- sensor: - name: "^DJI Trending Color" statae: > {% if state_attr("sensor.yahoofinance_dji","trending")=='up' %} rgb(38,209,88) {% else %} rgb(255,69,58) {% endif %}

#

I even did a power set on the RPI3B

sudden parrot
#

😩 damn

mighty ledge
#

πŸŽ‰

#

sometimes you just need new eyes on a problem

lapis quarry
#

i dont get the column thing

mighty ledge
#

number of characters

sudden parrot
marble jackal
#

this looks suspicious

#

use single quotes inside the template, that is probably causing the error

mighty ledge
#

you have 7 spaces

#

it's saying "that whole line is fucked", paraphrased

#

and it starts getting fucked at the 7th character

lapis quarry
#
      window_switch: "{{ window_switch: input_boolean.enable_windowbr{{ room_number }}"```
mighty ledge
#

no

#
      window_switch: input_boolean.enable_windowbr{{ room_number }}
#

or

#
      window_switch: "input_boolean.enable_windowbr{{ room_number }}"
#

both are fine

marble jackal
#

or

      window_switch: "{{ 'input_boolean.enable_windowbr' ~ room_number }}"
#

so with single quotes inside, and double quotes outside the template

mighty ledge
#

Personally I try to avoid string concatenation if I can

lapis quarry
#

and yes now it passes config test πŸ‘

#

let me restart and see

marble jackal
#

you can just reload automations

mighty ledge
#

If you want to avoid worrying about quoting, use multiline notation

lapis quarry
#

yep seems to work now πŸ˜„

#

so this other set line im using ```yaml
set enable_window_switch = "input_boolean.enable_windowbr" ~ '{}'.format(room_number)

would be writen like this correctly as variable:

enable_window_switch: input_boolean.enable_windowbr{{ room_number }}

marble jackal
#

not within a template

#

but the last line is fine as a variable

lapis quarry
#

ok cool

#

let me simplify this a little and then i can get back to your sugested code from before try to implement it πŸ‘

marble jackal
#

something like this is also valid:

some_variable: switch.{{ other_variable }}_on
lapis quarry
marble jackal
#

well yes, but that was before you started using variables

#

because I still create the same variables in the template there

lapis quarry
#

yes

marble jackal
#

if you use variables, it can be shortened a lot

lapis quarry
#

which i simplified like this

#

removing all the set statements

marble jackal
#

you can format code as jinja instead of yaml if you just post templates

#

same for dpaste (it's django/jinja there)

#

and you could the first part in a separate condition

lapis quarry
marble jackal
#

as it is the same for the others

#
- condition: template
  value_tempalte: >
    {{
      new_state.object_id is not none and new_state.entity_id is not none and new_state.state is not none
      and new_state.state not in ['unavailable', 'unknown'] and not new_state.object_id.endswith('batt') 
      and 'tamper' not in new_state.object_id and (new_state.object_id.startswith('windowbr') or new_state.object_id.startswith('doorbr'))
    }}
- condition: template
  value_tempalte: >
    {{ enable_window_switch_on and (window_auto_on_on or window_auto_off_on) }}
lapis quarry
#

not in is the same as !=?

lapis quarry
marble jackal
#

'banana' not in ['banana', 'apple'] would return false
'banana' != ['banana', 'apple'] wourld return true

#

so it's not the same

marble jackal
#

the first condition is the same for all 3, if not, move the part which is not the same to the separate conditions

#

but most of it will be the same

lapis quarry
#

does this look like what you meant?

#

and now next in the action section i can also remove all the set = X and take advantage of the variables right

marble jackal
lapis quarry
#

sometimes i dont know if i hate you or envy you or love you or what I feel, you make it seem so easy 🀣 πŸ‘

#

yes makes sense a lot simpler

#

let see if i dont break anything πŸ™

lapis quarry
#

followed all your sugestions, removed all set functions as they are variables now, used your code as trigger condition, formated everything a little better and so far it seems nothing broke, at least HA restared fine πŸ˜…

#

i guess there is till a lot of redundant code but its a rabbit hole, i just wanted to get rid of the warnings in the logs 🀣

#

Actualy I need to thank you TheFes, im reading the code again now and I can allready see how i can implement all your sugestions further down the code to simplify things further in a similar way πŸ₯°

shell cypress
#

Hi all, I have a problem to setup the value template for a rest sensor correctly.
I get a list of values like this:
[{"datapoints":[[49.96519,"2022-09-16 13:55:23"],[49.9658,"2022-09-16 13:55:24"],.....
and I want to extract only the 49.96519 as value.
My current template looks like this:
value_template: "{{ (value_json.datapoints[1][0]) | round(2) }}"
but it just gives "undefined".

mighty ledge
#

many many errors

lapis quarry
#

im sure i have

#

that is why i was ashamed of sharing my code, but hey it worked

#

Petro im a highschool dropout im not an enginner and a lot less a programmer 🀣

#

but if you would kindly point them out maybe i can learn something

mighty ledge
#

I just have some questions

lapis quarry
#

sure

#

what would you like to know?

mighty ledge
#

sensor_type

#

does it contain the room number

#

your object_id

lapis quarry
#

it might, or might not, not all my binary sensors contain the room number as i have some unrelated to rooms

mighty ledge
#

so how do you know you have a valid room_number?

#

you have all these conditions in place, yet you don't know if you have a room number

#

also, is room number... a number

lapis quarry
#

if the sensor is named either doorbr, windowbr, doorlr, windowlr, doorkitchen or windowkitchen it contains the number i need

#

so for instance doorbr01a

mighty ledge
#

ok

lapis quarry
mighty ledge
#

ok

lapis quarry
#

the reason i did it this way is i wanted the template to be transparent, no matter if i have 1 sensor or 50

#

if i add a new sensor it should just work as long as the sensor has the right name

mighty ledge
#

yes I understand this

#

but you have 909840598304958 if statements that can be extinguished

#

just give me a moment

lapis quarry
#

sure take your time

tepid onyx
#

that is one massive automation πŸ˜€

lapis quarry
#

🀣 its only one of a few same style πŸ˜…

mighty ledge
#

same crap?

#

doorbr01 or windowbr01?