#templates-archived

1 messages Β· Page 57 of 1

wanton sapphire
#

what do you mean?

inner mesa
#

You're mapping something to something

marsh cairn
#

Number -> Text
Text -> Number
Same system - just "inverted"

wanton sapphire
#

Now I think I get what you guys mean, I'll try. Thanks

mighty ledge
#

I lied, it was for processing conversations, or making a script return a value

steel swift
#

How do I add attributes to a sensor? Is this valid? ```
attribute_templates:
snittpris: "{{ state_attr('sensor.electricity_price_hjemme', 'avg_price') | float + avg_nettleie_pris }}"
flytende_pris: "{{ states('sensor.strompris_m_nettleie') | float }}" # Bruk strompris_m_nettleie som state for flytende_pris````

marsh cairn
#

Where does "avg_nettleie_pris" come from?

inner mesa
#

it also depends on whether you're using the new or legacy template format (also described on that page)

steel swift
inland peak
#

Hello, I need some help with a little issue.
How do you write "smaller than, or equal" in a template?

inner mesa
#

You mean <=?

inland peak
#

yes.

steel swift
inner mesa
#

Weird, ok

inland peak
#

I have a template to compare two temperatures from different sensors, but if I simply add "<=", then the template errors out.

marsh cairn
#

Because states are strings. You have to convert them to floats or integers

inland peak
#

I get "TemplateSyntaxError: expected token 'end of print statement', got '='"

#

oh, I have to put the = after the sign, not before

marsh cairn
#

If you share your template, we might be able to help

inland peak
#

I meant to say larger than, or equal

inland peak
#

Didn't realize the = had to be after > instead of before, as is usual in 5th grade math

marsh cairn
#

You might have to convert to float

inland peak
#

I used to do that, but it turned out to not be necessary.

marsh cairn
#

Wasn't sure about attributes

inland peak
#

the template worked fine otherwise, it's just that occasionally the two temperature values were exactly equal, which would cause issues in the automation.

#

anyway, thank you for the help.

pure tree
#

hello,
it possible to send one notification to my phone with the ups battery status ?
i have the ups battery entity in my hass

inland peak
#

Do you just want to know when the UPS battery is low, or do you want constant monitoring?
Also, how often do you want it to report?

pure tree
inland peak
#

Ok then, if you say you've found the solution.

pure tree
inner mesa
#

plese don't post images of text

#

role->gone

lunar basalt
#

Hi. Anyone who can give me a helping hand on getting a notification to work, that includes an if statement in the message? I am trying to change a part of the Message text based on data pulled from template. Is that even possible? (edited post to remove image)

service: notify.mobile_app_jonas_iphone
data:
title: Front door TEST
message: Unlocked by {{ if ('trigger.event.data.parameters.userId','1') }} Jonas

inner mesa
#

that's not how an if statement works

#

What is your actual goal there? That "if" statement will just return true or false, and I doubt that you want that just inserted in the text message

#

(if the syntax was correct, which it's not)

#

Unlocked by true Jonas

lunar basalt
#

The goal was for it to check if the value was 1 and then add the text "Jonas"

inner mesa
#

and if it's not 1?

#

just nothing?

#

If you describe exactly what your eventual goal is, you'll get a better help

#

I'm guessing it's this:

I would like to map userIDs from the trigger to names of people so that I can display that name in the message

#

which is a straightforward mapping exercise

lunar basalt
#

Alright. Got it. Will look into that. Thanks

inner mesa
lunar basalt
#

Thanks!

haughty breach
mellow sigil
#

Hi! I've a derivative that sends me spikes up to 10000kWh when I restart HA.
(While the curved which is based on has no spike)
How can I avoid this?

In a more general meaning, when you want to avoid anomalies in a sensor (like calculated, or a motor starting), what's the "best" way?
Send 0 ? Send the previous State? Make it unavailable? Send a median value based on n last samples?
Thanks!

cold star
#

Hi. I installed the smartthings integration and now see my Samsung appliances in home assistant. when I look at the dishwasher sensor that shows the time it scheduled yo finish it has an offset of 00:00. So the completion time should be 7:48pm eastern time but it shows 11:48+00:00. What would be the syntax for a template to show 7:48

#

sensor.dishwasher_dishwasher_completion_time
Dishwasher Dishwasher Completion Time
2023-10-23T23:48:34+00:00

obtuse zephyr
#

{{ states('sensor.dishwasher_dishwasher_completion_time') | as_datetime | as_local }}

lucid thicket
obtuse zephyr
#

Yeah, this might be better if you just want the time component formatted like that.
{{ states('sensor.dishwasher_dishwasher_completion_time') | as_timestamp | timestamp_custom('%I:%M %p') }}

plain magnetBOT
#

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

bright quarry
#

^ what's wrong with this? i updated my home assistant and my mqtt stuff doesn't work anymore.

#

mqtt explorer shows events fired such as; rtl_433/rtl433/devices/SimpliSafe-Sensor/1P7T3

plain magnetBOT
#

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

marble jackal
#

@steel swift easiest is:

availability: "{{ has_value('sensor.electricity_price_hjemme') and 'sensor.strompris_med_nettleie' | has_value }}"

or:

availability: "{{ states('sensor.electricity_price_hjemme') | is_number and is_number(states('sensor.strompris_med_nettleie')) }}"

both has_value and is_number can be used as function or filter, is_number can only be used if the sensor normally has a numeric state
has_value needs the entity_id as input, is_number needs the state (or any other value which you want to check)

#

I used both the filter and function now, just to illustrate they do the same πŸ™‚

#

when applying this availability template you no longer need the 2nd if statement

plain magnetBOT
#

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

marble jackal
#

yes

#

I now see that the other sensor you were checking on before was the actual template sensor

#

you can replace this: month >= 1 and month <= 3 with month == 2

#

and hour >= 6 and hour < 22 with 6 <= hour < 22

steel swift
marble jackal
#

sorry, my bad

steel swift
marble jackal
#

1 <= month <= 3

#

that will be correct

#

or month in [1, 2, 3] πŸ™‚

steel swift
#

ok, so I do not need to use the AND

marble jackal
#

no, you don't need the and

#

but it might be more readable, so no worries if you want to use it

steel swift
#

ahh, yes that is similar to what I am used to from some other languages I have been working with earlier.

plain magnetBOT
#

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

steel swift
#

it is in the first if-sentence with NORMAL I am unsure.

plain magnetBOT
#

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

marble jackal
#

that first if statement will never be true, as the template will not be rendered in such cases because of your availability template

steel swift
#

I suspected that, so I can remove that part of the sensor as as you say it will not be rendered if its not available?

marble jackal
#

yes, but the sensor will of course never report NORMAL then

#

oh wait, it will, there is a 2nd NORMAL

mighty ledge
# steel swift I suspected that, so I can remove that part of the sensor as as you say it will ...

personally, i'd reorganize that a bit to make it easier to maintain, and you had an extra endif

        {% set flytende_pris = states('sensor.strompris_med_nettleie') | float %}
        {% set weekday = is_state('binary_sensor.workday_sensor', 'on') %}
        {% set avg_price = state_attr('sensor.electricity_price_hjemme', 'avg_price') | float %}

        {% if 1 <= now().month <= 3 %}
          {% set avg_price = avg_price + iif(weekday, 0.3346, 0.2646) %}
        {% else %}
          {% set avg_price = avg_price + iif(weekday, 0.4014, 0.3314) %}
        {% endif %}

        {% if flytende_pris < avg_price * 0.6 %}
          VERY_CHEAP
        {% elif avg_price * 0.6 <= flytende_pris < avg_price * 0.9 %}
          CHEAP
        {% elif avg_price * 0.9 <= flytende_pris < avg_price * 1.15 %}
          NORMAL
        {% elif avg_price * 1.15 <= flytende_pris < avg_price * 1.4 %}
          EXPENSIVE
        {% else %}
          VERY_EXPENSIVE
        {% endif %}
steel swift
# mighty ledge personally, i'd reorganize that a bit to make it easier to maintain, and you had...

Have been working some hours, have some knowledge and I am learning a lot along the way. With knowledge comes the ability to do things simple. I fully agree that this one is much cleaner, but I am still satisfied I managed to get it working in the end. I got rid of the extra endif somwhere along the road. I struggled a lot with this ending up with finding that I prsented the datas in a template card. There I got an error when sensor was unavaiable or unknown, and I blamed the sensor. When I put default in the template card, I got rid of the errors πŸ™‚

wanton sapphire
mellow sigil
#

In a general meaning, when you want to avoid anomalies in a sensor (like calculated, or a motor / fridge starting), what's the "best" way?
Send 0 ? Send the previous State? Make it unavailable? Send a median value based on n last samples?
Thanks!

mighty ledge
#

unavailable

mellow sigil
#

thx @mighty ledge - but why is it preferred?

mighty ledge
#

because you don't want bad data in your data

mellow sigil
#

yes, but then there's "some holes" in your data... but this is still better than for instance a median value (which would leave no hole)?
I mean especially if you're making a derivative or an integration later on this data.

mighty ledge
#

the holes don't impact the derivative

mellow sigil
#

OK, thank you!

dense swan
#

I have a list of sensors and I wanted to build an automation to cover them all when they aren't getting updated via my SDR-RTL process I have. I was trying to be smart and use a template trigger in Automation but not sure how to craft the proper template for this and stuck.

Right now I have a loop where I can get all the sensors I want but not sure how to use that variable in other functions in the for loop like so

#
{% for i in states.sensor|selectattr('entity_id','search','_(planter|sink|sensor)_rssi')|map(attribute='entity_id') %}
states.{{ i | e }}.last_updated
{%- set ts_event = as_timestamp(states.{{ i }}.last_updated) %}
{%- set ts_now = as_timestamp(now())|round(0) %}
{%- set ts_delta = (ts_now - ts_event) %}
{{ ts_delta | round(0) > 3600 }}
{% endfor %}
#

I am able to get for example sensor.deck_sensor_rssi returned as i but trying to use it inside of the other logic I have isn't working. Also if more than one failed and I used this logic in an automation template trigger could I still use the {{ trigger.to_state.attributes.friendlier_name }} in the automation?

inner mesa
#

you're nesting templates

#

I'm not sure what this line is doing there:
states.{{ i | e }}.last_updated

#

there are several issues there

#

this returns a generator, and you want a list:
states.sensor|selectattr('entity_id','search','_(planter|sink|sensor)_rssi')|map(attribute='entity_id')

#

you need to add |list

marble jackal
#

for works on generators

inner mesa
#

oh, ok

#

things like states.{{ i }}.last_updated should be states[i].last_updated

marble jackal
#

And what is that i | e supposed to do?

#

The loop is not needed though, seems like he wants to find all entities updated in the last hour

inner mesa
#

it's currently output the time deltas, but yeah

dense swan
#

i | e is jinja for escaping

marble jackal
#

{{ states.sensor |selectattr('entity_id','search','_(planter|sink|sensor)_rssi') | selectattr('last_updated', '<', now() - timedelta(hours=1)) | map(attribute='entity_id') | list }}
Something like this

dense swan
#

That worked perfectly @marble jackal ! Thank you so much

mighty ledge
#

keep in mind that e is also overwritten as a function to output e (math)

#

i.e use escape over e because your milage may vary in HA (when using it as a filter)

#

This is only a HA thing, use e to your hearts content in jinja outside HA to escape things

mighty ledge
#

fyi

inner mesa
#

I never even thought of an e filter meaning "escape"

mighty ledge
#

just like == is an alias for eq

mighty ledge
inner mesa
#

TIL

mighty ledge
#

there's only 2 aliases for filters

#

e and escape, d and default

#

all the rest are for math stuff

#

but, when you think about where jinja came from, it makes sense that e is an alias

#

it was originally created to help w/ html and presenting forms

#

which use escape alot

inner mesa
#

that part in that line was certainly confusing, but it sitting there without any decoration was also weird

mighty ledge
#

yeah, I think he was just using it to see what the line of text would be, then he tried to use it in the decorated line later

#

makes sense if nesting was possible

steel swift
#

So I get this error, and I have searched and searched but cant find where this template are placed. Is it possible to find in some way? ````
homeassistant.exceptions.TemplateError: ValueError: Template error: float got invalid input 'unknown' when rendering template '{{ (states('sensor.snittpris_med_nettleie_2') | float * 100) | round(2) }} ΓΈre' but no default was specified

inner mesa
#

the state of sensor.snittpris_med_nettleie_2 is unknown and you didn't provide a default for float, such as float(0)

marble jackal
steel swift
steel swift
steel swift
#

Did some changes again, and hope I found them now. This is driving me crazy.

grim topaz
#

Is there an easy way to make two lights match each others states?

Example:

I want my hallway light to turn on/off if I turn on/off my chandelier.

I want my chandelier turn on/off if I turn on/off my hallway light

marsh cairn
young jacinth
#

hi,

is there a way to reuse this example template light i just did for my bed room.
i have 10 rooms where i want to use the same logic but dont want to copy and paste the code. somebody has a idea how i could do this?

https://pastebin.com/DCbvpnVC

marble jackal
#

Use yaml anchors

#

But you need to be able to get the source light from the properties of your template light

pure tree
#

Hi,
knows anyone's if it possible to send one notification to my phone with the ups battery status ?
actually i want to send the hass one notification when the power is off and who many battary i have

*i have conect the ups with usb cable and i use the nut server for conecting

marsh cairn
#

Yes. Trigger the automation based on the UPS status (mine has the status "On Battery" when power is cut)
and as action send a mobile app notification. In the message you can use the template {{ states('sensor.ups_battery_charge') }} (you would have to modify the entity name according to your NUT integration) for the UPS percentage

mellow sigil
#

I have this zigbee sensor: sensor.smartplug1_energy which I unplugged / don't use for reasons.
I make a total of 20 of those smartplugs to get the total energy.
Unfortunately, I have to manually remove this specific plug 1 in the calculation, because if not, HA doesn't know it's unavailable and always return its previous energy value (4 days ago).
Is there a way to detect if it's really available/plugged?
https://snipboard.io/7PCw6u.jpg

marsh cairn
#

If you show the calculation template, someone might know a solution

plain magnetBOT
#

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

mellow sigil
#

But I understand the fact the energy value remains constant, so its derivative == 0 (on the constant part), so it's not problem for a derivative.

I'm maybe more interested to know how to detect it's plugged or unplugged, because neither none, unknown or such test work, it's still available for HA.

wraith dust
#

Hey all. Trying to create an automation using team_tracker that triggers if the numeric state score attribute changes from 0 and then each subsequent change above 0. I believe the best way to do that would be via a value_template however I’ve no idea where to start with that.

lethal bison
#

ha-teamtracker's wiki has an example


alias: Automation - Team Score
trigger:
  - platform: state
    entity_id: sensor.team_tracker
    attribute: team_score
condition:
  - condition: template
    value_template: >-
      {{ trigger.to_state.attributes.team_score | int >
      (trigger.from_state.attributes.team_score | int ) }}
action:
  - your-action-here```
