#templates-archived

1 messages · Page 38 of 1

silent vector
#

At least I used reject correctly this time

marble jackal
#

And the value for for: 😉

frank gale
#

I return a datetime object with a macro, in template editor is as string recognised, wanted to filter it | as_datetime it returns None
Edit: I'm in BETA

mighty ledge
#

you have to ensure your macro doesn't output leading spaces or trailing spaces

frank gale
#

yeah you right! i already had that problem and forgot abou it, thnx

fast mason
#

Does anyone happen to be importing values through MQTT and telegraf for proxmox stats?

#

telegraf does the stupid thing of posting all values for a given stat under the same topic (e.g. load1 load5 load15)

#

I've ended up with something like

value_template: >-
  {% if value_json.fields.load1 == null %}{{ states('sensor.proxmox_load_1m')
  }}{% else %}{{ value_json.fields.load1 }}{% endif %}
#

but HA no longer likes it

#

is there a better way to not have unavailable states seeping through?

#

I guess an availability template would help?

fading hound
#

I would love to have some help on the following.

` ##Product naam zoeken

The states.sensor.barcode_reader.state seems not to be filed. The response is based on the default value 1.

marble jackal
marble jackal
#

power_cur will be power, measured in Watt. Not energy (measured in kWh)

#

And I guess you need '{{ value_json.Power_cur }}'

plain magnetBOT
#

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

flint yarrow
#

doh, that makes it harder to read 😅

plain magnetBOT
#

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

#

@pseudo glade 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.

flint yarrow
flint yarrow
#

So I've gotten a little bit further. My REST config is as such:
https://gist.github.com/Morgon/1d196003db9fd207d1cb243219a2672a

I see that I can't directly reference nested attributes, so only "Name" is working, but I'm uncertain how to go about adding the rest as attributes. I think I would prefer not to make unique sensors for every field if possible (and if it's not, please do let me know).

Strangely, the results of value_template are "Unknown" instead of the expected price value. I've been using jq to validate the structure, so I don't think it's a pathing issue. I also tried square brackets instead of dot notation. Would appreciate any thoughts!

orchid oxide
balmy wedge
#

In the demo template, it says The sun rose {{ relative_time(states.sun.sun.last_changed) }} ago. but that looks at the sunrise in UTC, not in local time. It's saying that the sun rose 2 hours ago, but it rose 8 hours ago. How can I fix that? Edit: never mind, that's simply when I restarted HA

orchid oxide
#

if it works in there and you have the same content as the rest sensor, you should jsut be able to move it over to the value_template

fresh egret
#

is there anyone that can help me? i am scraping data from a website but i want the value to change from comma to dot and divide by 100. i can't get it to work. anyone?
what i have now: value_template: '{{ (value | replace(",",".")) }}'

orchid oxide
fresh egret
#

nvm, just got it lol

#

had to float it first and then divide

#

value_template: '{{ ((value | replace(",",".") | float) / 100) }}'

orchid oxide
balmy wedge
#

Yup

orchid oxide
#

oh i didnt see the edit lmao

flint yarrow
orchid oxide
#

value json isnt affected by the json_attributes_path

#

its an attributes path

#

and the value template is for state

balmy wedge
#

Ok, I still can't figure out how to juggle as_timestamp, timestamp_local and timestamp_custom to get the sunrise or sunset time in HH:MM. I'm lost.

#

The sun will set at {{ as_timestamp(state_attr("sun.sun", "next_setting")) | timestamp_local }} gets me the local time with microseconds - I doubt my planet is that round that it's true, but hey.

#

But then I can't pass that to timestamp_custom

flint yarrow
balmy wedge
#

If I run as_timestamp on the timestamp_local, it gets turned into UTC again

eternal island
#

Hi! Short question, can someone tell me why doesn't work this code in a template chip with mushroom?
{{ states.group.all_lights | selectattr('state','eq','on') | list | count }}
Thanks

orchid oxide
balmy wedge
#

Yeah

#

Ahh I need to tell timestamp_custom to use the local zone

orchid oxide
balmy wedge
#

Thank you again @orchid oxide

flint yarrow
orchid oxide
#

i mean it looks like you could, achieve this with 3 rest sensors as you have 3 different json paths. then theres always the option to just take the input and run it through a template sensor

flint yarrow
#

Yeah, I don't want to make multiple calls (the endpoint has rate limiting and couldn't handle it anyway), so the second option seemed like what I should do, but again I haven't seen any good examples of this that I could directly apply to my data.

My end goal is to have an entity card like this that'll show the top 5 name, address, and prices https://i.imgur.com/GhTtDPw.png

orchid oxide
#

personaly i would make the rest sensor target the results list and have that be a single attribute, then just deconstruct it into the attributes you actually want using your template sensor

flint yarrow
#

I know some of those words... 😅 What do you mean by "target" the results list? Are you referring to the json_attributes_path?

I was about to go down this road but I don't think this is what you mean

- resource:
  ...
  sensor:
    - name: Gas Station 1 Address
      unique_id: gasstation_0_address
      value_template: "{{ value_json.data.locationBySearchTerm.stations.results[0].address.line1 }} {{ value_json.data.locationBySearchTerm.stations.results[0].address.locality }}, {{ value_json.data.locationBySearchTerm.stations.results[0].address.region }}"
#

(which is why I was hoping that json_attribute_path was the base for the value template.)

orchid oxide
#

i mean that works too lol

#

it would be better to do it as an attribute rather than a state, since attributes can be lists and states cant

flint yarrow
#

Right, but I cannot get nested attributes..? Would the "template sensor" be part of the rest resource, or I would need to create an actual sensor within the templates yaml?

#

Interesting. I did get the address to be an entity, but price still isn't working. (Doh, typo)

orchid oxide
#

i would do this

      json_attributes_path: '$.data.locationBySearchTerm.stations.results[0]'
      json_attributes:
        - "name"
        - "address"
        - "brands"
...```
and then in your template sensor

