#templates-archived

1 messages · Page 145 of 1

median pulsar
#

The bot calls any long text post a "codewall"

rain geode
#

I see

#

- platform: template sensors: vapor_deficit: friendly_name: 'vpd in kilo pascals' value_template: >- {% set T = states('sensor.itc_308_temperature')|float %} {% set RH = states('sensor.ihc_200_humidity')|float %} {% set SVP = 0.61078 * e ** (17.2694 * T / (T + 238.3)) %} {% set VPD = ((100-RH) / 100) * SVP %} {{-VPD | round(2) -}} unit_of_measurement: 'kPa'

#

It works but sometime trigger a lot of this error and make spikes in Grafana graphs:

Template warning: 'float' got invalid input 'unavailable' when rendering template '{% set T = states('sensor.itc_308_temperature')|float %} {% set RH = states('sensor.ihc_200_humidity')|float %} {% set SVP = 0.61078 * e ** (17.2694 * T / (T + 238.3)) %} {% set VPD = ((100-RH) / 100) * SVP %} {{-VPD | round(2) -}}' but no default was specified. Currently 'float' will return '0', however this template will fail to render in Home Assistant core 2022.1

#

Is there something I can do to avoid this error? Am I in correct channel for possible help on this? Thank you!

inner mesa
#

Either provide a default when you use |float or use an availability template

rain geode
#

I see, thank you!

inner mesa
olive hawk
#

The dev tools show a "last changed" timestamp, is that an attribute we can somehow read?

inner mesa
#

No, it’s a property of the state object

#

states.sensor.whatever.last_changed

olive hawk
#

attribute, property, same same? 😄 thanks

inner mesa
#

It’s not

#

You access them differently

olive hawk
#

so I guess that's why I can't use it with state_attr? the entity has leading zeros in it's id, so states.sensor.000e9be993a473.last_changed is not recogniced
However, {{ state_attr("sensor.000e9be993a473", "last_changed") }} returns "None"

inner mesa
#

Because it’s not an attribute

#

You have to use [‘00e9….’]

#

some other guy doing the exact same thing

charred badge
#

Evening all, did anyone have any thoughts on this post i did last night. I really struggle with this kind of subject #templates-archived message

olive hawk
#

omg, so close, only half a page up in here 😅

#

weird, states.sensor['000e9be993a473'].last_changed seems to be an empty string (not None)

#

because states.sensor['000e9be993a473'] is None

inner mesa
#

then you have the entity_id wrong

olive hawk
#

Isn't what I can enter in the "states" screen the entity id?

olive hawk
#

according to the entity list, the id is "climate.000393c994df54" so there is even a dot in the id 😆

umbral pond
#

how can I use time templates , to increase the minutes of a time set in an input_datetime by an 'X' amount ?
I 've been pulling my hair trying to figure it out - tried to go a different way by using jinja2 and increasing individual values for hours , minutes while trying to set them using input_datetime.set service but I ended up hitting dead ends having to do too many number and string manipulations to get it right.
So I am falling back to what seems to be the correct approach ... the time templates. But I am not sure if/how they can serve my purpose.

marble jackal
#

Something like this?

