#templates-archived

1 messages ยท Page 28 of 1

mighty ledge
#

if you want to use the switch instead, you'd use the switch.turn_on service

#

but you still need to have properly formatted yaml

#

which your turn_off service has but your turn_on service does not have

full nacelle
#

ok

#

i got what you are saying now

#

turn_on: service: switch.toggle target: entity_id: switch.lg_tv

#

something like this?

#

yeah works

mighty ledge
#

well, keep in mind if you call switch.turn_on again, it will turn off

#

so are you sure you want the switch.toggle service, or do you want the switch.turn_on service?

full nacelle
#

also I want to setup something where I give alexa a command and it answers from the ha scripts

mighty ledge
#

yeah but if you turn it on twice, it will turn off the 2nd time instead of staying on

#

toggle is a toggle

#

it alternates

#

on -> off -> on -> off -> on -> off

full nacelle
#

I can just use that switch to turn on devices

#

same goes to my pc

#

so I use hass to work with it on pc

#

and alexa media player on tv

full nacelle
mighty ledge
#

You're going to need to start with a starting place

full nacelle
#

starting place?

mighty ledge
#

i.e. that's a tall order and I don't have the time to walk you through the whole thing

#

especially if you don't have nabucasa and you're using the custom alexa media player integration

#

so, i suggest looking on the forums for posts or using the alexa media player integration documenation

full nacelle
#

yeah nabucasa make things easier

marble quiver
#

is there any way to write a template that would say for all devices (entity of type x) a new value would be created. So say for all lux values from each lux sensor, it would create a word description for each that says "direct sunlight" or "no sunlight" for that sensor, without having to create a yaml file entry for each sensor

mighty ledge
gusty ledge
#

states('switch....') or states.switch.....state ?

quasi widget
#

Well, I solved the wake on lan issue with my LG C2. All I had to do was remove the broadcast IP, leave only the MAC. For some reason the C2 doesn't like it if you input both. Power on and off toggle working like a charm now.

mighty ledge
#

only use the other method when you want to get properties of the state object. And if you don't know what that means, don't worry about it ๐Ÿ™‚

quasi widget
#

Hass.Agent is awesome btw.

mighty ledge
#

yah, it's super easy

gusty ledge
mighty ledge
#

so you have to use the other method

gusty ledge
mighty ledge
#

yes

#

state objects are python objects that hold information about the state of an entity

#

it contains, the state and attributes, both which are properties of the state object

#

it just so happens that states() gets the state property and state_attr() gets the attribute property's attributes

#

if you want access to any other properties on the state object, you have to use the states.xxx.xxx. method

#

If you want to read up on it, I made a post a few years ago that covers it

gusty ledge
#

many thx, now things are more clear ๐Ÿ™‚

#

it'll be good the docs/configuration/state_object/ will have your examples or a link to your post

mighty ledge
#

I believe they are in the state object docs

gusty ledge
#

your post is the better one ๐Ÿ˜‰

marble quiver
limber haven
#

Hm. This feels like it should be simple but Im struggling, I want to take a time value from a input_datetime, and work out how many seconds it will be from now, till that time

#

I... came up with this but I.. have no idea what the result means but its not right haha.. ```{{ now() + timedelta(seconds=state_attr('input_datetime.dishwasher_start_time', 'timestamp') |int) }}

#

(It gives me this in the template editor, I've no idea what Im doing 2023-02-09 15:32:00.146624+00:00

mighty ledge
#
{{ (states('input_datetime.dishwasher_start_time') | as_datetime | as_local - now()).total_seconds() }}
limber haven
#

okay, I was way off then..

mighty ledge
#

you were trying to add the total time from 1970 to the current time

#

so you would have been roughly 50 years off

limber haven
#

๐Ÿ˜„

#

hm, thats giving me a slightly odd error AttributeError: 'NoneType' object has no attribute 'tzinfo'

neon bolt
#

Hi, there, i have this message into a calendar entry

#

is there any way to grab et 4 digits and add them to a text field ?

mighty ledge
limber haven
#

Just a time I think, thats what I created it with in the UI

#

yeah, its just time. has_date: false

#

Im assuming the problem is the as_datetime but honestly I cnat figure out what filter it hsould be ๐Ÿ˜„

#

Logically, at least to me you think as_time would work, but that's not a thing

mighty ledge
#

On mobile

limber haven
#

Hm, that renders correctly, but behaves oddly after midnight as it converts the 'seconds' into a negative number ๐Ÿ˜„

#

So 00:10 which is about 1 hour from now gives -82440

#

i mean I guess that makes sense as its about that many seconds from midnight this morning

mighty ledge
limber haven
#

Hm, Is there a way to make it implicit that its 'past' that time to automatically make it the next day? this is going ot be part of an automation if I need to set the date/time manually each time it would rather defeat the point ๐Ÿ™‚

mighty ledge
#

Just add 24 hours on seconds

#

To the negative value if itโ€™s negative

hexed galleon
#

Is there such thing as a "friendly state"? Retrieving the state via a template for some entities gives a different result to what their entity card will show in a dashboard. Example: weather.home returns partlycloudy while the UI shows "Partly cloudy" and alarm.alarmo returns armed_away when the UI shows "Armed away".

inner mesa
#

That's a translation, and there's currently no way to get that from a template

hexed galleon
#

Bummer, thanks anyway!

#

Chained | replace() will have to do for now ๐Ÿ™‚

inner mesa
#

creating a dict and indexing into it is a straightforward way to do it

hexed galleon
#

Yeah, there's only a handful of states that need to be remapped though. If it were > 3, would definitely map it via a dict.

mighty ledge
#

@inner mesa did your PR ever go through?

inner mesa
#

Nope

#

It's not voice, I'm afraid

pine musk
#

wow, those calendar triggers are limited

marble jackal
inner mesa
#

Nope

marble jackal
#

Okay, otherwise it would be useful for Voice responses ๐Ÿ˜›

#

Is it for the expand thing?

humble mortar
#

How do you test against UndefinedError: list object has no element 3 I tried to put if not defined, if true, if length, it always explodes and never continues with the else but if I define it to element 2 it will complete fine and toss the if message and carry on.

marble jackal
#

{{ something[3] if something | count > 3 else 'whatever you want then' }}

humble mortar
#

Still fails

#
        {% set img = state_attr('sensor.printer_3d_file_metadata','thumbnails')[3].relative_path %}
        {{ img[3] if img | count > 3 else 'whatever you want then' }}
marble jackal
#

It fails in the first line

humble mortar
#

How do I fix that?

marble jackal
#
{% set thumb = state_attr('sensor.printer_3d_file_metadata','thumbnails') %}
{% set img = thumb[3].relative_path if thumb | count > 3 else 'whatever you want' %}
{{ img }}
limber haven
#

Are there any good guides on Jinga? I'm struggling to make much sense if the official stuff

humble mortar
#
        {% set thumb = state_attr('sensor.printer_3d_file_metadata','thumbnails') %}
        {% set img = thumb[3].relative_path if thumb | count > 3 %}
        {% else %} 
        {% set img = thumb[2].relative_path %}
        {% endif %}
#

TemplateSyntaxError: Encountered unknown tag 'else'.

humble mortar
#

Easiest way to poke at making templates stuff without restarting HA

marble jackal
humble mortar
#

if thumb?

#

I was trying to add the 'whatever you want' part

marble jackal
#
{% set thumb = state_attr('sensor.printer_3d_file_metadata','thumbnails') %}
{% set img = thumb[3].relative_path if thumb | count > 3 else thumb[2].relative_path %}
{{ img }}
humble mortar
#

but it didn't work when I added that thumb[2] there so I tried to expand it out

marble jackal
#

what does {{ state_attr('sensor.printer_3d_file_metadata','thumbnails') }} return in devtools > templates

limber haven
humble mortar
#

Your above worked

- name: 3d_printer_object_thumbnails
      unique_id: "IP59b37837-b751-4d31-98c2-516a52edf833"
      state: >
        .thumbs/pumpkaboo_print-400x300.png
        http://IP:7125/server/files/gcodes/some/directory1/directory2/.thumbs/pumpkaboo_print-400x300.png
      availability: >
        True
      icon: mdi:image
      attributes:
        friendly_name: "Object Thumbnails"
#

if you wanted to expand that so if now 2 doesn't exist it selects 1 and if 1 doesn't exist it selects 0 and if it doesn't exist at all it doesn't explode how would you manage that?

humble mortar
#

There is only 0 1 2 (basically different size of thumbnails)

#

People are having issues as apparently their slicers don't conform and spit out a different quantity of thumbnail sizes depending on what they set.

#

Hard to think about all the way users can break something.

marble jackal
#

do you always want the last one in the array?

humble mortar
#

yes

#

(the largest quality is the last)

marble jackal
#

then just use last

#
{% set thumb = state_attr('sensor.printer_3d_file_metadata','thumbnails') %}
{% set img = (thumb | last).relative_path if thumb else 'not available' %}
{{ img }}
humble mortar
#

Thank you that is perfect!

analog mulch
#

hi. Is there a way to manually trigger an update of a trigger-based template sensor?

humble mortar
#

scan_interval?

analog mulch
#

I mean I just literally need to do it now by hand, because it's unknown and it will not update itself for another hour.

humble mortar
#

scan_interval: 3600

analog mulch
#

I thnk I wasn't clear. I have a trigger-based sensor set up. It update once an hour. I am happy with this behaviour. But it got into a bad state, so I would like to evaluate itself now, once, outside it's automatic behaviour, like triggering an automation by hand. But I can't see how to do that.

marble jackal
#

add an event trigger and send out that particular event from devtools > events

regal temple
#

Is there any way to create template update.some_entity or repair.some_entity so they would show up in the update and repair list of the HA settings? I would love to be able to have all the update and repair issues clustered in the settings.

marble jackal
#

not that I'm aware of

regal temple
#

Pity... But thanks for your fast reply! I guess I have to file a feature request. ๐Ÿ™‚

thorny snow
#

Thanks, but this gives me: TypeError: unsupported type for timedelta hours component: str

marble jackal
#

Did you add | float?

#

oh wait, you'll have to move the last bracket

#

{{ now() + timedelta(hours=states('sensor.name')|float) }}

#

@thorny snow ^

thorny snow
#

Thanks, just struggling how to use strftime on this. I see in the docs that strptime uses strptime(string,format), but strftime doesn't seem to work that way, this gives me an error:

{{ strftime(a1,'%H') }}```

That strftime is undefined. How should I use this?
#

Got it!
{{ a1.strftime('%H:%M') }}

#