plain magnetBOT
bright quarry
#

anything wrong with this? compatible with new mqtt format? my mqtt stuff recently stopped working after an update and idk why.

young jacinth
sonic nimbus
#

is this ok:

  - service: media_player.select_source
    data:
      entity_id: >- 
        {{ speakers }}

and when I call it for variable

      media_player.hallway_ceiling_speaker,
      media_player.bathroom_ceiling_speaker, media_player.office,
      media_player.office_shelf_speakers
marble jackal
#

It will probably work, but I would enter the speakers as a list

#

Oh, and your service call needs an actual source setting

#

As service data

cosmic hamlet
#

how check if a string state_attr('media_player.alfred','media_content_id'))
endsWith RADIO538.mp3

#

a regex to the resque

inner mesa
#

{{ 'foobar'.endswith('bar') }}

sonic nimbus
marble jackal
sonic nimbus
#

nice! thanks!

sacred sparrow
#

my state is showing 'null' so I have:
{%- if state_attr('sensor.alexa_last_called', 'Entity') == '' -%} as
{%- if state_attr('sensor.alexa_last_called', 'Entity') == 'null' -%} doesnt work
Is there another way to do it just in case the sate is blank and not null?

pure tree
#

hi,
i wont to send to my phone one notification about the load and battery from ups. The code is this one
"service: notify.mobile_app_S10
data:
title: Ups is on battary
message: >-
The battary is {{ states('sensor.ups_battery_charge')}}%
The load is {{ states('sensor.test12')}}W'

the problem is on my phone the notification is in the same line, may know anyone how i can do this ?

sacred sparrow
#

{{ '\n' -}} makes a new line

lethal bison
#

Trying to pull the list of unavailable lights from a template sensor. The sensor works, but the entities are tucked away behind the sensor's attributes

inner mesa
#

what does that mean?

lethal bison
#
sensor:
- platform: template
  sensors:
    unavailable_lights:
      unique_id: '0a7476cc-d6c1-40ba-8ae1-606518c3497f'
      friendly_name: Unavailable Light Entities
      value_template: >
        {{ states.light | selectattr('entity_id', 'contains', 'light.bulb_') | selectattr('state', 'in', 'unavailable') | list | length }}
      attribute_templates:
        entities: >
          {{ states.light | selectattr('entity_id', 'contains', 'light.bulb_') | selectattr('state', 'in', 'unavailable') | map(attribute='entity_id') | list | join(', ') }}```
inner mesa
#

Is that a problem?

#

you can also just leave it as a list

lethal bison
#

The sensor itself is working fine. In template editor, I'm triying to retrieve the list reported by the sensor. I'm currently doing : {% set entity = "sensor.unavailable_lights" %} {% for item in states.sensor %} {{item}} {%- if loop.first %} entities:{% elif loop.last %}{% else %}{% endif -%} {% endfor %}, but that's reporting everything, not just the unique_id of the devices

#

for item in states.sensor.unavailable_lights.attributes.entities seems to be returning the names as strings, which I can work with

inner mesa
#

yeah, the better way is just state_attr('sensor.unavailable_lights', 'entities')

#

and if you remove the |join(', '), it just stays as a list that you can iterate on

lethal bison
#

I guess 'entities' doesnt count as the name. TypeError: state_attr() missing 1 required positional argument: 'name'

inner mesa
#

?

lethal bison
#

If I run it by itself: {{ state_attr('sensor.unavailable_lights', 'entities') }}, it returns that type error

#

which I understand to mean sensor.unavailable_lights doesn't have an attribute field named 'entities'

inner mesa
#

does it?

lethal bison
#

the sensor was pasted above, to me it does

inner mesa
#

it just returns null for me if the attribute doesn't exist

#

I certainly don't get that error message

#

that just indicates that you didn't call that function correctly

lethal bison
#

okay, that's odd, you're entirely correct

inner mesa
#

this returns that error: {{ state_attr('sensor.unavailable_lights') }}

dry narwhal
#

Hello everyone,
I am getting the error message TemplateRuntimeError: cannot assign attribute on non-namespace object for

    {% set area = states('input_select.apexcharts_dropdown_areas') %} 
    {% if area == '-- - --' %}
      {% set ns.list = ns.list | unique(attribute='entity_id') | list %} 
    {% else %}
      {% set ns.list = ns.list | unique(attribute='entity_id') | selectattr('entity_id', 'in', area_entities(area)) | list %}
    {%- endif %}
#

The input_select contains strings. Would someone maybe help me understand where the issue is?

inner mesa
#

You didn't actually create a namespace, you just started using ns

#

You don't actually even need a namespace there

dry narwhal
#

Oh no, so simple

#

I keep forgetting that you cannot just use a namespace or an array or an object, you always have to initialize them first.

marble jackal
cerulean karma
#

Hi, I want to check if a state change of a switch was triggered by an automation or external (button, physical,..). Using the context.* does not work. Since parent_id is alway set (and changing). And user_id is never set.

waxen dawn
#

Hi, {{ strptime(state_attr("sun.sun", "next_rising"), "") }} errors out.

serene tiger
#

I'm trying to get this rest endpoint working, its a json output of my ISP's disruption page

sensor:
  - platform: rest
    resource: "https://grm.glasnet.nl/api/getNotices"
    name: glasnet_disruptions
    value_template: "{{ value_json.storingen }}"

I know the current output but dont know the output when there are no disruptions
i also know that if there are multiple it just adds one to it within storingen.
How do i parse this in a way so i can get a tile with all disruptions and mabye a page for the updates

#

the endpoint is publicly accessable

rocky crypt
#

Hey there. I'm using a template to check the existing volume level of media player, however I'm running into an issue because sometimes the "volume_level" attribute doesn't exist. Is there a way of testing to see if the attribute exists before continuing?

#

{% if states.media_player.virtual_study_alexa.attributes.volume_level %} is my template... I thought that would work, but it doesn't..

#

Instead I get WARNING (MainThread) [homeassistant.helpers.template] Template variable warning: 'homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'volume_level' when rendering

marble jackal
#

You should use state_attr('media_player.virtual_study_alexa', 'volume_level')

#

that will return none instead of an error when the attribute doesn't exist

#

and is one of the reasons why this warning is in the docs

rocky crypt
#

Ok! THANK YOU! That worked!

lethal bison
#
  - if:
      - condition: template
        value_template: "{{trigger.event.data.devicename == "upbath-vanity"}}"``` This is wrong, but I don't know how to make it right. `devicename` is a field sent by an event, I want to perform additional actions if a specific device sent the event
serene tiger
#

Got it working to this point it now says the service that has the issue and some attributes but not sure it will show it for all of them if there multiple

#

Current status ```

  • platform: rest
    resource: "https://grm.glasnet.nl/api/getNotices"
    name: glasnet_disruptions
    json_attributes_path: "$.storingen[:1]"
    json_attributes:
    • regio
    • netwerk
    • diensten
      value_template: "{{ value_json.storingen[0].diensten }}"```
#

but not sure how to do it better

rocky crypt
#

New question. I have a variable labled "new_volume". I am trying to use it to set the volume...
volume_level: { new_volume | float }

However, I am getting error saying: expected float for dictionary value @ data['volume_level']