...
attributes
line1: "{{state_attr('rest_sensor', 'address').line1}}"```
etc

#

i think i did that right

#

cause the attribute address should return the json as the value

#

iirc

flint yarrow
orchid oxide
#

oh sorry, typo

#

just brands should work

flint yarrow
#

Can I make a "template sensor" as part of the rest, or it has to be a top level sensor?

dapper aurora
#

I'm having trouble with a statistics sensor - the yaml validates but it just doesnt show up:

this is in the file config/sensor/max_elevation.yaml

my configuration.yaml has sensor: !include_dir_list config/sensor/

name: max_sun_elevation_yesterday
entity_id: sensor.sun_elevation
state_characteristic: value_max
max_age:
  hours: 24
orchid oxide
flint yarrow
#

That's what I'm already using, I just couldn't figure out how to format my data from within the larger json

orchid oxide
#

oh, you can make 3 sensors with this with 1 api call

flint yarrow
#

Okay, so I do have to make unique sensors? Name, address, price? Or you're referring to each of the overarching station data (I was going to do 5)

orchid oxide
#

yeah you can specify a different json_attributes_path for each sensor

#

since theres 3 paths for you that would be 3 sensors

#

since the 3 from address are all under the same path, they can all be attributes on one sensor

flint yarrow
#

Gotcha. So a total of 15 unique sensors if I want to show the top 5. Not ideal (was hoping for self-contained attributes for each top entity), but something is better than nothing. Thanks for your help, I will play around with that idea more.

orchid oxide
#

theres that or theres breaking it down in a template sensor so instead of 15 rest sensors you could do 1 (or 5 depending on how you want to do it) template sensors

flint yarrow
#

Can you help me wrap my head around the template sensor? I had asked before if I could make a template sensor from within the rest module or if I would need to make a top level one. I like the idea of it, especially if I can define things a single time and reference the template

orchid oxide
#

you need to make a seperate template sensor, not part of the rest sensor

#

since you cant use templates on rest attributes

flint yarrow
#

Ah, I see what you meant by that now

flint yarrow
#

Unrelated, is there a way to get an icon to be a remote image instead of mdi (or local img)? Web searches are a PITA.

north locust
#

could anyone help debug my template sensor

#

its an dual android alarm clock time sensor ...

#

when my wife sets her alarm her time etc is noticed in the sensor but not her name ??

#
text_whos_alarm: null
#

?

#

or am i overcomplicating things for a wake-up-routine ... both android alarms

balmy wedge
#

@orchid oxide thank you again for your help earlier. My huge getting-out-of-bed tts routine now works perfectly.

mighty ledge
#

also, I think you're over complicating your alarms

#

and I'm the king of over complicating things

#

you can use time triggers to trigger at timestamp sensor times.

#

personally, i'd make a template sensor that simply has the next name and the next time to send the notification paired with an automation

north locust
#

Yeah i noticed them alarm sensor now have a local time nicer format

mighty ledge
#
text_whos_alarm: >
  {% set alarms = { 'Martijn': states('sensor.pixel_7_next_alarm'), 'Mirella': states('sensor.mirella_next_alarm') } %}
  {% if alarms.Martijn == alarms.Mirella %}
    Geen alarm
  {% else %}
    {{ alarms.items() | min(attribute='1') | first | default('Fout') }}
  {% endif %}
#

if you just want to fix your template @north locust ^

#

FYI you can use the same code just about everywhere

#

instead of doing math in multiple places

#

figure out what the lowest is, then do the math

#

no reason to do the math, then figure out what's the lowest

north locust
#

Time is finnicky

mighty ledge
#

if you have trouble, I made a whole library that calcs things for you

#

although it wont help you here

#

it will help you get relative time though

north locust
#

Ah Thanks 🙏

#

Bookmarked

orchid oxide
#

easter()
Easter’s date.

{{ easter() }}

this one feels so random lmao

eternal island
#

Hi! Can someone tell me how can rewrite that code so that it counts me how many lights are on in that group of lights.
{{ states(group.all_lights) | selectattr('state','eq','on') | list | count }}

obtuse zephyr
#

{{ expand('group.all_lights') | selectattr('state','eq','on') | list | count }}

obtuse zephyr
#

No prob

eternal island
#

Are any docs about this in the official website of Hassio? I tried to search the problem but no results...

obtuse zephyr
eternal island
#

Thanks

orchid oxide
obtuse zephyr
#

expand enumerates all of the entities contained within a group

flint yarrow
orchid oxide
#

Yes to the first one and not sure I understand the 2nd one

flint yarrow
# orchid oxide Yes to the first one and not sure I understand the 2nd one

Well I was hoping to make single generic sensors/templates/something (whatever needs to be done) so that I can feed it any number of entities that I've set up this way (in my case, 5 - sensor.gas_station_x, 1-5) without explicitly creating 15 different sensors. It sounded like you alluded that it could be done, but wasn't clear on how to approach it.

orchid oxide
#

you can make one template sensor with all 15 attributes

#

or you could probably make a macro if you wanted (dont think macros can be used in the front end)

flint yarrow
#

Oh. So to be clear, there's no way to abstract it out?

orchid oxide
#

yes, with templates

#

im not sure i understand

flint yarrow
#

I'm trying to avoid making 15 explicit attributes/templates, and simply define it once, e.g.

{{my_input.address.line1}} {{my_input.address.locality}}, {{my_input.address.region}}

Where my_input is assumed, in the template, to be whatever I pass into it. Whether it be 1 "Gas Station" entities, 5, 10, or 50. It's defined a single time and re-used.

orchid oxide
#

macros can accomplish that

compact rune
orchid oxide
#

youd still have to make 3 macros for your 15 template attribtues

flint yarrow
#

Well next month I could decide I want to show 10 stations, or 3. I don't want to have to go into three different files to update them, you know?

orchid oxide
#

true, valid

#

i suppose if thats the case, yeah

orchid oxide
flint yarrow
#

WOO. Okay, that is actually working on the UI

type: entities
entities:
  - entity: sensor.gas_station_1
    type: custom:secondaryinfo-entity-row
    secondary_info: > 
     {% from 'gas_station.jinja' import gas_get_address %}
     {{ gas_get_address('sensor.gas_station_1') }}
orchid oxide
#

wow ok i actually didnt even think about skipping the temp0late sensor lmao

flint yarrow
#

Still trying to figure out if I can dynamically update the name, though..

orchid oxide
#

thats only gonna work in some cards though, not all of them accept templates

flint yarrow
#

https://i.imgur.com/W7BiKiI.png Instead of "Gas Station 1", I'd like it to show the name. I couldn't find a way to dynamically update the sensor's name itself (though that'd be ideal), so just printing it on the UI would be fine

orchid oxide
#

i mean if entity row lets you use a template as a name its just state_attr('sensor', 'name') if im remembering it right

flint yarrow
#

No, it doesn't seem to.

#
type: entities
entities:
  - entity: sensor.gas_station_1
    type: custom:secondaryinfo-entity-row
    name: {{ state_attr('sensor.gas_station_1', 'name') }}

Configuration errors detected:
missed comma between flow collection entries (5:55)

orchid oxide
#

need quotes around the {{}}

flint yarrow
#

Tried that, too - that just prints the literal jinja string

orchid oxide
#

well then you can either make a new entity for the name and use that (if the card supports it) or you can use template config card

flint yarrow
#

So outside of the UI, there's no way to dynamically reference the name based on an attribute? I feel like there's gotta be some way of doing it, because it seems like a somewhat common use case.

orchid oxide
#

get the entity name by searching for what, the attribute value?

flint yarrow
#

I guess, or some other way of automating it (which I suppose is another angle, automations)

orchid oxide
#

well i thought the card didnt let you use a template for the name

flint yarrow
#

Right, but if the actual name of the entity could be dynamic, then it wouldn't matter what the template supported because it the idea would be HA returning the custom value as the name.

orchid oxide
#

yeah i think the only entity that could support a dynamic name would be mqtt entities

#

so you could make mqtt entities and publish with a new friendly name, and all the work that goes into that or you can wrap your card in config template card

#

or you can use a different card that supports templates in the name

flint yarrow
#

Hm. Apparently there's a friendly_name attribute

orchid oxide
#

afaik you cant update the friendly name outside of mqtt entities

#

best pick one of the options above

flint yarrow
orchid oxide
#

the entity_id wont change just cause you change the name

flint yarrow
#

Right, but the entity_id was initially populated by the name rather than the unique_id, I called it "Gas Station 1" and the device became sensor.gas_station_1

#

Even if existing sensors don't rename their ID, I'm concerned about new ones

orchid oxide
#

i mean you cant create a sensor out of thin air (except for mqtt lol), unsure if sensors try to use unique_id for the entity name if given, but if not you can just change it in the ui

flint yarrow
#

Okay, template-entity-row to the rescue. Ended up being much much harder than I imagined, but finally have (mostly) what I want.
https://i.imgur.com/e58e0AK.png
(Sweet, it also has an image, so I can show that, too)

#

Greatly appreciate you hanging with me to work through this, @orchid oxide

orchid oxide
#

yw

flint yarrow
#

(lol, all that and there's a gasbuddy bug - even if you choose to get prices for "Credit Only", it'll sort by the cash price, thus making the list out of order as shown in the last image)

orchid oxide
#

sort it yourself, in...a template sensor lmao

#

or config template card again

#

actually if your card takes templates for the name and entity i guess you could sort it there too

mighty ledge
orchid oxide
#

That's actually crazy, I didn't realize how insanely complex the date for Easter was lmao

warped shore
#

Useful little template to set the coulor of an icon based on a temperature if anyone want's it!

{% set colourhex = ['#0000FF','#0000F9','#0000F3','#0000ED','#0000E7','#0000E1','#0000DB','#0000D5','#0000CF','#0000C9','#0000C3','#0000BD','#0000B7','#0000B1','#0000AB','#00FFFFFFFFCCA5','#00FFFFFFFFF69F','#002099','#004A93','#00748D','#009E87','#00C800','#C89600','#CA6400','#CD3200','#CF0000','#D20000','#D40000','#D70000','#D90000','#DC0000','#DE0000','#E10000','#E30000','#E60000','#E80000','#EB0000','#ED0000','#F00000','#F20000','#F50000'] %} {{colourhex[states('sensor.average_house_temperature')|round(0)]}}

Goes from Blue for temperatures around 15, Green at 21 and then onto the reds

obtuse zephyr
#

Is there any way to include a macro for the entirety of a script? Was looking to use one for setting up some variables, but right now it's looking like it needs to be included on each variable definition.

grizzled grove
#
      - name: "Shirts - h:m:s"
        unique_id: shirts_hms
        state: >
          {{ (states('sensor.shirts') |float(0)) | round(0) | int | timestamp_custom('%H:%M:%S' , false) }}
        icon: mdi:tshirt-crew

      - name: "Shirts - when"
        unique_id: shirts_when
        state: >
          {{ (states('sensor.shirts') | float(0) + now().timestamp() | int) | timestamp_custom('%d | %H:%M:%S' , true) }}
        icon: mdi:tshirt-crew     
#

In development tools, second sensor: "30 | 16:23:29"

#

Gives the right value.

#

In configuration.yaml, and a entities card: the second sensor stays at: "30 | 01:37:29"

#

sensor.shirts=2,249 sec

marble jackal
#

Is that 2249?

grizzled grove
#

Yes.

#

Can't really pinpoint the moment the values start doing that. It was working fine before...

marble jackal
#

The template of the second sensor is incorrect, you are adding a floating point number and a string together

#

Oh no, I missed the brackets

#

What is your goal there, adding two timestamps together doesn't really make sense to me

grizzled grove
#

One says how long in: hours:minutes:seconds it will take. The other says "when" in: day | hours:minutes:seconds

marble jackal
#

{{ (now() + timedelta(seconds=states('sensor.shirts') | float(0))).strftime('%d | %H:%M:%S') }} should do the same

grizzled grove
#

Yep, but weirdly enough it does the some discrepancy. In development tools: "state: 30 | 16:39:31", if I add to confiigution.yaml, restart templates, in the entities card it stays: "30 | 01:37:29"

marble jackal
#

What does developer tools > states say

grizzled grove
#

30 | 16:41:29

#

Ohhh, I think I pinpoint the problem. But that's strange...

#

I added a trigger: 1h, time_pattern, to a template that was part of the equation; that would give the seconds.

#
  - trigger:
      - platform: time_pattern
        hours: 1
#

If I take that off, the values give the correct state in the cards....

#

Unfortunately it keeps changing all the time, instead of the value change from 1h-1h.

ember saffron
#

Where is the difference between template sensor and number?

#

When the temple number value changes the calculation is performed? Correct?

inner mesa
#

They both reevaluate their state when an entity in the template changes value. You can't directly set the value of a template sensor, while you can define a sequence to update a template number

marble jackal
#

To prevent it from updating every minute (which it does because you used now() in the template), you can change it to a trigger based template sensor which triggers on a state change of sensor.shirt

orchid oxide
#

semi template-relate, template sensor related. ive got a template sensor with device_class: running, the last_run attribute seems to change to when my sensor last went from any other state, to off. this means when I restart and the state is unknown for about 20 seconds, then switches to off. It changes the last_run. Is it possible to alter this behavior so that it only changes last_run when it goes from on to off?

mighty ledge
orchid oxide
#

ah ok

old python
#

2 way esphome sync

orchid oxide
#

if I want to reference a trigger id in a template, its trigger.id yes?

#

ie, the following is correct?

#
  - trigger:
    - platform: event
      event_type: zha_event
      event_data:
        device_id: 405aa8670b602b8480633896e93eac3a
        command: vibration_strength
      id: dirty
    - platform: state
      entity_id: binary_sensor.dishwasher
      from: 'on'
      to: 'off'
      id: clean
  - sensor:
      - name: Dishwasher Cleanliness
        state: "{{'Clean' if trigger.id == 'clean' else 'Dirty' if trigger.id == dirty}}"
steep plume
#

Hi, I was wondering what's the best way to set an alternative name for an entity. I have a Zigbee device that I want to keep its name, e.g. "Motion sensor bathroom". But in the scripts I'd like it to be "Bathroom" only for a concise status message. Is the only way to achieve this to create a map by its id/real name with the value being a short name? or is there a way to set some alias in the UI perhaps?

digital harness
#

Hello. i have a problem with this template:

plain magnetBOT
#

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

digital harness
#

its shown as not available in home assistant

#

test template works.

#

can anybody help?

obtuse zephyr
marble jackal
marble jackal
#

Probably something like "{{ states('sensor.shellyuni_e868e7f472ec_adc') | is_number }}"

#

You should also use states('sensor.foo') instead of states.sensor.foo.state

orchid oxide
compact robin
#

Hello masters, another one I need help with.

I'm creating a fake "heater" that replicates what my remote dummy controller is doing (lol).

What I intent?
A custom sensor that'll show a temperature. How? Well, considering the list below, with booleans and sensors, I want the new sensor to represent said temperature. Let's call it sensor.heater to work as an example.
Practical example:
if - input_boolean.heater_friday_1 is ON
it would read the value of sensor.heater_friday_1 and show it on the new sensor. If input_boolean.heater_friday_1 goes off but input_boolean.heater_friday_2 goes ON instead, it'll then update to what's on the sensor.heater_friday_2 instead.

#

How do I do this? I figured I could create an automation with "on" triggers (and I already have one created that all the other booleans go off, if one's on).
I just realistically want to know how I make one sensor show what's on other, BASED on a ON state of another boolean.

#

I figured I could make a custom-template-card with all this on the UI, but I'd think it would be so much nicer if I managed to just create a custom sensor with all of this.

compact robin
#

I saw and used it. It somehow manages to work way differently than my controller and the way I intend will work the exact same way.

#

Plus learning how to make sensors replicate each other would be a nice thing to learn. Appreciate the suggestion tho

mighty ledge
mighty ledge
mighty ledge
orchid oxide
#

it's honestly so obvious i deserve to be told twice lmao

mighty ledge
#

You could aslo just add capitals to your trigger id to avoid even needing title

mighty ledge
#
{% if is_state('input_boolean.heater_friday_1', 'on') %}
  {{ states('sensor.header_friday_1') }}
{% elif ... 2
  {{ ... 2
{% endif %}
#

if you want something that just works assuming that your sensors and heaters are all named the same...

compact robin
#

Something like this?

  - sensor:
      - name: "BOILER: Temperature"
        unique_id: boiler
        unit_of_measurement: 'ºC'
        state: >
          {% if is_state('input_boolean.heater_friday_1', 'on') %}
          {{ states('sensor.header_friday_1') }}
          {% elif is_state('input_boolean.heater_friday_2', 'on') %}
          {{ states('sensor.header_friday_2') }}
          {% endif %}
mighty ledge
#
{% set day = now().strftime("%A") | lower %}
{% for i in range(5) if is_state('input_boolean.heater_' ~ day ~ '_' ~ (i + 1), 'on') %}
  {{ states('sensor.heater_' ~ day ~ '_' ~ (i + 1)) }}
  {% break %}
{% endfor %}
#

that would work for all days w/ all input booleans

compact robin
#

Yeah, they're all named from sunday to saturday, 1 to 4, same format

#

@mighty ledgeShouldn't be too far from what we wanted to to do. It kinda works but it's giving me a 0ºC value. Ignoring with booleans on.

#

This is what I came up with:

      - name: "BOILER: Temperature"
        unique_id: boiler
        unit_of_measurement: "°C"
        state: >
          {% set day = now().strftime("%A") | lower %}
          {% for i in range(5) if is_state('input_boolean.heater_' ~ day ~ '_' ~ (i + 1), 'on') %}
            {{ states('sensor.heater_' ~ day ~ '_' ~ (i + 1)) }}
            {% break %}
          {% endfor %}```