One last question. I'm now trying to convert the sensor itself to a nice format %H:%M. Which I supposed would be the easier part, I'd suppose just delete the now() part. However, this gives me an error:

timedelta(hours=states('sensor.tesla_time_to_full_charge')|float).strftime('%H:%M')

UndefinedError: 'datetime.timedelta object' has no attribute 'strftime'

#

Included in the {{ }} brackets ofcourse, forgot to paste those

marble jackal
#

you can't format a timedelta using strftime

#

you can do this
{{ (timedelta(hours=states('sensor.tesla_time_to_full_charge')|float)).total_seconds() | timestamp_custom('%H:%M', false) }}

thorny snow
#

Thanks, so it works when I add now() to it but not without?

Your script works, thanks! What does the false do?

marble jackal
#

if you add a timedelta to a datetime, you get a new datetime

#

the false makes sure UTC time is used, otherwise you will get an incorrect result based on your local timezone

#

basically you are asking for the HH:MM format of the number of seconds since 1st of January 1970, which will be converted to your local time if you don't add false

plain magnetBOT
marble jackal
#

I don't see any template here ๐Ÿ˜› But it might work if you put the entity_id under data

mighty ledge
#

You should follow what the documents say for custom:vacuum-card

#

we are guessing

#

that card is what determines the yaml format

sonic sand
mighty ledge
#

yes, so I just looked at the documents of that card, and it doesn't support data, it supports service_data

#

TLDR, you should use the documents for the custom card you're using, not make up yaml based on your previous experience

sonic sand
#

thanks man, so generally how do I know to which service_data I should call?

mighty ledge
#

Not sure what you mean

sonic sand
#
  start:
    service: vacuum.start
    service_data:
      entity_id: vacuum.mijia_v2_202f_robot_cleaner
      segments:
        - 16
        - 20

For instance, I used now this.
but getting error :
Failed to call service vacuum/start. extra keys not allowed @ data['segments']

mighty ledge
#

does the vacuum.start service accept a segments key?

sonic sand
#

Where can I check that?

mighty ledge
#

that'll be on the documentation for the vacuum service

#

you can also check that in developer tools -> services

sonic sand
#

well It worked just with the entity id there

mighty ledge
#

yes, but the service itself will tell you all the available options that you can put in data

#

if it doesn't have a 'segments' field, that service does not accept segments

sonic sand
#

Okay, thanks!

sonic sand
#

One more question if I may ask,
I have a smart aquarium tank which has attribute to the device when it last fed them.
How can I take out this attribute and make a notification when it fed them
I know that's kinda considered as automation and it's not the right place but how do I use the attribute to do it?
Thanks!

the fish tank entity is

switch.hfjh_v2_eadb_fish_tank_2

the attribute is

event.4.1: {"timestamp":1675792811,"value":[{"piid":16,"value":"2023,2,7,20,0,0,2"}]}
marble jackal
#

Well, you will actually need a template here

#

something like {{ state_attr('switch.hfjh_v2_eadb_fish_tank_2', 'event.4.1.').timestamp | timestamp_custom('%H:%M') }}

#

what a crappy attribute key btw

sonic sand
marble jackal
#

In the message you want to send probably

#
service: notify.mobile_app_your_phone
data:
  message: Fish are fed at {{ state_attr('switch.hfjh_v2_eadb_fish_tank_2', 'event.4.1.').timestamp | timestamp_custom('%H:%M') }}
#

as an example

sonic sand
# marble jackal In the message you want to send probably

Thanks, I have contact you via DM regard what trigger do I use in this case.

and another template question - I got in my robot vacuum attribute this one

clean_record.clean_area: 2973

the numbers are squared meters but there should be a '.' between the first two numbers to the last numbers (29.73 squared meters in this case).
how can I add this dot to the attribute?

marble jackal
#

I've kindly ignored your DM request

sonic sand
#

Okay, thanks anyway for helping!

marble jackal
#

But for the trigger, that's up to you. When do you want it to trigger?

sonic sand
#

Whenever it changes (in my case whenever it fed them or failed to do it)

marble jackal
#

Then do a state trigger on that attribute

sonic sand
sonic sand
#

at the "finished" automation of my vacuum I want to add data of two attributes

clean_record.clean_time

Which shows how long did he worked
and

clean_record.clean_area

Which showing up how much area did he covered during his clean
How do I write it down in the data section in the automation I already created?
Thanks a lot!

inner mesa
sonic sand
inner mesa
#

Divide by 100?

sonic sand
#

Yeah, how can I show that up in that attribute?

analog mulch
#

Hi. What's a good way to convert an otherwise increasing sensor which resets to zero every day at midnight into a cumulative one?

#

My plug reports energy use only as daily

crude stream
analog mulch
#

I basically want anti-utility-meter

crude stream
analog mulch
#

but I want to just remove the resets, not integrate the whole functions. I already have the energy as the source sensor

#

I sort of want what the total_increasing state class does

plain magnetBOT
sonic sand
# inner mesa Divide by 100?
- platform: template
  sensors:
    vacuum_clean_area:
      friendly_name: "Vacuum Clean Area"
      value_template: '{{ (states.vacuum.mijia_v2_202f_robot_cleaner.attributes.clean_record.clean_area / 100) | round(2) }}'
      unit_of_measurement: 'mยฒ'

I have created this template sensor but it showing me unavailable although the attribute getting updated by the meters it goes.
What did I do wrong here?

inner mesa
#

what does the template show in devtools -> Templates?

#

is this an actual attribute? clean_record.clean_area

sonic sand
#

UndefinedError: 'homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'clean_record'

inner mesa
#

if so, it's pretty weird

#

well, there ya go

#

figure out what you really want to manipulate

sonic sand
#

clean_record.clean_area: 156

#

that's the attribute

inner mesa
#

you'll need to handle that differently

sonic sand
#

Why and how?
Thanks for helping

inner mesa
#

state_attr('vacuum.mijia_v2_202f_robot_cleaner', 'clean_record.clean_area')

#

that's how you should access attributes anyway

sonic sand
#

let me try

#

cool it now showing me 156.0

inner mesa
#

"why" is that it has a dot in the attribute key

sonic sand
#

how can I divide by 100

inner mesa
#

what you alreaddy had

#

I just gave you the part to get the attribute correctly

sonic sand
#

It gives me TypeError: unsupported operand type(s) for /: 'str' and 'int'

inner mesa
#

then add |float(0)

sonic sand
#

instead of round(2)?

inner mesa
#

no

sonic sand
#

or in addition?

inner mesa
#

did you want to round or not

#

here

sonic sand
#

no need to, to be honest.

inner mesa
#
      value_template: "{{ (state_attr('vacuum.mijia_v2_202f_robot_cleaner', 'clean_record.clean_area')|float(0) / 100) | round(2) }}"
#

it's up to you

sonic sand
#

trying wait

inner mesa
#

fixed the quotes

sonic sand
#

Thanks man works like a charm, now if I want to show up in data within an automation do I just put the sensor in it?
like to show "The vacuum went through (sensor.vacuum_clean_area)"

inner mesa
#

you have to use the proper syntax to get the state

lilac raven
#

Is it possible to create sensors from this?
today:

  • total: 0.2878
    startsAt: '2023-02-09T00:00:00.000+01:00'
  • total: 0.2592
    startsAt: '2023-02-09T01:00:00.000+01:00'
  • total: 0.226
    startsAt: '2023-02-09T02:00:00.000+01:00'
  • total: 0.2213
    startsAt: '2023-02-09T03:00:00.000+01:00'
  • total: 0.2853
    startsAt: '2023-02-09T04:00:00.000+01:00'
  • total: 0.3511
    startsAt: '2023-02-09T05:00:00.000+01:00'
  • total: 0.4079
    startsAt: '2023-02-09T06:00:00.000+01:00'
  • total: 0.4728
marble jackal
#

Sure

plain magnetBOT
humble mortar
#

Is there a nicer way to handle duplication of everything in a yaml? If I have multiple 3D printers using this script https://github.com/NonaSuomy/Moonraker-Home-Assistant/blob/main/moonraker.yaml what way would you go about having a second moonraker2.yaml, moonraker3.yaml or in the yaml somehow be able to select multiple printers with one yaml file, then for the multiple file one having to rename all the template variables with a 2 on the end as well or something, seems a little heavy handed?

analog mulch
marble jackal
#

YAML anchors are of limited use here, as the IP or entity_id references are unique per printer

humble mortar
#

What would you suggest @marble jackal ?

marble jackal
#

I would probably use 3 seperate files and just replace the IP and sensor references

humble mortar
#

Ok

thorny snow
#

Something weird is happening. I've installed some new cards through HACS yesterday, restarted HA, emptied browser cache, but they are still not showing up. Anything else I can do?

marble jackal
marble jackal
humble mortar
marble jackal
#
{% for i in value_json.result.version_info %}
{%- if value_json.result.version_info[i].version is defined %}
{{ i }}
{{ value_json.result.version_info[i].version }}
{%- endif %}
{% endfor %}
humble mortar
#

What kind of card would you display that on?

marble jackal
#

a markdown card accepts templates

#

BTW you need to define value_json and refer to wherever you have this data

analog mulch
#

Am I allowed to set a variable using the variables: key in the trigger in a trigged-based template sensor and then use it inside my templates for the state?

marble jackal
#

yes

humble mortar
#

Confused how to access this printername

 {"result": {"namespace": "mainsail", "key": "general", "value": {"printername": "SomeName"}}}
        {% set printername1 = state_attr('states.sensor.printer_3d_1_server','printername') %}
        {{ printername1 }}
sonic sand
marble jackal
#

Which part of that do you need

marble jackal
humble mortar
#
   - platform: rest
     name: 3d_printer_1_server
     unique_id: "IP1cba6677-02bd-4273-9083-b8301bf6943d"
     scan_interval: 1
     resource_template: "http://IP:7125/server/database/item?namespace=mainsail&key=general"
     json_attributes_path: "$.result"
     json_attributes:
       - key <= which value should I be putting here?
     value_template: "OK"

When I hit this url
http://IP:7125/server/database/item?namespace=mainsail&key=general
it outputs:

 {"result": {"namespace": "mainsail", "key": "general", "value": {"printername": "SomeName"}}}
marble jackal
#

and it worked before?

sonic sand
#

I forgot to check it on the developer tools after you sent it to me..

marble jackal
#
service: notify.mobile_app_your_phone
data:
  message: >
    {% set feed_time = (state_attr('switch.hfjh_v2_eadb_fish_tank_2', 'event.4.1') | default({}, true)).get('timestamp') | timestamp_custom('%H:%M', default='unknown') %}
    Fish are fed at {{ feed_time }}