#

I have it set to float, so I'm not sure where I am going wrong with this one 😦

marsh cairn
#

Without testing it I would guess you are missing the second curly bracket around the template
volume_level: {{ new_volume | float }}

marble jackal
#

and the quotes around the template πŸ˜‰

rocky crypt
#

Yep. Those were it πŸ™‚ Thank you both!

marsh cairn
marble jackal
#

if you don't add them, it will be interpreted as a mapping

mighty ledge
#

that tells the yaml that the field is a string and it should remain a string

#

we then take that string and analyze it as a template

marsh cairn
#

One line templates with " - multiline ones without

mighty ledge
#

well

#

it's the > or | that allow you to not use quotes

marsh cairn
mighty ledge
#

those are essentially indicators to yaml that say "the next lines that are indented are part of this field and this field is a string"

#

the |- or >- the minus just removes leading whitespace

#

which is 100% meaningless for pretty much everything we do in HA

#

because the template algo strips leading and trailing whitespace

marsh cairn
#

In markdown cards it matters

mighty ledge
#

whenever you see someone use the -, it means they don't understand what the tempaltes do

#

yes, markdown is the only place it matters

#

I tried to spell this out in one of the pinned posts on the forums

#

not sure where it is anymore

#

TBH, there is a difference between > and |, but I can't remember. I'm sure it's an easy google

marble jackal
#

| and > can make a difference, eg when sending messages

mighty ledge
#

IIRC, it was meaningless to HA

marsh cairn
#

Now that the markdown is working as I want (at least I hope), it will not be touched again. πŸ˜†

marble jackal
#

| leaves newlines in

mighty ledge
#

ah

marble jackal
#
message: |
  this
  will
  be
  5
  lines
mighty ledge
#

so > must convert them to spaces

marble jackal
#

yes

#

there is a whole website dedicated to it

mighty ledge
#

Yah, I'm sure there is

marsh cairn
mighty ledge
#

My issue w/ yaml tutorial sites, is that they never cover anchors properly

#

none of them show this, which I guessed at one day randomly and it worked

platform: state
<<: &declare
  entity_id: sensor.xyz
  state: "on"
#

it's the most used anchor for me, due to the nature of HA and it's rigid validation structure

marble jackal
#

yes, that one is nice, never saw <<: on yaml websites

mighty ledge
#

exactly

#

it's basically "merge this dictionary into this other dictionary"

#

but, they only show the use of it

#

i.e.

<<: *use_anchor
  ...
#

they never showed that you could use that to delcare the anchor

marble jackal
#

before I knew about that one, i had anchors for each key

mighty ledge
#

exactly

#

same here

#

then someone asked on the forums and I played around with it for a couple of hours

#

best discovery ever

marble jackal
#

I saw it one of Marius' configs he shared πŸ™‚

mighty ledge
#

interesting!

#

You remember which one?

#

I wish I found that sooner, I only discovered it a few years ago

#

I never look at other peoples config, I probably should more often

cold star
#

@quick jasper sorry for the delay response thank you this will work

mighty ledge
#

that's not the correct NSX

#

@obtuse zephyr ^

marble jackal
serene tiger
#

yea i dont get this.
trying to make unknown amount of entities based on the json api is harder than i expected haha

mighty ledge
#

you can't w/o an integration

#

it has to be a known number via yaml

serene tiger
#

well crap so i would have to make a intergration to get the thing i want working

lethal bison
#

It looks like my automation isn't handling the list it's being given.. ervice: select.select_option data: option: Always Off target: entity_id: '{{ resets }}'
Error: Template rendered invalid entity IDs: select.craftroom_relay_config select.frontporch_relay_config select.diningroom_relay_config select.officeceiling_relay_config

mighty ledge
serene tiger
#

i got rest working atm atleast so i can get the current disruption

#

aah okay, this is going to be more of a pain than i expected haha

mighty ledge
#

if you have a static number of entities, then no, you can do it w/o a custom integration

serene tiger
#

yea its variable, its a json api from my ISP, with all their disruptions listed in it

mighty ledge
#

if you just want to get 1 sensor based on information in a dynamic list of data, then yes you can do that too

serene tiger
#

that could work to, i'm only trying to get a certain list of data from the data
i wouldnt mind having it in 1 sensor

#

might be nicer to

#

my main goal was if no disruptions: no disruptions
and for each if there are, region, service, network, status

mighty ledge
#

post the data

serene tiger
#

Link to data fine, or a dump fine?

mighty ledge
#

link is fine

serene tiger
mighty ledge
#

ok, I can't read anyof that so you'll have to guide me

#

is storingen outages?

serene tiger
#

yes

mighty ledge
#

k

serene tiger
#

regio is region
netwerk is network
diensten is services
details.status is status

mighty ledge
#

so you want 4 sensors?

#

or 1 sensor w/ 4 attributes?

#

4 sensors will be easier

serene tiger
#

atm i got one sensor with 3 attribues working but i dont know how it will be if there are more entries in the json

#

as untill yesterday it was this but x3

mighty ledge
#

there will be

#

but you can make a list for the attributes

#

but you'll need to make template sensors

#

i.e. 1 rest sensor, 4 template sensors

serene tiger
#

one per data i want correct?

#

mabye a 5th one, but that should easy to be added i think
detail.gebeurtenis to also list what is wrong

#

also thank you for helping me, I'm a complete noob in this

mighty ledge
#

NP

#

sorry back

#

So, 4 sensors w/ a list of what's out in each

languid pendant
#

I did something like this, but it was with a card to display severe weather alerts, if that is of interest

#

I didnt save the data to sensors, because the data would be dynamic

mighty ledge
#

@serene tiger Use this for your rest sensor:

rest:
- resource: https://grm.glasnet.nl/api/getNotices
  sensor:
  - name: Outages
    unique_id: outages
    value_template: >
      {{ value_json.storingen | length }}
    state_class: measurement
    unit_of_measurement: Count
    json_attributes:
    - storingen
#

Then...

#

Well actually

#

do you want to just have the closest outage?

#

or if it's just for notifications, that 1 sensor should do your work

#

and I can hlep with anotification message

#

if you want this stuff in the UI, then we can make a static number of outages, lets say 5, and go from there

serene tiger
mighty ledge
#

ah, we could use autoentities to get the information out

#

it's a custom card that would allow use to dynamically create UI elements that display the info

#

w/o having the sensors

serene tiger
#

yea looks that way, currently trying to read the yaml to see how to use it

mighty ledge
#

yaml for what?

#

auto-entities?

serene tiger
#

the card he linked

mighty ledge
#

yeah, you don't need that

#

that's custom button card w/ a bunch of stuff

#

ifyou just want a dashboard w/ outages, you can do this w/ auto-entities and the sensor above

languid pendant
#

That card uses autoentities. I just put it behind a conditional card and in a browsermod pop up

serene tiger
#

atm used a markdown card as i had something similar for packages from 17track
but auto entities might be better yea

mighty ledge
#

well it would just allow you to have pretty separate cards

#

markdown also has the ability to add icons and such to it

#

custom button card allows you to make a specific card that looks and feels how you want it

#

but it's complicated

serene tiger
#

yea that is overkill for me haha

#

when i'm home i will try to work it out into into a better way, thank you for the help with the sensor @mighty ledge

plain magnetBOT
#

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

silent vector
#

Oops

#

How would I create a dictionary with namespace in a loop.

I can create this

   foo:
     sh: 'ds'
   santa:
    zha: 'zva'
#

But it seems like it's not possible to put that under 1 key

all: 
   foo:
     sh: 'ds'
   santa:
    zha: 'zva'
mighty ledge
#

you cant

silent vector
#

😦

#

Any other ways to do this in jinja or it's just not possible

mighty ledge
#

make key value pairs and then use dict.fromkeys

silent vector
#

Yeah I have {{ dict.from_keys(ns.fields) }}

#

Dictionary updates can only do 2 sequences though

#

I have 2 separate sets adding to ns.fields

mighty ledge
#

the value for a KVP can be a dictionary

silent vector
#

