#templates-archived

1 messages · Page 113 of 1

mighty ledge
#

or put it here

next elm
#

And I did a search of the config for other instances of history and recorder, and there's only one of each

#

Sure, one sec

#
    sensors:
      uptime_minutes:
        friendly_name: Uptime (Minutes)
        value_template: >
          {{ ((as_timestamp(now()) - as_timestamp(states('input_datetime.last_start_helper'))) / 60) | round(0) }}```
#

Nothing special there

#

Thanks again for the help with the value template, btw. Works a treat 👌

mighty ledge
#

whelp, just check for errors in your logs then

thorny snow
#

hi guys, need some help here
I have 5 input select sensor which are either off or a float
I need to catch those who aren't off and put them together as an array, i.e.
0,0,1,1,4,4
every input_select is either 'False' or '0,0' , '2,2', '4,4'

bright veldt
#

I'm trying to trigger 1hr before a calendar appointment, but just comparing unix timestamps seems to not actually be triggering. Currently I have {{ as_timestamp(states.calendar.my_calendar.attributes.start_time) - as_timestamp( now() ) == 3600 }}. Do I need to be a little less specific with the timestamps somehow? Like when the difference is =<3600 but > 3500 or so?

knotty dagger
#

Hi all. I have a temperature sensor which always runs a little hot. If I want to drop it by say 7 degrees, what is the format for that if its current value template is:
value_template: '{{ value_json.temperature | round(1) }}' ?

fast vigil
#

@knotty dagger just add -7 to that

knotty dagger
#

@fast vigil so, like this? value_template: '{{ value_json.temperature | round(1) -7 }}' ?

fast vigil
#

yeah, that should work

knotty dagger
#

@fast vigil that did it. thanks, bud!

waxen rune
#

@bright veldt The template updates at the start of each minute, so unless the exact time down to every second is of the essence, I'd suggest {{ as_timestamp(states.calendar.my_calendar.attributes.start_time) - as_timestamp( now()) < 3600}} which then will become true when there is less than 3600 seconds left. So if you trigger on state to: 'true' you should be fine

bright veldt
#

Will it trigger repeatedly during that hour?

#

I used == so it would just trigger once. I’m fine with anytime around that time being the actual trigger

#

Oh, you’re saying to trigger only when it goes from false to true. Then it’ll only happen the once.

#

Can I use from: and to: with a template trigger, or just with a state trigger?

#

Reading the docs more closely, I see “Being a boolean expression the template must evaluate to false (or anything other than true) before the trigger will fire again. “ so i guess I can use <3600 instead of ==3600 and not worry about it!

slender pawn
#

Hi!
I have an automation that are triggered by different sensors. In the notification message I want to include the triggering sensor name.
I use this in my automation:
message: "{{ trigger.from_state.attributes.friendly_name }}"

Should I access the friendly name by using state_attr() ? If yes, how can I do it?
https://www.home-assistant.io/docs/configuration/templating/#states

#

Solved... message: "{{ state_attr(trigger.from_state.entity_id, 'friendly_name') }}"
Found a post in the forum explaining.. 🙂

waxen rune
night mural
#

I've been searching Google for quite a bit and my template-talent is not that great. I'm looking for an automation that triggers each time any of my Shelly devices has a firmware update. Are wildcards supported for this? trigger:

  • platform: state
    entity_id: binary_sensor.*_firmware_update
deft timber
#

No you can not do that

#

Either you list all the binary sensor in the entity_id

#

Or you create instead an event trigger on the envent type state_changed

#

and check if the entity linked to the event matches your expression (binary_sensor.*_firmware_update)

#

{% if trigger.event.data.old_state.entity_id | regex_match('^binary_sensor\..*_firmware_update$') %} ...

warm saddle
#

Does anyone have an example of taking a list of entity ids and then returning true if at least one of the states is true.

hollow bramble
#

Are they all the same type of entity?

warm saddle
#

yeah

hollow bramble
#

You'd be better off just putting them in a group

warm saddle
#

doing an area blueprint selector for entity and noticed conditions started to fail and I just want to be sure at least one of them is true

#

eh.. blueprints are causing me much pain 😄

hollow bramble
#

put them in a group and use the group state as your condition

silent barnBOT
#

Groups allow the user to combine multiple entities into one.

warm saddle
#

I can't use that

hollow bramble
#

Why?

warm saddle
#

this is a blueprint. I can't control nor do I want to define groups for every single combo of lights the user picks

#

I'm getting a sorted list of entity ids and I just need to write a template to reduce to a single bool value if any of the states are on

warm saddle
#

- "{{ expand(motion_entities) | selectattr('state', 'eq', 'on') | list | count > 0 }}" does it but pretty sure it doesn't handle my case

abstract river
#

Could someone using input_datetimes help me try to pinpoint an issue I am having?

If you type this in (with a valid input_datetime for you) are the times off by 18 minutes?
{{ states('input_datetime.heater_time_variable') }}
{{ state_attr('input_datetime.heater_time_variable', 'timestamp') | timestamp_local() }}

trail estuary
#

Is there a function I can use to always have a set number of decimals? I was hoping round(x, "ceil") would do the trick, but no.

waxen rune
trail estuary
waxen rune
#

do you always want the same number of decimals?

trail estuary
#

👍

#

I have applied what I feel is a VERY diry workaround, not at least beacuse I mess with the actual value:
{{ ((state_attr('sensor.tidevann', 'high_tide_height') | float ) + (0.00000000000000100000000001)) | round(3, "ceil") }}

#

But, if there is a better way that is not messing with the value in this way, I'd be very interested!

waxen rune
#

'{{"{:.4f}".format(states('sensor.ping_router_roundtrip_max_tmpl') | float) }}' will always give you 4 decimals.

#

the 4 in .4f decides the number of decimals. I haven't actually verified it, but it should round correctly as well

#

so 1.2 will become 1.2000 in the example above

trail estuary
#

Let me check! 🙂

#

It works perfectly!!

#

Thank you so much!

#

No.... It works in the template editor, but not in Lovelace....

#

This is the weirdest thing....

#

If that template is the only thing being rendered it doesn't work! But if anything is added it works as expected....?

ivory delta
#

When you use a single template, you'll see the true value. When you use multiple templates, the dev tools makes a multi-line string with all the results.

#

Single = truth

#

Too slow, thomas 😉

charred dagger
#

Was double checking a workaround that doesn't work... around. Don't mind me.

#

Ok, got another workaround that does work.

#

The problem is that the template engine will always interpret a number as a number nowadays, even a string containing a number.

trail estuary
charred dagger
#

So you do all of that work to make 1.2 display as "1.200", but then python says, "Hey! I know what that means! That's 1.2"

trail estuary
#

Haha!

charred dagger
#

but it you instead make is say "1.200\x00" python will say "Hey! I know what that means! It means '1.200' and is a string, obvisusly!".

#

"\x00" will add a non-printing empty byte to the string.

#

This will stop you from making string comparisons, though, unless you accommodate for the null byte too.

#

Try '{{"{:.3f}\x00".format(states('sensor.ping_router_roundtrip_max_tmpl') | float) }}'

trail estuary
#

Not a problem! I simpy want 3 decimals! 🙂

charred dagger
#

You're not the first to run into this problem, but I realized the solution only right now. So thank you!

trail estuary
#

Hehe... That is a very generous way to look at it! 😉

#

Really enjoyed your talk yesterday btw! 👍

charred dagger
#

Glad to hear it! I look forward to seeing it myself, actually.

sonic oracle
#

So first time messing around with templates.
I am trying to do a template_sensor which uses a value of one sensor if its bigger than 0 and a other one if below
Thats what i came up with but it doesn't work:

{% set consumption = states('sensor.e3dc_home') %}
{% if consumption > 0 %}{{ consumption }}
{% else %}{{ states('sensor.e3dc_grid') }}
#

figured it out... {% endif %} was missing

dreamy sinew
#

Also, need to cast consumption to a float or an int

crimson quarry
#

I have a lightbulb that I flashed Tasmota (8.5.0) to and recently upgraded Tasmota (9.1.0) and now the light's rgb_color attribute always shows 255,255,255. I looked at the MQTT output and Tasmota is sending the RGB in hex (for example Green would be: 00FF00). Is there an easy way to convert/format the value template so the rgb_color attribute reads correctly? I use the rgb_color attribute in a node-red switch to do different actions. Thanks.

ivory delta
#

It took seconds to find that, btw.

crimson quarry
#

@ivory delta thanks, I've already read that link, but I need to go the other way. Hex to Decimal

#

in that same article it suggests using '{{ value | int(value,16) }}' to convert Hex to Decimal, I'm just wondering if there's a way to do this with a format, rather than split the Hex string into 3 pieces, and run an int(value,16) on each, and then concat them back into an array.

lyric notch
#

Hi @raw dust did you ever found a way to do this? I'm trying to find the device name given a device_id...

raw dust
#

no, unfortunately not

mighty ledge
#

@crimson quarry there's no quick easy way to do this in jinja. Here's your best option...

{% set value = '00FF00' %}
{% set rgb = namespace(value=[]) %}
{% for i in range(0, value | length, 2) %}
{% set current = value[i:i+2] %}
{% set rgb.value = rgb.value + [ current | int(current, 16) ] %}
{% endfor %}
{{ rgb.value }}
#

and the other way

{% set value = (0, 255, 0) %}
{% set hex = namespace(value='') %}
{% for i in value %}
{% set hex.value = hex.value + '%02X'%i %}
{% endfor %}
{{ hex.value }}
fossil hearth
#

hi can anyone please tell me why this wont work ? it works in developer tools when i tested it

  - platform: mqtt
    state_topic: "zigbee2mqtt/switch1"
    name: SW1
    value_template: >-
     {% if as_timestamp(states.sensor.sw1.last_updated) + 5 < as_timestamp(now()) %}
       {{value_json.action}}
     {% else %}
       blank
     {% endif %}
mighty ledge
#

think you replied to the wrong person 😉

brazen harbor
#

Oh my, I am sorry petro... 😦

brazen harbor
mighty ledge
fossil hearth
mighty ledge
#

So when you press the button, you want it to keep the pressed state for 5 seconds then return to 'empty' or something?

fossil hearth
#

the conditoin is not working properlu

mighty ledge
#

Also, what section are you putting this in?

#

switch... light... sensor...?

fossil hearth
#

sensor 🙂

mighty ledge
#

Ok, just use this template but set expire_after

#
    value_template: "{{ value_json.action }}"
    expire_after: 5
#

after 5 seconds it will return to a 'unavailable' state

fossil hearth
#

❤️

#

this is awosmn

#

thanks you soooo much

mighty ledge
#

np

fossil hearth
#

@mighty ledge you are the man ❤️ thank you very very very much hehe

#

but i still don't get why the formula wasn't working altho nevermind u dont have to explain thanks again 🙂

mighty ledge
#

It depends on the scope of templates

#

I'm not sure what the MQTT value_template scope is. It might not have access to the state machine

#

But you're also referencing itself

#

so, thats a no no

spiral imp
#

Could someone explain to me, in templates, when to use == vs ===?

fossil hearth
#

@mighty ledge thanks you well noted 🙂

dreamy sinew
#

In jinja templates the difference is a valid template or an invalid template

mighty ledge
spiral imp
#

ok, thanks

mighty ledge
#

Do you want toknow the JS difference?

#

in Jinja, always use ==.

spiral imp
#

sure

mighty ledge
#

== makes both sides the same type. === does not alter the types

spiral imp
#

gotcha, thanks

rugged laurel
charred dagger
#

Isn't that the same thing?

mighty ledge
#

yeah it is

charred dagger
#

It == is, but not === is

mighty ledge
#

== changes them both to the same type essentially, where === needs them both to be the same type to pass

rugged laurel
#

ah, okey, we agree then 😄

mighty ledge
#

Yep

#

I'm sure there's better ways to describe it. It's just what I rememeber

#

I'm no expert at JS

pallid lake
#

Is there a template to get the max value from another sensor in the last week or do I have to use the statistics sensor?

rustic meadow
#

hi there, I'd like to use an template sensor to fill the value of input_number but I'm unsure what's the proper way to do such "binding". any ideas?

hollow bramble
#

With an automation

rustic meadow
#

hmm 😦

#

oh. actually I may not even need to do template extraction in that case

#

oh well, it's not the prettiest thing I have ever encountered, but state change -> input_number.set_value works good enough for the christmas lights 🙂 thanks @hollow bramble

wet latch
#

Hi there. I hope that someone can help me understand templates a bit...which is what I think I need.

I have a garage door which reports on the status "open" or "closed" - I have it in another group with a couple of door locks which obviously report "locked" or "unlocked".... I'd like to have the garage door as part of this group and then report the group as "off" whenever the doors are locked and the garage door is closed - Is a template the right solution to what I'm trying to achieve, and if so, heeelp 🙂

hollow bramble
#

With a template binary sensor you could do something like {{ is_state('cover.garage', 'open') or is_state('group.locks', 'unlocked') }}

#

It will only have a state of off if everything is locked/closed

wet latch
#

Thank you for that response Villhellm - Not entirely sure how I can incorporate that into my configuration yaml tho...If I mention the names of the sensors, any chance you can help me piece it together?

pallid lake
#
  - platform: template
    sensors:
      custom_garage:
        friendly_name: "Custom Garage"
        value_template: "{{ is_state('cover.garage', 'open') or is_state('group.locks', 'unlocked') }}"
#

@wet latch

#

that goes under binary_sensor:

#

assuming entity ids and group names are correct

wet latch
#

Uh, cool @pallid lake I'll try to create that and make the modifications needed. Ty ty

pallid lake
#

np

crimson summit
#

Hello everyone, I have a problem with templating a binary sensor. The original sensor has value between -100 and 100. I would like to set the binary sensor to 'on' if the original sensor value is between 30 and 60 and to off if the original sensor is between -30 and -60. And the value remain the same (on or off) for all others value.

#

But for other values not captured by the 'if', the sensor does not stay at the same value but goes back to 'off'

crimson summit
mighty ledge
#

Yeah but he can't use a template sensor, it has to be an integration that traverses the state history

#

which min max sensor do ifr

#

iirc*

mighty ledge
pallid lake
#

@mighty ledge Thanks. I am having issues with my statistics sensors showing unknown state. I ended up using a SQL sensor but its a bit more convoluted than I would like

crimson summit
wet latch
#

@pallid lake - May I disturb you once more? I added the sensor and it seems to work...it does however only report the status of "True" if every group member is unlocked (or Open I guess) - I'm trying to create a group that reports something I can pick up for an automation that reminds me if I leave the house or go to bed at night with a door unlocked

mighty ledge
teal umbra
#

Don't know if this is the right section so forgive me if im wrong

I have made a mqtt binarie sensor for motion detection but i have multiple payloads that can be sent
These are

  • Car
  • Face 1 my wife
  • Face 2 my self
  • Face 3 kid
  • Face 4 kid
  • Dog

What would be the best approach to make it work?

grave arrow
#

Using a template condition, is it possible to extract the event_type of the trigger event. Using {{ trigger.event }} gives something like <Event ios.action_fired[R]: actiionID=someID, ...> I just want to check if the event type was ios.action_fired or not.

#

Obviously there are multiple triggers and I just want to take an extra step in the action if it matches this case

grave arrow
#

Dirty solution I have is {{ "ios.action_fired" in (trigger.event|string) }} but I feel there should be a better way

wet latch
#

@mighty ledge thank you, I'll try - Fingers crossed 😄

deft timber
grave arrow
#

I had but just went back through the logs and had a typo 😬 opppssss

#

Thanks 🙂

marsh lynx
#

I'm trying to send an image with my notify.notify but I get the message sent to my android phone which has the HA Companion app installed. I'm only receiving the message notification, but there is no image. Am I doing something wrong?
message: This is a test message with a picture title: Test Title data: photo: url: "https://raw.githubusercontent.com/home-assistant/home-assistant.io/current/source/images/default-social.png"

deft timber
marsh lynx
#

The symptom happens on all devices.

deft timber
marsh lynx
#

Where would be ideal to discuss the usage of notify.notify ?

deft timber
barren jungle
deft timber
#

why do you say in contradicts with docs ?

#

last_changed is updated when the state changes, last_updated is updated when the state or attributes change

#

That is what you noticed and what is in the doc. Or am I missing something?

barren jungle
#

A state_changed event can happen when just attributes change
would mean I cannot depend on it on major state changes because it could change with just 1 attribute change.

deft timber
#

no, this just says that when an attribute or a state changes, a state_event happend, it is not in contradiction with what we sayd

#

if you use event trigger, it means you should pay attention rather it is a state change or just an attribute change

barren jungle
#

ok, I get it, It references event not the last_changed itself.

deft timber
#

but if you use a state trigger, it will be trigger only when the state changes

#

yes

barren jungle
#

so last_changed is guaranteed to fire only on state change?

deft timber
#

yes

barren jungle
#

ok, this is what I wanted to know. Thank You.

deft timber
#

Welcome

faint loom
#

hey all, I am trying to send a telegram notification. Notifications is configured correctly as I can send simple text
But I would like to send the automation trigger name as part of the message

#

this is my current automation

#

`alias: Network monitor
description: ''
trigger:

  • platform: state
    entity_id: binary_sensor.garage_rb_ping
    to: 'off'
    condition: []
    action:
  • service: notify.telegram_henk
    data:
    message: ' {{ trigger.to_state.name }} '
    mode: single`
#

whenever I use the trigger I get an error

#

Error executing script. Unexpected error for call_service at pos 1: Error rendering data template: UndefinedError: 'trigger' is undefined

granite steppe
#

I use for: in my automation condition. But, when i reset my server, the device goes to 'unavailable' for a couple of mins which causes the counter to starts again. Can i still use for but ignore unavilable time? - condition: state entity_id: vacuum.robovac state: 'off' for: hours: 71

rugged laurel
deft timber
#

oh yes, indeed, sorry about that

rugged laurel
#

The issue is that it was triggered manually, when you do that, it only run the action part, which does not have the trigger context

faint loom
#

ah, ok

#

that makes alot of sense, it did cross my mine

#

let me do a propper trigger change test

spiral imp
#

This automation triggered when the state of weather.dark_sky changed to "snowy" but is not turning on the switch. Can anyone see an issue with the code? It was suggested that I may want in not == https://paste.ubuntu.com/p/cNx7JjpBdS/

faint loom
#

thanks @rugged laurel I was just testing it wrong.

umbral pond
#

hi all , I have made this temporary automation (https://hastebin.com/isiyugubis.kotlin) as a sanity check with some templating inside the inline_keyboard part which actually petro helped me and it works - if I trigger the automation manually the message comes and the buttons work with my callbacks (which I have on another file). The very same code when I put it inside an alert like so (https://hastebin.com/owujeyurez.java) returns an error in the logs , seems like from Telegram API that the Button data is bad. The only change between the codes is that in the working instance its A) an automation and B) I am sending to my personal chat with my bot , whereas in the non-working instance its A) an alert and B) I am sending to a group chat where the bot participates.

In the non working instance if in inline keyboard I hardcode the outcome of the template like so:
inline_keybaord: [ 'option1:/callbackbutton1' , 'option2:/callbackbutton2', ...etc ]
it works.

#

Could someone offer me some insight as to what might be giving this issue?

median pulsar
#

@spiral imp yes, you want in. == is for equality, and your state is never going to be equal to a list. in is true if the state value is in the list.

spiral imp
median pulsar
#

Well, the logic inside the double brackets is essentially Python syntax. But if you really want to know it all, look for the links to Jinga2 templating in the URL shown in this channel's header.

spiral imp
#

Thanks. I feel like I have been on that page 100 times as I am creating templates. The use of "in" was not one I had ever noticed. Thanks for the help

latent bough
#

Hi! I have 2 sensors at garage door. If I close the door I receive ON on the first sensor if I open the door I receive status ON on the second sensor. From these 2 sensors I would like to create a virtual "sensor" which will combine the status of these 2 sensors: so when
first is ON => closed,
first changes from ON to OFF => opening,
second is ON => open
second is OFF => opening

#

what is the best practice to achieve this?

#

how to create that "virtual" sensor

#

?

balmy wedge
#

Hi everyone

wide pivot
#

Does anyone know how to get the current user's name in a template?

latent bough
#

sorry, I'm new to HA

#

🙂

#

is the template some kind of "virtual" thing? like virtual sensor without physical sensor?

balmy wedge
#

I have a bulb where I can set the warmth, and I use a button for that - I just decrease or increase the current mired value. color_temp: '{{ state_attr(''light.desk'', ''color_temp'') | int - 50}}'

#

Now the issue is that the button can take the bulb past its limits.

#

It doesn't explode, but then the value is stuck in unattainable limbo, and I have to click my way back to the attainable range with the button on the other side.

#

Is there a way to make the template return the minimum or maximum of two numbers? That way I'd cap it to the bulb limits.

#

Ah, I think I can get there

#

color_temp: '{{ [state_attr(''light.desk'', ''color_temp'') | int - 50 , state_attr(''light.desk'', ''min_mireds'') | int]| max}}'

#

Thanks 🙂

latent bough
#

So what are templates?

silent barnBOT
ivory delta
#

The one command that doesn't work the way you'd want 😄

dreamy sinew
#

yeah, that one is a pain because of how the docs scraper tool works

ivory delta
silent barnBOT
dreamy sinew
#

haha

ivory delta
#

Ooo, nice

#

I need to keep the cheatsheet open 😄

balmy wedge
#

Oooh, I didn't know you could do all these things. Very useful.

charred haven
#

alright jinja gurus need some help...these date/time templates are always painful for me lol.....so one of hte breaking changes in 2020.12 was cert expiry no longer showing how many days left...we get a timestamp sensor....so how would i go about creating a template sensor that gives me back that countdown?

charred haven
#

well that was simple enough

#

{{ ((as_timestamp(states('sensor.cert_expiry_timestamp_domain')) - as_timestamp(now())) /60 /60 /24) | int }}

grave arrow
glacial matrix
#

I think this is the correct place to ask, I'm seeing a lot of errors in my log that are similar to this

#
2020-12-17 08:52:00 ERROR (MainThread) [homeassistant.helpers.template] Error parsing value: 'value_json' is undefined (value: E664DEOff, template: {{value_json.RfReceived.Data}})
#

They seem to be appearing for most (there are lots, so i'm not sure if it is all) of my motion sensors, they are setup in binary_sensors.yaml like:

#
- platform: mqtt
      state_topic: "tele/RF_Bridge/RESULT"
      name: 'motion_livingroom'
      value_template: '{{value_json.RfReceived.Data}}'
      payload_on: 'E664DE'
      payload_off: 'E664DEOff'
      device_class: Motion
      qos: 1

Once the motion sensors are activated, i have a flow in node red that waits 30 seconds before adding the offpayload to mqtt.

deft timber
#

If I understand correctly the error message, it says the payload (value) is E664DEOff (so, not a JSON), but you consider it as a json using value_json.

#

If that is correct, just remove value_template: and you are good

glacial matrix
#

Thanks, just going to try that now.

#

by removing that none of my motion sensors are activating. the errors were also gone though.

grim flicker
#

Is there a way to give a variabel a list of entries? So that i can check with a single condition if for example one of the artists is playing that is present on the list and mute the radio for example?

#

Something like this for example

  - entry 1
  - entry 2```