#

there was a . after 4.1 which should not be there

#

the code above should also work in case the attriubte is not available

sonic sand
#
UndefinedError: 'str object' has no attribute 'get'
acoustic arch
#

after many attempts i gave up on using attributes in a state template. I undressed my 255+ chars to this to get my head around it

    - name: "Calculated Setpoint CS"
      unit_of_measurement: "ยฐC"
      state: >
        {% set CS = ( 1 * 0.075 * (this.attributes.tbuiten - 10)**2 + 50 ) | float(default=55) | round(0)  %}
        {% if CS > 70 %}
          {% set CS = 70 %}
        {% endif %}
        {{CS}}
      attributes:
        tbuiten: "{{ states('sensor.buienradar_temperature') | float | round(2) }}"```
#

this gives me errors

marble jackal
#

Try this then

service: notify.mobile_app_your_phone
data:
  message: >
    {% set feed_time = (state_attr('switch.hfjh_v2_eadb_fish_tank_2', 'event.4.1') | default("{}", true) | from_json).get('timestamp') | timestamp_custom('%H:%M', default='unknown') %}
    Fish are fed at {{ feed_time }}
sonic sand
#

Now no error but it says Fish are fed at unknown even though there is a timestamp on the attribute (like in the picture I sent you)

also what was the problem with the get attribute so I will know for next time?

marble jackal
#

it only works on dictionaries, not on strings

#

the dot was back in my last template

#

I removed it now

sonic sand
#

Ah right yeah I see

marble jackal
#

you probably need to use a default. The state template is rendered first, so the attribute doesn't exist then

#

I usually use get() for that, but you dan also use the default filter

acoustic arch
# marble jackal define errors

TemplateError('UndefinedError: 'homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'tbuiten'') while processing template 'Template("{% set CS = ( 1 * 0.075 * (this.attributes.tbuiten - 10)**2 + 50 ) | float(default=55) | round(0) %} {% if CS > 70 %} {% set CS = 70 %} {% endif %} {{CS}}")' for attribute '_attr_native_value' in entity 'sensor.calculated_setpoint_cs'

marble jackal
#

yes, that confirms it

acoustic arch
#

tbuiten doesnt exist yet?

marble jackal
#

you can also use an if statement if you don't want an incorrect calculation

acoustic arch
#

shouldnt the default=55 catch the error?

marble jackal
#
      state: >
        {% if this.attributes.tbuiten is defined %}
          {% set CS = ( 1 * 0.075 * (this.attributes.tbuiten - 10)**2 + 50 ) | float(default=55) | round(0)  %}
          {% if CS > 70 %}
            {% set CS = 70 %}
          {% endif %}
          {{CS}}
        {% else %}
          unavailable
        {% endif %}
#

nope, the error occurs before that

acoustic arch
#

why limp version should start to work once buienradar_temp changes?

marble jackal
#

I have no clue what you are saying here

#

The error occurs when the template is rendered for the first time (after a reboot or template reload)

acoustic arch
#

is defined:.... when is it defined?

marble jackal
#

when it is defined

#

so when it exists

humble mortar
sonic sand
#

TheFes any idea why am I getting unknown even if in the state developer tools I can see the timestamp?

marble jackal
#

you need to change your attributes path to "$.result.value" and then use printername as the key

acoustic arch
#

when does it start to exist, because its a long time after a reboot and still no value CS

marble jackal
#

I'm out for lunch now

sonic sand
#

Bon apetit!

humble mortar
acoustic arch
#

so i assume the tbuiten value starts to exist once the buienradar ticks to another temp?

humble mortar
#
Invalid config for [template]: invalid template (TemplateSyntaxError: expected token 'end of print statement', got 'd_printer_server') for dictionary value @ data['sensor'][0]['state']. Got '{{ states.sensor.3d_printer_server.attributes["printername"]}}'. (See /config/packages/moonraker.yaml, line 113).
Invalid config for [template]: invalid template (TemplateSyntaxError: expected token 'end of print statement', got 'd_printer_1_sensor') for dictionary value @ data['binary_sensor'][0]['state']. Got '{{ states.sensor.3d_printer_1_sensor.attributes["filament_motion_sensor btt_smart_filament_sensor"]["filament_detected"] }}'. (See /config/packages/moonraker1.yaml, line 101).
Invalid config for [template]: invalid template (TemplateSyntaxError: expected token 'end of print statement', got 'd_printer_1_server') for dictionary value @ data['sensor'][0]['state']. Got '{{ states.sensor.3d_printer_1_server.attributes["printername"] }}'. (See /config/packages/moonraker1.yaml, line 113).

Can you not use a number at the start of your name seems to lop it off says d instead of 3d ?

mighty ledge
#

you have to use the state_attr function for that.

humble mortar
mighty ledge
#

at all times

#

if you mean "at the start" of your object_id, then yes

#

if you mean "at the start of HA", then no

humble mortar
#

I meant at the start of the object_id yes.

#

What does it confuse by using a number?

mighty ledge
#

then no, it will never work

#

it's a rule in all coding languages

#

as .3 for example is a number.

#

so the parser doesn't know if you're trying to access a method or if you have invalid syntax and trying to use a number

#

no languages allow numbers at the start of any method/definition/property/attribute

marble jackal
marble jackal
sonic sand
marble jackal
#

what's the result of this {{ state_attr('switch.hfjh_v2_eadb_fish_tank_2', 'event.4.1') }}

humble mortar
sonic sand
#
Result type: dict
{
  "timestamp": 1676027698,
  "value": [
    {
      "piid": 16,
      "value": "2023,2,10,13,14,0,0"
    }
  ]
}
This template listens for the following state changed events:

Entity: switch.hfjh_v2_eadb_fish_tank_2
marble jackal
#
  1. Why don't you just use state_attr() instead of states.domain.object_id.attributes['some_attribute']
  2. what does that sensor show in devtools > states
marble jackal
sonic sand
#

by the way, you see the last two digits on the value line?
6th position corresponds to status (0 = OK; >0 = NOK);
7th position corresponds to number of portions feeded.

Is there a way to monitor only them to let me know if the fed was successful and how many portions did it fed them?

#

I'm trying hold on

sonic sand
marble jackal
#

okay, so it's not a dict, it's a string. The template editor is lying here ๐Ÿ˜‰

humble mortar
mighty ledge
marble jackal
#

that's what I said ๐Ÿ˜›

mighty ledge
#

I told him to use state_attr a half hour ago

marble jackal
sonic sand
marble jackal
#

that

sonic sand
#
Result type: number
1676027698
This template listens for the following state changed events:

Entity: switch.hfjh_v2_eadb_fish_tank_2
marble jackal
#

so, that works

acoustic arch
plain sedge
#

Can anyone give me a pointer as to whether I can do this? json_attributes_path: "$.photos.photo[{{ range(1, 500) | random }}]"

sonic sand
# marble jackal so, that works

yeah, so In the first template you've sent me

service: notify.mobile_app_your_phone
data:
  message: >
    {% set feed_time = (state_attr('switch.hfjh_v2_eadb_fish_tank_2', 'event.4.1.') | default("{}", true) | from_json).get('timestamp') | timestamp_custom('%H:%M', default='unknown') %}
    Fish are fed at {{ feed_time }}

should I change only the first part after the set feed_time?

marble jackal
#

then (to avoid errors on when the entity is not working)
{{ (state_attr('switch.hfjh_v2_eadb_fish_tank_2', 'event.4.1') | default("{}", true) | from_json).get(timestamp) }}

mighty ledge
sonic sand
plain sedge
#

hmmm that's scuppered that idea then ๐Ÿ˜ฆ

humble mortar
mighty ledge
#

@plain sedge what are you trying to do? You can put the randomness in the attribute

humble mortar
#

I guess it got polluted with an extra _2

acoustic arch
#

this.attributes.tbuiten | default(10) this works @marble jackal , But now i dont know if its the default calculation or the real one yet lol

marble jackal
#

ah, you are getting my point

acoustic arch
#

i thought default= will catch any error, but thats not so

marble jackal
#

no, it will catch an error on the part you apply the filter on, but not errors before that

acoustic arch
#

got it, after the |

#

lesson is learned ๐Ÿ˜‰

marble jackal
#

( a lot of calculations and stuff) | default will still run in error if there is an error in the calculations and stuff

acoustic arch
#

thanks for your time.

marble jackal
acoustic arch
#

ah the get(), i was looking into that for syntax :)))

#

i can finally build out this practice to the full version again ๐Ÿ˜‰

#

all this because 255+ chars.... :/

#

and because state is rendered before attributes

mighty ledge
#

the laziest way to deal w/ 255+ characters is to plop the data in an attribute and be done with it

acoustic arch
#

that would be me

marble jackal
#

if you have multiple levels you can do this.get('attributes', {}).get('something, {}).get('something_else', 99)

acoustic arch
#

ill be making 3 or 4 attributes, and calling in them in the state

#

non nested

marble jackal
#

but I'm overcomplicating it here

#

so what do you want as the message text
Something like the fishes have been fed 7 times? or do you also want the timestamp somewher

#

The fishes have been fed 7 times, last time was at 23:23

sonic sand
#

wait i'm checking

#

sweet now It shows the number.
I want like every feeding session it doing it will send me a message The fishes have been fed (number of portions) at (timestamp).
If the 6th position number is not equal to 0 which mean the feeding session has failed so it will send a different message to me

marble jackal
#
service: notify.mobile_app_your_phone
data:
  message: >
    {% set timestamp = (state_attr('switch.hfjh_v2_eadb_fish_tank_2', 'event.4.1') | default("{}", true) | from_json).get('timestamp') %}
    {% set value = (state_attr('switch.hfjh_v2_eadb_fish_tank_2', 'event.4.1') | default("{}", true) | from_json).get('value', []) %}
    {% set t = timestamp | timestamp_custom('%H:%M', default='unknown') %}
    {% set n = value[6] | default('unknown') %}
    The fishes have been fed {{ n }} at {{ t }}.
sonic sand
plain magnetBOT
marble jackal
#

if you remove the dot after event.4.1 it should (I would place quotes around it as well)

#

and the template should be indented two spaces compared to message

sonic sand
#

in the attribute line you mean?

marble jackal
#
alias: Fish Fed Telegram Notification
trigger:
  - platform: state
    entity_id: switch.hfjh_v2_eadb_fish_tank_2
    attribute: "event.4.1"
action:
  - service: notify.home_assistant_group
    data:
      message: >
        {% set timestamp = (state_attr('switch.hfjh_v2_eadb_fish_tank_2', 'event.4.1') | default("{}", true) | from_json).get('timestamp') %}
        {% set value = (state_attr('switch.hfjh_v2_eadb_fish_tank_2', 'event.4.1') | default("{}", true) | from_json).get('value', {}).get('value', '').split(',') %}
        {% set t = timestamp | timestamp_custom('%H:%M', default='unknown') %}
        {% set n = value[6] | default('unknown') %}
        ๐ŸŸ The fishes have been fed {{ n }} at {{ t }}.
mode: single
sonic sand
#

Thank you man!!

#

When I paste it to the devtools I get

UndefinedError: 'list object' has no attribute 'split'
marble jackal
#

oh, so it is actually a list already

#

try the adjusted version

sonic sand
#

trying

mighty ledge
#

I feel like that can be simplified w/ a simple condition

marble jackal
#

you're probably right

sonic sand
#
       ๐ŸŸ The fishes have been fed unknown at 13:14.

Why is it showing unknown

marble jackal
#

{{ (state_attr('switch.hfjh_v2_eadb_fish_tank_2', 'event.4.1') | default("{}", true) | from_json).value[6] }} what does this show in devtools?

mighty ledge
#
alias: Fish Fed Telegram Notification
trigger:
  - platform: state
    entity_id: switch.hfjh_v2_eadb_fish_tank_2
    attribute: "event.4.1"
condition:
  condition: template
  value_template: "{{ trigger.to_state.attributes['event.4.1'] is defined and trigger.to_state.attributes['event.4.1'] is mapping }}"
action:
...
marble jackal
#

it's actually not a mapping, it's a string

sonic sand
#

UndefinedError: list object has no element 6

mighty ledge
#

that doesn't make sense

marble jackal
#

that's why the from_json is required

mighty ledge
#

why would it be a string?

marble jackal
#

dunno

humble mortar
#

How do you remove states from developer tools ( I removed the entities that dealt with them ) is there another place as well?

mighty ledge
#

that means it's invalid json

sonic sand
#

this is the line from states

event.4.1: {"timestamp":1676027698,"value":[{"piid":16,"value":"2023,2,10,13,14,0,0"}]}
mighty ledge
#

if it doesn't come through as valid json

sonic sand
#

last two digits are 0,0
which mean feeding was successful but fed them 0 portions (?)

mighty ledge
marble jackal
#
{{ state_attr('switch.hfjh_v2_eadb_fish_tank_2', 'event.4.1') is string }}
{{ state_attr('switch.hfjh_v2_eadb_fish_tank_2', 'event.4.1') is mapping }}
{{ (state_attr('switch.hfjh_v2_eadb_fish_tank_2', 'event.4.1') | from_json).value is string }}
#

can you try that

#

sorry, adjusted

mighty ledge
#

I don't see how that wouldn't be json... really odd

sonic sand
#
Result type: string
True
False
False
mighty ledge
#

well, if it's a string, then it's a string

#

what's making this attribute?

humble mortar
#
sensor.3d_printer_server
3d_printer_server
unavailable    restored: true
friendly_name: 3d_printer_server
supported_features: 0

sensor.3d_printer_server_2
printer_3d_server
OK    printername: VoronV0_001
friendly_name: printer_3d_server

This second one has the right name but the first one doesn't I don't know where it is coming from...

#

purged all the other values

marble jackal
mighty ledge
sonic sand
marble jackal
#

wait, I totally missed there is a value in the value

#
        {% set timestamp = (state_attr('switch.hfjh_v2_eadb_fish_tank_2', 'event.4.1') | default("{}", true) | from_json).get('timestamp') %}
        {% set value = (state_attr('switch.hfjh_v2_eadb_fish_tank_2', 'event.4.1') | default("{}", true) | from_json).get('value', {}).get('value', '').split(',') %}
        {% set t = timestamp | timestamp_custom('%H:%M', default='unknown') %}
        {% set n = value[6] | default('unknown') %}
        ๐ŸŸ The fishes have been fed {{ n }} at {{ t }}.
mighty ledge
#

Uh, that value is a time tuple and it's almost identical to 1676027698

#

@sonic sand is your timezone + 2?

#

if yes, no reason to dig deep into that object

#

just use the timestamp and convert it to your local time

#

| as_datetime | as_local

sonic sand
marble jackal
#

wait, I think I'm trying to get the wrong value hjere

mighty ledge
#

if you're +2, that timetuple is 58 seconds off from the timetamp

marble jackal
mighty ledge
#

so then that last value is not milliseconds

marble jackal
#

apparantly

mighty ledge
#

that's so weird

#

templates don't handle time tuples

#

so you have to use the timestamp or manually create the datetime by replacing values in now w/ the time tuple values

marble jackal
#

I was using that for the number of feed moments, but I agree it does look a lot like a time tuple

sonic sand
mighty ledge
#

well a time tuple in python has 9 values

#

that only has 7

marble jackal
mighty ledge
#

so weird

marble jackal
#

Does the latest template work @sonic sand

sonic sand
sonic sand
marble jackal
#

sorry

#

should have read that json properly

#
        {% if state_attr('switch.hfjh_v2_eadb_fish_tank_2', 'event.4.1') is not none %}
          {% set timestamp = (state_attr('switch.hfjh_v2_eadb_fish_tank_2', 'event.4.1') | from_json).timestamp %}
          {% set value = (state_attr('switch.hfjh_v2_eadb_fish_tank_2', 'event.4.1') | from_json).value[0].value.split(',') %}
        {% endif %}
        {% set t = timestamp | default() | timestamp_custom('%H:%M', default='unknown') %}
        {% set n = (value | default())[6] | default('unknown') %}
        {% if (value | default())[5] | default() == 0 %}
          ๐ŸŸ The fishes have not been fed
        {% else %}
          ๐ŸŸ The fishes have been fed {{ n }} at {{ t }}.
        {% endif %}
sonic sand
#

Works like a charm, thank you!

sonic sand
barren patrol
#

Hullo. {{ states('zone.home') }} says Result type: number in developer tools. Does that mean the states function automatically casts the string to a number?

#

The documentation suggests that it should still be a string

buoyant pine
#

States are always strings, but IIRC templates were changed a while ago to output data in the appropriate data type instead of always being a string

analog mulch
#

Is there some canonical way of initialising a trigged-based template sensor -- it's initial state is unknown and I want it to add to it. Do I just set it to some intial value through the developer tools?

marble jackal
#

states are always strings, the result of states() will always be a string

#

however, devtools>templates does conversion to native types (which can be confusing)

marble jackal
sonic sand
acoustic arch
#

like one attribute needs the value of another for its calculation? Or is it only the state

marble jackal
#

also in other attributes

#

of | default, whatever you prefer

acoustic arch
#

got it

marble jackal
#

You have to have a failsafe for when the attribute isn't rendered yet

acoustic arch
#

yup especially when dealing with a boiler ๐Ÿ˜‰

#

been toying with the setpoint of it. works, but now i want it depended on outside temp

humble mortar
mighty ledge
#

the system naturally increments entity_id's if the entity_id already exists

humble mortar
#

I can't find that one under entities

mighty ledge
#

if it doesn't , it keeps it un touched

#

how can you not? You just posted that you see it in dev tools -> states

#

that's the entity list

#

click the info icon and change the entity_id

humble mortar
#

I mean if I go to settings -> devices -> entities it's not there

#

This entity is no longer being provided by the rest integration. If the entity is no longer in use, delete it in settings.

#

Oh the settings tab there is a delete

mighty ledge
#

if the entity comes from yaml, it will not show up in any devices

#

nothing in yaml shows in the integrations area or devices area

#

the developer tools -> states page shows you everything and you can access everything from that menu

#

you literally don't need to use any other entity list

#

That page is all I use

#

so, just click the info button then delete from there

humble mortar
#

I wish I knew this before I had so many entities from esphome testing devices under entities that I couldn't remove but they remove fine from the states page!

analog mulch
mighty ledge
#

I thought that was common knowledge, I guess not

#

I made a forum post about it, maybe that will reach more people.

humble mortar
#

I've asked how to get rid of that stuff multiple times and nobody could answer it just kept telling me to restart was driving me batty.

#

Now all we need is a checkbox beside them so we can delete hundreds of entries faster ๐Ÿ˜„

mighty ledge
#

I mean if you know where the info button is, then there's no reason to llok at the post

mighty ledge
#

if the entity comes from the UI

#

you want to disable it

#

otherwise it will continually come back

#

if it comes from yaml, you want to remove it from yaml and delete it from dev tools -> states

#

if you know your entity is no longer getting created from a UI integration, you can safely delete it without it coming back

humble mortar
#

I was developing a garage device and I added hundreds of analog/digital port devices while I was testing something from esphome yaml I then remove those modules and use that esp32 device for other module tests (I2C devices) every time I removed the modules they would just pend more entities and would never go away after removing them.

mighty ledge
#

right, that's because you kept changing the name of your esphome device

#

if you kept the name the same, it would just create new entities. Unless you renamed those as well

#

the name derives the device when coming from esphome

humble mortar
#

The esphome device never changed it's name just the build up of sensors I was testing with it.

mighty ledge
#

you change the name, you change everything else

mighty ledge
#

then the device shouldn't have changed, just the entities

#

and in that case, those entities could still be found in the integration -> entities list

#

because they were in the entity registry

humble mortar
#

So I was using I2C expanders that had 16+ digital ports on them, I removed them from the esphome yaml then tried another analog 16 pin I2C device on the same esp32, I then removed the i2c analog expander, then tested a PWM module with 16+ ports on it, then tested multple other I2C devices on that esp32. It never removed the entities from HA even though those sensor no longer existed in the ESPHome yaml.

mighty ledge
#

so you would have just had to delete them, which they would still exist in the entity list

#

however you most likely would have had to restart for HA to allow you to delete them

humble mortar
#

Yes that was where I was having the issue as I assumed HA would poll the ESPHome device and say "I don't have these" and HA would purge them automagically. That is where I went wrong so they have been stuck there for a year now. As I didn't know about this state delete. As it would just say I couldn't delete them from the entities page.

marble jackal
#

If you remove the ESP device from the ESP Integration and add it again (or wait until it's discovered again), the entities will also be cleaned up

mighty ledge
#

it assumes you they just haven't talked to HA in a while

#

that's the downside of reloading via the UI

#

restarting fixes that problem, but people don't like restarting

humble mortar
#
sensor.3d_printer_printername
3d_printer_printername
Voron_V0_001    icon: mdi:printer-3d
friendly_name: 3d_printer_printername

Yay it's working now

#

That was rough. Changed the template code like 50 times until finding out that glitched entry.

mighty ledge
#

just make sure you never change the unique_id after you create it

#

if you change the unique_id, you'll end up with an _2 entity

humble mortar
#
        {% for i in printer_3d_updates.result.version_info %}
        {%- if printer_3d_updates.version_info[i].version is defined %}
        {{ i }}
        {{ printer_3d_updates.result.version_info[i].version }}
        {%- endif %}
        {% endfor %}

Tried this in the dev tools template UndefinedError: 'printer_3d_updates' is undefined

mighty ledge
#

rhymes with schmate_schmattr

humble mortar
#

I was just using the code provided...

mighty ledge
#

what code provided?

#

that code he posted uses value_json

#

you're trying to get the state's attribute version_info

mighty ledge
#

right

#

so you set your json path to json_attributes_path: "$.result"

#

then you're extracting - version_info as an attribute

#

and now you have an entity, sensor.printer_3d_updates with an attribute version_info

#

value_json no longer exists

humble mortar
#

what does state_attr mean?

mighty ledge
#

it's a method/function in templating

#

that gets attributes from a state object

inner mesa
#

That and much more template magic in the links in the topic

humble mortar
#

Is this something local to jinja or to ha or other?

mighty ledge
#

it's specific to HA

humble mortar
#

ok

#

Thank you

mighty ledge
#

it's covered in the templating documents

plain magnetBOT
#
The topic of this channel is:

Become a real Jinja2 Ninja! Don't worry my Genin, we are here to help! You can find general Jinja docs at https://jinja.palletsprojects.com/en/3.1.x/templates/, Home Assistant extensions at https://www.home-assistant.io/docs/configuration/templating/, and trigger variables at https://www.home-assistant.io/docs/automation/templating/

This channel is for support with Jinja templates. Some custom Lovelace cards support other types of templates, such as those written in JavaScript, and #frontend-archived is the right channel for that.

Please use http://pastie.org/, https://dpaste.org/, or https://paste.debian.net/ to share code or logs

mighty ledge
#

it's the extensions link

humble mortar
#

I really have no idea what to do with these lines...

{% for i in state_attr('sensor.printer_3d_updates','version_info') %}
{%- if state_attr('sensor.printer_3d_updates','version_info[i]).version is defined %}
{{ i }}
{{ state_attr('printer_3d_updates','version_info').version }}
{%- endif %}
{% endfor %}
mighty ledge
humble mortar
#
Result type: string
This template listens for the following state changed events:

Entity: sensor.printer_3d_updates
#

There's a grey box between the last two lines I assume a list should have been printed there?

mighty ledge
#

yep, but it seems version is not defined

#

what does

{{ state_attr('sensor.printer_3d_updates','version_info') }}

return?

humble mortar
#

The full json

#

Says Result type: dict

#

starts at

{
  "system": {
    "package_count": 0,
    "package_list": []
  },
  "moonraker": {
    "channel": "dev",
etc...
mighty ledge
#

ok, then

#

{{ state_attr('sensor.printer_3d_updates','version_info').moonraker }}

humble mortar
#

Dumps the moonraker version

mighty ledge
#

you basically need to learn how to access your information by knowing what the current object is

#

that post covers all the object types and how to get info out of them

humble mortar
#

So why is your for loop not outputting the multiple software names and versions under version_info?

mighty ledge
#

because I was basing it off what you said from what thefes posted

#

I didn't know what the object shape was, now I do, that loop won't work at all

#

You just want that information on your dashboard?

humble mortar
#

yes

mighty ledge
#

if yes, you'll have to use a markdown card. Otherwise you'll have issues trying to make these template sensors if the list is a variable length

humble mortar
#

Yes that is fine

#

I have the markdown card there just don't know how to get the data there.

mighty ledge
#
package | version
:-:|:-:
{% for name, value in state_attr('sensor.printer_3d_updates','version_info').items() %}
{% if value.version is defined %}
{{ name }} | {{ value.version }}
{% endif %}
{% endfor %}
#

if you want it as a table in the markdown card

open trout
humble mortar
#

Do you just paste that into the markdown card?

#
type: markdown
content: >-
package | version
:-:|:-:
{% for name, value in state_attr('sensor.printer_3d_updates','version_info').items() %}
{% if value.version is defined %}
{{ name }} | {{ value.version }}
{% endif %}
{% endfor %}
title: Update Manager
#

(worked fine in the template tester)

mighty ledge
#

if you want a table in markdown, use this

<table>
  <tr><th>Package</th>th>Version</th></tr>
{%- for name, value in state_attr('sensor.printer_3d_updates','version_info').items() %}
{%- if value.version is defined %}
  <tr><td>{{ name }}</td><td>{{ value.version }}</td></tr>
{%- endif %}
{%- endfor %}
</table>
#
type: markdown
content: >-
  <table>
  <tr><th>Package</th><th>Version</th></tr>
  {%- for name, value in state_attr('sensor.printer_3d_updates','version_info').items() %}
  {%- if value.version is defined %}
  <tr><td>{{ name }}</td><td>{{ value.version }}</td></tr>
  {%- endif %}
  {%- endfor %}
  </table>
mighty ledge
humble mortar
open trout
#

it passed a yaml linter, ill figure it out

mighty ledge
#

your spacing is correct for turn_off, but not for turn_on

open trout
#

thanks!

mighty ledge
#

you're also missing spaces for siren

#

well, everything under siren

#

I recommend comparing your yaml to yaml in the documentation. Ensure the spacing matches

open trout
#

will do

#

when i get all that correct will HA create an entity called switch.siren?

humble mortar
mighty ledge
#

yah, was just oging to say

#

typo

#

on my part

open trout
#

goal is to turn the siren on an off with a toogle in the ui

mighty ledge
#

that won't be a toggle in the UI

#

that will show up as 2 lighting bolts

open trout
#

i need to involve a boolean?

mighty ledge
#

yes

#

why do you want a toggle if the the services are the same?

#

just make it a button

open trout
#

the value should be 0 for one and 255 for the other

#

ie on/off

mighty ledge
#

well, just keep in mind that it will be out of sync

#

if you use a boolean

open trout
#

how would you do it?

mighty ledge
#

I'd make 2 buttons, one to turn it on, one to turn it off

open trout
#

i have 4 of these zwave smoke alarms, 3 of then have a binary switch exposed but after a FW update which the last one shipped with, it's now in the command class

mighty ledge
#

if there's nothing to grab the state from, then i'd just deal with it as 2 separate services

open trout
#

you can grab the state by checking the value

mighty ledge
#

command class 32 is a switch

#

are you sure you don't already have the switch somewhere?

open trout
#

yes

mighty ledge
#

are you sure it's not disabled?

open trout
#

zwave devs had to patch the device config file just to be able to see the command class

#

before that i couldnt even see command class 32

#

brilliant aye

mighty ledge
#

ah 37 is aswitch, my memory is off

#

the best you can do is poll the state of the siren

open trout
#

the previous FW has Binary CC

#

the latest one has Basic CC

mighty ledge
#

ok, so why don't you update the old one?

open trout
#

if anything id want to downgrade the new one

#

the old firmware has a binary switch

#

the new one changed to basic cc

mighty ledge
#

and the new one is using 32?

open trout
#

yes

#

dont buy heait

#

heatit*

mighty ledge
#

there isn't an option to change the reporting type?

open trout
#

that's above my paygrade

mighty ledge
#

check the configuration of it

#

usually devices have the ability to switch how they report

open trout
#

whoops

#

wrong link

mighty ledge
#

do you use zwave js ui?

open trout
#

yes

mighty ledge
#

ok, take a screenshot of the expanded configuration

plain magnetBOT
#

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

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

open trout
mighty ledge
#

๐ŸŽ‰

#

so what version are you on ๐Ÿคฃ

open trout
#

of zwavejsui?

mighty ledge
#

of that firmware

open trout
#
SDK: v6.81.6```
mighty ledge
#