mighty ledge
#

if it's giving you a number, its working

compact robin
#

Okay, news for you, I just tested on the programmer tools thing

#

Both give me a value. So both work. BUT they don't work together?

mighty ledge
#

I don't know what you mean by that statement

#

you wouldn't combine anything

compact robin
#

As in:

{% for i in range(5) %}
{{ states('sensor.heater_' ~ day ~ '_' ~ (i + 1)) }}
{% break %}
{% endfor %}``` gives me a 20 value (ºC) and gives the proper sensor name we intended.
#

But I had to remove the {% for i in range(5) if is_state('input_boolean.heater_' ~ day ~ '_' ~ (i + 1), 'on') %}

#

The complete template you gave me, doesn't give neither the sensor OR the boolean, gives me this:
Result type: string
This template updates at the start of each minute.

This template listens for the following state changed events:

Entity: input_boolean.heater_monday_1
Entity: input_boolean.heater_monday_2
Entity: input_boolean.heater_monday_3
Entity: input_boolean.heater_monday_4
Entity: input_boolean.heater_monday_5

#

but gives no ºC value. Something is breaking. And probably that's why it's giving 0ºC on the final sensor. We're almost there 😄

mighty ledge
#

your booleans need to be on

#

so...

compact robin
#

I tried with multiple and all gave 0 as value too, let me retry but I'm p sure there's always at least one on.

#

input_boolean.heater_tuesday_3 is ON

mighty ledge
#

so it'll output the number for sensor 3

compact robin
#

I am so stupid, sec

#

Yeah, it totally works. I'm dummy. lol

mighty ledge
#

if you get a number out, it's working 😉

compact robin
#

I was testing with a TUESDAY boolean on, on a MONDAY hahahahaha

mighty ledge
#

if you get no number out, it's also working but you don't ahve any booleans on

compact robin
#

It works. As soon as I turned on a "monday" boolean it worked and updated the sensor we created.

#

Petro, I can't thank you enough. This will be so useful even for other stuff. Thank you. I understand the process behind it 😄

#

Have a good day!

steep plume
worn moth
#

I'm trying to set up custom:vacuum-card and add some stats, but my value templates aren't working. I made this using the template section in Developer Tools, but it doesn't seem like it works in the card

{{ (float(states('sensor.roborock_s6_filter_left')) / int(3600)) | round(0)  }}
#

That shows the correct value of 130, but the vacuum card still shows 467756, which is the value before dividing

#

And this is the yml for the vacuum card

type: 'custom:vacuum-card'
entity: vacuum.roborock_s6
actions:
  start:
    service: vacuum.start
    service_data:
      enetity_id: vacuum.roborock_s6
stats:
  default:
    - entity_id: sensor.roborock_s6_filter_left
      value_template: {{ (float(states('sensor.roborock_s6_filter_left')) / float(3600)) | round(0)  }}
orchid oxide
worn moth
#

Yeah seems like that's gonna be the way to go

#

This card is so nice but there's so many unresolved issues looking through the Github page

heavy crown
#

Hi, I was triggered by a question on the forum... is it possible to combine sensors to one line? Example

#

sensorA, value 1 and attr C and sensor B, value 2 and attr. C

#

can I combine this to one line grouped by attr. C, i.e. : attr.C , value 1, value 2

#

I hope I am not to confusing 🙄

orchid oxide
#

im getting getting the following error for the following template:

#

2023-05-02 02:33:39.300 ERROR (MainThread) [homeassistant.helpers.template_entity] TemplateError('UndefinedError: 'trigger' is undefined') while processing template 'Template<template=({{'Dirty' if trigger.id == 'dirty' and states('sensor.dishwasher_door') == 'on' else 'Clean' if trigger.id == 'clean'}}) renders=4>' for attribute '_attr_native_value' in entity 'sensor.dishwasher_cleanliness'

https://dpaste.org/oyksd

#

is trigger id not supported in template sensors? cause changing this to an automation and swapping out the state for a persistent notification it works fine

orchid oxide
#

just kidding my syntax is wrong lmao

#

silly little dash

marble jackal
floral shuttle
#

have this auto-entities template filter working just fine: {% set ns = namespace(sensors=[]) %} {% for s in states.sensor |selectattr('entity_id','search','poe_port') if s.state|float(0) != 0%} {% set ns.sensors = ns.sensors + [ { "entity": s.entity_id, "name": (state_attr(s.entity_id,'friendly_name').split('PoE')[1]|trim), } ] %} {% endfor %} {{ns.sensors}}

#

but when I use it in dev template, it errors with UndefinedError: list object has no element 1

#

what am I missing here?

#

especially odd, since this {% set ns = namespace(switches=[]) %} {% for s in states.switch |selectattr('entity_id','search','poe_port') %} {% set ns.switches = ns.switches + [ { "entity": s.entity_id, "name": (state_attr(s.entity_id,'friendly_name').split('PoE')[1]|trim), "secondary_info": 'last-changed' } ] %} {% endfor %} {{ns.switches}} works fine in both dev template and auto-entities

ember saffron
#

is it possible to do math in a template sensor and round it on the same?

marble jackal
#

just wrap the entire calculation in paranthesis and add a round() filter

floral shuttle
#

hmm, rejecting a specific string of another sensor make it work: {% set ns = namespace(sensors=[]) %} {% for s in states.sensor |rejectattr('entity_id','search','poe_ports') |selectattr('entity_id','search','poe_port') if s.state|float(0) != 0%} {% set ns.sensors = ns.sensors + [ { "entity": s.entity_id, "name": (state_attr(s.entity_id,'friendly_name').split('PoE')[1]|trim), } ] %} {% endfor %} {{ns.sensors}}

marble jackal
floral shuttle
#

really odd..

marble jackal
#

should be one of the sensors with poe_ports in the entity_id then

floral shuttle
#

yes thats is correct

#

its because this "name": (state_attr(s.entity_id,'friendly_name').split('PoE')[1]|trim) doesn work in that case`

marble jackal
#

okay, well that sensor will have only one item after splitting the friendly name

#

so indeed it will fail on that line

floral shuttle
#

so auto-entities is smarter than HA 😉

#

it simply doesnt list that

marble jackal
#

you have a list with one item, and you want to take the 2nd item out of that list

#

there is no 2nd item

#

not sure why auto-entities doesn't error on it though, but I wouldn't consider it smarter 😉

floral shuttle
#

its the same with the selects on attributes. In auto-enties those simply work (as they used to in Ha some time ago), in HA we need to select 'defined' first

silent seal
#

It's probably null coalescing and/or just handling that in the background for you

floral shuttle
#

I need to select these entity_id's sensor.switch_48_poe_port_1_poe_power where only that port number changes of course. Ther is 1 compound sensor it needs to exclude sensor.poe_ports_power

floral shuttle
silent seal
#

Bear in mind, it's just that someone else wrote the code which checks if it's defined first. It's still doing that

floral shuttle
#

well yes, personally I really like that a system has these kind of checks, and doesn't impose that on the user. Wev'e seen a huge amount of that the last couple of years, just think of all the defaults..

ember saffron
floral shuttle
ember saffron
#

I guess you answered the wrong guy 🙂

floral shuttle
#

o my pardon, yes, I hadn't noticed I 'answered'.

ember saffron
#

no problem

floral shuttle
#

but what the Fes was saying was {{ (your_calculation_in_parenthesis) |round(2) }}

#

if I use it as is, it orders on human listing perfectly, except for the last

#

if I add sort: name, things go understandably wrong, so that is not useful

#

the order with the Port 17 as last is also in the dev tools.

#

so I seem to be needing a sort in the template on that number. But I dont understand why it does this in the first place

marble jackal
#

states[domain] used to sort on entity_id, but that has been removed like 2 months ago, becuase it was quite heave on resources

#

but that also only works with a leading 0 in the entity_id

#

you could sort it in your template, by adding a sort id to your dict and sort it on that

heavy crown
#

HI, as I was confusing ... a new attempt with more realistic data

#

sensor.station_ABC_e10
state: 0.99
attr:

  • type: e10
  • address: xyz

sensor.station_ABC_diesel
state: 1.8
attr.:

  • type: diesel
  • address: xyz

Wished output: 'columns' per station
station_ABC 0.99 1.8 xyz

floral shuttle
#

ok, I will do so, however, can you explain why only 17 is misplaced?

marble jackal
#

where are you sorting on now?

floral shuttle
#

nothing, just the {% set ns = namespace(switches=[]) %} {% for s in states.switch |selectattr('entity_id','search','poe_port') %} {% set ns.switches = ns.switches + [ { "entity": s.entity_id, "name": (state_attr(s.entity_id,'friendly_name').split('PoE')[1]|trim), "secondary_info": 'last-changed' } ] %} {% endfor %} {{ns.switches}}

#

try it in dev tools template and it does what auto-entities does, no background magic just yet 😉

marble jackal
#