#

to fill a condition like this

    - "{{ is_state_attr('media_player.android_tv', 'artist', '{{variable}}') }}"```
silent barnBOT
young jacinth
# silent barn

ups..
why is this giving me an error while the template works fine in the template editor?

grim flicker
young jacinth
#

mh no that does not work..

#

same error

#

oh it was a slide in error (its that how its called?) in the template. its working now. damn yaml 🤣

grim flicker
#

2 spaces you mean?

#
value_template: >
  {% if is_state_attr('remote.harmony_hub', 'current_activity', 'PowerOff') %}```
instead of:

value_template: >
{% if is_state_attr('remote.harmony_hub', 'current_activity', 'PowerOff') %}```

young jacinth
#

yes

grim flicker
#

yeah spaces can be a pain

fossil hearth
#

how to get average value of sensor with respect to a time range ? 🙏

fossil hearth
#

thanks

umbral pond
#

I have made this temporary automation (https://hastebin.com/isiyugubis.kotlin) as a sanity check with some templating inside the inline_keyboard part which actually petro helped me and it works - if I trigger the automation manually the message comes and the buttons work with my callbacks (which I have on another file). The very same code when I put it inside an alert like so (https://hastebin.com/owujeyurez.java) returns an error in the logs , seems like from Telegram API that the Button data is bad. The only change between the codes is that in the working instance its A) an automation and B) I am sending to my personal chat with my bot , whereas in the non-working instance its A) an alert and B) I am sending to a group chat where the bot participates.

In the non working instance if in inline keyboard I hardcode the outcome of the template like so:
inline_keybaord: [ 'option1:/callbackbutton1' , 'option2:/callbackbutton2', ...etc ]
it works.

#

Some guidance on what might be going wrong?

spiral imp
#

This template It is {{ states('sensor.dark_sky_current_text') }} today. returns "It is Cloudy today". Can I change it to "It is cloudy today" without changing the sensor?

umbral pond
#

Yes but since I am on phone I could only describe the rough process to you until later on that i will be on pc

#

Would you care for that?

spiral imp
#

sure, that is fine

umbral pond
#

Essentially what you want is to get that value and pass it through template filters. So make it a string type first if it isn't already. And then use another filter like many languages have usually it's called "split" or "slice" to get the first letter of the string. Then yet another to turn it to lower case. Again should be called toLowerCase or lowerCase or something similar.

#

All those should be able to be found in the templates documentation of home assistant.

spiral imp
#

thanks, will do some digging

#

Actually, it was simple. This worked... It is {{ states('sensor.dark_sky_current_text') | lower }} today.

umbral pond
#

Nice. Well played!

fossil hearth
#

how can i mius the time now ? like this format 2020-12-17 23:48:31.925237+08:00 but i wanne do now() - 60 minutes

spiral imp
#

It possible to include two states in an if_state if I want to return the same value for both? I tried this but it did not work:
{% if is_state('sensor.part_of_day', ['Morning','Afternoon']) %} today {% else %} tonight {% endif %} It does work if I use just 'Morning'

waxen rune
#

@spiral imp I saw something yesterday about you using in. You could do the same now. There may very well be slicker solutions, but this should work:
{% if states('sensor.part_of_day') in ['Morning', 'Afternoon'] %} today {% else %} tonight {% endif %}

spiral imp
fossil hearth
#

Thanks figured it out ❤️

#

btw is there a way to set variables inside config yaml as a global ? to use all around ?

dreamy sinew
#

no

rugged laurel
#

kinda

#

secrets.yaml
myvar: "Hi there!"

somewhere.yaml
value: !secret myvar

fossil hearth
#

❤️ YES!

dreamy sinew
#

but you can't use them in templates

rugged laurel
#

kinda

ivory delta
#

Expose them in a hidden input_text 😄

rugged laurel
#
variables:
 yo: !secret myvar
action:
  - service: something.bla
    data:
      message: " Test {{yo}}"
#

untested, but I think it should work

charred dagger
#

Beautiful!

ancient garnet
#

I have a sensor which exposes nothing as entities and just has a big list of state.attributes. Am I right in thinking templates are the only way to pull this data out?

brisk temple
#

Trying to use a template in a entity_id for media_player but keep getting error, it not possible?

#
        sequence:
          - service: media_player.media_pause
            entity_id: '{{ media_player1 }}'
#

media_player1 is a variable

#
    - variables:
        media_player1: "media_player.master_bathroom"
deft timber
#

@brisk temple if you use a template for the entity_id, you have to put it under data:

#
        sequence:
          - service: media_player.media_pause
            data:
              entity_id: '{{ media_player1 }}'
brisk temple
#

I tried data but got the same I thought, I'll try again

brisk temple
#

all seems good with that, thanks @deft timber

wild magnet
deft timber
#

wget -q -O- https://money.tmx.com/en/quote/BU | grep hwRiQ returns me nothing. Are you about the hwRiQ ?

wild magnet
#

Not really, I'm not really good in html css I try to find the correct thing maybe such sc-jOvPaO.hwRiQ

deft timber
#

it seems this value is provided by a 'subpage' (called by js or so), not sure (and apparently it is not the cas) that HA is going down, it just get the content of the URL, it doesn't interpret the page to call sub-documents/xhr

wild magnet
#

Oh ok maybe i can write a script with some regex to get the value

deft timber
#

you have to push data in POST

#

and I don't think the HA scraper can do that

wild magnet
#

Maybe i can write a php page with some regex an run it every minute on my website and get the content of my page with HA

deft timber
#

yes, that you can do

#

or just a shell_command

#

using what i pasted above

#

the curl and then use jq to get the value in the json

wild magnet
#

Ok i ll try with sell command

deft timber
wild magnet
#

Command 'jq' not found, but can be installed with: sudo apt install jq

nicecube@DESKTOP-9H6FOG1:~$ sudo apt install jq
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package jq

#

If i can't run it in ubunutu i don't think my docker ll run it

deft timber
#

with sed to avoid usage of jq

wild magnet
#

Yes ty very mutch its working, you are really good 🙂

deft timber
#

🙂 you are welcome

quaint seal
#

Hi guys, I'm trying to grab a specific set of numbers that are a part of a calendar event

#

I want to grab the last 4 digits of these calendar event to set up a lock code

#

to be honest I don't even know where to start. this is my first experience with templates

brisk temple
#

is the data in home assistant?

quaint seal
#

I should be able to get the data by using {{ states.calendar.airbnbcal.attributes.description

#

its in the description portion, but I dont know how to filter out the other text and stuff

brisk temple
#

is it always at the end?

quaint seal
#

it should be, unless airbnb changes their format

#

which is a gamble im willing to take until i get more comfortable with templates

brisk temple
#

k

#

{{ state_attr('calendar.airbnbcal', 'description').split("Digits): ")[1] }}

#

give that a go @quaint seal

quaint seal
#

amazing!

#

what does the [1] do

brisk temple
#

selects the second item in the list

#

if you go to your template editor and put in {{ state_attr('calendar.airbnbcal', 'description').split("Digits): ") }}

#

you'll see there are 2 items

#

[0] for the first, [1] for the second, etc

quaint seal
#

OH

#

the split

#

splits it into two

#

and i want the second half

brisk temple
#

ya, for the life of me I can't find documentation about it, I figured it was a jinja filter, but doesn't seem to be

quaint seal
#

did i get that right

brisk temple
#

yes

quaint seal
#

you are a legend

brisk temple
#

a legend wouldn't have taken 15 minutes to figure it out

quaint seal
#

that is infinitely faster than me

azure tinsel
#

hi, any idea how to create sensor template with value from mqtt
in this format
home/OpenMQTTGateway_SRFB/PilighttoMQTT {"message":{"unit":692,"state":"opened"},"protocol":"iwds07","length":"","value":"692","repeats":2,"status":2}

#

with mqtt auto discovery openmqttgateway is creating gateway pilighttomqtt with every message which is not very usable 🙂

azure tinsel
#

thank you 🙂

atomic gorge
#

Does anyone know why a template for a time stamp would show properly in the dev tools template area but when I use the template to be part of a file name, it turns it into (seemingly) random characters? This is the template I’m using:
{{ as_timestamp(strptime(state_attr('automation.notify_camera_person_event', 'last_triggered'), '%M-%D-%Y %H:%M:%S')) | timestamp_custom('%m-%d-%y %I:%M:%S%p') }}

brisk temple
#

probably because of the : character

atomic gorge
eternal saddle
#

Greetings. I'm just getting started with HA and would like to find a way to change the entity being displayed from On/Off to Open/Closed. Can this be done on the card itself via the visual editor, or would I need to make some entries into the .yaml files?
My card on the dashboard is just referencing the entity binary_sensor.shelly_1_xxxxxxxxxx_input_0

azure tinsel
azure tinsel
azure tinsel
#

how to use template on mqtt.publish topic: ?

#

i'm successfully using payload_template, but cannot template the topic ?

waxen rune
stoic cedar
#

Do you have to import int in a template for it to work? I keep getting undefined when calling it

mighty ledge
#

you're doing something wrong in the template

#

post it here

ivory delta
#

Or testing something that can't be tested in devtools > Templates 🤷‍♂️

stoic cedar
#

"{{int(trigger.event.data.args.activated_face)}}"

ivory delta
#

Yeah... wrong for two reasons.

stoic cedar
#

service: input_select.select_option
entity_id: input_select.alisa_cube
data: "{{int(trigger.event.data.args.activated_face)}}"

ivory delta
#

Casting to an int is done like so... {{ some_value | int }}

stoic cedar
#

I know that testing part @ivory delta.... i am not getting undefiend on the trigger. I am able to test it but triggering a fake event

ivory delta
#

You will as soon as you fix the cast.

mighty ledge
#

because in't isn't a method it's a filter

#

int() -> method. | int -> filter

stoic cedar
mighty ledge
#

that's still a filter

stoic cedar
#

@mighty ledge ok ty

mighty ledge
#

applied like this

{{ value | int('', base) }}

#

but if the base is 10, then it's just {{ value | int }}

stoic cedar
#

@ivory delta i understood what you said about triggers in templates and that is not why I asked ab out them here

#

ahhhhh that is what I was missing @mighty ledge

#

ty

ivory delta
#

You can stop tagging me now...

#

We're all reasonably intelligent. We can tell from the context of the conversation which reply is intended for whom.

stoic cedar
#

its working now. Thanks petro.

azure tinsel
#

is there any way to template mqtt.publish topic , not only payload

#

i'm finding some old forum topics, but currently dont work

mighty ledge
#

only way you can is through mqtt.publish

azure tinsel
#

yeah but service mqtt.publish seems does not support template on topic?

mighty ledge
#

it supports templates on all items inside the data field

#

you can't use templates in the service checker in the UI

azure tinsel
#

yeah i know that, trying in automation action, but only work with static topic

#

topic: '/home/sensor' is ok

#

topic: '/home/sensor' + {{ sensor.id }} should work?

mighty ledge
#

no...

#
topic: "/home/sensor/{{ sensor.id }}"
azure tinsel
#

thanks will try that

mighty ledge
#

assuming sensor.id is a valid object and populated

azure tinsel
#

yes it is OK, I see it as payload

mighty ledge
#

that doesn't make sense

azure tinsel
#

thanks will try now

mighty ledge
#

no objects return as 'sensor'

#

so, i doubt it will work

azure tinsel
#

yeah my mistake, sensor was for example

topic: "home/sensor/{{ trigger.payload_json.protocol}}/{{ trigger.payload_json.message.id }}"
payload_template: '{{ trigger.payload_json.message.temperature }}'
#

this is ok, working now

#

thanks @mighty ledge

mighty ledge
#

yep that should work

#

np

#

remember, math can only go inside templates

azure tinsel
#

i see, thanks

meager orchid
#

Hey folks - I have a contact sensor on my garage door to capture the state of the door. Because of where/how I mounted the sensor, when the door is closed, the contact sensor separates and the state of binary_sensor.garage_door reads as "open". So I wrote this template sensor to reverse that, so the state actually matches the door position. But having trouble with the template - which always evaluates to "open"

#
sensor:
  - platform: template
    sensors:
      garage_inverted:
        friendly_name: "Garage (Inv)"
        value_template: >-
          {% if states('sensor.garage_door_sensor') == 'on' %}
            Closed
          {% else %}
            Open
          {% endif %}```