the docs mention V1, V8, V11

#

Oh I understand their docs now

open trout
mighty ledge
#

those are shit docs

open trout
mighty ledge
#

yeah it now uses notifications

#

instead of an on/off

open trout
#

any idea why they would do such a thing?'

mighty ledge
#

well, that's the standard

#

so it seems they are moving in line w/ the standard

open trout
#

too bad, the switch was very easy to work with

mighty ledge
#

notifications are too

open trout
#

i cant even manage to get an on/off toggle in the HA ui for it

#

ill be the first to admit my knowledge is poor

mighty ledge
#

well you shouldn't be turning on/off the alarm

open trout
#

i use the sirens for the alarm system

mighty ledge
#

ok, then just make it a switch like you have

#

you don't need the state being on/off

#

if you're calling a switch.turn_on service, you don't need to know the state

#

of the siren

open trout
#

ok cool, thank you very much for helping out!

lean yacht
#

Hi,
I'm trying to substract timestamps to get remaining time of a washing machine.
However because I suspected DST, the calculation is 1h off...
Any idea what would be a correct template?

#

{% set remaining = states('sensor.washing_machine_washer_completion_time') | as_timestamp(default) - now() | as_timestamp(default) %}

mighty ledge
lean yacht
#

Thanks, however the calculation still has 1 hour offset...
Washing machine will end in {% if (remaining | timestamp_custom("%H") | int) > 0 -%}{{ remaining | timestamp_custom("%-H") }} hours,{{ " " }}{% endif -%}{{ remaining | timestamp_custom("%-M") }} minutes