I'm not sure how states.switch is sorted now. But it will use whatever order the state objects are provided

floral shuttle
#

I must add that I only recently added that entity (enabled it in the integration), so maybe some background calculations on being available..

marble jackal
#

it's probably last there, as it was most recently added

floral shuttle
#

yeas, something like that would explain that behavior

#

which is ofc a completely silly sorting argument, might even call that an issue

marble jackal
#

there is no sorting argument, it just provides the state objects as it gets them

floral shuttle
#

maybe not an active sorting argument, but listing in order of recently added is de facto sorting.

#

for this to work properly again, I have to disable all, and re-enable all again....

marble jackal
#

or just sort them yourself

floral shuttle
#

right.. and thats when we get back to some posts above

marble jackal
#
            {% set ns = namespace(switches=[]) %}
            {% for s in states.switch
               |selectattr('entity_id','search','poe_port') %}
              {% set name = state_attr(s.entity_id,'friendly_name').split('PoE')[1]|trim %}
              {% set ns.switches = ns.switches + [
                {
                  "entity": s.entity_id,
                  "name": name,
                  "secondary_info": 'last-changed',
                  "sort": name.split(' ')[1] | int
                }
              ] %}
            {% endfor %}
            {{ns.switches | sort(attribute='sort') }}
#

something like this

floral shuttle
#

yes, that is beautiful, thank yvm. also works in auto-entities.

solid inlet
#

given that a helper with entity id 'input_text.04_26_fb_c2_e3_72_81' exists and a tag_id correctly returns '04_26_fb_c2_e3_72_81', can i get it's state like this, if so please help with syntax ... name: "{{ states('input_text.' ~ trigger.event.data.tag_id).state }}"

#

i'm trying to evaluate the text for use in an automation action.

marble jackal
#

because you added .state

#

remove that

#

it's either states.sensor.foo.state (which you should avoid) or states('sensor.foo')

solid inlet
#

i just noticed another problem... the name of the text input and the tag_id returned is input_text.04-26-fb-c2-e3-72-81... but the entity has underscores! lol yikes..

#

can i add in some kind of search replace to change tag_id '-' to '_' so that states will function correctly?

#

oops.."_"

#

i think i'm almost there with name: "{{ states('input_text.' ~ (replace(trigger.event.data.tag_id,"-","_")) }}" ... but still syntax

marble jackal
#

you need to replace - with _

#

now you're just removing the -

#

"{{ states('input_text.' ~ (replace(trigger.event.data.tag_id,"-","_")) }}"
Oh wait, it was just because you didn't add code formatting, and discord made your text cursive

#

or you use "{{ states('input_text.' ~ trigger.event.data.tag_id | slugify) }}"

solid inlet
#

slugify! for the win

#

thanks so much!

#

I've been staring at dashes and seeing underscores for hours! lol thanks again

tender summit
#

why does visual code studio say this is a unknown tag:

#

frontend:
themes: !include_dir_merge_named themes

obtuse zephyr
#

What's the error

tender summit
#

"unknow tag <! include

#

i don't understand it. now it displays a different error on "default_config:

obtuse zephyr
#

You're using the latest version of the add-on, which has schema validation issues

#

You need to revert to the previous version if you want it fixed

tender summit
#

what is schema validation issues?

obtuse zephyr
#

The issue you're seeing

tender summit
#

yes. thats exactly what i found this minute

#

so it is just a displayed error and does not affect my system=?

obtuse zephyr
#

That error itself doesn't affect you, correct. Apart from it not being able to actually validate the file

#

It doesn't mean it's wrong (or right...)

tender summit
#

ah okay. so this is the reason the other error does not show up anymore

#

?

obtuse zephyr
#

Yeah, this would likely prevent it from showing other actual errors

tender summit
#

hmm now how to downgrade?

obtuse zephyr
#

You using HA OS and the addon?

tender summit
#

yes

obtuse zephyr
#

Restore a partial backup

tender summit
#

WOW thank you this is amazing. i learned now what the partial backup is

#

i found the other issue now: (from before)
it says:
unknown tag <!include_dir_merge_named>

#

as error to this: frontend:
themes: !include_dir_merge_named themes

#

okay seems like no more errors after restore

#

i thank you a lot for your help

obtuse zephyr
#

You bet np

tender summit
#

👍

#

the other problem is still not solved but has nothing to do with templates🥲

#

u know which channel would be right for trusted network/user problems?

obtuse zephyr
modest shore
#

I posted earlier about this value. Is there any way I can have it be a minumum? For example, if sensor.coreception_progress is less than 7, then the value should be 7. If it's more than 7, the value should be sensor.coreception_progress
value: "{{ states('sensor.coreception_progress') | float }}"
How do I do that?

inner mesa
#

sure

#

value: "{{ [7, states('sensor.coreception_progress') | float]|min }}"

modest shore
#

Ah thanks. Any chance that you would have a doc that shows that's how it's done? I googled it and couldn't really find anything that says that's how it's done. I just want to learn about these different functions I can use.

inner mesa
#
min([x, y, ...]) will obtain the smallest item in a sequence. Uses the same parameters as the built-in min filter.
#

which shows essentially what I gave you

modest shore
#

Thanks. That's useful.

peak juniper
#

With the help of some awesome boffins from this forum, I put together a sensor to check my history sensors (+ utility meter sensors) to see who is watching the most content on my plex server. This works great. However, I would like to tweak this code to look at the state attribute "last_period" and not just the state, but not sure how to achieve this

plain magnetBOT
#

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

peak juniper
#

any thoughts?

#

tried adding 'last_period: s.last_period' but didn't seem to work

inner mesa
#

Every time I hear 'boffin' it seems like the most unlikely word to be a positive or complimentary description 🙂

#

Hey, who are you calling a boffin? 😠

peak juniper
#

I love the word boffin!

#

I would love to be a boffin myself 😄

inner mesa
#

Or some kind of bird. I would totally believe that

peak juniper
#

flightless, ofc

#

but well-loved by all

sage aurora
#

I have a 433MHz sensor and it works well with RTL_433 and publishing to MQTT. It's a doorbell, so it pushes a message when someone rings, but it's stateless. So the signal is sent twice for redundancy, but there's no "on" or "off". Topic is rtl_433/doorbell/12345- the sensor ID is 12345, and then there's values inside, although they don't really matter much. What sort of sensor would work in HA where it would trigger?

lofty mason
#

Do you need an entity/sensor? You can just trigger automations straight from the MQTT event with an MQTT trigger.

sage aurora
#

This is what I have so far, not sure if I'm in the right ballpark or not.

mqtt:
    sensor:
    - name: "Reolink Camera"
      state_topic: "rtl_433/Reolink-Doorbell/4151085"
      value_template: '{{ "3f572d8" in data }}'
      
round oriole
#

Anyone know how I can turn this into a value template? I want to change it so that the below value is 'equal to or less than' ?

condition: numeric_state
entity_id: sensor.avg_climate_temperature
below: input_number.thermostat_setpoint
above: sensor.combined_ac_temp_setting

inner mesa
#

{{ states('input_number.thermostat_setpoint')|float <= states('sensor.avg_climate_temperature')|float < states('sensor.xxxx')|float }}

#

Got tired of typing long names on my phone

round oriole
#

haha understandable

#

thank you I will check that out

inner mesa
#

It would be a template condition

round oriole
#

yup

#

Thanks @inner mesa that was perfect. Makes sense now that I look at it.

wanton girder
#

Could anyone help to change this, so that I could use it in a time trigger function:
´´´
{% set energyPriceSensor = "sensor.energi_data_service" %}
{% set priceData = namespace(numbers=[]) %}
{% for i in state_attr(energyPriceSensor,'raw_today') %}
{% set priceData.numbers = priceData.numbers + [i.price] %}
{% endfor %}
{% set three_consecutive_hours = namespace(numbers=[]) %}
{% set this_hour = now().hour %}
{% for n in range(this_hour,22) %}
{% set three_hour_sum = (priceData.numbers[n]+priceData.numbers[n+1]+priceData.numbers[n+2])|round(2) %}
{% set three_consecutive_hours.numbers = three_consecutive_hours.numbers + [three_hour_sum] %}
{% endfor %}
{% set min_three_hour = min(three_consecutive_hours.numbers) %}
{% set least_expensive_hours = this_hour + three_consecutive_hours.numbers.index(min_three_hour) %}
{{ least_expensive_hours | int }}

#

For other:
Changed that last line to
{{ least_expensive_hours | int ~ ':00' }}

#

Trying to start an automation based on a template sensor time value,
The sensor value is hh:mm and is called: sensor.bedste_3_timer_i_dag
so the sensor is 11:00 i would like for a automation to start at 11:00

#

Actually, now that I think about it, it might be better to just look for the hour value, so the sensor is 11 and the hour corresponse to 11...so a condition based on time...Ive got the trigger but need to check for the hour value

marble jackal
#

I actually made a macro for this, it's available on HACS

nimble copper
#

I'm trying to match a future datetime in a list using selectattr('datetime'.... But running into trouble.

#

I can't work out why, but this code is showing me (today_at('06:00') + timedelta(days=1)).astimezone(utcnow().tzinfo).isoformat() this output 2023-05-04T05:00:00+00:00

#

However, I'd exepect it to show tomorrow at 06:00 not 05:00. What am I doing wrong?

#

This is the example datetime=2023-05-04T06:00:00+00:00 I'm trying to match to in the list of items.

marble jackal
#

You start with local time 6:00 and you then convert that to UTC, which seems to be 5:00

#

So I assume your timezone is GMT with 1 hour because of DST

#

But are you sure it's not a datetime?

#

So not a datetime isoformat string, but actually a datetime object

nimble copper
#

I'm on London/Europe Tz. So yes, GMT+1 because of DST.

#

Here's the first item in the list of weather predictions. I'm not sure how to tell if the datetime is in an isoformat string or a datetime object.
{'datetime': '2023-05-03T15:00:00+00:00', 'condition': 'cloudy', 'precipitation_probability': 16, 'wind_bearing': 'NE', 'temperature': 14.0, 'wind_speed': 6.44}

#

How can I tell?

#

Using the Dev Tools>Template window. It reports that the result type is a string for this

{{ state_attr('weather.XXXXX', 'forecast')[1].datetime }} which is the weather sensor that is providing the data.

marble jackal
#

If it's from a weather entity it should be a datetime

#

@nimble copper Just try to compare it to a string

#

{{ state_attr('weather.XXXXX', 'forecast')[1].datetime > 'foo' }}

nimble copper
#

The test returns false. So it's a datetime object?

marble jackal
#

No, if it returns false it's a string

#

Otherwise you would have got an error that you are trying to compare a datetime.datetime with a string

nimble copper
#

👍

nimble copper
#

Is there a way to convert each datetime field in my dict into a date object?

bronze tide
#