ivory delta
#

You want a binary sensor, not a sensor.

#

So your template will just be the inverse of the original: {{ states('sensor.garage_door_sensor') == 'off' }}

#

That'll evaluate to True if the sensor is off, False if it's on. Then just set the device class as 'door' to get Lovelace to say Open/Closed.

#

@meager orchid ☝️

meager orchid
#

@ivory delta perfect, got it working - thanks

brisk temple
#

can you have a template in secrets.yaml?

#

or does it pull everything as a string

dull ledge
#

I have a sensor template that works. It returns text. What card type would I use to show the text?

dull ledge
meager orchid
dull ledge
#

Yeah. That worked if I moved the template code into the card.

meager orchid
#

I could be wrong, but if you already have that template set up as a sensor in your config, I think all you need in the markdown card is {{ states('sensor.nameofyoursensor' }}

restive flume
#

are templates able to access mqtt directly?

azure tinsel
#

what u mean? automation can be triggered by mqtt message

#

and you can use template on payload

ivory delta
#

Their question was 3 hours ago. You may need to tag them to get their attention.

azure tinsel
#

sorry, didnt notice that, thanks @ivory delta
@restive flume ^^

mighty ledge
#

@restive flume only through events or MQTT <domains> like MQTT sensor, MQTT light, etc

drifting plaza
#

Hi All !, i have some sensors counting the number of times an event happened during the day , the sensors stopped working and cant figure why?, it seams that sensors related to TIME are having issues in my config : for example https://hastebin.com/oxusebavam.yaml , any hints appreciated .

silk smelt
#

i thought that a '''sensor: !include_dir_merge_named sensors/''' would include all files in the directory sensors?

#

when am I ever going to learn that three backticks markup..

silk smelt
#

solved it! sensor: !include_dir_merge_list sensors will include all files in the subfolder "sensors"

#

have a great day everyone 🙂

brisk temple
#

@drifting plaza looks fine, is that entity name right? the a at the end of alarm looks out of place

brisk temple
#

I have a feeling my condition loop will fail miserably

#

it will never be true true

grave arrow
#

With template types is it possible to force a numeric value to a string piping to string still returns a number. I.e. the type of: {{ state_attr('device_tracker.toms_iphone', 'latitude') | string }} is number I've tried even adding on an empty string on the end but it looks like the typing is done post Jinja

mighty ledge
#

@grave arrow the typing is done after resolution of the template

#

Why do you want this?

grave arrow
#

iOS notifications can provide a map pointer which you pass lat/long to. This requires a string value at the moment and fails if a float is passed. We can do the typing on the push server to fix but I feel like there are other cases where a specified type should be respected.

ivory delta
#

The difficulty is that HA casts to a sensible type automatically. This has changed slightly with the new ability to return native types (dicts/lists/etc) from a template but it's now each integration's responsibility to handle the incoming types.

#

That said... someone came up with a workaround that might help your specific use case. Gimme a minute to dig it out.

grave arrow
#

Ooo that’s smart. Going to fix server side though rather than put that in docs it’s not exactly user friendly I think.

tardy patio
#

Hello, can somebody help me with a template for an automation? I need to publish the current temperature from one of my aqara sensors every x seconds to a certain mqtt topic. I have until now something but it does not work:

#
  • alias: 'send temp'
    trigger:
    • platform: time
      minutes: /3
      seconds: '0'
      action:
      service: mqtt.publish
      data_template:
      payload_template: '{{ states.sensor.0x00158d000465809a_temperature.state }}'
      topic: 'opentherm-thermostat/current-temperature/set'
narrow glacier
tardy patio
#

Ill try this. Thanks.

#

Not working yet.

#

I do not know exactly how to test the automation in dev tools - states

#

I am not sure the payload template is correct

narrow glacier
#

Plug that template into dev tools->templates and you can see what it's actually resolving to

tardy patio
#

I am doing this,

#

and the problem is with the syntax

#

I really do not know what should be there

narrow glacier
#

try {{ states('sensor.0x00158d000465809a_temperature') }} instead maybe

tardy patio
#

that looks good to go, now i get an error in yaml file:

#

can not read a block mapping entry; a multiline key may not be an implicit key at line 254, column 12:
topic: opentherm-thermostat/current-t ...

#

for topic word

narrow glacier
#

That sounds like maybe wrong indentation, or not having the payload as one line and the topic as one line. I don't know how multi-line strings work in yaml

tardy patio
#

I posted on the forums and ill wait to see what happens.

narrow glacier
#

Good deal, sorry I couldn't help you further; I'm still learning too

hallow dock
#

When using a device as a trigger, what template would I use to get an attribute state of the triggering device? I see {{ trigger.event.data.event }} for a different type of trigger that was not platform: device

keen abyss
#

Hey, I'm not sure if this is the right place to ask, but someone mentioned somewhere about making sensor groups, so if I have two sensors, the group state would be on as long as any sensor would be on, and it would only be off when all sensors are off

#

How would I do something like this?

#

Do I just set up a template and have its state in a helper?

hallow dock
#

group

#

1 second

keen abyss
#

Thank you so much

hallow dock
#

no problem

hexed galleon
#

How would I create a template sensor that tracked my kWh consumed from solar generation in a day? I have solar generated, house draw already - problem being that I only want to track solar generated - house draw only while solar is actually being generated.

silent barnBOT
worthy heath
#

this seems like it should be really simple, but I'm completely stuck. How do I get the sunset/sunset time as a relative time? the output of the sun.sun next_setting attribute doesn't work with the relative_time function

flint spoke
#

isn't the "sun.sun next_setting" already a relative time?

ivory delta
#

No, it's an absolute time: next_setting: '2020-12-21T15:40:58+00:00'

mighty ledge
#

@tardy patio your object_id starts with a number. If you want to use the states object instead of the method then you need to access the item as if it were a dictionary key. {{ states.sensor['0x00158d000465809a_temperature'].state }}

tardy patio
#

Thank you @mighty ledge I managed to resolve the issue with: data: {"payload": "{{ states('sensor.0x00158d000465809a_temperature') }}", "topic": "opentherm-thermostat/current-temperature/set", "qos": 0, "retain": 0} with the help of user shcherban on the community forumns

#

Now I am trying to start a very big project for me, with multi zone heating control.

mighty ledge
#

might be easier to read if you don't treat it as a dictionary.

data:
  payload: "{{ states('sensor.0x00158d000465809a_temperature') }}"
  topic: opentherm-thermostat/current-temperature/set
  qos: 0
  retain: 0
tardy patio
#

Yep, I know, just copy pasted it as I received it 🙂

#

I think I need only some hints to build it up to work. Ill add more details lated.

#

later

mighty ledge
#

Seeing that you understand flowcharts better than code, I suggest you use node red as an automation engine over the built in automations.

tardy patio
#

Shcherban mentioned it too,

#

but I would love to understand simple coding also,

mighty ledge
#

that's the thing, you're either wired for it or you're not

#

work with what you got. I'm not wired for flowcharts

#

so I use code

tardy patio
#

and I think I just need very little info, like, I do not know if an automation can have multiple actions added, I do not know if the action from automation can pickup a value from an mqtt topic and publish it forward

mighty ledge
#

Yes they can

tardy patio
#

🙂

mighty ledge
#
- service: blah.1
  data: ...
- service: blah.2
  data: ...
#

the dashes indicate each 'action' in the action section

tardy patio
#

yes, that part ii understand. good.

mighty ledge
#

see how your trigger has that?

tardy patio
#

yes

mighty ledge
#

each section can have multiple

#

well, each major section: trigger, condition, and action

#

You should read up on how to format conditions

tardy patio
#

and actions too

#

But I think the info on the info pages is not enough

mighty ledge
#

and your trigger will not give you the ability to see what's on your MQTT topics

#

what's not enough about the conditions page?

#

are you reading or skimming?

tardy patio
mighty ledge
#

so what's the problem?

tardy patio
#

I am not sure if I can make something like:

ivory delta
#

@thorny snow - try something like this: {{ states.sensor | map(attribute="entity_id") | list }}. You can change the domain after states. to report on other types.

tardy patio
#

having 2 rooms, each with 2 temperatures, let's say minimum and maximum (each published on its own mqtt topic)

ivory delta
#

That template will output a list of all the entity ID's of all sensors.

mighty ledge
#

if you have 2 mqtt topics with 2 different sensors, then you should make 2 mqtt sensors

#

create triggers based on those sensors changing.

tardy patio
#

can an automation compare these and publish the pair of minimum to a new mqtt topic1 and maximum to new topic2 from the room with the biggest difference between maximum-minimum?

#

I need to have the vaclue updated every 20-30 seconds,

mighty ledge
#

why do you need this?

tardy patio
#

so I thought I should have the trigger as time_pattern

#

long message: “Automation algorithm”: This should be the multi area/zone calculator. This automation should receive set temp dummy 2 and current temp dummy from each room, make pairs of them, and calculate which room has the greatest difference of temperature (set temp-current temp) and send this data to the ot shield.
By doing this, the boiler will always work for the room that needs heating the most, and the automation for the TRVs will prevent other rooms from getting overheated.

mighty ledge
#

yes that's fine, but you'll have a periodic result instead of a live result

tardy patio
#

I need to send this temperature to an opentherm controller, so the boiler knows what to do.

thorny snow
mighty ledge
#

Ok, so first order of business is that yous hould get your sensor values into home assistant

tardy patio
#

I have the sensors in home assistant.

mighty ledge
#

this would be done by making MQTT sensors that read from the topics

#

Then you'll make an auotmation that has a time period that updates every 30 seconds.

#

You'll have 2 actions. 1 that publishes the min

#

1 that publishes the max

tardy patio
#

Yes, that i understant.

#

the calculation is the issue for me 🙂

mighty ledge
#

you're going to be using a template for each result that's getting pubished

#

this is your template for min:

 {{ expand('sensor.abc', 'sensor.xyz') | map(attribute='state') | map('int') | list | min }}

this is your template for max:

 {{ expand('sensor.abc', 'sensor.xyz') | map(attribute='state') | map('int') | list | max }}
#

if you want you can use variables so you only have 1 input list

ivory delta
tardy patio
#

wait asec. let me try to read this.

#

Wait wait wait.

#

I do not want to find the minimum value of 2 sensors.

thorny snow
mighty ledge
#
variables:
  sensors: "{{ expand('sensor.abc', 'sensor.xyz') }}"
actions:
- service: mqtt.publish
  data:
    topic: path\to\min
    payload: "{{ sensors | map(attribute='state') | map('int') | list | min }}" 
- service: mqtt.publish
  data:
    topic: path\to\max
    payload: "{{ sensors | map(attribute='state') | map('int') | list | max }}" 
tardy patio
#

I need to find: maximum between (room1.sensor1-room1.sensor2) and (room2.sensor1-room2.sensor2)

#

I do not know what that expand does

mighty ledge
#

why do you need the delta... that makes no sense? You're going to have the same value... just negated

tardy patio
#

after finding the bigger difference, I need to publish that room's sensor values, sensor1 and sensor2

#

because the boiler will take into account the room that needs the most heating,

#

and the others will shut off the TRVs in case temp goes too high

#

It is for multi area heating.

mighty ledge
#

So the device requires a delta?

tardy patio
#

Yes, the opentherm adapter works with modulation,

#

and needs current temperature and set temperature

#

and will heat the water in the installation accordingly

mighty ledge
#

ok... so where does the delta come into play if it needs current temp and set temp?

tardy patio
#

that is how I know which of the rooms needs most of the heating. in case both tooms are at 15 celsius, and I only want one of them to go to 24 and the other to 20, i should publish current temp of 15 and set temp of 24

#

It might also work with minimum and maximum of them all if I think about it,

mighty ledge
#

I get that!

tardy patio
#

but it will be a little less efficient

mighty ledge
#

but what the hell do you need the delta to be published?

tardy patio
#

no no no

mighty ledge
#

ok, let me explain

tardy patio
#

I do not need the delta published

tardy patio
#

I want to send to the opentherm controller the current and set temp temps of the room with the gratest delta.

#

I do not want to send the delta

mighty ledge
#

what does sensor1 represent, and what does sensor 2 represent

tardy patio
#

sensor1 would be set temp, sensor2 would be current temp.

mighty ledge
#

Ok, so where is the 'greatest delta for the rooms' coming from?

tardy patio
#

my head 🙂

#

It is only me who wants this,

mighty ledge
#

my point is, you don't have enough info

#

you'd need a sensor in 1 room. A sensor in the other, and you'd need to be able to read both of those. Then, you'd need to compare them to a desired temperature

tardy patio
#

yes,

#

I have that,

#

but I want different temperatures in each room

mighty ledge
#

Do you have sensors in each room?

tardy patio
#

yes

#

3 rooms

#

the 2 rooms was just an example

mighty ledge
#

You need to explain the whole thing not just 1 portion.

tardy patio
#

At this time the home assistant thermostat works with the sensor from one of the rooms

mighty ledge
#

So you have 6 sensors? or 3 sensors and 1 target?

tardy patio
#

If you speak english ok, I can call you 🙂

mighty ledge
#

na, i'm at work

tardy patio
#

I will have 3 thermostats in home assistant,

#

one for each room

#

each thermostat will publish a set temp to a dummy m1tt topic

#

and each room has a sensor with real room temperature

mighty ledge
#

so, that'll be 3 temperatures with 3 targets

tardy patio
#

yes

#

the boiler should calculate its water temperature based on room temp and set temp.

mighty ledge
#

OK. the automation will still be the same. But you'll have to use templates to get the desired affect.

#

this is a complicated template btw

tardy patio
#

hypothetically, if 2 rooms are at 24 celsius and 3rd is at 10 degrees, and I want it to go to 15, I should publish set temp of 15 and current temp of 10,

mighty ledge
#

Yes I understand now

tardy patio
#

yea, some really hair pulling situations, but the correct way to do it 🙂

#

templates, new thing.

mighty ledge
#

That's where you should start and the logic will be heavy

#

there's no examples because it's code.

#

The problem with doing this in templates is that you'll have to track which climate leads to what temperature. And it'll probably be easier if you don't make them climate devices

tardy patio
#

Isn't it easy by using different mqtt topic names?

mighty ledge
#

no, not really

brisk temple
#

If i define variables: in an automation below trigger, does it work in the action too?

mighty ledge
# tardy patio Isn't it easy by using different mqtt topic names?

This template here gets you the low device. But you'll have to come up with more logic to decide what to do based on that low. Example: What happens if the low is positive in value? That means it's above the target temperature. Also, remember low_device is a state object, so to access the temperature for further logic would be low_device.state | float

{% set devices = expand('sensor.room1', 'sensor.room2', 'sensor.room3') %}
{% set targets = expand('sensor.target_room1', 'sensor.target_room2', 'sensor.target_room3') |  %}
{% set ns = namespace(deltas=[]) %}
{% for i in range(3) %}
  {% ns.deltas = ns.deltas + [ targets[i].state | float - devices[i].state | float ] %}
{% endfor %}
{% set low_idx = ns.deltas.index(ns.deltas | min) %}
{% set low_device = devices[low_idx] %}
#

If none of this jives with you... I recommend node red.

#

also, to get the low target...

#
{% set low_target = targets[low_idx] %}
#

if they are climate devices and not sensors... then the logic is different

#

you can see how having all the information affects the templates 😉

tardy patio
#

I am in the car now, and i thought of this. If i make 3 automations, each with condition AND

#

And there are 2 conditions. Delta room1 > delta room2 and delta room1> delta room3. Action publish room1 current to topic 1 and publish room1 set temp to topic 2

#

Would this work?

mighty ledge
#

nope

tardy patio
#

Because there is only one solution of these 3 automations

mighty ledge
#

if they are on the same update cycle, it'll be intermitten which one gets reported

#

it needs to be in 1 automation with 1 logic step

#

You can build a massive action section using the choose. Where you put all possibilities into the choose action. But it will get very complicated.

If a < b and a < c:
if b < a and b < c:
if c < a and c < b:

#

then each will need to find the minimum

tardy patio
#

If they are on same cycle it should be ok. If they are off, it may create intermittent responses.

#

Because on same cycle only one delta will be the largest, correct?

#

I am continuing my idea :)