mighty ledge
#

what's the state of states('sensor.washing_machine_washer_completion_time')?

#

@lean yacht ^

green wasp
#

I dont want applehealth listed in each one

#

though i guess all the default icons suck too. maybe i do need to micro manage them. =/

waxen belfry
#

Is there a way to take an existing time entity and subtract a period of time? i.e. I have a helper "input_datetime.alarm" and if its set for 5:30am i want to start a task at 4:30am without having two separate helpers to manage. I have tried a few things to try and "math that time" but nothing I am doing is working

inner mesa
#

you're looking for timedelta()

waxen belfry
#

thanks, time to do some more reading and futzing around ๐Ÿ˜„ - EDIT: got it. thanks man!

plain magnetBOT
desert plover
#

Hi guys, is it possible to do a simple math of 2 values inside a message without setting up a variable first? I have 2 strings with the year inside of it that have to be converted to an integer and then substracted from each other to get an age of person on its birthday.

The substraction isn't working because they are not integers right now

service: notify.mobile_app_phone
data:
  message: >-
    Birthday: {{state_attr('sensor.geburtstage', 'data')[0].summary}} Age:
    {{now().strftime('%Y')-state_attr('sensor.geburtstage',
    'data')[0].originalStartDate[:4]}}
  title: Test
woeful socket
desert plover
#