Lately HA complains with a warning to a temple sensor I created in YAML which usually contains a number but also can contain a string. The warning goes like this:
WARNING (MainThread) [homeassistant.components.sensor] Sensor sensor.full_moon has device class None, state class None and unit thus indicating it has a numeric value; however, it has the non-numeric value: at 7:33 P.M. Central European Summer Time, Friday, May 5, 2023 (3) (<class 'str'>); Please update your configuration if your entity is manually configured, otherwise create a bug report at <link here>
The definition of the sensor goes like this:

    - sensor:
      - name: "Full Moon"
        unit_of_measurement: ""
        unique_id: "a775b3cd-8d50-4583-9ffa-e4c6fbb6c322"
        icon: mdi:moon-full
        state: >
          {% set d = states("sensor.Full_Moon_days_until") %}
          {% if '0' == d %}
          {% set d = 'today' %}
          {% endif %}
          {% set s = states("sensor.Full_Moon_date") + " (" + d + ")" %}
          {{ s }}What can I do to make the warning go away?```
mighty ledge
mighty ledge
#

i.e. delete it from the UI, then remove the unit_of_measurement from the yaml, then restart HA

fickle sand
#

Also entities should be always fully lowercase

wanton girder
marble jackal
nimble copper
#

Or should I just use a string replacement to remove the +01:00 and change it to +00:00?


Output
2023-05-04T06:00:00+00:00
mighty ledge
#

if you change the +1 to 0, you just changed the time by 1 hour.

nimble copper
#

But then it wont ever match with one of the items in weather sensor.

All of the datatimes in the weather sensor are like this.

2023-05-04T06:00:00+00:00

mighty ledge
#

if you're trying to match against UTC, then you need to use UTC timestamps

#

06:00+00:00 is not 6am

#

it's 6am UTC

#

which is 5 AM +01:00

#
{{ (today_at('06:00') + timedelta(days=1)).astimezone(utcnow().tzinfo).isoformat() }}
wanton girder
nimble copper
#

I'm a bit confused here. The code above doesn't match the expect item I'm trying to select from the weather sensor dict.

The item in the weather sensor dict is this

However the code above shows tomorrow at 05:00am and not tomorrow at 06:00am as I'm expecting. Presumbaly due to BST / London/Europe.


Output
2023-05-04T05:00:00+00:00```

Apologies I'm probably missing interpretaing / understanding something .
mighty ledge
#

UTC is a universal time zone

#

it's +00:00

#

6am for me is 10:00+00:00

#

6am for you is 5:00+00:00

nimble copper
#

Ok. That makes sense.

#

So is {{ (today_at('06:00') + timedelta(days=1)).astimezone(utcnow().tzinfo).isoformat() }} changing when my time moves from DST (Winter +00:00) to BST (summer +01:00)?

mighty ledge
#

DST will be accounted for with your today_at

marble jackal
nimble copper
#

Ok. So how can I match an item in the dictionary of weather predictions? Bearing in mind that I'm trying to find the item that's tomorrow at 06:00:00+00:00?

Is there an equivelant today_at('06:00') that uses UTC time that I can add a timedelta(days=1) to?

