#templates-archived

1 messages Β· Page 12 of 1

mighty ledge
#

You have to get the temperature as a separate template sensor

queen girder
#

I'm not looking for temperature. I have that working.

#

I want state (heating/idle/cooling) as a sensor. But using the above template, it's returning as if it expects units in Farenheit

heavy crown
#

Interesting challenge (I hope)

#

I have a sensor with two attibutes

#

date and value

#

I want to select on the date to collect the value but only (!) the first and last one of that date

#
date
  - 2022/10/07
  - 2022/10/07
  - 2022/10/07
  - 2022/10/07
  - 2022/10/08
  - 2022/10/08
value
  - A
  - B
  - C
  - D
  - E
  - F
#

I would like to have A and D returned

#

How can I find the index of A and D (i.e. 0 and 3) ? I would also be happy if the list can be truncated/split out from the values not equal to 2022/10/07, then I could use count for last index and 0 for first

marble jackal
# heavy crown ``` date - 2022/10/07 - 2022/10/07 - 2022/10/07 - 2022/10/07 - 2022/10...
{% set date = [ "2022/10/07", "2022/10/07", "2022/10/07", "2022/10/07", "2022/10/08", "2022/10/08" ] %}
{% set value = [ "A", "B", "C", "D", "E", "F" ] %}
{% set search_date = "2022/10/07" %}
{% set i_first = date.index(search_date) %}
{% set i_last = i_first + date | select('search', search_date) | list | count  - 1 %}
{{ value[i_first] }}
{{ value[i_last] }}
heavy crown
floral shuttle
#

using - unique_id: here_destination name: Here destination state: > {% set select = states('input_select.destination') %} {% if select == 'Thuis'%} {% set destination = 'zone.home' %} {% elif select in ['Marijn','Members','Family'] %} {% set destination = 'person.' ~ select|lower %} {% else %} {% set destination = 'zone.' ~ select|slugify %} {% endif %} {{destination}} I get the name of the entity alright showing either person.marijn or zone.home but using that template sensor as an input for the Here traveltime wont see that state as input in a Map....

#

it this because of an issue in the template, or would it be the specifics for the Here integration. Aware the outcome of the template is a string, this might be it?

plain magnetBOT
marble jackal
#

I don't think it accepts templates

#

You use an input select and an automation to select the option you need

floral shuttle
#