mighty ledge
#

home assistant is async

#

the only way to make them occur on the same update cycle is to have them in 1 automation

#

otherwise they will not be.

tardy patio
#

I understand. Did not know that

mighty ledge
#

@brisk temple yes

mighty ledge
#

you'd still need templates though.

#

to decide which one is smaller

thorny snow
#

I just leave that here, in case someone needs it:
If you want to create a group out of your motion/window/door sensors to do some fancy stuff with it. Do the following:

  1. Get all sensors from dev tools/templates via
    {{ states.binary_sensor | map(attribute="entity_id") | list }}
  2. copy the list to an editor of your choice (select/sort if needed)
  3. replace leading spaces and quotation mark with 4 spaces, dash, space
  4. replace trailing quotation mark and comma with nothing
  5. paste into the fitting section of your groups.yaml
  6. reload groups
  7. profit

(Thanks to @ivory delta for pushing me in the right direction.)

mighty ledge
#

@thorny snow you can just have it do that for you:

group:
  mygroup:
{%- for bs in states.binary_sensor %}
    - {{ bs.entity_id }}
{%- endfor %}
#

then your step list becomes:

  1. Get all sensors from dev tools/templates via
  mygroup:
{%- for bs in states.binary_sensor %}
    - {{ bs.entity_id }}
{%- endfor %}
  1. copy the chunk
  2. paste it into your group file