wanton girder
mighty ledge
#
[{'datetime': '2023-05-04T06:00:00+00:00', ....
                 ^-- ISOFORMAT
marble jackal
mighty ledge
#

e.g.

{% set t = (today_at('06:00') + timedelta(days=1)).astimezone(utcnow().tzinfo).isoformat() %}
{{ state_attr('weather.XXXXX', 'forecast') | selectattr('datetime', 'eq', t) | first | default }}
wanton girder
mighty ledge
#

@wanton girder

plain magnetBOT
#

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

wanton girder
mighty ledge
mighty ledge
wanton girder
#

Im pretty sure.... I have hacs on the left hand side...from there...where should I go ?

mighty ledge
nimble copper
wanton girder
nimble copper
#

The code I was suing was working as expected when it was DST back in Winter. It's only since moving to BST that it's broken

mighty ledge
marble jackal
wanton girder
#

In hacs ?

nimble copper
#

Or {{ (today_at('07:00') + timedelta(days=1)).astimezone(utcnow().tzinfo).isoformat() }} ?

But wont this code need to be changed, once my tz moves back to DST?

obtuse zephyr
#

Do you just want {{ today_at('06:00').replace(tzinfo=utcnow().tzinfo).isoformat() }} ?

bronze tide
marble jackal
wanton girder
#

In the intregation tab, i see hacs, if I press configure i have enabled experimental mode

mighty ledge
#

Did you restart after you turned it on?

marble jackal
mighty ledge
wanton girder
nimble copper
#

I can't think of another reason why the template code would stop working that would coincide with the change from DST to BST.

wanton girder
mighty ledge
#
{% set ts = [
      (today_at('07:00') + timedelta(days=1)).astimezone(utcnow().tzinfo).isoformat(),
      (today_at('06:00') + timedelta(days=1)).astimezone(utcnow().tzinfo).isoformat(),
] %}
{{ state_attr('weather.met_office_battlefield', 'forecast') | selectattr('datetime', 'in', ts) | first | default }}
wanton girder
#

In my hacs intregrations im getting this error: Error while loading page repository.

#

all of them

marble jackal
#

I actually downloaded all templates which are in the store (and two of them are created by me) 😅
Not so popular yet

marble jackal
nimble copper
wanton girder
#

In still can't see templates, its only intergrations and frontend

mighty ledge
#

what do you see on your main page

#

when you click hacs

wanton girder
#

Not loaded in Lovelace
You have 5 Lovelace elements that are not loaded properly in Lovelace.

and 4 menus

mighty ledge
#

then you're not running experimental

wanton girder
#

Is there another place to enable experimental ?

mighty ledge
#

the main page will look like this:

#

you enable experimental via configuration options on the integration page for hacs

#

if the store shows HACS, then it's enabled, so maybe you haven't cleared your cache and refreshed the page

marble jackal
wanton girder
#

After you change the setting for experimental features, you must fully reload HACS. Restart Home Assistant and then, once Home Assistant has fully started, clear your browser cache.

#

Tried incognito...bingo

marble jackal
#

Just press ctrl + F5 to clear browser cache

wanton girder
#

Thanks....I think its download...so how to use it...only though code and no ui....

marble jackal
#

You were already creating a template sensor right, which is not possible in the GUI

wanton girder
#
{% from 'cheapest_energy_hours.jinja' import cheapest_energy_hours %}
{{ cheapest_energy_hours('sensor.energi_data_service', hours=3, time_format='time24') }}

Something with start ?

marble jackal
#

Not sure what you are trying to achieve

wanton girder
#

Im trying to start a device when the energy price is low

#

Will you be here in a couple of hours...need to pick up my kids ?

nimble copper
#

Is there a way to test / run templates from VSCode?

mighty ledge
#

not within HA's environment

inner mesa
#

I thought there was a 'render template' task

#

devtools -> is the way, though

marble jackal
marble jackal
mighty ledge
#

That's not available in VSCode though, maybe the vscode addon, but it's not available in vscode because there's no HA running

#

yeah, I just downloaded the HA extension and template command pallet tasks are missing

wanton girder
inner mesa
#

Which I generally assume folks here are using

mighty ledge
#

that's what I'm saying

#

That's how I run it, and that's why I've never seen the command pallet

#

there is no Home Assistant: Render Template for the extension outside of the container

inner mesa
#

You mean installing it in the remote code-server container?

mighty ledge
#

I mean installing the extension in VSCode

inner mesa
#

That's...what I did

mighty ledge
#

what OS?

inner mesa
#

MacOS

#

does it matter?

mighty ledge
#

Well, it's never been available on windows

#

so, yes

inner mesa
#

It's an advertised feature of the extension

mighty ledge
#

🤷‍♂️

inner mesa
#

Indeed

mighty ledge
#

what extension are you using?

inner mesa
#

The one from Kees

mighty ledge
#

?

inner mesa
#

Yes

mighty ledge
#

Yep, it's not available

#

it's not listed in the features either

inner mesa
#

You configured it with a link to your HA instance?

mighty ledge
#

oh, nope, it is listed

#

at the bottom

inner mesa
mighty ledge
#

I'll have to look at the configuration later, work calls

left minnow
#

I have problem with my FR24 Feeder rest sensors.

wanton girder
marble jackal
#
{% from 'cheapest_energy_hours.jinja' import cheapest_energy_hours %}
{{ cheapest_energy_hours('sensor.energi_data_service', hours=3, time_format='time24', look_ahead=true) }}
wanton girder
#

In an automation as a trigger ?

marble jackal
#

That could give you a 24 hour format time string when the cheapest consecutive block of three hours today starts

wanton girder
#

will that check if the now(hour) is equal to cheapest hour ?

marble jackal
#

No

wanton girder
#

If I put it in template test thingy - it says; UndefinedError: 'dict object' has no attribute 'start'

marble jackal
#

Did you test this in developer tools > template?

#

Okay

#

Did you have a look at the documentation I provided

#

You will need to provide a time_key

wanton girder
marble jackal
#

And maybe also a value_key

#

Look in developer tools > states to see which keys are used for your sensor

wanton girder
#

I this: sensor.energi_data_service ?

marble jackal
#

Yes

#

It should have an attribute raw_today

wanton girder
#

it does

marble jackal
#

In that you will see a list with an item for each hour of the day

wanton girder
#

yes correct 🙂

marble jackal
#

And there is a value with the date and time in each of those list items

#

Preceded by a key to indicate that value

#

That is what you need to provide as time_key

wanton girder
#

raw_tomorrow:

  • hour: '2023-05-04T00:00:00+02:00'
    price: 1.23
#

raw_today:

  • hour: '2023-05-03T00:00:00+02:00'
    price: 1.3
marble jackal
#

Okay, so you need to add time_key='time', value_key='price'

wanton girder
#

not hour ? (trying to learn)

marble jackal
#
{% from 'cheapest_energy_hours.jinja' import cheapest_energy_hours %}
{{ cheapest_energy_hours('sensor.energi_data_service', hours=3, time_format='time24', look_ahead=true, time_key='hour', value_key='price') }}
marble jackal
wanton girder
#

YES that gives me a response: 21:00

marble jackal
#

Okay

wanton girder
#

Just so that I learn here... that means that todays 3 cheapest hours starts at 21:00 ?

marble jackal
#

Well, not sure what time it is currently where you are, but because of the look_ahead=true setting the hours which are already passed are not taken into account

#

So it could be the cheapest block of 3 hours was actually at 13:00

wanton girder
#

but we are past 21:00...so...its not looking ahead ?

#

it 21:21

celest tinsel
#

Am I the only one that is looking for a way to create custom jinja filters? I have a need to use a small python function as a filter. There was a hacs component but it no longer seems to work.

inner mesa
#

I would love to be able to do that, and you can't

#

there was a feature request for Jinja to use macros as filters, which would also be nice, but it was rejected. I posted it here a while ago

#

(rejected by the Jinja project, not HA)

celest tinsel
#

So jinja doesn't allow custom filters?

inner mesa
#

HA doesn't

celest tinsel
#

Sorry - misread your last post

#

Any thoughts on how to handle a complicated data conversion? I need to convert a value before passing it to a modbus service call. using a python script didn't work because the python_script integration doesn't support import.

inner mesa
#

PyScript, Appdaemon

marble jackal
celest tinsel
#

Can pyscript return a value i can use?

inner mesa
#

no, but you can stuff it into a helper and use that

#

or you can just call the service from PyScript with whatever you want

wanton girder
inner mesa
#

the latter is what I recommend

wanton girder
#

How do I make an automation with this now ?

marble jackal
#

Either using a template trigger, or by creating a template sensor and using that in a time trigger

marble jackal
#

This would work for the trigger:

platform: template
value_template: >
  {% from 'cheapest_energy_hours.jinja' import cheapest_energy_hours %}
  {% set s = cheapest_energy_hours('sensor.energi_data_service', hours=3, look_ahead=true, time_key='hour', value_key='price', time_format='time24') %}
  {{ now().strftime('%H:%M') == s }}
wanton girder
#

I just lost all local access - didnt to anything

marble jackal
#

That's not related to templates

wanton girder
#

Sorry... - If I put this in template tester.. it says false

#

But should there also be a time pattern trigger to acompany this template trigger ?

marble jackal
#

That's because it isn't 21:00 now

#

It specifically checks for that time

wanton girder
#

by it self or do i need to trigger this in another manner ?

marble jackal
#

And it depends on your goal what the trigger should be, but time pattern triggers are almost never the best choice

wanton girder
#

so its not "checking" by itself ?

marble jackal
#

I'd assume that if you want to turn on a device which has a 3 hour run time, you'd want to do that when that period starts

wanton girder
#

yes..

marble jackal
wanton girder
#

should i somehow check for true/false ?

marble jackal
#

That's what the template does

#

It returns false now

wanton girder
#

or do it just run when it becomes true

marble jackal
#

It would return true if the current time would be 21:00

wanton girder
#

so false since its past 21:01 ?

marble jackal
#

Correct

wanton girder
#

when will it check for next 3 hour period ?

plain magnetBOT
#

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

marble jackal
wanton girder
#

so in 6 minuts I should get a new value ?

silver wren
marble jackal
wanton girder
#

if I include: include_tomorrow=true ?

marble jackal
#

Then it will probably show some time in the early afternoon

marble jackal
#

And only use switch: once

wanton girder
#

Ill test this out...finally, can I have this template output shown on my dashboard.

marble jackal
#

Yes, in any card which supports templates

silver wren
marble jackal
wanton girder
marble jackal
#

Then do that 🙂

wanton girder
#

Funny... dont know how or where ?

plain magnetBOT
wanton girder
#

As I said im learning much more talking here...It just makes more sence "in person"

#

be back in 40 min...:)

#

Grateful for all your help! 🙂

celest tinsel
wanton girder
# marble jackal Or by creating a template sensor out of it

Like this:

template:
  - sensor:
      - name: "Billigste 3 timer i dag - NY"
        state: >
          {% from 'cheapest_energy_hours.jinja' import cheapest_energy_hours %}
          {{ cheapest_energy_hours('sensor.energi_data_service', hours=3, time_format='time24', look_ahead=true, time_key='hour', value_key='price') }}
viscid flint
viscid flint
junior moth
#

little advice on what i'm doing wrong here please:

state: >
        {% if states('sensor.vibration_sensor_garage_door_angle_z')|int() < 0 %}
          Closed
        {% else %}
          Open
        {% endif %}

READS as Open
However the sensor state i see is 14...

#

apparently i can't paste screen shots

#

the unit of measure is angle. maybe that is messing me up somehow?

inner mesa
#

Remove () after int

#

And please format your code

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.

junior moth
# inner mesa And please format your code

sorry, updated. Also, i removed the () and still shows open

state: >
        {% if states('sensor.vibration_sensor_garage_door_angle_z')|int < 0 %}
          Closed
        {% else %}
          Open
        {% endif %}
inner mesa
#

As expected

#

You said the sensor value is 14 🤷

junior moth
#

my logic brain has clearly shut down.

inner mesa
#

No worries, it happens

orchid oxide
#

i still dont know, is it possible to do somthing like this
states('sensor.pc_lastsystemstatechange') == ('unavailable' or 'Suspend')
obviously without having to specify the state twice. everything i try either doesnt work or something like this only listens for the first string

marble jackal
#

states('sensor.pc_lastsystemstatechange') in ['unavailable', 'Suspend']

#

or is_state('sensor.pc_lastsystemstatechange', ['unavailable', 'Suspend'])

orchid oxide
#

you are a lifesaver. these wouldnt match if i had a state that was available for example, would it?

marble jackal
#

this will be true if the state is either unavailable or Suspend

#

for all other states it will be false

orchid oxide
#

cool cool, tysm

torpid hinge
#

My heatpump has a sensor that gives the total system uptime every minute, I have been trying to create a binary sensor to be able to quickly tell if the heatpump is on or off, I tried this:

 - trigger:
    - platform: state
      entity_id: sensor.total_system_uptime
      to:
    binary_sensor:
      - name: heatpump_test3
        auto_off: 0:01:01
        state: >
          {{ trigger.from_state.state | int < trigger.to_state.state | int }}

it seems that the trigger does not work when the state remains the same so I had to add the auto_off, is there a better way to do this?

marble jackal
#

what is the state of that sensor when the heatpump is off ?

jolly crest
#

Hey! I have a rest sensor. Is it possible to template the json_attributes reults without making a new sensor with the template as value?

#

I want to convert one of the json_attributes

orchid oxide
#

im having some trouble with this sensor. every time i reload the templates yaml, it changes the state to clean. for some reason its triggering that id, despite it supposed to be going from on to off. the sensor binary_sensor.dishwaser is a template sensor, but its going from, unavailable to off when i reload the yaml, so i dont understand why its triggering this automation

https://dpaste.org/9anif

#

what am i looking straight past here

orchid oxide
marble jackal
orchid oxide
#

Yeah I checked the history in the more info and it goes to unavailable

mighty ledge
#

tbh, inline if statements are hard to read the order of operations when you have multiple. I'd break it out.

{% if trigger.id == 'dirty' and is_state('binary_sensor.dishwasher_door', 'on') and is_state('binary_sensor.kitchen_motion_sensor_motion', 'on') %}
  Dirty
{% elif trigger.id == 'clean' and trigger.from_state.state == 'on' %}
  Clean
{% endif %}

Also keep in mind that your tempalte will only update on the triggers, it will not update when either binary_sensor in the template updates.

#

@orchid oxide ^

#

But just to be clear, you don't have an else built into that. So the sensor will go unavailable whenever the for 3 minutes triggers and the from_state is off.

#

It was hard to see that logic because you were using nested inline if statements

orchid oxide
mighty ledge
#

it does not

#

because that's how you built the template

orchid oxide
#

Kk ill fix that then

orchid oxide
mighty ledge
#
{% if trigger.id == 'dirty' and is_state('binary_sensor.dishwasher_door', 'on') and is_state('binary_sensor.kitchen_motion_sensor_motion', 'on') %}
  Dirty
{% elif trigger.id == 'clean' and trigger.from_state.state == 'on' %}
  Clean
{% else %}
  {{ this.state }}
{% endif %}
mighty ledge
orchid oxide
#

Yes. But it goes from unavailable to off, not on to off

mighty ledge
#

you can make a debug sensor to see if that's true

#

or add them as attributes

#
attributes:
  from_state: "{{ trigger.from_state.state }}"
  to_state: "{{ trigger.to_state.state }}"
  id: "{{ trigger.id }}"
orchid oxide
#

Okay something much more suspicious is going on as I've added those attributes, checked my config and even double checked the yaml and spacing, and they just aren't even showing up. I'll have to figure this out later since I'm on my phone

#

Just kidding, actually manually triggered one of the triggers in devtools and the attributes updated, which I'm assuming means that there is no trigger causing the automation to update when I reload the yaml

#

Which doesn't explain why it's changing State when I reload..

mighty ledge
#

trigger template entities restore state

orchid oxide
#

Hold on... I'm realizing my issue now lmfao

#

I haven't let it actually run the dirty trigger since trying to fix this yesterday and what you put in devtools doesn't count towards restoring state so... It's probably fixed

plain magnetBOT
#

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

marble jackal
#

@wanton girder what does the macro return now?

wanton girder
#

False

#

I have put sensors on my dashboard so I know that I have passed a time multiple times

marble jackal
#

No, the macro itself

wanton girder
#

I don't know

plush willow
#

What is wrong with this template. It gives since the update of 2023.5.0 unknown as value

template:

  • sensor:
    • name: water_usage_daily_liters
      unique_id: "water_usage_daily_liters"
      unit_of_measurement: L
      state: "{{ (states('sensor.water_usage_daily') | float * 1000) |round(3)| replace ('.',',') }}"
#

sensor.water_usage_daily has the value: 0.0592

wanton girder
mighty ledge
#

by looking at what s returns in the template editor

wanton girder
#

It says false

mighty ledge
#

no... {{ s }}

marble jackal
wanton girder
marble jackal
marble jackal
mighty ledge
plush willow
mighty ledge
#

er nevermind, you omitted the :

#

so your last line should remain what it was

wanton girder
# marble jackal You say you've put sensors on your dashboard, what kind of sensors do you mean?

I made these:

template:
  - sensor:
      - name: "Billigste 3 timer i dag - NY"
        state: >
          {% from 'cheapest_energy_hours.jinja' import cheapest_energy_hours %}
          {{ cheapest_energy_hours('sensor.energi_data_service', hours=3, time_format='time24', look_ahead=true, time_key='hour', value_key='price') }}

  - sensor:
      - name: "Billigste 3 timer i dag og imorgen - NY"
        state: >
          {% from 'cheapest_energy_hours.jinja' import cheapest_energy_hours %}
          {{ cheapest_energy_hours('sensor.energi_data_service', hours=3, time_format='time24', look_ahead=true, time_key='hour', include_tomorrow=true, value_key='price') }}
mighty ledge
#

So, just so you understand, your template will only be true exactly at 12:00

#

all other times it will be false

wanton girder
#

yes but I didn't get any notifications today

marble jackal
#

When did you create the automation?

wanton girder
#

maybe I should try to remove include tormorrow

#

then the next should be 21:00

plain magnetBOT
#

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

marble jackal
#

The problem with including tomorrow is that the time can change to a time which has already passed today after the data for tomorrow becomes available

#

I expect you also want to remove look_ahead=true, because that will also keep moving the time

plush willow
wanton girder
#

Could I just set these to to false for now ?

plush willow
#

@marble jackal Okay the solution is to remove the replace part...now in the mushroom chip it is showed with the correct decimal seperator....in the developer tools it showed it wrong but that is no problem.

marble jackal
plush willow
#

okay.

marble jackal
plain magnetBOT
#

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

marble jackal
#

{{ area_name(trigger.entity_id) }}

floral steeple
#

thanks!

marble jackal
#

What it does, or why you should remove it?

amber hull
#

I am trying to figure out what I am doing wrong using Pedro's template guide. ``` sensor:

  • platform: time_date
    display_options:
    • 'date'
      template:
  • sensor:
    • name: recycling day
      state: >
      {% set t = now() %}
      {% set midnight = today_at() %}
      {% set event = state_attr('calendar.recycle', 'start_time') | as_datetime | as_local %}
      {% set delta = event - midnight %}
      {% set values = [ 'Today', 'Tomorrow', 'Day After Tomorrow' ] %}
      {{ values.get(delta.days, 'In %s Days'%delta.days) }}```
#

The sensor sensor.recycling_day comes back unavailable

#

The calendar shows the correct date and the date seems correct.

#

Seems it doesn't work in the template tool but his other example does.

marble jackal
#

What example did you base this on then?

plain magnetBOT
#

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

amber hull
#

works

#

I'm trying to understand what I am doing wrong (or not understanding why Petro's code is not working for me. In any case I have them all working modifing one of his examples.

wanton girder
marble jackal
marble jackal
#

Oh wait, I do now

amber hull
#

Thanks. I have it working so I'm good. Just trying to follow his code and gain a little knowledge 🙄

marble jackal
#

It works if yo do this
{% set values = { 0: 'Today', 1: 'Tomorrow', 2: 'Day After Tomorrow' } %}

#

@mighty ledge did something change here? You posted this 3 years ago, I expect someone would have mentioned that it did not work in that time period

mighty ledge
#

It should work

mighty ledge
marble jackal
mighty ledge
#
      {% set midnight = today_at() %}
      {% set event = state_attr('calendar.hvac', 'start_time') | as_datetime | as_local %}
      {% set delta = event - midnight %}
      {% set values = [ 'Today', 'Tomorrow', 'Day After Tomorrow' ] %}
      {{ values[delta.days] if delta.days < values | length else 'In %s Days'%delta.days }}
#

or

      {% set t = now() %}
      {% set midnight = today_at() %}
      {% set event = state_attr('calendar.hvac', 'start_time') | as_datetime | as_local %}
      {% set delta = event - midnight %}
      {% set values = {0: 'Today', 1:'Tomorrow', 2:'Day After Tomorrow'} %}
      {{ values.get(delta.days, 'In %s Days'%delta.days) }}
marble jackal
#

Or with a dict like I did above

mighty ledge
amber hull
#

Thanks guys.

wanton girder
marble jackal
#

With look_ahead= false it will show 13:00, but with look_ahead=true it will reject all hours before 20:00

wanton girder
#

Then it should be true...i guess...

marble jackal
#

That really depends on your use case. If you want to start a device on the cheapest hour of the day, so eg at 13:00 you don't want that time to change every time so the automation will trigger again at 14:00 and then again at 15:00 etc

wanton girder
#

True - Thanks, that makes sense....im waiting for the time to be 21:00

marble jackal
#

That's now

wanton girder
#

didn't get a notification :S

#

it false without '' right...

marble jackal
#

Sorry? What do you mean with that last sentence?

wanton girder
#

look_ahead=false not look_ahead='false' right

#

My templateslooks like:

template:
  - sensor:
      - name: "Billigste 3 timer i dag - NY"
        state: >
          {% from 'cheapest_energy_hours.jinja' import cheapest_energy_hours %}
          {{ cheapest_energy_hours('sensor.energi_data_service', hours=3, time_format='time24', look_ahead=false time_key='hour', value_key='price') }}

  - sensor:
      - name: "Billigste 3 timer i dag og imorgen - NY"
        state: >
          {% from 'cheapest_energy_hours.jinja' import cheapest_energy_hours %}
          {{ cheapest_energy_hours('sensor.energi_data_service', hours=3, time_format='time24', look_ahead=false, time_key='hour', include_tomorrow=true, value_key='price') }}

Right now the first one says:: entity not avaliable and number 2 says unavaliable

plain magnetBOT
#

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

marble jackal
#

did you update to the latest version in HACS, seems I introduced a bug there

wanton girder
#

Im running 1.4.1

marble jackal
#

Try to downgrade to 1.3.x for now

#

And I need to fix something else, I know why it doesn't work

plain magnetBOT
#

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

marble jackal
#

on version 1.4.1 or an older version?

wanton girder
#

1.3.2

marble jackal
#

let me check

marble jackal
# wanton girder 1.3.2

what does this give in devtools > template

      {% from 'cheapest_energy_hours.jinja' import cheapest_energy_hours %}
      {% set s = cheapest_energy_hours('sensor.energi_data_service', hours=3, look_ahead=false, time_key='hour', value_key='price', time_format='time24', include_tomorrow=false) %}
      {{ s }}
wanton girder
#

13:00

#

look ahead true gives 21:00

#

should I try 1.4.2

marble jackal
#

1.4.2 fixes the issues in the other 1.4 versions

#

What does this give

      {% from 'cheapest_energy_hours.jinja' import cheapest_energy_hours %}
      {% set s = cheapest_energy_hours('sensor.energi_data_service', hours=3, look_ahead=false, time_key='hour', value_key='price', time_format='time24', include_tomorrow=false) %}
      {{ s == '13:00' }}
wanton girder
#

True

floral steeple
#

Hi all, I have a water meter that reports instantanoues water consumption in the units L/h. How do I create a sensor that turns that into consumption, i.e. just Liters? I'm a little confused about the time part

wind forum
#

Hi
i got six counters and want to pick an action based on which of them is the lowest. Is there any more elegant way than "if this counter is lower than THAT counter AND lower than THAT counter AND ....." for each and every one of them?

I have very little experiance with templates (pretend it´s zero)

marble jackal
wanton girder
#

what should the final try be then...does it work as a trigger and a condition ?

marble jackal
#

That would you want to put in the condition?

wanton girder
#

?

wanton girder
#

never mind, ill use it as a trigger..which code ?

#

they do know - v. 1.4.2

marble jackal
#

The code you were using should work

wanton girder
#
{% from 'cheapest_energy_hours.jinja' import cheapest_energy_hours %}  {% set s = cheapest_energy_hours('sensor.energi_data_service', hours=3, look_ahead=false, time_key='hour', value_key='price', time_format='time24', include_tomorrow=false) %}  {{ now().strftime('%H:%M') == s }}
marble jackal
#

As you already have these sensors, you could also use
{{ is_state('sensor.billigste_3_timer_i_dag_ny', now().strftime('%H:%M')) }}

#

Do check if that entity_id is correct though

wanton girder
#

thanks ill try that 😄 Thanks again 🙂

marble jackal
#

No worries, I'm off to bed now

wanton girder
#

Sleep tight 🙂

topaz walrus
#

This the correct channel for "scripts" as well?

wind forum
#

Is there any good introduction into templates? I have NO idea how they work

inner mesa
#

Several links in the channel topic

orchid oxide
#

i would like to make a template select that can inherit the state of another entity, but still set its own state or the state of a trigger sensor, but this seems to not be possible, as template selects seem to be unable to affect their own state, and there is no way to inorganically set the state of a sensor entity. therefore, the only way i can see to make this work is to have the template select change the state of a dummy entity, which can be one of the trigger sensors triggers...but then the dummy entitys state wont update if the trigger sensor updates, meaning i wont be able to trigger the template trigger...i cant figure out how to do what im trying to do lmao

#

at least, not without creating an automation to make the dummy sensor mirror the trigger sensors state on change

#

and im trying to avoid automations for stuff like this if possible

dusk sorrel
#

is it possible in template that sensor value is be zero automatically when mqtt data does not come in ( mqtt device is turn off)?

#

how to solve it?

#

Because when device turned off then sensor value is still old value.

#

possible that expire_after: 3 but i want to value is zero

plush willow
#

Since some versions ago the number of default decimals are changed. I have a lot of utilitymeters that are now showing a lot of decimals instead of 2 some versions ago. What is the best way to have 2 decimals in the UI. I have this template:

utility_meter:
vaatwasser_energy_daily:
source: sensor.vaatwasser_energy
cycle: daily

According to me you can't specify in this template how many decimals you want.

orchid oxide
#

dont qoute me on this, i dont have manny mqtt sensors myself

orchid oxide
dusk sorrel
orchid oxide
wind forum
#

I don´t understand what i am doing wrong. This gives me "false" even if "tagesaufgabe_wasche" is the hiighest counter.

{{  states('counter.tagesaufgabe_wasche') == counters | map('float') | max }}```
#

{{ states('counter.tagesaufgabe_wasche') }}
gives 20
{{ counters | map('float') | max }}
also gives 20
but
{{ states('counter.tagesaufgabe_wasche') == counters | map('float') | max }}
gives false... WHAT?

#

{{ states('counter.tagesaufgabe_wasche') == 20 }}
gives false
{{ 20 == counters | map('float') | max }}
gives true
BUT
{{ states('counter.tagesaufgabe_wasche') }}
still gives me 20.... I don´t get it

mighty ledge
wind forum
#

it SAYS its a number in the output

#

but that makes sense

mighty ledge
#

the output of all sensors is a string

#

if you use states() you will get a string

#

it doesn't matter if it looks like a number, it's a string

#

that's it. There's nothing else to it

#

so when you do a comparision with states() == 349283, you're comparing a string "this_is_a_string" to a number 89892834

#

notice the lack of quotes

#

and "89892834" will always be unequal to 89892834

wind forum
#

I would have thought of that if the output didn´t specificly state it was a number 😄
Okay, how do i convert it?

mighty ledge
#

use | float or | int

#

after states()

wind forum
#

( I know about strings and numbers, i just didn´t think HA would lie to me 😛 )

#

so...
{{ states('counter.tagesaufgabe_wasche') | float == counters | map('float') | max }}
?

mighty ledge
#

You can simplify your template btw

{% set counters = 'counter.tagesaufgabe_altpapier', 'counter.tagesaufgabe_aufraumen', 'counter.tagesaufgabe_bugeln', 'counter.tagesaufgabe_fensterputzen', 'counter.tagesaufgabe_kuche', 'counter.tagesaufgabe_wasche' %}
{{ states('counter.tagesaufgabe_wasche') | float == counters | map('states') | map('float') | max }}
wind forum
#

Ah got it thx

mighty ledge
#

that's the ending result inside your sensor

#

not the result output of the template

#

so if you were to put that into a template, it would produce a number

#

templates themselves always return strings

wind forum
#

oohhhhhhhhh i get it

mighty ledge
#

the template resolver runs after and tries to discern the type it will be.

#

you can check types inside your templates by using is

#

e.g. {{ 'abc' is string }}

wind forum
#

thats something to trip a beginner up

#

At least when i was programming a compiler would give me something like an invalid variable type or something 😄
Thanks for rescuing me
AGAIN!

mighty ledge
#

np

plush willow
orchid oxide
#

i didnt use it for utility meter, but i looked and utility meter doesnt accept templates, so you could create a template sensor if you wanted, or if you just want to use it on the dashboard you could just place it in a card that accepts templates

plush willow
#

Okay I will format it in my dashboard

analog mulch
#

hi. what's the optimal way to turn off all lights except one particular entity (e.g. light.led_eyes), without creating and then curating a group by hand.

obtuse zephyr
#
service: light.turn_off
target:
  entity_id: >
    {{ states.light | rejectattr('entity_id','eq','light.led_eyes') | map(attribute='entity_id') | list }}

should work

analog mulch
#

great! indeed it does

indigo haven
#

I got the following list

I need to map each iten to get the value of a dict and then join it all as a string

{{ states.sensor.plex_ena_server.attributes.keys()|list|reject('in', ['unit_of_measurement', 'icon', 'friendly_name'])|list }}
#

I cant figure outhow map works with this syntax

inner mesa
#

what are you trying to do?

indigo haven
#

I want to get the values from the dict to send as a message

inner mesa
#

the values from all the keys that aren't in that list?

indigo haven
#

yes

#

and then I'll concate the index itself + space + the value

inner mesa
#

like this?
{{ states.sensor.plex_ena_server.attributes.items()|rejectattr('0', 'in', ['icon', 'friendly_)name', 'unit_of_measurement'])|map(attribute='1')|join(', ') }}

indigo haven
#

hmmmmm

#

let me see

inner mesa
#

works4me

indigo haven
#

Im trying to understand how this map works

inner mesa
#

in this case, it's extracting the value for every key (that's left)