Oh as in
{% set ns.fields = ns.fields + [('all', {})] ?

mighty ledge
#

if that's how you want to do it, yes

silent vector
#

What's the other way?

#

To make sure foo and Santa are under all

mighty ledge
#

there's many different ways to make a dict

#

dict(...), dict.fromkeys(...), {}, etc

silent vector
#

The challenge is I'm not sure how to make the dictionary all go under 1 key all as I have
2 different sets adding to ns.fields because it's in a loop.

tight adder
#

hello, i'd like to get the decimal part of a float in a template. Is there a nice method to get this ? and also I only want to have 2 digit (i.e. 4.1 -> 10 or 6.2355 -> 24)

silent vector
#

Figured it out

mighty ledge
#

set x = {'foo': dict.fromkeys(...)...

silent vector
#

Yeah I did

{{ {'all': dict.from_keys(ns.fields) } }}
marble jackal
tight adder
#

seems so simple πŸ™‚ thx

marble jackal
#

That will give 0.14. based on your example you might want to multiply it

mighty ledge
marble jackal
#

Or do that

mighty ledge
#

modulo returns the remainder

#

so it works on floats

#

and ints

marble jackal
#

Hehe, I already thought it must be possible with modulo.

mighty ledge
#

lol yah, it's so simple you wouldn't think it would work

tight adder
#

ok here is my line {{ (states('sensor.out_pool_sensor_ble_yc01_temperature') | float / 4) % 1 }} but return value is 0.625 for a start value of 3.625

marble jackal
#

Yes, that's what I already mentioned, you need to multiply with 100 (and then round it)

tight adder
#

oops sorry I've missed your comment 😦

mighty ledge
#

make sure to use parenthesis

tight adder
#

ok guys, i know i just stop finished to be ill, but {{ ((states('sensor.out_pool_sensor_ble_yc01_temperature') | float / 4) % 1) * 100 | round(0) | int }} return 62.5 and not 62

mighty ledge
#

you're rounding the 100

#

parethesis

tight adder
#

ok returning to bed....

#

working nice with parenthesis !

#

thx

humble forge
#

Anyone have good code for a esp8266 with single relay and ultrasonic sensor, I have everything wired up. just need a good front end button card

jagged obsidian
#

How does that relate to templates in HA?

vocal sedge
#

i'm sitting on a script with variables. but if i paste the variable with templating at the end of a String it will be parsed with simicolons:

Script: media_content_id: media-source://media_source/local/'{{media_to_play}}'
output: media_content_id: media-source://media_source/local/'fantasy sms.mp3'

how can i fix this?

humble forge
#

getting bounced around channels...

jagged obsidian
#

Yeah, you'll need to be more clear about what exactly you want

humble forge
#

its really kind of got to do with everything

#

but here goes

#

I built a esp8266, with esphome to trigger a relay, and report status using a state text binary sensor.

#

this all works, but I need some front end help to figure out how to make it somewhat close to the cover entity

#

I liked the way MyQ looked in HA but the api can go pound sand

jagged obsidian
#

You make it a cover entity in esphome which is #diy-archived or their own discord

humble forge
#

a cover entity ahhh okay cool

#

I will take a look at diy

#

so I have a text_sensor can it be used for cover value?

mighty ledge
#

it's not a channel here, it's a completely separate discord server

humble forge
#

does it matter what I am using in the backend?

#

I am now on the front end asking a template question

#

in templates...

humble forge
mighty ledge
#

ok, I wasn't sure because it seemed like you arrived here assuming this was the esphome channel

jagged obsidian
humble forge
#

so using the cover template and asking about how to set up the value portion of it is frontend?

#

okay Thanks! I'll try another channel πŸ™‚

jagged obsidian
mighty ledge
humble forge
#

sounds good thank you

vocal sedge
#

i'm sitting on a script with variables. but if i paste the variable with templating at the end of a String it will be parsed with simicolons:

Script: media_content_id: media-source://media_source/local/'{{media_to_play}}'
output: media_content_id: media-source://media_source/local/'fantasy sms.mp3'

how can i fix this?

inner mesa
#

I don't see any semicolons there

#

If you mean single quotes, just remove them

vocal sedge
fading stratus
#

is there a way for me to get a device sensor from a different entity on the device? e.g. I'm trying to find and read sensor.upstairs_east_left_window_ip when given light.upstairs_east_left_window

mighty ledge
#

lol yes, using templates πŸ˜‰

#

explain where you want to use this

plain magnetBOT
#

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

mighty ledge
#

so you want to do what? provide the IP or the light to them?

fading stratus
#

I would like to have a single script i can provide the list of light entities for easier readability

mighty ledge
#

ok, so...

#
{% set entity_id = light | device_id | device_entities | select('search', '^sensor(.*)_ip$') | first | default('') %}
{{ states(entity_id) }}
#

where light is the vairable you put in from the script

#

if light is going to be a list, then it would need to be adjusted

fading stratus
#

Yeah, I'll handle looping it - I didn't realize you could traverse the device ID like that. I just don't understand the templating, lol

#

thanks, now to understand it, haha!

mighty ledge
#

just copy/pasate this

#
{% set light = 'light.cabinet_wled' %}

1

{{ light | device_id }}

2
{{ light | device_id | device_entities }}

3
{{ light | device_id | device_entities | select('search', '^sensor(.*)_ip$') | list }}

4
{{ light | device_id | device_entities | select('search', '^sensor(.*)_ip$') | first }}

5
{{ states(light | device_id | device_entities | select('search', '^sensor(.*)_ip$') | first) }}

{% set entity_id = light | device_id | device_entities | select('search', '^sensor(.*)_ip$') | first %}
{{ states(entity_id) }}
#

in the template editor

#

shows you what it's doing

#

but you have to change the light

#

in line 1

fading stratus
#

I was just building that, lol

#

thanks again!

vestal crater
#

Hi all, I am using a DMX addon for HA and they have you create the devices/entities in the configuration.yaml file. I need to create 24 fixtures with 9 channels each. They all have the same channels but just need to be incremented. Is there a clean way to do this in the configuration.yaml file or programatic way?

plain magnetBOT
#

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

sacred sparrow
#

my state is showing 'null' so I have:
{%- if state_attr('sensor.alexa_last_called', 'Entity') == '' -%}
as
{%- if state_attr('sensor.alexa_last_called', 'Entity') == 'null' -%}
doesnt work
Is there another way to do it just in case the sate is blank and not null?

not defined doesn't work for some reason

mighty ledge
#

is none

#

@sacred sparrow

small turtle
#

is it possible to set an icon color through a template sensor?

inner mesa
#

If the card you're using supports templates for the color, you can use any entity

austere ledge
#

does anyone have experience with nodered JSONata templating?

#

I'm trying to get frigate to telegram notifications working via nodered

inner mesa
austere ledge
#

oh

#

thanks

#

lol

lethal bison
#

Trying to filter a list of matching results from a state engine query: {% set bulb = ["diningroom","livingroom"] %} {{states.select | selectattr('attributes.options','defined') | selectattr('entity_id','contains','_relay_config') | selectattr('entity_id', 'contains', bulb) | map(attribute='entity_id')}}
state engine reports TypeError: can only concatenate list (not "str") to list
How can I end up with a list of entities to perform actions?

#

My first thought was to use a for item in bulb, but that doesnt return a list, just a bunch of strings

marble jackal
#

there are 2 quotes before _relay_config

lethal bison
#

typo in discord, sorry

marble jackal
#

and you need to add | list at the end, otherwise it's still a generator

#

you can test the template in developer tools > templates

#

oh wait, I see where it goes wrong

#

use this:

{% set bulb = ["diningroom","livingroom"] %}
{{
  states.select | selectattr('attributes.options','defined') 
    | selectattr('entity_id','contains','_relay_config')
    | selectattr('entity_id', 'search', bulb | join('|'))
    | map(attribute='entity_id')
    | list
}}
#

or

{% set bulb = 'diningroom|livingroom' %}
{{
  states.select | selectattr('attributes.options','defined') 
    | selectattr('entity_id','contains','_relay_config')
    | selectattr('entity_id', 'search', bulb)
    | map(attribute='entity_id')
    | list
}}
lethal bison
#

ahh, it must have been the `| join('|') I was missing

#

oh, that's a whole statement - bulb | join('|')

marble jackal
#

yes, it converts your list to the same string for bulb in the 2nd version

#

the search test allows regex as input, and in regex | is or

lethal bison
#

That's basically what I wanted, to perform selectattr('entity_id','search',bulb) with both items

marble jackal
#

I use search instead of contains, contains doesn't allow a list as input

lethal bison
#

I thought contains would be faster than search, but I have no proof, just a guess

marble jackal
#

but you can not use contains here, as you want to check for 2 values

#

you were checking if a string (eg sensor.foo_relay_config) contains the list ["diningroom","livingroom"]

#

which resulted in your error

lethal bison
#

ahh, gotcha

marble jackal
#

@lethal bison you can do it in one search filter if you want

#

or maybe not, at least not with my regex knowledge πŸ™‚

#

found it:

{% set bulb = 'diningroom|livingroom' %}
{% set search_string = '(?=.*_relay_config)(?=.*('~bulb~'))' %}
{{
  states.select | selectattr('attributes.options','defined') 
    | selectattr('entity_id', 'search', search_string)
    | map(attribute='entity_id')
    | list
}}
sacred haven
#

is there a tidy way to put default values of 0 into these sensor values, so the sum still works if any of the data is missing?

{{ [
  states('sensor.solis_daily_grid_energy_purchased'),
  states('sensor.solis_energy_today'),
  states('sensor.solis_daily_energy_discharged')
] | map('float') | sum }}

Is it just to put float(0) after each states call? Or can I add another map that puts in default(0) at the end?

#

(I'm having trouble testing using the developer tools template feature, because I can't generate UNKNOWN input values reliably... is there a trick to that?)

marble jackal
#

@sacred haven map('float', 0)

#

btw, you can do:

{{
  [
    'sensor.solis_daily_grid_energy_purchased',
    'sensor.solis_energy_today',
    'sensor.solis_daily_energy_discharged'
  ]
    | map('states')
    | map('float', 0)
    | sum
}}
sacred haven
#

ooooh thx! this is great advice

#

one small issue to banging around on forum threads etc is it's easy to fall into outdated or suboptimal habits

marble jackal
#

yes, and 2023.11 will bring new templating stuff

sacred haven
#

oh cool! looking forward to that then πŸ˜„

sacred haven
#

I am having fun with templates today; I want to show a Mushroom Chip card on the dashboard with a little alert if the UV value is over 1.5, but not otherwise. Here's where I'm at:

- sensor:
    - name: "uv_level_if_above_threshold_for_notification"
      state: >
        {% set rounded_val = states('sensor.current_uv_index') | float(0) | round(1) %}
        {{ rounded_val if rounded_val > 1.5 else 0 }}

(Yes, I called it uv_level_if_above_threshold_for_notification. I was a Java coder by trade and that's how I name things! srynotsry)

marble jackal
#

what is your goal here? If you want to use it in a conditinal card, you should create a binary sensor

#

or wait until next wednesday, because then numeric states can be used in conditional cards

#

oh wait, mushroom chips can be conditional out of the box

sacred haven
#

I just posted in #frontend-archived, funnily enough. I want to feed it into an auto-entities (with a "state>0" filter), then feed the auto-entities into a Mushroom chip card. So I get a compact row of "things HA thinks you need to know about right now." It'll also have light groups that are on.

My current config uses normal condition mushroom chips, but it's tedious to maintain / hardcode the list of everything I want to show. Inserting auto-entities is going to clean that up.

marble jackal
#

but for what do you need the sensor then?

sacred haven
#

I only want to show the chip when the value is above 1.5, and I also want to format the chip value to prepend a string (I omitted this above). So the template I'm using is actually

        {% set rounded_val = states('sensor.current_uv_index') | float(0) | round(1) %}
        {% if rounded_val > 1.5 %}
          Current UV: {{ rounded_val }}
        {% endif %}

My next plan is to set some attribute on the sensor like "notification=true", then have auto-entities show everything where "notification is true" and "value is not 0/empty string"

#

does that make sense? it should mean, I think, that I can create sensors or helpers and have them show up in the mushroom chips automatically whenever they have anything to tell me

marble jackal
#

I would use a template chip then, not creat a sensor for it

sacred haven
#

hmmm so I concede I had not seen the template chip option, lol

(I am just kinda banging around learning HA as a I go, please bear with me, I am not necessarily taking the most efficient paths...)

thx for the pointer!

#

hmmm if I do that, though, I don't see how to merge it in with the rest of my chips that I want to show in the same card, that are coming from the auto-entities... I shall continue to experiment, maybe there is a way

#

sorry, I drifted OT there, this isn't really templating any more

hard venture
#

I have a humidity sensor that is significantly out of line with all the rest of the humidity sensors in my house. My plan is to make a template sensor helper that will include the math necessary to adjust it to be close to the others and use that value in automations.
When I go to create the helper, I put in {{sensor.guest_bath_humidity_old}} - 17 for the template, but it tells me that This template does not listen for any events and will not update automatically.
When I used any variation of int(states(sensor.guest_bath_humidity_old)) I get a warning of Sensor None has device class 'humidity', state class 'None' unit '%' and suggested precision 'None' thus indicating it has a numeric value; however, it has the non-numeric value: 'int(states(sensor.guest_bath_humidity_old))' (<class 'str'>) .
Obviously, I'm doing something wrong, but haven't figured out what that is yet. Would someone please point me in the correct direction.

marble jackal
#

You need quotes around the entity id when using states()

hard venture
#

Wow. Thanks. I have no idea how I missed that since I copied the states() from my devtools templates where I have a whole bunch of them (including this exact one).

#

Also, this would be the "proper"/most logical/"best" way of making this correction, right? Is there another way that might work better/be more in line with the way HA is supposed to work?

mighty ledge
#

there's a compensation integration

#

although it's in dire need of some updates, the dev is super lazy for that integration and hasn't updated it in a while

inner mesa
#

typical for that guy

mighty ledge
#

super typical, that lazy ass

hard venture
hard venture
mighty ledge
hard venture
#

Is it a default helper type that can be created from the UI? If so, I'm not seeing it. It's not listed as "compensation <anything>" in the list of helpers, and the Integration specifies that it's a "Riemann sum integral sensor"

mighty ledge
#

It's not in the UI, it's yaml only

#

it'll never be in the UI because the UI can't handle unknown length lists

hard venture
#

gotcha.

mighty ledge
#

I've been waiting for the core team to make an element that can handle that to get it into the UI

hard venture
#

doesn't sound to me like you're the slacker, then! πŸ˜‰

mighty ledge
#

Well, it's not really a high priority

lethal bison
#

quick-and-dirty guide on expanding a light group to expose it's members in a template?

#
variables:
  lights_in_group: |-
    {{ expand(states.light | selectattr('entity_id','contains','group_') 
    | selectattr('entity_id','search',(trigger.event.data.area)))
    | map(attribute='entity_id')|list}}```
This works in template editor, but returns an empty list in the automation
unborn glade
#

I'm writing a template in to my configuration.yaml l,basically it calculates out certain power consumption for me but I can't find a good guide on how to set the unit type. It's defaulting to none in the template but Wh is being filled in by the front end. I want kWh. Is there not a way to set the unit in the template?

real oasis
#

mind if i ask a few stupid questions?

unborn glade
#

No such thing as a stupid question in my opinion.

real oasis
#

you haven't heard my questions yet

unborn glade
#

What are they?

real oasis
#

Button-card template 'live_tile_card' is missing!
type: custom:button-card
template:

  • live_tile_card
  • live_tile_with_picture
    name: Aurora
    color_type: icon
    variables:
#

i have the template sitting in a file called live-tites.yaml sitting the templates folder

#

how do i include this into my config so that the card can find the template?

real oasis
#

i have a view of these includes going on

#

i tried template: !include etc etc

#

it tossed me an error

#

what do you classify it as?

inner mesa
#

none of that has anything to do with Jinja templates

#

some Minimalist thing, I imagine

real oasis
#

ok ill go over there

unborn glade
#

Jinja that's why I couldn't find my answer I should have been looking for jinja templates not ha templates. πŸ˜’

#

Thanks!

clear mist
#

hey guys, i'm not sure if this is the right answer but i'm trying to make an IR blaster with esphome to control my air con and one of the things with it is that the bits the air con is receiving for the speed can be calculated like so (based on what others are saying since i'm very new to all this):

speed (int) -> convert to binary, reverse the digits -> bitwise shift 4 digits left (i think from what people have told me) -> convert to hex -> get compliment

so as an example, if the speed is 4, converting it to binary would make it 0100, which reversed would be 0010

bitwise shift that and you geto 0010 0000, which converted to hex is 20, then the compliment of that is DF, and that's the info i need to send to my esp device

is there a way to do that process in a template? so the whole convert to binary, bitwise shift, convert to hex and compliment it? or should i just do a bunch of if/else statements instead?

mighty ledge
clear mist
#

yeah, i can't find much out about it unfortunately

#

i think i might just have to make a bunch of if/else statements to get it working

mighty ledge
#

If you shoot me a reminder in about 12 hours I’ll take a look at it

clear mist
#

time zones may make that hard but i'll give it a shot πŸ™‚

mighty ledge
#

Struct from python was added to jinja in HA

#

That probably can handle this

inner mesa
#

here's an example of constructing a bitmask:

    - data:
        entity_id: input_number.zones_violated
        value: >-
          {% set orig_value = states('input_number.zones_violated')|int %}
          {{ orig_value|bitwise_or(2**state_attr(trigger.entity_id, 'index')) }}
      service: input_number.set_value
clear mist
#

is there a way to convert from decimal to binary?

#

if so, if there's a way to convert from binary to a string, i can just do some string manipulation on it to act as the reverse bits and bit shift, then once done i could convert it to hex?

inner mesa
#

I would probably use a python_script instead

#

I just don't know if you need packages that aren't avaialble

clear mist
#

that's ok, i think if i'm going into that much effort i think i'd rather just do some if/else statements

#

wait, there's a way to convert decimal to binary!

{{ '{:b}'.format(test) }} ```
#

is there something like a ternary operator in jinja? something where i can go
test == 0? 1 : 2
or similar?

clear mist
#

hmm - i was hoping for something shorter but that might do

#

thanks!

#

actually that looks perfect, thanks!

clear mist
#

hey guys, is there a way to use a for loop to concat a string x times? i'm trying to take a number, say 1, and put a 0 in front of it 3 times to end up with a string of 0001, but for some reason it's not working - here's my code:

{% for i in range(0, 3 ) -%}
  {% set test = "0" + test | string -%}
  {{ test }}
{% endfor -%}
{{ test }}```

and the output: 

```Result type: string

01
01
01
1```
inner mesa
#

You have to use a namespace

clear mist
#

a namespace?

#

ah ha!

{% for i in range(0, zeroes ) -%}
  {% set ns.paddedBinary = "0" + ns.paddedBinary|string -%}
  {{ ns.paddedBinary }}
{% endfor -%}```
gives me an output of:
```Result type: string

01
001
0001```
thank you so much!
plain magnetBOT
#

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

marble jackal
#

@steel swift All your checks have not weekend in it, you just don't output anything when it's weekend

steel swift
plain magnetBOT
#

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

junior star
#

Trying to add an entity to a list when that entity state is on
This works if it actually is on, but it fails when it's not:

#
  alias: Master Bed White
  sequence:
  - service: light.turn_on
    data:
      kelvin: 2700
      brightness_pct: 80
    target:
      entity_id:
      - light.masterbed_fan_light
      - light.masterbed_cans
      - >
        {% if is_state('light.masterbed_closet','on') %}
          light.masterbed_closet
        {% endif %}
  mode: single```
#

error is an empty element in the array:
Error: Template rendered invalid entity IDs: ['light.masterbed_fan_light', 'light.masterbed_cans', '']

marble jackal
#
entity_id: >
  {{
    [
      'light.masterbed_fan_light',
      'light.masterbed_cans',
      'light.masterbed_closet' if is_state('light.masterbed_closet','on')
     ] | select() | list
  }}
#

@junior star this

inner mesa
#

TIL:

If no test is specified, each object will be evaluated as a boolean.

#

nice!

plain magnetBOT
#

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

spark vortex
#

is it possible to create a sensor that contains the energy consume of a single cycle, if I have a washing machine with sensors: sensor.washingmachine.status that has "run" and "stop" to say that it is running or stop, and sensor.washingmachine.energy that contains the total consumtion in KWh? if so how? with automation or with a trigger template?

#

the sensor needs also to be reset on each new cycle

lethal bison
#

Probably use a modification of existing 'energy' incremental sensors, using the [stop] function as a counter reset?

spark vortex
#

I guess you mean with utility meter, but how to reset it when the sensor.washingmachine.status is 'stop'? with automation?

lethal bison
#

Would something like this work, to have a script wait until all items in list are true?```
action:

  • condition: and
    conditions: template
    • wait_template: "{{ is_state(multiple_sensors, 'on') }}"```
lethal bison
#

and a second question: Is it possible to display the members of a light group that are currently unavailable? I've tried many variations of
{{ expand(state_attr('light.group_livingroom','entity_id'))}}, but all come up empty.

inner mesa
#

A variant of {{ state_attr('light.test', 'entity_id')|select('is_state', 'unavailable')|list }}

#

You didn't say what you actually tried

lethal bison
#
{% set group = ('light.group_'+single) %}{{"Group = " ~group}}
{{ expand(state_attr('light.group_'~single,'entity_id'))}}
{{ "State of "+group+": "+states(group)}}
{{expand(group)|list|count}}
{{expand(state_attr(group,'entity_id'))|list|count}}
{{ expand(states.light) }}blah
{% for item in group %}{{is_state(item,'on')}}{%endfor%}```
#
  {{ lights.entity_id }}
  {{ expand(lights) | list }}```
lethal bison
#

{{ state_attr('light.group_diningroom', 'entity_id')|select('is_state', 'unavailable')|list }}
[]
after looking at the 'States' developer tool, it appears the entity_id that contains the group's members is removed if the entity becomes unavailable.

inner mesa
#

Then it's easy

plain magnetBOT
#

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

final parcel
#

Is that possible please? πŸ™‚

mighty ledge
#

or

{% set value = 4 %}
{{ '%0XF'%(15 - '{:04b}'.format(value) | list | reverse | join | int(base=2)) }}
lucid thicket
stark spindle
#

anyone here confident with using the calendar event start / end triggers in templates?
I've currently got a template working, but it triggers in the morning on day of an event and during, not the start and during as I'd prefer

spark vortex
weary frigate
#

I have a table of oil depth against volume for an oil tank that has a slightly unusual shape making calculating remaining oil based on a sensor measuring current height non trivial. Idea is to use this to perform a lookup and conversion from height to volume. As I want to use the lookup for multiple cards and in some cases more than once for the same card is there a better option than using a custom_template for a macro and calling that with the depth to convert? (Besides writing a dedicated integration/helper)

dry narwhal
#

I think I have thought my brain into a knot.
I wanted to check if the state of any entity matching the search changes from GOOD and return "true" if it does.
{{ (states.sensor|selectattr('entity_id', 'search', 'sensor.eq3_battery')|selectattr('state', '!=', 'GOOD')|map(attribute='entity_id')|list)|length > 0 }}

But my approach is too limited

  1. I am only getting feedback from the first entity to change state
  2. I should really monitor every change of state to any state that is not GOOD, i.e. if the same entity changes from GOOD to Medium it should trigger and then again when it changes from Medium to Low
#

Tried setting a namespace and stuff like that and creating if/else, but I think this should be possible with a one-liner like the above. I just don't see it yet 😦

inner mesa
#

You can do a couple of things -

  • Remove the > 0 and just use the change in the length as a trigger
  • Create a template sensor and use the list itself as an attribute, then use the state of that entity as a trigger
dry narwhal
# inner mesa You can do a couple of things - * Remove the `> 0` and just use the change in th...

If possible, since I am reducing working code, I would prefer not to create additional "helpers" like template sensors.

If I remove the > 0 then the template will return the count of sensors that are not GOOD, so it will not change when the state changes from e.g. Mediumto Low. It would trigger if another sensor changes state though. So it is one better than what I had πŸ™‚
But would it be possible to monitor that change without creating e.g. a variable to store the previous length? I did not find a mapping/piping that directly tracks changes.

marble jackal
#

You need an additional entity to trigger on, if you also want to trigger on the second entity to change

marble jackal
dry narwhal
dry narwhal
marble jackal
#

Is there also a medium state? You mentioned that above

dry narwhal
#

medium was just an example because they are all caps.
Currently they are GOOD and LOW plus the system's unavailable and unknown.

inner mesa
#

Create a template sensor with a list of entities in each state in separate attributes

marble jackal
#

That's what I wanted to propose as well, you can also give every state a weight, so MEDIUM 1, LOW 2, etc, in that case a change from medium you low will also cause a state change

quiet kite
#

hello, i have this code:

plain magnetBOT
quiet kite
#

i want to create switch to set state form this select:

plain magnetBOT
quiet kite
#

this shoudl works good?

#

this code is better, but change state from this switch dont works:

plain magnetBOT
quiet kite
#

works better if i keep good types... i need to sue select, not input_select

dry narwhal
inner mesa
#

Perhaps your optimization attempt isn't worth it

marble jackal
#

The real advantage of the template sensor is that it is dynamic, if entities are added or removed, the template sensor will adjust

#

if you have a state trigger with a list of entities, you'll have to change that when entities are added or removed

dry narwhal
#

Since the sensors will always have the nomenclature, so the template will always include all of them

quasi gulch
#

I can see the hourly forecast in the UI, but can't find an entity for it in the developer tools
(can't upload an image)

dry narwhal
#

Is it crucial? No. Is the current solution poor coding? Yes.
(poor on my part because HA does not allow for a lot of things (like templating everywhere) which forces me to use approaches that I find suboptimal and cannot find a workaround that feels elegant)

sacred sparrow
#
  {{ is_state('climate.mitsubishi_hvac', 'off') or
  state_attr('climate.mitsubishi_hvac','current_temperature') >= 24 or
  is_state('binary_sensor.living_room_warmed_up', 'on') or
  is_state('binary_sensor.office_warmed_up', 'on') or
  is_state('binary_sensor.bedroom_warmed_up', 'on') or
  is_state('input_select.bedroom_status', 'Off') }}```
#

is there a way to make is_state('binary_sensor.office_warmed_up', 'on') only wait if it goes from OFF to ON? I don't want to continue if the sensor is already ON

sacred sparrow
lucid thicket
quasi gulch
final parcel
lucid thicket
final parcel
#

thanks!

#

will do πŸ™‚

strange geode
#

Is there a way i can call Emby for a remote control card like this ?

  - type: button
    icon: mdi:netflix
    tap_action:
      action: call-service
      service: remote.turn_on
      data:
        activity: https://www.netflix.com/title
      target:
        entity_id: remote.living_room_tv
    hold_action:
      action: none
marble jackal
strange geode
#

Is not a sensor im trying to but a template card ? πŸ™‚

marble jackal
#

you first need to know how to perform the action

#

and you can't use templates anyway in tap actions

strange geode
#

Okay make sense thanks πŸ™‚

marble jackal
#

but you want to perform a service call, so you need to know how it works for emby

acoustic arch
#

Goodmorning! Im subtracting 2 timestamps from eachother which result in an X amount of seconds. How can i convert this into hours and minutes, so i can TTS the hours and minutes to my phone?

#

I tend to just TTS hours and minutes seperate because else i get a in the afternoon TTS as extra

#

got it:
{{ 3660 | timestamp_custom('%H', false) }}
{{ 3660 | timestamp_custom('%M', false) }}

tender bloom
#

I want to document a Template sensor I created. Apart from a screenshot, is it possible to copy the code and configuration of the sensor. I was going to copy the YAML but I created it using the UI and can't see where they are saved.

mighty ledge
#

that information is likely only available in the hidden files

marsh cairn
#

Or you go to the sensor's settings and select template settings. There your template will be shown.

thorny snow
#

hello everyone.

newbie here, so dont hit me too hard.

ive made and setup this "template"

  • platform: template
    sensors:
    tempo_formatado:
    friendly_name: Data e Hora
    value_template: >
    {% set days = ['Segunda', 'TerΓ§a', 'Quarta', 'Quinta', 'Sexta', 'SΓ‘bado', 'Domingo'] %}
    {{ days[now().weekday()] }} - {{ now().timestamp() | timestamp_custom('%d/%m/%Y %H:%M') }}

its working, its shows the accurante day of the month, with all the formating i want in the template editor

But how do i add it to homeassistant so that i can go and fetch the entity "tempo_formatado" and disply its value on a simple card on my frontend? πŸ€”

mighty ledge
#

if you put that in configuration.yaml in the sensor section, just add the entity to your UI

#

like you would any other entity

thorny snow
#

well, i THOUGH so, but its not working

#

configuration.yaml

plain magnetBOT
#

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

thorny snow
#

and when i try to reboot the home assistant to update / verify the file, i get

The system cannot restart because the configuration is not valid: Integration error: platform - Integration 'platform' not found. Integration error: sensors - Integration 'sensors' not found.

mighty ledge
#

you have to put that template in the sensor section

#

you just paste that at the root level

#

i.e.

sensor:
  - platform: template
    ...
#

make sure your indentation is correct as well when you add it properly

thorny snow
#

Ok, we getting somewhere, but now the "error" grew lol

The system cannot restart because the configuration is not valid: Invalid config for [sensor.template]: expected dictionary for dictionary value @ data['sensors']. Got None extra keys not allowed @ data['tempo_formatado']. Got {'friendly_name': 'Data e Hora', 'value_template': "{% set days = ['Segunda', 'TerΓ§a', 'Quarta', 'Quinta', 'Sexta', 'SΓ‘bado', 'Domingo'] %} {{ days[now().weekday()] }} - {{ now().timestamp() | timestamp_custom('%d/%m/%Y %H:%M') }}"}. (See ?, line ?).

mighty ledge
#

you probably didn't indent everything together

#

indentation is important in yaml, make sure that all your indentations line up w/ the indentations in the documentation

thorny snow
#

tried to send a picture but it doesnt allow me !

mighty ledge
#

we don't want pictures of text

thorny snow
#

funny thing is that the filed editor says its all good

mighty ledge
#

post what you've tried

inner mesa
#

(as formatted text)

#

doh

thorny snow
#

`sensor:

  • platform: template
    sensors:
    tempo_formatado:
    friendly_name: Data e Hora
    value_template: >
    {% set days = ['Segunda', 'TerΓ§a', 'Quarta', 'Quinta', 'Sexta', 'SΓ‘bado', 'Domingo'] %}
    {{ days[now().weekday()] }} - {{ now().timestamp() | timestamp_custom('%d/%m/%Y %H:%M') }}
    `
inner mesa
#

you need to indent everything under sensors:

#

the docs show the formatting

mighty ledge
#

yes, you just indented the first 2 lines, you ddin't indent the rest with it

#

if the docs show

x:
  Y:
    Z:

when you indent it, it should still have that same waterfall look.

   x:
     Y:
       Z:
thorny snow
#

....it really is all spacing uh?

#

thanks everyone, damn that was strangely hard, like the coding part was the easy one LOL

mighty ledge
#

YAML is just JSON w/ spaces

inner mesa
#

that's one take πŸ™‚

woven moth
#

YAML is Python for data nerds πŸ˜„

frigid vale
#

Good evening everyone! I've set up a switch using Wake-on-LAN and Karpach's software to power on and off my computer. Here's the template I'm currently using:

shell_command:
  sleep_on_lan_desktop: 'curl http://192.168.0.52:5001/shutdown'

wake_on_lan:
switch:
  - platform: wake_on_lan
    mac: C8-7F-54-A0-FD-79
    name: "PCBRYAN"
    host: 192.168.0.52
    turn_off:
      service: shell_command.sleep_on_lan_desktop

Now, I'd like to turn this switch into a media player. Is it possible to create a media player template? Thank you.

fossil venture
#

No you can't turn a switch into a media player. How would a switch play audio?

plain magnetBOT
#

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

fossil venture
#

Yeah that is not going to support any of the media services.

frigid vale
fossil venture
#

Also, if you must abuse the integration like that you can use: value_template: "{{ is_state('switch.pcbryan', 'on') }}"

inner mesa
#

With some single quotes in place of double πŸ™‚

fossil venture
#

Fixed.

tribal cloak
#

Hi, bear with me, I'm new to the "inner" workings of HA.
I'm trying to get a calculation on a utility meter I created, which tracks the energy of shelly2 plugs.
The helper is working fine and showing me the daily energy consumption (needs utility meter as shelly only shows the sum and resets from time to time).
So far so good. Now I tried to use this new sensor to do a calculation to give me the respective cost:

When I try this in the dev-template i get this:

#

{{ states('sensor.monthly_rack') | float 0.20.98 | round() }}
{{states('sensor.rack_monthly_cost')}}

3.4472766666665997
unknown

#

I've entered this in the configuration.yaml:

template:

  • sensor:
    • name: "Rack monthly cost"
      unit_of_measurement: "€"
      state: >
      {{ (states('sensor.monthly_rack')| float * 0.2 * 0,98) }}
#

why does the calculation work in the template test but not when I put this in the config (I get "unknown" on the created sensor)?

#

Help MUCH appreciated as I never did this. And this example will get me going with other calcs

fickle sand
#

state: >{{ (states('sensor.monthly_rack')| float * 0.2 * 0,98) }}
Notice the inconsistent use of comma and points to define decimals

marble jackal
#

the template should also be on the next line

#

oh and

plain magnetBOT
#

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

#

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

tribal cloak
#

Something is wrong but I'm really struggling

#

Found it: There was one extra line I had pasted wrongly.
Now with this in the config it works:

template:
  - sensor:
     - name: "Rack monthly cost"
       unit_of_measurement: "€"
       state: >
          {% set state = states('sensor.monthly_rack') | float *0.2*0.98 %}{{ state | float }}
marble jackal
#

@tribal cloak you can simplify this, and I would advice to add an availability template

template:
  - sensor:
    - name: "Rack monthly cost"
      unit_of_measurement: "€"
      state: "{{ states('sensor.monthly_rack') | float * 0.2 * 0.98 }}"
      availability: "{{ states('sensor.monthly_rack') | is_number }}"
mighty ledge
marble jackal
mighty ledge
#

oh, nice that was a total guess 🀣

plain magnetBOT
#

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

marble jackal
#

you should remove the first template: line in your templates.yaml

#

that one you already have in configuration.yaml

tribal cloak
#

I deleted that line in the configuration.yaml, so I put it in the templates.yaml.
But the issue was just a few extra spaces at the beginning of some lines (so hard to see). YAML is super sensitive on this. Using BBEdit on Mac and it's hard to align everything

marble jackal
#

no, the line should be in configuration.yaml, otherwise you don't inlcude the file

#

template: should be removed from templates.yaml

tribal cloak
#

done

#

All working now. Thx all!

sly harbor
#

Hi guys I have a rest sensor which currently spits out a string for a time in the format "15:00" - my value template is as follows:

      fajr:
        friendly_name: Fajr
        value_template: "{{ state_attr('sensor.salah_data', 'Fajr') }}"

How do I cast this to a proper homeasistant time so it can be used in automations?

plain magnetBOT
#

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

marble jackal
#

you can use this in a time trigger:

      fajr:
        friendly_name: Fajr
        value_template: "{{ today_at(state_attr('sensor.salah_data', 'Fajr')) }}"
        device_class: timestamp
        availability_template: "{{ state_attr('sensor.salah_data', 'Fajr') is not none }}"
sly harbor
marble jackal
#

it will be converted to a datetime isoformat string

#

you can then use sensor.fajr in a time trigger

#

I'm not sure what you mean with a real time

sly harbor
#

Ah nice - I suppose I meant a datetime isoformatted string. Thank you, I'll give that a go

sly harbor
plain magnetBOT
#

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

mighty ledge
#

guessing you figured it out?

#

was just looking at it

analog mulch
#

Sorry I begun to feel like it was too long to post here and was going to move it to the forums

mighty ledge
#

can you just DPaste the entire template sensor?

analog mulch
sly harbor
marble jackal
#

I would do that in the template sensor

#

for 10 minutes

      fajr:
        friendly_name: Fajr
        value_template: "{{ today_at(state_attr('sensor.salah_data', 'Fajr')) - timedelta(minutes=10) }}"
        device_class: timestamp
        availability_template: "{{ state_attr('sensor.salah_data', 'Fajr') is not none }}"
#

then use the template sensor in a time trigger

sly harbor
#

Is there an easy way to duplicate the fajr sensor so I have a fajr_minus_ten and retain the original fajr sensor?

mighty ledge
#

nothing is jumping out at me wigster

analog mulch
mighty ledge
#

Not yet

#

it's been discussed

marble jackal
#

you can create it in an automation

#

dump the data in a persistent notification

analog mulch
mighty ledge
#

You can also create an event and look at the event data

#

actually, you could simplify your triggers that way

sly harbor
mighty ledge
#
- trigger:
    - platform: template
      value_template: >-
        {% set midnight = as_local(as_datetime(state_attr('sun.sun','next_midnight')))%}
        {{ now().minute == max([5,midnight.minute+1])}}
    - platform: time
      at: "00:00:10"
  action:
  - variables:
        hour_local: "{{ now().hour | int}}"
        hour_solar: >-
          {% set mid = as_local(as_datetime(state_attr('sun.sun','next_midnight')))%}
          {{((now() - mid+timedelta(hours=24)).seconds/3600)|int}}
        T_curr: "{{states('sensor.inpo_praha_temperature')|float}}"
  - event: WIGSTERS_TEMPLATE_VARIABLES
    event_data:
      hour_local: "{{ hour_local }}"
  sensor:
  ...
#

@analog mulch ^

#

then your automation could just listen to WIGSTERS_TEMPLATE_VARIABLES

mighty ledge
#

or you could just watch the event in developer tools -> events tab

sly harbor
#

Thanks again @marble jackal for all the help

marble jackal
#

no problem

analog mulch
kind silo
#

`- platform: template
sensors:
garage_main_brightness:
value_template: {{ state_attr('light.garage_main','brightness') }}

  • platform: template
    sensors:
    garage_main_brightness:
    value_template: state_attr('light.garage_main','brightness')`
inner mesa
#

your first one is missing quotes around the template. the second is just bad syntax

kind silo
#

i agree with the second, do you mean value_template: {{ "state_attr('light.garage_main','brightness')" }}

inner mesa
#

no

#

around the whole template

kind silo
#

got you, thanks

acoustic arch
#

pickup_start: '2023-11-01T16:30:00Z' is an attribute, in this case tomorrow.

How can i tell if this date is today, tomorrow, or later this week

#

i made something absolutely terrifing, which works.... until we go from 31e to 1e of the new month hahaha

mighty ledge
#
{% set days = (now() - state_attr('sensor.whatever', 'pickup_start') | as_datetime).days %}
{% if days == 0 %}..
{% elif days == 1 %}..
... etc
acoustic arch
#

this actually looks at the calendar?

#

because i scraped the day and compared it to the scraped day of the month, resulting in crap from 31 to the 1e

#

ill have a look thx!

#

with {{ days }} i get -1 so need to switch places

mighty ledge
#

ya, sry

acoustic arch
#

np! at least i can figure this stuff out nowadays

#

spoke to soon 😦
{{ (state_attr('sensor.tgtg_dirk_van_den_broek_amersfoort_groningerstraat_verrassingspakket', 'pickup_start') | as_datetime - now()).days }} resulting in 0 days, because its 21hours from now

#

but i need tomorrow

next pasture
#

Guys, can somebody help me to create binary sensor with decoupled button on Tasmota smart plug please?
I used SetOption73 https://tasmota.github.io/docs/Commands/#setoption73 but it just send MQTT message {"Button1":{"Action":"SINGLE"}} and immediately after CLEAR

#

I tried this but it doesn't work

  {% if is_state('binary_sensor.bathroom_button','On') -%}
    {{ False }}
  {%- else -%}
    {{ True }}
  {%- endif %}
{%- endif %}```
inner mesa
#

several things wrong with that

#

just fixing the syntax, this is what you'd want:
{{ value_json.Button1.Action == 'SINGLE' and not is_state('binary_sensor.bathroom_button','on') }}

next pasture
#

oh yes.. sorry, I copy here few times modified version πŸ˜„

#

but this doesn't work as well

#

I think because it's checking all MQTT messages and when it receive message without Button1 it's error so my sensor failed

#

I also tried it with regular sensor but it had True value just for second and after no value

acoustic arch
#
{% if (now().date() + timedelta(days=0)) | string == boxdag %}vandaag
{% elif (now().date() + timedelta(days=1)) | string == boxdag %}morgen
{% else %}vanaf overmorgen
{% endif %}```
seems to work now. Keeping if for now
#

comparing strings instead of numbers

mighty ledge
#

((… | as_datetime | as_local).date() - now().date()).days

acoustic arch
#

i see if i can make that work. I sort of always end up going timestamp first, and go from there, because thats the syntax i sort of understand lol

#

got it! resulting in 1

#

is that result a string?

marble jackal
#

No, it's an integer

lucid thicket
#

what's the right way to look up values in a dictionary if I want to find the key that is less than or equal to my lookup value?
This is what I have, and it works, but I assume there is a better way:

#
{% set mapping = {
  -10:[67,'heat'],
  0:[68,'heat'],
  10:[69,'heat'],
  20:[70,'heat'],
  40:[71,'heat'],
  60:[72,'heat'],
  70:[73,'off'],
  80:[74,'cool'],
  150:[75,'cool'] }
%}
{% set lookup = 45.2 %}
{{ mapping[mapping | select('le',lookup)| reverse | first] }}
inner mesa
#

That's a clever way to do it

lucid thicket
#

referring to the mapping variable twice seems like a kludge but if there's not a better way I'll leave it as is. Thanks

acoustic urchin
#

I would like to monitor my car's fuel consumption. I have VW integration in place that gives me the fuel level in %. I already created a template sensor that converts that to L.
How can I configure a (meter?) sensor that it monitor the decrease of the fuel and respect whens it's filled up?

sacred sparrow
#

whats the best way to turn a binary sensor on if the temp of a sensor is rising more than .5 degrees in the last 10 minutes or so

tight thicket
#

Hey, how can I make a * 10 ^ x calculation in a template?

#

{{ ((states('sensor.eheim_ph_control_kh_value') | float / 2.8) * (10 ^ (7.91 - (states('sensor.eheim_ph_control_current_ph') | float)))) | round(2)}}

analog mulch
#

Hi! When I am generating variables in a trigger, am I guaranteed that they are evaluated sequentially? i.e. if I define var1 from a template, then in the var2 template, var1 is already defined? Or can the order be indeterminate?

variables:
  var1: "{{this.state|float+1}}"
  var2: "{{var1+1}}"
tight thicket
livid quiver
#

I'm trying to get this history_stats sensor working, but although I've reloaded the yaml and tried a few different configurations, I can't get it to appear in Developer Tools -> States or anywhere. Can anyone spot the issue?

sensor:
  - platform: history_stats
    name: Fred has been at work today
    unique_id: fred_times_in_office_today
    entity_id: person.fred_bloggs
    state: "work"
    type: count
    start: "{{ now().replace(hour=0, minute=0, second=0, microsecond=0) }}"
    end: "{{ now() }}"
#

Or do I need to do a full system restart or something?

marble jackal
#

I use it in many scripts/automations

livid quiver
#

Ah I thought reloading All YAML config would be enough?? That works for other templates

marble jackal
#

First time you add a new integration you need a HA core restart

livid quiver
#

Ah does history_stats count as a new integration?

marble jackal
#

Yes

livid quiver
#

Thank you, I will try that

livid quiver
#

Thank you, that did work, though I was briefly confused by who Fred Bloggs was when I forgot to de-sanitise the example πŸ˜‚

mighty ledge
sturdy yarrow
#

Anyone know if it's possible to split my custom sensor so it not only outputs the state, but also has some of the {{ value }} as attributes to the sensor?

mighty ledge
#

you'll have to share your custom sensor and the integration it's using.

plain magnetBOT
#

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

mighty ledge
#

that's only the template

sturdy yarrow
#

Yeah, I am basically just re-calculating the Nordpool price to add all the extra my power provider charges me. So this template that I will put into my config is just giving me the value I need to pay per kwh. But I also have some math to add to a helper meter, but that would be an attribute if this is possible? As {{ prisTime }} is the price * my current consumption..

mighty ledge
#

You'd have to duplicate the template in the attribute you want it in, assuming this is a template sensor.

sturdy yarrow
#

So basically make two sensors, one for each value I want outputted?

mighty ledge
#

No, in your template sensor, duplicate the template in an attribute

#

but instead of outputting the variable that is the state, you output the variable that you want

sturdy yarrow
#

I'll give it a shot! Thank you!

plain magnetBOT
#

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

south portal
#

That was the bot's fault

#

My message: Hi. Can someone please offer some assistance? I've been trying to control my Phillips Hue bulb with HA without a bridge via Google Home (Because you don't need a bridge to add to Google Home) I can turn it on and off and get the state but can't adjust the brightness when I try to do so I get this error in Lovelace: "Failed to call service light/turn_on. extra keys not allowed @ data['brightness']".

#

Script for adjusting brightness

#

light template

mighty ledge
#

You are duplicating service on set_level

#

also do not post this twice

#

the bot did it's job and hid the post because you went over the number of allow lines for a single message.

south portal
#

thanks

#

do I then need to incorparate the set brightness in the on/off script?

mighty ledge
#

Your script needs to use the brightness variable

south portal
#

how?

mighty ledge
#

By using the brightness variable as an input, i.e. your script needs to use that variable in whatever it's using the brightness for

#

post your script

south portal
#

I have a script for off and another one for on

mighty ledge
#

ok, well what do you expect set level to do then?

south portal
#

idk

mighty ledge
#

alright, then remove it

#

if you aren't setting the brightness on the light and you don't have a script, then you don't need it

south portal
#

I am setting the brightness

mighty ledge
#

then you need a set level script

south portal
#

I have a script to set the brightness to brightness, since I am using the Google assistant api I had to send a text command to Google assistant that says: set brightness of bedroom ceiling light to β€œ{{ brightness }}”

#

So how do I get set-level to call that script?

mighty ledge
#

you just said you only had the turn on and turn off script

#

I feel like I'm taking crazy pills

#

if you have a set level script, post it

#

otherwise we will continue to go in circles here

south portal
#

alias: Set bedroom ceiling light brightness
sequence:

  • service: google_assistant_sdk.send_text_command
    data:
    command: Set brightness of bedroom ceiling light to "{{ brightness }}"
    mode: single
    icon: mdi:ceiling-light-multiple
mighty ledge
#

format it please

south portal
#

how

mighty ledge
#

google "format code discord"

south portal
#

` alias: Set bedroom ceiling light brightness
sequence:

  • service: google_assistant_sdk.send_text_command
    data:
    command: Set brightness of bedroom ceiling light to "{{ brightness }}"
    mode: single
    icon: mdi:ceiling-light-multiple `
mighty ledge
#

Your script is already using the brightness variable

#

so all you need to do is remove the duplicate service: input_boolean... line

south portal
#

I know but why do I get an error when I try to adjust the brightness?
sorry if I'm not being very clear.

mighty ledge
#

again, it's because you have a duplicated service line

#

I've said this 2 or 3 times now

#

so, look at your code, read the duplication and remove the one not calling your script

south portal
#

thanks

#

it worked

mighty ledge
#

np

south portal
#

wait the brightness adjuster works but the light isn't updating.

mighty ledge
#

light in the UI?

#

if yes, that's expected because you don't have a level_template

#

and because you're going to some google device, you likely won't have that

south portal
#

no the physical light

#

@mighty ledge

mighty ledge
#

If the script ran, look at the trace.

#

it will tell you if it failed

south portal
#

problem solved it was becuase of the quotes around the varible because it passes the command on to google asisatnt

#

Grammarly does not work on discord

plush escarp
#

question for ya fellers. i tried {{ as_timestamp(states('sensor.date')) | timestamp_custom('%B') }} in the dev tools template tool thingy dingy and it works. however, when i add it to my config, and check yaml i get the error "Error loading /config/configuration.yaml: invalid key: "{"as_timestamp(states('sensor.date')) | timestamp_custom('%B')": None}"
in "/config/sensor.yaml", line 17, column 0" what gives?!

inner mesa
#

You need to share what you added

#

My guess is you didn't surround it in quotes

plush escarp
#

i made another one for day of the month and that works, but month doesnt

#

quotes where exactly?

inner mesa
#

Dude

plush escarp
#

it wont let me post an image

inner mesa
#

I'm done guessing

#

That's good. It's text

plush escarp
#

{{ as_timestamp(states('sensor.date')) | timestamp_custom('%B') }}

marsh cairn
#

A wise man once said:

RobC:
You need to share what you added

plush escarp
#
    sensors:
      month:
        value_template:
          {{ as_timestamp(states('sensor.date')) | timestamp_custom('%B') }} ```
mighty ledge
#

you're missing the multiline indicator

#

: >

plush escarp
#

where would that go exactly?

mighty ledge
#

after value template

#

just the >

plush escarp
#

my man. preciate ya, p

sage aurora
#

I have a custom template that converts a differential pressure in Pascals to Inches of Water.

I'd like to add a 5 minute rolling average. What's the best way to do this? Should I use statistics on the raw value, then convert it after?

#

Right now I'm doing the opposite but getting errors trying to get statistics to find the converted value.

mighty ledge
#

w/ the stats integration

sage aurora
# mighty ledge w/ the stats integration

I think that's what I am trying?

sensor:
  - platform: statistics
    name: "Pressure Differential 5-Min Avg inH2O"
    entity_id: sensor.pressure_differential_inches_of_water
    max_age:
      minutes: 5
mighty ledge
#

you can also try the filter integration

#

which might be more what you're looking for if you want moving average

sage aurora
#

Template is

template:
- sensor:
  - name: "Pressure Differential in Inches of Water"
    unique_id: pressure_differential_inches_of_water
    unit_of_measurement: 'inH2O'
    state: "{{ states('sensor.press_diff_pressure') | float / 248.84 }}" # Conversion factor from pascals to inches of water
    device_class: "pressure"
    state_class: "measurement"

It's saying it can't find the sensor.

#

Ok let me try filter

#

that looks better

sage aurora
fossil venture
#

Has the source sensor changed state?

mighty ledge
#

That or wrong entity id

sage aurora
#

I did have a bad unit value. I removed the unit alltogether, we'll give it 5 minutes see if it updates.

#

I'll get a forum post going this is just way to challenging

supple night
#

Hi, im trying to just get the date and not the time on one of my lines that just tells me the countdown to the next bin day. And i have no idea about yaml etc.
type: entity
entity: calendar.garbage
attribute: (what to i put in here)

#

thanks

mighty ledge
charred oar
#

I am playing around trying to create a template sensor for my met.no integration. I am currently trying to just print the current temperature in the developer tools/template. I am just seeing "weather is undefined" when I try to access weather.home

#

Any ideas?

lofty mason
#

post what you tried

#

probably missing quotes

charred oar
#

Yeah that was definitely one mistake!

#

should I access the temperature through state_attr() with second argument 'Temperature'?

lofty mason
#

sure

charred oar
#

{{ state_attr('weather.home', "Temperature") }} gives me None

lofty mason
#

lowercase?

silver meteor
#

is on mine

#

temperature

lofty mason
#

you'll want to look at what is available in your developer tools/states

charred oar
#

Yeah that's it πŸ™‚

#

And template sensors are still only defined in yaml by editing a config file?

lofty mason
#

nope they have a helper in the UI now

#

much easier

charred oar
#

Oh neat!

lofty mason
#

(at least for simple templates)

silver meteor
#

I'm trying to use a template to show time since a dehumidifier tank was full and my second as_timestamp is failing.
FULL for {{ (as_timestamp(now()) - as_timestamp(states.sensor.dehumidifier_tank_last_full,0) | int ) | timestamp_custom("%M", false)|int }} minutes right now that's just returning the current minutes of the hour, which means the second as_timestamp method is returning 0 because it's failing. anybody see anything obvious I'm doing wrong? the sensor is a template of its own. it looks like...

#
  - trigger:
      - platform: state
        entity_id: binary_sensor.dehumidifier_1fa0_tank_full
        from: "off"
        to: "on"
    sensor:
      - name: Dehumidifier Tank Last Full
        state: "{{ now() }}"```
#

that returns a string that looks like a date time

lofty mason
#

states.sensor.dehumidifier_tank_last_full - remember this returns the state object, not the state

silver meteor
#

oh doh

#

so it should be sensor.dehumidifier_tank_last_full.state

#

?

lofty mason
#

yes, or use the states() function

inner mesa
silver meteor
#

hrm as_timestamp(states(sensor.dehumidifier_tank_last_full),0) results in 'sensor' is undefined

inner mesa
#

like I said

#

needs to be a string

silver meteor
#

ah the parameter for states() is a string

#

awesome

#

thanks so much everyone

inner mesa
#

You can do datetime math to make that simpler, BTW. As an example:

{{ ((now() + timedelta(minutes=5)) - now()).total_seconds()//60 }}
#

you're unnecessarily converting everything to a timestamp and then turning that timetamp difference into a formatted string

silver meteor
#

cool, thanks. I was just working off code I found, heh

violet kite
#

any idea on how i can sum the values of 40 sensors without blowing my brains out?

it's for a solar array - i can get the power of every panel but i have 40 of them and this feels like i'm going to die if i have to do this for each unique panel

       {{ [ states('sensor.power_1_1_1'), states('sensor.power_1_1_10') ]
           | map('float') | sum }}
gentle juniper
#

Does anyone know how to do regex matching against entity states? The reason being, I'm using last notification entity from my phone companion app. I need to read states from notifications that will vary in content.

#

Context: Attempting to create conditions, within a trigger to do matching against the content of the state. Since the state is the text provided by the app notification on my phone, there isn't a set of expected responses. But I do know the responses I want to react to contain certain phrases.

marble jackal
#

Or.. are they the only power sensors for that integration

gentle juniper
#

There is an attribute that contains the text I need to evaluate if that's what you mean

#

oops you're not repsonding to me lol

violet kite
#

and then the other sensor would be
sensor.power_1_1_10

#

and so on

#

i thought there was a FR for this a while ago i'm not sure if they ever pulled trigger on this cuz there's gotta be a better way to add values than YAML

#

the only thing that is the same with them is that they all start with sensor.power

no other entities besides them have sensor.power in them in that exact context

marble jackal
#

Do they all start with sensor.power_1_1

violet kite
#

unfortunately not.

here's a list of 5

sensor.power_1_1_1
sensor.power_1_1_10
sensor.power_1_1_11
sensor.power_1_1_2
sensor.power_1_1_3

marble jackal
#

They still all start with sensor.power_1_1

violet kite
#

the only thing that's static is

sensor.power_1_

#

oh why did it do that

#

hm doesn't like the lonely _ _

#

underscore

marble jackal
#

Because it's markdown for italics

violet kite
#

ah

#

_1_

#

oh use backslash

#

there we go!

marble jackal
#

{{ states.sensor | selectattr('object_id', 'search', '^power_1_') | map('states') | select('is_number') | sum }}

violet kite
#

no attribute lower :/ not sure what that means

#

it's measured in Watts if that adds any context

#

if that helps

marble jackal
#

Not much

#

What does this return
{{ states.sensor | selectattr('object_id', 'search', '^power_1_') | map('states') | list }}

violet kite
#

AttributeError: 'TemplateState' object has no attribute 'lower'

tepid fox
#

Hello everyone, i'm trying to create a 3d visual of all the lights at home, and after I finished all the light work etc and doing the link beetwen the pictures and the light state I get a loading icon that never goes away. Anyone knows what it can be?

marble jackal
violet kite
#

updated the imgur link with OS info

#

2023.11.0

marble jackal
#

Wait

violet kite
#

2023.10.1 for sup

marble jackal
#

Sorry

#

{{ states.sensor | selectattr('object_id', 'search', '^power_1_') | map(attribute='state') | select('is_number') | map('float') | sum }}

violet kite
#

TypeError: unsupported operand type(s) for +: 'int' and 'str'

marble jackal
#

Corrected above

violet kite
#

85.13999999999999

#

LOOKS RIGHT!

#

suns's going down so not suprising how low it is lol

marble jackal
#

πŸ‘

#

Sorry for all the mistakes πŸ™‚

violet kite
#

ill check it out tomorrow when the suns up but thanks so much for the assist i was dreading having to code that device by device - you're a lifesaver!

gentle juniper
tardy stirrup
#

I'm a total freaking programming newb, would anyone be willing to help me work through the language to pull specific attributes out of a entity ?

I've spent the last few hours digging through forum posts, trying to figure this out, and I think I am close, but still getting a invalid config for sensor error

#

I created a sensor.yaml file, which I know is working, trying to add a new platform to pull the sensor attribute using value_template and state_attr per recommendation on a github forum

lofty mason
#

You've still not really posted what you tried (specific lines of code and specific error messages). Until you do, nobody is really going to have anything much to say.
Personally I think you're probably better off trying to make a template helper in the UI, much easier than mucking about in yaml.

tardy stirrup
#

I didn't want to flod the chat with a bunch of code and stuff

#

Is the template helper the preferred route for peopel who can't navigate the .yaml well?

#

I actually just got the sensor to show on my dashboard, but the value is "unknown"

#
    sensors:
      sensedge_co2:
        value_template: "{{ state_attr('air_quality.laseregg_air_quality', 'Carbon_dioxide') }}"
        device_class: Carbon_dioxide
        unit_of_measurement: ppm```