I guess I'm doing something wrong with the syntax (my usual problem)

#

perfect!

#
Birthday: {{state_attr('sensor.geburtstage', 'data')[0].summary}} Age:
{{now().strftime('%Y') | int - state_attr('sensor.geburtstage',
'data')[0].originalStartDate[:4] | int}}
#

that is working now!

woeful socket
#

I'm still stuck on this:

          - condition: template
            value_template: >
              {{ (states(lux_sensor)|int) > (states(light_threshold)|int) }}

Gives error: "error": "In 'template' condition: AttributeError: 'dict' object has no attribute 'lower'"
lux_sensor is an entity with domain.binary_sensor and _device_class.illuminance. The light_threshold is an input_number
In my template editor, I tried this: it's {{ ("ON" if ((states('sensor.hue_motion_sensor_2_illuminance')|int) > (states('input_number.terskel_lys_kjokken_vest')|int)) else "OFF")|lower }} and it worked as expected

glacial swan
mighty ledge
#

based on what I can see in all your templates, most of them are not correct. But that's making the assumption that the 2 bottom ones are correct. Your template condition is also using the translated state when it should be using the under the hood state.

woeful socket
#

How does a under the hood state look?

#

The error was found. I was referencing the light directly and not via its entityId

#

I am shopping now but will share the entire thing when I get home

mighty ledge
plain magnetBOT
desert plover
#

Is there an easy way to compare 2 dates with each other if one of them looks like
"11.2.2023" and the other one like "11.02.2023"?

#

the leading 0 for the month on the timestampe of "now()" drives me crazy

grand quarry
marble jackal
#

Use strptime on both of them to convert them into datetimes

desert plover
# marble jackal Use `strptime` on both of them to convert them into datetimes

I was able to get rid of the leading 0 by using %-m instead of %m but now I have 2 exactly same strings, but my condition is still "false" ๐Ÿ˜ฆ
is the syntax wrong for the comparison?

condition: template value_template: >- {% set heute = now().strftime('%-d.%-m.') ~ 1985 %} {% set kalender = (state_attr('sensor.geburtstage','data')[0].startDate) %} {{ ('heute') == ('kalender') }}

ok fixed it.... just writing the variables straight without quotes etc. fixed it => {{ heute == kalender }}

woeful socket
#

@mighty ledge and @glacial swan , I'm back from shopping and as promised, here is my now working Blueprint template. Would love comments and areas of improvement. I'm new to this HA templating language
https://gist.github.com/digitaldias/9cb752c2fbd344515a2cdb362739eb87

Making the code cleaner is also something I'd love input on, i.e. if I can write
{{ target_light.entity_id }} instead of ``{{ target_light['entity_id'] }} then that is a win for me, unless it has an expense that I don't need ๐Ÿ™‚

mighty ledge
#

no way that's working 100%

#

you're still using the incorrect state on your template condition when checking the target light

woeful socket
#

It is working 100%, I tested all conditions

mighty ledge
#

and yes, you can change to target_light.entity_id

#

I'm sorry, it's not

#

it's literally impossible for the state to be 'On' for a light.

woeful socket
#

no it's not, you can check if it is on or off

mighty ledge
#

my man, I've been doing this for 7 years

#

your light will have a state of 'on' or 'off'

#

not 'On'

woeful socket
#

{{ is_state('light.hue_ambiance_spot_1', 'On' ) }} works perfectly here

mighty ledge
#

go to developer tools -> states if you don't believe me

#

dude

#

it's not possible

woeful socket
#

I'm looking at it working ๐Ÿ™‚

mighty ledge
#

light domains only have 4 possible states

#

on, off, unavailable, unknown

#

notice the lack of capital letters

woeful socket
#

Oo, casing!?

mighty ledge
#

go to developer tools -> states and you'll see the state of your light is 'on'

woeful socket
#

yupyup, already fixing ๐Ÿ˜„

mighty ledge
#

so that condition is not working.

woeful socket
#

Fixed!

#

Gist updated too

#

can I always replace object['attribute'] with object.attribute or do some triggers/conditions/actions require one style over the other?

mighty ledge
#

you can always access key's in dictionaries with dict['key'] or dict.key unless the key starts with a number. In that case, it needs to be dict['key']

woeful socket
#

ok, so updated (revision 3), anything else that I could/should improve in your view?

#

Can I remove empty statements, i.e. empty data and empty conditions that define empty arrays, or do they need to be there?

sonic sand
obtuse zephyr
#

It'd help if you shared your automation, but you'll likely either need to add not_from and not_to trigger conditions for unavailable/unknown or put those in the condition to prevent it from firing in those instances

fiery sage
#

Making sure a template sensor is the way to go here and I can't do this with a helper - I want to create a battery sensor that is based off the value or two attributes of another sensor -- template is the way to go, right?

woeful socket
#

I need to set some last-minute variables on a trigger temperature change.
Is it allowed to use templates under action: ?

gaunt trench
#

i have multiple sensors like 'sensor.tag_0', 'sensor.tag_1' and so on. the amount is dynamic. every entity has an attribute 'Date'. I want to check in a template if one entity has today as a 'Date' in his attribute. How can I do that?

#

in pseudo code i am looking for sth like: {{ '11.02.2023' in (give_me_all_entities_which_startswith('sensor.tag_') | give_me_the_attributes_of_all_entities('Date')) }}

plain magnetBOT
woeful socket
#

(I fixed the targetTemp quotation mark) - still wrong, it complains about
template value should be a string for dictionary value @ data['action'][0]['data']

mint drift
#

Hello, Looking to take my thermostat valvues and put the attribute into an entity to then use the history stats sensor to show how long each thermostat has been in heating mode, trying to do the first bit to take the attribute of the sensors, but nothing is showing up, putting the below into my sensors.yaml sensors: hvac_action_sensor: friendly_name: "test Heat" value_template: "{{ state_attr('climate.wiser_test', 'hvac_action') }}"

lofty mason
#

What does 'nothing is showing up' mean? The sensor doesn't exist? It is undefined? Blank?

mint drift
#

yeah can't find anything in HA search with that nam

obtuse zephyr
#

What key is that under in your configuration? Is sensors: at the top level?

mint drift
#

yes

obtuse zephyr
#

Actually for the old style what you have needs to be in

sensor:
  - platform: template
lofty mason
#

Also confirm if you have the correct include statement in configuration.yaml.

rose scroll
woeful socket
rose scroll
#

Anyway, you don't need the brackets in the if statements.

rose scroll
woeful socket
#

ooh!

#

That solved the string error, @rose scroll , it only complains about a bad entity_id now

rose scroll
#

Pretty sure your entity_id is climate.xxx. Check your entities list.

#

Oh wait...panel_oven is a variable name not a domain. Hmm...

woeful socket
#

yeah, it's defined as an input up top as an entity.domain.climate

rose scroll
#

What exactly is the error?

mighty ledge
#

If thatโ€™s the case, then your timezone is set incorrectly in your system

woeful socket
#

Message malformed: Entity entity_id is neither a valid entity ID nor a valid UUID for dictionary value @ data['entity_id']

obtuse zephyr
#

Should just be able to use target: !input panel_oven

woeful socket
#

Trying that

#

well, it updated the error message:
Message malformed: not a valid value for dictionary value @ data['action'][0]['target']['entity_id']

when I changed to target: !input panel_oven

#

I couldn't see any device classes on the developer page

#

Should I define the input as a device instead?

mint drift
#