indigo haven
#

but like what is attribute='1'?

inner mesa
#

it's kind of a special case. using .items() on a dict returns a list of (key, value) tuples

#

then you can access each item in the tuple by its index

#

it's a dumb example, but this returns [3]:
{{ [(1, 2, 3, 4)]|map(attribute='2')|list }}

orchid oxide
#

that hurts to look at

inner mesa
#

both of these return 3:

{{ [(1, 2, 3, 4)]|map(attribute='2')|first }}
{{ (1, 2, 3, 4)[2] }}
#

thus endeth the class on stupid template tricks

indigo haven
#

wow

#

I cant understant anything lol

orchid oxide
#

the 2 in [2] and attribute = 2 is just the index of the value

inner mesa
#

yes

orchid oxide
#

{{ states.sensor.plex_ena_server.attributes.items()|rejectattr('0', 'in', ['icon', 'friendly_)name', 'unit_of_measurement'])|map(attribute='1')|join(', ') }}

in this, 0 is the key and 1 is the value of the respective key-value pairs

inner mesa
#

you win...something

#

a green check, I guess

indigo haven
#

bc it ltierealy can only Map

#

like directly to another param

orchid oxide
indigo haven
#
{% for key in states.sensor.plex_ena_server.attributes.keys()|list|reject('in', ['unit_of_measurement', 'icon', 'friendly_name'])|list %}
'{{ key }}' is watching '{{states.sensor.plex_ena_server.attributes[key]}}' 