torn meteor
#

is it better to use entities or snapshot_entities when trying to do on-the-fly scenes? snapshot_entities is not working for me - the light doesn't return to its previous state in my automation

mighty ledge
thorny snow
ivory delta
#

I think petro's point is that it removes the need for several of your manual edits.

#

You already get it formatted as a nice YAML list his way. The only manual step then is to identify which rows you want to keep 🙂

thorny snow
ivory delta
#

You can only do it in the template editor. afaik, groups don't accept that template.

thorny snow
#

works, nice!

broken valley
#

So I need to load a mib for a snmp OID. Anyone know where to put them so it can scan the device

mighty ledge
broken valley
#

So I have a device that has a custom MIB file. So When I create the sensor HA knows about the OID.

#

it is for an APC

mighty ledge
#

the integrations don't use a mib file

#

mib files help you figure out the oid using a package that lets you scan the via snmp

broken valley
#

Ok. So maybe I am doing something else wrong.

mighty ledge
broken valley
#

I have the device monitoring vian LibreNMS. This is the OID I want.

.*.4.1.3*.*.2.1 = 61```
mighty ledge
#

@atomic mantle talk here

#

what is making t_entities?

atomic mantle
#

I had posted the "full" code earlier and then I was talking snips ....

#

so pseudo code is: {% set i = (range(1,(t_entities|length)+1)|random) %} {% set chosen_light = (t_entities[i-1]|replace("'", "")) %} {%- if (as_timestamp(now()) - as_timestamp(states[chosen_light].last_updated) < 5) -%} *** Loop to pick a new random light and check again*** {%- else -%} {{chosen_light}} {%- endif %}

mighty ledge
#

change a bunch of things

atomic mantle
#

I can't figure out how to do the loop

#

LOL, I expect that... I am really struggling with YAML and mixing it with jinja2

mighty ledge
#

you don't need a loop

atomic mantle
#

I don't?

#

I am trying to not "randomly" select the same light over and over again...

#

and then ultimately I am going to not randomly set the same colour to what that light already is...

mighty ledge
#

no loop. Just choose a random light from your list and use it.

#

expand turns it into a state object

#

if you don't want to use expand, you can just use random on the list itself.

#

or, if you just want the entity_id...

chosen_light: >
  {{ t_entities | random }}
#

either way, seems like you're over complicating it

atomic mantle
#

ok, that is a simpler way of selecting a light. but it fundamentally change which light is selected from my more convoluted way of doing it... but when I run this it will change light1, light2, light1, light1, light4, light3, light1 .....

#

and I want it to pick a different light if the one chosen has changed in the last 5 seconds...

mighty ledge
#

then you need a placeholder to store the last light

atomic mantle
#

so that it appears more consistent to someone viewing the lights that they are changing..

#

right, I could use a placeholder, or the last_updated time, but I still need a loop right?

ivory delta
#

This sounds like exactly the kind of thing that would benefit from an actual Python script instead of a template.

atomic mantle
#

I think I need to loop until I select a light that isnt the last light, or the selected light hasn't changed in 5 seconds (or 10 seconds haven't decided yet)

ivory delta
#

A simple way would be to have a list that doesn't include the current light, then randomise.

atomic mantle
#

I should step back for a second so that Mono and Petro know what I am doing... Every 2 seconds I am calling this script to change the light colour.. which is working fine, but what I am trying to improve now is to not pick a light that has already changed in the last 5 seconds and to not change it to the colour it already is.

#

so the current light doesn't really work, cause it would be the last two lights if I decide on 5 seconds, or the last 5 lights if I decide on 10 seconds

mighty ledge
#
{% set lights = expand(t_entities) %}
{% set t = now() - timedelta(seconds=5) %}
{{ lights | rejectattr('last_updated', '>', t) | map(attribute='entity_id') | list | random }}
atomic mantle
#

wow, that is elegant petro...

#

or at least concise

mighty ledge
#

had to adjust it, i think it should work

#

might want to do 6 seconds if your changing it every 5 seconds

#

for the timedelta

atomic mantle
#

Hey @mighty ledge , are you still around?

#

this throws the error: ```Logger: homeassistant.components.script
Source: helpers/entity_component.py:283
Integration: Script (documentation, issues)
First occurred: 1:48:33 PM (1 occurrences)
Last logged: 1:48:33 PM