Still confused what to change, I have set in configuration to use sensors.yaml so not sure if there is something I need to remove ```# test

  • platform: template
    sensors:
    climate_wiser_test_hvac_action:
    friendly_name: "Wiser test HVAC Action"
    value_template: "{{ state_attr('climate.wiser_test', 'hvac_action') }}"
    entity_id: climate.wiser_test
obtuse zephyr
#

climate_wiser_test_hvac_action needs to be indented

#

Check your home-assistant.log

#

It'll say what it's failing to parse

woeful socket
#
      selector:
        target:
          entity:
            domain: climate

This DOES report with an entity_id right?

sonic sand
#

so NSX what condition should I add to prevent those messages from appearing? I can't figure it out

mighty ledge
mighty ledge
woeful socket
#

ah, that could be it, so I just take the first element.

mighty ledge
#

Also, do you have multiple template sensors? If yes, do you only have a SINGLE sensor: section?

woeful socket
#

I suspect that by NOT having set multiple: false that I am being tricked in my selectors? If I add it at the same inset as the domain: climate , the template does not even load. Also, the other two inputs I have do not have multiple: false set, and yet I can pick as many as I want from them?
I am on Home Assistant 2023.1.6 btw, if anything related to this has been fixed lately?

marble jackal
#

Otherwise this condition

- condition: template
  value_template: "{{ not 'unavailable' in [trigger.from_state.state, trigger.to_state.state] }}"
woeful socket
#

Still no joy, I get the same error over and over. I'm stumped!
http://pastie.org/p/1IngUVr0gogW0OqbNtu13r

Message malformed: Entity entity_id is neither a valid entity ID nor a valid UUID for dictionary value @ data['entity_id']
plain magnetBOT
mighty ledge
#

Thatโ€™s not an entity selector, thatโ€™s a target selector

#

That means you have to use xxx.entity_id

#

If you chose a single entity

woeful socket
#

ok, in both triggers and actions?

haughty breach
#

Is it possible to use a template to output a list of dictionaries in such a way that it can be used in a Repeat for each action? No matter what I try, I get "Error: Repeat 'for_each' must be a list of items". The following is an example of one attempt.

sequence:
  - repeat:
      for_each: >
        {{ states.sensor | selectattr('attributes.trash_holiday', 'defined')
        | selectattr('attributes.trash_holiday', 'eq', 'on') | list }}
      sequence:
        - service: persistent_notification.create
          data:
            message: "{{repeat.item}}"
mighty ledge
#

And you can only pass โ€œsimpleโ€ objects. List, dict, int, float, str, bool.

#

When Iโ€™m home later I can help you make that work

haughty breach
mighty ledge
#

Ok, yeah I can help out. Wonโ€™t be home til 6 or 7 est

#

But what you can do is use namespace to make a list of dicts using the info from the state objects

#

If you wanna try without my help

mighty ledge
# woeful socket ok, in both triggers and actions?

everywhere you want to use the data from the selector. Keep in mind that if you choose area or devices for the target selector, the code changes to get to your entity. And itโ€™s not simple code.

haughty breach
woeful socket
mighty ledge
#

Look at your trace

#

It will tell you what the variables look like

woeful socket
#

I commented out the actions, so the trace is empty

mighty ledge
#

In the variables section

#

If the automation runs. Itโ€™ll have populated variables

sonic ember
#

Probably a simple question, but I can't seem to find it in the docs... How do I test for multiple conditions in an if statement? All I could find was a nested if and that seems messy

mighty ledge
woeful socket
#

the best I get now is
Message malformed: Entity {'entity_id': 'sensor.soverom_elinor_temperature'} is neither a valid entity ID nor a valid UUID for dictionary value @ data['entity_id']

when I use

trigger:
  - platform: state
    entity_id: 
      - !input temp_sensor
    for:
      minutes: 1

I've isolated the problem to triggers I think

mighty ledge
#

You can only use inputs with specific triggers

#

It has to return an wntity_id for it to work. I..e. You canโ€™t use a target selector for triggers

woeful socket
#

Howcome this one works then?

trigger:
  - platform: state
    id: motion_triggered
    alias: 'Motion is detected'
    entity_id: !input motion_sensor

from a different blueprint I made

mighty ledge
#

Because thatโ€™s an entity selector

#

Entity selectors return entity ids

woeful socket
#

They both are, or am I not understanding this correctly?

sonic ember
mighty ledge
woeful socket
#

The difference is that one is a binary sensor (the motion sensor) and the temperature sensor is a sensor with device class temperature

mighty ledge
plain magnetBOT
woeful socket
#

ooh, I see one has a target, the other doesen't!

mighty ledge
#

Ok, one is a target selector the other is entity

#

So you have to use an entity selector, not target

sonic ember
# mighty ledge It follows normal parenthesis order of operation

Sorry it's not computing in my head (or the editor)... I'm ok if you can point me to the docs page where I can look it up myself too, just haven't been able to find it

{% if states('schedule.home') == 'off' and states('device_tracker.reinhardt_mobile' == 'not_home') %}
inner mesa
#

You put the test in the function call?

sonic ember
#

It's a service call action in an automation. Here's the full one:

service: climate.set_temperature
data:
  temperature: >
    {% if states('schedule.home') == 'off' %} {{
    states('input_number.living_room_low_temperature') | float }} {% else %} {{
    states('input_number.living_room_home_temperature') | float }} {% endif %}
target:
  entity_id: climate.livingroom_thermostat
inner mesa
#

I'm talking about this:

states('device_tracker.reinhardt_mobile' == 'not_home')
sonic ember
#

Yeah I'm trying to add that test into the if statement. THe code I shared was by accident the one with only one test

inner mesa
#

That will not work. Move the parenthesis

#

You're putting the test in the function call

sonic ember
#

is states() the function call? Guess I'm missing some terminology here

inner mesa
#

Yes

#

The first is correct, the second is wrong

sonic ember
#

๐Ÿคฆโ€โ™‚๏ธ

#

thanks

grizzled grove
#

What would be the best approach to see how long would a phone/tablet take to charge(100%), in %h:%m? I noticed that the data from the companion app updates in a somewhat erratic way: from 50%-52%-55%

grand quarry
#

You can change the update interval in the app settings

grizzled grove
#

Oh, true. Will have to check it.

#

Right now I'm having a timer start when the state of battery_state changes to charging; and stop when the battery_level goes beyond 99.

#

Will have to work from there.

plush pewter
#

Hi all, i am pulling my hair out now. I really need help with this templating.

I tried to use an event trigger of the overwolf_game_event (need to fetch data for counter strike stats)
when doing so i get this data:

INFO: {"game_info":{"scoreboard_0":{"nickname":"TRoager","steamid":76561198085455790,"team":"T","money":1000,"kills":0,"assists":0,"deaths":0,"mvps":0,"score":0,"adr":0,"ud":0,"ef":0,"ping":4,"local_player":1}}}

now how do i extract, "kills" and "mvps" into an automation ?
my problem is that "scoreboard_0" key is not always 0 it can also be 3, 4, 5 etc so i need to get around that this variable is unknown.

Anyone have a clue ?
i did try this and this works but then i need to know the scoreboard_0
json_data.game_info.scoreboard_0.mvps

inner mesa
#

just do {{ (json_data.game_info|first).mvps }}

plush pewter
#

Hmm strange, this seems to give this issue:
UndefinedError: 'str object' has no attribute 'mvps'

#

`{% set json_data = {"game_info":{"scoreboard_0":{"nickname":"TRoager","steamid":76561198085455790,"team":"T","money":1000,"kills":10,"assists":0,"deaths":0,"mvps":15,"score":0,"adr":0,"ud":0,"ef":0,"ping":4,"local_player":1}}} %}

{{ (json_data.game_info|first).mvps }}`

inner mesa
#

yeah

#
{% set json_data = {"game_info":{"scoreboard_0":{"nickname":"TRoager","steamid":76561198085455790,"team":"T","money":1000,"kills":0,"assists":0,"deaths":0,"mvps":0,"score":0,"adr":0,"ud":0,"ef":0,"ping":4,"local_player":1}}} %}
{{ (json_data['game_info'].values()|first)['mvps'] }}
#

-> 0

plush pewter
#

You are amazin !! โค๏ธ

plain magnetBOT
marble jackal
#

You don't need to add {{ d }}

#

@sonic sand

sonic sand
#

There you are! ๐Ÿคฉ

marble jackal
#

You can just change the timestamp_custom filter to include the date as well

sonic sand
#

is it on the third line?

inner mesa
#

I don't know what all the "> " are about, but you need to quote your template

marble jackal
#

{% set t = timestamp | default() | timestamp_custom('%H:%M', default='unknown') %}

#

There

sonic sand
#

tried to do it myself but I failed.
also wanted to ask you, sometimes after my internet drops I get the same notification over over (about it fed them) most likely because it changed from unkonwn to the last fed time

marble jackal
sonic sand
#

is there a way to workaround it so it won't spam me?

marble jackal
#

I already gave two possible solutions for that

sonic sand
#

Hold on I will send you screenshot

marble jackal
#

If that doesn't work, try the condition

plush pewter
sonic sand
#

just need the day and month

sonic sand
#

Okay the new timestamp is working fine, just adjusted it

 {% endif %} {% set t = timestamp | default() | timestamp_custom('%H:%M %A',
        default='unknown') %}

Thanks man

plush pewter
marble jackal
sonic sand
marble jackal
#

No, it will prevent that the message will be sent if the attribute changes to or from none. And it will be none if your switch is not available

#

The condition will basically do the same, but will check on the state of the switch itself

sonic sand
#

Okay, thanks.
so generally there is no way to prevent the issue that I showed up in my screenshot?

#

Because this condition is preventing the unknown issue, right?

marble jackal
#

Well, in practice it will prevent that

silent flicker
#

is it possible to get the current color of my lights? am i close?

{{ state_attr('light.aaron_s_room_light_3', 'color') }}
marble jackal
#

The message is sent because the attribute changed

sonic sand
#

Yeah

#

It changed from unknown most likely

marble jackal
silent flicker
#

about what color value?

sonic sand
#

Question is there a way to check the last attribute that was sent to prevent it to send it again

marble jackal
#

And I'm trying to tell you that either the condition, or the extra values on the trigger will already prevent that

sonic sand
#

Okay, I thought it will only prevent the unknown

marble jackal
silent flicker
#

gotcha thanks. i forgot about that

sonic sand
#

I will check it for a day see if it will stop to send it more than once.
Thanks for your explanation and help!

marble jackal
#

If you really want to prevent the same message to be sent again, you can write the last message to an input text, and compare that to the new message.

#

But I don't think that's needed here

silent flicker
plush pewter
sonic sand
silent flicker
sonic sand
silent flicker
#

yeah basically

#

i store the subject of an email and compare it to the new email, if its different, it will continue

sonic sand
#

cool, I will check it the condition won't prevent it I might create a helper to do so

silent flicker
#

you can also look at doing things like checking the TIME a value changed, and if it did / didnt change in the last X minutes or hours or whatever, then also do X and Y

sonic sand
#

yeah but it feeding them at the same time every 2 days

#

so time will always be equal

sonic sand
swift gull
#

How do i make a template condition to see that the state has been 'on' less then xx seconds?

obtuse zephyr
#

You could have 2 conditions, one state condition to check that it's 'on' and a not condition for the xx duration of the state, unless there's a reason you didn't mention where you need a template.

swift gull
#

But i think thats actually 1 minute because it changes from detected to not detected in 30 secs

obtuse zephyr
#

you can have multiple conditions

swift gull
#

Yeah i know, my brains wont work today ๐Ÿ˜‚

paper pumice
#

I'm setting up an energy template sensor to calculate my current energy bill cost. My bill cycle runs from the 17th of the month-17th of the next month. There is a daily charge for electric service of $0.71/Day. How can I calculate how many days its been since the 17th of the previous month so I can add this in to my template sensors math to figure out the total cost?

desert plover
#

Good Morning guys, is it possible to replace my string "John Doe (1999)" with "John Doe" inside a template? The passed in Variable can have the year in brackets at the end but that isn't always the case.

woeful socket
#

Can I specify some duration in a code section of a template?

      - condition: template
        alias: "Check if the light is above threshold"
        value_template: >
          {{ states(lux_sensor)|int >= states(light_threshold)|int }}

I would like to add to this that it needs to be true for 30 seconds

rose scroll
woeful socket
#

I came up with this:

    value_template: >
      {% set lux_state = states(lux_sensor)|int %} {% set threshold =
      states(light_threshold)|int %} {% if lux_state >= threshold %}
        {% set trigger_time = trigger.last_triggered %}
        {{ (as_timestamp(now(), default=0) - as_timestamp(trigger_time, default=0)) >= 30 }}
      {% else %}
        false
      {% endif %} 

Testing now, but still seems like it runs "immediately"

marble jackal
woeful socket
#

Is that the usual approach, or do people mostly just check the lux value before turning off the lights once a threshold has been found? I see my hue illuminance sensors tend to jump a little around

#

(What would the sensible thing to do be)

mint drift
#

It be to preserve battery also in the default hue app there isn't much automation to do with luniminance so no suprise it's not in firmware to report when changes

#

I would get a separate sensor and have that as a condition to triggering motion

woeful socket
#

Aah, so if I have detected motion at low light during sun-up, then the added changes in light level won't trigger my "shut down lights when the light level is above my threshold" ?

#

Man, I bought 5 hue sensors just because of that illuminance lol, now they're sorta not fully useful to me :/

mint drift
#

Illuminance is a part of the motion sensor I believe so it's not specially a real illumiance sensor put in there for this sort of thing

#

There is some motion sensors with built in separate illumiance like aotec 5 in one

humble mortar
inland stag
#

Does anyone know of any repos of template examples? The docs dont show full examples.
Ignore this - found a decent youtube tut.

paper pumice
rose scroll
inland stag
#

Is its possible to take a delta reading using history_stats? I want to get the KWh from a sensor for the current week. Or should I use something else?

obtuse zephyr
inland stag
#

Looks like it only uses new data. I suppose that's ok - I'll have to be patient ๐Ÿ˜ฆ

lone rain
#

Can someone please help me with this ESPHome template switch?
` - platform: template
name: "Display Page Switch"
lambda: |-
return display.is_displaying_page("page1")