{% endfor %}
#

this worked

#

was a nightmare tho

inner mesa
#

is your point that you want to compose a sentence with those keys and values?

indigo haven
#

yes

#

that too

#

I guess im just too spoiled by javascript's map, where I can do anything inside of a context of the map

marble jackal
orchid oxide
#

HUGE

maiden magnet
#

hi
i am trying to make a template sensor which can calculate the date out of weekday, year and calendar week

this is what i have, but it does not work:

  - platform: template
    sensors:
      berechnetes_datum:
        friendly_name: "Berechnetes Datum"
        value_template: >
          {% set januar_1 = as_datetime(sensor.akt_jahr ~ "-01-01") %}
          {% set tag_jan_1 = januar_1.weekday() %}
          {% set erster_donnerstag = januar_1 + timedelta(days=((4 - tag_jan_1 + 7) % 7)) %}
          {% set gesuchter_tag = erster_donnerstag + timedelta(days=(input.wochentag - 4)) + timedelta(weeks=(input_number.kalenderwoche - 1)) %}
          {{ gesuchter_tag.date().isoformat() }}```
north locust
#

I've got a few errors while rendering some template sensor in logs :

Error while processing template: Template<template=({% set alarm_time = as_timestamp(states('sensor.next_alarm')) %} {% set time_now = as_timestamp(now()) %} {% if alarm_time != None %} {{ time_now >= alarm_time }} {% else %} {{ unavailable }} {% endif %}) renders=2>

don't quite know what's wrong with it ...

obtuse zephyr
#

What's states('sensor.next_alarm')?

north locust
#

a time

thorny snow
#

Why is the following selectattr('state'|int, 'lt', 25|int) failing?

{%- set entities = states
  | selectattr('attributes.device_class', 'defined')
  | selectattr('attributes.device_class', 'eq', 'battery')
  | rejectattr('state', 'in', ['unavailable', 'unknown', 'none'])
  | selectattr('state'|int, 'lt', 25|int) 
-%}

Errr

ValueError: Template error: int got invalid input 'state' when rendering template '{%- set entities = states
  | selectattr('attributes.device_class', 'defined')
  | selectattr('attributes.device_class', 'eq', 'battery')
  | rejectattr('state', 'in', ['unavailable', 'unknown', 'none'])
  | selectattr('state'|int, 'lt', 25|int) 
-%}' but no default was specified

I tried adding int(0) on the state, it didn't help. I tried float, no luck. And if I use 'lt' with string, then obviously the filtering is incorrect.
Do I have to use a for loop? 😦

inner mesa
#

this part is wrong:
'state'|int

#

that's trying to turn a string into an integer 🤷

#

and 25|int is turning an integer into an integer

#

there isn't a straightforward way to do what you want

thorny snow
# inner mesa this part is wrong: `'state'|int`

Well, I can't compare strings, the compare will be false. For example, if I use selectattr('state', 'lt', '9') it will list all sensors with battery laver (aka state) of 100 🙂
So, I have to use selectattr on the state attribute in int or float in order for the filtering to be correct. But for whatever reason, it doesn't accept the |int conversion.

inner mesa
#

you're literally trying to turn the string "state" into an integer

thorny snow
inner mesa
#

you can't do that to modify

#

no, literally the string "state"

#

that is a word

#

it is not a number

#

I understand what you're trying to do and there isn't a straightforward way to do it

#

it really depends on what you're planning to do with the entity list you're generating

thorny snow
# inner mesa it is not a number

This is why I make sure I filter out entities where the state is only a number, basically device_class=battery where the state is not unavailable. I checked, the returned list has only numbers in states. Now I want to filter out numbers below say 9 (9% battery), and I need to compare numbers, not strings for that.
The bloody thing doesn't want to convert the state str into a int 🙂

inner mesa
#

I don't think you're understanding

#

'state' is just a string

#

it is not the state of an entity

thorny snow
inner mesa
#

'foo' is also a string, and can't be interpreted as an integer

#

I get that

thorny snow
inner mesa
#

we have discussed creating a filter that allows one to modify the incoming value before a comparison (such as converting it to an integer), but I don't think it exists yet

#

sigh

#

I'm saying that this makes no sense at all

#

| selectattr('state'|int, 'lt', 25|int)

#

do you understand that?

thorny snow
#

nope 🙂

inner mesa
#

ok

#

why do you think it makes sense?

thorny snow
#

I mean, i don't need the 25|int, the int can go away. But it should be able to convert the 'state'|int(0) to an integer where possible and to 0 where not possible. I don't get why this is not working

inner mesa
#

you do not understand at all

#

I keep saying it

#

"state" is just a string. it IS NOT the state of an entity

#

it is a string

#

a string

#

not a number, not a state

#

like "foo" or "tulip"

#

or "whale"

#

you cannot pretend that typing 'state' represents the state of the entity, and then do something to it. it is just a random string

thorny snow
#

ok, how do I pipe and filter out based on state then? is it not {% set entities = states | selectattr('state', 'lt', 25) %} ?

obtuse zephyr
#

It can't be that, as states are strings and your comparison value is an int. There isn't a way using selectattr to map state to a string though and compare it to the comparison value, as Rob mentioned.

#

One way is a loop ... if you need other properties from the object, if you need a count, just map state to an integer and then filter your list

thorny snow
#

I get it, but what is the way then?
And the 'state' in this case is the state. For example this works perfectly:

{% set entities = states
  | selectattr('state', 'eq', 'on') 
%}

{% for entity in entities %}
{{ entity.state }} : {{ entity.entity_id }}
{% endfor %}

I can filter and only show entities that are 'on' or 'off'. So why cant I filter based on numbers, where the state is a number

#

I see, so a for loop is the only way.

obtuse zephyr
#

As I said, it's one way. If you need to list things out like you've got there, that's probably the route you want to take

#

If you just want to say ## of devices have < 25% battery, you can do it using filters

thorny snow
#

apparently I cant, because the comparison can only be based on strings, not on integers 🙂

#

jinja weirdness I guess

obtuse zephyr
#

How about we try this... what are you trying to accomplish

#

End goal

#

It's not Jinja-weirdness, it's order of operations in this case

#

This is literally what you're doing in the template, notice how it's the same error

thorny snow
#

GOAL: I want to get a list of all entities where the battery level is below 15%.
Approach: iterate trough the state database, filter only entites where device_class is battery, filter out entities that are in unnown/unavailable state, the filter only entities where the state (the battery level) is below 15%, and then map that to entitty_id attribute so I get a list of entity_id's which satisfy my criteria above.

Technically, this should work

{%- set entities = states
  | selectattr('attributes.device_class', 'defined')
  | selectattr('attributes.device_class', 'eq', 'battery')
  | rejectattr('state', 'in', ['unavailable', 'unknown', 'none'])
  | selectattr('state'|int(0), 'lt', 15)
  |  map(attribute='entity_id') 
-%}

But it throws an err (see above), saying that I didn't supply a default value when converting the state of the entity from str to int

cursive ice
#

so I know how to do a template for if a device is on, else etc, but I have a water temp on my washing machine that when off or not running it shows water temp as not selected

#

how should the template go for this if anyone has time

clear mist
#

Hey guys, I've got a simple question I can't quite figure out

I've got some code atm that imports a macro, runs some code and spits out a result, as below:

{% set postcode = states('input_number.postcode') %} 
{% set coords = suburbCoords(postcode | int) %}```

This code works and spits out a valid working result for coords, but I want to use it for a rest url and want to do something like add it to the end of a url like www.google.com or whatever

Whenever I try to do something like www.google.com/{{coords}} in dev tools it just has the url and a bunch of white space that never seems to end (on mobile and it takes so long to scroll I've not been able to get to the bottom yet). How can I add it to the end of my url for a rest command?