yeah, I was moving from templated input_selects with a name (and rebuild the lat/long in the attributes, to a direct zone/person in the state (see above). that wont work though, because it isnt a true tracker, but a string.. Have to use the real trackers in the select, and then template those names. just the other way around...

proven fog
#

Any idea why {{ expand(area_devices('Master Bathroom')) }} returns nothing? area_entities works fine

mighty ledge
#

expand doesn't expand devices

#

it expands entities

#

@proven fog ^

#

there's no reason to use area_devices if you're trying to get an area's entities

#

if you want device names, then that's a different story.

proven fog
#

I want device names

inner mesa
#
{% set ns=namespace(names=[]) %}
{% for id in area_devices('Family Room') %}
  {% set ns.names=ns.names+[device_attr(id, 'name')] %}
{% endfor %}
{{ ns.names }}
#

I don't know why device_attr can't be used as a filter...

wicked parrot
#

I've got a ping binary sensor pinging a machine to see if it's awake or not every 30 seconds. That state is being fed into a switch template which runs a wake/suspend script when turning on/off. When I flip the switch to off I can see the switch flip back to on and be in that state until the next ping cycle happens. Is there a way to have the switch template hold it's state until the binary sensor's value changes?

#

Really hoping there's an easy solution that doesn't require me to automate flipping another toggle somewhere else.

mortal harness
#

Hello All,
Total noob question here...
I have a binary sensor attached to a reservoir tank which activates when the water level gets low. The sensor is called: binary_sensor.grow_reservoir
The sensor is integrated with ESPHome and seems to be working fine - the only thing is that it returns "on" "off" and I would like to customise these values.
I understand that I need to do this in a template which I have written in configuration.yaml and tested in Developer Tools > Template
configuration.yaml loads fine.
However when I check the output of the sensor in an entity card on the dashboard it just returns "on" for it's value.
Do I have to apply the template in the card or somewhere else for it to work?
Thanks...

mortal harness
inner mesa
#

you've managed to spell "reservoir" three different ways πŸ™‚

#

that template doesn't change the original sensor, it creates a new one

#

you can't "customize" an existing sensor, you need to create a new one that reports the values that you care about, which is seems like you have, but these two statements appear to conflict:

#

I have a binary sensor attached to a reservoir tank which activates when the water level gets low. The sensor is called: binary_sensor.grow_reservoir

#

{{ 'Resovoir Full' if is_state('binary_sensor.grow_resorvoir_water_level', 'on') else 'Rasorvoir is empty' }}

mortal harness
# inner mesa you've managed to spell "reservoir" three different ways πŸ™‚

Thanks Rob,
Yea, that was a bit embarrassing, I just corrected the spelling while you were replying 😊
Also the incomplete name for the sensor was a weird cut and paste, they are the same in the name and correct.
So once I have created the Template, Home assistant creates a new sensor that I can use in the card, right?

inner mesa
#

yes

mortal harness
#

Thanks very much for your help. Much appreciated.

quiet niche
#

Folks, I need help. I think it's some kind of punctuation or syntax... N

#
      state_topic: "openevse/temp"
      device_class: temperature
      unit_of_measurement: "Β°C"
      value_template: "{value | states(entity_id) * 0.1 }"```
#

Just need to divide the MQTT topic by 10

#

I'm on my 12th check config > reboot

inner mesa
#

that's pretty weird syntax

#

what is states(entity_id) doing there?

quiet niche
#

I'm just copying out of the documentation πŸ˜›

inner mesa
#

I hope not

#

where?

quiet niche
#

and trying everythign!!!!

inner mesa
#

value_template: "{{ value * 0.1 }}"

inner mesa
#

that's referring to the previous value

quiet niche
#

ah I see...

inner mesa
#

in any case, value | states(entity_id) doesn't mean anything

quiet niche
#

I thank you for your help - I find the documentation assumes the reader has a LOT of prerequisites

#

for fluency in yaml, jinja, etc

#

So RobC - It's still not rendering...

#
- name: "OpenEVSE Temperature"
      state_topic: "openevse/temp"
      device_class: temperature
      unit_of_measurement: "Β°C"
      value_template: "{{ value * 0.1 }}"
inner mesa
#

what does that mean?

#

It's still not rendering...

quiet niche
#

Sensor state is coming back unknown (Others from the device are fine, but I don't need to math on them)

inner mesa
#

what do your logs say?

quiet niche
#

TypeError: can't multiply sequence by non-int of type 'float'

#

Exception in message_received when handling msg on 'openevse/temp': '317' Traceback (most recent call last): File "/usr/src/homeassistant/homeassistant/components/mqtt/debug_info.py", line 44, in wrapper msg_callback(msg) File "/usr/src/homeassistant/homeassistant/components/mqtt/sensor.py", line 297, in message_received _update_state(msg) File "/usr/src/homeassistant/homeassistant/components/mqtt/sensor.py", line 262, in _update_state payload = self._template(msg.payload, default=self._state) File "/usr/src/homeassistant/homeassistant/components/mqtt/models.py", line 234, in async_render_with_possible_json_value return self._value_template.async_render_with_possible_json_value( File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 583, in async_render_with_possible_json_value return _render_with_context( File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 1915, in _render_with_context return template.render(**kwargs) File "/usr/local/lib/python3.10/site-packages/jinja2/environment.py", line 1301, in render self.environment.handle_exception() File "/usr/local/lib/python3.10/site-packages/jinja2/environment.py", line 936, in handle_exception raise rewrite_traceback_stack(source=source) File "<template>", line 1, in top-level template code TypeError: can't multiply sequence by non-int of type 'float'

inner mesa
#

alright

#

value_template: "{{ value|float * 0.1 }}"

quiet niche
#

ah - It's a string then, and it's gotta get converted to a float...

#

THEN we can math it.

#

Now, as far as the publishing device, and this is more an MQTT question, but I didn't' know there were data types in an MQTT

inner mesa
#

it's JSON

#

numerical values should be published as numerical values, but 🀷

quiet niche
#

Gotta take that up in C++ on the publishing device..

#

I acctually notice this in lots of integrations, HACS for the car shows the range on the EV for example as that beautifully colored bar graph...

inner mesa
#

at least it "should" be JSON. in this case, it looks like it's just a raw value, which is interpreted as a string

quiet niche
#

Brilliant man, I think this is it, the data types. Thanks @inner mesa

#

So sir, interestingly, when these raw values come in and I apply a device class and unit of measurement to them (current, for example) this whole raw value thing goes away merrily

#

or the problem with it anyhow

inner mesa
#

I see some special casing in the code for dates and timestamps, but not numeric values. I guess it could be there somewhere

obsidian lintel
#

Whats the equivalent of not equals if equals is 'eq'.

#

oh its ne

devout halo
#

Newbie here, can anybody help me with messages tempates in trigger context

buoyant pine
#

Just ask your question @devout halo πŸ˜„

acoustic arch
#

this is doesnt trigger the automation:
{{ (as_timestamp(states("sensor.mob_harro_next_alarm"), 0) | round(0)) == (as_timestamp(now()) | round(0)) }}

#

i can see it working in development tools templating, when i make a countdown timer of it...

marble jackal
#

Because now is evaluated every minute. So I think im your system might be a little slow, so it rounds to 1 second over the minute, making you missing the match

mighty ledge
#

that's a pretty over engineered alarm template

marble jackal
#

And that

acoustic arch
#

hahahahaha! touchΓ©

#

im looking for 20min before next alarm

#

and the error catch when none is set....

mighty ledge
#

what's the format of snesor.mob...

#

state

acoustic arch
#

2022-10-10T05:15:00+00:00

mighty ledge
#

will it always have the timezone?

acoustic arch
#

which is odd because its actually 7:15

mighty ledge
#

that's not odd, your timestamp is in UTC

#

not local

marble jackal
#

Which is correct, because you are at GMT +2

acoustic arch
#

ok got it

mighty ledge
#

{{ states("sensor.mob_harro_next_alarm") | as_datetime >= now() }}

acoustic arch
#

we are now +1 AND +1 summertime

marble jackal
mighty ledge
#

hah, was just going to say that

acoustic arch
#

sorry.... WE as in me....

#

netherlands

marble jackal
#

Same here

acoustic arch
#

TheFes and me at least

#

lemme try yout solution petro

mighty ledge
#

{{ now() >= states("sensor.mob_harro_next_alarm") | as_datetime }}

#

if you want 20 minutes

#

{{ now() >= states("sensor.mob_harro_next_alarm") | as_datetime - timedelta(minutes=20) }}

acoustic arch
#

what if a second alarm is set...

marble jackal
#

I do had some people saying that caused unwanted triggers

acoustic arch
#

the sensor hops directly to the next, not triggering..?

mighty ledge
#

if a second alarm is set, it will turn false

#

when you set the second alarm

marble jackal
#

Yep, I was just about to say that

mighty ledge
#

and then turn true again later

acoustic arch
#

so when 2 alarms are set it only triggers on the last one?

mighty ledge
#

you're not making sense

acoustic arch
#

ofcourse i dont

mighty ledge
#

how can 1 entity have 2 alarms

#

at any given moment, it will have 1 alarm

#

so if you set it twice throughout the day, both will trigger unless you set it 1 minute apart

marble jackal
#

The problem with this sensor is that it changes to none or the next alarm before now() is rendered again

acoustic arch
#

ok let me try your 20min solution. brb

#

and also setting a second alarm as test

mighty ledge
#

but, that could be built in for safety

marble jackal
#

Okay, sorry unavailable. It's indeed as_datetime which makes it none

acoustic arch
#

ok well.... i cant even get a light to turn off when my alarm goes... lol

#

when no next alarm is set i get: TypeError: '>=' not supported between instances of 'datetime.datetime' and 'NoneType'

#

thats what you are talking about

#

i pasted this in dev tools so i can see the countdown to zero which works. But then it doesnt go TRUE

#
{{ now() >= states('sensor.mob_harro_next_alarm') | as_datetime }}```
#

hence my guinee pig light not turning off

#

hahahaha still no go..... man man man

inner mesa
acoustic arch
#

could this be the problem for this solution? {{ now() >= states("sensor.mob_harro_next_alarm") | as_datetime }}
As soon as it should go to TRUE the sensor is reset to 24x60x60= 86400 seconds, hence its not triggering

#

in fact. dev tools trow an error for brief second and then showing 86400 again

#

so TRUE is never catched

#

So.... if i add a timedelta of at least a couple of seconds there is a timeframe where it IS true....

#

bingo

#

so waiting for that exact moment when 2 timestamps are the same is never catched indeed

marble jackal
#

It will throw an error every minute when there is no alarm set though

acoustic arch
#

But even when it is set, i saw the error for that split second

#

how can i catch the error with {{ now() >= states("sensor.mob_harro_next_alarm") | as_datetime - timedelta(minutes=20) }} when no alarm is set?

marble jackal
#
{% set alarm = states('sensor.pixel_5_next_alarm') | as_datetime %}
{{ now() >= alarm - timedelta(minutes=20) if alarm else false }}
#

Replace with your own sensor

acoustic arch
#

well my overengineered smartsocket to charge a mobile phone in the night is complete hahaha

#

evil Mandrak laugh

#

thank you both for the help

valid hatch
#

Is this the right channel to talk about issues I am having with a Template Lock?

trail estuary
#

I am trying to have a template return only a specific object in a list.
I have this template

{{state_attr('sensor.nordpool_kwh_bergen_nok_5_096_025', 'raw_today') | sort(attribute='value') | map(attribute='start') | list}}

which gives this output: https://hastebin.com/awuyaruqol.json
How can I have the template return the first (or fifth) element in that list?

inner mesa
#

|first

#

Or [5]

buoyant pine
#

fifth would be [4]

mighty ledge
#

If you use first, make sure to use |default after

trail estuary
#

| first works, but I cannot get [x] to work? Where do use it? I only get TemplateSyntaxError: expected token 'name', got '['...

mighty ledge
#

Before using []

#

Or set your call equal to a variable, then use the []

trail estuary
#

Ahh!

#

Perfect!

trail estuary
#

I think this works as I intended... Let me know if this is gonna blow up in the future because of something I have not foreseen...

{{ ((state_attr('sensor.nordpool_kwh_bergen_nok_5_096_025', 'raw_today') | sort(attribute='value') | map(attribute='start') |list()) [3] |as_timestamp | timestamp_custom('%H') | int) == (now() | as_timestamp | timestamp_custom('%H') | int)}}
#

This lists all hours today and sorts them based on cost of electricity. It compares the current hour with the hour pulled from the list. I am planning to make maybe 10 of these template sensors to pull the 10 cheapest hours, trying to shift energy usage towards those hours....

#

Maybe a cleaner way to do this is not to make a bunch of template sensors, but check if the current hour is one of the first X objects in the list?

#

Any way to do that?

valid hatch
trail estuary
#

This template

{{(state_attr('sensor.nordpool_kwh_bergen_nok_5_096_025', 'raw_today') | sort(attribute='value') | map(attribute='start') | list()) [0:2] }}

provides this output

[datetime.datetime(2022, 10, 10, 2, 0, tzinfo=zoneinfo.ZoneInfo(key='Europe/Oslo')), datetime.datetime(2022, 10, 10, 1, 0, tzinfo=zoneinfo.ZoneInfo(key='Europe/Oslo'))]
#

How can I convert each of those items to a timestamp?

#

If I add a filter | as_timestamp I get an error saying that as_timestamp got an invalid input...

mortal harness
#

Hello,
I need a bit of help with a template, please.
I have the following code in my configuratoin.yaml file to change the values of a binary-sensor (water) to something readable:

template:

  • binary_sensor:
    • name: Grow Reservoir Status
      icon: mdi:cup-water
      state: >
      {{ 'Reservoir Full' if is_state('binary_sensor.grow_reservoir_water_sensor', 'on') else 'Reservoir Empty' }}

When I check the statement in Developer Tools > Template the output is the desired result 'Reservoir Full' or 'Reservoir Empty', however when I add the template sensor to a dashboard I just get an 'On' or 'Off' output.
Also when I add the templated sensor to the dashboard, it reads as 'Off' when the physical sensor (binary_sensor.grow_reservoir_water_sensor) reads as 'On'

Any ideas, please? And thanks for any help offered...

trail estuary
#

@mortal harness You have created a template binary sensor. Binary sensor only have the states on/off, depending on if the template evaluates to true or false

mortal harness
marble jackal
silent vector
#

With auto entities I'm trying to list devices in an area then hopefully with a pop-up list the entities associated with the device.

Doesn't list anything but it says this template listens for 2ded089b802ac773ae109a297b171ae5 which is the device id of the device currently in the area

trail estuary
marble jackal
#

If you first map it to a timestamp yes

#

Just tested it, this works: {{ [ now() ] | map('as_timestamp') | map('timestamp_custom', '%H:%M') | list }}

trail estuary
#

Very cool! πŸ™‚

silent vector
trail estuary
# silent vector Anyone have any ideas on this?

Not my area of expertice, but I beleive expand(area_devices()) will include any devices in a area that you have created. Unless you have created an area named Temperature Sensors I don't think that will give any output.

silent vector
#

I did create an area called 'Temperature Sensors' it's tracking the device but not listing it.

trail estuary
#

And named it Temperature Sensors?

silent vector
#

Yes

#
Result type: list
[]
This template listens for the following state changed events:

Entity: 2ded089b802ac773ae109a297b171ae5
#

That's the correct device id but nothing is shown in the list. I would want the device name of course but device id is a starting point hopefully.

dusty grailBOT
mighty ledge
silent vector
#

Auto entities can? I think

mighty ledge
#

yes, but you're outputting the device

#

what CARD displays devices?

#

by id

silent vector
#

More or less was hoping using the Id, we can get the entities associated with the device.

#

I don't know if this is fully possible. The idea would be to tap on a device a pop-up happens and the associated devices appear.

#

Rather than listing all of them all at once.

mighty ledge
#

if you want entities from the device, just use area_entities

mighty ledge
#

so I keep asking you "what card can display a device"

#

and the answer is "No cards can display a device"

#

so, you can't even get step one of your 2 step process

silent vector
#

Ok lol. I was hoping it could be possible.

#

To have a clean page where I tap to see entities associated to a device vs all device entities in an area being displayed all at once which gets cluttered fast.

#

Maybe a wth topic

silent seal
#

Isn't that the device page?

silent vector
silent seal
#

The link I provided?

mighty ledge
# silent seal Isn't that the device page?

Is there a card that shows a device? Thomas's auto-entities card can only use cards that exist. If there isn't a "display this device via the device_id" card, then nothing will work

#

I don't use devices, so I don't know the answer to that. There may be a card that displays devices.

silent seal
#

I'd use the template in the Markdown card if I really wanted all the device entities listed together

#

Someone in here had something a while ago for getting the device ids from entities, but I never bothered with it as for me it makes more sense to grab all the temperature sensors and put them together regardless of the physical device involved

mighty ledge
#

and there's no tap action, so it wouldn't lead to his entities when clicked

#

He could use a custom button card that displays specific information, but that doesn't have access to jinja

#

so he'd have to build the logic from the auto-entities card

plain magnetBOT
mighty ledge
silent vector
mighty ledge
#

Nope, not sure if it’s possible

silent vector
#

Interesting. Would be nice. The only reason I would do this is because I would rather have temperature and humidity in the same place for each device. Keeping it clean if I want to see a specific room I only will see that room not 30 rooms all at once.

tacit sun
#

new to templates (15 mins in)... I've worked out what sensors/values to compare. got a if/then template working in the dev template tool... but... not sure how to convert that to a condition in an automation... I assume I'll use template condition... just not sure of the template logic for it... :\

#

can someone offer assistance?

silent seal
#
{{ states('sensor.outdoor_temperature') | int > states('sensor.climate_min_temp') | int }}

or something similar

tacit sun
#

This did it. πŸ™‚ Thanks!

#

Followup question: should I create 2 conditions? One for Less than, and another for Greater than?
-or-
is there an easy way in the template to say less than this and greater than that?

silent seal
#

Take a step back and explain what you're trying to do πŸ™‚

tacit sun
#

I'd like the condition to be:
outdoor temp > climate min temp
and outdoor temp < climate max temp

#
  • My ecobee is in auto mode (with a heating setpoint, and cooling setpoint)
  • If my front door is open, I'd like to notify someone only if:
    -- the outdoor temp is outside of the range of setpoints
#

thoughts?

buoyant pine
tacit sun
#

will that trigger after the door has been left open all day, and the temp dips down?

#

or, only at the single point that the door has been open for 1 min

#

this is something I get hung up on a lot...

#

essentially, I want to leave my door open while it's nice, and have a reminder to close it when it is no longer nice enough to leave it open

buoyant pine
#

ah, i see

tacit sun
#

I think what you provided is good for accidentally leaving it open when it's not nice.

#

I am going to look into template triggers... πŸ™‚

buoyant pine
#

yeah, one sec

tacit sun
#

trigger: outside temp moves outside of the "good range"
condition: door is open for 1 min
action: notify door should be shut

buoyant pine
#

that will trigger when the door is open for one minute and the temp is outside of the range OR if the temp goes outside of the range and the door has already been open for at least a minute

#

you could also simplify it by making a template binary sensor that's on when the door is open and the temp is out of the ranges and set delay_on to 1 minute and use that as the trigger

tacit sun
#

You're awesome! I love having working examples to work with. πŸ˜„

#

yeah... I think I'm finally at the point I can start learning more about templates.

buoyant pine
#

templating is nice

#

took me a while before it finally clicked, but it opened up many other possibilities when it did

tacit sun
#

I have always known it's more flexible than straight up automations... but, my phases of learning tend to be: 1) freak out 2) get overwhelmed 3) freak out again 4) start to understand
lol

#

Well, thank you for your help, and also to Rosemary Orchard.

rocky crypt
#

Hello. I am wanting an automation to run while the word "ready" doesn't exist in a state field. I know the repeat function will run while it return true, so this is what I have for my repeat value_template: "{{ ('Ready ' in states('sensor.sub_alarm_panel_message') == false) }}"
However, it's not working. It doesn't repeat at all. Would that be the correct way of doing it?

marble jackal
#

I would use {{ not 'Ready' in states('sensor.sub_alarm_panel_message') }}

#

and what is your entire code for the repeat?

vast plover
#

Hi, does anybody know how to count persons, who are "not_home"? The counter for persons at home works at me, not_home doesnt (I editted sensor.yaml)

#

petro answered: templates. "{{ states.person | selectattr('state','eq','not_home') | list | count }}", if you have questions -> templates

#

I inserted this:

#

{% set count = [states.person | selectattr('state','eq','not_home') | list | count %}

#

konfiguration invalid...

arctic sorrel
#

That's not what Petro gave you, why did you change {{ to {%?

vast plover
#

how can I insert the code here? I changed to {{ and it is invalid

#

/config/sensor.yaml

#

Zaehler Persons away

#

number_persons_away:

#

friendly_name: 'Persons away'

#

value_template: >

#

{{ states.person | selectattr('state','eq','not_home') | list | count }}

marble jackal
#

do you use other zones besides home?

vast plover
#

no. Status is home or not_home or something like unavailable

#

At the moment, my wife and me are "not_home"

mighty ledge
#

if you're putting it in sensor.yaml, you're missing the header

#
- platform: template
  sensors:
    number_persons_away:
      friendly_name: 'Persons away'
      value_template: >
        {{ states.person | selectattr('state','eq','not_home') | list | count }}
vast plover
#

I will try, but number_persons_home works without header

#

platform: template starts with - platform: template
sensors:

Time

time_of_day:
#

then number_persons_home

#

\test

#

\test

#

`test

#

Β΄test

#

'i dont know how to insert code here

#

test

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).

vast plover
#
thank you
mighty ledge
vast plover
#

Yes, I am sure that this works. /config/configuration.yaml ```

Configure a default setup of Home Assistant (frontend, api, etc)

default_config:

Text to speech

tts:

  • platform: google_translate

group: !include groups.yaml
automation: !include automations.yaml
script: !include scripts.yaml
scene: !include scenes.yaml
sensor: !include sensor.yaml
...

#

is that right? I think so

mighty ledge
#

i.e. platform: template has different fields in relation to platform: tod

rocky crypt
mighty ledge
#

personally, I think it reads better if you have

{{ 'Ready' not in states('sensor.sub_alarm_panel_message') and repeat.index < 20 }}
rocky crypt
#

Oh! Ok. So don't need not at the beginning and that solves the whole line not being "not" πŸ™‚

mighty ledge
#

the whole line wouldn't have been not

#

it would have only been the first condition

#

code has order of operations that are implied

rocky crypt
#

Even if I didn't use the extra parenthesis around the first condition?

mighty ledge
#

everything before the and is resolved before everything after the and is checked

#

Yep, even if you don't use the extra parenthesis

rocky crypt
#

Gotcha! That's why I added the extra parenthesis is because I thought it would do the whole line πŸ™‚ Learn something new every day πŸ™‚

mighty ledge
#

personally, i'd also reverse those and's as well

#

if you're beyond 20, there's no reason to check if ready is in the state.

rocky crypt
#

That makes sense πŸ™‚

mighty ledge
#

if the first condition fails, the second condition is never checked

#

it works that way with or as well. If the first condition passes, the remaining arn't checked.

rocky crypt
#

Good to know! Thanks for all the teaching πŸ™‚

#

Oh, and another quick question while I'm in the learning mood... What's the difference of using "value_template: >-" vs "value_template: >" I have seen it both ways...

mighty ledge
#

it's 100% useless everywhere accept for markdown card. If you see people use it, they don't understand what it's doing. I exclusively use just >

#

because leading and trailing whitespace in templates is trimmed in every scenario except for the markdown card

rocky crypt
#

Gotcha πŸ™‚ Thank you!

mighty ledge
#

np

vast plover
mighty ledge
#

Not sure what you mean, delete them from the UI?

vast plover
#

Sorry, I went to /config/entities

#

here, I filtered "persons"

#

And I have 5 ones there, 2 are wrong ("persons away") for example. Persons away is not in sensor.yaml

#

In sensor.yaml, i have "persons home", "persons not home" and "persons unknown"

#

How can I get rid of the entities, that are not any more in sensor.yaml and not used in the UI?

marble jackal
#

click on the (i) in develper tools > states and delete it from there

#

also accessible from the search in the top right

vast plover
#

Sorry, I dont find it. I have developer tools, but there is no "i"

#

Aah I see. The entities can be deleted by (i) and the pen. My problem is, that this entitiy doesnt have the pen symbol

vestal narwhal
#

Hi - a question about selecting on state. I have a group of window sensors ("windows") and wish to display which are open, so "expand('binary_sensor.windows')" should give me a list of the object members, and then filter using selectattr to get states that are on. The problem then occurs when I try to use the "friendly_name" of the objects rather than the "entity_id". So for example:
{{ expand('binary_sensor.windows') | selectattr('state','eq','on') | list}}

#

gives
[<template TemplateState(<state binary_sensor.window_childrens_bedroom_l_iaszone=on; device_class=opening, friendly_name=Window Childrens Bedroom (L) Iaszone @ 2022-10-11T14:09:46.705967+01:00>)>, <template TemplateState(<state binary_sensor.window_master_bedroom_l_iaszone=on; device_class=opening, friendly_name=Window Master Bedroom (L) Iaszone @ 2022-10-11T13:29:43.166089+01:00>)>]
and so we get a list of entit id by using
{{ expand('binary_sensor.windows') | selectattr('state','eq','on') | map(attribute='entity_id') | list}}

#

['binary_sensor.window_childrens_bedroom_l_iaszone', 'binary_sensor.window_master_bedroom_l_iaszone']

#

but is I try to get the friendly name- which is listed in the template objects I get
{{ expand('binary_sensor.windows') | selectattr('state','eq','on') | map(attribute='friendly_name') | list}}
[Undefined, Undefined]

#

Any idea why one works and the other doesn't

#

And where would I go for documentation to understand such details

marble jackal
#

Yes, friendly_name is an attribute, so you need to use | map(attribute='attributes.friendly_name')

#

However, it's better to use | map(attribute='name')

vast plover
#

@ thefes: Do you have another idea how to delete the entities?

marble jackal
#

there should alway be a Settings tab on each entity, although it might mention it can not be edited because there is no unique_id. The delete button should be on that screen

vestal narwhal
#

Thank you the "attributes.friendly_name" worked

marble jackal
#

'name' will also work

vestal narwhal
#

Yes it does

#

Thanks

vast plover
marble jackal
#

If there is no delete button there, the sensor is somewhere in your configuration

vast plover
#

no it isnt. The entities have "disappeared" now. It seems, that the unused (old) ones are deleted after a while

vestal narwhal
inner mesa
#

what are the available types?

#

I just use "normal"/"standard" regex as documented everywhere

vestal narwhal
#

PERL type, ISO 1003.2, early unix

inner mesa
#

it uses Python re underneath

vestal narwhal
#

Which lib

inner mesa
#

re

vestal narwhal
#

re

#

sorry

inner mesa
#

it just passes it straight through

vestal narwhal
#

How do I make a documentation change request?

#

A link to the re library would help

vestal narwhal
buoyant pine
#

You can edit it yourself and submit a PR

vocal agate
inner mesa
#

your indentation is messed up there, but that could be dpaste

#

is the state of either sensor actually "True", just like that?

vocal agate
#

The first sensor shows 2 h and the other the actual time

#

the indentation is ok in the yaml

#

no the sensor is false

inner mesa
#

you need to specify the actual state, then

#

if it isn't "True", then you're doing it wrong

#

you also haven't said what's wrong, so it's kind of a "where's waldo?" question

#

this kind of question makes me feel like I'm in a job interview

vocal agate
#

πŸ™‚

#

the issue is the first sensor shows the correct duration 2:30 and the other one just the actual time like 22:01

#

How would be the code for counting the time the sensor is true?

inner mesa
#

what you have there should do that if the state is really "True", just like that, which you haven't really answered

#

you've said "no the sensor is false"

#

and "sensor is true". Neither of which is "True"

vocal agate
#

ok

#

the sensor switches to true when the climate attribute is not idle

#

and the sensors show true when the climate is heating

#

the switching between the states and i want to count the time the climates are heating so i created following templates

inner mesa
#

I still don't think you've recognized the difference between "true" and "True"

#

you need to be precise if you want the right results

vocal agate
#

ok.

#

what you mean exactly?

mighty ledge
#

well for 1, the state isn't going to be True or False

#

unless that's under the sensor section

vocal agate
#

it is petro

#

the sensors are working as intended

mighty ledge
#

post a screenshot of the state in developer tools -> states

plain magnetBOT
#

Please use imgur or other image sharing web sites, and share the link here.

Image posting is blocked in most channels to discourage people from sharing text as images. Sharing text as images assumes that everybody sees the world as you do, which isn't the case. Some people are colour blind, or have visual impairment that means they can't make sense of an image of text.

vocal agate
mighty ledge
#

Ok, not sure why you wouldn't make those binary sensors.

vocal agate
mighty ledge
#

so, what's the problem then? History stats not counting correctly?

vocal agate
#

yes

mighty ledge
#

It's most likely due to you choosing poor state names

mighty ledge
buoyant pine
#

The Boolean That's Actually a Stringℒ️

mighty ledge
#

Right

vocal agate
#

whoa nice any suggestion `?

mighty ledge
#

Make binary sensors?

vocal agate
#

ok i will try to look for it

mighty ledge
#

nothing to look for

#

put it in the binary_sensor section instead of sensor section

#

copy/paste

vocal agate
#

ook

mighty ledge
#
binary_sensor:
- platform: template
  sensors:
     hzbuero:
        friendly_name: "BΓΌro heizt"
        value_template: "{{ (state_attr('climate.heizung_buero', 'hvac_action')!= 'idle')  }}" 
vocal agate
#

anyhow the indentation

#

how do i insert this in the middle of the yaml?

mighty ledge
vocal agate
#

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

#

somehow this is messed up... i need to declare first?

inner mesa
#

You..put it under sensor

vocal agate
#

no copied it to configuration.yaml

floral shuttle
#

uhm, how can we smarten this:```
state: >
{% if utcnow().hour - as_datetime( state_attr('sensor.energieprijs_uur_0','Timestamp')).hour ==0 %}
{{states('sensor.energieprijs_uur_0')}}
{% elif utcnow().hour - as_datetime( state_attr('sensor.energieprijs_uur_1','Timestamp')).hour ==0 %}
{{states('sensor.energieprijs_uur_1')}}
{% elif utcnow().hour - as_datetime( state_attr('sensor.energieprijs_uur_2','Timestamp')).hour ==0 %}
{{states('sensor.energieprijs_uur_2')}}
etcetc to 23....

#

its a sensor calculating the current hours energy price. and its completly verbose up to now, but I can not find the correct way of replacing the number in the uur_X

#

wait, it's as simple as```
state: >
{% set hour = now().hour %}
{{states('sensor.energieprijs_uur_'~hour)}}

#

what were they thinking.. completely threw me off.

floral shuttle
#

another one then: we dont need defaults on average? state: > {% set ns = namespace(vandaag=[]) %} {% for dag in range(24) %} {% set ns.vandaag = ns.vandaag + [states('sensor.energieprijs_uur_'~dag)|float(0)]%} {% endfor %} {{ns.vandaag|average}}

floral shuttle
marble jackal
floral steeple
#

Guess this is too early as I tried to find this, anybody set up a room presence detection with the iBeacon/BTProxy integration? Guess its going head to head with ESPresence. With that, was able to determine which ESP32 my phone was connected to, and thus the room was known.

#

I guess I have to create a sensor that read the state (home and not_home) and the attribute (source)

#

source is the room

#

if you have 4 rooms, it will be an if structure, I guess?

mortal bear
#

trying to get the below code to work in a Markdown Card.

it correctly lists the devices on my network & the IP address.

it doesn't format the output to fit in the table.

|Name | Ip Address |
|---  |---: |
{% for state in states.device_tracker %}
{% if state_attr(state.entity_id,'ip_address') != none %}
| {{ state.name }} | {{ state_attr(state.entity_id,'ip_address') }}|
{% endif %}
{% endfor %}
mortal bear
#

ok, managed to figure it out

|Name | Ip Address |
|----|----:| 
|{% for state in states.device_tracker %} {%if state_attr(state.entity_id,'ip_address') !=None %} {{ state.name }}|{{ state_attr(state.entity_id,'ip_address') }}  {% endif %}|
{% endfor %}
floral steeple
#

hey thanks, @mortal bear I was just going to post that

#

it works! except, I'm trying to filter out

#

just one device_tracker

dusty grailBOT
floral steeple
#

I thought putting this before your code, would filter out all other entities, but it does not

#

type: entity-filter
entities:

  • entity: device_tracker.2686f39c_bada_4658_854a_a62e7e5e8b8d_1_0_2a2b
    name: Android Phone
    state_filter:
  • home
mortal bear
floral steeple
#

Yes, it reports correctly with source, which is the attribute for the device_tracker

#

From iBeacon

#

It seems however, to list all the entities that have source as an attribute, though

#

source in this case is the ESP32 board, in the room.

marble jackal
#

You need to use None instead of none

#

Or this

content: |
  |Name | Location |
  |---  |---: |
  {% for state in states.device_tracker | selectattr('attributes.source', 'defined') %}
  | {{ state.name }} | {{ state_attr(state.entity_id,'source') }}|
  {% endfor %}
storm cloud
#

Rounding to fixed decimal for currency

thorny snow
#

Hey Guys, could somebody help me out on a Template Sensor please ? I want as example Sensor.X state value is above 0.1 else Sensor.Y state is 1, and when Sensor.X is above 0.1 and Sensor.Y is 0 to show an specific image in Lovelace for each function? Thank you

coarse tiger
#

somebody have a template to convert internet speeds to human readable?
e.g. I have a trafficsensor reporting in kbit/s but doesn't make much sense to display 349073450 kbit/s in the frontend

mighty ledge
#

divide by 1000 for Mb/s

#

divide by 1000000 for Gb/s

#

@coarse tiger ^

#

and if it's actually bits and not bytes, divide by 8 on top of that

coarse tiger
#

ok then there's apparently no clever way πŸ˜›
dumb works, as always

{% set rate = states('sensor.fritz_box')|int(0) %}
{% if rate < 0 %}
  0
{% elif rate > 1000 %}
  {{ rate / 1000 }} mbit/s
{% elif rate > 1000000 %}
  {{ rate / 1000000 }} gbit/s
{% else %}
  {{ rate | round  }} kbit/s
{% endif %}```
mighty ledge
#

Just so you understand bits are not the same as bytes

#

and Gbs and Mbs the b stands for bytes

#

FYI there's a units conversion WTH that you might want to vote for, as this should be covered under it

coarse tiger
#

all my internet speed related things go with bit (you order a 500mbit contract, you get something below in mbit, etc...)
but you are right, the sensor reports in bytes

dark frost
#

Hi, after i've upgraded the homeassistant to the latest version some of my self made templates stopped working, i've got something like 2022-10-12 04:44:16.902 ERROR (MainThread) [homeassistant.helpers.event] Error while processing template: Template("{{ (states('sensor.ups_nominal_real_power')|int * states('sensor.ups_load')|int / 100) / 1000 }}")

#

may i know where can i find info about whats have been changed, that the templates where stopped working, thanks

rocky hawk
#

Howdy, I am trying to develop a template to change my outdoor lighting based on the holiday season. So based on a date range I want to activate different scenes.

coarse tiger
#

this is not helping really, how can I get the statistics back?
(I'd assume by setting a unit_of_measurement but that just gets appended in the UI afterwards I believe and also is dynamic in this case)

#

guess there is no easy solution to this other than the WTH FR

mighty ledge
#

so go with mbits or gbits

#

not what you currently have

coarse tiger
#

Neither 2663838 mbit or 0,00363663 mbit make it readable for humans but OK πŸ˜…

dark frost
#

that damn thing broke on every month release, i'm giving up, better will move to some other home automation software

mighty ledge
mighty ledge
#

No one here owes you anything.

#

"Hey let me threaten to quit a software to a bunch of people who help others with the software"

#

πŸ™„

buoyant pine
#

that'll show 'em

mighty ledge
#

Oh man, 1 less person to help, darn

jagged obsidian
#

well my week is ruined now

#

i wanted to dedicate it to helping that person but now I don't know what to do

floral steeple
#

thanks @marble jackal ! This works also! What would be the easiest way to display the state (home or not home), and when the state is home, to display the room, for example, source attribute right now is showing " esp32-bluetooth-proxy-5f189c" but a friendly name of "Living Room" could be more intuitive

marble jackal
#

You need some kind of mapping to map the source to the room then

floral steeple
tidal meteor
#

I am wondering if somebody has created a template sensor to help predict if car windows get frosted during the night, I could use the info to adjust the alarm clock time in the morning so I have some extra time to clean the windows of my car.

mighty ledge
#

aka, doesn't exist in HA

#

FWIW farmers pay big bucks to know this info, i'm sure there's a history for your area somewhere

tidal meteor
# mighty ledge You'd need a history of frost from previous years

I can start building the history in influxdb for the temp, humi wind speed, cloud cover and dew-point sensor data.

This morning the windows were frozen with outside temp above 0 degreese C, so i know that its not a simple thing, was just wondering if maybe somebody else had looked into this problem and also does not like to clear the windows in a hurry because of not coming in late for work

mighty ledge
#

Well your second hurdle is that you can't access history from templates

#

so even if you had the information, you'd need to come up with a way to get it into HA

floral steeple
#

You're probably better off getting a local weather station, like Ecowitt and then use ecowitt2mqtt integration

#

OR if you trust your local API weather, im sure there is a sensor for that

floral steeple
#

OR use the data and Bayesian

tidal meteor
floral steeple
#

ok I took a bit of different approach for my room presence sensor, I realized I actually don't need the state because if the attribute (source) is not available, then im not home or in the room

#

I don't know if the bot is going to chop this up, its 15 lines of code for a template sensor

#

think this would work?

#

hmm, wonder if I should be using

#

is_device_attr(device_or_entity_id, attr_name, attr_value)

vivid ridge
#

hello im in need of alittle assistance with a received MQTT message

{
   "Id": "4a9bc0ea-5876-464c-a938-f832208005e5",
   "Topic": "Gaming Room Temp",
   "Title": "",
   "Message": "",
   "Data": [
       {
           "Name": "Gaming Room Temp",
           "Id": "data\\temperatures\\5",
           "Unit": "Β°C",
           "Value": 23.39
       }
   ]
}

all i want to display is the temperature value

currently config.yaml

  sensor:
    - name: "GamingRoomTemp"
      unique_id: sensor_gamingroomtemp
      state_topic: "Gaming Room Temp"
      unit_of_measurement: 'Β°C'
      value_template: '{{ value_json.temp }}'```    ^^^ without this line it Outputs
 
`{"Id":"4a9bc0ea-5876-464c-a938-f832208005e5","Topic":"Gaming Room Temp","Title":"","Message":"","Data":[{"Name":"Gaming Room Temp","Id":"data\\temperatures\\5","Unit":"Β°C","Value":23.39}]} Β°C`


`outputs:  0 Β°C`

im im 98% there i just dont understand the templates and the documentations is wild
next pier
#

Is there a template to make a sensor that is either home or away, but it's based on if 1 of a few location/proximity sensors are home or away?

#

like a binary sensor with a condition the HA App says I'm home, the network says my phone is connected, or possibly more?

floral steeple
floral shuttle
#

is what I use now, and I dont really understand where the |default needs to be added after the 'value_json[0]' ...

#

to prevent:```
Logger: homeassistant.components.rest.sensor
Source: components/rest/sensor.py:170
Integration: RESTful (documentation, issues)
First occurred: 12:23:50 (24 occurrences)
Last logged: 12:23:50

JSON result was not a dictionary or list with 0th element a dictionary```

marble jackal
#

you need to add the default before you take the first item

#

{{ (value_json | default(['something']))[0] }}

floral shuttle
#

Right. Thanks will do. Btw all 48 of them do show their value..

#

hmmm, does not help I am afraid..

marble jackal
#

I'm not using rest sensors myself, so I'm no expert on this, but to me it looks like the attriubute also tries to use the first item out of the value_json which will probably give similar issues if the provided value is empty

floral shuttle
#

found it. its fares well on 0-23, but from 24 on it errors

#

and those are the values that are for the next day, and currently not available in the main data (that data is provided after 1600 )

#
         value_template: "{{(value_json|default(['default']))[24]['TariffUsage']|float(0) + states('sensor.prijsopslag_energie')|float(0)}}"
         json_attributes_path: "$[24]"
         json_attributes: *attributes``` then throws the error
#

so a default is not sufficient....

marble jackal
#

Hmm, I would expect this to error after 0 (so already on [1]). Your default only has one item, so if value_json is not available your default will kick in

#

but in this case I assume there are 24 hours of data provided, so there are 24 items in the list

#

[24] is the 25th

floral shuttle
#

Well, even more, there are 48… today and tomorrow s prices. As said, tomorrows prices are only available after 16:00 hr

#

So not sure how to prevent that other than in the template. (We can not do something like a trigger template I guess. Would be cool though)

marble jackal
#

then you need to provide a default with 48 items.
Not sure if this most efficient, but it should work

{% set ns = namespace(default=[]) %}
{% for i in range(0,48) %}
  {% set ns.default = ns.default + ['default'] %}
{% endfor %}
{{ (value_json | default(ns.default))[24] }}
floral shuttle
#

Wow. Now that’s a default filter πŸ˜‰ thanks and I’ll try when I get back! Will let you know here . Cool🌢️

mighty ledge
#
{{ (value_json | default(['default']*48))[24] }}
floral shuttle
#

Right. Even better. Besides this template per sensor, I can’t stop figuring whether the whole rest sensor couldn’t be simplified.

#

It’s a single resource with 48 verbose sensors right now . Couldn’t I write that as a β€˜for 0-47’ loop somehow ?

mighty ledge
#

Nope

#

post your yaml, I'm sure I could simplify it with anchors

#

it depends on how much redundancy there is

silent seal
#

I want to see an example of that. I need to start using anchors more.

mighty ledge
#

You can look at my setup for that

#

I use them ALOT

#

and I refactored scripts this weekend

#

Let me attach my github to my name

silent seal
#

Ooh, excellent.

#

I shall enjoy perusing them. Though sometimes seeing a before and after is the most helpful, so I may have to check out your previous commits.

mighty ledge
#

Ok, attached them to my name

#

Let me find a good example

#

but it's 5 automations

#

the take away is that you can use <<: &some_name to declare yaml that you want to reuse

#

and then to reuse all those fields <<: *some_name

marble jackal
#

@mighty ledge now that you are here, I'm having a strange problem with the media_content_type of a cast device

mighty ledge
#

What's the problem?

marble jackal
#
{%- set ns = namespace(info=[]) %}
{%- for entity in expand('media_player.zolder_mini_martijn')  %}
  {%- set general = dict(media_content_type = state_attr('media_player.zolder_mini_martijn', 'media_content_type')) %}
  {%- set ns.info = ns.info + [ general ] %}
{%- endfor %}
{{ ns.info }} # [{'media_content_type': <MediaType.MUSIC: 'music'>}]
{{ state_attr('media_player.zolder_mini_martijn', 'media_content_type') }} # music
{{ states.media_player.zolder_mini_martijn.attributes.media_content_type }} # music
{{ states.media_player.zolder_mini_martijn.attributes.get('media_content_type') }} # music
floral shuttle
marble jackal
#

why do I get [{'media_content_type': <MediaType.MUSIC: 'music'>}] in the first version, and not [{'media_content_type', 'music'}]

#

I didn't have it on an older version of the cast integration (which I was running as custom component so I could keep my players as idle instead of off)

floral shuttle
mighty ledge
#

or enum in python

#

I ran into this recently

#

what's the name of <MediaType.MUSIC: 'music'>

#

variable name

marble jackal
#

media_content_type

#

I acutally use state_attr('media_player.zolder_mini_martijn', 'media_content_type') in this version

mighty ledge
#

media_content_type.name

marble jackal
#

That used to be entity.attributes.media_content_id. I changed it to see if it helped

mighty ledge
#

entity.attributes.media_content_id.name

#

if that doesn't work, let me know

#

I ran into this serializing MQTT payload recently

marble jackal
#

[{'media_content_type': Undefined}]

mighty ledge
#

.value

#

try that

#

and your last resort is

marble jackal
#

same

mighty ledge
#

'' ~ entity.attributes.media_content_id

marble jackal
#

sorry, both name and value worked

mighty ledge
#

ah ok

#

good to know

marble jackal
#

I used id instead of type

mighty ledge
#

ah

marble jackal
#

and then copied your version,. where you used my incorrect input

#

name gives MUSIC and value gives music

mighty ledge
#

πŸ‘

#

the

#

the '' ~ should also work

marble jackal
#

however, your last resort version will also work on older installations, so I might use that anyway

#

yes, that works as well

mighty ledge
#

basically, you need to get it as a string

marble jackal
#

hmm, I actually use entity.attributes.get('media_content_type', 'no type')

#

'' ~ entity.attributes.get('media_content_type', 'no type') it is then

warped blade
#

I have rhasspy setup and got it to report the date to me. How can i get it to tell me the date like october 13 2022? and not 13th of the 10th two thousand twenty two? sorry if this is an easy thing, i have just started with home assistant

mighty ledge
#

if you want the year to be 20 22, then just put a space in the year

warped blade
#

it is outputting as 13th of the 10th two thousand twenty two. I would like it to say it in the american format if possible. like Thursday October 13th 2022.

marble jackal
#

What is the code you are currently using to create this output?

plain magnetBOT
#

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

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

marble jackal
#

You lost me here, you are outputting the state of sensor.date is the state of that sensor 13th of the 10th two thousand twenty two?

warped blade
#

sorry, this is like day 2 for me with home assistant. and the sensor does appear to be outputting as you said

marble jackal
#

You don't need that sensor

action:
  - service: mqtt.publish
    data:
      topic: hermes/dialogueManager/endSession
      payload_template: >-
        {"sessionId": "{{ trigger.event.data._intent.sessionId }}", "text":
        "Today is {{ now().strftime('%A %B %-d %Y') }}"}
#

it will output Today is Thursday 13 September 2022

warped blade
#

perfect

#

ok, so just use strftime for things like this?

marble jackal
#

I do

warped blade
#

that works. now i just need to determine why its saying its the 10th lol

marble jackal
#

because I used %-m instead of %-d

#

πŸ˜…

warped blade
#

ah

marble jackal
#

It's fixed in the template above

warped blade
#

you are the king of cool

mighty ledge
#

usually people want it to read phonetically.... Today is Thursday, Septemper 22nd, 2022

marble jackal
#

but adding st nd rd th requires a bit more code

mighty ledge
#

| ordinal

#

e.g. {{ 4 | ordinal }} -> 4th

marble jackal
#

Oh, okay, that's easy

mighty ledge
#

yep, super easy

warped blade
#

might try to add that

#

I really appreciate the help

grizzled grove
#

Is there a way to change the state "unavailable" to something else (ex: away)?

#

I have a HC-SR04 finding the "presence" of the car in the garage. But when the car it's out, the distance goes far beyond the range of the HC-SR04.

silent seal
#

It sounds like you just need a simple template:

iif(is_state('sensor.car_in_garage', 'unavailable'), "away", states('sensor.car_in_garage'))

Or something similar

#

If you want a binary sensor instead that you'd need to tweak it

amber obsidian
#

This template condition is currently true: {{ is_state_attr('light.mh1_light_group', 'rgb_color', (255, 251, 247)) }} -- how could I check a range on say the blue component so that the condition would be true between 240-255?
I'm having hard time building stateful automations as the read state attributes seem to be always off-by-one from those I have set earlier. Doesn't matter if it's done by rgb, xy or hs.

mighty ledge
# warped blade might try to add that
        {% set t = now() %}
        {"sessionId": "{{ trigger.event.data._intent.sessionId }}", "text":
        "Today is {{ t.strftime('%A %B {0} %Y').format(t.day | ordinal) }}"}
warped blade
#

oh wow, thank you!

fiery glen
#

Hello.

Is there anyone here who can help me with a "template" for wifi connection

next pier
floral steeple
next pier
#

Am I going about this right? I have 2 parts - one is an input helper if I am home or away and one input helper if my wife is home or away, I'd like a group that is "everyone is home" if both input helper's are home, or someone is home if only one of us is?

#

so I have 3 ways to tell if I'm home or not, 3 slightly different ways to see if she is

#

both toggle a drop down menu/input helper

#

i'd like the status of those helpers to be the "All are home" or "some are home" factors

next pier
next pier
#

"All Entities"?

#

read it - thank you Anto!

silver talon
#

Hi! I would like to create a template, that convert a percentage value to number. I would like to set a min max value (like min 30, max 45) and the percentage is 0-100%

#

any idea how to make it?

#

the percentage and the output number is a entity

marble jackal
#

That's just math

#
{% set min = 30 %}
{% set max = 45 %}
{% set percentage = 75 %}
{{ min + (max - min)*percentage/100 }}
#

replace 75 with states('some.entity') | float

floral shuttle
#

note I still have the former default, and had tried both single and multi line notation. that all means nothing really, was just looking for a way to be more efficient. Maybe split the 2 days into separates? that way at least we would only have issues on the 'tomorrow's hours

mighty ledge
#

You could make it a template sensor using a trigger to cut it down but it’s not worth it

floral shuttle
#

sorry, had a few typos there... this now works: https://dpaste.org/TXvzU and not sure yet when, but I guess the errors start at daybreak, when tomorrow is only available after 16:00..

floral shuttle
mighty ledge
#

Put the result in a single sensor as an attribute, then use a trigger that updates based on the attribute. Then make variables that call out the index. Like I said, it’ll cut it down but it’s not worth the effort

floral shuttle
#

a yes, that is clever indeed! cool. and it would prevent all of these errors, I like that.... will see tomorrow. thx Petro 🌢️

pastel mauve
#

I don't know anything about the mqtt integration. However, the template will need to navigate the JSON structure you're showing. The temperature value is the `Value` key in an object which is in the `Data` array. The template expression for this would look something like `value_json.Data[0].Value`.

floral shuttle
glad zenith
#

Morning, can anyone help me with a sensor template and default state?

#

I've got this template, but the sensor itself has a state where there it is empty, in this case it shows as unavailable, I want to swap that so unavailable = another name

#
  • name: Heating System State
    unique_id: heating_system_state
    icon: mdi:thermostat-box
    state: "{{ state_attr('climate.holly_house', 'preset_mode') }}"
floral shuttle
heavy crown
#

Hi, rest has a value_template for the state... is there also an option to use value_template for the json_attributes_path ? I need this as my file changes of content/structure each 5mins and the info I need may be on any index, I use the value_template to iterate through which works fine....but now I need also the attribs. If no template, can I posisbly pass on the index from the value_template to the path?

lofty nimbus
#

Hi there.
I have a question about using a blueprint and its probably more of a general understanding question. I have Home Assistant up and running and have a few devices which I happily use. Now I have a room where I need more than 1 motion sensor to cover the whole room.
Up until now I was using a blueprint that looks like it is in Home Assistant by default. It's called Motion-actived Light and is found at config/blueprints/homeassistant/motion_light.yaml (http://pastie.org/p/7dOLabVp5MyOG79HsFuvrJ).
It has been doing what I want until now ... Turning on a light when motion is detected and turn off light after motion sensor is clear for x seconds.
As said I now need 2 motion sensors. I though I just make a group. I created a Binary Sensor group and added the two motion sensors. Now I cannot use this group in the blueprint above. Just not showing up.

Now is it not showing up because the blueprint has a specific class for the motion_entity (domain is binary_sensor, device_class is motion) and the broup is just in the domain binary_sensor but does not have the proper device_class?

If this is correct. Should I copy this built in blueprint and create a new one without the device_class? Or do I need to do it differently?

Any tips appreciated. I haven't found anything specific to this via Google. If my Googling skills are lacking ... I'm happy to get a link where I can read more about it. Still new with blueprints.

tidal heart
#

From node red I get a timestamp that looks like this 1665755149166, HA recognise it as a number. How can I use it with as_timestamp?

#

{{ state_attr('sensor.node_red_test', 'timestamp') | timestamp_local }} renders a ValueError: Template error: timestamp_local got invalid input '1665755149166' when rendering template

#

Solved it:
{{ state_attr('sensor.node_red_test', 'timestamp')| multiply(0.001) | round(0) | timestamp_local }}

pastel mauve
amber obsidian
#

Is it possible to remove one entity_id from a group with the "Group: Remove" action or is it only for removing a group as whole?

obsidian lintel
#

https://pastebin.com/iKm5ScXs

Trying to create a light template that when brightness dimmed, it will warm the lights accordingly. This is what I got so far, nothing works except for turning it on and off.

silent seal
#

Did you look at the Flux integration? Because that might solve your problem

obsidian lintel
#

Well, the flux integration is timed based, im trying to build something that I can manually control...

silent seal
#

I think you'll need an integration (custom or native) rather than a template. I don't think you can do what you're trying to do with a template at all actually

obsidian lintel
#

Hmm alright thanks!

marble jackal
#

You can take the entire entity_id list, reject the one you don't need and use that to set the group

#

I've also seen a WTH requesting a service for it

marble jackal
#

It matches color_temp on a change of brightness, not the other way around

amber obsidian
#

Would be helpful if the Set service would have an option to remove an entity just like it can be used to add one.

marble jackal
# amber obsidian Thanks! How could I implement this rejection?
- alias: "Remove entity from group"
  service: group.set
  data:
    object_id: some_group
    name: "Group name"
    icon: mdi:play-box
    entities: >
      {%- set g = 'group.some_group' %}
      {%- set current = state_attr(g, 'entity_id') | default([], true) %}
      {{ current | reject('eq', 'some.entity_id') | list }}
mighty ledge
toxic dome
#

Actually that should probably be a WTH come to think of it

obsidian lintel
mighty ledge
toxic dome
#

json_attributes? That would be nice

mighty ledge
#

It should probably be a separate field, like attributes template. Mutually exclusive with json attributes.

toxic dome
#

Alternatively could stick a post processing template in between like Mqtt sensors have. Something that runs on the output before it gets handed to the state and attribute handlers

mighty ledge
#

I didn’t want to do the PR because he would have to be deployed in six places

toxic dome
# mighty ledge Example?

I'm thinking of Mqtt availability actually, my bad. Where the value is compared to payload_available or payload_not_available but value_template can modify it first

#

So I guess I don't have a good example of this. But was thinking of a field like output_template which modifies what actually comes from the rest API and sets value for the templates that follow. Idk if that's easier though

lofty nimbus
odd maple
#

any idea why this templete won't work for me anyone?

{{states.sensor|selectattr('attributes.device_class', '==', 'battery')|selectattr('attributes.unit_of_measurement', '==', '%')|list}}
marble jackal
#

Yes, you need to check if the attributes are defined

#
{{ states.sensor |selectattr('attributes.device_class', 'defined') | selectattr('attributes.device_class', 'eq', 'battery') |selectattr('attributes.unit_of_measurement', 'defined') | selectattr('attributes.unit_of_measurement', 'eq', '%') |  list }}
odd maple
#

is that a recent change? it used to work with the shorter line

marble jackal
#

And this will list the complete state objects, if you need entity_ids, you need to map those

#

Uhm, few months I guess

odd maple
#

excellent, thanks

thorny snow
#

Does Somebody got a better method then the Statistics, HADailySensor etc to see Min and Max Temp of the Day (History not needed, and takes Data what is already there and not just starts when the sensor got created or resets itself by an restart)?

mighty ledge
waxen rune
#

I would like to see which device an entity belongs to. When I tried it a year ago or so it was said you can't do that, but I am under the impression it is possible now.

The end game is to list all entities with state = unavailable, get the devices from that list and then remove the duplicates.
So instead of a list like "sensor.adguard_parental_control_blocked, sensor.adguard_safe_browsing_blocked, sensor.adguard_safe_searches_enforced, sensor.bw16a01_current, sensor.bw16a01_power_2, sensor.bw16a01_power, sensor.bw16a01_voltage" I would get "Adguard Home, StrΓΆm till fΓΆrstΓ€rkare i kΓΆk" (the device/integration names).

Since we got the "related device" now, I assume it is possible now. Any ideas how?

mighty ledge
#
{%- set devices = states | map(attribute='entity_id') | map('device_id') | unique | list %}
{%- set ns = namespace(items = []) %}
{%- for device in devices %}
  {%- set unique_states = expand(device_entities(device)) | map(attribute='state') | unique | list %}
  {%- if unique_states == ['unavailable'] %}
    {%- set ns.items = ns.items + [ device_attr(device, 'name') ] %}
  {%- endif %}
{%- endfor %}
{{ ns.items }}
#

that's if they are all unavailable

#

(all entities)

#

in the device

#

if yuou want devices where any entity is unavail..

#
{%- set ns = namespace(items = []) %}
{%- for device in states | selectattr('state','eq','unavailable') | map(attribute='entity_id') | map('device_id') | reject('none') | unique %}
    {%- set ns.items = ns.items + [ device_attr(device, 'name') ] %}
{%- endfor %}
{{ ns.items }}
waxen rune
#

That is just awesome. Thanks!

floral steeple
#

hey all, im trying to create a trigger based on a temperature change, rather than an above or below

#

something like if the temperature drops by more than 10 degrees oC, this is the trigger, regardless of what the temperature is

inner mesa
#

create a template binary_sensor to represent that and use it as the trigger

#

or a state trigger and a template condition comparing the trigger.to_state.state and trigger.from_state.state

#

I'm not sure what kind of help you're looking for

floral steeple
#

ok this is great! Here's what I'm trying to solve. I have a clothes dryer automation, that starts a time and stops a time and then announces its done and provides an estimated time to completion.

#

Problem is because the dryer is electric and 240 V, I can't monitor the power consumption (at least not easily), so I simply bought a temperature sensor and placed it in the vent

#

it works, say if trigger to start is temp above 27oC, and trigger to end, temp is below 50oC

#

BUT sometimes, the temp drops in the beging, from say 52oC then to 48 oC

#

then goes back up and stays up

#

however, the dry has a cool down period, so it drops steadily from 60oC and then turns off at around 50oC

#

im trying to capture that 10oC drop from 60 to 50oC

inner mesa
#

yes, I get that

#

what help do you need?

floral steeple
#

binary_sensor:

  • platform: trend
    sensors:
    temp_falling:
    entity_id: sensor.outside_temperature
    sample_duration: 7200
    max_samples: 120
    min_gradient: -0.0008
    device_class: cold
#

this is the example from docs

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).

floral steeple
#

what is min gradient?

inner mesa
#

min_gradient string (optional, default: 0.0)
The minimum rate at which the observed value must be changing for this sensor to switch on. The gradient is measured in sensor units per second.

#

just that

#

another paragraph there on it:

A trend line is then fitted to the available samples, and the gradient of this line is compared to min_gradient to determine the state of the trend sensor. The gradient is measured in sensor units per second - so if you want to know when the temperature is falling by 2 degrees per hour, use a gradient of (-2) / (60 x 60) = -0.00055

floral steeple
#

ok, it takes about 6 minutes for the temp to drop from 60 to about 50oC, and the sensor only updates every 61 to 76 seconds

#

duration: 360

#

based on your example and my data, gradient would be (-10)/(6*60)= 0.027

#

-0.027

floral steeple
#

I'm going dust off the old Ti-89 and do some high school math here. πŸ˜€

rustic moat
#

Hello, my name is Sebastian and I'm facing a problem that I can't solve myself because I don't have the right idea.
I have a heating valve (NC) that opens in 4 minutes when it gets power. When the current is gone, it closes again in 4 minutes.
I have a sensor for that valve that tells me "power on" and "power off". What I am missing is how to calculate the degree of opening of the valve from this "true" and "false" information in connection with the 4 minutes opening time.
Does anyone have experience with this, or has something similar already been implemented?
I would appreciate a tip on how to implement something like this. I'll be happy to fumble my way through it, but at the moment I don't have any idea where to start.

inner mesa
#

I suppose this is the operative part of your question, but I don't know what you actually want:

how to calculate the degree of opening of the valve from this "true" and "false" information

#

you want a binary_sensor that only reflects on or off if the valve is open or closed, taking into account the 4-minute delay?

rustic moat
#

(Think of it as a garage door opener. I want to calculate the opening position of the door with the running time. The only difference is that the valve is auto-closing agian after the power is gone).

#

As I think of it, it needs to be a counter. I need to increment the counter by 0,0041666666666667 every second if the state of the binary sensor is on and decrement by the same value every second it the binary sensor is off. Don't go over 1, don't go under 0 and show that as "%".

inner mesa
#

You could do that, yes

rustic moat
#

Ok, will try.

stuck kiln
#

hello

#

Does anyone know how to put a variable here {%set cons_price = 0.228080389 | float %}

in such a way that the price of "0.228080389" is {%set cons_price = variable | float %}

Where that variable is the value of this sensor "sensor.esios_pvpc" I am in the regulated market so I am interested in having that variable that varies as you know every hour and every day.

rustic moat
#

{% set cons_price = states('sensor.esios_pvpc') | float(default=0) %} probably

stuck kiln
#

ok, tnks @rustic moat

#

I probe now , and it not work

#

{% set cons_price = states('sensor.esios_pvpc') | float(default=0) %}

inner mesa
#

that's how it would be done, so you'll have to expand on "it not work"

stuck kiln
#

sorry, if i change this line , The sensor change a not available

stuck kiln
#

sorry and thanks, i tried again, and now it's work fine

warped blade
#

I have created a weather template and it works great as a card. Would anyone be able to help me figure out how to get that info to report to my rhasspy instance? I was able to figure out how to get it to report the temperature, but i am unsure how to add the forecast as an intent script. Any help would be super amazing.

teal umbra
#

I want to change the outcome of this sensor
{{ (states('sensor.solaredge_ac_power')) | float / 1000 | round(2) }}
5.465
to 5,5 but i have no idea how to accomplish this πŸ™‚ Any help?

marble jackal
#

You are now rounding 1000

#

You need to use parenthesis to round the result of the calculation

#

Basically you need to move the ) you already have to after the 1000

#

And you need to use round(1) instead of round(2)

teal umbra
#

That did it πŸ™‚ Thx @marble jackal

lyric hatch
#

Can anyone help me template this. I want to do something like if sensor1 is less than sensor2 and sensor3, I can't work it out

marble jackal
#

sensor1 < sensor2 and sensor1 < sensor3

#

Or [ sensor1, sensor2, sensor3 ] | min == sensor1, but that will also be true is the states are equal to each other

#

I now see your post in #automations-archived You also need to convert the states to a number, as the string comparison "10" < "5" will result in true

lyric hatch
acoustic arch
#

i got confused and running around in circles. What is the the proper way to setup home not_home presence detection? I got multle device_tracker.xxxx i would like to combine to either a home/not_home sensor OR a binary OFF/On sensor. Any tips?

#

because old style grouping is just putting all device trackers entities in the config. But new style doesnt have that? only binary/fan/light etc

#

so do i first need to make a home/not_home into a binary on/off sensor for each device tracker and put those into a group then?

#
   awesome_people:
    name: "Awesome People"
    entities:
      - device_tracker.dad_smith
      - device_tracker.mom_smith```

is this still valid or being phased out?
buoyant pine
#

Still supported, but it's encouraged to move to the new style

acoustic arch
#

but how.... bundle up multiple device_trackers to one single home/not_home ...?

#

i cant find a group in the helpers menu to bundle up multiple device trackers

#

i would like to bundle person.joe and a couple of device-trackers made with ping to a single entity.

thorny snow
#

in helper the input_number slider has no setting for steps of 0.5? or is their a otherway of doing it?

inner mesa
#

you can type whatever you want

thorny snow
#

but the slider only allows me to change in steps of 1

inner mesa
acoustic arch
#

if i use ping as device tracker, why shoud i bother. I might as well make it a binary sensor straight away to be used as presence detection?

#

else its an extra step: having to template a ping device tracker home/nothome to binary anyway so it seems

#

correct me if im wrong

#

running around in circlesss....♻️

thorny snow
# inner mesa

Ohh wow, the column turn red for me when i type 0,5 and that got me to think its not accepting the value but it does when clicking update. Thanks!!

rain cove
#

How can I add a template switch through the GUI? Or is it only possible through yaml files?

inner mesa
#

you can only do that by editing YAML

buoyant pine
#

YAML? More like YUML amirite

ember wagon
#

I have a Multi meter sensor I want to export to a Google Sheet using template in the data field of an automation but I simply cannot get the "number" out (I try to show it in the Demo template) :

{{ States('sensor.mileage_sensor') | float(0) }} but 'States' is undefined

marble jackal
#

@ember wagon it's states(), so lowercase s

ember wagon
#

Thanks a lot

floral shuttle
mighty ledge
#

it's going to be 'heavy'

floral shuttle
#

yeah, heavy is ok. But this is not ok. It's still locked....

mighty ledge
#

look at your logs

floral shuttle
#

it auto restarted.....

#

can you enter both templates at the same time?

mighty ledge
#

I can on my system

floral shuttle
#

also, I had a look at that train config, but wasnt successful in re-writing my resource rest sensor to that format

mighty ledge
#

I told you it wasn't worth it

marble jackal
#

I pasted both in devtools > templates, and although a bit slow (like half a second or so) they load fine here

mighty ledge
#

you have to make all separate trigger entities. Your config might be largely the same number of lines, but you'd only have to edit 1 template.

#

and, you'd still need to maintain indexes

#

TLDR: Not worth it

marble jackal
#

Hmm, I was a bit too soon, my HA is not responsive anymore

floral shuttle
#

hehe, wait 5 minutes and it ll restarts....

marble jackal
#

trying ha core reboot from ssh, but that is processing already some time now

floral shuttle
marble jackal
#

ah, the command is processed

#

and CPU usage and Disk IO stabilized again

floral shuttle
#

individually these templates render fine (first is a bit slower than the second), together in the dev tools templates is a no-go. btw, I now discover on the second template, that is returns devices that are disabled, or, at least not listed in my devices list. That means that the backend template engine still sees these devices. That seems unexpected..

mighty ledge
#

delete the device (instead of disabling it) and it won't be in the registry

half pendant
#

I have an integration (Greenley) that gives a sensor that gives me the total daily usage for the day before and a json (i assume) list of the past week or so. Is there anyway to convert this into a long term sensor so that i can track the energy usage over a longer period of time

mighty ledge
#

no

#

Currently, there are issues related to past historical data being put into HA. So if you did make this sensor available in the energy tab, the data would be off by the offset presented in your sensor

#

i.e. it would be off by a day if it was yesterdays reading.

half pendant
#

No it doesn’t need to be connected to the energy tab (currently it isn’t). I have my own energy dashboard based on a couple of sensors using apex charts. Also it doens’t need to work historically. It’s fine if it starts recording today and keeps going forward

mighty ledge
floral shuttle
#

1 ask: could a generic deselect be made for devices like: 'S1b7898d3b6995169C 0A98' ? its the new iBeacon adding countless numbers of them, and they can be left out of this template. Theyre all different, but all have that same format.

#

'e20a39f4-73f5-4bc4-1864-17d1ad07a962_14390_4928 BF3D', 'e20a39f4-73f5-4bc4-1864-17d1ad07a962_19899_45253 6848', 'e20a39f4-73f5-4bc4-1864-17d1ad07a962_28553_1869 942E', 'e20a39f4-73f5-4bc4-1864-17d1ad07a962_4280_54190 4E26', 'e20a39f4-73f5-4bc4-1864-17d1ad07a962_54087_18166 F99F', 'e20a39f4-73f5-4bc4-1864-17d1ad07a962_64939_32411 4A16', 'e2c56db5-dffb-48d2-b060-d0f5a71096e0_0_0 047D', 'e2c56db5-dffb-48d2-b060-d0f5a71096e0_0_0 A8BE', 'FM One 1DF2', 'N/G 3718', 'S004045e768eb6f4dC C079', 'S03181b8f78355fe7C BEC4', 'S08207288b7a9c3b1C 7A8E', 'S0aed85c7d2389efeC 1BB2', 'S148a80e3ccda0a8bC 9081', 'S1b44953c1369ed2bC A36E', 'S1b7898d3b6995169C 0A98', 'S1d5aeec4c46d00e4C 017B', 'S1db85daeccf8c99bC 52F5', 'S21296737cf94afa5C 0455', 'S282d1c03285b1515C 3CCB', 'S2f4f11eef8a6fc92C 53AF', 'S38cad119ce1bf536C 6DA9', 'S3f29ce079172f647C D463', 'S42d91114c625f57dC C566', 'S42f3df7c2906429eC 4895', 'S433830d79a4d7050C 1836', 'S467b41fad282209eC 8C7D', 'S46a05f68fa464ea6C D2F8', 'S5065772242e550dbC 3B85', 'S51b9b328b91f37faC D88C', 'S52e5ae6e3421bb24C 49ED', 'S52f1e90afdfa9744C 3AAB', 'S58613499bca50161C B0CC', 'S5ba9456074306d18C 6543', 'S674759cfd93190a6C B74C', 'S6d868b971490996dC D2D1', 'S6f5882d43c53dba8C 3F4A', 'S76a4a43f75359d6dC B0D9', 'S776c5be44a92ad49C 38F3', 'S793afd1c93410333C F8F1', 'S8d2f31624c12649fC FFA6', 'S8f4b1a9fcdba0cbcC 7E7B', 'S966f48237b39c82eC 3910', 'S9cbb50678687492aC 44A2', 'Sa0830c5e68ce1e07C 22CB', 'Sa1b7a71a16ba3776C 36B1', 'Sa4d8dc271f1aab5dC 248B', 'Sa782c856a9b0e0cfC C382', 'Sa8fb66b51b39f0e3C 4995', 'Sacbe70f70f5afe10C 95FD', 'Saf3a4f597f1dd28dC 0EC8', 'Sb0bd1432249097c8C 8474', 'Sb35d3b8190e670d6C 11BC', 'Sbb9ddbd23acf3941C AD64', 'Sbbad443d68604c82C C25D', 'Sbdfdaafe9308b12dC C739', etc etc

#

the ones that dont have that format standout immediately πŸ˜‰

half pendant
plain magnetBOT
half pendant
mighty ledge
#

for long term statistics?

#

or... just in your database

half pendant
#

Well so that i can create a graph (that’s showing a months data) with it

mighty ledge
#

if you want normal history graph, you have to increase your database collection period to beyond 10 days

#

but that will be for all of your history

half pendant
#

Is that the norm for every sensor?

mighty ledge
#

yep

half pendant
#

And i can’t create a sensor that has a longer retention specifically?

mighty ledge
#

nope

half pendant
#

I see

#

Well that complicates stuff

mighty ledge
#

yep, use influx or something else

#

before you ask, no i don't know how to set that up

half pendant
#

Yeah i was trying to avoid that. Since the integration somehow saves the last week i was hoping i could reuse that. But it seems to be too much work

toxic dome
floral shuttle
#

I did try: - name: Energieprijzen value_template: "Ok" json_attributes_path: "$.converted.ArrayOfEnergyTariff" json_attributes: - EnergyTariff but figured the 'converted' bit was caused by the converter (...) and not part of the real outcome of the resource. It doesnt help. No matter what I enter there, it remains an empty list, until I start using the path '$[x]'

toxic dome
floral shuttle
#

XML I would think

#

just throw this is the browser: https://mijn.easyenergy.com/nl/api/tariff/getapxtariffs?startTimestamp=2022-10-17&endTimestamp=2022-10-18

toxic dome
#

Oh. That's going to be extremely difficult to use then. Sorry I thought you had found some way to turn xml into json on the fly

#

You definitely cannot use a rest sensor with xml, that'll never work. You also can't use Jinja templates, they have no support for xml either.

#

The only way I can think of is a command line sensor that ssh's to another machine which has xq installed. Do the curl there and pass the response to xq

floral shuttle
#

but this works perfectly:```
- name: Energieprijs uur 0
value_template: >
{{not important value}}
json_attributes_path: "$[0]"
json_attributes:
- TariffReturn
- TariffUsage
- Timestamp

#

does that at least make sense?

toxic dome
#

Oh. I'll be damned. Rest sensor converts xml to json. I totally forgot that

toxic dome
#

Dump the response into a file, read that file in Python and run that on it just like HA would, see what it looks like. Or make the API call from python if you prefer

floral shuttle
#

ok let me try that!

#

well, this is what is logged: 2022-10-17 17:32:51.405 DEBUG (MainThread) [homeassistant.components.rest.sensor] Data fetched from resource: [{"Timestamp":"2022-10-16T22:00:00+00:00","SupplierId":0,"TariffUsage":0.139857900000000000,"TariffReturn":0.12831},{"Timestamp":"2022-10-16T23:00:00+00:00","SupplierId":0,"TariffUsage":0.124706900000000000,"TariffReturn":0.11441},{"Timestamp":"2022-10-17T00:00:00+00:00","SupplierId":0,"TariffUsage":0.115158500000000000,"TariffReturn":0.10565},{"Timestamp":"2022-10-17T01:00:00+00:00","SupplierId":0,"TariffUsage":0.097707600000000000,"TariffReturn":0.08964},{"Timestamp":"2022-10-17T02:00:00+00:00","SupplierId":0,"TariffUsage":0.085270700000000000,"TariffReturn":0.07823},{"Timestamp":"2022-10-17T03:00:00+00:00","SupplierId":0,"TariffUsage":0.110449700000000000,"TariffReturn":0.10133},{"Timestamp":"2022-10-17T04:00:00+00:00","SupplierId":0,"TariffUsage":0.134080900000000000,"TariffReturn":0.12301},{"Timestamp":"2022-10-17T05:00:00+00:00","SupplierId":0,"TariffUsage":0.168045300000000000,"TariffReturn":0.15417},{"Timestamp":"2022-10-17T06:00:00+00:00","SupplierId":0,"TariffUsage":0.198837800000000000,"TariffReturn":0.18242},{"Timestamp":"2022-10-17T07:00:00+00:00","SupplierId":0,"TariffUsage":0.175599000000000000,"TariffReturn":0.16110},{"Timestamp":"2022-10-17T08:00:00+00:00","SupplierId":0,"TariffUsage":0.149112000000000000,"TariffReturn":0.13680},{"Timestamp":"2022-10-17T09:00:00+00:00","SupplierId":0,"TariffUsage":0.149820500000000000,"TariffReturn":0.13745},{"Timestamp":"2022-10-17T10:00:00+00:00","SupplierId":0,"TariffUsage":0.134091800000000000,"TariffReturn":0.12302},{"Timestamp":"2022-10-17T11:00:00+00:00","SupplierId":0,"TariffUsage":0.143956300000000000,"TariffReturn":0.13207},{"Timestamp":"2022-10-17T12:00:00+00:00","SupplierId":0,"TariffUsage":0.149624300000000000,"TariffReturn":0.13727},] etc etc

#

so it seems it does start at the [0] level, and not the ArrayOfEnergyTariff level.

#

its a nasty beast, I figure I have to forget about.

#

unless you'd think (with me) this is a bug, and I will file an issue...]

#

the 'JSON converted from XML' is not logged at all btw

silent seal
#

What's there in the log is JSON

#

It's invalid JSON, presumably because we only have part of it, but it's JSON

plain magnetBOT
toxic dome
#

Right. course you also lost the mention bot friend lol. @floral shuttle take a look at that output there. I hit the API in curl

#

You can see its actually returning JSON, not XML

#

The API appears to return the response in different formats depending on the headers passed in

#

Yea in Firefox I just used the console to see what it sends. Here's the Accept header browsers provide:

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8

curl on the other hand sends this:

Accept: */*

Haven't found where HA sets Accept but I would guess it lists XML after JSON since it prefers JSON. I think the API prefers to return JSON but returns XML if its the only one supported or preferred (like browsers specify)

wicked parrot
#

I have an energy meter helper for my power meter reader (Rainforest Eagle 200), to give me daily usage (resets daily). I have a template to apply my power rate cost and spit out a daily usage cost. When the day rolled over this morning the template did 1 update ($0.02) and then stopped updating. I've restarted HA but no updates.

#
- platform: template
  sensors: 
    daily_energy_cost:
      # unit_of_measurement: '$'
      friendly_name: 'Daily Energy Cost'
      # icon: mdi:currency-usd
      value_template: "${{ (states('sensor.daily_energy_usage') | float * 0.13609 ) | round(2) }}"
#

Ok let me take that back. So I was getting a line graph for that sensor last night and I left it open over night, which is where I saw the $0.02. Now have one of these graphs...

wicked parrot
#

ah I think I understand. Getting rid of unit_of_measurement and tossing in the dollar sign into the value_template was messing it up.

#

Next question is, how do I get HA to represent $ as a unit of measurement and have it shown before the value of a sensor?

#

I've tried both $ and USD for unit_of_measurement but both appear after the value.

marble jackal
#

You can't

wicked parrot
#

Woo hoo.

#

America.

marble jackal
#

But you can use custom cards to template how it's shown on your dashboard

wicked parrot
#

Nah it's ok, I'm fine giving up my American freedom. :)

#

Welp done with that.

white totem
#

Is it possible to make a template sensor from the GUI?

inner mesa
#

No

white totem
chilly locust
#

Is there a way to set a state value as an attribute at a certain time? I'd like to add an attribute to some of my sensors that stores a historical value so I can easily compare data. I have hourly, daily, and monthly sensors that I'd like to capture the last value before it resets and store it as that attribute. Is this possible?

inner mesa
#

no, you cannot programmatically add an attribute to an existing entity like that

#

you can create a template sensor that records the previous state

chilly locust
#

The sensors I'd like to add to are already template sensors.

#

I already have an attribute for kwh cost added to them

inner mesa
#

then you can make them trigger-based template sensors and use trigger.from_state.state one of the attributes

floral shuttle
# toxic dome Of course the JSON it does return is a top-level array which then can't be stuff...

thx for your patience, but this is going nowhere. The header: settings does not make any difference, as they still are transformed to JSON. Ive tried all 3 xml options. The command_line has me guessing on all details. I cant find the correct syntax for either the command or the path/attributes... Trying all of this in the terminal, and it keeps throwing errors on parser near this and that, or no matches found ....

chilly locust
#

I lied, only some of them are. The others are utility_meter sensors. I'd have to convert those.

inner mesa
#
- trigger:
    - platform: state
      entity_id: input_number.foo
  sensor:
    - name: test
      unique_id: test_sensor
      state: "{{ trigger.to_state.state }}"
      attributes:
        old_value: "{{ trigger.from_state.state }}"
toxic dome
# floral shuttle thx for your patience, but this is going nowhere. The header: settings does not ...

Strange. When I did this just now I got back this XML:

# curl -H'Accept: application/xml' https://mijn.easyenergy.com/nl/api/tariff/getapxtariffs\?startTimestamp\=2022-10-17\&endTimestamp\=2022-10-18
<ArrayOfEnergyTariff xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/GreatValue.Common.Models.Tariffs"><EnergyTariff><SupplierId>0</SupplierId><TariffReturn>0.12831</TariffReturn><TariffUsage>0.139857900000000000</TariffUsage><Timestamp xmlns:d3p1="http://schemas.datacontract.org/2004/07/System"><d3p1:DateTime>2022-10-16T22:00:00Z</d3p1:DateTime><d3p1:OffsetMinutes>0</d3p1:OffsetMinutes></Timestamp></EnergyTariff><EnergyTariff><SupplierId>0</SupplierId><TariffReturn>0.11441</TariffReturn><TariffUsage>0.124706900000000000</TariffUsage><Timestamp xmlns:d3p1="http://schemas.datacontract.org/2004/07/System"><d3p1:DateTime>2022-10-16T23:00:00Z</d3p1:DateTime><d3p1:OffsetMinutes>0</d3p1:OffsetMinutes></Timestamp></EnergyTariff><EnergyTariff><SupplierId>0</SupplierId><TariffReturn>0.10565</TariffReturn><TariffUsage>0.115158500000000000</TariffUsage><Timestamp xmlns:d3p1="http://schemas.datacontract.org/2004/07/System"><d3p1:DateTime>2022-10-17T00:00:00Z</d3p1:DateTime><d3p1:OffsetMinutes>0</d3p1:OffsetMinutes></Timestamp></EnergyTariff><EnergyTariff><SupplierId>0</SupplierId><TariffReturn>0.08964</TariffReturn><TariffUsage>0.097707600000000000</TariffUsage><Timestamp xmlns:d3p1="http://schemas.datacontract.org/2004/07/System"><d3p1:DateTime>2022-10-17T01:00:00Z</d3p1:DateTime><d3p1:OffsetMinutes>0</d3p1:OffsetMinutes></Timestamp></EnergyTariff>...</ArrayOfEnergyTariff>
floral shuttle
#

yes, me too πŸ˜‰ now let me try to template those timestamps to startTimestamp={{now().strftime('%Y-%m-%d')}}&endTimestamp={{(now()+ timedelta(days=1)).strftime('%Y-%m-%d')}}

#

btw, in a command_line sensor, what would be the path? Is there a special syntax to have it throw all of the ArrayOfEnergyTariff into the attribute?

toxic dome
#
sensor:
  - platform: rest
    name: Energy Tariffs
    resource: "https://mijn.easyenergy.com/nl/api/tariff/getapxtariffs"
    value_template: "ignore me"
    params:
      startTimestamp: "2022-10-17"
      endTimestamp: "2022-10-18"
    headers:
      Accept: "application/xml"
    json_attributes_path: "$.ArrayOfEnergyTariff"
    json_attributes:
      - EnergyTariff

This just worked for me

#

@floral shuttle

floral shuttle
#

o wow, bingo! Ive templated the timestamp to: params: startTimestamp: "{{now().strftime('%Y-%m-%d')}}" endTimestamp: "{{(now()+ timedelta(days=1)).strftime('%Y-%m-%d')}}" and now can do {{state_attr('sensor.energy_tariffs_rest','EnergyTariff')[23].TariffUsage}} 🌢️ 🌢️

#

now only thing left is to find a an availability template for [24] to [47] ... and create that trigger template sensor to only trigger after 16:00 and condition on their existence...

#

this is huge! thank you so much.

toxic dome
#

np

#

honestly had no idea rest sensors worked on xml so that's cool in a pinch too. Plus it means xmltodict is available if necessary without sshing for xq

floral shuttle
#

Unable to parse output as JSON: <ArrayOfEnergyTariff xmlns:i= etc etc

#

so its already in the command to use the xml, but it doesnt accept it just yet.

keen abyss
rocky crypt
#

Hey there. I have a value_template that is throwing a fit, so I'm guessing I am coding it wronge :(. I want it to only return true if ".." exists in states field... Here is what I have:
{% if states('input_text.bypassed_zones').count('..') = 1 %}
Can I count a text in the state? Am I doing it wrong?

#

I am using count because I am going to have it more complicated when all said and done. So, I really do want to count how many occurrences of ".."

marble jackal
#
{% set test = "foo...bar...petunia" %}
{{ test.count("..") > 0 }}
#

that results true

#

your template only returns true if it is exactly 1, in my example it is 2, so your version would return false

#

Oh, and you need to use ==, not =

rocky crypt
#

Great πŸ™‚ I actually wanted exactly one. I miss worded the question. Because then I am going to have another if >1 πŸ™‚

#

So was the real problem just because I didn't use == I wonder?

marble jackal
#

Yes

rocky crypt
#

Perfect! Yep, I just tested it! Thank you!!!!

tepid onyx
marble jackal
#

how do you mean, what is the template which gives errors?

tepid onyx
#

sorry trying to find a working code dump site

plain magnetBOT
#

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

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

tepid onyx
#

the topic sites are toast, fyi

marble jackal
#

value_template and availability are not supported for that sensor

#

I don't see senders in the docs as well

mighty ledge
#

just looked at the code

marble jackal
#

you can use search

mighty ledge
#

@tepid onyx you have to make a template sensor using the imap sensor

marble jackal
#
sensor:
​  - platform: imap_email_content
    name: "parcel_notify"
    server: imap01.server
    port: 993
    username: parcel
    password: pass
    verify_ssl: false
    search: FROM <yo@mumma.com>, SUBJECT <Parcel Notification>
mighty ledge
#

Not sure the <> are needed

marble jackal
#

not really sure as well, just copying the example here πŸ˜›

mighty ledge
#

I'd assume they are required

edgy river
#

Hi Guys, I have a remotecontrolled light, which I can also toggle on/off via HASS. Unfortunately the on/off state is not reported, but HASS receives the remotecontrol command.

So I guess I would create a virtual switch, which controls the light, when used via HASS, but also gets changed, when the remote is uses. Is there a template for this or do I need to create one for myself.

Cant imagine this does not exist, but I absolutely do not know what to google πŸ™‚

tepid onyx
#

damn time difference

wild pumice
#
template:
  - sensor:
      - name: tesal-model-x-rated-range
        unique_id: 3a33104e-42d7-4e4e-b705-38437556520c
        unit_of_measurement: Km
        state_class: measurement
        state: >- 
          {{ ((states('sensor.sensor.tesla_rated_battery_range_km') | float - states('sensor.sensor.tesla_battery_level')) * 100) | round }}

I have made tis code but is shows up as unavailable

acoustic arch
#

when i start a timer, can i trigger at a certain time?

#

I see idle/active etc, but not a time

tired kayak
#

dashbord entities timestamp to ddmmyyyy_hhmmss

marble jackal
radiant spindle
#

hey, I'm having a look at an example that looks like this label: '[[[ return states["sensor.lumi_lumi_weather_temperature"].state + "Β°C" ]]]'

#

why is he using [] and not {} ?

inner mesa
#

it's from a frontend card, and it's Javascript

radiant spindle
#

oh

#

thanks

twin gull
#

End goal:
Price per month (nice to have is graphs for days as well. Not sure if graphs need daily entities or if they can use monthly. Without the energy dashboard.
What I have got:

  • Nordpool entity for price per hour
  • Power sensor that have 3 entities: Current power draw (W), current hour draw (kWh) and what i assume is daily power draw (kWH) seeing my price depends on the hour I need to look into current power or hour draw..

I'd like to use the entities in several cards so I'd like to move away from energy dashboard (which i know shows what i want to). Kind of lost what to Google, especially combining the hourly price with hourly usage and integral it. I understand I basically want to do what the energy dashboard already does (energy used + price entity)

coarse tiger
#

Have a look at the utility meter

twin gull
#

Utility meter in GUI only gives me the integral power usage. Cant use it to do power usage * current price

#

So i kinda assume I need my own integral template sensor in order to do that and then use several utility meters to reset it? But I'm quite lost for the first integral template.

glad moth
#

Anyone know why my template is stating an error that no default was specified? It seems to run okay but gives: "Error evaluating 'template' trigger for 'HVAC Fan: living room and bedroom temp differ less than 4 deg then fan auto': ValueError: Template error: float got invalid input 'unavailable' when rendering template '{{ (states('sensor.motion_sensor_2_temperature') | float) - (states('sensor.t6_pro_z_wave_programmable_thermostat_air_temperature') | float) < 4 }}' but no default was specified"

inner mesa
#

one of your sensors has a state of "unavailable"

#

and you didn't provide a default

glad moth
#

Thanks! This helps a lot!

wild pumice
#
template:
  - sensor:
      - name: tesal-model-x-rated-range
        unique_id: 3a33104e-42d7-4e4e-b705-38437556520c
        unit_of_measurement: Km
        state_class: measurement
        state: >- 
          {{ ((states('sensor.sensor.tesla_rated_battery_range_km') | float - states('sensor.sensor.tesla_battery_level')) * 100) | round }}

I have made tis code but is shows up as unavailable

waxen rune
#

I guess changing sensor.sensor.tesla_rated_battery_range_km and sensor.sensor.tesla_battery_level to
sensor.tesla_rated_battery_range_km and sensor.tesla_battery_level is a start.
Then testing the template in Dev Tools

warped blade
#

I am trying to get tts to tell me the rain chance for the day. How would I get it to give me the actual percent? Right now i have it setup like this alias: weather test
description: ""
trigger:

  • platform: event
    event_type: rhasspy_Test
    condition: []
    action:
  • service: tts.google_cloud_say
    data:
    entity_id: media_player.livingroomtv
    message: >-
    {% set forecast = state_attr('weather.forecast_home', 'forecast')[0] %}
    You can expect today to be {{forecast.condition}} with a high of
    {{forecast.temperature}} and a low of {{forecast.templow}} and a
    {{forecast.precipitation_probability}} percent chance of rain
    mode: single
#

it only say "and a percent chance of rain" instead of like a zero percent chance of rain

silent seal
#
and a {{forecast.precipitation_probability}} percent chance of rain

would become

{% iif forecast.precipitation_probability > 0, "and a {{forecast.precipitation_probability}} percent chance of rain", "" %}

Or something similar

warped blade
#

oh ok

silent seal
warped blade
#

thats is very helpful. thank you

silent seal
#

You're welcome πŸ™‚

#

You could also map different %s to different words if you wanted, e.g. <5%, don't say anything, 5-30% low, 30-60% medium, and 60% high or similar πŸ™‚

warped blade
#

oh cool

#

so i would just replace the line in my automation "and a {{forecast.precipitation_probability}} percent chance of rain"

silent seal
#

With the iif example? Probably, though you can use the template editor to check what I wrote actually works

plain magnetBOT
#

When working with templates, don't forget:

  • You can test them in Developer tools -> Templates
warped blade
#

ok, when i put it into the template it say unknown tag iif

silent seal
#

That's because I used {% instead of {{, etc πŸ™‚

#
{{ iif forecast.precipitation_probability > 0, "and a {{forecast.precipitation_probability}} percent chance of rain", "" }}
warped blade
#

I dont know enough about all this to understand what the new error i'm getting means. "TemplateSyntaxError: expected token 'end of print statement', got 'forecast'"

marble jackal
#

iif can be used as function or filter, but not like this

#

It needs parenthesis

#
{{ iif(forecast.precipitation_probability > 0, "and a {{forecast.precipitation_probability}} percent chance of rain", "") }}
silent seal
#

Yeah, I was just experimenting, it would probably just be easier to do:

{% if forecast.precipitation_probability > 0 %}and a {{forecast.precipitation_probability}} percent chance of rain{% endif %}
warped blade
#

ok, i think i actually understand those examples!

marble jackal
#

That would also work

silent seal
marble jackal
#

Basically you don't need to add > 0

#

If it's 0 it will return false

#

You can also use
{{ 'and a ' ~ forecast.precipitation_probability ~ }} 'percent chance of rain' if forecast.precipitation_probability }}

warped blade
#

awesome! that last one seems to work perfectly

#

my wife loves it. thank you so much, you both helped me lear quite a lot

silent seal
#

There's lots to learn when it comes to templates πŸ˜„

warped blade
#

I am very quickly learning that. I know next to nothing about programming so I am slowly learning syntax and logic.

mighty ledge
#

sensei is typing

frank gale
#

Can I have a list from all the lights from the Integration 'WLED'?

{{ integration_entities('WLED') | select('search', 'light.') | list }}

This returns me the entities from a device named 'WLED' that's a member from the integration "WLED".
Am I understanding something wrong?

deft timber
#

The following works for me: {{ integration_entities('wled') | select('search', '^light\.') |list}}

mighty ledge
#

if you only want lights, you can use what slashback wrote, but you don't really need the .

#
{{ integration_entities('wled') | select('search', '^light') |list}}
#

the ^ means startswith

frank gale
#

that still returns me exact the same one with my previous post

#

I have 3 devices from wled

#

I only get one returned