invalid key: "OrderedDict([('chosen_light', None)])" in "/config/scripts.yaml", line 31, column 0```

#

but if I comment out lines 29 -> 32 it works fine (selects a light and colour, and writes it to the log).. how can chosen_light not be found 3 lines later?

flat cave
#

im trying to hunt - is there a way to make a template read occurrence in x time

I have a counter and if that resets 2 times in 5 mins i want to run an automation

atomic mantle
#

Petro, never mind... I found my issue... I need to enclose the {{chosen_light}} in ' '

atomic mantle
#

no worries, just debugging now... I am changing the light colours, but it doesn't appear like it ignoring ones that have recently changed...

#

wait, testing again... seems to be working.... 😕

#

nope... still repeating lights within the 15 seconds... (I changed to 15 seconds and am using a 3 second trigger, so in theory it should update 5 lights before repeating)...

#
2020-12-21 14:22:27 WARNING (MainThread) [homeassistant.components.system_log.external] ('15 second catch >:', 'light.driveway_2', 'red')
2020-12-21 14:22:30 WARNING (MainThread) [homeassistant.components.system_log.external] ('15 second catch >:', 'light.01401742cc50e3e1b6fd', 'green')
2020-12-21 14:22:33 WARNING (MainThread) [homeassistant.components.system_log.external] ('15 second catch >:', 'light.driveway_2', 'red')
2020-12-21 14:22:36 WARNING (MainThread) [homeassistant.components.system_log.external] ('15 second catch >:', 'light.014017422cf43280c9ac', 'blue')
2020-12-21 14:22:39 WARNING (MainThread) [homeassistant.components.system_log.external] ('15 second catch >:', 'light.driveway_2', 'green')
2020-12-21 14:22:42 WARNING (MainThread) [homeassistant.components.system_log.external] ('15 second catch >:', 'light.014017422cf43280c9ac', 'red')
2020-12-21 14:22:45 WARNING (MainThread) [homeassistant.components.system_log.external] ('15 second catch >:', 'light.driveway_3', 'red')
2020-12-21 14:22:48 WARNING (MainThread) [homeassistant.components.system_log.external] ('15 second catch >:', 'light.underdeck', 'red')```
#

that is a subset of the logs put out, and as you can see the light ending in 9ac is changed at 22:36 and 22:42 and driveway_2 is changed at 22:27, 22:33 and 22:39

#

is it possible that last_updated is not the attribute I want to be looking at?

true otter
#

Is there a best practice when deciding when to use float as part of a template sensor?

blazing burrow
#

how could I make a template sensor that returns the entity id of the most recently updated out of a list of entities?

nocturne chasm
#

@true otter , Integers and floats are two different kinds of numerical data. An integer (more commonly called an int) is a number without a decimal point. A float is a floating-point number, which means it is a number that has a decimal place. Floats are used when more precision is needed.

hexed galleon
#

Is it possible to check if all/some objects in a domain are of a specific state with templates? Basically want a {{ is_state('states.person.state','not_home') }} that will automatically check the state of all person objects. Kinda like a group, without needing to group.

jovial mason
#

Can I add a template to my device before flashing to 9.2.0 from 8.5.1 ?

ivory delta
#

Flip the equality check and the zone names as needed... but that'll return True when the count is greater than 0.

#

In fact, you can simplify it further by removing the | map(), since you don't care about getting any details.

mighty ledge
#

@blazing burrow

{% set entities = expand(LIST OUT ENTITIES) %}
{% set last_ts = entities | map(attribute='last_updated') | list | max %}
{{ (entities | selectattr('last_updated', 'eq', last_ts) | list | first).entity_id }}
blazing burrow
#

wow, that does look like it'll work 👍

#

I'll give a shot when I get a chance 👍

mighty ledge
#

oh it works

mighty ledge
jovial mason
#

Oh wait.. Sorry, I got confused on templates and software.. Tasmota is what I am referring to, so that has nothing to do w/ anything here, so disregard my question.. When I asked that, I was running on 4 hours asleep in the last 48 hours.. I've gotten some sleep now, and my confusion has cleared..

haughty kiln
#

morning, all. the peloton sensor i'm using stores an image URL in one of the attributes. how can i get that image into a card? my suspicion is that i need to use a template, but i am wildly unfamiliar with them

#

googles didn't turn anything up 😦

ivory delta
#

It depends on the card, since the native ones don't support templates.

#

But yes... you can use a template to read the attributes of an entity: {{ state_attr('sensor.peloton', 'picture_url') }}

#

Update the names to suit 🙂

haughty kiln
#

thanks @ivory delta. it's not clicking for me yet, but i'll keep playing with it

brisk temple
haughty kiln
#

thanks@brisk temple

blazing burrow
mighty ledge
#

@blazing burrow you have to template each field. json_attributes_template does not accept templates, child fields do

json_attributes_template:
  camera: "{{}}"
  start_time: "{{}}"
  label: "{{}}"
