#templates-archived

1 messages · Page 150 of 1

mighty ledge
#

You can actually see all of this in the trace functions for automations or scripts

#

IIRC the parent_id should match an ID for an automation

#

the user_id should match the user as long as it was called from the UI (or from a api like alexa if you logged in via it's own cridentials)

weak flax
#

I have created several input_booleans and other configurations successfully in my configuration.yaml but for some reason none of the sensors I specify show up in the web UI.

weary pumice
#

Good morning everyone, quick template question: Is there a proper way / built in function to check if entity "x" belongs to domain "y", something like is_domain("x", "y") returning true or false?

weary pumice
inner mesa
#

There's no is_domain, but the last one should work

fossil venture
#

Or this {{ states.sensor.something.domain }} gives sensor

#

So {{ states.sensor.something.domain == 'sensor'}}

weary pumice
marble jackal
#

And entities changed by the script, will have the same context as the script itself, right?

#

No wait, that's not right I guess

#

If I have script 1 and in that script I start script2, and perform some state changes, both the entities changed, and script2 will have the same context

marble jackal
#

Okay, so this seems to work for me, it will show all cast entities which are changed by my script

{% set context = states.script.test_script.context %}
{{ context in expand(integration_entities('cast')) | map(attribute='context') | list }}
{%- set ns = namespace(context = []) %}
{%- for p in expand(integration_entities('cast')) %}
  {%- if p.context == context %}
    {%- set ns.context = ns.context + [p.entity_id] %}
  {%- endif %}
{%- endfor %}
{{ ns.context }}
#

script1, script2 and the entities changed by the script all have the same context (until the entities are changed again by something else, eg volume change on the device)

#

The 2nd line will be used in a wait_template to ensure the actions are performed. I might add a repeat after that to add more entities in case there are more service calls with a delay in between or something like that

#

Well, I have something to do now 🙂

#

(besides working for my boss)

mighty ledge
#
{{ expand(integration_entities('cast')) | selectattr('context','eq', context) | map(attribute='context') | list }}
#

just keep in mind that probably won't work during execution as the context object will be the momentary version with a user_id or parent_id attached

#

at that point you can just compare the ID that you care about

#
{{ expand(integration_entities('cast')) | selectattr('context.user_id','eq', context.user_id) | map(attribute='context') | list }}
marble jackal
#

Ah, yes, the loop is not needed, I was thinking to difficult

mighty ledge
#

I’ve never looked at the context isequal override. It mighty just compare the ids or have some intelligence to it, so it may work.

#

With our matching the ids in the select*

#

Without*

marble jackal
#

I actually don't want the user_id, I want to link it to the specific script activation, as it can run multiple times in parallel

#

But I think this will work 🙂 Thanks a lot

mighty ledge
#

That would be the parent_id then

marble jackal
#

Well, with the template above, and running a simple script just playing an mp3 on some speakers, and this template:

{% set context = states.script.test_script.context %}
{{ context in expand(integration_entities('cast')) | map(attribute='context') | list }}
{{ expand(integration_entities('cast')) | selectattr('context','eq', context) | map(attribute='entity_id') | list }}
{{ context }}

I get this:

True
['media_player.beneden_groep', 'media_player.floris_mini', 'media_player.pepijn_mini', 'media_player.slaapkamer_hub']
Context(user_id='24c8260fb51f4fb995e5aeaaaa3edd1b', parent_id=None, id='ec6b9ac1e1b00333f43de6970883217e')
#

The list of entities is correct, those are the ones I targeted, but there is no parent_id

mighty ledge
#

Maybe it’s just Id then

#

I haven’t played with context and scripts called from an automation. Something has to point to it though

mighty ledge
#

Ok, I know the behavior now

#

The state machine does contain the last context for each script

#

so you can search the state machine for the origin

#

so what you have makes sense, and the entire context object matches

#

FYI it is the ID

#

not the parent_id

#

and the context object doesn't tell you the origin, which is opposite what I thought.

#

it tells you which objects have that context

#

So, typically, if an automation has a context object, and it matches a bunch of entity_id's, that's most likely the origin

distant plover
mighty ledge
#

deactivated isn't a thing in home assistant, so what do you mean

#

@distant plover

distant plover
#

Hmm.. it's probably the translation then. How about 'disabled'?

#

If I click on an entity I can 'deactivate' it or perhaps disable it

mighty ledge
#

if entities are disabled, they aren't in the state machine

#

i.e. they won't show up in any templates

distant plover
#

"Disabled by Config entry. Disabled entities will not be added to Home Assistant."

mighty ledge
#

exactly, so see my previous response

distant plover
#

That's what I thought... lemme check again

mighty ledge
#

an entity being removed won't update the state of that template BTW

#

so that's probably what you're seeing

#

reload your templates after removing the entity

distant plover
#

Looks like I needed a restart of HA. Reloading just template entities didn't help. Oh well, fixed now. Thanks.

mighty ledge
#

the state object was probably still in the state machine then

#

reloading the integration that created the disabled entities would have worked then

tawny coral
#

Unsure of which channel is correct but i'll try here first. Do tell me if my request should go somewhere else.
I have the following sensor: https://pastebin.com/NfiBP90R
It seems to turn on and off as expected. My issue is that i can't seem to figure out if it loads the json attributes. I've triggered the sensor and checked the trace of an automation (https://pastebin.com/0KtZdNXP) but it doesn't list the attributes that are supposed to be picked up. I've verified that the data is available in the broker

teal cove
#

Hiya! I noticed template shorthand notation could be a little more consistent. When in a condition-action, the syntax is - condition: "{{ true }}" while when in a regular automation condition, that syntax isn't allowed and I have to use - "{{ true }}" instead.
The problem might be me, but that has me look up the correct syntax every time I use it.
Now, should I open an issue or a feature request (or is this old news and already being worked on?) 😅

mighty ledge
teal cove
#

got me. post there now?

mighty ledge
#

There is no yaml channel, but what you're talking about is yaml being picky not templates

#

the condition field expects a list

teal cove
#

Yes, absolutely.

mighty ledge
#
  • conditions: "{{ ... is a single item
#

not a list

teal cove
#

I thought of ```
conditions:

  • condition: "{{ ...
  • condition: "{{ ...
mighty ledge
#

shorthand notation is just:

teal cove
#

or is that a bad Idea

mighty ledge
#
  • "{{}}"
#

in that regard

#

or is that what you're pointing out

teal cove
#

Yes 😅

mighty ledge
#

longhand:

- condition: template
  value_template: "{{ }}"

shorthand:

- "{{ }}"
#

nothing between

teal cove
#

Yeah I wanted to ask whether I should open an issue or a feature request if I wanted to suggest adding this: ```
conditions:

  • condition: "{{ ...
  • condition: "{{ ...
mighty ledge
#

that would be feature request, but why would you want that

#

the whole point of templates is to put your entire condition in the template

#

so you woudln't have multiple, hence the singular - "{{ }}"

teal cove
#

okay. I think its easier to remember but I might be alone on that one 😅

#

because condition-action uses this syntax already (obviously, because its an action)

#

okay, not sure if I really understand, but if you say it makes the most sense the way it is, I'll discard my idea 😅

mighty ledge
#

I don't like shorthand, I use longhand

#

because it makes the most sense to me. You're welcome to put in any FR you want

teal cove
#

ohh I understand. Well I dont put ALL templates into one template, because its easier to understand when I look at it a few months after writing 😅

buoyant pine
#

Make it multiline?

teal cove
buoyant pine
#

One of my favorite comments ever on a FR is "if I could give this negative votes, I would"

teal cove
#

🤣 🤣 🤣

teal cove
#

After seeing THAT feature request, I am DEFINITELY shooting my shot...

marble jackal
buoyant pine
#

ur a list

#

Ha gottem

mighty ledge
opaque creek
#

Hey! I want to make a sensor that shows my heat pumps current target temp. Cant make a code work, do anyone know what a working code should look like?

teal cove
opaque creek
#

Shouldnt this show the current target temp:

  • platform: template
    sensors:
    temperature:
    friendly_name: "Daking Target Temp"
    value_template: "{{ state_attr('climate.daikinap42587', 'temperature') }}"
#

No it doesnt have its on Entity

#

its only in the "attribute" of the core entity

#

Cant I make a sensor of some of them and track them in a chart to see the attribute change during the day?

teal cove
#

Looks fine to me, assuming the correct indentation was lost in the process of posting here. Elaborate on 'code doesnt work' 🤔

opaque creek
#

it give me green check, but check config give me:
Invalid config for [sensor.template]: expected dictionary for dictionary value @ data['sensors']. Got None
extra keys not allowed @ data['friendly_name']. Got 'Daking Target Temp'
extra keys not allowed @ data['temperature']. Got None
extra keys not allowed @ data['value_template']. Got "{{ state_attr('climate.daikinap42587', 'temperature') }}". (See ?, line ?).

teal cove
#

Not sure, (I'm not a pro) but looks like wrong indentation?
You should use the modern configuration format anyway, instead of legacy format.

#

in configuration.yaml:

template:
  - sensor:
      - name: "Daking Target Temp"
        unit_of_measurement: "°C"
        state: "{{ state_attr('climate.daikinap42587', 'temperature') }}"
opaque creek
#

hm ok I get error... guess the rest of my configuration.yaml is messed up lol

#

since I laready have tempplate and sensor

#

do I need to add that again?

teal cove
#

I don't know what you mean exactly.
The code I sent is a replacement to yours, and it goes into configuration.yaml instead of sensors.yaml.

opaque creek
#

seemed to went trough now, awesome! lets see what the sensor show

teal cove
#

That tool is only to check integrity of YAML, not whether your yaml does what you want it to do or not.

opaque creek
#

yeha I mean me as a newbie probably dont know all the "-" and spacings etc to get it right and that one at least give me that right?

teal cove
#

Yes and no. For example, your yaml passed the check, because its valid yaml. But your yaml doesn't do what you want. 😅

opaque creek
#

but in my configuration file now I have the code you cave me... will All the new sensor I do go under that "template" or do I need to re write it again if I want another sensor?

teal cove
#

for more sensors you'd do:

template:
  - sensor:
      - name: "Daking Target Temp"
        unit_of_measurement: "°C"
        state: "{{ state_attr('climate.daikinap42587', 'temperature') }}"

  - sensor:
      - name: "New Sensor"
        unit_of_measurement: "°C"
        state: "{{ ... }}"

  - sensor:
      - name: "Even Newer Sensor"
        unit_of_measurement: "°C"
        state: "{{ ... }}"
opaque creek
#

Ah ok, I must type the "template" for all sensor?

#

Right!

#

ok

#

cool

teal cove
#

sorry, formatting was off. fixed now

opaque creek
#

Cool then I get it! Thanks! I did add a sensor some days ago from GitHub, and just copy and pasted the code. And under the code you gave me I now have that sensor in this way:
sensor:

  • platform: greenely
    email: XXXX
    password: XXX
    usage: true
    prices: true
#

that "-" is there infront of the platform, hm

buoyant pine
#

Or just

template:
  - sensor:
      - name: "Daking Target Temp"
        unit_of_measurement: "°C"
        state: "{{ state_attr('climate.daikinap42587', 'temperature') }}"
      - name: "New Sensor"
        unit_of_measurement: "°C"
        state: "{{ ... }}"
opaque creek
#

Ah cool ! Thanks !

buoyant pine
#

Assuming both of those are sensors and not another type like binary sensor

opaque creek
#

nice!

teal cove
#

how do I get dem fancy colours? 🤯

buoyant pine
#

```yaml

teal cove
#

thanks!

opaque creek
#

last newbie question 😛
So this is a Template - Sensor then?
But the greenely thing I mentioned is coded
Sensor
-platform

Whats the diffrence?

inner mesa
#

One is the old format and one is the new one. Both are described on the docs page

opaque creek
#

Ok so I could rewrite them with this new way?

teal cove
#

Nope, the greenly sensor isn't a template sensor.

opaque creek
#

Hm right! Yeha that one required some files to be added etc

inner mesa
#

Oh, right

#

There goes my New Year's resolution about not jumping into the middle of a conversation

opaque creek
#

hehe

#

but thanks for the help!

opaque creek
#

What decides what entitys is created when adding a new device?

#

why wasnt this target temp created for example? but some other was

#

haha I know I always ask the best questions 😛

teal cove
#

The integration decides which sensors it adds automatically. If you want more, you need to make your own. 💁

opaque creek
#

Fair enough 😄

wicked oracle
#

Hi guys, may I request a bit of help ? I do have an Awtrix display (DIY) and I'm trying to integrate it in HA. I'm almost there except for the "state" which is giving me headaches...(MQTT)

#

Sorry if I'm not in the correct place

rigid olive
#

Hi all, I am trying to build a URL string with a template for the REST integration. I need to insert today's date in the URL. The following works as expected in the template panel of the developer tool but not in the configuration.yaml file.

#

{%- set my_string = 'https://api.tidesandcurrents.noaa.gov/api/prod/datagetter?product=predictions&application=NOS.COOPS.TAC.WL&begin_date=' %}
{%- set my_string = my_string ~ now().timestamp() | timestamp_custom('%Y%m%d' ) ~ '' %}
{%- set my_string = my_string ~ '&end_date=' %}
{%- set my_string = my_string ~ (now() + timedelta( days = 1)).timestamp() | timestamp_custom('%Y%m%d') ~ '' %}
{%- set my_string = my_string ~ '&datum=MLLW&station=9410840&time_zone=lst_ldt&units=english&interval=hilo&format=json' ~ '' %}
{{ my_string }}

rigid olive
#

It actually looks like the integration looks for a leading "http" string and fails when it ends up being a jinja bracket instead.

inner mesa
#

Did you introduce the multi line template with >- and use resource_template?

rigid olive
#

Ah, RTFM badge for me. I was using "resource" instead of "resource_template"

#

Thx

real terrace
#

Any thoughts on why I would be unable to change a Lutron switch into a light with the usual-

light:

  • platform: switch
    name: Switch Name - Light
    entity_id: switch.lutron_switch_id
#

I’m changing a tasmota outlet into a light in the same manner with no issues

buoyant pine
#

if you're adding another light: in your config, that's why

real terrace
#
  - platform: switch
    name: Switch Name - Tasmota
    entity_id: switch.tasmota_switch_id
  - platform: switch
    name: Switch Name - Light
    entity_id: switch.lutron_switch_id ```
#

Also if I only use the Lutron one it still does not create the light

buoyant pine
#

Check the log

marble jackal
tawny coral
#

is attribute data now showed in trace?

marble jackal
#

How do you mean?

tawny coral
#

not*

#
              "id": "0",
              "idx": "0",
              "platform": "device",
              "entity_id": "binary_sensor.blueiris_driveway_motion",
              "from_state": {
                "entity_id": "binary_sensor.blueiris_driveway_motion",
                "state": "off",
                "attributes": {
                  "friendly_name": "BlueIris Driveway Motion",
                  "device_class": "motion"
                },```
#

this is from a trace

#

the attributes are missing. it just says friendly name and device class. not the json attributes

marble jackal
#

I'm not sure which attributes are missing, but if the entity does have more attributes, I guess they will show if you use a state trigger instead of a device trigger

tawny coral
#

Ok i'll try flipping it to state instead

shut silo
#

So, setting up a unique_id should set the entity-id to binary_sensor.unique_id, right?

#

This one works:

    - sensor:
      - name: "Leistung für Überschussladen"
        unique_id: charging_current
        device_class: power
        unit_of_measurement: "W"
        state: >-
          {% set charging = is_state('switch.superb_iv_charging','on') %}
          {% set offset = states('input_number.current_offset') %}
          {% set generated = states('sensor.senec_solar_generated_power') %}
          {% set housepower = states('sensor.senec_house_power') %}
          {% set current = generated|float - housepower|float - offset|int %}
          {{ '%.2f' % current|float if current|float > 0.00 or charging else 0.00 }}
#

This on not:

    - binary_sensor:
      - name: "Abreiseplanung 1: Wiederkehrend"
        unique_id: deptimer1_recurring
        state: >-
          {{ true if is_state_attr('switch.superb_iv_departure_timer_1','timerFrequency','cyclic') else false }}
#

First ones entity-id is sensor.charging_current as expected.
Second one has binary_sensor.abreiseplanung_1_wiederkehrend instead of binary_sensor.deptimer1_recurring.
Maybe the ":" cause this?

marble jackal
#

The entity_id will be based on the name not on the unique_id

#

But if you provide a unique_id, you can change the entity_id in the GUI

mighty ledge
mighty ledge
shut silo
mighty ledge
shut silo
#

OK thanks. So unique id will never be used in UI?

#

In old style templating there was friendly_name. That was easier

#

Name was entity_id, friedly_name was for the UI.
Now I have to set name to get some thing friendly for the UI and change the entity_id later. Not very smart.

marble jackal
#

You can set only the unique_id, and not the name, and then set a friendly_name attribute

tawny coral
upper tinsel
#

Hello, someone knows about json, I would like to extract multiple data at once from an api.. I would like to extract the name and the schedules.

#

Here is the answer in json.

narrow surge
#

Is this possible? (as_timestamp(today_at("18:00")))

inner mesa
#

I don't see why not. did you try it?

#

here: {{ (as_timestamp(today_at("18:00"))) }} -> 1645063200

narrow surge
#

ah thanks, was using it in something bigger and got an error

inner mesa
#

devtools -> Templates is your friend here

narrow surge
#

How can I do after {{ (as_timestamp(states("sensor.motorola_one_hyper_next_alarm" )) - 1800) }} in the template manager?

#

so if set my alarm, minus 30 minutes that time, after that it should be true

mighty ledge
#

{{ states("sensor.motorola_one_hyper_next_alarm" ) | as_datetime | as_local - timedelta(minutes=30) > now() }}

narrow surge
#

Seems to be always true

mighty ledge
#

Are you past the alarm time - 30 minutes?

narrow surge
#

Current time is 18:45, setting alarm to 16:00 = true, and to 20:00 = true

mighty ledge
#

Ok, then it’ll be true because now is past the alarm time - 30 minutes

narrow surge
#

It should be false >31 minutes before the alarm time.

mighty ledge
#

18:45 > 15:30

#

You set the alarm time to 1600

#

18:45 is past that no matter what. Not sure what you expect

narrow surge
#

Doesnt matter if I set it to 18:10, 18:35, 19:00, its always true

mighty ledge
#

What’s the state of your sensor

narrow surge
#

2022-02-17T16:40:00+00:00

mighty ledge
#

Remove the as_local

narrow surge
#

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

mighty ledge
#

Yes

narrow surge
#

Meh

#

The problem is that after the alarm went off it forgets

#

It cannot calculate -30 minutes anymore.

#

Which is fine

#

Hmm

mighty ledge
#

Build that into your template

narrow surge
#

Now its never true anymore

mighty ledge
#

No clue what you’re using at this point, based on your sensor state, the one you posted should work.

narrow surge
#

So what does it need to do:
It has to always be true after 09:00
It needs to be true 30 minutes before the alarm goes off (So the lights are bright if I'm out of bed before the alarm)
It should be false after sun.sun elevation is above 4 (which I now handle with a different numeric_state condition)

#

So this does most of the above, however it becomes false again after the alarm went off before 09:00

              {{ as_timestamp(states("sensor.date_time").replace(",","")) >=
              (as_timestamp(states("sensor.motorola_one_hyper_next_alarm" )) -
              1800)   or   now().hour >= 9 }}
#

Because I think after the alarm went off it switches to the next upcoming alarm, which will then be in 24 hours.

mighty ledge
#

You won’t be able to make that template if the sensor wipes out it’s data after the alarm is hit. It’s impossible

narrow surge
#

Maybe an if statement that checks if the alarm is set for today if so it converts it to just the time.

mighty ledge
#

Either it has to keep the data or you have to use a different method like turning on an input boolean or a trigger based template sensor.

narrow surge
#

Hmm, what do you suggest I use?

mighty ledge
#

Whatever you want to get the job done

#

Either way, a single template won’t work.

#

To me, it seems odd that you want it to stay on. Id just make a momentary template sensor that’s just on for the minute that the alarm should go off. Then trigger off that.

narrow surge
#

Well I want it to stay on until 09:00, until this picks it up: or now().hour >= 9

inner mesa
#

I feel like we've been discussing this same problem for like a week 🙂

mighty ledge
#

Make a template that works off a trigger then. On when the sensor = the current time, off when the its 9

narrow surge
#

Yep, still struggling to come up with a solution, but I believe the input boolean could work

#

template that works of a trigger,

#

Should it be an external automation?

narrow surge
#

It cannot be done through the GUI?

inner mesa
#

correct

narrow surge
#
  - trigger:
      - platform: state
        entitiy_id: sensor.motorola_one_hyper_next_alarm
    sensor:
      - name: "Alarm"
        state: '{{ as_timestamp(states("sensor.date_time").replace(",","")) >= (as_timestamp(states("sensor.motorola_one_hyper_next_alarm" )) - 3600) }}'
narrow surge
#

This also goes to false when the alarm went off, so it does exactly the same as in the automation :S

#

And the trigger-based-template-sensors does not have the options the automation Template trigger has.

mighty ledge
#

As I explained before, your trigger on needs to be the template, your trigger off needs to be an @9. Your state template needs to be based on the triggers, not the value of your sensor

#

I don't know why you keep going back to the as_timestamp either

#
- trigger:
  - id: "on" 
    platform: template
    value_template: "{{ now() >= states("sensor.motorola_one_hyper_next_alarm" ) | as_datetime - timedelta(minutes=30) }}"
  - id: "off"
    platform: time
    at: "09:00:00"
  sensor:
  - name: "Alarm"
    state: "{{ trigger.id == 'on' }}"
#

or make an automation that does this with an input boolean

narrow surge
#

Oops, just did

mighty ledge
#

So: To recap: You cannot use a template as your state. It's not possible based on how your sensor behaves.

narrow surge
#

Thanks, using a boolean which I turn on/off using 2 automations, automations also enable conditions, so I can say it should only turn on between 06:00 and 10:00

floral shuttle
#

I know this is classic, but I cant find the answer, sorry: {% set threshold = states('input_number.battery_alert_level')|float(0) %} {{states.sensor|selectattr('attributes.device_class','eq','battery') |rejectattr('state','in',['unknown','unavailable']) |selectattr('state','<',threshold) |map(attribute='name') |list}} needs to map the number to be able to do the comparison.. should be possible with a double mapping shouldnt it? (and not use the namespace construction, which I have)

#

: {% set threshold = states('input_number.battery_alert_level')|float(0) %} {{states.sensor|selectattr('attributes.device_class','eq','battery') |map(attribute='state') |map('int',default=0) |select('<',threshold) |list}}... obviously doesnt work it just returns the numbers

mighty ledge
carmine jetty
#

So I am using a template sensor to track my phone's position using the wifi bssid it is connected to in my mesh network

https://pastebin.com/9RLxRmWZ

Is there a better way of doing this, also for multiple phones? 🤔

inner mesa
#

Yes, there is a better way

#

Create a dict that maps BSSID to location and then use the sensor value as the key

vestal aspen
#

Can someone help. I need clear_effects: url: "http://10.0.0.10/api/command/" method: post content_type: "application/json" payload: '{"command":"Effect Stop","multisyncCommand":false,"multisyncHosts":"","args":["24"]}'

#

to look like

#
    url: "http://10.0.0.10/api/command/"
    method: post
    content_type: "application/json"
    payload: '{"command":"Effect Stop","multisyncCommand":false,"multisyncHosts":"","args":["{{ state_attr( 'sensor.nhl_sensor', 'home_score' )}}"]}'```
#

but that gives me yaml errors

#

syntax?

inner mesa
vestal aspen
#

so there is no way to pass an attribute as a string?

#

a sensor value in a restful call

inner mesa
#

You're trying to put a template there. You can't do that

vestal aspen
#

well how then, would i get a current dynamic value from a sensor and use it to build an restful api call.

carmine jetty
inner mesa
vestal aspen
#

nhl api as a sensor

#

and restfulcommand intergration to send to fPP

inner mesa
#

The problem is that you're using the same quotes both inside and outside the template

vestal aspen
#

i think this is working.. set_actbackground: url: "http://10.0.0.10/api/command/" method: post content_type: "application/json" payload: "{\"command\":\"Effect Start\",\"multisyncCommand\":false,\"multisyncHosts\":\"\",\"args\":[\"{{ state_attr( 'sensor.nhl_sensor', 'away_id' ) }}\",\"\",\"true\",\"true\",\"false\"]}"

#

its terrible but works possibly

#

testing now

#

yup that worked

#

but is there a better way to write that without escaping all the quotes?

#

I'm way new to yaml

#

freaking doc z's crew made me install HA.. now i'm challenging myself.

inner mesa
#

You might be able to use '' '' or ''' '''

#

Multiple single quotes

vestal aspen
#

This is all for a live scoreboard on a projector in my window

#

and when the team scores the goal horn goes off on my house, audio and all

#

i got the live scores working, and the goal detection, game state detection. now working on changing the opposing team logo dynamically on the display based on away team ID

#

so now thats working

#

good deal

tawny coral
#

i have the following error message:
Invalid config for [sensor.template]: [state_class] is an invalid option for [sensor.template]. Check: sensor.template->sensors->realtime_consumption_a->state_class. (See ?, line ?).

These are my sensors:
https://pastebin.com/sxMgBa54

#

i understand that it wants me to remove state_class. But state_class is required for long term statistics (and me being able to add it to the energy section of homeassistant. How do i proceed?

inner mesa
#

You're using the legacy format and you need to use the new format for your sensor

#

Review the template sensor docs

tawny coral
inner mesa
#

You're missing some colons

tawny coral
#

ah, right i see

inner mesa
#

But that's the right format

tawny coral
#

thank you! i'll give this a shot (after adding the colons)

#

Alright yeah that seems to work however its still not showing up in "configure grid consumption"

vestal aspen
#

One more question, i should be able to use {{ state_attr( 'sensor.nhl_sensor', 'away_id' ) }} as event data in a event triggered automtation?

#

hmm that didn't work

#

i think i got it

#

team_id: '{{ state_attr( ''sensor.nhl_sensor'', ''away_id'' ) }}'

tawny coral
#

Could it be that i'm missing a "last_reset"?

#

According to the documentation it shouldn't be required

marble jackal
#

for consumption in the energy dashboard you need:

state_class: total_increasing # or total
device_clas:: energy
unit_of_measurement: kWh
tawny coral
#

Hmmm

marble jackal
tawny coral
#

ok i guess i could pull that information also

#

directly from the sensor

marble jackal
#

okay, that would be better

tawny coral
#

well actually it just shows the number of total imported watts, not kwh

#

but it's total_increasing at least

#

This should work then i guess:

    - name: "Neurio Total Increasing"
      unit_of_measurement: kWh
      device_class: energy
      state_class: total_increasing
      state: "{{ (state_attr('sensor.neurio_raw', 'channels')[3].eImp_Ws | int) / 1000 }}"```
marble jackal
#

simply dividing W by 1000 won't give you kWh

tawny coral
#

youre right, i'm silly. you've got the h factor in there

marble jackal
#

Use the link above to convert it

tawny coral
#

Thanks, i'll do that

#

Question, do i feed the current value or the total_increasing into the integration?

floral shuttle
floral shuttle
#

found something else I admit not to understand... filter: template: >- {% set threshold = states('input_number.battery_alert_level')|float(0) %} {% for s in states.sensor|selectattr('attributes.device_class','eq','battery') if s.state|is_number and s.state|float < threshold %} {{s.entity_id}} {%- endfor %} works fine in an auto-entities card. The is_number is used to filter out the entities with 'Not/Charging' . If the |is_number selects s.state to be a number, why then do I still need to set s.state|float in the comparison?

tawny coral
#

i set it up like this

    - name: "Neurio consumption Total"
      unit_of_measurement: W
      device_class: power
      state: "{{ state_attr('sensor.neurio_raw', 'channels')[3].p_W }}"```
#

and then the sensor

  - platform: integration
    source: sensor.neurio_consumption_total
    name: energy_spent
    unit_prefix: k
    unit_time: h
    round: 2```
#

the sensor provides realtime data in W, and i'm hoping the integration will turn it into kWh

flint crown
#

Is it possible to define global macros (jinja macros) and use them in all value templates (jinja templates) ?

silent barnBOT
marble jackal
#

@jade inlet this channel is intended for jinja templates, your question is better suited in #integrations-archived. Please use a code share website to share your code when you ask your question there

silent barnBOT
#

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

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

jade inlet
tawny coral
#

So i'm really struggling to figure out how to build something on json attributes loaded through mqtt. Why aren't they showing in the trace?

- platform: mqtt
  device_class: motion
  name: 'testd'
  state_topic: 'BlueIris/driveway/Status'
  value_template: "{{ value_json.trigger }}"
  json_attributes_topic: "BlueIris/driveway/Status"
  json_attributes_template: >
    {
        "trigger": {{ value_json.trigger}},
        "object": {{ value_json.memo.split(":")[0] }},
        "type": {{ value_json.type}}
    }```
mighty ledge
#

Strings need quotes numbers and bools do not

#
- platform: mqtt
  device_class: motion
  name: 'testd'
  state_topic: 'BlueIris/driveway/Status'
  value_template: "{{ value_json.trigger }}"
  json_attributes_topic: "BlueIris/driveway/Status"
  json_attributes_template: >
    {
        "trigger": "{{ value_json.trigger }}",
        "object": "{{ value_json.memo.split(":")[0] }}",
        "type": "{{ value_json.type }}"
    }
mighty ledge
mighty ledge
#

Also, I added is_number as a test in 2022.2

#

so you can now do...

#
{{ states | selectattr('state', 'is_number') | ...
floral shuttle
#

thats what I thought, but I still get the error TypeError: '<' not supported between instances of 'str' and 'float' on ```
{{states.sensor|selectattr('attributes.device_class','eq','battery')
|selectattr('state', 'is_number')
|selectattr('state','<',threshold)|list}}

mighty ledge
#

is_number just tells you that the state is a number and does not contain non-numeric symbols

floral shuttle
#

right, so 'does not contain non-numeric symbols' is not the same as 'is type: number' ? which is what I figured it would mean

#

but i see. even though {{states('sensor.back_door_battery_level')}} is type: number, when we do {{states('sensor.back_door_battery_level' ) < threshold}} we need to use {{states('sensor.back_door_battery_level')|float > threshold}}

#

basics....

tawny coral
mighty ledge
#

"3325.342342" | is_number will return true

#

that's all it does

#

it does not take "3342324.3423243" and convert it to 3342324.3423243

floral shuttle
#

yes, I see, my confusion was in the next step, that after having established the state was a number, the comparison still needs the |float on the state, even though it is a float already (but it isnt because it is a template and that always is a string) . this leaves us no other option than the for loop (or a ns construction) and the direct template is useless in this case (because we can not set |float to that state selector)

thorny snow
#

Scarpe

mighty ledge
mighty ledge
#

Well I have an idea. I Just looked at selectattr's method and I think something like this would work if I implmeneted it.

... | selectattr('state', 'compare', '<=', value)

where compare would be a test that accepts a test but coverts the comparison to the values type.

x is compare('<=', 5)

compare would convert x to an int because the value 5 is an int

#

the problem is, does the word 'compare' make sense or should it be something else.

nocturne merlin
#

hi, im trying to make 1 sensor whit value = another sensor * number

#

im stuck in code

#

value_template: "{{ states('sensor.monthly_energy_general_kwh2')"

#

this is like im trying to get value from other sensor, but it fails at verification

#

if someone could help me, thanks!

inner mesa
#

To start, you're missing the closing }}

nocturne merlin
#

copy fail

#

value_template: "{{ states('sensor.monthly_energy_general_kwh2')}}"

#

could u see another fail?? thx

inner mesa
#

What is the error?

nocturne merlin
#

let me check

#

}} and 1 hidden .

#

thx bro

floral shuttle
frank gale
#

Is there any way to get the most common item from a list?
['foo','foo','bar']
return: 'foo'

mighty ledge
#

that are strings or int

floral shuttle
#

well, it would mean anything you use it with would be seen as if |float or |int was mapped? as if it was type: number on both sides

mighty ledge
#

yes, but it would also need to work with datetime objects

#

like, it would see that it's comparing to a datetime and then attempt to convert the left side to a dateime

floral shuttle
#

you specifically want 1 operator? because you could also use a dedicated one for the datetime comparison?

mighty ledge
#

I don't want to create 10 tests, one for each type. It would confuse users on which one to use, espeically if they don't know what they have

#

which is usually the case

floral shuttle
#

especially with datetime.... haha. yes I guess you're right about that

#

'compare' would be magnificent in that case, and take care of all the background mappings. when used in a numerical situation set both to float or int, and when used on datetimes, equalize those

#

or, given your syntax, simply use 'operator' and the 3d argument shows what to do, a bit like auto-entities does it

mighty ledge
#

🤷‍♂️

floral shuttle
frank gale
#

what's the complicated way to do this in a template if I may ask?

mighty ledge
#

you have to come up with it

frank gale
#

😂 thank you 😄

mighty ledge
#

Most likely will involve you creating and using namespace with 2 lists

frank gale
#

what should they contain?

#

to make it more clear I want to get the most common weather forecast condition. That would be making the announce: Today's weather would be mostly < the most common condition from the weather forecast>

mighty ledge
#

This probably can be condensed but this is what I mean by complicated

#
{% set stuff = ['foo','foo','bar'] %}
{% set targets = stuff | unique | list %}
{% set ns = namespace(values=[]) %}
{% for item in stuff %}
  {% set ns.values = ns.values + [dict(value=item)] %}
{% endfor %}
{% set ret = namespace(ret=[]) %}
{% for target in targets %}
  {% set kvp = dict(name=target, count=ns.values | selectattr('value','eq',target) | list | count ) %}
  {% set ret.ret = ret.ret + [kvp] %}
{% endfor %}
{% set highest = ret.ret | map(attribute='count') | first %}
{{ ret.ret | selectattr('count','eq', highest) | map(attribute='name') | list | first }}
frank gale
#

if it works it is fine 😉

#

let me try it

mighty ledge
#

it's not error proof either

#

well, i'm going down to the production line so, you're on your own after this 😉

frank gale
#

thank you!

spiral imp
#

I am moving all of my templates over to the new format, how are people creating and keeping track of unique IDs? Or is it really not necessary to use them?

marble jackal
frank gale
#

let me try yours because the other one didn't quite work

#

yes that worked!

#

the other one gave me the second most common item

mighty ledge
#

That makes no sense. They must be the same number then

frank gale
#

no they weren't

#

let me try again

mighty ledge
#

Either way, the other template is more concise

marble jackal
#

If there are multiple items which are all mentioned the most, it will probably select the one earliest in the day in your use case

frank gale
#

here's the list I tested:
['partlycloudy', 'partlycloudy', 'partlycloudy', 'partlycloudy', 'cloudy', 'rainy', 'rainy', 'rainy', 'rainy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'rainy', 'rainy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'rainy', 'cloudy', 'cloudy', 'cloudy', 'clear-night', 'partlycloudy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'partlycloudy', 'partlycloudy', 'partlycloudy', 'partlycloudy', 'partlycloudy', 'partlycloudy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'sunny', 'sunny']

#

the method from petro returns 'partlycloudy' and the method from TheFes returns 'cloudy'

#

and cloudy is the winner

#

Thank you both for your time! I have learned something new today 🙂

mighty ledge
#

ah yes, i used count instead of max

#

I still don't like using separate lists

#

1 sort and it breaks

frank gale
#

in this case, there is no other way... or not?

mighty ledge
#

the way I made it uses a list of objects that can be sorted but it will keep the name and value together

frank gale
#

I'm surprised that I'm maybe the first one that would like to know which condition will be the most common today 😛

marble jackal
#

I tried that first, but then didn't really know with the list with combined item names and counts

mighty ledge
#
{% set stuff = ['partlycloudy', 'partlycloudy', 'partlycloudy', 'partlycloudy', 'cloudy', 'rainy', 'rainy', 'rainy', 'rainy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'rainy', 'rainy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'rainy', 'cloudy', 'cloudy', 'cloudy', 'clear-night', 'partlycloudy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'partlycloudy', 'partlycloudy', 'partlycloudy', 'partlycloudy', 'partlycloudy', 'partlycloudy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'sunny', 'sunny'] %}
{% set targets = stuff | unique | list %}
{% set ret = namespace(ret=[]) %}
{% for target in targets %}
  {% set kvp = dict(name=target, count=stuff | select('eq',target) | list | count ) %}
  {% set ret.ret = ret.ret + [kvp] %}
{% endfor %}
{% set highest = ret.ret | map(attribute='count') | max %}
{{ ret.ret | selectattr('count','eq', highest) | map(attribute='name') | list | first }}
#

that gets the right answer

marble jackal
#

And I don't fully understand what you are doing

mighty ledge
#

it's making a list of dictionaries

#
{% set stuff = ['partlycloudy', 'partlycloudy', 'partlycloudy', 'partlycloudy', 'cloudy', 'rainy', 'rainy', 'rainy', 'rainy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'rainy', 'rainy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'rainy', 'cloudy', 'cloudy', 'cloudy', 'clear-night', 'partlycloudy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'partlycloudy', 'partlycloudy', 'partlycloudy', 'partlycloudy', 'partlycloudy', 'partlycloudy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'sunny', 'sunny'] %}
{% set targets = stuff | unique | list %}
{% set ret = namespace(ret=[]) %}
{% for target in targets %}
  {% set kvp = dict(name=target, count=stuff | select('eq',target) | list | count ) %}
  {% set ret.ret = ret.ret + [kvp] %}
{% endfor %}
{{ ret.ret }}
#

returns

#
[
  {
    "name": "partlycloudy",
    "count": 11
  },
  {
    "name": "cloudy",
    "count": 27
  },
  {
    "name": "rainy",
    "count": 7
  },
  {
    "name": "clear-night",
    "count": 1
  },
  {
    "name": "sunny",
    "count": 2
  }
]
marble jackal
#

Yep, I get it now

mighty ledge
#

this would also work

#
{% set stuff = ['partlycloudy', 'partlycloudy', 'partlycloudy', 'partlycloudy', 'cloudy', 'rainy', 'rainy', 'rainy', 'rainy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'rainy', 'rainy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'rainy', 'cloudy', 'cloudy', 'cloudy', 'clear-night', 'partlycloudy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'partlycloudy', 'partlycloudy', 'partlycloudy', 'partlycloudy', 'partlycloudy', 'partlycloudy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'sunny', 'sunny'] %}
{% set targets = stuff | unique | list %}
{% set ret = namespace(ret=[]) %}
{% for target in targets %}
  {% set kvp = dict(name=target, count=stuff | select('eq',target) | list | count ) %}
  {% set ret.ret = ret.ret + [kvp] %}
{% endfor %}
{{ (ret.ret | sort(attribute='count') | last).name }}
marble jackal
#

I had
[ { "foo" : 2 }, { "bar" : 1 } ]

#

But I should have included keys

mighty ledge
#

if you end up with that you can also make that work

#

but instead of dictionaries make it a tuple

frank gale
#

I got it also now! +1 in skills

#

thank you guys you are wonderful

marble jackal
#

I must admit I don't really know what a tuple is. I have encountered them 🙂

mighty ledge
#

(this, is, a, tuple)

#

[this, is, a, list]

#

here's it with tuples

marble jackal
#

{{ state_attr('group.some_group', 'entity_id') }} returns a tuple, although the template editor shows it as a list, if it is the only thing showing

mighty ledge
#
{% set targets = stuff | unique | list %}
{% set ret = namespace(ret=[]) %}
{% for target in targets %}
  {% set ret.ret = ret.ret + [ (target, stuff | select('eq',target) | list | count ) ] %}
{% endfor %}
{{ (ret.ret | sort(attribute='1') | last)[0] }}
marble jackal
#

That was annoying when I tried to add it to a list

mighty ledge
#

yah, but you can just

#

| list + [ ]

marble jackal
#

Yeah, I figured that out

mighty ledge
#

tuples are rigid in python. in jinja tuples and lists are very similar

#

because jinja limits lists

marble jackal
#

{{ (ret.ret | sort(attribute='1') | last)[0] }} this is exactly what I tried to do with my first attempt, but that did not work with a dict

mighty ledge
#

with a dict...

#

you have to do

#
{{ (ret.ret.items() | list | sort(attribute='1') | last)[0] }}
#

but that wont work with a list of dicts

marble jackal
#

Well, it didn't work with a list of dicts

mighty ledge
#

which is what you had

marble jackal
#

that was what I meant yes

#

🙂

#

But also knowledge level +1 🙂

mighty ledge
#

it's gaming the system

#

you shouldn't be able to create dictionaries dynamically in jinja

#

but you can get around that using fromkeys

#

or dict(**items)

#

but that requires a dict

#

and if you don't understand * vs ** then gaming the system is a pain

mighty ledge
#
{% set targets = stuff | unique | list %}
{% set ret = namespace(ret={}) %}
{% for target in targets %}
  {% set kvp = [(target, stuff | select('eq',target) | list | count )] %}
  {% set ret.ret = dict.fromitems(ret.ret.items() | list + kvp) %}
{% endfor %}
{{ ret.ret }}
#

good to use if you want to template the entire data section of a service call dynamically

marble jackal
#

I'll make a note of this

inner mesa
#

Never again!

mighty ledge
spiral imp
#

In templates, when do I use state: >- vs state: >?

buoyant pine
#

> is used for multiline templates. Adding the hyphen just strips the newline at the end which HA strips anyway

tidal heart
#

I'm pulling a message from a sensor message[1].details this is a wall of text and I want to look for a specific sentence in there, how can I do that?

spiral imp
#

ok, so I don;t need the hyphen then?

buoyant pine
#

Nope

spiral imp
#

Thanks, trying to get my code cleaned up

silent barnBOT
#

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

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

tidal heart
#

And it's what's coming after Var: part that I'm trying to compare. (var = where, btw). But really It does not matter where my sentence will be, just if it contains Nordvästra Skåne then I want it to be true

#

It's Swedish weather warnings and it sucks because it gives you information from all around one region, but as the text contains more information on where exactly in that region the warning is set I would simply like it to just ignore everything that does not contain it

buoyant pine
#

Is Var: always at the end?

#

And only appears once?

tidal heart
#

Should be only once but if it's always at the end I'm not to sure about

buoyant pine
#

as long as it only appears once (and ideally only at the end), this should work:

{% set data = message[1].details %}
{{ 'Nordvästra Skånein' in data[data.find('Var:'):] }}
``` although you'll need to tweak `message[1].details` accordingly
tidal heart
#

Thanks! It's pretty annoying as it sometimes spams out alerts for the same thing but sometimes for different days. Is the best practice to sort on date and then just always select the [0] one? Or is there any better method to fetch the "nearest" in time in a set category? If that makes sence

#

And as you can see the first Vind event is not in Var: Nordvästra Skåne and is therefore not really interesting to me at all. If I want it to only show events that contains Var: Nordvästra Skåne

#

Or maybe best practice is to just do a if 0 contains string elif 1 contains string and so on

buoyant pine
#

I'll have to take a look later

dull bloom
#

Is it possible to create an attribute template that I can use across multiple entities? I'm creating a complex attribute for my firesticks throughout my house to show what app is currently running on each one... I'd like to create the template once and have all my media_player.firestick entities use it. Is this possible or is there a different way I should be thinking?

tawny coral
#
service: notify.discord
data:
  message: >-
    {{ state_attr(trigger.entity_id, 'object') }} approaching on {{
    trigger.entity_id }}
  target:
    - 'xxxxx'

How do i access friendly_name? I can see it in the trace but {{ state_attr(trigger.from_state, 'friendly_name') }} gives an error

tawny coral
#

Also, how do i go about experimenting with templates and triggers? the template developer tool is usually so useful but now it just says "trigger is undefined"

analog coral
#

Am I able to pull the URL hash with Jinja? Trying to get an auto-entities template to automatically fill in the "area" filter by the hash

inner mesa
#

The first argument to state_attr is the entity id, which you're already referencing in the other statement

marble jackal
#

Whoops, Rob already said that

#

You can also take it directly from the from_state

tawny coral
marble jackal
#

Correct

tawny coral
#

@marble jackal that gives me Error: Error rendering data template: UndefinedError: 'dict object' has no attribute 'entity_id'

#
service: notify.discord
data:
  message: >-
    {{ state_attr(trigger.entity_id, 'object') }} approaching on {{
    trigger.from_state.attributes.friendly_name }}```
marble jackal
#

That error is not coming from trigger.from_state.attributes.friendly_name. It is coming from trigger.entity_id

tawny coral
#

but trigger.entity_id is already working on its own

#

its only when i add the from_state that it bails

marble jackal
#

Well, are not referring to entity_id in that template, so it can not cause the error that entity_id does not exist

#

do you have multiple triggers in your automation, and are they all state triggers?

tawny coral
#

yes, they're 3 identical state triggers

marble jackal
#

Are you activating this automation manually to test?

tawny coral
#

yeah, i think i did

marble jackal
#

Then there is no trigger, hence not trigger.entity_id

#

When you refer to the trigger, there needs to be a trigger 🙂 You can add an additional trigger which you can manually trigger easily, like an input_boolean, but in this case it will not have the attribute object so that part will not work

#

but is should give you the friendly name

tawny coral
#

well yeah that makes sense

marble jackal
#

It will probably result in something like null approaching on Test Boolean

#

But at least, it will show something 🙂

marble jackal
#

I've been playing a bit with this, it does allow you to do something like this:

{% set stuff = [ 'cloudy', 'cloudy', 'sunny', 'sunny', 'partly_cloudy' ] %}
{% set targets = stuff | unique | list %}
{% set ret = namespace(ret={}) %}
{% for target in targets %}
  {% set kvp = [(target, stuff | select('eq',target) | list | count )] %}
  {% set ret.ret = dict.fromitems(ret.ret.items() | list + kvp) %}
{% endfor %}
{% set max = ret.ret.items() | map(attribute='1') | max %}
{% set most = ret.ret.items() | selectattr('1', 'eq', max) | map(attribute='0') | list %}
The weather tomorrow will be mostly {{'' if most | count == 1 else 'a mix of '}}{{ iif(most | count == 1, most[0], most[0:-1] | join(', ') ~ ' and ' ~ most[-1]) }}
#

But of course you can do the same with the list of tuples

{% set targets = stuff | unique | list %}
{% set ret = namespace(ret=[]) %}
{% for target in targets %}
  {% set ret.ret = ret.ret + [ (target, stuff | select('eq',target) | list | count ) ] %}
{% endfor %}
{% set max = ret.ret | map(attribute='1') | max %}
{% set most = ret.ret | selectattr('1', 'eq', max) | map(attribute='0') | list %}
The weather tomorrow will be mostly {{'' if most | count == 1 else 'a mix of '}}{{ iif(most | count == 1, most[0], most[0:-1] | join(', ') ~ ' and ' ~ most[-1]) }}
marble jackal
floral shuttle
#

can I ask how I could use that to extract the difference between these two lists: {{states.sensor|selectattr('attributes.device_class','eq','battery') |map(attribute='entity_id')|list}} and {{expand('group.battery_sensors')|map(attribute='entity_id')|list}}?

#

theres a 5 number difference when counting them... 😉

mighty ledge
mighty ledge
#

[:-1] means everything before the last item

floral shuttle
floral shuttle
#

this works in its most basic form:```
{% set a = states.sensor|selectattr('attributes.device_class','eq','battery')
|map(attribute='entity_id')|list %}

{% set b = expand('group.battery_sensors')|map(attribute='entity_id')|list %}

{{ (a | reject('in', b) | list + b | reject('in', a) | list) }}``` or, with a condition:

#
         |map(attribute='entity_id')|list %}

{% set b = expand('group.battery_sensors')|map(attribute='entity_id')|list %}

{% set difference = (a | reject('in', b) | list + b | reject('in', a) | list) %}

{% if difference|length != 0 %} {{difference}}
{% else %} No difference
{% endif %}```
floral shuttle
#

bcs I had a manually created group of battery sensors, that seemed no longer up to date, and then selecting the device_class battery showed it contained more (and renamed entities...) this template now spits out the differences

mortal monolith
#

I want my temp sensor to round down - I have this in my value_template '{{ value | round(0) }}'

floral shuttle
#

I've returned now to my auto create group on startup so it is always up to date

mortal monolith
#

but I still get .4 or .2

floral shuttle
#

use |int ?

mighty ledge
floral shuttle
#

yep, thats what I have now. ```automation:

  • alias: Create battery group
    trigger:
    platform: homeassistant
    event: start
    action:
    service: group.set
    data:
    object_id: battery_sensors_auto
    entities: >
    {{states.sensor|selectattr('attributes.device_class','eq','battery')
    |map(attribute='entity_id')|list}}```
mighty ledge
floral shuttle
#

I seem to recall that at some point I had issues with that, and then created the explicit group. Its a pain to maintain though with 70+ entities

mighty ledge
#

I do all my groups dynamically now. I just made a script that fires an event that updates them when I want them to update

marble jackal
#

I also recently discovered group.set but at this moment I misuse it to store entitiy_id's to be shared between scripts 🙂

astral turtle
#

Hi,
am trying to assign min value of two sensors to a virtual sensor. The code below is not working, please advice.
Thanks!
value_template: >-
{{ (min(
(states('sensor.filtered_outdoor_temperature_1') | float)
(states('sensor.filtered_outdoor_temperature_2') | float)
)) | round(1)
}}

marble jackal
floral shuttle
#

at one point I drastically cut the amount of groups (helped a lot by the fact we can use auto-entities to represent things in the Frontend) but now see i still have 64. Updating these groups was an issue for the backend at that time, but now I dont seems to notice any issues with that any longer.

marble jackal
#
              {{ min(
                  [states('sensor.filtered_outdoor_temperature_1') | float,
                  states('sensor.filtered_outdoor_temperature_2') | float
                  ]) | round(1)
                }}
astral turtle
#

Thank you!

marble jackal
#

but you should also use defaults in your float, and maybe reject those which are not numbers

#

I fixed some parantheses

astral turtle
#

I am very new to HA. The issue I am trying to solve is the sun, or warm wall of the house giving higher temp values. So I installed several and just want always to see the min one.

#

I also use filters before, to make sure there are no spikes etc.

marble jackal
#

I would do it like this:

{% set values = [
                  states('sensor.filtered_outdoor_temperature_1'),
                  states('sensor.filtered_outdoor_temperature_2')
                ] | select('is_number') | list
%}
{{ values | min | round(1) if values | count > 0  else 'none available' }}
astral turtle
#

So this will solve an issue if one of the sensors is unavailable?

#

I mean the code you suggested

marble jackal
#

yes, it will take out those which are not a number

#

and if all of them are not a number, it will show none available

astral turtle
#

cool, thanks a lot. Moving to HA, from Xiaomi app, love how flexible HA is.

floral shuttle
mighty ledge
mighty ledge
#

Unless that’s the availability template

marble jackal
#

oh, you are right

#
{% set values = [
                  states('sensor.filtered_outdoor_temperature_1'),
                  states('sensor.filtered_outdoor_temperature_2')
                ] | select('is_number') | map('float') | list
%}
{{ values | min | round(1) if values | count > 0  else 'none available' }}
#

@astral turtle correction in the template above

#

String comparison will give the wrong result if the number of digits is different. eg min([9,10]) will give 9, but min(['9','10']) wil give 10.
So as @mighty ledge mentioned, there should have been a map to float in the template

turbid charm
#

so you can no longer pipe max and min and if so why?

floral shuttle
inner mesa
turbid charm
#

yeah managed to fix it

mighty ledge
#

It was a fluke that it worked the way people were using it before.

turbid charm
#

so a bug that was a feature. 😅

mighty ledge
#

Yes, exactly 🤣

spiral imp
#

Can I still change "friendly_name" for templates in customize: if I do not use unique_id?

marble jackal
#

for templates? I think you mean template sensors, and yes you can, but why would you want to? You can simply set it in the yaml

spiral imp
#

yes, template sensors. How can I set it in yaml? I have tried using a friendly_name attribute. That did not work

inner mesa
#

the new format doesn't have it

#

Embrace "name"

spiral imp
#

Yes, I used name, which creates the entity and friendly name it appears. I don;t always want them to be the same. Is that when I should use unique_id intead of name?

inner mesa
#

unique_id just allows you to change the names in the UI

#

you don't use it "instead" of name

spiral imp
#

for example, in this basic template sensor, I define name: and "Chore Spa Water" this creates binary_sensor.chore_spa_water. In the front end, I only want to show "Spa Water". I only add "chore" because that is how I do my naming conventions.

template:
  - binary_sensor:
      - name: "Chore Spa Water"
        state: "{{ states('sensor.chore_spa_water') in ['Tomorrow', 'Today', 'Overdue'] }}"
#

How can I keep my entity naming structure as is but alter what shows up on the frontend?

inner mesa
#

you have a few options: choose your names to reflect how you'd like them to show up in the frontend, you can probably still create a friendly_name via customization, use a card that allows you to customize the name there

#

I do all three depending on what I'm doing, but I've mostly stopped using customization and rely more on the first and last

spiral imp
#

Ok. I can do it on the card side. I did try customization and it did not seem to work. I made the change and reloaded but the friendly names did not change

#

Doesn;t require a restart does it?

inner mesa
#

"Reload core" will reload customizations, but the entity also has to update (or you need to force an update) to see the changes reflect

marble jackal
#

I have a LOCATION & CUSTOMIZATIONS reload button under server controls

frank gale
#

Is it possible to filter some entities if they are in an area_name?
i.e

{{ states.sensor
      | selectattr('attributes.area_name','eq','Bathroom') }}

I want to use a filter and NOT to check it through a for loop like this:

{% for x in states.sensor %}
{% if area_name(x.entity_id) == 'Bathroom' %}
...
inner mesa
#

I don't think area_name is an attribute

#

area_name(lookup_value) returns the area name for a given device ID, entity ID, or area ID. Can also be used as a filter.

#

Last sentence

frank gale
#

using it as a filter in template editor works. tried to use exactly the same template for a sensor returns " no filter name area_name " though.

#

but I want to filter the state object by an area_name and that's not the way to use the filter

frank gale
#

I've changed it to use the method instead the filter. I tried it now with the filter in version 2022.2.8 and it worked. Maybe there was an issue in 2022.2.7 ?

frank gale
#

| area_name

mighty ledge
#

interesting

#

I'm running dev, which is partly behind 2022.2.8 but also partly ahead of 2022.2.8 (it's complicated) and it works for both

frank gale
#

it's not an issue any more... maybe it was something in 2022.2.7

#

but that's irrelevant in my question...

#

anyway thank you 😄

mighty ledge
#

like states, state_attr, is_state_attr, etc

trim oak
#

Anyway to get the entity_id from the friendly name?
{{ states.binary_sensor.xiaomi_motion_8_occupancy.friendly_name }}
returns "Bathroom Motion Detector" as expected
(and works with the shorthand ... occupancy.name )

How to go the other way?

mighty ledge
#

Can you explain what your end goal is?

#

The problem with going from the friendly name to wntity_id is that you can have more than 1 entity with the same name

trim oak
#

I'm in deep... trying to turn off an input_boolean (called bathroom_occupancy) when catching the triggering event of timer.bathroom_motion_timer switching to idle.

trigger:
    - platform: state
      entity_id:
        - timer.bathroom_motion_timer
        - timer.bedroom_motion_timer
      to: "idle"

I'm stripping off the room name ('bathroom') from the trigger.
Need to use that to construct the friendly name of the motion sensor to check it's state.

mighty ledge
wise sluice
#

I’m trying to generate a list from a group of devices showing which have battery level below 60%. Im running into a some problems here
I can’t figure out how to show both the name and the state (battery %) in the generated list

#

This is what I’ve got right now..

{{ expand(‘group.battery_levels’) | selectattr(’state’, ’lessthan’, ’60’) | map(attribute=‘name’) | list }}

thorny snow
#

Hi, i have an sensor with a date for example 25-02-2022 my goal is how many days are left to today. That the sensor shows 6 days. Is that possible ?

wise quartz
wise sluice
marble jackal
wise sluice
#

i want to generate a list of my personal devices (ipad, macbook, etc) that are low battery. i want to output the list in a format that is useful to put in a telegram bot message so it will tell me in the morning when i wake up if i forgot to charge something that i need for work

#

so i'm hoping for something like
Macbook Pro: 18%
Iphone: 26%
ipad: 44%

marble jackal
#

You'll need a for loop then, either creating a dictionary, or these strings directly.

manic onyx
#

how can I write a template for automation that will check how long sensor was in that condition?
I want an alert if my fridge temp is above +6C for over 5 minutes

marble jackal
#

Create a binary sensor and then use that in your automation

wise sluice
marble jackal
#

😅

manic onyx
#

how can I write a template for automation that will check how long sensor was in that condition?
I want an alert if my fridge temp is above +6C for over 5 minutes
Can only think of creating a binary sensor with {{ states('sensor.fridge_thermometer_temperature') | float > 6 }} and using that as a state condition with time of 5 minutes. But is there a way to do the same without extra sensors? Can we use template in the state contition?

marble jackal
marble jackal
manic onyx
#

so, only the new sensor that is based on the same template?

marble jackal
#

But with a numeric state I would really advice to use the template binary sensor

manic onyx
#

thanks

deep summit
#

Hi, can anyone help me out with this ?
Im trying to make an automation that will trigger by a change in state of a sensor and that will send me a notification to TG that tells me the old and new state , do i just use state_changed as trigger ? if so what do i use for action or rather what do i put in the TG notify action ?

arctic sorrel
#

You need to provide more information

#

As I said, what entity?

deep summit
#

this is my entity
sensor.batterychargestatus

#

it has different kind of status, float/bulk/off

arctic sorrel
#
trigger:
- platform: state
  entity_id: sensor.batterychargestatus
action:
- service: notify.petunia
  data:
    message: "The sensor was {{ trigger.from_state.state }} and is now {{ trigger.to_state.state }}"
#

See the docs linked from the channel topic

deep summit
#
alias: New Automation
description: ''
trigger:
  - platform: state
    entity_id: sensor.batterychargestatus
condition: []
action:
  - service: notify.rons_tg
    data:
      title: Victron Boat - Charge Status Change
      data: 
        message: "The state was {{ trigger.from_state.state }} and is now {{ trigger.to_state.state }}"
mode: single
silent barnBOT
#

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

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

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

deep summit
#

this looks ok ?

arctic sorrel
#

Assuming you got all the indenting right

#

Remember you can EDIT your posts

deep summit
#

sorry trying again

#

crap

#

lol not sure how i do this

#

backticks is ?

arctic sorrel
#

You can test out in #botspam

deep summit
#

there

arctic sorrel
#

The YAML looks good

deep summit
#

if im firing this up should it send a message ? or need a change of state first ?

arctic sorrel
#

It needs to change state, but you can do that manually

deep summit
#

yes will try

#

mmm

#

didnt get any message

silent barnBOT
#

If you're having problems with your updates to your configuration:

  • Check the troubleshooting steps
  • Check your log file - remembering you may need to set logger to info or debug
  • Explain what the problem you're having is - sharing configuration, errors, and logs
deep summit
#

Triggered by the state of sensor.batterychargestatus at February 20, 2022, 12:24:03 AM
Call service notify.rons_tg
Stopped because an error was encountered at February 20, 2022, 12:24:03 AM (runtime: 0.01 seconds)

required key not provided @ data['message']

#

i have this in my trace

arctic sorrel
#
action:
  - service: notify.rons_tg
    data:
      title: Victron Boat - Charge Status Change
      message: "The state was {{ trigger.from_state.state }} and is now {{ trigger.to_state.state }}"
#

Try that

deep summit
#

yayyyy

#

awesome!

#

Thanks a lot !!

#

so this trigger.from_state.state method, it knows to relate itself to whatever entity was in the trigger in that automation?

arctic sorrel
#

Yes, that's the state object

#

See the docs linked from the channel topic - top of the window

deep summit
#

great, very useful tool

#

thanks again

tired sandal
#

I'm still trying to work through an issue I have with a REST template sensor.

So, I have a URL that returns an array of JSON objects. I need to somehow parse through that array, filter it down to 1 object and then set that as the sensor state attributes. How can I do that?

#

I know I can filter through it to grab a certain value for the sensor value, but the same doesn't seem to be true for state attributes.

#

Using some code that RobC gave me, I can pair down sensor value to the correct value, but I need some additional data with that for the sensor state attributes.

marble jackal
#

You'll need to be more concrete, what is the dataset, what do you have now, and what do you need?

toxic dome
#

It just says "Template for the select’s available options." But like how does one give multiple options? I tried these two and neither worked:

options: "{{ ['stopped', 'paused', 'running'] }}"
options:
  - stopped
  - paused
  - running
tired sandal
#

I can use that in value_template to get the correct value for the sensor value. The problem is I need to also grab all the other attributes and set them as state attributes for the sensor.

#

if I just use $.data as the json_attributes_path - I just end up with the first entry in the array as the sensor attributes, which is wrong.

#

ideally, I'd use a template in my json_attributes_path to make sure I got the right value, but that's apparently not supported.

tired sandal
#

I guess I'm trying to figure out how to correctly slice and dice this data to be consumable by HA. I can do it with jq in a one-liner, so it must be possible with the template sensor somehow

toxic dome
#

Ah I got it. This one was right:

options: "{{ ['stopped', 'paused', 'running'] }}"

The problem is that it when you use a trigger it doesn't run that template until the trigger occurs

obsidian lintel
#
            selectattr('state','eq','on')|
            rejectattr('attributes.type','eq','browser_mod' ) | list %}```
#

Is there any way that I can list the entities and then return a url link to that entity?

inner mesa
#

What kind of URL are you looking for? To link to what?

obsidian lintel
#

A link to the device page

#

/config/devices/device/

spiral imp
#

Does this:
{%- elif states.binary_sensor.haboard01.attributes.battery_level <= 5 %}
become this:
{% elif is_state_attr('binary_sensor.haboard01, 'battery_level', '<= 5') %}

inner mesa
#

no

#

second time in about 30mins that someone tries to add logic like that

#

'<= 5' this needs to be a value

#

{% elif state_attr('binary_sensor.haboard01', 'battery_level')|float <= 5 %}

spiral imp
#

that makes sense to me, thank you

#

actually, why state_attr and not is_state_attr?

inner mesa
#

because you're not testing equality to a value

spiral imp
#

got it, thanks

#

is there a certain time when {%- is used instead of {%

inner mesa
#

only if you care about whitespace in the output

#

most of the time you do not. it generally only matters if you're trying to construct a string in a loop

spiral imp
#

thanks

fossil venture
#

Is there a way to test if any member of a list is not in another list, e.g. {{ [1, 2, 3 ] not in [3, 4, 5 ] }} ?

mighty ledge
#

Iterate with namespace

#

123 asked me to add that the other day… might do it

#

You can filter the list based on the other list and see if the count drops

inner mesa
#

That last bit is what I would do. Seems straightforward

#
{% set list1 = [1, 2, 3] %}
{% set list2 = [4, 5, 6] %}
{{ list1|reject('in', list2)|list|count != list2|count }}

{% set list1 = [1, 2, 3] %}
{% set list2 = [3, 5, 6] %}
{{ list1|reject('in', list2)|list|count != list2|count }}
#

False, True

fossil venture
#

Nice. Thanks folks.

#

Rob, should that be {{ list1|reject('in', list2)|list|count != list1|count }} for lists with unequal numbers of elements?

inner mesa
#

Yeah, you're right

#

Point is whether any items were rejected

#

Or you could use select and just check > 0

barren jungle
#

Out of curiosity... can yaml merge key <<: be used together with !include ?

odd condor
#

Hi guys, I was told this is the proper place for this question, so here goes:

#

Hi guys, I believe this should be simple but just can't figure it out. So I have a template sensor -just a different representation of day/date- and would like to show year in '22 format. So how do I write ' character? I've tried with \ but no luck (with " works but ' doesn't). This is my current value: value_template: "{{ as_timestamp(now()) | timestamp_custom('%a, %d %b %y.') }}" Thanks!

silent barnBOT
#

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

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

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

odd condor
#

I was given advice to try with '"'"' but doesn't seem to work

arctic sorrel
#

Back ticks

#

See the bot message, and you can test in #botspam

#

Indeed, see #botspam message in there

#

The snippet you posted:

value_template: "{{ as_timestamp(now()) | timestamp_custom('%a, %d %b %y.') }}" 

does seem to work

odd condor
barren jungle
odd condor
#

I miss the ' character

arctic sorrel
#
value_template: "{{ as_timestamp(now()) | timestamp_custom('%a, %d %b \'%y.') }}" 
noble fern
#

That's a lot more robust than the way I suggested. I think I need another cup of tea. Sheesh <embarassment>

odd condor
#

found unknown escape character "'"

silent barnBOT
#

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

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

odd condor
#

is the error I get

arctic sorrel
#

Share the whole thing using a code share site

noble fern
#

Yes, would like to see the whole thing. I think there's more at play here from your other error in the first answer.

odd condor
#

Sorry for being so slow, I'm a complete dumbass on this site

arctic sorrel
#

Ok, and .. what's the context of those three lines?

#

There's supposed to be more above it... what's there?

#

Ok, we're getting closer

#

What comes above

  - platform: template
```?
odd condor
#

As I said, please forgive my dumbassery and have patience 🙂

arctic sorrel
#

I'm trying to lead you to give us the information we need

#

If you don't want help, feel free to just say 😉

odd condor
#

No no, it just takes me a while to understand what you mean to say 🙂

#

hopefully it's all in now

#

I have some other sensors so cannot simply paste all

arctic sorrel
#

That's enough, it's the full context, which is what's needed

#

Somebody who gets Jinja escaping will hopefully be able to help you

mighty ledge
#

\'

odd condor
#

From what I was able to google it should work with \ but unfortunately it doesn't

odd condor
# mighty ledge `\'`

So you mean value_template: "{{ as_timestamp(now()) | timestamp_custom('%a, %d.%b \'%y.') }}"

mighty ledge
#

Yep

odd condor
#

It just doesn't, I get error

#

Error loading /config/configuration.yaml: while scanning a double-quoted scalar
in "/config/configuration.yaml", line 62, column 25
found unknown escape character "'"
in "/config/configuration.yaml", line 62, column 80

mighty ledge
#

Then use multi line notation and use double quotes outside your format

#

See pin 3

arctic sorrel
#
  - platform: template
    sensors:
      day_date_short_eu:
        friendly_name: "Day/Date short EU"
        value_template: >
          {{ as_timestamp(now()) | timestamp_custom("%a, %d.%b '%y.") }}
mighty ledge
#

Ya that

#

I’m on mobile, coding is a pita

odd condor
#

YES!!! THANKS @mighty ledge for help and @arctic sorrel for putting it down to my level!! 😃

thorny snow
tranquil ember
#

hey there.

could anyone assist me with a sensor? It always shows as not available
If I change the value to states it works, but the states are switched (when it's wet it states dry and the other way around)

  sensors:
    regensensor:
      unique_id: "123070995"
      friendly_name: "Rainsensor"
      device_class: moisture
      value_template: >-
        {{is_state('binary_sensor.rain')}}
      icon_template: >-
        {% if is_state('binary_sensor.rain', 'off') %}
          mdi:weather-rainy
        {% else %}
          mdi:water-off
        {% endif %}```
marble jackal
#

Try {{ is_state('binary_sensor.rain', 'on') }} for your value_template

inner mesa
#

The problem was that you didn't provide anything to compare the value to

#

As you did in the very next instance

tranquil ember
#

that makes totally sense! Thank you guys - it is working now 🙂

marble jackal
#

👍🏼

young jacinth
#

Hi!
i want to print a list off all scripts with the entity_id that have the word effect

{{ states.script|map(attribute='entity_id')|list }}

this lists all the scripts i got but i dont know how to filter by keyword...

inner mesa
#

selectattr('entity_id', 'search', 'thingtosearchfor')

thorny snow
#

I'm close to the solution: how can I set payload_on, for a binary sensor as "vibrate" or "drop" or "tilt"? I can only set it as: payload_on: vibrate

inner mesa
#

You can use the value_template to account for that

#

Have it output 'on' if the vibration mode is any of those, then your payload_on is just 'on'

tired sandal
#

hoping someone could help me, I have a REST API that I'm pulling data from. It returns an array of dictionary objects. I want to use one of those dictionary objects (NOT the 0th one) for state attributes, but i can't find a way to do that.

inner mesa
#

How do you know which one? And what part of the dict do you want the state to be?

#

~share the output

silent barnBOT
#

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

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

thorny snow
tired sandal
jolly parrot
#

Oh! I have a related question, I have an array of dictionaries and I want them all (solar forecast data from local weather service), so far I only see the first one.

#

(which has been plotting nicely on a sensor, but like, the next hour's forecast isn't going to get me far in the long run.)

inner mesa
tired sandal
#
{
  data: [
    { date: '2022-01-01' }, // <--- This one gets picked because it's the 0th
    { date: '2022-02-21' }, // This is the one that SHOULD get picked
  ]
}
thorny snow
inner mesa
#

I thought I provided a solution for that

tired sandal
inner mesa
thorny snow
inner mesa
#

you need to actually output 'on' from that template, though, and you're not

tired sandal
#

(more or less)

inner mesa
#
value_template: >
          {{ 'on' if value_json["ZbReceived"]["vibrazione-1"]["AqaraVibrationMode"] in
             ('vibration', 'tilt', 'drop') else 'off' }}
inner mesa
tired sandal
thorny snow
#
  • platform: mqtt
    name: "vibrazione-1"
    off_delay: 15
    state_topic: "tele/tasmota_zbbridge/SENSOR"
    value_template: >
    {{ 'on' if value_json["ZbReceived"]["vibrazione-1"]["AqaraVibrationMode"] in
    ('vibration', 'tilt', 'drop') else 'off' }}
    payload_on: 'on'
    device_class: window
inner mesa
#

'Doesn't work' how?

thorny snow
#
  • platform: mqtt
    name: "vibrazione-1"
    off_delay: 15
    state_topic: "tele/tasmota_zbbridge/SENSOR"
    value_template: '{{ value_json["ZbReceived"]["vibrazione-1"]["AqaraVibrationMode"] }}'
    payload_on: vibrate
    device_class: window
inner mesa
#

only for vibrate, of course

thorny snow
#

yes

inner mesa
#

test the template in devtools -> Templates

#

I guess that's kinda hard with the MQTT topic

dreamy sinew
#

can get the json payload and test against it

thorny snow
#

how can I test it?

dreamy sinew
#

use some sort of MQTT explorer to see what payload you are actually getting

inner mesa
#

it's pretty straightforward

thorny snow
#

phnx I use the tasmota console. and the previous configuration works

inner mesa
#
{% set data = "vibrate" %}
{{ data in ('vibrate', 'foo', 'bar') }}
#

-> true

dreamy sinew
#

first hint is, you used "vibration" in your "not working" example but "vibrate" in your "working" one

thorny snow
#

phnx damn you re right!

inner mesa
thorny snow
#

All fixed! thanks to RobC and phnx

inner mesa
#

only you can decide what's "appropriate" 🙂

#

are you looking for a cube or something like that?

thorny snow
#

but I did not take note of it. but it shows a vibration

inner mesa
tired sandal
thorny snow
#

but they are not the HA's default icons. I need the default icon automatically used by zha for these sensors

inner mesa
#

dump all the attributes into the rest sensor and use the template sensor to pull what you want

tired sandal
#

Doesn't the rest sensor have to be a single scalar value?

inner mesa
#

the state, but I said "attributes"

tired sandal
#

Oh right, so the state attributes of that sensor is <huge array of data>?

#

Then I do my fancy templating stuff in the template sensor.

inner mesa
#

yes

#

it is a common pattern

tired sandal
#

Ah, I see now.

#

Thanks.

#

I'll give that a try.

stuck remnant
#

is it possible to make a rest switch for the flash next to the laptop webcam?

inner mesa
#

Impossible to know. Is there a service that controls that that you want to trigger?

stuck remnant
#

I don't know, it's the light next to the webcam and windows has control of it so - possibly

inner mesa
#

HA just sends a REST command, so you'd need to find something that runs on the laptop that controls the flash. Not a #templates-archived

stuck remnant
#

oh okay thanks

inner mesa
# tired sandal I'll give that a try.

It occurs to me that you should just use a trigger-based template sensor with an MQTT trigger, rather than an MQTT sensor and separate template sensor

wanton osprey
#

Normally, I use something like {{ value_json["ENERGY"]["Power"] }}' to get the value of the sensor. However, a Shelly 2.5 provides two power values in a bracket, one for the left channel and another one for the right channel. The output looks like

#

{"Time":"2022-02-20T18:40:01","Switch1":"ON","Switch2":"OFF","ANALOG":{"Temperature":55.6},"ENERGY":{"TotalStartTime":"2022-01-28T21:01:26","Total":0.094,"Yesterday":0.000,"Today":0.000,"Period":[0.00,0.00],"Power":[0.00,0.00],"ApparentPower":[0.00,0.00],"ReactivePower":[0.00,0.00],"Factor":[0.00,0.00],"Frequency":50,"Voltage":236.32,"Current":[0.000,0.000]},"TempUnit":"C"}

#

How can I modify the template to extract the first power value from the bracket?

inner mesa
#

it's a list, so {{ value_json["ENERGY"]["Power"][0] }}

wanton osprey
#

That simple?

#

Thanks, I will try

inner mesa
#
{% set data = {"Time":"2022-02-20T18:40:01","Switch1":"ON","Switch2":"OFF","ANALOG":{"Temperature":55.6},"ENERGY":{"TotalStartTime":"2022-01-28T21:01:26","Total":0.094,"Yesterday":0.000,"Today":0.000,"Period":[0.00,0.00],"Power":[0.00,0.00],"ApparentPower":[0.00,0.00],"ReactivePower":[0.00,0.00],"Factor":[0.00,0.00],"Frequency":50,"Voltage":236.32,"Current":[0.000,0.000]},"TempUnit":"C"} %}
{{ data["ENERGY"]["Power"][0] }}
#

-> 0

wanton osprey
#

@inner mesa Seems to work. Thank you very much. I thought the solution must be much more complicated.

spiral imp
#

I am getting this warning in the log for a few template sensors. How do I go about settnig a "default" to avoid this issue?
Template warning: 'float' got invalid input 'unknown' when rendering template '{{ states('sensor.qbittorent_down_speed') | float / 977 }}' but no default was specified. Currently 'float' will return '0', however this template will fail to render in Home Assistant core 2022.1

spiral imp
#

thanks, just found that and reading through it now

obsidian lintel
#
            selectattr('state','eq','on')|            rejectattr('attributes.type','eq','browser_mod' ) | list %}```


Is there any way that I can list the entities and then return a url link to that entity?
#

The url will link to the device page

spiral imp
# inner mesa pinned

So it really is as simple as: '{{ states('sensor.qbittorent_down_speed') | float(0) / 977 }}'

inner mesa
#

if you want it to be zero if the entity has a non-numeric value

spiral imp
#

I have a sensor (sensor.dark_sky_precip) that returns a state of "unknown" when there is no precipitation. I have the following template binary sensor that I need to only have a state of "on or "off" because it triggers a switch based on it's state. But, when the dark_sky sensor is "unknown" so it my template binary sensor. How can I fix this?

  - binary_sensor:
    - name: "Snowing"
      state: "{{ states('sensor.dark_sky_precip') in ['snow', 'sleet'] }}"
      availability: "{{ not states('sensor.dark_sky_precip') in ['unavailable'] }}"
inner mesa
#

just remove the availability line

#

all that will do is sometimes make the state "unavailable"

spiral imp
#

This still results in the binary_sensor showng unknown

inner mesa
#

seems unlikely

#

you said this:

#

I have a sensor (sensor.dark_sky_precip) that returns a state of "unknown"

#

I don't see how that can result in binary_sensor.snowing to be "unknown", which is what you're defining here

spiral imp
#

I know but it is. It has been very difficult to figure out.
This {{ states('sensor.dark_sky_precip') }} in the template editor returns "unknown"
This {{ states('sensor.dark_sky_precip') in ['snow', 'sleet'] }} in the template editor returns "False"
But the binary sensor entity is returning "unknown"

inner mesa
#
{{ states('sensor.whatever') }}
{{ states('sensor.whatever') in ['foo', 'bar'] }}
#

-> unknown, False

#
- binary_sensor:
  - name: test
    state: "{{ states('sensor.whatever') in ['foo', 'bar'] }}"
#

-> off

#

cannot reproduce

#

I think you didn't reload templates

spiral imp
#

I have reloaded multiple times

#

Could it be because the sensor is actually returning the string "unknown"? Meaning the state is not not known, it is actually "unknown"? Not sure that makes sense.

inner mesa
#

it does not

#

I replicated my success with an input_text with a state of "unknown"

spiral imp
#

I just changed sensor.dark_sky_precip to sensor.dark_sky_icon which has a state of "clear night". The binary sensor still returns "unknown"

silent barnBOT
#

Always run the configuration check command when you make changes. Don't trust the UI check - it misses some problems.

spiral imp
#

I'm running that now

#

I did restart HA as well. Still showing as unknown

inner mesa
#

perhaps you're just looking at the wrong entity

spiral imp
#

ha core check completed sucessfully

#

I'm looking at binary_sensor.snowing

inner mesa
#

I have nothing more to add. It works for me, 2+2=4

spiral imp
#

ok

tall otter
#

hi all, i have an mqtt sensor that i'm using a script to update.. i have an automation that is updating an input_boolean whenever a 0 or a 1 is received but for that object, last_changed and last_updated seem to only change when the value changes (0 to 1 or 1 to 0). from what i can find, it seems duplicate values are ignored. i'm looking to send a notification if the script breaks, basically if mqtt is no longer receiving anything.

let me know if there is a better way... but i set up an input_datetime and along with updating the input_boolean mentioned above, i am also updating that input_datetime with the current datetime. so now i have an input_boolean that updates with the current datetime any time a payload is received on that mqtt topic.. this works fine, but how do i get the 'secondary info > last changed' data?

it doens't seem to like these:

"{{ states('input_datetime.garage_mqtt_updated.last_changed') }}"
"{{ state_attr('input_datetime.garage_mqtt_updated', 'last_changed') }}"

inner mesa
#

neither is correct

#

"{{ states.input_datetime.garage_mqtt_updated.last_changed }}"

tall otter
#

i thikn i tried that also, it gives me ""

inner mesa
#

try again

tall otter
#

was reading that also. it returns "" for me but i have it on my lovelace dashboard and i can see plain as day "2 seconds ago" etc..

inner mesa
#

{{ states.input_datetime.date_test.last_changed }} -> 2022-02-20 20:30:32.322301+00:00

#

review your entity_id, I suppose. or it's another rift in the spacetime continuum

tall otter
#

hmm, maybe it's how i'm setting my input_datetime. is this not right?

service: input_datetime.set_datetime
data:
timestamp: '{{ now().timestamp() }}'
target:
entity_id: input_datetime.garate_mqtt_updated

inner mesa
#
test_datetime:
  sequence:
    service: input_datetime.set_datetime
    data:
      entity_id: input_datetime.date_test
      timestamp: "{{ now().timestamp() }}"
#

works fine for me

tall otter
#

hmm, i'll play with it. thanks

#

LOL nvm.. user error of course, thanks

#

"garate", wow. sorry about that

#

instead of garage

spiral imp
#

@inner mesa well, I learned my lesson and sorry for wasting your time. An additional part of my template (that I did not think was relevant - hence, learned my lesson) was delay_off of 2 hours. This means this means that when I do a restart or reload during the delay period, there are issues. I found a thread in forums and there is an issue open about it as well.

inner mesa
#

np, glad you found it

spiral imp
#

In case you are curious

tight arch
#

Looking for some help on pulling data from a json file into HA.
Using this json file:
https://www.nascar.com/cacher/2022/1/race_list_basic.json

How can I pull just the info from say "race_id": 5146 I can do it if I use value_json[3] since its the 3 entry. for the life of me though, I cannot figure out the proper syntax for calling it with out knowing its position in the array?

Any ideas?

inner mesa
#

Oh, never mind. Confused you with someone else

tired sandal
#

np

#

I think my syntax for json_attributes_path is wrong. When I fill in "$.data" the logs say: " JSON result was not a dictionary or list with 0th element a dictionary "

#

the API response looks like this:

{
  status: 200,
  data: [],
}
#

Therefore, $ should be the root object(which is a dictionary) an $.data should be a list with a 0th object.

#

I should point out that $.data.0 works just fine

#

As does $data.1, $data.2 etc.

#

It would be useful if there was a way to get HA to spit out exactly what it was seeing

marble jackal
#

I'm trying to store a list with dicts in a file, using the file integration. The message used for the notify service only accepts strings, so I had to wrap it in double quotes.

#

Now I want to use that data. I can remove the double quotes using replace and the template editor clams the result is a list, but it's still a string

#

Example:

{%- set dataset = "[ {'entity_id': 'media_player.beneden_groep', 'friendly_name': 'Beneden groep', 'state': 'off', 'media_content_id': 'no media_content', 'media_title': 'no title', 'media_artist': 'no artist', 'media_content_type': 'no type', 'app_name': 'no app', 'entity_picture': 'no pic', 'volume_level': 'no volume', 'media_position': 86399, 'data_source': 'event_script'}, {'entity_id': 'media_player.boven_groep', 'friendly_name': 'Boven groep', 'state': 'off', 'media_content_id': 'no media_content', 'media_title': 'no title', 'media_artist': 'no artist', 'media_content_type': 'no type', 'app_name': 'no app', 'entity_picture': 'no pic', 'volume_level': 'no volume', 'media_position': 86399, 'data_source': 'event_script'} ]".replace('"','') %}
{{ dataset[0] }}

results in [

#

Is there a way to get this working?

silver flare
#

try the json filter instead of the replace function

#

| to_json

marble jackal
#
{%- set dataset = "[ {'entity_id': 'media_player.beneden_groep', 'friendly_name': 'Beneden groep', 'state': 'off', 'media_content_id': 'no media_content', 'media_title': 'no title', 'media_artist': 'no artist', 'media_content_type': 'no type', 'app_name': 'no app', 'entity_picture': 'no pic', 'volume_level': 'no volume', 'media_position': 86399, 'data_source': 'event_script'}, {'entity_id': 'media_player.boven_groep', 'friendly_name': 'Boven groep', 'state': 'off', 'media_content_id': 'no media_content', 'media_title': 'no title', 'media_artist': 'no artist', 'media_content_type': 'no type', 'app_name': 'no app', 'entity_picture': 'no pic', 'volume_level': 'no volume', 'media_position': 86399, 'data_source': 'event_script'} ]" | to_json  %}
{{ dataset[0] }}

Gives me ", also if I leave the replace in

#

ah, got it. I need to use from_json, but for that to work, I need double quotes inside

#

This probably can be done more efficient, but for now it works:

{%- set dataset = "[ {'entity_id': 'media_player.beneden_groep', 'friendly_name': 'Beneden groep', 'state': 'off', 'media_content_id': 'no media_content', 'media_title': 'no title', 'media_artist': 'no artist', 'media_content_type': 'no type', 'app_name': 'no app', 'entity_picture': 'no pic', 'volume_level': 'no volume', 'media_position': 86399, 'data_source': 'event_script'}, {'entity_id': 'media_player.boven_groep', 'friendly_name': 'Boven groep', 'state': 'off', 'media_content_id': 'no media_content', 'media_title': 'no title', 'media_artist': 'no artist', 'media_content_type': 'no type', 'app_name': 'no app', 'entity_picture': 'no pic', 'volume_level': 'no volume', 'media_position': 86399, 'data_source': 'event_script'} ]".replace('"', '').replace("'", "|").replace('|','"') | from_json  %}
{{ dataset[0] }}
silver flare
#

cool

marble jackal
#

Had to rewrite the dataset to a ordered dict though, to be able to retreive it from the file using json_attributes. But thanks to the experts here I knew how to do that 🙂 (below only a part becuase of the line limit

          {%- set ns = namespace(info={}) %}
          {%- for entity in expand(integration_entities('cast')) %}
            {%- set data = { entity.entity_id: 
                            { 'friendly_name':entity.attributes.friendly_name,
                              'state': entity.state,
                              'media_content_id': entity.attributes.get('media_content_id', 'no media_content'),
                              'media_content_type': entity.attributes.get('media_content_type', 'no type')}
                          }
            %}
            {%- set ns.info = dict(ns.info, **data) %} 
          {%- endfor %}
#

Shouldn't have marked the code as yaml 😛

amber hull
#

I have a value template that is giving me the correct temperature, but I am generating an error in the logs. Works fine in the developers tools.

#
    friendly_name: High_Forecast
    unit_of_measurement: '°F'
    value_template: "{{ state_attr('weather.17_seaview_avenue', 'forecast') [0].temperature}}"```
#

None has no element 0 in the logs.

inner mesa
#

I only get that if I use the wrong entity_id

#

so I don't see how it can both return the right value and give that error in the log

mighty ledge
amber hull
#

yes

mighty ledge
#
{% set forcast = state_attr('weather.17_seaview_avenue', 'forecast') %}
{% if forcast is not none %}
  {{ forcast[0].temperature  }}
{% endif %}
amber hull
#

Thanks. I got it. I'll reboot and see if it fixes the error. Rebooted and this error is fix. I have a couple of more that are similar that should be easy to follow your example. I do see some other start up errors due to integration not ready. Are these bugs are working as designed?

fast vigil
#

you can also use the |default option

strange geode
#

Is it possible to combine 2 ikea blinds as "one" unit ?

fast vigil
#

something like {{ (state_attr('weather.17_seaview_avenue', 'forecast')|default('NA') }} should work @amber hull

strange geode
#

and mabye change the device type name: roller blind to curtains

fast vigil
#

@strange geode you can create a group

strange geode
#

Okay cool, and is is possible to set the "device type" ?

fast vigil
#

device_type can always be configured in customize:

strange geode
#

Thank you so much, so in cutomize, i will define the class type right ?

  • Do i have to put other informations here to have the same functions ?

sorry im new to HA

fast vigil
#

if you create a cover group, it will have all the cover functions

strange geode
#

Okay thank you i will try that..

amber hull
#

@fast vigil I get TemplateSyntaxError: unexpected '}', expected ')' in the template editor.

fast vigil
#

there is one more closing parentheses required

#

{{ (state_attr('weather.17_seaview_avenue', 'forecast'))|default('NA') }}

inner mesa
#

that will be trouble if you then try to dereference it

#

|default(['NA']), maybe

amber hull
#

Also this gives all the values, not the "0" temperature I am looking for.

#

I try difference options so I can try and understand templates better

fast vigil
#

because forecast is not empty

inner mesa
#

see my post

amber hull
#

I understood what the code does with Petro.

fast vigil
#

then follow that

#

it is easier

inner mesa
#

{{ state_attr('weather.17_seaview_avenue', 'forecast')|default(['NA'])[0] }}

amber hull
#

TemplateSyntaxError: expected token 'end of print statement', got '['

inner mesa
#

{{ (state_attr('weather.17_seaview_avenue', 'forecast')|default(['NA']))[0] }}

amber hull
#

back to all the values

fast vigil
#

yes, that is because forecast is not empty

inner mesa
#

I'm out, feel free to chew on that

fast vigil
#

the |default(['NA']))[0] part is only used when forecast is none

amber hull
#

value_template: "{% set forecast = state_attr('weather.17_seaview_avenue', 'forecast') %}{% if forecast is not none %}{{ forecast[0].temperature }} {% endif %}" give me one

fast vigil
#

like in petro's code

amber hull
#

I'll stay with this until I have time to figure out what each of your options are doing. Thanks as always for teaching me different ways of doing things

fast vigil
#

{{ (state_attr('weather.17_seaview_avenue', 'forecast')[0]|default(['NA']))[0] }}

#

this should work

inner mesa
#

ha

mighty ledge
#

I avoid default because it's not smart enough for what I want it to do

inner mesa
#

{{ (state_attr('weather.wf_udp', 'forecast')|default([{'temperature':'NA'}], True))[0].temperature }}

#

gotta add the , True to get it to recognize null

mighty ledge
#

yah, that's probably the best way to get a 1 liner

#

you can also use... selectattr

#

but not sure if selectattr will bitch if it's fed a None

#

{{ state_attr('weather.wf_udp', 'forecast') | map(attribute='temperature') | first }}

#

something like that

#

probably would need a default too after first

spiral imp
#

Can a template be used with delay_off when using minutes? I am not been able to get it to work with:

delay_off:
  minutes: "{{ template }}"
inner mesa
#

do...the docs say it is?

#

I'm just going to look it up there

#

well, taking that back, it does seem to hate that

#

but this does work:

#
- binary_sensor:
  - name: test
    state: "{{ states('input_text.test') in ['foo', 'bar'] }}"
    delay_off: "{{ '00:05:00' }}"
marble jackal
#

"00:{{ template if template | int >= 10 else '0' ~ template }}:00"
Something like this maybe?

inner mesa
#

yes, but it's way more complicated and the docs are ambiguous

marble jackal
#

That's true

#

Doesn't providing seconds work, like for delay

inner mesa
#

the docs imply that delay: xxx works the same way

marble jackal
#

delay_off: "{{ template | int * 60 }}"

spiral imp
#

Good know that I did not miss anything. The only examples I found in the docs were seconds-based. I just converted my minutes to seconds and did it that way.

olive moth
#

hello