{{ states('input_datetime.something') | as_datetime + timedelta(hours=3, minutes=25) }}```
#

That will return a datetime which you can use for input_datetime.set

umbral pond
#

let me try this looks promising

inner mesa
#

so...states.climate['000e9be993a473'].last_changed

umbral pond
# marble jackal Something like this? ``` {{ states('input_datetime.something') | as_datetime + t...

I went to the documentation to understand it first of all (as I'm not familiar with templates very much). So first things first thank you for that. I see what you did , and it should be working , however there seems to be some weird type incompatibility that I cannot explain.

{{ states('input_datetime.vacuum_scheduler_weekdays') | as_datetime + timedelta(hours=3, minutes=25) }}
TypeError: unsupported operand type(s) for +: 'NoneType' and 'datetime.timedelta'
#

I also tried going as_datetime( ... ) and putting the states() argument as a parameter inside ... same thing

#

I mean I don't get it , you are 100% correct. The state of the datetime entity is indeed a string ... and the as_datetime is supposed to get a UNIX formated time string and turn it to something that the timedelta in turn should be able to alter

#

but the machines have a different opinion 😛

marble jackal
meager relic
#

Hi, i need some help (:
When jusing:
{{ (as_local(states.switch.switcher_boiler_34b0.last_updated)) }}
I'm getting:
2021-12-31 07:30:00.762222+02:00
I'm trying to get rid of the seconds, miliseconds and +02:00 text so it will only say:
2021-12-31 07:30
But nothing seem to work for some reason...
i tried using
strptime and as_timestamp but i can't get it to output the text i want.

Any ideas?

pastel moon
meager relic
#

I'm getting this error:
TypeError: float() argument must be a string or a number, not 'datetime.datetime'

#

So it's a float for some reason

#

OK, this works:
{{as_timestamp(as_local(states.switch.switcher_boiler_34b0.last_updated)) | timestamp_custom('%H:%M %d/%m/%y')}}

#

Thank you!

pastel moon
#

np. glad you found it! 🙂

meager relic
#

So i'm trying to have a script that tells me how long was my boiler running last time.
What i thought about doing is retrieving the last time boiler state was changed minute the last --> last time boiler had changed.

So basically it will be when boiler changed to off MINUTE when boiler changed to on = the amount of time it ran.

But i don't think there's a way to get the last --> last updated time right?

Any simple ideas on how to do it?

#

I can probably create a helper that change everytime that the boiler turns on and keep that time.
But i wonder if there's a simple one liner script that can do that calculation without adding more complexity to this

#

i can also create 2 helpers

  1. for when the boiler last turned off
  2. for when the boiler last turned on
  3. create a sensor that has 1 minute the other
    And also keeps the two other fileds (last turned on and last turned off)
    So i'll have a sensor with all those fileds.
    Just wandering if there's an easier way...
pastel moon
#

you could probably store "last" value in a input_text helper, then do the compare to the current

#

if I got this right, that is... 🙂

meager relic
#

emmmm you might be right.
Let me think about it for one sec

charred badge
#

Morning everyone, yesterday (and for last year or so) this was working fine. Today I am getting errors when trying to restart HA or do a config check. ```yaml

  • platform: template
    sensors:
    toaster_cost:
    friendly_name: Toaster Cost £/day
    unit_of_measurement: £
    value_template: "{{ (states('sensor.toaster_energy_today')|float*0.21607))|round(2) }}"```
#

The error is Invalid config for [sensor.template]: invalid template (TemplateSyntaxError: unexpected ')') for dictionary value @ data['sensors']['toaster_cost']['value_template']. Got "{{ (states('sensor.toaster_energy_today')|float*0.21607))|round(2) }}". (See ?, line ?).

#

theres an extra ")"

#

how the fk did that happen, ive not changed this in AGES....

pastel moon
charred badge
#

i just removed the extra ) after the 0.21607 and its solved the error message. Dont know how on earth this has ever worked

#

I wanted to replace the 0.21607 with a variable I declared called var.electric_tariff

#

but when i substitute the number for the variable it complains about float & integer

#

im not very good with templates

pastel moon
#

try type-casting your variable? float("22")

charred badge
#
{{ (states('sensor.speakers_energy_today')|float*('var.electric_tariff'))|round(2) }}```
#

thats what i put into the Template editor

#

get TypeError: can't multiply sequence by non-int of type 'float' as error message

#

what does float 22 mean? (sorry im rubbish with templates)

pastel moon
#

I'm sorry if I am confusing you, trying not to. I would try this "{{ (states('sensor.toaster_energy_today')|(float* float(var.electric_tariff)))|round(2) }}"

charred badge
#

no its ok, just trying to get my head around how it hangs together to try and be self sufficient

#

Get this message TemplateSyntaxError: expected token 'name', got '('

pastel moon
#

Well, without being able to test, I am at loss too, sorry. Hope someone else can spot the issue, good luck!

charred badge
#

cheers and happy new year

pastel moon
charred badge
#

@pastel moon getting there with this template...

#

{{ (states('sensor.toaster_energy_today')|round(2))| float * (states('var.electric_tariff')|round(2)) }}

#

This gives me an output which is correct, but is 0.xxxx in format

pastel moon
#

Oh! states... I should've seen that. Good job!

charred badge
#

need to somehow make it 0.xx

#

guess need to encapsulate the whole expression into a round(2) somehow

#

only been 1 hr of fiddling

olive yacht
#

When adding a template to my config.yaml, can I bring over the exiting properties too?

sensor:
  - platform: template
    sensors:
      mmolbloodsugar:
        friendly_name: "Blood Sugar"
        entity_id: sensor.blood_sugar
        icon: "state_attr('sensor.blood_sugar', 'icon')"
        value_template: "{{ '%.1f'|format(int(states('sensor.blood_sugar')) / 18) }}"

Here, Icon is updated by the integration, but I need to format it into mmol/l instead of mg/dl. I do however want the icon to come through also.

charred badge
#

out of interest, where are you retrieving the blood sugar levels from?

charred badge
#

So the following which provides an output that I can't seem to keep at 2 decimal places only, it is very unlikely that the value would ever be about 1.0 £{{ (states('sensor.toaster_energy_today')|round(2))| float * (states('var.electric_tariff')|round(2,'floor')) }} so far today

#

Sometimes the output is 0.xxxx and sometimes its 0.xxxxxxxx etc

#

i just want it to always be x.xx

dreamy sinew
#

Convert to a number and then round

#

Also, convert both to numbers, do your math and then round at the end so your values are more likely to be accurate

mellow pulsar
#

Greetings! I am using the following to get readings from 2 different oregon scientific weather sensors, using the following:
value_template: '{% if value_json.chan == 1 %} {{value_json.tempf}} {% endif %}'

#

as well as :

#

value_template: '{% if value_json.chan == 2 %} {{value_json.tempf}} {% endif %}'

#

and they are working, except that when the value is for the opposite case for the channel, the value is set to zero.

#

How can I get the value to be ignored and not set if the channel is not for the current temperature? one sensor is outside and one is inside, so it isn't good for them to be bouncing between the temperature and the value of zero. any ideas?

#

Thanks!

inner mesa
#

they're MQTT sensors?

mellow pulsar
#

yes

#

the raw data looks like this: {"lowbatt":0,"chan":2,"tempf":73.220001,"humid":53.000000,"tempc":22.900000,"checker":30841} for the mqtt topic 'tele/ostemp'

inner mesa
#

I wonder what would happen if you just specified the current state of the sensor

#

BTW, you could simply what you have with this:

#

value_template: '{{ value_json.tempf if value_json.chan == 1 }}'

#

then, maybe value_template: '{{ value_json.tempf if value_json.chan == 1 else states('sensor.whatever') }}'

mellow pulsar
#

so in the else statement, it would effectively use the previous value, right? I think i like that

inner mesa
#

see if it works

mellow pulsar
#

thanks, trying now

inner mesa
#

it's a bad idea for a template sensor, but may work here

mellow pulsar
#

if I had been wiser i would have initially had the chan number as part of the topic.. 🙂 I may go there if this doesnt pan out!

inner mesa
#

that would be a better solution if you're controlling it

#

this is an atypical combination of topics and sensors

mellow pulsar
#

right.

inner mesa
#

You can also use an availability_template, but I suspect that that would cause the state to switch to unavailable

mellow pulsar
#

restarting now with the example with the else statement in it.

#

the else states version fixed it, thanks!

meager relic
#

Quick question... i don't get it.. i'm going nuts

{{as_timestamp(states('input_datetime.boiler_last_on')) | timestamp_custom('%H:%M:%S') }}
Results in: 17:32:46

{{as_timestamp(states('input_datetime.boiler_last_off')) | timestamp_custom('%H:%M:%S') }}
Results in: 17:33:04

The second - the first should give: 00:00:18
i.e. {{((as_timestamp(states('input_datetime.boiler_last_off'))) - (as_timestamp(states('input_datetime.boiler_last_on')) ))|timestamp_custom('%H:%M:%S') }}
However, it results in: 02:00:18
What's going on!?
Both entities are date&time objects.

inner mesa
#

Sounds like a time zone issue

meager relic
#

i thought so as well, but both on their own provide the same time zone. i've checked

meager relic
#

That worked...
{{((state_attr('input_datetime.boiler_last_off', 'timestamp')|int) - (state_attr('input_datetime.boiler_last_on', 'timestamp')|int))|timestamp_custom('%H:%M:%S', false)}}

analog coral
#

Hi everyone! Is there a way to auto-populate a group from entities within an area?

inner mesa
#

Yes, by calling group.set with a template

#

But why would you need that? Vs just using the area as is, or just creating a group

analog coral
#

I want to just expose 1 singular entity for all of each room's lights with Google Assistant, if that makes sense. So even if I swap some lights around, as long as the areas are set up correctly in HA then Google will still control the appropriate lights.

inner mesa
#

And GA sees the areas? Or just a group?

charred badge
#

I got my template rounding as I wanted using this ``` value_template: "£{{ ((states('sensor.ninja_xl_energy_today')|float)| float * (states('var.electric_tariff')| float))|round(2,'floor') }}"

inner mesa
#

I would just ignore areas and create a group

charred badge
#

shame ive spent hours fiddling about to do it, all good learning though

analog coral
#

I would like to stick with areas, basically just trying to make it as hassle-free as possible

inner mesa
#

Anyway, group.set with a template that uses area_entities() and an automaton to call that at startup

#

It’s possible, but not straightforward

analog coral
#

I'll fiddle around with that! Thank you for your help! Happy New Years!

umbral pond
# marble jackal What does `{{ states('input_datetime.vacuum_scheduler_weekdays') }}` return when...

Thanks for the inspiration! I managed to get around to it ultimately like so:

    - service: input_datetime.set_datetime
      data_template:
        time: "{{ (strptime(states('input_datetime.vacuum_scheduler_weekdays'), '%H:%M:%S') + timedelta(minutes=10)) | as_timestamp | timestamp_custom('%H:%M') }}"
      target:
        entity_id: input_datetime.vacuum_scheduler_weekdays

Idk if there are redundant filters in the time: attribute however this does exactly what I want.

hazy trench
#

#energy-archived Hello, I have 3 PZEM sensors installed on the 3 phases at the main entry of my house to analyze my electical consumption. In order to have a full view of the consumption, I have a template to add the value of the 3 phases. For some reason, at unknown events, the total value jumps to unrealistic values (in thousands of kWh).

#
  • sensor:
    • name: PZEM Main Energy Total
      unique_id: pzem_main_energy_total
      state: "{{ (((states('sensor.pzem_main_l1_energy') | float(0)) + (states('sensor.pzem_main_l2_energy') | float(0)) + (states('sensor.pzem_main_l3_energy') | float(0))) | float(0) / 1000) | round(2) }}"
      unit_of_measurement: "kWh"

      device_class: energy

      state_class: total_increasing

#

I did comment to 2 last lines. Was is the mistake?

silent barnBOT
solid jay
#

so ive been researching all night and can't find anything on how to make a automation that sends a notification to my phone randomize the message that is displayed on the notification can someone point me in the right direction? I see a bunch of stuff about TTS service and random messages and tried how those people set that up but didn't work for my case.
https://www.toptal.com/developers/hastebin/igabekowoy.yaml

jagged obsidian
#

What is the originating JSON payload

inner mesa
#

You’re missing a space before message:, you should use data: instead of data_template, and just use the notify service directly rather than using a device action

#

@solid jay

inner mesa
#

your indentation is inconsistent

#

two spaces some places, one in others

#

none before title:

silent barnBOT
#

YAML is the mark up language used by Home Assistant, consistent indenting (two spaces per level) is key. Here is a primer, and this explains multi-line templates. For validating YAML see YAML Lint.

solid jay
#

like so?

inner mesa
#

nope

#

I don't know whether templates work with device actions, but it's much more compact to just use the right notify service

#
  - service: notify.mobile_app_xxxx
    data:
      message:'{{ ["Hello Welcome Home", "Welcome Home, Sir", "Good to have you back"] | random }}'
      title: Home Automation
solid jay
#

got it working! thank you

jagged obsidian
#

Define payload on and off in sensor config

limber haven
#

hm, just to confirm something.. Can you use data_templates with Scenes? Im trying to call a dynamitacally created scene related to the name of my switches, but I get an error with this code block ``` - service: scene.turn_on
data:
scene_id: "{{ trigger.event.data.id | regex_replace(find='_switch.*', replace='', ignorecase=False) }}_daylight_lights"

#

Error while executing automation automation.hue_light_remotes_on_variable: extra keys not allowed @ data['scene_id']

inner mesa
#

it's complaining about scene_id, which doesn't look like a valid thing

#

it is for scene.create

limber haven
#

Ahhhh... -.-

#

Yeah, I copied the code and just replaced the create with turn_on, totally missed that

manic epoch
#

Hi all. I'm trying to set up a means to edit a field within lovelace where the value of that field is referenced by an automation. As an example, I can set the temperature from a lovelace card where an automation looking for the value uses the very same value from the other card. I have a helper set up using input_number but I'm not sure how to tie that to the automation in the UI. It seems I can only choose one or the other (thermostat or input_number helper) where I want to really use both (use input_number as value for thermostat). Am I missing something?

manic epoch
#

aw heck, I don't even need to do this. If I set up a single entity to climate.set_temperature it achieves the same exact thing as the whole helper idea anyway. This is basically a built in alternative. Nevermind!

teal umbra
#

Can someone please explain why this isn't working

[[[
    if (light.d_g_kitchen.state == 'on'){
      return `<ha-icon
        style="height: 20px; color: black"
        icon="mdi:lightbulb">
        </ha-icon>`
    } else {
      return `<ha-icon
        style="height: 20px;"
        icon="mdi:lightbulb-outline">
        </ha-icon>`
    }
]]]
inner mesa
#

light.d_g_kitchen.state isn’t the way to get the entity state

teal umbra
#

custom button card

inner mesa
#

The docs have lots of examples for getting the state

#

Exhibit A:

#

  label: >
    [[[
      return 'Other State: ' + states['switch.skylight'].state;
    ]]]
teal umbra
#

Thx i will try again

inner mesa
#

You also need to surround the HTML in backticks, and shown in the docs. It’s JavaScript

teal umbra
#

It is working now 🙂 Thx @inner mesa

round hill
#

Having difficulty with simple template created to convert units from gram to lbs:

#

template:

  • sensor:
    • name: "Kiki's Weight"
      unit_of_measurement: "lbs"
      unique_id: "sensor.kiki_s_weight"
      state: "{{(states('sensor.t3_100006205_pet_weight') | float * 0.00220462) | round(2)}}"
#

Will about once per minute return a momentary zero for value in history trend, original sensor does not show these zeroes

inner mesa
#

I suspect that the sensor is becoming unavailable or otherwise reporting something non-numeric. You'd also see something in the log for that

round hill
#

Yep, the log has a detail stating 'float' got invalid input 'unknown', is there an easy way to change to refer to previous value rather than '0'?

inner mesa
#

You could add that the source sensor as a trigger and use trigger.from_state.state

#

As the default. |float(trigger.from_state.state)

round hill
#

Thanks, I haven't played around with trigger before so I give that a read/try

round hill
#

I have this in the configuration now:

#

template:

  • trigger:
    • platform: state
      entity_id: sensor.t3_100006205_pet_weight
      sensor:
    • name: "Kiki's Weight"
      unit_of_measurement: "lbs"
      unique_id: "sensor.kiki_s_weight"
      state: "{{(states('sensor.t3_100006205_pet_weight') | float(trigger) * 0.00220462) | round(2)}}"
#

It seems to no longer return the 0 in the trend, but still getting log errors

#

Error rendering state template for sensor.kiki_s_weight: TypeError: unsupported operand type(s) for *: 'dict' and 'float'

inner mesa
#

You didn't use the code that I provided

round hill
#

resetting now

inner mesa
round hill
#

I had tried it, but didn't wait long enough for the poll refresh (2 minutes), so it was not returning any value

inner mesa
#

It was also incorrect

round hill
#

With

#

state: "{{(states('sensor.t3_100006205_pet_weight') | float(trigger.from_state.state) * 0.00220462) | round(2)}}"

#

I am now getting the log error

#

Error rendering state template for sensor.kiki_s_weight: TypeError: can't multiply sequence by non-int of type 'float'

inner mesa
#

Oh, add |float

#

state: "{{(states('sensor.t3_100006205_pet_weight') | float(trigger.from_state.state|float) * 0.00220462) | round(2)}}"

round hill
#

Thanks, trying now

inner mesa
#

It will still be a problem if you get more than one in a row

round hill
#

Template warning: 'float' got invalid input 'unknown' when rendering template '{{(states('sensor.t3_100006205_pet_weight') | float(trigger.from_state.state|float) * 0.00220462) | round(2)}}' but no default was specified. Currently 'float' will return '0', however this template will fail to render in Home Assistant core 2022.1

inner mesa
#

You're probably getting more than one in a row

#

You should fix the source sensor

round hill
#

I'll look into that, thanks. I'm guessing the source is polling every 2 minutes and it normally returns the prior value (and briefly is unavailable while polling)

round hill
#

I'm guessing the dev can quickly fix the sensor issue since it looks like the rest of the sensors only update with value changes instead of with every poll

#

Thanks again @inner mesa

solid jay
#

I want to display additional weather attributes/states computed from a formula

marble jackal
#

@round hill you could also provide an availlibility template and state is should only be available if the source sensor is available

pastel moon
#

Hi guys! This morning something odd happened. isoweekday() no longer works? If I instead use weekday() I'm back in operation... Using it in this template {% set day = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] %} {{ day[now().weekday()] }}

pastel moon
#

Ok. Somehow it was the list that did not return correctly. Changing the list into this syntax resolved it tho {% set days = {6: "Saturday", 7: "Sunday"} %}

calm tinsel
#

Hi,

need some I getting values from api, they coming through as a string instead of numeric.
how can I go about changing it?

inner mesa
#

|float

small hatch
#

hi all, is there an way to template to count the total number of calendar event for the next 12 hours.

#

will actually more than count. And the end I want to pull all the event for the next 12 hrs and read in my current tts morning briefing

#

so far i can going get event message for the next incoming events and nothing after that.

brazen stone
round hill
#

Yeah, adding the default float(0) to 2nd float fixed my log warning @inner mesa @marble jackal
So my unit conversion template seems to be working perfectly without log issues with the trigger fix

drifting plaza
#

Hi , im trying to include template sensors on my configuration in order to use them on the energy screen . So far i was not able to make the template.yaml file to load properly , and there are no visible errors detected by the config check . just the message template integration could not be set up , any ideas what the cause may be ?, tks

solar field
#

Sorry I know this message is ancient, just now getting back to this after all the holiday madness... yeah, feed count is an entity. I thought I could use a numeric state for that, but if I'm reading the docs right numeric state is only useful when you're crossing a given threshold. I guess that means I could still use it but it wouldn't be as simple, e.g. I'd have to set up separate ones for when it crosses 1 time fed, 2 times fed, 3 times fed for the day etc. which I would need to use a template in the trigger to accomplish. Does that sound right?

dreamy sinew
#

you can use a numeric state trigger with no params other than the entity. use a template condition or choose action to figure it out from there

#

{{ trigger.to_state.state|int(0) > trigger.from_state.state|int(0) }}

glacial matrix
#

morning all, I'm trying to create a template that will calculate my bmi. the formula is weigh in lbs / height in inches squared multiplied by 703, butI cannot get my template to work.

#

{{ (states('input_number.weight_karl_lbs') | float / (states('input_number.height_karl_inches')*(states('input_number.height_karl_inches'))) *703) }}

#

the error i recieve is:
TypeError: can't multiply sequence by non-int of type 'str'

i'm just not sure how i can fix it now.

jagged obsidian
#

turn the other two values into float

glacial matrix
#

sorry, how do i do that?

#

hang on.

jagged obsidian
#

| float

glacial matrix
#

great. Thank you! didnt realise it was a s simple as putting that after each entitiy.

marble jackal
#

If you want to avoid warnings/errors in your log, you should also provide a default value (eg | float(0))

glacial matrix
#

Thank you. Managed to get that doing the calculations i need.#

heady cosmos
#

Hey guys, Pretty new to all this home assistant, really excited. By any chance is there a free/outsourced template for Lovelace or something I can at-least start from?

hexed wing
#

which you can use as the starting point (it will ask if you want to keep the existing dashboard when you take control)

heady cosmos
#

Yeah I chose the “no option” and realised that was a mistake and now I have no idea how to get it back 🤦‍♂️

hexed wing
#

You can create a new dashboard in the configuration panel

#

a new dashboard will by default be the auto generated one

inner mesa
#

Or you can go into the raw editor, delete everything, and save. But we're well into #frontend-archived territory

sly urchin
#

Is it possible to parse a json Webhook that is multipart? Specifically for plex webhooks. I saw a post from '17/'18 saying HA didn't support it and I can't see that it does now? Thanks

sweet veldt
#

Good morning everyone! Yet another HA Newbie here... so far I'm enjoying the experience although I get sucked into a lot of black holes! I hear that's par for the course... I've got a few questions if that's ok... first one is a custom sensor I setup for my litter robot which "works". It feels like I did it the wrong way however and I'm hoping someone can guide me in cleaning it up:

#

#Litter Robot Sensor Over Torque
template:
sensor:

  • name: "Litter Robot Status Code"
    state: =
    {% set litterrobotstatus = state_attr('vacuum.litter_bear_litter_box', 'status_code')%}
    {{litterrobotstatus}}
#

I don't think I have it written the right way although it is functional.. but I think that due to the way I'm writing it, it is stopping me from creating other customer sensors (that read attributes)

sly urchin
#

I think you can replace it with just state: = {{ state_attr('vacuum.litter_bear_litter_box', 'status_code') }}

sweet veldt
#

@sly urchin Trying that now... is the other part ok though? the way it's structured? template, sensor, name i mean

sly urchin
#

I don't get discord formatting but the link above should be fine

#

I'd use > rather than = actually

sweet veldt
#

@sly urchin thank you.. I'm trying that and attempting to clean it up like you wrote... Afte that I'll try to add my second sensor and see if it gives me issues like before

sly urchin
#

Is there anyone who can help with my post above regarding a mutli part json webhook from plex? I am struggling to extract the relevant pieces of info. Thanks

inner mesa
#

that formatting isn't quite right

#

if you're putting it all on the same line, it would be this:

#

state: "{{ state_attr('vacuum.litter_bear_litter_box', 'status_code') }}"

#

">" is only used if you're introducing a multiline template

sweet veldt
#

@sly urchin @inner mesa Indeed, when I do it the with the proper formtting that HolyBift sends me, it breaks it.. I was able to rework it a bit to make it work again though buy doing this:

#

#Litter Robot Sensor Over Torque
#template:

sensor:

- name: "Litter Robot Status Code"

state: = {% set litter_robot_status_code = state_attr('vacuum.litter_bear_litter_box', 'status_code')%} {{litter_robot_status_code}}

#

(minus the # )

#

If I don't put in % set then it doesn't work (or well, then I'm not reading the info right lol)

inner mesa
#

that's just broken

sly urchin
#

You've mixed and matched there

inner mesa
#

use the code that I provided

sweet veldt
#

@sly urchin @inner mesa So, I've used the code provided but now it says (and I think it makes sense): entity not available: sensor.litter_robot_status_code. I'm thinking that makes sense because I haven't created a custom sensor called litter_robot_status_code. What I'm trying to do (which worked with my sucky code) is to add a status and when it has a certain value (OTF specifically), it will turn off my smart plug and turn it back on (the only way to fix that error according to support). With my bad code, I could see this:

#

oops..seems I can't post a screen cap lol

inner mesa
#

I assumed that the entity and attribute that you were using actually existed

sweet veldt
#

@inner mesa No, I'm sorry.. I need to create a custom sensor.. I'm actually trying to do that with multipel different devices but I can't get past the one I posted lol

#

@inner mesa I wrote it in the original thread but maybe I used the wrong words to express myself clearly lo

inner mesa
#

please stop tagging me

sweet veldt
#

oh sorry

inner mesa
#

it is unnecessary

#

I just jumped in when I saw some broken code posted

sweet veldt
#

sorry bad code

final parcel
#

is it possible in template to cut part of entity name? Lets say trigger will be climate.trv and i need to change the part "climate" into switch. so it become switch.trw.

inner mesa
#

of course. I recommend checking out the template docs...

#

{{ "climate.foo".replace('climate', 'switch') }} -> switch.foo

final parcel
#

where did you learned all the stuff?

slate ermine
#

I just stumbled upon this in the HASS logs:

2022-01-03 19:30:23 WARNING (MainThread) [homeassistant.helpers.template] Template warning: 'multiply' got invalid input 'unavailable' when rendering template '{% if is_state('sensor.tasmota_kuhlgerate_energy_total', 'unknown') %}
  Unknown
{% else %}
  {{ '{:.2f}'.format(states('sensor.tasmota_kuhlgerate_energy_total')  | multiply(0.19)) }}
{% endif %}' but no default was specified. Currently 'multiply' will return 'unavailable', however this template will fail to render in Home Assistant core 2022.1

This is the little script that calculates the whole kW usage to a properly readable Euro value. However I really have no idea what's wrong here as I also just found this exact thing in a forum and edited the values... Could someone help me? I already found the forum entry explaining how to "fix" it but I still am just... stuck 😓

mighty ledge
#

just add a default

#

to multiply

slate ermine
#

Or maybe there's a better solution to this in general, as I just want to convert one value to Euro. Maybe this is too complicated to begin with anyways.

slate ermine
#

And since then it work(s/ed) ^^"

mighty ledge
#

check the 'confused about defaults' pin

#

it describes how to add defaults to existing methods & filters, multiply is a filter

inner mesa
slate ermine
# mighty ledge to multiply

I know I sound really stupid but I don't understand this much at all ^^"
So... simply editing multiply(0.19) to multiply(0.19, default=0.19) should fix this?

mighty ledge
#

yep

slate ermine
#

I've read the post but tbh it's just confusing me a lot more.

#

Ah, good.

mighty ledge
#

but default is for the value you're multiplying against

slate ermine
#

The "perks" of not being a programmer nor understanding any of the terms much at all lol

mighty ledge
#

so when states('xyz') fails to convert to a float, it will use the default

#

do you want to multiply 0.19 * 0.19 if the state of sensor.tasmota_kuhlgerate_energy_total fails to convert?

slate ermine
#

But to my understanding a simple state of 0.19 which will never fail to be a float could also just be ignored? I mean, I understand that this is rather for cases that "in case this sensor gives me a wrong value back" and all.

#

Or am I understanding this wrong

mighty ledge
#

you are

slate ermine
#

Hm.

mighty ledge
#

your code is

#
value | multiply(value_that_youre_multiplying_value_by)
#

essentially

#
value * value_that_youre_multiplying_value_by
slate ermine
mighty ledge
#

the default is for value, not value_that_youre_multiplying_value_by

slate ermine
#

Aaah

#

okay

#

Bit confusing at first then lol

mighty ledge
#

well, it's only confusing because you're using multiply

#

you could just... multiply

#
{{ states('sensor.tasmota_kuhlgerate_energy_total') | float * 0.19 }}
slate ermine
#

I mean, as said I found that script online somewhere ^^" I really have no idea about Templates whatsoever as you may already could guess by me being confused by this simple stuff :D

mighty ledge
#

but you still need to specify a default for float

#

states are strings i.e. letters. you can't multiply letters and numbers. So you have to convert the letters to numbers

#

that's what float does

#

multiply also does this for the user, but as you can see, it's confusing.

slate ermine
#

So | basically just "gives" the state of the sensor to float for it to convert it to a proper number, then multiplies it

mighty ledge
#

| means "apply filter"

#

you're filtering the letters into numbers

#

🤷‍♂️

#

you could also write it like this...

#
{{ float(states('...')) * 0.19 }}
#

but you still need a default for float

slate ermine
mighty ledge
#

Yep

#

It doesn’t work for every filter or function

#

But you can find out which do what in the docs

slate ermine
#

Yeah, tho thanks for explaining it a bit. Never really looked much into this since I never needed it and also a bit confusing.

#

Not even sure if this is the "most elegant" way to do things, it simply converts a value my Tasmota plug gives me into Euro for Today, Yesterday and All-In-One values. But that's out of the scope for Templates then of course.

mighty ledge
#

If you have used macros in excel, it’s the same crap minus the {{ }} and {% %}

final parcel
#

How can i check if this works in Template editor? {{ state_attr('trigger.entity_id', 'current_temperature') > state_attr('trigger.entity_id', 'temperature') }}

#

seems it do not

mighty ledge
#

Also, trigger is an object. Putting in quotes makes it a string

final parcel
#

oh

#

this should work right {{ state_attr( trigger.entity_id, 'current_temperature') >= state_attr( trigger.entity_id, 'temperature') }}

inner mesa
#

Probably. As long as it's in the action of an automation and the automation triggers

final parcel
#

it is in the condition...

#

To be precise condition template

mighty ledge
#

It’ll work if your triggers have entity_ids

#

Every trigger*

#

If you have a time trigger it won’t work

final parcel
#

I have it but it doesn not work :/

silent barnBOT
final parcel
#

always chooses default option

#

of course it will not work if i trigger it 😄

#

sorry guys

marble jackal
#

Both triggers have entity_ids, so the template should work.
If you want to test it in the template editor, you can do something like this:

{% set trigger = { 'entity_id' : 'climate.radiator_loznice' } %}
{{ state_attr( trigger.entity_id, 'current_temperature') >= state_attr( trigger.entity_id, 'temperature') }}
civic mortar
#

I added a custom switch, to toggle my alarmsystem on and off (I use that variable in node red)

switch:
  - platform: template
    switches:
      alarmsystem:
        turn_on:
          service: switch.turn_on
          target:
            entity_id: switch.alarmsystem_on
        turn_off:
          service: switch.turn_off
          target:
            entity_id: switch.alarmsystem_off

But why do I have then on the dashboard this lightning icons?

#

and not a regular switch like another cards

mighty ledge
#

Because you didn’t provide a value_template

#

The state is determined by the template provided by the value_template field

#

It doesn’t know the state, therefore is just provides you with on or off buttons

civic mortar
#

so I need a sensor template? Cant find a "value_template"

mighty ledge
#

What do you mean “can’t find a …”

civic mortar
#

ok sry I found it. https://www.home-assistant.io/integrations/template/
But I don't understand this now ... I have now defined a switch and this switch is in the end a entry ( I can perfectly switch from off to on and in node-red I get the state correctly) If I add now a sensor, why should this affect the dashboard ...

#

I tried a sensor, but that didnt worked

inner mesa
#

You're overthinking it

civic mortar
# inner mesa You're overthinking it

I think this is often my problem with home assistant ... I have still a problem / bug with my total power consumption from a measure device. I searched in the whole source code from the integration why this can happen ... didn't found the reason yet ... Maybe I have to read the whole documentation from HASS including the integration docs

mighty ledge
#

what's the bug..

civic mortar
mighty ledge
#

the state is determined by the value_template

#

if your template is wrong, the state will always be wrong

foggy night
#

Hey guys I'm having somewhat of a problem controlling my lights. The setup is as follows: All my lights are controlled by a Siemens LOGO which I control through Node Red. All lights exist inside HASS as template lights and input booleans. the boolean corresponds to the current state of the light and is defined as such. node red listens for the events and triggers a variable inside the logo which turns on a relay. Node red reads this change and updates the input boolean to have the correct value.

        unique_id: light_bedroom
        friendly_name: Licht Slaapkamer
        value_template: "{{states('input_boolean.light_bedroom')}}"
        turn_on:
          event: light_bedroom
        turn_off:
          event: light_bedroom```

Everthing works fine when I use the lights individually either from HASS or pressing the switches inside my home. Updates instantly and has been working for over half a year without any issues. Now this issue is when I want to update more than one light at once, for example turn on/off all the lights in a room. Because this just inverts the state of all lights, due to the turn on and off event being the exact same thing.
The PLC operates completly seperatly from hass which is a hard requirement as I want my lights to function as normal even when my HASS instance could be dead.
Inside the LOGO the logic is that if a Pulse is detected on the variable the corresponding output relay is switched on/off.
The problem is that HA calls a turn off command for lights that are already turned off, which somewhat makes sense, just not in my case 😄
civic mortar
#

I was able to set the state from off to on and vise versa in the dev tool

#

and the state was displayed correctly on the dashboard

silent barnBOT
nimble steppe
#

I did find a template i think has been written by petro so i am trying to get to work but cant get it to work as my Yaml knowlage is minimale..
i have a template sensor i am trying to get to put out 5 states open, closed, closing, opening and sensor error. ( 4 states works but not closing)
Setup:
i have 2 binary sensors so giving input if door is open or closed and i want 2 "fake" between status opening and closing when sensor goes between the states open_on and close_on.
But i cant get the templaet to work properly, after the state open it do not go to state closing after the binary contact for open_on goes false/off. (it then goes back to opening and not closing)

marble jackal
#

What if you try

      {% elif close_on and not open_on %}
        closed
#

Or

{% elif (not open_on) and close_on %}
nimble steppe
#

no still the same, but will it not be this part of the template so changes the "fake" states betwen closing and opening?
{% else %}
{% if is_state('sensor.garage_door_2_status', 'open') %}
closing
{% else %}
opening
{% endif %}

marble jackal
#

Oh sorry, I misread. I though closed was not working, but it was closing

#

If I understand correctly, the state should be closing or opening when both binary_sensors are off

#

and it should be closing when the previous state was open, and opening when the previous state was closed

nimble steppe
#

if i have understand the template right the state shall change to open and close when binary contacts are triggerd, and that {% if is_state('sensor.garage_door_1_status', 'open') %} statment will trigger the next fake state when one of the binerys goes false/off.. but i cant read code so im on thin ice hehe

#

yes as you write is how i have understand this template to work

marble jackal
#

Could you check in devtools > States if the entity_id of this sensor is actually sensor.garage_door_2_status

nimble steppe
#

entity_id is: sensor.garage_door_2_status copyed from dev tools

marble jackal
#

And if the door is acutally closing, the state shown is probably opening right?

nimble steppe
#

the sensor is not connected to the door, i have it right her with me so i can trigger it as i want. Green wire was the idea of closed and yellow was open. and that is what so is showing when i trigger the binarys. ( it is a fibaro smart inplant)

marble jackal
#

Okay, but what happens then if you simulate the closing of the door, what does your sensor return in that case

nimble steppe
#

if i trigger the binary for close door (green wire) status is closed, if i relase binery it goes to opening, then when i put binary sensor on for open door (yellow wire) it goes to state open. ( so far it works fine) and if i then relase binary for open (yellow wire) it goes to state opening ( her it was supose to go closing). The error state works to if i try both binary at same time it says sensor error.

#

dubbel checked from dev tools that yellow wire is the binary_sensor.garage_door_1_open this goes on

marble jackal
#

Okay, then the part which goes wrong is this {% if is_state('sensor.garage_door_2_status', 'open') %}

Could you stimulate the open state, and check what this returns in the template editor
{{ is_state('sensor.garage_door_2_status', 'open') }}

mighty ledge
#

had to update link, template got cut off.

#

I'm sure you could simplify the event stream template to just

- sensor:
  - name: Garage Sensor Events
    unique_id: garage_sensor_events
    state: >
      {%- set a = is_state('sensor.a', 'on') %}
      {%- set b = is_state('sensor.b', 'on') %}
      {%- if a and b %}error
      {%- elif not a and not b %}transition
      {%- elif a and not b %}open
      {%- else %}closed
      {%- endif %}
#

either way, to avoid circular references, you'll need 2 sensors. IIRC the guy in that thread only wanted one... So I made 1 sensor.

#

2 sensors is more robust and will not produce errors

foggy night
#

I have these template lights, but I want to prevent turn_on/turn_off actions to fire the event if the state of the corresponding boolean is on/off. I've found there is a condition property but I'm not sure how to combine these with the event property.

light:
  - platform: template
    lights:
      light_desk_upstairs:
        unique_id: light_desk_upstairs
        friendly_name: Licht Bureau Boven
        value_template: "{{states('input_boolean.light_desk_upstairs')}}"
        turn_on:
          event: light_desk_upstairs
        turn_off:
          event: light_desk_upstairs
mighty ledge
heady cosmos
#

This is going to sound really lazy but is there any free dashboard templates out there that I am able to have a play around with I have not long started and just looking for something to get me started mainly

mighty ledge
heady cosmos
mighty ledge
#

this section is for templating

#

with jinja and yaml

#

this is a template: "{{ do_something('xyz') | something_else }}"

#

and yes, you'd be hand editing everything. You should just use the auto front end. If you want to play around, make another dashboard where you can add things in. Otherwise starting from some one elses UI is fruitless because you'll have to edit the entire thing.

final parcel
#

Hello. I need an automation to be triggered by numeric state change but it is being triggered just by not change but even by update by the same number. To avoid that I would need to make to automation to run only each three minutes but I need to leave the triggers there. Is it possible to solve it by condition to template? How please? 🙂

foggy night
mighty ledge
heady cosmos
sly urchin
#

Can anyone help extract a webhook that starts as such? Thanks
data: __type: <class 'multidict._multidict.MultiDictProxy'> repr: >- <MultiDictProxy('payload': bytearray(b'{"event":"media.pause",

mighty ledge
sly urchin
#

From a plex webhook

#

I am stuggling to find any information on it like usual templates

mighty ledge
sly urchin
#

Yes

mighty ledge
#

you want the trigger.json

sly urchin
#

If I use {{ trigger.json }} then it just spits out the whole thing yes. I'm wondering if I can actually extract from it like json i've come across before

mighty ledge
#

yes, but you have to use trigger.json

sly urchin
#

Sorry I don't understand, use it how?

mighty ledge
#

what have you seen before?

sly urchin
#

I can make it print the whole webhook by just using {{ trigger.json }} in the message but for a sonarr webhook for example I can use {{ trigger.json.level }}: {{ trigger.json.message }}

mighty ledge
#

ok then, what's the problem, it's the same thing

#

if you aren't getting trigger.json, then that would mean your result isn't json

sly urchin
#

I get trigger.json but the attributes I'm trying either don't work or i'm doing it wrong

mighty ledge
#

what are you getting back from trigger.json then

#

again, what you've posted is not trigger.json

sly urchin
#

Oh sorry two secs

mighty ledge
#

dude, you have to post the entire thing

#

not snppits of it

#

can't help with snippits

sly urchin
#

that's with some formatting trying to split it sorry

#

so {{ trigger.json }} emits this....

#

Ah it's embedded all my info taking ages to clense so I've passworded and pmed you sorry for the long

mighty ledge
#

it's still cut off

sly urchin
mighty ledge
#

there is no ending

#

therefore I can't format it to view the shape

sly urchin
#

That could be telegram snipping it

#

the last link is from the show trace

#

same pw

mighty ledge
#

that's still not json, that's a repr of the python object

#

if plex is cutting off the payload, then there's nothing you can do

sly urchin
#

Yes this will be all that's being sent from plex, I can't change it in there at all

mighty ledge
#

I'd need to see what's fully in trigger.json, not trigger.data

sly urchin
#

I don't know how else I can see that

#

I'll give plex a http test url and send rsult

mighty ledge
#

paste that pastebin into the formatter and format it

#

what info are you trying to get?

#

for example, if you wanted "event"

#

it would simply be trigger.json.event

#

however if you want metadata

#

it depends on what you're trying to get

sly urchin
#

Oh

#

I was using trigger.data the whole time

#

Error: Error rendering data template: UndefinedError: 'dict object' has no attribute 'json'

#

So is it JSON nested inside plain data? In basic terms

mighty ledge
#

the json attribute will only be populated if it has valid json

#

is that error occuring when you use {{ trigger.json }} or {{ trigger.data.json }}

sly urchin
#

when using `{{ trigger.json.event }}'', but using {{ trigger.json }} it doesn't show anything the message just sends with the icon no text

mighty ledge
#

Then the information being sent over is not json

#

again, trigger.json only exists if it's actually json

sly urchin
#

Right I understand, so is it possible to 'parse' the trigger.data to grab the things I'd like (user , device, title, episode)?

mighty ledge
#

it is but it's not easy

#

you have to use regex or split the string

#

both can be complicated

sly urchin
#

Yep I got as far as finding a split example but you are right it is complicated. Where should I start? 🤣

mighty ledge
#

start with the word you want and split the string based on that

#

with regex, you'll need to fart around. It's a whole string parsing language

sly urchin
#

Ok thanks very much for your help thus far, I've just realised you're the author of some posts i'm reading on HA forums too lol

mighty ledge
#

Been here a looooooooong time

sly urchin
#

I've probably been using HA 4 years now and every time I go to change anything I learn something new!

#

{{ (trigger.data.split("event":[?] }} is this on the right line? Does it literally split by number of characters? My goodness I thought templates were difficult

modest sparrow
#

So, I have a question I can't figure out. I've added an template sensor which determines the active speaker in a pool of Google Homes. the state is simply the name (media_player.googlehome8007). However, I would like to create a 'template' media_player which I can use in my lovelace cards. Any idea?

chilly light
marble jackal
#

You are missing an } at the end

#

The template should be closed with }}, you only have one }

chilly light
sonic nimbus
#

how to check if my variables has a value, in order to avoid some errors and warning in my logs

#
fields:
  variable1:
    description: 'speed of wled effect'
    example: '100'
sequence:
  - choose:
    - conditions: '{{ variable1 is defined }}'
      sequence: ...```
#

I saw somewhere this is defined but Im not sure..

marble jackal
#

Should work, but in that case it will also return true if the variable is [] or ''. If you don't want that you can use {{ True if variable1 else False }}

slate tundra
#

is there a way to sum up 41 sensor that contain some repeating keywords in name (so i can clearly use regex) without naming every single one of them and add a + after each one
basically i do not want this:

{{ (states('sensor.server_room_outlet_1_energy_power')|default(0)|float + states('sensor.server_room_outlet_2_energy_power')|default(0)|float)|round(3) }}
marble jackal
#

Do they all end with _energy_power

slate tundra
#

yes

#

and they all contain outlet also

#

so easy to regex them

#

but i do not know the format i'd use

marble jackal
#

The | default(0) is not needed anyway, you can use | float(0) to use 0 as default

slate tundra
#

will do

#

so any idea how to accomplish this?

#
{{ (states('sensor.server_room_outlet_1_energy_power')|float(0) + states('sensor.server_room_outlet_2_energy_power')|float(0))|round(3) }}
#

i've change it to this for now

marble jackal
#

Something like this:
{{ states.sensor | selectattr('entity_id', 'search', 'energy_power') | selectattr('entity_id', 'search', 'outlet')| map(attribute='state') | map('float', default=0) | sum | round(3)}}

slate tundra
#

this actually works

marble jackal
#

I know

slate tundra
#

very nice

#

thanks man

#

Template loop detected while processing event: <Event state_changed[L]: entity_id=sensor.total_sockets_consumption, old_state=<state sensor.total_sockets_consumption

#

sad story

#

no idea why

#

since in template on test worked ok

#

skipping template render for Template[{{ states.sensor | selectattr('entity_id', 'search', 'energy_power') | selectattr('entity_id', 'search', 'outlet')| map(attribute='state') | map('float', default=0) | sum | round(1)}}

#

😦

marble jackal
#

But does it return a result?

slate tundra
#

yes

marble jackal
#

Well, I think it is because it's a sensor itself, so it is included in states.sensor. but after that it is filtered out, so it doesn't matter

slate tundra
#

yah i took special care not to include any of searched attributes

#

so i do not include this sensor also

marble jackal
#

Maybe if you do it like this it won't give this warning:

{% set energy = states.sensor | selectattr('entity_id', 'search', 'energy_power') | selectattr('entity_id', 'search', 'outlet')|  map(attribute='entity_id') | list %}
{{ expand(energy) |  map(attribute='state') | map('float', default=0) | sum | round(1) }}
slate tundra
#

let me give it a try

#

oh yah

#

seem if you make a list and parse that it works

#

no more warnings

slate tundra
#

@marble jackalcan u please point me in the right direction to learn more template-ing in general?

marble jackal
#

There are some pinned links on this channel

slate tundra
half pendant
#

I'm trying to create a template for all my doors and windows. Basically i want if all are closed i want the state to be Closed, if one is open it should be the name of that sensor (or something readable) and if multiple are open it should say "multiple open". How can i achieve this?

marble jackal
#

Just create a group

#

Oh, the multiple open will not work then. But you can not template the name of the sensor, only the state

hollow smelt
#

Hi! Does anyone could help me to tell what is wrong with the expression below?

- service: script.activate_alexa_custom_skill_notification
  data_template:
    text: >
      Espere! As janelas
      {% set windows_area = { "binary_sensor.janela_do_quarto_contact": " do quarto", "binary_sensor.janela_da_suite_contact": " da suíte", "binary_sensor.janela_da_varanda_contact": " da varanda" } %}
      {{ [windows_area[k] for k in windows_area.keys() if is_state(k, "on")]|join(", ") }}
      ficaram abertas
    event_id: "close_windows"
    response: {}
    alexa_device: media_player.echo_dot_sala

The line that is causing the error is:
{{ [windows_area[k] for k in windows_area.keys() if is_state(k, "on")]|join(", ") }}
I am receiving this message:

Invalid config for [automation]: template value should be a string for dictionary value @ data['action'][1]['data_template']. Got None.

silent barnBOT
#

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

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

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

arctic sorrel
#

data_template is long dead, it's just data

marble jackal
#

What are you trying to achieve with this template?

hollow smelt
#

I have a list of key:value pairs (entity_id:area)
I would like to filter the values based on the state of the entity id (key) and join its areas (value)

#

I thought I could use python...
That is why I used [windows_area[k] for k in windows_area.keys() if is_state(k, "on")]

#

Then I saw mentions about jinja2 in the docs and don't know whether there is some equivalent to do what I need

hollow smelt
#

The expected message translated would be similar to this:

"Wait! The windows from room, bathroom, kitchen are open"

"room, bathroom, kitchen" is the dynamic part that is causing the error

marble jackal
#

Check the template docs in the pinned post. There is actually a function to retrieve the area_name:
{{ area_name('entity_id') }}

hollow smelt
#

in my case, it isn't the area exactly because of my language that requires different preposition for each area

In portuguese, the message would be:
"Espere! As janejas do quarto, da suíte, da varanda ficaram abertas"

"do quarto, da suíte, da varanda" is the dynamic part

#

I think the biggest problem I have is how to filter a list using jinja2

#

based on the condition is_state("entity_id", "on") or similar

hollow smelt
marble jackal
#

{{ expand(windows_area.keys() | list) | selectattr('state', 'eq', 'on') | map(attribute='entity_id') | list }} should return those which are on

half pendant
marble jackal
half pendant
#

Okey but it wont show which one?

hollow smelt
marble jackal
half pendant
marble jackal
# half pendant Any guidance on how that would look?

Something like this:

{% set open = states.binary_sensor | selectattr('attributes.device_class', 'in', [ 'door', 'window' ]) | selectattr('state', 'eq', 'on') | map(attribute='attributes.friendly_name') |list %}
{{ open | join if open | count == 1 else 'multiple' if open | count > 1 else 'closed' }}
half pendant
#

This is how the template looks.


      doors_and_windows:
        friendly_name: 'Doors and windows'
        value_template: "{% set open = states.binary_sensor | selectattr('attributes.device_class', 'in', [ 'door', 'window' ]) | selectattr('state', 'eq', 'on') | map(attribute='attributes.friendly_name') |list %}
{{ open | join if open | count == 1 else 'multiple' if open | count > 1 else 'closed' }}"
hollow smelt
#

@marble jackal
I wasn't able to retrieve windows_area back again after all those filters applied

I did this:

Espere! As janelas {% set windows_area = { "binary_sensor.janela_do_quarto_contact": "do quarto", "binary_sensor.janela_da_suite_contact": "da suíte", "binary_sensor.janela_da_varanda_contact": "da varanda" } %}{% for k in windows_area.keys() %}{% if is_state(k, "on") %}{{ windows_area[k] }}, {% endif %}{% endfor %}ficaram abertas.

The only side effect is an additional comma at the last item but it doesn't make difference to Alexa.

Actual result: Espere! As janelas do quarto, da suíte, da varanda, ficaram abertas. (satisfatory)
Expected result 1: Espere! As janelas do quarto, da suíte, da varanda ficaram abertas. (acceptable)
Expected result 2: Espere! As janelas do quarto, da suíte e da varanda ficaram abertas. (my dream)

inner mesa
#

the first two look identical to my American English eyes

hollow smelt
silent seal
#

I believe they are aside from a comma

inner mesa
#

oh, I missed the comma

silent seal
#

Why don't you use concat join instead of building a string?

hollow smelt
silent seal
#

I usually recommend creating your variable that is input into the string on one line, with {% set myVariable = template_stuff_here %} and then outputting it in the sentence afterwards.

#

So what we're really looking at, is how to do this part better:

{% set windows_area = { "binary_sensor.janela_do_quarto_contact": "do quarto", "binary_sensor.janela_da_suite_contact": "da suíte", "binary_sensor.janela_da_varanda_contact": "da varanda" } %}{% for k in windows_area.keys() %}{% if is_state(k, "on") %}{{ windows_area[k] }}, {% endif %}{% endfor %}
dreamy sinew
#

tried to find a way to pass it through map but no joy

silent seal
#

So this part:

{% for k in windows_area.keys() %}{% if is_state(k, "on") %}{{ windows_area[k] }}, {% endif %}{% endfor %}

Could become:

{% set myOutput = expand(windows_area.keys()) | selectattr('state', 'eq', 'on') | list | join() %}
dreamy sinew
#

got this far:

{{ expand(test.keys())|selectattr('state', 'eq', 'off')|map(attribute='name')|join(', ') }}```
silent seal
#

Untested, but that might work.

dreamy sinew
#

uses the friendly names

hollow smelt
dreamy sinew
#

right. but i hate loops

#

😛

silent seal
#

(Though if it's assigned to an area I think I read something earlier about getting the area from a the entity_id? area_name('entity_id')? I've lost the forum post)

inner mesa
#

looping == failure 🙂

silent seal
#
{% set myOutput = expand(windows_area.keys()) | selectattr('state', 'eq', 'on') | map(attribute='entity_id') | map('area_name') | list | join() %}
hollow smelt
silent seal
#

You could put the preposition in the area name itself 😉

#

It's a relatively common approach to translations to make sure that articles are included where they are necessary. Cases do complicate matters, but they're not impossible either.

inner mesa
#

I've customized the friendly_name of my leak detectors to improve text output

#

you could even make a custom attribute just for this if you like

silent seal
#

(If this were German, Latin, Russian, or any language with cases, you'd need custom attributes for the indefinite and definite articles in each of the cases!)

mighty ledge
#
{% set test = {"binary_sensor.living_room_occupancy": "living room", "binary_sensor.guest_bedroom_occupancy": "guest bedroom"} %}
{% set open = expand(test.keys())|selectattr('state', 'eq', 'off')|map(attribute='entity_id')|list %}
{{ test.items() | list | selectattr('0', 'in', open) | map(attribute='1') | join(', ') }}
hollow smelt
inner mesa
#

your language should clearly be changed to be more computer friendly

#

consider a PR

silent seal
inner mesa
#

Does Merriam-Webster accept PRs?

silent seal
#

Though perhaps a different construction of the sentence would be better:

Aguentar! Existem janelas abertas nos seguintes quartos:

  • Balcony
  • Living Room
    ...
#

*Apologies for the Google Translated Portuguese

hollow smelt
mighty ledge
# hollow smelt <@!723160143314812971> I wasn't able to retrieve windows_area back again after ...
{% set windows_area = { "binary_sensor.janela_do_quarto_contact": "do quarto", "binary_sensor.janela_da_suite_contact": "da suíte", "binary_sensor.janela_da_varanda_contact": "da varanda" } %}
{% set open = expand(test.keys())|selectattr('state', 'eq', 'on')|map(attribute='entity_id')|list %}
{% set open = test.items() | list | selectattr('0', 'in', open) | map(attribute='1') | list %}
{% if open | length > 1 %}
  Espere! As janelas {{ open[:-1] | join(', ') }} e {{ open[-1] }} ficaram abertas.
{% else %}
  Espere! As janelas {{ open[0] }} ficaram abertas.
{% endif %}
hollow smelt
dreamy sinew
#

yeah, all of my sensors were off so i needed to get it working 😛

hollow smelt
#
{% if open | length > 1 %}
  Espere! As janelas {{ open[:-1] | join(', ') }} e {{ open[-1] }} ficaram abertas.
{% else %}
  Espere! A janela {{ open[0] }} ficou aberta.
{% endif %}
mighty ledge
#

🤷‍♂️ I have no idea what language that is

#

so I just copied

#

I'm guessing spanish?

inner mesa
#

I said that in portuguese we need a different preposition before each area

mighty ledge
#

ah

#

I was about to start swearing in spanish

hollow smelt
inner mesa
#

Italian and Portuguese look vaguely like Spanish to me

hollow smelt
inner mesa
#

similar enough, and yet not

mighty ledge
#

come mierda is all I know

#

99% sure it means eat shit

#

well, all I remember

inner mesa
#

and even then, I suspect that English curses are probably understood by most worldwide 🙂

#

at least you can tell if somebody is swearing at you

hollow smelt
#

Thanks @mighty ledge , @silent seal , @inner mesa, @dreamy sinew and @marble jackal
I will study this code, mainly selectattr('0', 'in', open) this part
I also will read more about custom attributes

silent seal
#

There's also rejectattr which has the same syntax but works the other way around.

mighty ledge
#

It's taking key value pairs, converting them into a list of tuples, then comparing the first item but using the second item

#

it's not high level stuff, but it's not straight forward

inner mesa
#

I'm also puzzling over that one

mighty ledge
#

ok, so dict.items() returns an items() object

#

I cast that as a list

#

which looks like this

#

[('key1','value1'), ('key2','value2') ]

#

selectattr only accepts strings

inner mesa
#

I didn't know that '0' and '1' worked in that way

mighty ledge
#

so... if I want to select based on the first item, '0', then I have to put it in quotes

#

yah, it's dumb

#

like I said, work-around

inner mesa
#

well, good to know

mighty ledge
dreamy sinew
#

its the hacky stuff that comes up when you're mixing python and jinja

mighty ledge
#

yah

dreamy sinew
#

you totally can but it might not do what you expect 😛

mighty ledge
#

right

#

but thats essentially how it works for selectattr

dreamy sinew
#

so its usually better to say "don't"

#

heh its been a while since i've been able to catch a question here. Too many of you have caught up to me 😛

inner mesa
#

it's making it a string that confused me, or at least quoting it

dreamy sinew
#

things inside of filters are kinda strange too

mighty ledge
#

it's why you can do foo.0.foo in jinja but not in python

snow laurel
#

is it possible to fetch the last updated value of a sensor prior to it becoming unavailable? something akin to: state at time = last_updated?

inner mesa
#

If you trigger on the state going to 'unavailable', then the trigger.from_state.state would be the state it came from

mighty ledge
#

fetching it after the fact requires you to use the SQL sensor

snow laurel
marble jackal
#

Yes, but it will only have a state after sensor.ence_01_energy_total became unavailable
You probable want to trigger on every state change, and use the to_state in case the state is not unavailable.

snow laurel
#

I always wonder if this type of thing is poor form? having automations that fire so often

inner mesa
#

Not really

#

It's already registering the changes

snow laurel
#

(typo: Should be 01 instead of 02)

inner mesa
#

That will start producing 'unavailable' after the first one

snow laurel
#

Ah it can update the unavailable state and still remain the same I see

marble jackal
#

{{ trigger.from_state.state if trigger.to_state.state == 'unavailable' else trigger.to_state.state }}

inner mesa
#

This has become a fairly typical problem

#

That has the same problem

marble jackal
#

Does it? The sensor triggering the changes is not the template sensor itself

inner mesa
#

The sledgehammer is to store the last valid value in an input_number. You may be able to replicate that by referencing the current template sensor state

snow laurel
#

Ah this is why people were saying to install the variable custom integration

#

Is there not a way to say "If state is unavailable, keep template the same as previous template state"

inner mesa
#

In the end, it's better to gave a reliable sensor.

marble jackal
inner mesa
#

Not built in. In part because it's a bandaid for a broken sensor

snow laurel
inner mesa
#

Try replacing trigger.from_state.state with states('sensor.xxx') (your template sensor)

#

input_number is a helper

snow laurel
#

Yeah Im saying are the helpers Hass' answer to variables going forward?

inner mesa
#

I've seen nothing to say differently

#

try something like this:

inner mesa
#

yeah, maybe something like that. gotta work through all the cases

#

you can condense it using the syntax that TheFes provided

snow laurel
#

Yeah I will definitely give that a shot. Quite compact!

#

Would it be...

{{ trigger.to_state.state if trigger.to_state.state != 'unavailable' else states('sensor.ence_01_energy_total_const')}}

#

Hm, looks like that doesnt work. Changing the state of total to unavailable made the template unknown.

#

Perhaps I will just create the helper then.

inner mesa
#

what does your whole template sensor look like now?

#

I would expect something like that to work

snow laurel
#

Oh wait I changed it away from the template sensor.

#

Using the template I wrote up above does not change anything

inner mesa
#

that's using the helper

#

I was more curious if you could get it working by just referencing the template sensor value

#

you're saying that if you use the template from directly above, you still get "unknown"?

#

are you sure your sensor name is correct? I would have expected sensor.ence_01_energy_total_consistent

#

it looks like you're using the unique_id instead

snow laurel
#

Oh jeez

#

Yup... now it works. Oh god.

#

Note to self, entity names are not derived from unique_ids.

inner mesa
snow laurel
#

Ha, interesting. I think the new functionality of being able to set the unique id made me assume that's been changed.

snow laurel
#

A problem that I've now encountered with the above solution is that upon resetting the templates, the value resets to an unknown.

inner mesa
#

You can use 'is defined' or 'is not none' or similar to detect that and provide a default. This ends up being a lot of work to workaround a misbehaving sensor

snow laurel
#

I wouldn't really say misbehaving - its a plug that I dont always use so sometimes its disconnected and thus unavailable

marble jackal
mighty ledge
#

But don’t let it fool you, those items are not lists, they are objects

#

You have to cast them as a list to get list funcs

#

However most list funcs are present on them with a small set of exceptions

marble jackal
#

Aaah, right, I mixed items and values.
I already used it in several templates now

river sail
#

I have a quarterly sensor for electricity. Now this just increases every until it resets after 15 mins. But I would like to use that sensor to calculate a quarterly average instead.

#

1 kWh in 5 minutes -> 3 kWh for that quarter

#

Is there a way to do that?

short magnet
#

I hope this is the right place to ask, and Ill try to make it short.
I have made a covers.yaml file and included it in the configuration,yaml and it works fine, I use it to group up my curtains.
Now i need an automation for my garage door, but when i place the code in covers.yaml then it doesnt accept: platform: template.
And if i put the code in configration.yaml it says cover: is already in use

inner mesa
#

~share your code

silent barnBOT
#

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

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

mighty ledge
#

you're either missing the -'s in your cover file, your spacing is off, or you have cover inside cover

short magnet
inner mesa
#

If that's the contents of covers.yaml, then it's what petro said: you need to remove cover: and realign what's under it

silent barnBOT
#

@short magnet Your message has been deleted as it contains a link or a domain name 'pasteboard_dot_co' that is on the blocked list because of: 'Virus detected!'.
Please re-post by removing/changing the domain name/link. Your original message has been DM'ed to you.

mighty ledge
#

good rule of thumb: Don't copy and paste blindly.

short magnet
#

Well thats why i am asking here, im very VERY new to this

mighty ledge
#

because the indentation is wrong

#

look at the previous section

#

then look at the one you're adding

#

it looks like this

#
- platform: ...
  otherstuff: ...

- platform: ...
  otherstuff: ...

  - platform: template
    otherstuff: ...
#

see how that's wrong?

#

all the platforms and other stuff should have the same indentation

#

@short magnet did you die

inner mesa
#

By bad indentation. Must be a first

mighty ledge
#

🤷‍♂️ I'm guessing he's confused an afraid to talk because my example of bad indentation is less complex than what he has

short magnet
#

Sorry, the wife made pancakes... ill try to fix the indentation now

mighty ledge
#

Post your entire cover.yaml file

#

that's telling me that cover is still included in the previous item

inner mesa
#

And your indentation still appears to be wrong

short magnet
#

the file is called covers.yaml - might that be the issue?

inner mesa
#

Please align icon_template properly

#

The whole section is 2 spaces too far to the left

short magnet
inner mesa
#

Looks better. Does it work?

short magnet
#

Theres no more errors now, now i just cant find the right entity to add to lovelace

#

Should I use name: instead of friendly_name: ?

#

like I do with my curtains above

inner mesa
#

cover.garageport

#

And you'll need to restart HA

neon dove
inner mesa
#

None of those things is a template

#

Template entities

neon dove
#

There's also a template button in the reload. I though he also made a new group.

inner mesa
#

I was avoiding the next question from Wace

#

No

neon dove
#

Ahh. I'm just trying to understand when those reloads can/can't be used. I seem to have trouble with them sometimes.

inner mesa
#

If there isn't already at least one template in the system or advanced mode isn't enabled, it won't be there

short magnet
#

Well im a fucking moron. Restart fixed all. thanks alot for all the help and especially the patience

#

Next part is to figure out why the icon doesnt change :)

cinder lotus
#

Made some new template sensors. friendly_name: is not a valid option. Any alternative?

inner mesa
#

name:

cinder lotus
#

Ok, thanks! My sensor.abc is based on the name: abc so if I change the name, my sensor name will also change I guess. Have it used on many places... Any clever 'mechanism' to discover where it is used in HA?

short magnet
#

{% if state_attr('binary_sensor.garageport_vibration_sensor_vibration', 'orientation')[2] | int > 0 %} im guessing the state it tries to read is orentation, but i want it to read angle_y - i am unsure what the [2] after orientation does

inner mesa
#

It indexes into a list

#

You can try it in devtools ->Templates

short magnet
#

I wanted to change it to {% if state_attr('binary_sensor.garageport_vibration_sensor_vibration', 'angle_y') | int < 7 %} but there i dont have the index

#

yay, it works, thanks again

inner mesa
#

np. You need to look at the attributes to know how to access them

stone delta
#

I'm trying to get milight remote controls to control my Hue lights. I've got an esp8266_milight_hub set up and I've integrated it into HA via MQTT which is working fine, but the entities appear in HA as lights and I'm struggling to wrap my head around how to control lights in another integration using their state. Is this a use case for templates? Or is there some easy way of doing this that I'm missing?

I could build a bunch of automations to update the state of the hue lights every time the state of the MQTT lights changes but I feel like there has to be a less clunky way of doing this

inner mesa
#

So you want to trigger on some number of remote controls and each should control a light?

stone delta
#

the DIY hub is basically listening to the radio traffic, normally the remote would be paired with a light. In the hub I can define devices for each device ID and group number, and these will appear in HA as light entities via MQTT, but there's no actual bulb paired so I end up with a light entity whose state changes when I use the remote control

inner mesa
#

The easiest way to do that is to trigger on a list of light entities and use names for the remote lights and real lights that are easily translated. Then you construct the real light from the entity that triggered

nimble steppe
soft sail
#

{{states.sensor.new_movies.entries | map(attribute='title') | list | join(', ') }}

#

I am trying to grab the 'title' value from my attributes from my sensor but unable to.

#

Can someone point me to the right direction?

#

the sensor is an rss feed from my Feedparser HAC integration.

raven token
#

How do I get the creation time of a persistent notification entity? "created_at" does not work even though that is what it seems like it is in the source.

inner mesa
#

If so:
{{ state_attr('weather.wf_udp', 'forecast')|map(attribute='temperature')|join(',') }}

#

Or for you:
{{ state_attr('sensor.new_movies' , 'entries') | map(attribute='title') | join(', ') }}

livid hearth
#

I guess it somehow wrong(ish) place but a problem with Template Editor under Developer Tools: on different PCs contents is different, can we sync it somehow to allow working on same entries from different sessions?

mighty ledge
livid hearth
#

Thanks, so save snippets to cloud and reuse at another location 🙂

rustic moat
#

Hi there, I consider myself still a beginner of HA. I got the following log entries. Can I find out somehow where to look for the source that I need to correct (e.g. cast)? There are no more hints in the log file...
2022-01-07 13:01:24 WARNING (MainThread) [homeassistant.helpers.script] Error in 'choose[1]' evaluation: In 'template' condition: TypeError: '>' not supported between instances of 'str' and 'int' 2022-01-07 13:08:17 WARNING (MainThread) [homeassistant.helpers.script] Error in 'choose[1]' evaluation: In 'template' condition: TypeError: '>' not supported between instances of 'str' and 'int' 2022-01-07 13:09:10 WARNING (MainThread) [homeassistant.helpers.script] Error in 'choose[1]' evaluation: In 'template' condition: TypeError: '>' not supported between instances of 'str' and 'int'

I even don't know what to post here as the error in the log is very generic. Is there a way to see more in the logs, e.g. which script/automatisation is executed before / after?

mighty ledge
#

most likely states('something.something') > 8972

rustic moat
#

@mighty ledge Yes, I can see that in the log and I need to change that. But how do I find out where to look?

mighty ledge
#

read the error like a sentence

#

it points to 2 things that should stand out to you. can you identify them?

rustic moat
#

@mighty ledge I will search in the HA files for that...

mighty ledge
#

keep in mind, the starting number inside the brackets [] starts at zero

#

so the [1] indicates the second condition

#

well, second choose path

rustic moat
#

@mighty ledge: OK so in YAML I should look for a "- condition: template"...?

#

I looked after that and only found (states('something.something')|int)

mighty ledge
#

yes, in the second -conditions: on a choose

#
choose: <---------- YOUR CHOOSE THAT IT"S CALLING OUT
- conditions: <------------ FIRST ITEM IN THE CHOOSE, START IS INDICATED BY the -
  - blah
  sequence: <----------- THIS IS STILL PART OF THE FIRST ITEM BECAUSE THERE IS NO -
  - blah
- conditions: <------------ SECOND ITEM IN THE CHOOSE, START IS INDICATED BY the -
  <-------------------------- HERE
slate tundra
#

is also good to use alias

mighty ledge
#

no alias's here, hard mode all the time

slate tundra
#

instead of starting an item with -condition

#

start with:

choose:
- alias: 'bla bla'
  conditions:
  - first cond
  ....
  sequence:
#

this works and also will show in debugger what alias was executed

#

simple example would be:

#
  action:
  - choose:
    - alias: 'during night select silent profile'
      conditions:
      - condition: time
        after: "00:00:00"
        before: "07:59:59"
      sequence:
      - service: ....
    default:
    - alias: 'in rest of the situations select Auto profile'
      service: ....
rustic moat
#

@slate tundra, @mighty ledge Thx. Will look for that...

#

Got it, it was in a blueprint I made...

#

After restart it seems to be gone...

slate tundra
#

glad to hear it

#

have a great day man

rustic moat
#

Thx!

arctic sorrel
coarse sable
#

So I read in #automations-archived that there's going to be breaking things in 2022.2 re templates ? Is there more info on this somewhere, I'd like to read up on that.

#

oh...that timing tho.

arctic sorrel
#

Disappointed in you @mighty ledge - you never even pinned a link to the article you wrote

mighty ledge
#

check out the 4th pin 😉

arctic sorrel
#

Is that what that means 🤔

mighty ledge
#

I can edit that pinned message to have a better phrase

arctic sorrel
#

Yeah, that'd help. I know it means something to you, but ...

mighty ledge
#

I tried to keep the phrases short for mobile

arctic sorrel
#

We need a link shortener for HA 😄

jagged obsidian
#

what if you're not confused by default but you don't know what it does

arctic sorrel
#

I'm just permanently confused

jagged obsidian
#

that's called early onset Alzheimer disease

mighty ledge
#

That's just being confused in general

#

that's usually the case in templates

#

so, start top down with the pins 😉

arctic sorrel
coarse sable
#

Will the Check Home Assistant configuration add-on throw warnings about the templates that are impacted with this default thingy ?

mighty ledge
#

🤷‍♂️

#

most likely no

#

if the template is correct, but the resolution only fails when the conversion fails, it won't show up

#

Do you understand what |int and |float are doing?

#

they convert a string to an int or a float

coarse sable
#

yes - i think :p

#

that's what i thought

mighty ledge
#

but what happens the value of your sensor is "HEY MY NAME IS TOMMIII"?

#

and you convert that to a float or an int?

#

what would you expect?

coarse sable
#

it'll say warning : unwarranted use of all-caps.

mighty ledge
#

nope, it'll just result in that warning about missing a default

#

when conversions fail, default is used

coarse sable
#

It ought to return a value that corresponds to the conversion...

mighty ledge
#

if you don't provide a default, it bitches

coarse sable
#

got it, thanks

#

wait...int isn't mentioned in your post ?

mighty ledge
#

read the post 😉

#

if you understand the code, you won't need an example explicitly calling out int

#

because they are all the same

coarse sable
#

devtools will be getting heavy use.

mighty ledge
#

you can do a simple find and replace

#

that's all I did

#

well, I did update a few templates to actually use default to catch bad info. But other than that, find/replace and you're done

#

int -> int(default=0)

median mason
#

I was using the following to get my nuc's uptime.

{% set d, h, m, s = states('sensor.intel_nuc5i3_system_uptime').split(':')  | map('int') %}
{{ as_datetime(states('sensor.date_time_iso')) - timedelta(days=d, hours=h, minutes=m, seconds=s) }}

But for some time it's not rendering anymore. now i get this warning and shows Unknown instead of time.

sensor.template_intel_nuc5i3_uptime rendered timestamp without timezone: 2021-12-30 08:28:38

how can i solve this?

slate tundra
#

put a timezone on your docker container

limber haven
#

So, Im perhaps totally out of my depth here, but Im trying to write a command_line switch to test of a service is up and running by running some JSON queries via curl. I've got the queries setup and the service returns "READY" as a responce when its up and running, but Im rather confused what Im supposed to put in for the value_template to read and parse that in a way that HA will understand

mighty ledge
limber haven
#

Yup.. # curl -X GET -H "Content-Type: application/json" -H "Authorization: xxx" http://xxx/api/v2.0/system/state "READY"

mighty ledge
#

what happens if the state of the switch is off?

limber haven
#

Hm, nothing.. It would be powered down and unable to respond

mighty ledge
#

ok, so in that instance, what does that command return

limber haven
#

It'd return nothing, just a http time-out I'd imagine

mighty ledge
#

well, that's what you'd want to find out

#

cause that'll all be for nothing if you can't template off the command

#
{{ value == 'READY' }}
limber haven
#

Becaue this is controlling a physical PC, if its 'off' then.. its never going to return anything because its actually off, I guess I could read the state of the machine from IPMI (which is what Im doing to turn it on) but..

#

(If the damn ipmi did a APCI shutdown this would be much simpler :D)

mighty ledge
#

You could also just use a device_tracker home/not_home for the pc on your network if your router is connected to HA via an integration

#

either way, it's a polled state, so it won't be live

#

you could also leave it out all together and just have the on/off commands

limber haven
#

Hm, well I tried changing the value template to just {{ value = 'READY'}} Im not getting any errors in the log.. but its also not reporting the state of the machine correctly either

#

do I not need some way for HA to tell when the machine is actually on though?

mighty ledge
#

if you don't care, you can just have the on/off commands

#

either way, it's polled

#

so the state will be out of sync until it's polled

#

polled means HA is asking what the state is

#

not it telling HA what the state is

limber haven
#

How often will it poll by default? I'd want some feedback to know if this service is running or not

mighty ledge
#

30 seconds IIRC

limber haven
#

Even something basic like.. 'does it respond to ping' would do? If that's easier

mighty ledge
#

yes but pinging is also polling

limber haven
#

I dont mind if its 30 seconds behind, as long as it updates within a few mins I'd be content with that

mighty ledge
#

then anything you can dream up can be in that value template

#

it has access to the entire state machine

limber haven
mighty ledge
#

The command is run every 30 seconds

#

value_template represents the state of your switch

#

true or false

#

when the command run, value_template runs

#

templates in general also update whenever anything used in the template updates

#

so if you can come up with a way to let your switch know through the state machine by attaching it to HA... IP sensor, something your PC runs, etc, then you could get faster updates

#

templates are templates, they behave the same way everywhere

#

but if you were to go the route where something else is creating the on/off state of that virtual switch, I would change to command_line services with a template switch

limber haven
#

... right because.. Unless Im reading what you are saying here wrong, thats not what the docs say?

#

If given, this command will be run. Returning a result code 0 will indicate that the switch is on.
value_template string (Optional)

If specified, command_state will ignore the result code of the command but the template evaluating to true will indicate the switch is on.
mighty ledge
#

then you can use an automation trigger to trigger it

#

you're not understanding what's written there

#

that's saying exactly what I said

limber haven
#

Ok, so in thsi context.. 'value_template' can be true or false, but where does it get the data from for its evaluation? I took it to read that it could take the result of command_state? but.. thats not the case?

mighty ledge
#

from the command_state

#

let me read the docs

limber haven
#

okay.. so if command state in this context returns READY, what would I need to template that to read that state, and return 'true' if that is the value, and false if its anything else? 😄

mighty ledge
#

i've already given you that

#
{{ value == 'READY' }}
#

value is what comes from command_state

limber haven
#

Yeah, except that doesnt seem to work, Im not getting any errors but HA is still reporting that the switch is 'off'

mighty ledge
#

if that's not working then your command doesn't send just "READY"

#

you can try

#
{{ "READY" in value }}
limber haven
#

(As an aside, is there way ot test/update this code without rebooting the entire HA instance as its pretty slow)

#

"READY" in value works 🙂 it's now returning 'ON'.. how odd!

#

maybe its returning a linereturn or.. something daft..

#

🥳

mighty ledge
#

sometimes it's a special char in front that's not visible

limber haven
#

But yeah, all seems to be working a treat now, state is returning correctly and the on/off works fine, Thank you for the assistance 🙂

proper void
#

Guys after restart ONLY of home assistant I am getting the following error messages
2022-01-07 21:38:17 WARNING (MainThread) [homeassistant.helpers.script] Error in 'condition' evaluation:
In 'template' condition: TypeError: argument of type 'NoneType' is not iterable

mighty ledge
#

You're iterating over something before it exists

#

a for loop

#

it's in your condition

#

gotta find out which condtiion, but that should narrow it down.

proper void
#

Which files?

#

script.yaml?

mighty ledge
#

it says in your error

proper void
#

I have a lot if if conditrions in script.yaml but thye work just fine

mighty ledge
#

see my previous responses

soft sail
red gale
#

ok moving my issue from #automations-archived to here since this is mainly a templating issue..

{{ ( states.input_datetime.zoe_last_fed.attributes.timestamp | timestamp_custom('%H:%M', False)) }}

so if I pop this into the template editor it spits out 22:22 which would be 10:22PM however the acutual value of states.input_datetime.zoe_last_fed.attributes.timestamp is 1641594123 which is 2:22PM – where are those 8 hours coming from? lol

inner mesa
#

Time zone?

red gale
#

shouldn't setting the TZ in HA config be enough? 🤔

raven token
#

Causes them to go into utc time. You can quickly verify that by checking your utc offset

red gale
#

ah.. so it seems timestamp_custom is coercing my timestamp to the wrong time zone

inner mesa
#

And you're passing False, which means 'not local time'

red gale
# inner mesa And you're passing False, which means 'not local time'

thank you for pointing that out.. timestamp_local is what I'm looking for? just as you sent that I finally found the docs I was looking for. so things like timestamp_custom are custom filters provided by HA for jinja? i was looking for jinja docs to tell me what that boolean arg was for

red gale
#

or duh, timestamp_custom without the 3rd argument 🔫

inner mesa
#

Or that

red gale
#

awesome – taking my full paternity time to learn to speak HA/Jinja lmao.. thank you guys.

rare panther
#

if there a way to write else if within this block? say I wanted another condition to be evaluated within this --> {{ 1 if is_state('light.study_light','on') else 2 }} Currently it only allows else

inner mesa
#

You sure?

inner mesa
#

{{ 1 if 2==3 else 3 if 2==3 else 4 }} -> 4

rare panther
#

thanks. I was just adding else if earlier 🙂

marble jackal
#

{{ as_local(as_datetime(states('input_datetime.dishwasher_program'))).strftime('%H:%M') }} this will work if you change it to your input_datetime

#

@red gale

red gale
marble jackal
#

You can also use .time() at the end, but that will include the seconds

gleaming eagle
#
  resource: https://api.airvisual.com/v2/city?city=......
  method: GET
  value_template: '{{my_test_json["data"]["current"]["pollution"]["aqius"]}}'
  name: "Air Quality Index"
  scan_interval: 1800```

I'm writing this rest sensor, how do I set the value I'm getting from this to attribute and set custom names like Healthy, Unhealthy to the state?
#

Like if value is
0-50 then good
else if
51-100 then moderate
else if
101-150 then Unhealthy for Sensitive Groups
etc...

mighty ledge
#

there's thousands of examples that show you how do to if statements and check values against other values

gleaming eagle
#

Yes I've got it to work

silent barnBOT
gleaming eagle
#

is there a better way to do?

mighty ledge
#

Nope, that’s good

edgy umbra
#

Can anyone give a hint how to add this in a seperate file? I have a packages folder with yaml files included but if i add this template to my garagedoor.yaml i get this error.

#

Invalid config for [template]: [platform] is an invalid option for [template]. Check: template->platform. (See /config/packages/garage.yaml, line 6).

#
    - trigger:
      platform: event
      event_type: zha_event
      event_data: 
        device_id: xxxxxxxxxxxxxxxxxxxxx
        command: Tilt
      binary_sensor:
        - name: garagepoort
          state: >
            {% if trigger.event.data.args[0].degrees|float > 0 %}
                on
            {% else %}
                off
            {% endif %}```
inner mesa
#

you currently can't use that template format in packages

edgy umbra
#

Thanks RobC 🙂

#

Just pasted it to configuration.yaml but after a restart i don't get a binary_sensor?

inner mesa
#

your indentation is wrong too

silent barnBOT
#

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

#

YAML is the mark up language used by Home Assistant, consistent indenting (two spaces per level) is key. Here is a primer, and this explains multi-line templates. For validating YAML see YAML Lint.

edgy umbra
#

Just noticed that, but the strange thing is it passes the config check?

#

Oh, didn't know the UI config check is not reliable

#

Fixed the indentation but still no sensor?

inner mesa
#

it's not bad YAML syntax, but it's not valid for HA

edgy umbra
#
  - trigger:
    platform: event
    event_type: zha_event
    event_data: 
      device_id: xxxxxxxxxxxxxxxxxxxxxxx
      command: Tilt
    binary_sensor:
      - name: garagepoort
        state: >
          {% if trigger.event.data.args[0].degrees|float > 0 %}
              on
          {% else %}
              off
          {% endif %}```
inner mesa
#

still broken

edgy umbra
#

Whut? 😐

inner mesa
edgy umbra
#

Thanks 🙂

marble jackal
#

You can also set your template to just {{ True }} and use auto_off

stone lintel
#

Is there a way to pull the full title as a state attribute please? https://i.imgur.com/UHIy4S5.png
{{ state_attr('sensor.tautulli','mbridges88') }} Pulls the activity and full title but I am just after the full title for that user

inner mesa
#

I don't have any like that, but either {{ state_attr('sensor.tautulli','mbridges88.full_title') }} or {{ state_attr('sensor.tautulli','mbridges88').full_title }} or {{ state_attr('sensor.tautulli','mbridges88')['full_title'] }} should work if it's really a dict

#

I have one that looks like that, but it's really just a big string

analog coral
#

If I'm making a JS template to display the brightness attribute of an entity, is there a way to use a generic variable like "this.entity_id" within the template so I don't have to update the entity per card?

#

This is the template I'm working with
label: | [[[ var bri = Math.ceil(states[this.entity_id].attributes.brightness / 255 * 100) + "%"; return bri; ]]]

mighty ledge
analog coral
mighty ledge
#

It’s simply entity

#

Check out the docs, that’s the configured entity

analog coral
#

It just returns [object Object] and I don't know how to convert to an entity_id

mighty ledge
#

it’s the state object

#

So if you want state it would be entity.state

#

If you want the entity_id, what would it be?

analog coral
#

It would be entity.entity_id, thank you for pointing me in the right direction!

stone lintel
sullen crow
#

how can I write a template that takes the average of all the temperature sensors (or a subset from a list). Is there a sum() or mean() function equivalent I can use?

inner mesa
#

Yes

silent barnBOT
inner mesa
#
{{ [states('sensor.xxx'), states('sensor.yyy')]|map('float')|sum }}
#
{% set sensors = [states('sensor.xxx'), states('sensor.yyy')] %}
{{ sensors|map('float')|sum / sensors|length }}
sullen crow
#

so I can create a list wrapped n brackets like python, get the sum, then divide by len(list) or something?

#

beat me to it 🙂

#

could I use a for filter to define sensors

inner mesa
#

there isn't a for filter

#

what are you trying to do with that?

#

generate the list based on some criteria?

sullen crow
#

yes

inner mesa
#

like what?

sullen crow
#

get all the temperature sensors

inner mesa
#

what makes a temperature sensor unique?

sullen crow
#

unit of measurement?