hollow rampart
#

Hello. I would like setup a template to open blinds in sequence with a set delay in between. This may not be the best approach using a template. Basically, I would like to have single cover entity to control 4 blinds with a delay in between. I did try grouping them together, which works but I’m afraid that I will have communications conflict.

mighty ledge
#

@hollow rampart that's an automation

#

delays cannot be performed in templates.

hollow rampart
#

Ok thank you!

blazing burrow
#

ah, I had forgotten to tojson filter anyways 😅

blazing burrow
#

yeah, sure looks like I can put a template there

#

from the docs

mighty ledge
#

That's new functionality then

blazing burrow
mighty ledge
#

Look at the history, it used to be like that

#

either way, you have it sorted out aparently

#

it most likely extends from the data field so templates are now allowed at the root level or internally

silver pewter
#

Hi! I use this template sensor to see how many active connections my emby server has.
But i also want it to include 'paused' state not only 'playing'. So if 1 is playing and one paused value should be 2 🙂 Anyone knows how ? 😄 :
{{ states.media_player | selectattr('state', 'eq', 'playing') | rejectattr('attributes.server_name') | list | count}}

ivory delta
#

What other states can it have?

#

If there's only one other possible state, go with | selectattr('state', 'ne', 'theotherstate')

#

Otherwise, chain a few | rejectattr() together to eliminate the ones you don't want.

blazing burrow
ivory delta
#

If they're not comma-separated, they're not a list...

#

toffee apples

#

toffee, apples

blazing burrow
#

that's what I thought lol I'm not familiar with expand(...)

#

but my question is more about the brackets

#

does expand take multiple args, or a single list arg?

ivory delta
#

A single list

blazing burrow
#

👍

#

works for me

median pulsar
#

Mmmm, toffee apples....

hexed galleon
mighty ledge
#

expand is pretty smart. If you pass expand(a, b, c, d) it will return a list of state objects [ a, b, d, d ]. Same as if you pass it as a list expand([a, b, c, d])

teal cove
#

its possible to pass a variable to a script. How do I check for the sole existence of that variable in the script? Or is there any other sleek way of preventing the script to throw an error if the variable isn't set? 🙂

flat cave
#

im trying to hunt - is there a way to make a template read occurrence in x time

I have a counter and if that resets 2 times in 5 mins i want to run an automation

brisk temple
#

@teal cove you can use is defined

#

but i think you need a default set regardless

teal cove
#

{% if myvariable is defined %} ?

brisk temple
#

ya

#

problem is the script expects something

teal cove
#

whats the shorthand for a condition for this? Can I get away with not having the entire if else syntax?

brisk temple
#

i put it in the script so not every automation needs it

#

only used it for lights

#

so i can pass brightness or transition from the automation if wanted, otherwise the script defaults in the else of the template

teal cove
#
- service
- condition: " ... "
- service
blazing burrow
mighty ledge
#

it should, works for me

blazing burrow
#

ooh you know what

#

frigate updates all of them every time around

#

so it is, but they're all getting updated with the same (or close) time

little field
#

Hi, I'm having some issues with a template switch? I'm trying to combine two switches into one on/off switch

#

I can get the switch.erv entity but i can't seem to trigger the 'turn_on' or 'turn_off'

silent barnBOT
little field
#

im on version 2020.12.1

inland hazel
#

@little field I can’t exactly follow your intended actions here. You’re turning on/off an Input Boolean, and then toggling switch entities that are associated with on/off.

What is your use case, and why can you not just use the Input Boolean and a couple automations instead of a template switch?

little field
#

@inland hazel I have two switchbot bots that is on either end of a rocker switch that controls my ventilation . I could turn them into an automation but I'd much rather merge the two bots as one single entity controlled by input_boolean toggle. I've tried without the "service: input_boolean.turn_on data: entity_id: input_boolean.erv" bit but both scenarios didn't work. Not sure what the correct syntax is and figured i'd just leave it in there.
Edit: I misunderstood what the value_template did. I've figured it out. switch.erv is working, but input_boolean does not trigger switch.erv (which i thought value_template would accomplish via state change).

tardy patio
#

Hello, is this templating correct?```
- payload: template
- value_template: "{{ max: states('sensor.dummy-t2-r2')|float; states('sensor.dummy-t2-r1')|float }}"

#

It should spit out the highest value of the 2 sensors.

#

Checked it by dev tools, and looks like the correct syntax should be

#
"{{ max, states('dummy-t1-r1')|float, states('dummy-t2-r1')|float }}"
tardy patio
#

It is not good,

tardy patio
#

Got it: "{{ (states('dummy-t1-r1')|float, states('dummy-t2-r1')|float)|max }}"

fresh yarrow
#

Hello, when im creating a light template and want to configure the "set_color" action, are the 'h' and 's' variable the only ones which were deliverd or is there a way to grab the R, G,B values of the "Change" ?

shrewd flume
#

victron

eternal saddle
#

I'm working with a climate | mqtt platform when I trigger the device for off I'm expecting a 0 in mqtt because I have the payload_off: 0 set. But if sends off. any ideas
power_command_topic: "aqualinkd/Pool_Heater/set" payload_on: "1" payload_off: "0"

silent barnBOT
inland hazel
#

@calm sundial It looks like you're trying to provide a list of templates, when only a single template is expected. Also, templates should be quoted unless a block is defined. Can you test this and see if it works out for you? https://hastebin.com/ucifevogiz

calm sundial
#

Yep, that was it! Thanks!

molten scroll
#

Expected <block end>, but found ‘<block mapping start>’

fast mason
molten scroll
#

I have to remove the _?

fast mason
#

You have four is_state but they aren't all written the same

#

it's supposed to be is_state(

molten scroll
#

Oh lens added spaces

fast mason
#

your second value template also has spaces

#

It's also better this way states('sensor.luxtronik_id_web_analogout2_2') so everything is more consident

#

And single quotes

molten scroll
#

It's an old template that was only available as a screenshot

molten scroll
#

I mean up to the |

#

Oh my model doesn't have that function

#

So I'll delete

fast mason
molten scroll
#

It turns out my device doesn't support that one

fast mason
#

Then no issue

#

it's the same thing

#

just two different ways of writing it

#

NOt sure what the difference is. I just had people tell me that second one is better

#

I don't actually know why haha

molten scroll
#

Well it's more readable

#

That alone is a win in my book

steady citrus
#

if i have an array of dicts, is there a way to get a value from each element of an array?

#

i see a lot of examples of using the index value ([0], [1]) but nothing that will let me get all of a single key. for example, all of the id values from an array of dicts

#

or let's try it another way

#

{{ states.sensor.adhan_tracks.attributes['items'] | random }} this returns a dict

#

i want to now get a singular value out of this dict

#

do i have to do it separately like this:

#
{% set x = states.sensor.adhan_tracks.attributes['items'] | random %}

{{x.id}}
dreamy sinew
#

selectattr is a thing

#

Also map

grim flicker
#

Hi everyone. i have a automation in which i want to use a slider to change the brightness of my lights. For some reason i get the error:
Mancave brightness aanpassen: Error executing script. Invalid data for call_service at pos 1: expected int for dictionary value @ data['brightness']

#

im using this template:

  - service: light.turn_on
    entity_id: light.mancave_lampen
    data_template: 
      brightness: >
        '{{ (states("input_number.mancave_brightness") | int) | round(0) }}'
#

could someone help me out. In the devtools the {{ (states("input_number.mancave_brightness") | int) | round(0) }} gives a perfect round number

grim flicker
#

nm. i fixed it myself eventually. the ' in front and ' behind should be removed.

granite steppe
#

I'm trying to turn on a boolean when my robovac is docked but only if it has been cleaning for a minimum of 1 min. I have this so far... https://pastebin.ubuntu.com/p/H38Pp4xFWy/ (note the conditions) but does not work. Does anyone know a template that will know when something has ran for >1min in the last 24 hrs.

grim flicker
#

i have this code: {% if is_state('input_number.mancave_brightness', '25') -%}but what i want is to check if this value is "<= 25" how do i write this in an if statement template?

molten scroll
#

@fast mason how do I make android/discord not lose the yaml formatting

silent barnBOT
#

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

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

For over 15 lines you must use a code share site such as https://paste.ubuntu.com/ or https://www.hastebin.com/.

molten scroll
#

Mother of god

#
- platform: template 
  sensors: 
  delta_t:
  friendly_name: "Delta T"
  unit_of_measurement: '°C'
  value_template: "{{ states('luxtronik.temperatuur_aanvoer')|int - states('luxtronik.temperatuur_retour')|int }}" 
  device_class: "temperature"

fast mason
#

Is this exactly what you have ?

molten scroll
#

Yeah the whole relevant block

#

There's a bunch of sensors above tho

fast mason
#

Cos indentation is wrong in what you are showing me

#
- platform: template 
  sensors: 
    delta_t:
      friendly_name: "Delta T"
      unit_of_measurement: '°C'
      value_template: "{{ states('luxtronik.temperatuur_aanvoer')|int - states('luxtronik.temperatuur_retour')|int }}" 
      device_class: "temperature"
#

And I am assuming you only have this once

- platform: template
  sensors:
molten scroll
#

Ok that worked

#

Yaml really kicking my ass

#

Yamllint didn't say anything

fast mason
#

Hmm weird

molten scroll
#

In any case thanks again

#

Is there any good yaml editor for android?

fast mason
#

For android? I have no idea

#

Best would be to use vscode since that has a lot of plugins for yaml

steady citrus
#

I'm having a hard time grabbing the id value out of this resulting dict

molten scroll
#

The code works but the way

steady citrus
#
{
  "id": 10,
  "title": "Ahmad Al Nafees",
  "title_sort": "Ahmad Al Nafees",
  "artist": "Adhan",
  "artist_sort": "Adhan",
  "album": "Adhan",
  "album_sort": "Adhan"
}
#

this dict is created by doing: {{ state_attr('sensor.adhan_track', 'items') | random }}

#

i've tried {{ state_attr('sensor.adhan_track', 'items') | random | selectattr("id") } but the devtools just shows me <generator object select_or_reject at 0x7f2376d8a510>

steady citrus
#

this seems to work fine

#
 value_template: >
   {% set track =  value_json['items']  | random  %}
   {{ track.id }}
twin jewel
#

I'm having trouble formatting datetime in a template, somehow the online topics on this won't work

#

online examples work with sensors, using a value_template property, I work with an entity, which seems to ignore that property

#
entity: sensor.voordeur_last_ding
name: Laatste keer aangebeld
value_template: >-
  {{ as_timestamp(sensor.voordeur_last_ding) | timestamp_custom('%D %-I:%M %P')
  }}```