return display'is_displaying_page';

turn_on_action:
  - display.page.show: page1
turn_off_action:
  - display.page.show: page2`
#

It says: /config/lora32-v2-oled.yaml:66:21: error: expected primary-expression before '.' token (that's the return line)

plain magnetBOT
obtuse zephyr
#

You'll want to check w/ their Discord

sonic ember
#

Short logic question...

{% set thermlr = 'climate.livingroom_thermostat' %}
{% if states('schedule.home') == 'off' or states('schedule.away_no_heating') == 'on' %}
{{ state_attr(thermlr, 'current_temperature')|float(0) > states('input_number.living_room_low_temperature')|float(0) }}
{% else %}
{{ state_attr(thermlr, 'current_temperature')|float(0) > states('input_number.living_room_home_temperature')|float(0) }}
{% endif %}

Would "else" trigger only if neither of the conditions in the if is true?

inner mesa
#

yes

sonic ember
#

Ok cool, then it should work. Somehow my brain was telling me that it would also trigger if only one of them is true ๐Ÿ˜„

inner mesa
#

the "or" explains it

sonic ember
#

or if both were true, which would also suck

inner mesa
#

what you described is "and"

sonic ember
#

Haha yeah, so it sounds logical, but somehow wasn't sure

limber haven
#

I'm trying to utilize an addon (Sankey) to map my power usage in my home, but I've run into a potential problem that due to how my solar PV system presents if it is drawing to/from the grid/battery, rather than give two seperate entitys it only has one that goes positive/negative depending if its charging/discharging. So my thinking is a 'simple' solution is to create two new entities based on a template from the source. setting them to what they need to be depending if the source is a positive or negative number. Does that make sense and is possible?

#

I've written some.. basic templating? which I think will do the correct logic but unsure how to turn that into entities ```{% set grid_power = states('sensor.growatt_grid_power') %}
{% if is_number(grid_power) and grid_power | int <= 0 %}
Sending {{ grid_power }}w to Grid!
{%else%}
Drawing {{grid_power}}w from Grid!
{% endif %}

{% set battery_charge = states('sensor.growatt_battery_power') %}
{% if is_number(battery_charge) and battery_charge | int <= 0 %}
Sending {{ battery_charge }}w to Battery!
{%else%}
Drawing {{battery_charge }}w from Battery!
{% endif %}```

#

... Sorta, Still very much getting my head around the basics of this stuff ๐Ÿ˜„

inner mesa
plain magnetBOT
leaden harness
#

Executed: February 12, 2023 at 6:03:00โ€ฏAM
Result:
result: false
conditions/0
Executed: February 12, 2023 at 6:03:00โ€ฏAM
Result:
result: false
conditions/0/conditions/0
Executed: February 12, 2023 at 6:03:00โ€ฏAM
Result:
result: true
conditions/0/conditions/1
Executed: February 12, 2023 at 6:03:00โ€ฏAM
Result:
result: false
entities: []

civic latch
#

Is there a way to basically do a string variable? I want to be able to set the values of a string global to Home Assistant that Node-Red and/or ESP Home can reference. Seems like this is solved already and I'm just lost on what to search for.

plain magnetBOT
civic latch
#

Welp, closer

#

I've got an input_text sensor called 'alarm_url' setup and it is updating in HA through Node-Red. Here's my ESPHome config for it; but it's never updating. on_value is never triggering even when I force a change to the input text entity:

text_sensor:
  - platform: homeassistant
    name: "Alarm Url"
    entity_id: input_text.alarm_url
    id: alarm_url
    internal: true
    on_value:
      lambda: |-
        ESP_LOGD("main", "Alarm URL: %s", x.c_str());
#

Is there a way to poll for a sensor value rather than using esphome's update function or am I doing something wrong here?

inner mesa
#

You'll get more help on their discord server

plain magnetBOT
civic latch
sacred sparrow
inner mesa
#

I don't see how you're preventing it

marble jackal
#

The state trigger will cause errors because it doesn't have event data

inner mesa
#

If you have an availability key, it can be unavailable

marble jackal
#

Looks like you added the state trigger as a kind of condition, but that's not how it works

#

Do it the other way around, check on the unwanted states and combine that with the check on the device tracker. Do that check first in your if statement

#
- trigger: 
    - platform: event
      event_type: delonghi_primadonna_event
    - platform: state
      entity_id: device_tracker.delonghi_primadonna
      to:
        - unavailable
        - unknown
  sensor:
    - name: DeLonghi Dinamica Plus
      icon: mdi:coffee-maker-outline
      state: >
        {% if trigger.platform == 'state' or states('device_tracker.delonghi_primadonna') == 'not_home' %}
        Disconnected
        {% elif %}
          Your other stuff
        {% endif %}
#

Oh, and indeed remove the availability

sacred sparrow
#

does this look right?

floral shuttle
#

now here's a challenge ๐Ÿ˜‰ having a rest sensor to dutch KNMI results in a Waarschuwing attribute that does not always contain the same string. When all is good (green) a simple text string is returned so I can use {{state_attr('sensor.knmi_waarschuwingen_nb','description')}} and have it say 'Code Groen, geen waarschuwingen'. I use that in a markdown. However, when an actual alert is on, the same template returns: Code Geel.<br>Plaatselijk dichte mist.<p><a href="/kennis-en-datacentrum/waarschuwingen/zicht">Wat kan ik verwachten en wat kan ik doen bij slecht zicht door mist?</a> (van 13/02/2023 09:00 tot 13/02/2023 11:00 uur)<br><br> which has an incomplete link in the href... so using that in the frontend does show correctly like in the screenshot, but clicking it leads to nowhere. It should add the prefix to this full address https://www.knmi.nl/kennis-en-datacentrum/waarschuwingen/zicht, so insert https://www.knmi.nl . Any thought on how I should approach that template...?

marble jackal
floral shuttle
#

thanks ! I did consider that, but am not sure if that also works when there is nothing to replace? in the case of no link when Green

marble jackal
#

if there is nothing to replace, it will do nothing

#

well, the filter will do nothing

floral shuttle
#

great, Ill add it and thank you very much!

#

Added an extra replace for the double <br><br> which messed up the layout, using ``` content: >
Actueel:
{{state_attr('sensor.knmi_waarschuwingen_nb','description')
|replace('href="','href="https://www.knmi.nl')|replace('<br><br>','')}}
KNMI waarschuwingen Noord-Brabant

marble jackal
sonic sand
#

also got this warning before the error above^

Logger: homeassistant.components.sensor.helpers
Source: components/sensor/helpers.py:22
Integration: Sensor (documentation, issues)
First occurred: 10:00:13 AM (2 occurrences)
Last logged: 10:02:04 AM

sensor.feed_record_timestamp rendered invalid timestamp:
marble jackal
#

add an availability_template which checks if the switch (or attribute) is available

sonic sand
#

well through the devtools I get that:

ValueError: Template error: timestamp_local got invalid input '2023-02-11 18:00:17+00:00' when rendering template '- platform: template
  sensors:
    feed_record_timestamp:
      value_template: >-
        {%- if state_attr('switch.hfjh_v2_eadb_fish_tank_2','event.4.1') -%}
          {% set feed_record = state_attr('switch.hfjh_v2_eadb_fish_tank_2','event.4.1')|from_json %}
          {{ as_datetime(feed_record.timestamp)|timestamp_local }}
        {%- endif -%}
      friendly_name: "Last Fish Feed"
      icon_template: "{{ 'mdi:fish' }}"
      device_class: timestamp' but no default was specified
#

by the way, the condition on the fish tank automation did prevented the duplicate messages so far

marble jackal
#
- platform: template
  sensors:
    feed_record_timestamp:
      value_template: >-
        {% set feed_record = state_attr('switch.hfjh_v2_eadb_fish_tank_2', 'event.4.1') | from_json %}
        {{ as_local(as_datetime(feed_record.timestamp)) }}
      friendly_name: "Last Fish Feed"
      icon_template: "{{ 'mdi:fish' }}"
      device_class: timestamp
      availabitliy_template: "{{ state_attr('switch.hfjh_v2_eadb_fish_tank_2', 'event.4.1') is not none }}"

Does this work?

#

the sensor expects a datetime object or a isoformat datetime string

plain magnetBOT
heady trellis
#

Most likely a dumb-ass question , but where can I find what the difference (and how to use) between '{%' and '{%-' ?
Thanks

sonic sand
heady trellis
mighty ledge
#

I can't find a tutorial that actually covers the delimiters

#

Jinja uses various delimiters in the template strings.

{% %} - statements
{{ }} - expressions to print to the template output
{# #} - comments which are not included in the template output

Adding a - after a starting delimiter will remove previous whitespace. Adding a - before an ending delimiter will remove trailing whitespace.
e.g.
{%- removes leading whitespace before a statement
-}} removes trailing whitespace after an expression that prints to the template output

floral shuttle
mighty ledge
#

@heady trellis check the most recent ๐Ÿ“Œ for explanation on the bracket meanings

latent geyser
#

Hi All, I have a pool pump that I was able to integrate into HA using a HASS plugin. One challenge with using it to manage pump speed is that the pump is turned on an off with a switch entity, but the speed is adjusted with a custom service. I realized I could simplify things with a fan template, and I got it working, but with a challenge in that when it's exposed to HomeKit it shows up in HomeKit as a group of five switches, three of which seem to be turning on and off the presets. I'm not sure what is happening and I'm hoping someone has encountered this before. Template code in a threaded reply.

mighty ledge
#

if it's not showing up as a fan, you aren't exposing it as a fan

latent geyser
#

It's showing up as a fan, the problem is it's a fan with four extra switches.

#

When I set a speed the first switch reflects that, it seems to be the presets that pose a problem.