#

Can anyone tell me the correct syntax to have this work with an entity card

twin jewel
#

okay I got it. template needs to be defined in configuration.yaml, after that I can reference the template in my frontend.

fossil hearth
#

hi !:) rest sensors cannot introduce icon_template? [sensor.rest]: [icon_template] is an invalid option for [sensor.rest].

native pilot
#

Why is this template not working?

{{ is_state_attr('media_player.mibox3', 'app_name', 'YouTube') }}
{{ state_attr('media_player.mibox3', 'app_name') == 'YouTube' }}
{{ state_attr('media_player.mibox3', 'app_name') }}
#

The latest does show "YouTube" but the two above stay false

#
Result type: string
False
False
‏YouTube
#

(I'm in the template editor)

granite steppe
#

Is there any way to get this into one template? I want to have a running time for my robovac shown. It looks like i have to do. it in two. One to get the running time and two to make it readable in time... https://pastebin.ubuntu.com/p/XPZKhwQNgY/

native pilot
#

@granite steppe

#

I use it to notify me how long it took for last cycle and how much it covers in meters

granite steppe
#

Thanks.. thats helpful. I'm looking for a time stamp in hh:mm of how long the vac has ran today which resets at midnight. I am them looking to integrate it into a an automation to turn on a boolean only if the vac has been running more than 15 mins each day

#

@native pilot

native pilot
#

If that is your main goal you don't need a template to achieve that

#

Line 49

#

And also the reset automation is there

#

@granite steppe

granite steppe
#

Thanks. I might do that. I try to merge a lot of automations together into one so that i dont have 100's of notifications in the UI haha

native pilot
#

Obviously this is a goal. Just lately I have combined a lot of sensors and automation.. last couple of update greatly helped

steep kiln
#

these two templates do basically the same and should update every minute right? -->

#

{{ ((as_timestamp(states('sensor.cert_expiry_timestamp_cvoid_de')) - as_timestamp(states.sensor.date.last_updated)) / 86400) | int }} {{ ((as_timestamp(states('sensor.cert_expiry_timestamp_cvoid_de')) - as_timestamp(now())) / 86400) | int }}

#

thanks

patent flame
#

Hello

#
      friendly_name: "Consumo Total Actual"
      value_template: "{{( states.sensor.shelly_shem_1_current_consumption.state)|int + (states.sensor.shelly_shem_2_current_consumption.state )|int}}"
      device_class: power
#

Why is not returning properly?

#

The final value i belive is text

#

But xxxxx only...

#

Also shows a bar graph instead of line graph on history...

#

What am I doing wrong?

steep kiln
#

when using "days" as unit of measurement is there anything that I could use for the frontend to be autotranslated to the browsers set locale?

#

like en_US 21 days and 21 Tage when e.g. de_DE is set?

ivory delta
#

If you're specifying the unit of measurement, probably not.

#

You could pick any word/symbol/abbreviation for a unit - HA can't know how to translate them all.

steep kiln
#

so only when I define a device_class HA would add a unit by itself?

#

anyway thanks

ivory delta
steep kiln
#

👍

fast mason
#

If you are dyslexic your username @steep kiln spells a disease 😮 I really got taken aback for a few seconds there

wispy bane
#

Hi all. Newbie here. In the example "value_template: '{{ value_json.value.state }}'" to extract a value from a json output is defining this the actual template itself or do value_template and value_json have to be defined somewhere first before being referenced?

autumn hemlock
#

I have two devices (light switch) that each have 3 potential triggers (turn_on, turn_off, dim_up). I have them all listed as triggers in an automation. However I'd like the action to be dependent upon the the device that fired the action. Basically if trigger is from device 1 then the action should be for bulb 1. Device 1 turn_on Bulb 1, Device 2 dim_up Bulb 2

#

but I'm not quite sure I am wrapping my head around how to accomplish the conditionals I'm looking for

autumn hemlock
#

I'm not sure if what I am trying to do with the if in the service area is possible

steep kiln
#

@fast mason well... it was always chrisvoid (short cv..) but this stupid flu came after me 😉

prime hinge
#

I'm trying to convert temperature data which comes from an MQTT sensor and which looks like xx.xx C into a numeric value.

#

I tried value_template: "{{ value_json | from_json | regex_replace(' C', '') | float }}"

#

But it doesn't look like it works ("unknown")

#

any clue?

prime hinge
#

Oh, using value instead of value_json | from_json seems to do it

cedar wigeon
#

This sensor gives me the value of "2:07:23", how can I display this whitout the ""?

This is just a value, no label in api,

ivory delta
#

Something like this {{ x.split('"')[1] }} would make it into a list (splitting at the double quotes) and take the second item (the value between the quotes).

#

Swap out x with your actual sensor.

cedar wigeon
#

I think I might do it wrong @ivory delta ?
- platform: rest name: Glances - DeCONZ - Uptime value_template: {{ glances_deconz_uptime.split('"')[1] }} resource: http://10.0.24.11:61208/api/3/uptime

#

This worked:

value_template:  '{{ value_json }}'
ivory delta
#

So the value doesn't have quotes 🤷‍♂️

cedar wigeon
#

nop, but it was displayed with quotes in if it was no value_template

nocturne chasm
#

@autumn hemlock , your trigger.entity_id is a sensor which you are using to trigger off of, then you are trying to turn it off/on

autumn hemlock
#

Yeah I realized my setup probably won't work because the trigger needs to adjust a different device

#

It's a switch that controls a light bulb

silent barnBOT
nocturne chasm
#

Sorry, @autumn hemlock , that was @wispy bane

autumn hemlock
#

Haha

#

No worries

wispy bane
#

my bad guys.

nocturne chasm
#

Posts happen so quickly

wispy bane
#

Didn't realise there was a limit on the size of the post. I guess it makes sense

nocturne chasm
#

@autumn hemlock , you can in fact do what you are trying to do you just need a some what advanced template

#

You need to define the entity_id in an if elif statement according to the trigger entity.

autumn hemlock
#

perfect, i think i can go from there

wispy bane
#

Hi guys, do I post the link aut-generated by HassBot? I don't want to spam the channel

autumn hemlock
#

yes, it appears to link your code for you

#

though you could only upload your code and then post your question (since it took your entire post and put it in the link)

wispy bane
nocturne chasm
#

@wispy bane , you posted information with values != unavailable and then said your device is unavailable. Do you need help with the actual sensor or templating it’s attributes? Cause the first should be moved to #diy-archived or #general-archived

wispy bane
#

I need help with the template so that I can extract the temperature from the json output

#

Not sure why the device is showing as unavailable. Thought it might have something to do with why the value is not being extracted.

deft timber
#

Could you test without the availability part? You set an availability topic, are you sure the Online has been sent on the topic to make the sensor available?

wispy bane
#

Yes. "tele/zbBridge/LWT" is "Online". Will try without the availability topic

#

It works. Thank you. I thought my template was wrong.
Now I need to figure out why the availability isn't working 🙂

#

Here's the Log entry for the messages received for tele/zbBridge/LWT
2020-12-28 14:25:01 DEBUG (MainThread) [homeassistant.components.mqtt] Received message on tele/zbBridge/LWT (retained): b'Online'

deft timber
#

Could you try to use availability_topic: instead of
`availability:

  • topic:
    `
    ?
wispy bane
#

Do I need to specify "payload_available" and "payload_not_available"?

deft timber
#

yes

wispy bane
#

It works. Thank you so much

autumn hemlock
#

Ok so I realized I needed to change the triggers (for better or worse) and I think I needed to switch to a data_template as the action. The one thing I am unclear on is how to act on a subtype, ie type: remote_button_short_press, subtype: turn_on, in the data_template area https://hastebin.com/aqilezeyes.yaml

#

when I add the switches (sensors) in the automation UI it adds it as with a device_id and domain: zha. I read that I can omit those and replace it with the entity_id, is that correct?

deft timber
wispy bane
#

oddly enough I had tried the one you suggested previously and it didn't work. I must have done something wrong then. The good thing is that it works now but you're right updating the documentation is probably a good idea.

deft timber
#

@autumn hemlock data_template is not an action, you can't put that directly under action:

#

you have to use - service: "{% your template to choose light.turn_on or turn_off %}"

#
action: 
  - service: "{% your template to choose light.turn_on or turn_off %}"
    data:
        entity_id: "{% your template to choose your entity_id %}"
autumn hemlock
#

so i just psuedo coded the subtype stuff, is that viable code?

deft timber
#

it is not viable code. I see a lot of issue in your code... you can not put the template at a new line like that, you have to use >

#

and are you sure your entity_id are lamp.* and not light.* ?

#

I don't know the domain lamp

autumn hemlock
#

you are totally correct, let me do another pass so i dont waste your time

deft timber
#

subtype can't be use as you do, for sure

#

though I don't know how to get it, if possible

autumn hemlock
#

crap haha, i feel like that probably halts my progress

#

unless i want to try to do conditionals based on the current state/brightness of the bulb

deft timber
#

{% if trigger.entity_id === sensor.isabellesroom_switch %}
should be
{% if trigger.entity_id == "sensor.isabellesroom_switch" %}

autumn hemlock
deft timber
#

you still need to change === with ==, and put quotes around the texts

autumn hemlock
#

(disregard triple 🙂

#

haha

#

all text?

deft timber
#
brightness: >
        {% if subtype === turn_on %}
          brightness: 25
        {% elif subtype === dim_up %}
          brightness: 255
        {% endif %}

with ```yaml
brightness: >
{% if subtype === turn_on %}
25
{% elif subtype === dim_up %}
255
{% endif %}

#

well yes

#

basically everything that is on the right side of your == in your code

autumn hemlock
#

right right, i wanted to clarify you didnt mean brightness or service values

#

(unless in a conditional)

cinder ore
#

Hi, I am new to home assistant, I have installed it on a PI4 and I need some help

#

I tried almost all day to make it work

#

I have a tp link router and there are some entities that display bytes sent and received in bytes

#

I would like to show in MB and I tried to do it using template.

#

i have this entity

#

sensor.tl_mr6400_kib_s_received that has the following attributes:
unit_of_measurement: KiB/s
friendly_name: TL-MR6400 KiB/s received
icon: 'mdi:server-network'

and the "state" is the total bytes received.